blob: e2fa3e22b6ad45a5902881d3010afbd9d5a4f708 [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
715 && fchown(curbuf->b_ml.ml_mfp->mf_fd, -1, st.st_gid)
716 == -1)
717 swap_mode &= 0600;
718 }
719
720 (void)mch_setperm(swap_fname, (long)swap_mode);
721 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000722#endif
723 }
724
Bram Moolenaarb815dac2005-12-07 20:59:24 +0000725#if defined(HAS_SWAP_EXISTS_ACTION)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000726 /* If "Quit" selected at ATTENTION dialog, don't load the file */
727 if (swap_exists_action == SEA_QUIT)
728 {
729 if (!read_buffer && !read_stdin)
730 close(fd);
731 return FAIL;
732 }
733#endif
734
735 ++no_wait_return; /* don't wait for return yet */
736
737 /*
738 * Set '[ mark to the line above where the lines go (line 1 if zero).
739 */
740 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
741 curbuf->b_op_start.col = 0;
742
Bram Moolenaar7a2699e2017-01-23 21:31:09 +0100743 try_mac = (vim_strchr(p_ffs, 'm') != NULL);
744 try_dos = (vim_strchr(p_ffs, 'd') != NULL);
745 try_unix = (vim_strchr(p_ffs, 'x') != NULL);
746
Bram Moolenaar071d4272004-06-13 20:20:40 +0000747 if (!read_buffer)
748 {
749 int m = msg_scroll;
750 int n = msg_scrolled;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000751
752 /*
753 * The file must be closed again, the autocommands may want to change
754 * the file before reading it.
755 */
756 if (!read_stdin)
757 close(fd); /* ignore errors */
758
759 /*
760 * The output from the autocommands should not overwrite anything and
761 * should not be overwritten: Set msg_scroll, restore its value if no
762 * output was done.
763 */
764 msg_scroll = TRUE;
765 if (filtering)
766 apply_autocmds_exarg(EVENT_FILTERREADPRE, NULL, sfname,
767 FALSE, curbuf, eap);
768 else if (read_stdin)
769 apply_autocmds_exarg(EVENT_STDINREADPRE, NULL, sfname,
770 FALSE, curbuf, eap);
771 else if (newfile)
772 apply_autocmds_exarg(EVENT_BUFREADPRE, NULL, sfname,
773 FALSE, curbuf, eap);
774 else
775 apply_autocmds_exarg(EVENT_FILEREADPRE, sfname, sfname,
776 FALSE, NULL, eap);
Bram Moolenaar7a2699e2017-01-23 21:31:09 +0100777 /* autocommands may have changed it */
778 try_mac = (vim_strchr(p_ffs, 'm') != NULL);
779 try_dos = (vim_strchr(p_ffs, 'd') != NULL);
780 try_unix = (vim_strchr(p_ffs, 'x') != NULL);
781
Bram Moolenaar071d4272004-06-13 20:20:40 +0000782 if (msg_scrolled == n)
783 msg_scroll = m;
784
785#ifdef FEAT_EVAL
786 if (aborting()) /* autocmds may abort script processing */
787 {
788 --no_wait_return;
789 msg_scroll = msg_save;
790 curbuf->b_p_ro = TRUE; /* must use "w!" now */
791 return FAIL;
792 }
793#endif
794 /*
795 * Don't allow the autocommands to change the current buffer.
796 * Try to re-open the file.
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000797 *
798 * Don't allow the autocommands to change the buffer name either
799 * (cd for example) if it invalidates fname or sfname.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000800 */
801 if (!read_stdin && (curbuf != old_curbuf
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000802 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
803 || (using_b_fname && (old_b_fname != curbuf->b_fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000804 || (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) < 0))
805 {
806 --no_wait_return;
807 msg_scroll = msg_save;
808 if (fd < 0)
809 EMSG(_("E200: *ReadPre autocommands made the file unreadable"));
810 else
811 EMSG(_("E201: *ReadPre autocommands must not change current buffer"));
812 curbuf->b_p_ro = TRUE; /* must use "w!" now */
813 return FAIL;
814 }
815 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000816
817 /* Autocommands may add lines to the file, need to check if it is empty */
818 wasempty = (curbuf->b_ml.ml_flags & ML_EMPTY);
819
820 if (!recoverymode && !filtering && !(flags & READ_DUMMY))
821 {
822 /*
823 * Show the user that we are busy reading the input. Sometimes this
824 * may take a while. When reading from stdin another program may
825 * still be running, don't move the cursor to the last line, unless
826 * always using the GUI.
827 */
828 if (read_stdin)
829 {
Bram Moolenaar234d1622017-11-18 14:55:23 +0100830 if (!is_not_a_term())
831 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000832#ifndef ALWAYS_USE_GUI
Bram Moolenaar234d1622017-11-18 14:55:23 +0100833 mch_msg(_("Vim: Reading from stdin...\n"));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000834#endif
835#ifdef FEAT_GUI
Bram Moolenaar234d1622017-11-18 14:55:23 +0100836 /* Also write a message in the GUI window, if there is one. */
837 if (gui.in_use && !gui.dying && !gui.starting)
838 {
839 p = (char_u *)_("Reading from stdin...");
840 gui_write(p, (int)STRLEN(p));
841 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000842#endif
Bram Moolenaar234d1622017-11-18 14:55:23 +0100843 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000844 }
845 else if (!read_buffer)
846 filemess(curbuf, sfname, (char_u *)"", 0);
847 }
848
849 msg_scroll = FALSE; /* overwrite the file message */
850
851 /*
852 * Set linecnt now, before the "retry" caused by a wrong guess for
853 * fileformat, and after the autocommands, which may change them.
854 */
855 linecnt = curbuf->b_ml.ml_line_count;
856
857#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000858 /* "++bad=" argument. */
859 if (eap != NULL && eap->bad_char != 0)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000860 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000861 bad_char_behavior = eap->bad_char;
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000862 if (set_options)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000863 curbuf->b_bad_char = eap->bad_char;
864 }
865 else
866 curbuf->b_bad_char = 0;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000867
Bram Moolenaar071d4272004-06-13 20:20:40 +0000868 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000869 * Decide which 'encoding' to use or use first.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000870 */
871 if (eap != NULL && eap->force_enc != 0)
872 {
873 fenc = enc_canonize(eap->cmd + eap->force_enc);
874 fenc_alloced = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000875 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000876 }
877 else if (curbuf->b_p_bin)
878 {
879 fenc = (char_u *)""; /* binary: don't convert */
880 fenc_alloced = FALSE;
881 }
882 else if (curbuf->b_help)
883 {
884 char_u firstline[80];
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000885 int fc;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000886
887 /* Help files are either utf-8 or latin1. Try utf-8 first, if this
888 * fails it must be latin1.
889 * Always do this when 'encoding' is "utf-8". Otherwise only do
890 * this when needed to avoid [converted] remarks all the time.
891 * It is needed when the first line contains non-ASCII characters.
892 * That is only in *.??x files. */
893 fenc = (char_u *)"latin1";
894 c = enc_utf8;
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000895 if (!c && !read_stdin)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000896 {
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000897 fc = fname[STRLEN(fname) - 1];
898 if (TOLOWER_ASC(fc) == 'x')
899 {
900 /* Read the first line (and a bit more). Immediately rewind to
901 * the start of the file. If the read() fails "len" is -1. */
Bram Moolenaar540fc6f2010-12-17 16:27:16 +0100902 len = read_eintr(fd, firstline, 80);
Bram Moolenaar8767f522016-07-01 17:17:39 +0200903 vim_lseek(fd, (off_T)0L, SEEK_SET);
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000904 for (p = firstline; p < firstline + len; ++p)
905 if (*p >= 0x80)
906 {
907 c = TRUE;
908 break;
909 }
910 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000911 }
912
913 if (c)
914 {
915 fenc_next = fenc;
916 fenc = (char_u *)"utf-8";
917
918 /* When the file is utf-8 but a character doesn't fit in
919 * 'encoding' don't retry. In help text editing utf-8 bytes
920 * doesn't make sense. */
Bram Moolenaarf193fff2006-04-27 00:02:13 +0000921 if (!enc_utf8)
922 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000923 }
924 fenc_alloced = FALSE;
925 }
926 else if (*p_fencs == NUL)
927 {
928 fenc = curbuf->b_p_fenc; /* use format from buffer */
929 fenc_alloced = FALSE;
930 }
931 else
932 {
933 fenc_next = p_fencs; /* try items in 'fileencodings' */
934 fenc = next_fenc(&fenc_next);
935 fenc_alloced = TRUE;
936 }
937#endif
938
939 /*
940 * Jump back here to retry reading the file in different ways.
941 * Reasons to retry:
942 * - encoding conversion failed: try another one from "fenc_next"
943 * - BOM detected and fenc was set, need to setup conversion
944 * - "fileformat" check failed: try another
945 *
946 * Variables set for special retry actions:
947 * "file_rewind" Rewind the file to start reading it again.
948 * "advance_fenc" Advance "fenc" using "fenc_next".
949 * "skip_read" Re-use already read bytes (BOM detected).
950 * "did_iconv" iconv() conversion failed, try 'charconvert'.
951 * "keep_fileformat" Don't reset "fileformat".
952 *
953 * Other status indicators:
954 * "tmpname" When != NULL did conversion with 'charconvert'.
955 * Output file has to be deleted afterwards.
956 * "iconv_fd" When != -1 did conversion with iconv().
957 */
958retry:
959
960 if (file_rewind)
961 {
962 if (read_buffer)
963 {
964 read_buf_lnum = 1;
965 read_buf_col = 0;
966 }
Bram Moolenaar8767f522016-07-01 17:17:39 +0200967 else if (read_stdin || vim_lseek(fd, (off_T)0L, SEEK_SET) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000968 {
969 /* Can't rewind the file, give up. */
970 error = TRUE;
971 goto failed;
972 }
973 /* Delete the previously read lines. */
974 while (lnum > from)
975 ml_delete(lnum--, FALSE);
976 file_rewind = FALSE;
977#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000978 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000979 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000980 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000981 curbuf->b_start_bomb = FALSE;
982 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000983 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000984#endif
985 }
986
987 /*
988 * When retrying with another "fenc" and the first time "fileformat"
989 * will be reset.
990 */
991 if (keep_fileformat)
992 keep_fileformat = FALSE;
993 else
994 {
995 if (eap != NULL && eap->force_ff != 0)
Bram Moolenaar1c860362008-11-12 15:05:21 +0000996 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000997 fileformat = get_fileformat_force(curbuf, eap);
Bram Moolenaar1c860362008-11-12 15:05:21 +0000998 try_unix = try_dos = try_mac = FALSE;
999 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001000 else if (curbuf->b_p_bin)
1001 fileformat = EOL_UNIX; /* binary: use Unix format */
1002 else if (*p_ffs == NUL)
1003 fileformat = get_fileformat(curbuf);/* use format from buffer */
1004 else
1005 fileformat = EOL_UNKNOWN; /* detect from file */
1006 }
1007
1008#ifdef FEAT_MBYTE
1009# ifdef USE_ICONV
1010 if (iconv_fd != (iconv_t)-1)
1011 {
1012 /* aborted conversion with iconv(), close the descriptor */
1013 iconv_close(iconv_fd);
1014 iconv_fd = (iconv_t)-1;
1015 }
1016# endif
1017
1018 if (advance_fenc)
1019 {
1020 /*
1021 * Try the next entry in 'fileencodings'.
1022 */
1023 advance_fenc = FALSE;
1024
1025 if (eap != NULL && eap->force_enc != 0)
1026 {
1027 /* Conversion given with "++cc=" wasn't possible, read
1028 * without conversion. */
1029 notconverted = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001030 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001031 if (fenc_alloced)
1032 vim_free(fenc);
1033 fenc = (char_u *)"";
1034 fenc_alloced = FALSE;
1035 }
1036 else
1037 {
1038 if (fenc_alloced)
1039 vim_free(fenc);
1040 if (fenc_next != NULL)
1041 {
1042 fenc = next_fenc(&fenc_next);
1043 fenc_alloced = (fenc_next != NULL);
1044 }
1045 else
1046 {
1047 fenc = (char_u *)"";
1048 fenc_alloced = FALSE;
1049 }
1050 }
1051 if (tmpname != NULL)
1052 {
1053 mch_remove(tmpname); /* delete converted file */
Bram Moolenaard23a8232018-02-10 18:45:26 +01001054 VIM_CLEAR(tmpname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001055 }
1056 }
1057
1058 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001059 * Conversion may be required when the encoding of the file is different
1060 * from 'encoding' or 'encoding' is UTF-16, UCS-2 or UCS-4.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001061 */
1062 fio_flags = 0;
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001063 converted = need_conversion(fenc);
1064 if (converted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001065 {
1066
1067 /* "ucs-bom" means we need to check the first bytes of the file
1068 * for a BOM. */
1069 if (STRCMP(fenc, ENC_UCSBOM) == 0)
1070 fio_flags = FIO_UCSBOM;
1071
1072 /*
1073 * Check if UCS-2/4 or Latin1 to UTF-8 conversion needs to be
1074 * done. This is handled below after read(). Prepare the
1075 * fio_flags to avoid having to parse the string each time.
1076 * Also check for Unicode to Latin1 conversion, because iconv()
1077 * appears not to handle this correctly. This works just like
1078 * conversion to UTF-8 except how the resulting character is put in
1079 * the buffer.
1080 */
1081 else if (enc_utf8 || STRCMP(p_enc, "latin1") == 0)
1082 fio_flags = get_fio_flags(fenc);
1083
1084# ifdef WIN3264
1085 /*
1086 * Conversion from an MS-Windows codepage to UTF-8 or another codepage
1087 * is handled with MultiByteToWideChar().
1088 */
1089 if (fio_flags == 0)
1090 fio_flags = get_win_fio_flags(fenc);
1091# endif
1092
Bram Moolenaard0573012017-10-28 21:11:06 +02001093# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001094 /* Conversion from Apple MacRoman to latin1 or UTF-8 */
1095 if (fio_flags == 0)
1096 fio_flags = get_mac_fio_flags(fenc);
1097# endif
1098
1099# ifdef USE_ICONV
1100 /*
1101 * Try using iconv() if we can't convert internally.
1102 */
1103 if (fio_flags == 0
1104# ifdef FEAT_EVAL
1105 && !did_iconv
1106# endif
1107 )
1108 iconv_fd = (iconv_t)my_iconv_open(
1109 enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc);
1110# endif
1111
1112# ifdef FEAT_EVAL
1113 /*
1114 * Use the 'charconvert' expression when conversion is required
1115 * and we can't do it internally or with iconv().
1116 */
1117 if (fio_flags == 0 && !read_stdin && !read_buffer && *p_ccv != NUL
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02001118 && !read_fifo
Bram Moolenaar071d4272004-06-13 20:20:40 +00001119# ifdef USE_ICONV
1120 && iconv_fd == (iconv_t)-1
1121# endif
1122 )
1123 {
1124# ifdef USE_ICONV
1125 did_iconv = FALSE;
1126# endif
1127 /* Skip conversion when it's already done (retry for wrong
1128 * "fileformat"). */
1129 if (tmpname == NULL)
1130 {
1131 tmpname = readfile_charconvert(fname, fenc, &fd);
1132 if (tmpname == NULL)
1133 {
1134 /* Conversion failed. Try another one. */
1135 advance_fenc = TRUE;
1136 if (fd < 0)
1137 {
1138 /* Re-opening the original file failed! */
1139 EMSG(_("E202: Conversion made file unreadable!"));
1140 error = TRUE;
1141 goto failed;
1142 }
1143 goto retry;
1144 }
1145 }
1146 }
1147 else
1148# endif
1149 {
1150 if (fio_flags == 0
1151# ifdef USE_ICONV
1152 && iconv_fd == (iconv_t)-1
1153# endif
1154 )
1155 {
1156 /* Conversion wanted but we can't.
1157 * Try the next conversion in 'fileencodings' */
1158 advance_fenc = TRUE;
1159 goto retry;
1160 }
1161 }
1162 }
1163
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001164 /* Set "can_retry" when it's possible to rewind the file and try with
Bram Moolenaar071d4272004-06-13 20:20:40 +00001165 * another "fenc" value. It's FALSE when no other "fenc" to try, reading
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001166 * stdin or fixed at a specific encoding. */
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02001167 can_retry = (*fenc != NUL && !read_stdin && !read_fifo && !keep_dest_enc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001168#endif
1169
1170 if (!skip_read)
1171 {
1172 linerest = 0;
1173 filesize = 0;
1174 skip_count = lines_to_skip;
1175 read_count = lines_to_read;
1176#ifdef FEAT_MBYTE
1177 conv_restlen = 0;
1178#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001179#ifdef FEAT_PERSISTENT_UNDO
Bram Moolenaar59f931e2010-07-24 20:27:03 +02001180 read_undo_file = (newfile && (flags & READ_KEEP_UNDO) == 0
1181 && curbuf->b_ffname != NULL
1182 && curbuf->b_p_udf
1183 && !filtering
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02001184 && !read_fifo
Bram Moolenaar59f931e2010-07-24 20:27:03 +02001185 && !read_stdin
1186 && !read_buffer);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001187 if (read_undo_file)
1188 sha256_start(&sha_ctx);
1189#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001190#ifdef FEAT_CRYPT
1191 if (curbuf->b_cryptstate != NULL)
1192 {
1193 /* Need to free the state, but keep the key, don't want to ask for
1194 * it again. */
1195 crypt_free_state(curbuf->b_cryptstate);
1196 curbuf->b_cryptstate = NULL;
1197 }
1198#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001199 }
1200
1201 while (!error && !got_int)
1202 {
1203 /*
1204 * We allocate as much space for the file as we can get, plus
1205 * space for the old line plus room for one terminating NUL.
1206 * The amount is limited by the fact that read() only can read
1207 * upto max_unsigned characters (and other things).
1208 */
Bram Moolenaara2aa31a2014-02-23 22:52:40 +01001209#if VIM_SIZEOF_INT <= 2
Bram Moolenaar071d4272004-06-13 20:20:40 +00001210 if (linerest >= 0x7ff0)
1211 {
1212 ++split;
1213 *ptr = NL; /* split line by inserting a NL */
1214 size = 1;
1215 }
1216 else
1217#endif
1218 {
1219 if (!skip_read)
1220 {
Bram Moolenaara2aa31a2014-02-23 22:52:40 +01001221#if VIM_SIZEOF_INT > 2
Bram Moolenaar311d9822007-02-27 15:48:28 +00001222# if defined(SSIZE_MAX) && (SSIZE_MAX < 0x10000L)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001223 size = SSIZE_MAX; /* use max I/O size, 52K */
1224# else
1225 size = 0x10000L; /* use buffer >= 64K */
1226# endif
1227#else
1228 size = 0x7ff0L - linerest; /* limit buffer to 32K */
1229#endif
1230
Bram Moolenaarc1e37902006-04-18 21:55:01 +00001231 for ( ; size >= 10; size = (long)((long_u)size >> 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001232 {
1233 if ((new_buffer = lalloc((long_u)(size + linerest + 1),
1234 FALSE)) != NULL)
1235 break;
1236 }
1237 if (new_buffer == NULL)
1238 {
1239 do_outofmem_msg((long_u)(size * 2 + linerest + 1));
1240 error = TRUE;
1241 break;
1242 }
1243 if (linerest) /* copy characters from the previous buffer */
1244 mch_memmove(new_buffer, ptr - linerest, (size_t)linerest);
1245 vim_free(buffer);
1246 buffer = new_buffer;
1247 ptr = buffer + linerest;
1248 line_start = buffer;
1249
1250#ifdef FEAT_MBYTE
1251 /* May need room to translate into.
1252 * For iconv() we don't really know the required space, use a
1253 * factor ICONV_MULT.
1254 * latin1 to utf-8: 1 byte becomes up to 2 bytes
1255 * utf-16 to utf-8: 2 bytes become up to 3 bytes, 4 bytes
1256 * become up to 4 bytes, size must be multiple of 2
1257 * ucs-2 to utf-8: 2 bytes become up to 3 bytes, size must be
1258 * multiple of 2
1259 * ucs-4 to utf-8: 4 bytes become up to 6 bytes, size must be
1260 * multiple of 4 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001261 real_size = (int)size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001262# ifdef USE_ICONV
1263 if (iconv_fd != (iconv_t)-1)
1264 size = size / ICONV_MULT;
1265 else
1266# endif
1267 if (fio_flags & FIO_LATIN1)
1268 size = size / 2;
1269 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1270 size = (size * 2 / 3) & ~1;
1271 else if (fio_flags & FIO_UCS4)
1272 size = (size * 2 / 3) & ~3;
1273 else if (fio_flags == FIO_UCSBOM)
1274 size = size / ICONV_MULT; /* worst case */
1275# ifdef WIN3264
1276 else if (fio_flags & FIO_CODEPAGE)
1277 size = size / ICONV_MULT; /* also worst case */
1278# endif
Bram Moolenaard0573012017-10-28 21:11:06 +02001279# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001280 else if (fio_flags & FIO_MACROMAN)
1281 size = size / ICONV_MULT; /* also worst case */
1282# endif
1283#endif
1284
1285#ifdef FEAT_MBYTE
1286 if (conv_restlen > 0)
1287 {
1288 /* Insert unconverted bytes from previous line. */
1289 mch_memmove(ptr, conv_rest, conv_restlen);
1290 ptr += conv_restlen;
1291 size -= conv_restlen;
1292 }
1293#endif
1294
1295 if (read_buffer)
1296 {
1297 /*
1298 * Read bytes from curbuf. Used for converting text read
1299 * from stdin.
1300 */
1301 if (read_buf_lnum > from)
1302 size = 0;
1303 else
1304 {
1305 int n, ni;
1306 long tlen;
1307
1308 tlen = 0;
1309 for (;;)
1310 {
1311 p = ml_get(read_buf_lnum) + read_buf_col;
1312 n = (int)STRLEN(p);
1313 if ((int)tlen + n + 1 > size)
1314 {
1315 /* Filled up to "size", append partial line.
1316 * Change NL to NUL to reverse the effect done
1317 * below. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001318 n = (int)(size - tlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001319 for (ni = 0; ni < n; ++ni)
1320 {
1321 if (p[ni] == NL)
1322 ptr[tlen++] = NUL;
1323 else
1324 ptr[tlen++] = p[ni];
1325 }
1326 read_buf_col += n;
1327 break;
1328 }
1329 else
1330 {
1331 /* Append whole line and new-line. Change NL
1332 * to NUL to reverse the effect done below. */
1333 for (ni = 0; ni < n; ++ni)
1334 {
1335 if (p[ni] == NL)
1336 ptr[tlen++] = NUL;
1337 else
1338 ptr[tlen++] = p[ni];
1339 }
1340 ptr[tlen++] = NL;
1341 read_buf_col = 0;
1342 if (++read_buf_lnum > from)
1343 {
1344 /* When the last line didn't have an
1345 * end-of-line don't add it now either. */
1346 if (!curbuf->b_p_eol)
1347 --tlen;
1348 size = tlen;
1349 break;
1350 }
1351 }
1352 }
1353 }
1354 }
1355 else
1356 {
1357 /*
1358 * Read bytes from the file.
1359 */
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01001360 size = read_eintr(fd, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001361 }
1362
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001363#ifdef FEAT_CRYPT
1364 /*
1365 * At start of file: Check for magic number of encryption.
1366 */
1367 if (filesize == 0 && size > 0)
1368 cryptkey = check_for_cryptkey(cryptkey, ptr, &size,
1369 &filesize, newfile, sfname,
1370 &did_ask_for_key);
1371 /*
1372 * Decrypt the read bytes. This is done before checking for
1373 * EOF because the crypt layer may be buffering.
1374 */
Bram Moolenaar829aa642017-08-23 22:32:35 +02001375 if (cryptkey != NULL && curbuf->b_cryptstate != NULL
1376 && size > 0)
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001377 {
1378 if (crypt_works_inplace(curbuf->b_cryptstate))
1379 {
1380 crypt_decode_inplace(curbuf->b_cryptstate, ptr, size);
1381 }
1382 else
1383 {
1384 char_u *newptr = NULL;
1385 int decrypted_size;
1386
1387 decrypted_size = crypt_decode_alloc(
1388 curbuf->b_cryptstate, ptr, size, &newptr);
1389
1390 /* If the crypt layer is buffering, not producing
1391 * anything yet, need to read more. */
1392 if (size > 0 && decrypted_size == 0)
1393 continue;
1394
1395 if (linerest == 0)
1396 {
1397 /* Simple case: reuse returned buffer (may be
1398 * NULL, checked later). */
1399 new_buffer = newptr;
1400 }
1401 else
1402 {
1403 long_u new_size;
1404
1405 /* Need new buffer to add bytes carried over. */
1406 new_size = (long_u)(decrypted_size + linerest + 1);
1407 new_buffer = lalloc(new_size, FALSE);
1408 if (new_buffer == NULL)
1409 {
1410 do_outofmem_msg(new_size);
1411 error = TRUE;
1412 break;
1413 }
1414
1415 mch_memmove(new_buffer, buffer, linerest);
1416 if (newptr != NULL)
1417 mch_memmove(new_buffer + linerest, newptr,
1418 decrypted_size);
1419 }
1420
1421 if (new_buffer != NULL)
1422 {
1423 vim_free(buffer);
1424 buffer = new_buffer;
1425 new_buffer = NULL;
1426 line_start = buffer;
1427 ptr = buffer + linerest;
1428 }
1429 size = decrypted_size;
1430 }
1431 }
1432#endif
1433
Bram Moolenaar071d4272004-06-13 20:20:40 +00001434 if (size <= 0)
1435 {
1436 if (size < 0) /* read error */
1437 error = TRUE;
1438#ifdef FEAT_MBYTE
1439 else if (conv_restlen > 0)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001440 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001441 /*
1442 * Reached end-of-file but some trailing bytes could
1443 * not be converted. Truncated file?
1444 */
1445
1446 /* When we did a conversion report an error. */
1447 if (fio_flags != 0
1448# ifdef USE_ICONV
1449 || iconv_fd != (iconv_t)-1
1450# endif
1451 )
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001452 {
Bram Moolenaare8d95302013-04-24 16:34:02 +02001453 if (can_retry)
1454 goto rewind_retry;
Bram Moolenaarf453d352008-06-04 17:37:34 +00001455 if (conv_error == 0)
1456 conv_error = curbuf->b_ml.ml_line_count
1457 - linecnt + 1;
1458 }
1459 /* Remember the first linenr with an illegal byte */
1460 else if (illegal_byte == 0)
1461 illegal_byte = curbuf->b_ml.ml_line_count
1462 - linecnt + 1;
1463 if (bad_char_behavior == BAD_DROP)
1464 {
1465 *(ptr - conv_restlen) = NUL;
1466 conv_restlen = 0;
1467 }
1468 else
1469 {
1470 /* Replace the trailing bytes with the replacement
1471 * character if we were converting; if we weren't,
1472 * leave the UTF8 checking code to do it, as it
1473 * works slightly differently. */
1474 if (bad_char_behavior != BAD_KEEP && (fio_flags != 0
1475# ifdef USE_ICONV
1476 || iconv_fd != (iconv_t)-1
1477# endif
1478 ))
1479 {
1480 while (conv_restlen > 0)
1481 {
1482 *(--ptr) = bad_char_behavior;
1483 --conv_restlen;
1484 }
1485 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001486 fio_flags = 0; /* don't convert this */
Bram Moolenaarb21e5842006-04-16 18:30:08 +00001487# ifdef USE_ICONV
1488 if (iconv_fd != (iconv_t)-1)
1489 {
1490 iconv_close(iconv_fd);
1491 iconv_fd = (iconv_t)-1;
1492 }
1493# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001494 }
1495 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001496#endif
1497 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001498 }
1499 skip_read = FALSE;
1500
1501#ifdef FEAT_MBYTE
1502 /*
1503 * At start of file (or after crypt magic number): Check for BOM.
1504 * Also check for a BOM for other Unicode encodings, but not after
1505 * converting with 'charconvert' or when a BOM has already been
1506 * found.
1507 */
1508 if ((filesize == 0
1509# ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001510 || (cryptkey != NULL
1511 && filesize == crypt_get_header_len(
1512 crypt_get_method_nr(curbuf)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001513# endif
1514 )
1515 && (fio_flags == FIO_UCSBOM
1516 || (!curbuf->b_p_bomb
1517 && tmpname == NULL
1518 && (*fenc == 'u' || (*fenc == NUL && enc_utf8)))))
1519 {
1520 char_u *ccname;
1521 int blen;
1522
1523 /* no BOM detection in a short file or in binary mode */
1524 if (size < 2 || curbuf->b_p_bin)
1525 ccname = NULL;
1526 else
1527 ccname = check_for_bom(ptr, size, &blen,
1528 fio_flags == FIO_UCSBOM ? FIO_ALL : get_fio_flags(fenc));
1529 if (ccname != NULL)
1530 {
1531 /* Remove BOM from the text */
1532 filesize += blen;
1533 size -= blen;
1534 mch_memmove(ptr, ptr + blen, (size_t)size);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00001535 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001536 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001537 curbuf->b_p_bomb = TRUE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001538 curbuf->b_start_bomb = TRUE;
1539 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001540 }
1541
1542 if (fio_flags == FIO_UCSBOM)
1543 {
1544 if (ccname == NULL)
1545 {
1546 /* No BOM detected: retry with next encoding. */
1547 advance_fenc = TRUE;
1548 }
1549 else
1550 {
1551 /* BOM detected: set "fenc" and jump back */
1552 if (fenc_alloced)
1553 vim_free(fenc);
1554 fenc = ccname;
1555 fenc_alloced = FALSE;
1556 }
1557 /* retry reading without getting new bytes or rewinding */
1558 skip_read = TRUE;
1559 goto retry;
1560 }
1561 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001562
1563 /* Include not converted bytes. */
1564 ptr -= conv_restlen;
1565 size += conv_restlen;
1566 conv_restlen = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001567#endif
1568 /*
1569 * Break here for a read error or end-of-file.
1570 */
1571 if (size <= 0)
1572 break;
1573
1574#ifdef FEAT_MBYTE
1575
Bram Moolenaar071d4272004-06-13 20:20:40 +00001576# ifdef USE_ICONV
1577 if (iconv_fd != (iconv_t)-1)
1578 {
1579 /*
1580 * Attempt conversion of the read bytes to 'encoding' using
1581 * iconv().
1582 */
1583 const char *fromp;
1584 char *top;
1585 size_t from_size;
1586 size_t to_size;
1587
1588 fromp = (char *)ptr;
1589 from_size = size;
1590 ptr += size;
1591 top = (char *)ptr;
1592 to_size = real_size - size;
1593
1594 /*
1595 * If there is conversion error or not enough room try using
Bram Moolenaar19a09a12005-03-04 23:39:37 +00001596 * another conversion. Except for when there is no
1597 * alternative (help files).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001598 */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001599 while ((iconv(iconv_fd, (void *)&fromp, &from_size,
1600 &top, &to_size)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001601 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
1602 || from_size > CONV_RESTLEN)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001603 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001604 if (can_retry)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001605 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001606 if (conv_error == 0)
1607 conv_error = readfile_linenr(linecnt,
1608 ptr, (char_u *)top);
Bram Moolenaar42eeac32005-06-29 22:40:58 +00001609
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001610 /* Deal with a bad byte and continue with the next. */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001611 ++fromp;
1612 --from_size;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001613 if (bad_char_behavior == BAD_KEEP)
1614 {
1615 *top++ = *(fromp - 1);
1616 --to_size;
1617 }
1618 else if (bad_char_behavior != BAD_DROP)
1619 {
1620 *top++ = bad_char_behavior;
1621 --to_size;
1622 }
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001623 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001624
1625 if (from_size > 0)
1626 {
1627 /* Some remaining characters, keep them for the next
1628 * round. */
1629 mch_memmove(conv_rest, (char_u *)fromp, from_size);
1630 conv_restlen = (int)from_size;
1631 }
1632
1633 /* move the linerest to before the converted characters */
1634 line_start = ptr - linerest;
1635 mch_memmove(line_start, buffer, (size_t)linerest);
1636 size = (long)((char_u *)top - ptr);
1637 }
1638# endif
1639
1640# ifdef WIN3264
1641 if (fio_flags & FIO_CODEPAGE)
1642 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001643 char_u *src, *dst;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001644 WCHAR ucs2buf[3];
1645 int ucs2len;
1646 int codepage = FIO_GET_CP(fio_flags);
1647 int bytelen;
1648 int found_bad;
1649 char replstr[2];
1650
Bram Moolenaar071d4272004-06-13 20:20:40 +00001651 /*
1652 * Conversion from an MS-Windows codepage or UTF-8 to UTF-8 or
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001653 * a codepage, using standard MS-Windows functions. This
1654 * requires two steps:
1655 * 1. convert from 'fileencoding' to ucs-2
1656 * 2. convert from ucs-2 to 'encoding'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001657 *
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001658 * Because there may be illegal bytes AND an incomplete byte
1659 * sequence at the end, we may have to do the conversion one
1660 * character at a time to get it right.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001661 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001662
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001663 /* Replacement string for WideCharToMultiByte(). */
1664 if (bad_char_behavior > 0)
1665 replstr[0] = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001666 else
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001667 replstr[0] = '?';
1668 replstr[1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001669
1670 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001671 * Move the bytes to the end of the buffer, so that we have
1672 * room to put the result at the start.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001673 */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001674 src = ptr + real_size - size;
1675 mch_memmove(src, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001676
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001677 /*
1678 * Do the conversion.
1679 */
1680 dst = ptr;
1681 size = size;
1682 while (size > 0)
1683 {
1684 found_bad = FALSE;
1685
1686# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
1687 if (codepage == CP_UTF8)
1688 {
1689 /* Handle CP_UTF8 input ourselves to be able to handle
1690 * trailing bytes properly.
1691 * Get one UTF-8 character from src. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001692 bytelen = (int)utf_ptr2len_len(src, size);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001693 if (bytelen > size)
1694 {
1695 /* Only got some bytes of a character. Normally
1696 * it's put in "conv_rest", but if it's too long
1697 * deal with it as if they were illegal bytes. */
1698 if (bytelen <= CONV_RESTLEN)
1699 break;
1700
1701 /* weird overlong byte sequence */
1702 bytelen = size;
1703 found_bad = TRUE;
1704 }
1705 else
1706 {
Bram Moolenaarc01140a2006-03-24 22:21:52 +00001707 int u8c = utf_ptr2char(src);
1708
Bram Moolenaar86e01082005-12-29 22:45:34 +00001709 if (u8c > 0xffff || (*src >= 0x80 && bytelen == 1))
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001710 found_bad = TRUE;
1711 ucs2buf[0] = u8c;
1712 ucs2len = 1;
1713 }
1714 }
1715 else
1716# endif
1717 {
1718 /* We don't know how long the byte sequence is, try
1719 * from one to three bytes. */
1720 for (bytelen = 1; bytelen <= size && bytelen <= 3;
1721 ++bytelen)
1722 {
1723 ucs2len = MultiByteToWideChar(codepage,
1724 MB_ERR_INVALID_CHARS,
1725 (LPCSTR)src, bytelen,
1726 ucs2buf, 3);
1727 if (ucs2len > 0)
1728 break;
1729 }
1730 if (ucs2len == 0)
1731 {
1732 /* If we have only one byte then it's probably an
1733 * incomplete byte sequence. Otherwise discard
1734 * one byte as a bad character. */
1735 if (size == 1)
1736 break;
1737 found_bad = TRUE;
1738 bytelen = 1;
1739 }
1740 }
1741
1742 if (!found_bad)
1743 {
1744 int i;
1745
1746 /* Convert "ucs2buf[ucs2len]" to 'enc' in "dst". */
1747 if (enc_utf8)
1748 {
1749 /* From UCS-2 to UTF-8. Cannot fail. */
1750 for (i = 0; i < ucs2len; ++i)
1751 dst += utf_char2bytes(ucs2buf[i], dst);
1752 }
1753 else
1754 {
1755 BOOL bad = FALSE;
1756 int dstlen;
1757
1758 /* From UCS-2 to "enc_codepage". If the
1759 * conversion uses the default character "?",
1760 * the data doesn't fit in this encoding. */
1761 dstlen = WideCharToMultiByte(enc_codepage, 0,
1762 (LPCWSTR)ucs2buf, ucs2len,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001763 (LPSTR)dst, (int)(src - dst),
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001764 replstr, &bad);
1765 if (bad)
1766 found_bad = TRUE;
1767 else
1768 dst += dstlen;
1769 }
1770 }
1771
1772 if (found_bad)
1773 {
1774 /* Deal with bytes we can't convert. */
1775 if (can_retry)
1776 goto rewind_retry;
1777 if (conv_error == 0)
1778 conv_error = readfile_linenr(linecnt, ptr, dst);
1779 if (bad_char_behavior != BAD_DROP)
1780 {
1781 if (bad_char_behavior == BAD_KEEP)
1782 {
1783 mch_memmove(dst, src, bytelen);
1784 dst += bytelen;
1785 }
1786 else
1787 *dst++ = bad_char_behavior;
1788 }
1789 }
1790
1791 src += bytelen;
1792 size -= bytelen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001793 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001794
1795 if (size > 0)
1796 {
1797 /* An incomplete byte sequence remaining. */
1798 mch_memmove(conv_rest, src, size);
1799 conv_restlen = size;
1800 }
1801
1802 /* The new size is equal to how much "dst" was advanced. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001803 size = (long)(dst - ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001804 }
1805 else
1806# endif
Bram Moolenaar56718732006-03-15 22:53:57 +00001807# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001808 if (fio_flags & FIO_MACROMAN)
1809 {
1810 /*
1811 * Conversion from Apple MacRoman char encoding to UTF-8 or
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001812 * latin1. This is in os_mac_conv.c.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001813 */
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001814 if (macroman2enc(ptr, &size, real_size) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001815 goto rewind_retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001816 }
1817 else
1818# endif
1819 if (fio_flags != 0)
1820 {
1821 int u8c;
1822 char_u *dest;
1823 char_u *tail = NULL;
1824
1825 /*
1826 * "enc_utf8" set: Convert Unicode or Latin1 to UTF-8.
1827 * "enc_utf8" not set: Convert Unicode to Latin1.
1828 * Go from end to start through the buffer, because the number
1829 * of bytes may increase.
1830 * "dest" points to after where the UTF-8 bytes go, "p" points
1831 * to after the next character to convert.
1832 */
1833 dest = ptr + real_size;
1834 if (fio_flags == FIO_LATIN1 || fio_flags == FIO_UTF8)
1835 {
1836 p = ptr + size;
1837 if (fio_flags == FIO_UTF8)
1838 {
1839 /* Check for a trailing incomplete UTF-8 sequence */
1840 tail = ptr + size - 1;
1841 while (tail > ptr && (*tail & 0xc0) == 0x80)
1842 --tail;
1843 if (tail + utf_byte2len(*tail) <= ptr + size)
1844 tail = NULL;
1845 else
1846 p = tail;
1847 }
1848 }
1849 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1850 {
1851 /* Check for a trailing byte */
1852 p = ptr + (size & ~1);
1853 if (size & 1)
1854 tail = p;
1855 if ((fio_flags & FIO_UTF16) && p > ptr)
1856 {
1857 /* Check for a trailing leading word */
1858 if (fio_flags & FIO_ENDIAN_L)
1859 {
1860 u8c = (*--p << 8);
1861 u8c += *--p;
1862 }
1863 else
1864 {
1865 u8c = *--p;
1866 u8c += (*--p << 8);
1867 }
1868 if (u8c >= 0xd800 && u8c <= 0xdbff)
1869 tail = p;
1870 else
1871 p += 2;
1872 }
1873 }
1874 else /* FIO_UCS4 */
1875 {
1876 /* Check for trailing 1, 2 or 3 bytes */
1877 p = ptr + (size & ~3);
1878 if (size & 3)
1879 tail = p;
1880 }
1881
1882 /* If there is a trailing incomplete sequence move it to
1883 * conv_rest[]. */
1884 if (tail != NULL)
1885 {
1886 conv_restlen = (int)((ptr + size) - tail);
1887 mch_memmove(conv_rest, (char_u *)tail, conv_restlen);
1888 size -= conv_restlen;
1889 }
1890
1891
1892 while (p > ptr)
1893 {
1894 if (fio_flags & FIO_LATIN1)
1895 u8c = *--p;
1896 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1897 {
1898 if (fio_flags & FIO_ENDIAN_L)
1899 {
1900 u8c = (*--p << 8);
1901 u8c += *--p;
1902 }
1903 else
1904 {
1905 u8c = *--p;
1906 u8c += (*--p << 8);
1907 }
1908 if ((fio_flags & FIO_UTF16)
1909 && u8c >= 0xdc00 && u8c <= 0xdfff)
1910 {
1911 int u16c;
1912
1913 if (p == ptr)
1914 {
1915 /* Missing leading word. */
1916 if (can_retry)
1917 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001918 if (conv_error == 0)
1919 conv_error = readfile_linenr(linecnt,
1920 ptr, p);
1921 if (bad_char_behavior == BAD_DROP)
1922 continue;
1923 if (bad_char_behavior != BAD_KEEP)
1924 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001925 }
1926
1927 /* found second word of double-word, get the first
1928 * word and compute the resulting character */
1929 if (fio_flags & FIO_ENDIAN_L)
1930 {
1931 u16c = (*--p << 8);
1932 u16c += *--p;
1933 }
1934 else
1935 {
1936 u16c = *--p;
1937 u16c += (*--p << 8);
1938 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001939 u8c = 0x10000 + ((u16c & 0x3ff) << 10)
1940 + (u8c & 0x3ff);
1941
Bram Moolenaar071d4272004-06-13 20:20:40 +00001942 /* Check if the word is indeed a leading word. */
1943 if (u16c < 0xd800 || u16c > 0xdbff)
1944 {
1945 if (can_retry)
1946 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001947 if (conv_error == 0)
1948 conv_error = readfile_linenr(linecnt,
1949 ptr, p);
1950 if (bad_char_behavior == BAD_DROP)
1951 continue;
1952 if (bad_char_behavior != BAD_KEEP)
1953 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001954 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001955 }
1956 }
1957 else if (fio_flags & FIO_UCS4)
1958 {
1959 if (fio_flags & FIO_ENDIAN_L)
1960 {
Bram Moolenaardc1c9812017-10-27 22:15:24 +02001961 u8c = (unsigned)*--p << 24;
1962 u8c += (unsigned)*--p << 16;
1963 u8c += (unsigned)*--p << 8;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001964 u8c += *--p;
1965 }
1966 else /* big endian */
1967 {
1968 u8c = *--p;
Bram Moolenaardc1c9812017-10-27 22:15:24 +02001969 u8c += (unsigned)*--p << 8;
1970 u8c += (unsigned)*--p << 16;
1971 u8c += (unsigned)*--p << 24;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001972 }
1973 }
1974 else /* UTF-8 */
1975 {
1976 if (*--p < 0x80)
1977 u8c = *p;
1978 else
1979 {
1980 len = utf_head_off(ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001981 p -= len;
1982 u8c = utf_ptr2char(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001983 if (len == 0)
1984 {
1985 /* Not a valid UTF-8 character, retry with
1986 * another fenc when possible, otherwise just
1987 * report the error. */
1988 if (can_retry)
1989 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001990 if (conv_error == 0)
1991 conv_error = readfile_linenr(linecnt,
1992 ptr, p);
1993 if (bad_char_behavior == BAD_DROP)
1994 continue;
1995 if (bad_char_behavior != BAD_KEEP)
1996 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001997 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001998 }
1999 }
2000 if (enc_utf8) /* produce UTF-8 */
2001 {
2002 dest -= utf_char2len(u8c);
2003 (void)utf_char2bytes(u8c, dest);
2004 }
2005 else /* produce Latin1 */
2006 {
2007 --dest;
2008 if (u8c >= 0x100)
2009 {
2010 /* character doesn't fit in latin1, retry with
2011 * another fenc when possible, otherwise just
2012 * report the error. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002013 if (can_retry)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002014 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002015 if (conv_error == 0)
2016 conv_error = readfile_linenr(linecnt, ptr, p);
2017 if (bad_char_behavior == BAD_DROP)
2018 ++dest;
2019 else if (bad_char_behavior == BAD_KEEP)
2020 *dest = u8c;
2021 else if (eap != NULL && eap->bad_char != 0)
2022 *dest = bad_char_behavior;
2023 else
2024 *dest = 0xBF;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002025 }
2026 else
2027 *dest = u8c;
2028 }
2029 }
2030
2031 /* move the linerest to before the converted characters */
2032 line_start = dest - linerest;
2033 mch_memmove(line_start, buffer, (size_t)linerest);
2034 size = (long)((ptr + real_size) - dest);
2035 ptr = dest;
2036 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002037 else if (enc_utf8 && !curbuf->b_p_bin)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002038 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002039 int incomplete_tail = FALSE;
2040
2041 /* Reading UTF-8: Check if the bytes are valid UTF-8. */
2042 for (p = ptr; ; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002043 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002044 int todo = (int)((ptr + size) - p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002045 int l;
2046
2047 if (todo <= 0)
2048 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002049 if (*p >= 0x80)
2050 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002051 /* A length of 1 means it's an illegal byte. Accept
2052 * an incomplete character at the end though, the next
2053 * read() will get the next bytes, we'll check it
2054 * then. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002055 l = utf_ptr2len_len(p, todo);
Bram Moolenaarf453d352008-06-04 17:37:34 +00002056 if (l > todo && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002057 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002058 /* Avoid retrying with a different encoding when
2059 * a truncated file is more likely, or attempting
2060 * to read the rest of an incomplete sequence when
2061 * we have already done so. */
2062 if (p > ptr || filesize > 0)
2063 incomplete_tail = TRUE;
2064 /* Incomplete byte sequence, move it to conv_rest[]
2065 * and try to read the rest of it, unless we've
2066 * already done so. */
2067 if (p > ptr)
2068 {
2069 conv_restlen = todo;
2070 mch_memmove(conv_rest, p, conv_restlen);
2071 size -= conv_restlen;
2072 break;
2073 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002074 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002075 if (l == 1 || l > todo)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002076 {
2077 /* Illegal byte. If we can try another encoding
Bram Moolenaarf453d352008-06-04 17:37:34 +00002078 * do that, unless at EOF where a truncated
2079 * file is more likely than a conversion error. */
2080 if (can_retry && !incomplete_tail)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002081 break;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002082# ifdef USE_ICONV
2083 /* When we did a conversion report an error. */
2084 if (iconv_fd != (iconv_t)-1 && conv_error == 0)
2085 conv_error = readfile_linenr(linecnt, ptr, p);
2086# endif
Bram Moolenaarf453d352008-06-04 17:37:34 +00002087 /* Remember the first linenr with an illegal byte */
2088 if (conv_error == 0 && illegal_byte == 0)
2089 illegal_byte = readfile_linenr(linecnt, ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002090
2091 /* Drop, keep or replace the bad byte. */
2092 if (bad_char_behavior == BAD_DROP)
2093 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002094 mch_memmove(p, p + 1, todo - 1);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002095 --p;
2096 --size;
2097 }
2098 else if (bad_char_behavior != BAD_KEEP)
2099 *p = bad_char_behavior;
2100 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002101 else
2102 p += l - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002103 }
2104 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002105 if (p < ptr + size && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002106 {
2107 /* Detected a UTF-8 error. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002108rewind_retry:
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002109 /* Retry reading with another conversion. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002110# if defined(FEAT_EVAL) && defined(USE_ICONV)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002111 if (*p_ccv != NUL && iconv_fd != (iconv_t)-1)
2112 /* iconv() failed, try 'charconvert' */
2113 did_iconv = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002114 else
2115# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002116 /* use next item from 'fileencodings' */
2117 advance_fenc = TRUE;
2118 file_rewind = TRUE;
2119 goto retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002120 }
2121 }
2122#endif
2123
2124 /* count the number of characters (after conversion!) */
2125 filesize += size;
2126
2127 /*
2128 * when reading the first part of a file: guess EOL type
2129 */
2130 if (fileformat == EOL_UNKNOWN)
2131 {
2132 /* First try finding a NL, for Dos and Unix */
2133 if (try_dos || try_unix)
2134 {
Bram Moolenaarc6b72172015-02-27 17:48:09 +01002135 /* Reset the carriage return counter. */
2136 if (try_mac)
2137 try_mac = 1;
2138
Bram Moolenaar071d4272004-06-13 20:20:40 +00002139 for (p = ptr; p < ptr + size; ++p)
2140 {
2141 if (*p == NL)
2142 {
2143 if (!try_unix
2144 || (try_dos && p > ptr && p[-1] == CAR))
2145 fileformat = EOL_DOS;
2146 else
2147 fileformat = EOL_UNIX;
2148 break;
2149 }
Bram Moolenaar05eb6122015-02-17 14:15:19 +01002150 else if (*p == CAR && try_mac)
2151 try_mac++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002152 }
2153
2154 /* Don't give in to EOL_UNIX if EOL_MAC is more likely */
2155 if (fileformat == EOL_UNIX && try_mac)
2156 {
2157 /* Need to reset the counters when retrying fenc. */
2158 try_mac = 1;
2159 try_unix = 1;
2160 for (; p >= ptr && *p != CAR; p--)
2161 ;
2162 if (p >= ptr)
2163 {
2164 for (p = ptr; p < ptr + size; ++p)
2165 {
2166 if (*p == NL)
2167 try_unix++;
2168 else if (*p == CAR)
2169 try_mac++;
2170 }
2171 if (try_mac > try_unix)
2172 fileformat = EOL_MAC;
2173 }
2174 }
Bram Moolenaar05eb6122015-02-17 14:15:19 +01002175 else if (fileformat == EOL_UNKNOWN && try_mac == 1)
2176 /* Looking for CR but found no end-of-line markers at
2177 * all: use the default format. */
2178 fileformat = default_fileformat();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002179 }
2180
2181 /* No NL found: may use Mac format */
2182 if (fileformat == EOL_UNKNOWN && try_mac)
2183 fileformat = EOL_MAC;
2184
2185 /* Still nothing found? Use first format in 'ffs' */
2186 if (fileformat == EOL_UNKNOWN)
2187 fileformat = default_fileformat();
2188
2189 /* if editing a new file: may set p_tx and p_ff */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002190 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002191 set_fileformat(fileformat, OPT_LOCAL);
2192 }
2193 }
2194
2195 /*
2196 * This loop is executed once for every character read.
2197 * Keep it fast!
2198 */
2199 if (fileformat == EOL_MAC)
2200 {
2201 --ptr;
2202 while (++ptr, --size >= 0)
2203 {
2204 /* catch most common case first */
2205 if ((c = *ptr) != NUL && c != CAR && c != NL)
2206 continue;
2207 if (c == NUL)
2208 *ptr = NL; /* NULs are replaced by newlines! */
2209 else if (c == NL)
2210 *ptr = CAR; /* NLs are replaced by CRs! */
2211 else
2212 {
2213 if (skip_count == 0)
2214 {
2215 *ptr = NUL; /* end of line */
2216 len = (colnr_T) (ptr - line_start + 1);
2217 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2218 {
2219 error = TRUE;
2220 break;
2221 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002222#ifdef FEAT_PERSISTENT_UNDO
2223 if (read_undo_file)
2224 sha256_update(&sha_ctx, line_start, len);
2225#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002226 ++lnum;
2227 if (--read_count == 0)
2228 {
2229 error = TRUE; /* break loop */
2230 line_start = ptr; /* nothing left to write */
2231 break;
2232 }
2233 }
2234 else
2235 --skip_count;
2236 line_start = ptr + 1;
2237 }
2238 }
2239 }
2240 else
2241 {
2242 --ptr;
2243 while (++ptr, --size >= 0)
2244 {
2245 if ((c = *ptr) != NUL && c != NL) /* catch most common case */
2246 continue;
2247 if (c == NUL)
2248 *ptr = NL; /* NULs are replaced by newlines! */
2249 else
2250 {
2251 if (skip_count == 0)
2252 {
2253 *ptr = NUL; /* end of line */
2254 len = (colnr_T)(ptr - line_start + 1);
2255 if (fileformat == EOL_DOS)
2256 {
Bram Moolenaar2aa5f692017-01-24 15:46:48 +01002257 if (ptr > line_start && ptr[-1] == CAR)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002258 {
Bram Moolenaar2aa5f692017-01-24 15:46:48 +01002259 /* remove CR before NL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002260 ptr[-1] = NUL;
2261 --len;
2262 }
2263 /*
2264 * Reading in Dos format, but no CR-LF found!
2265 * When 'fileformats' includes "unix", delete all
2266 * the lines read so far and start all over again.
2267 * Otherwise give an error message later.
2268 */
2269 else if (ff_error != EOL_DOS)
2270 {
2271 if ( try_unix
2272 && !read_stdin
2273 && (read_buffer
Bram Moolenaar8767f522016-07-01 17:17:39 +02002274 || vim_lseek(fd, (off_T)0L, SEEK_SET)
2275 == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002276 {
2277 fileformat = EOL_UNIX;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002278 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002279 set_fileformat(EOL_UNIX, OPT_LOCAL);
2280 file_rewind = TRUE;
2281 keep_fileformat = TRUE;
2282 goto retry;
2283 }
2284 ff_error = EOL_DOS;
2285 }
2286 }
2287 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2288 {
2289 error = TRUE;
2290 break;
2291 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002292#ifdef FEAT_PERSISTENT_UNDO
2293 if (read_undo_file)
2294 sha256_update(&sha_ctx, line_start, len);
2295#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002296 ++lnum;
2297 if (--read_count == 0)
2298 {
2299 error = TRUE; /* break loop */
2300 line_start = ptr; /* nothing left to write */
2301 break;
2302 }
2303 }
2304 else
2305 --skip_count;
2306 line_start = ptr + 1;
2307 }
2308 }
2309 }
2310 linerest = (long)(ptr - line_start);
2311 ui_breakcheck();
2312 }
2313
2314failed:
2315 /* not an error, max. number of lines reached */
2316 if (error && read_count == 0)
2317 error = FALSE;
2318
2319 /*
2320 * If we get EOF in the middle of a line, note the fact and
2321 * complete the line ourselves.
2322 * In Dos format ignore a trailing CTRL-Z, unless 'binary' set.
2323 */
2324 if (!error
2325 && !got_int
2326 && linerest != 0
2327 && !(!curbuf->b_p_bin
2328 && fileformat == EOL_DOS
2329 && *line_start == Ctrl_Z
2330 && ptr == line_start + 1))
2331 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002332 /* remember for when writing */
2333 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002334 curbuf->b_p_eol = FALSE;
2335 *ptr = NUL;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002336 len = (colnr_T)(ptr - line_start + 1);
2337 if (ml_append(lnum, line_start, len, newfile) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002338 error = TRUE;
2339 else
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002340 {
2341#ifdef FEAT_PERSISTENT_UNDO
2342 if (read_undo_file)
2343 sha256_update(&sha_ctx, line_start, len);
2344#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002345 read_no_eol_lnum = ++lnum;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002346 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002347 }
2348
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002349 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002350 save_file_ff(curbuf); /* remember the current file format */
2351
2352#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002353 if (curbuf->b_cryptstate != NULL)
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002354 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002355 crypt_free_state(curbuf->b_cryptstate);
2356 curbuf->b_cryptstate = NULL;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002357 }
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002358 if (cryptkey != NULL && cryptkey != curbuf->b_p_key)
2359 crypt_free_key(cryptkey);
2360 /* Don't set cryptkey to NULL, it's used below as a flag that
2361 * encryption was used. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002362#endif
2363
2364#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002365 /* If editing a new file: set 'fenc' for the current buffer.
2366 * Also for ":read ++edit file". */
2367 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002368 set_string_option_direct((char_u *)"fenc", -1, fenc,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00002369 OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002370 if (fenc_alloced)
2371 vim_free(fenc);
2372# ifdef USE_ICONV
2373 if (iconv_fd != (iconv_t)-1)
2374 {
2375 iconv_close(iconv_fd);
2376 iconv_fd = (iconv_t)-1;
2377 }
2378# endif
2379#endif
2380
2381 if (!read_buffer && !read_stdin)
2382 close(fd); /* errors are ignored */
Bram Moolenaarf05da212009-11-17 16:13:15 +00002383#ifdef HAVE_FD_CLOEXEC
2384 else
2385 {
2386 int fdflags = fcntl(fd, F_GETFD);
2387 if (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0)
Bram Moolenaarfbc4b4d2016-02-07 15:14:01 +01002388 (void)fcntl(fd, F_SETFD, fdflags | FD_CLOEXEC);
Bram Moolenaarf05da212009-11-17 16:13:15 +00002389 }
2390#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002391 vim_free(buffer);
2392
2393#ifdef HAVE_DUP
2394 if (read_stdin)
2395 {
2396 /* Use stderr for stdin, makes shell commands work. */
2397 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00002398 ignored = dup(2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002399 }
2400#endif
2401
2402#ifdef FEAT_MBYTE
2403 if (tmpname != NULL)
2404 {
2405 mch_remove(tmpname); /* delete converted file */
2406 vim_free(tmpname);
2407 }
2408#endif
2409 --no_wait_return; /* may wait for return now */
2410
2411 /*
2412 * In recovery mode everything but autocommands is skipped.
2413 */
2414 if (!recoverymode)
2415 {
2416 /* need to delete the last line, which comes from the empty buffer */
2417 if (newfile && wasempty && !(curbuf->b_ml.ml_flags & ML_EMPTY))
2418 {
2419#ifdef FEAT_NETBEANS_INTG
2420 netbeansFireChanges = 0;
2421#endif
2422 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
2423#ifdef FEAT_NETBEANS_INTG
2424 netbeansFireChanges = 1;
2425#endif
2426 --linecnt;
2427 }
2428 linecnt = curbuf->b_ml.ml_line_count - linecnt;
2429 if (filesize == 0)
2430 linecnt = 0;
2431 if (newfile || read_buffer)
Bram Moolenaar7263a772007-05-10 17:35:54 +00002432 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002433 redraw_curbuf_later(NOT_VALID);
Bram Moolenaar7263a772007-05-10 17:35:54 +00002434#ifdef FEAT_DIFF
2435 /* After reading the text into the buffer the diff info needs to
2436 * be updated. */
2437 diff_invalidate(curbuf);
2438#endif
2439#ifdef FEAT_FOLDING
2440 /* All folds in the window are invalid now. Mark them for update
2441 * before triggering autocommands. */
2442 foldUpdateAll(curwin);
2443#endif
2444 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002445 else if (linecnt) /* appended at least one line */
2446 appended_lines_mark(from, linecnt);
2447
Bram Moolenaar071d4272004-06-13 20:20:40 +00002448#ifndef ALWAYS_USE_GUI
2449 /*
2450 * If we were reading from the same terminal as where messages go,
2451 * the screen will have been messed up.
2452 * Switch on raw mode now and clear the screen.
2453 */
2454 if (read_stdin)
2455 {
2456 settmode(TMODE_RAW); /* set to raw mode */
2457 starttermcap();
2458 screenclear();
2459 }
2460#endif
2461
2462 if (got_int)
2463 {
2464 if (!(flags & READ_DUMMY))
2465 {
2466 filemess(curbuf, sfname, (char_u *)_(e_interr), 0);
2467 if (newfile)
2468 curbuf->b_p_ro = TRUE; /* must use "w!" now */
2469 }
2470 msg_scroll = msg_save;
2471#ifdef FEAT_VIMINFO
2472 check_marks_read();
2473#endif
2474 return OK; /* an interrupt isn't really an error */
2475 }
2476
2477 if (!filtering && !(flags & READ_DUMMY))
2478 {
2479 msg_add_fname(curbuf, sfname); /* fname in IObuff with quotes */
2480 c = FALSE;
2481
2482#ifdef UNIX
2483# ifdef S_ISFIFO
2484 if (S_ISFIFO(perm)) /* fifo or socket */
2485 {
2486 STRCAT(IObuff, _("[fifo/socket]"));
2487 c = TRUE;
2488 }
2489# else
2490# ifdef S_IFIFO
2491 if ((perm & S_IFMT) == S_IFIFO) /* fifo */
2492 {
2493 STRCAT(IObuff, _("[fifo]"));
2494 c = TRUE;
2495 }
2496# endif
2497# ifdef S_IFSOCK
2498 if ((perm & S_IFMT) == S_IFSOCK) /* or socket */
2499 {
2500 STRCAT(IObuff, _("[socket]"));
2501 c = TRUE;
2502 }
2503# endif
2504# endif
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002505# ifdef OPEN_CHR_FILES
2506 if (S_ISCHR(perm)) /* or character special */
2507 {
2508 STRCAT(IObuff, _("[character special]"));
2509 c = TRUE;
2510 }
2511# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002512#endif
2513 if (curbuf->b_p_ro)
2514 {
2515 STRCAT(IObuff, shortmess(SHM_RO) ? _("[RO]") : _("[readonly]"));
2516 c = TRUE;
2517 }
2518 if (read_no_eol_lnum)
2519 {
2520 msg_add_eol();
2521 c = TRUE;
2522 }
2523 if (ff_error == EOL_DOS)
2524 {
2525 STRCAT(IObuff, _("[CR missing]"));
2526 c = TRUE;
2527 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002528 if (split)
2529 {
2530 STRCAT(IObuff, _("[long lines split]"));
2531 c = TRUE;
2532 }
2533#ifdef FEAT_MBYTE
2534 if (notconverted)
2535 {
2536 STRCAT(IObuff, _("[NOT converted]"));
2537 c = TRUE;
2538 }
2539 else if (converted)
2540 {
2541 STRCAT(IObuff, _("[converted]"));
2542 c = TRUE;
2543 }
2544#endif
2545#ifdef FEAT_CRYPT
2546 if (cryptkey != NULL)
2547 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002548 crypt_append_msg(curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002549 c = TRUE;
2550 }
2551#endif
2552#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002553 if (conv_error != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002554 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002555 sprintf((char *)IObuff + STRLEN(IObuff),
2556 _("[CONVERSION ERROR in line %ld]"), (long)conv_error);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002557 c = TRUE;
2558 }
2559 else if (illegal_byte > 0)
2560 {
2561 sprintf((char *)IObuff + STRLEN(IObuff),
2562 _("[ILLEGAL BYTE in line %ld]"), (long)illegal_byte);
2563 c = TRUE;
2564 }
2565 else
2566#endif
2567 if (error)
2568 {
2569 STRCAT(IObuff, _("[READ ERRORS]"));
2570 c = TRUE;
2571 }
2572 if (msg_add_fileformat(fileformat))
2573 c = TRUE;
2574#ifdef FEAT_CRYPT
2575 if (cryptkey != NULL)
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002576 msg_add_lines(c, (long)linecnt, filesize
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002577 - crypt_get_header_len(crypt_get_method_nr(curbuf)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002578 else
2579#endif
2580 msg_add_lines(c, (long)linecnt, filesize);
2581
Bram Moolenaard23a8232018-02-10 18:45:26 +01002582 VIM_CLEAR(keep_msg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002583 msg_scrolled_ign = TRUE;
2584#ifdef ALWAYS_USE_GUI
2585 /* Don't show the message when reading stdin, it would end up in a
2586 * message box (which might be shown when exiting!) */
2587 if (read_stdin || read_buffer)
2588 p = msg_may_trunc(FALSE, IObuff);
2589 else
2590#endif
2591 p = msg_trunc_attr(IObuff, FALSE, 0);
2592 if (read_stdin || read_buffer || restart_edit != 0
Bram Moolenaar1c7715d2005-10-03 22:02:18 +00002593 || (msg_scrolled != 0 && !need_wait_return))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002594 /* Need to repeat the message after redrawing when:
2595 * - When reading from stdin (the screen will be cleared next).
2596 * - When restart_edit is set (otherwise there will be a delay
2597 * before redrawing).
2598 * - When the screen was scrolled but there is no wait-return
2599 * prompt. */
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002600 set_keep_msg(p, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002601 msg_scrolled_ign = FALSE;
2602 }
2603
2604 /* with errors writing the file requires ":w!" */
2605 if (newfile && (error
2606#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002607 || conv_error != 0
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002608 || (illegal_byte > 0 && bad_char_behavior != BAD_KEEP)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002609#endif
2610 ))
2611 curbuf->b_p_ro = TRUE;
2612
2613 u_clearline(); /* cannot use "U" command after adding lines */
2614
2615 /*
2616 * In Ex mode: cursor at last new line.
2617 * Otherwise: cursor at first new line.
2618 */
2619 if (exmode_active)
2620 curwin->w_cursor.lnum = from + linecnt;
2621 else
2622 curwin->w_cursor.lnum = from + 1;
2623 check_cursor_lnum();
2624 beginline(BL_WHITE | BL_FIX); /* on first non-blank */
2625
2626 /*
2627 * Set '[ and '] marks to the newly read lines.
2628 */
2629 curbuf->b_op_start.lnum = from + 1;
2630 curbuf->b_op_start.col = 0;
2631 curbuf->b_op_end.lnum = from + linecnt;
2632 curbuf->b_op_end.col = 0;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002633
2634#ifdef WIN32
2635 /*
2636 * Work around a weird problem: When a file has two links (only
2637 * possible on NTFS) and we write through one link, then stat() it
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00002638 * through the other link, the timestamp information may be wrong.
Bram Moolenaar03f48552006-02-28 23:52:23 +00002639 * It's correct again after reading the file, thus reset the timestamp
2640 * here.
2641 */
2642 if (newfile && !read_stdin && !read_buffer
2643 && mch_stat((char *)fname, &st) >= 0)
2644 {
2645 buf_store_time(curbuf, &st, fname);
2646 curbuf->b_mtime_read = curbuf->b_mtime;
2647 }
2648#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002649 }
2650 msg_scroll = msg_save;
2651
2652#ifdef FEAT_VIMINFO
2653 /*
2654 * Get the marks before executing autocommands, so they can be used there.
2655 */
2656 check_marks_read();
2657#endif
2658
Bram Moolenaar071d4272004-06-13 20:20:40 +00002659 /*
Bram Moolenaar34d72d42015-07-17 14:18:08 +02002660 * We remember if the last line of the read didn't have
2661 * an eol even when 'binary' is off, to support turning 'fixeol' off,
2662 * or writing the read again with 'binary' on. The latter is required
2663 * for ":autocmd FileReadPost *.gz set bin|'[,']!gunzip" to work.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002664 */
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002665 curbuf->b_no_eol_lnum = read_no_eol_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002666
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02002667 /* When reloading a buffer put the cursor at the first line that is
2668 * different. */
2669 if (flags & READ_KEEP_UNDO)
2670 u_find_first_changed();
2671
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002672#ifdef FEAT_PERSISTENT_UNDO
2673 /*
2674 * When opening a new file locate undo info and read it.
2675 */
2676 if (read_undo_file)
2677 {
2678 char_u hash[UNDO_HASH_SIZE];
2679
2680 sha256_finish(&sha_ctx, hash);
Bram Moolenaar6ed8ed82010-05-30 20:40:11 +02002681 u_read_undo(NULL, hash, fname);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002682 }
2683#endif
2684
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02002685 if (!read_stdin && !read_fifo && (!read_buffer || sfname != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002686 {
2687 int m = msg_scroll;
2688 int n = msg_scrolled;
2689
2690 /* Save the fileformat now, otherwise the buffer will be considered
2691 * modified if the format/encoding was automatically detected. */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002692 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002693 save_file_ff(curbuf);
2694
2695 /*
2696 * The output from the autocommands should not overwrite anything and
2697 * should not be overwritten: Set msg_scroll, restore its value if no
2698 * output was done.
2699 */
2700 msg_scroll = TRUE;
2701 if (filtering)
2702 apply_autocmds_exarg(EVENT_FILTERREADPOST, NULL, sfname,
2703 FALSE, curbuf, eap);
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02002704 else if (newfile || (read_buffer && sfname != NULL))
Bram Moolenaarc3691332016-04-20 12:49:49 +02002705 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002706 apply_autocmds_exarg(EVENT_BUFREADPOST, NULL, sfname,
2707 FALSE, curbuf, eap);
Bram Moolenaarc3691332016-04-20 12:49:49 +02002708 if (!au_did_filetype && *curbuf->b_p_ft != NUL)
2709 /*
2710 * EVENT_FILETYPE was not triggered but the buffer already has a
2711 * filetype. Trigger EVENT_FILETYPE using the existing filetype.
2712 */
2713 apply_autocmds(EVENT_FILETYPE, curbuf->b_p_ft, curbuf->b_fname,
2714 TRUE, curbuf);
2715 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002716 else
2717 apply_autocmds_exarg(EVENT_FILEREADPOST, sfname, sfname,
2718 FALSE, NULL, eap);
2719 if (msg_scrolled == n)
2720 msg_scroll = m;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002721# ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002722 if (aborting()) /* autocmds may abort script processing */
2723 return FAIL;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002724# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002725 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002726
2727 if (recoverymode && error)
2728 return FAIL;
2729 return OK;
2730}
2731
Bram Moolenaarf04507d2016-08-20 15:05:39 +02002732#if defined(OPEN_CHR_FILES) || defined(PROTO)
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002733/*
2734 * Returns TRUE if the file name argument is of the form "/dev/fd/\d\+",
2735 * which is the name of files used for process substitution output by
2736 * some shells on some operating systems, e.g., bash on SunOS.
2737 * Do not accept "/dev/fd/[012]", opening these may hang Vim.
2738 */
Bram Moolenaarf04507d2016-08-20 15:05:39 +02002739 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002740is_dev_fd_file(char_u *fname)
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002741{
2742 return (STRNCMP(fname, "/dev/fd/", 8) == 0
2743 && VIM_ISDIGIT(fname[8])
2744 && *skipdigits(fname + 9) == NUL
2745 && (fname[9] != NUL
2746 || (fname[8] != '0' && fname[8] != '1' && fname[8] != '2')));
2747}
2748#endif
2749
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002750#ifdef FEAT_MBYTE
2751
2752/*
2753 * From the current line count and characters read after that, estimate the
2754 * line number where we are now.
2755 * Used for error messages that include a line number.
2756 */
2757 static linenr_T
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002758readfile_linenr(
2759 linenr_T linecnt, /* line count before reading more bytes */
2760 char_u *p, /* start of more bytes read */
2761 char_u *endp) /* end of more bytes read */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002762{
2763 char_u *s;
2764 linenr_T lnum;
2765
2766 lnum = curbuf->b_ml.ml_line_count - linecnt + 1;
2767 for (s = p; s < endp; ++s)
2768 if (*s == '\n')
2769 ++lnum;
2770 return lnum;
2771}
2772#endif
2773
Bram Moolenaar071d4272004-06-13 20:20:40 +00002774/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00002775 * Fill "*eap" to force the 'fileencoding', 'fileformat' and 'binary to be
2776 * equal to the buffer "buf". Used for calling readfile().
Bram Moolenaar071d4272004-06-13 20:20:40 +00002777 * Returns OK or FAIL.
2778 */
2779 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002780prep_exarg(exarg_T *eap, buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002781{
Bram Moolenaar333b80a2018-04-04 22:57:29 +02002782 eap->cmd = alloc(15
Bram Moolenaar071d4272004-06-13 20:20:40 +00002783#ifdef FEAT_MBYTE
Bram Moolenaar333b80a2018-04-04 22:57:29 +02002784 + (unsigned)STRLEN(buf->b_p_fenc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002785#endif
Bram Moolenaar333b80a2018-04-04 22:57:29 +02002786 );
Bram Moolenaar071d4272004-06-13 20:20:40 +00002787 if (eap->cmd == NULL)
2788 return FAIL;
2789
2790#ifdef FEAT_MBYTE
Bram Moolenaar333b80a2018-04-04 22:57:29 +02002791 sprintf((char *)eap->cmd, "e ++enc=%s", buf->b_p_fenc);
2792 eap->force_enc = 8;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002793 eap->bad_char = buf->b_bad_char;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002794#else
Bram Moolenaar333b80a2018-04-04 22:57:29 +02002795 sprintf((char *)eap->cmd, "e");
Bram Moolenaar071d4272004-06-13 20:20:40 +00002796#endif
Bram Moolenaar333b80a2018-04-04 22:57:29 +02002797 eap->force_ff = *buf->b_p_ff;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002798
2799 eap->force_bin = buf->b_p_bin ? FORCE_BIN : FORCE_NOBIN;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002800 eap->read_edit = FALSE;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002801 eap->forceit = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002802 return OK;
2803}
2804
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002805/*
2806 * Set default or forced 'fileformat' and 'binary'.
2807 */
2808 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002809set_file_options(int set_options, exarg_T *eap)
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002810{
2811 /* set default 'fileformat' */
2812 if (set_options)
2813 {
2814 if (eap != NULL && eap->force_ff != 0)
2815 set_fileformat(get_fileformat_force(curbuf, eap), OPT_LOCAL);
2816 else if (*p_ffs != NUL)
2817 set_fileformat(default_fileformat(), OPT_LOCAL);
2818 }
2819
2820 /* set or reset 'binary' */
2821 if (eap != NULL && eap->force_bin != 0)
2822 {
2823 int oldval = curbuf->b_p_bin;
2824
2825 curbuf->b_p_bin = (eap->force_bin == FORCE_BIN);
2826 set_options_bin(oldval, curbuf->b_p_bin, OPT_LOCAL);
2827 }
2828}
2829
2830#if defined(FEAT_MBYTE) || defined(PROTO)
2831/*
2832 * Set forced 'fileencoding'.
2833 */
2834 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002835set_forced_fenc(exarg_T *eap)
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002836{
2837 if (eap->force_enc != 0)
2838 {
2839 char_u *fenc = enc_canonize(eap->cmd + eap->force_enc);
2840
2841 if (fenc != NULL)
2842 set_string_option_direct((char_u *)"fenc", -1,
2843 fenc, OPT_FREE|OPT_LOCAL, 0);
2844 vim_free(fenc);
2845 }
2846}
2847
Bram Moolenaar071d4272004-06-13 20:20:40 +00002848/*
2849 * Find next fileencoding to use from 'fileencodings'.
2850 * "pp" points to fenc_next. It's advanced to the next item.
2851 * When there are no more items, an empty string is returned and *pp is set to
2852 * NULL.
2853 * When *pp is not set to NULL, the result is in allocated memory.
2854 */
2855 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002856next_fenc(char_u **pp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002857{
2858 char_u *p;
2859 char_u *r;
2860
2861 if (**pp == NUL)
2862 {
2863 *pp = NULL;
2864 return (char_u *)"";
2865 }
2866 p = vim_strchr(*pp, ',');
2867 if (p == NULL)
2868 {
2869 r = enc_canonize(*pp);
2870 *pp += STRLEN(*pp);
2871 }
2872 else
2873 {
2874 r = vim_strnsave(*pp, (int)(p - *pp));
2875 *pp = p + 1;
2876 if (r != NULL)
2877 {
2878 p = enc_canonize(r);
2879 vim_free(r);
2880 r = p;
2881 }
2882 }
2883 if (r == NULL) /* out of memory */
2884 {
2885 r = (char_u *)"";
2886 *pp = NULL;
2887 }
2888 return r;
2889}
2890
2891# ifdef FEAT_EVAL
2892/*
2893 * Convert a file with the 'charconvert' expression.
2894 * This closes the file which is to be read, converts it and opens the
2895 * resulting file for reading.
2896 * Returns name of the resulting converted file (the caller should delete it
2897 * after reading it).
2898 * Returns NULL if the conversion failed ("*fdp" is not set) .
2899 */
2900 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002901readfile_charconvert(
2902 char_u *fname, /* name of input file */
2903 char_u *fenc, /* converted from */
2904 int *fdp) /* in/out: file descriptor of file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002905{
2906 char_u *tmpname;
2907 char_u *errmsg = NULL;
2908
Bram Moolenaare5c421c2015-03-31 13:33:08 +02002909 tmpname = vim_tempname('r', FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002910 if (tmpname == NULL)
2911 errmsg = (char_u *)_("Can't find temp file for conversion");
2912 else
2913 {
2914 close(*fdp); /* close the input file, ignore errors */
2915 *fdp = -1;
2916 if (eval_charconvert(fenc, enc_utf8 ? (char_u *)"utf-8" : p_enc,
2917 fname, tmpname) == FAIL)
2918 errmsg = (char_u *)_("Conversion with 'charconvert' failed");
2919 if (errmsg == NULL && (*fdp = mch_open((char *)tmpname,
2920 O_RDONLY | O_EXTRA, 0)) < 0)
2921 errmsg = (char_u *)_("can't read output of 'charconvert'");
2922 }
2923
2924 if (errmsg != NULL)
2925 {
2926 /* Don't use emsg(), it breaks mappings, the retry with
2927 * another type of conversion might still work. */
2928 MSG(errmsg);
2929 if (tmpname != NULL)
2930 {
2931 mch_remove(tmpname); /* delete converted file */
Bram Moolenaard23a8232018-02-10 18:45:26 +01002932 VIM_CLEAR(tmpname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002933 }
2934 }
2935
2936 /* If the input file is closed, open it (caller should check for error). */
2937 if (*fdp < 0)
2938 *fdp = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
2939
2940 return tmpname;
2941}
2942# endif
2943
2944#endif
2945
2946#ifdef FEAT_VIMINFO
2947/*
2948 * Read marks for the current buffer from the viminfo file, when we support
2949 * buffer marks and the buffer has a name.
2950 */
2951 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002952check_marks_read(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002953{
2954 if (!curbuf->b_marks_read && get_viminfo_parameter('\'') > 0
2955 && curbuf->b_ffname != NULL)
Bram Moolenaard812df62008-11-09 12:46:09 +00002956 read_viminfo(NULL, VIF_WANT_MARKS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002957
2958 /* Always set b_marks_read; needed when 'viminfo' is changed to include
2959 * the ' parameter after opening a buffer. */
2960 curbuf->b_marks_read = TRUE;
2961}
2962#endif
2963
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002964#if defined(FEAT_CRYPT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002965/*
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002966 * Check for magic number used for encryption. Applies to the current buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002967 * If found, the magic number is removed from ptr[*sizep] and *sizep and
2968 * *filesizep are updated.
2969 * Return the (new) encryption key, NULL for no encryption.
2970 */
2971 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002972check_for_cryptkey(
2973 char_u *cryptkey, /* previous encryption key or NULL */
2974 char_u *ptr, /* pointer to read bytes */
2975 long *sizep, /* length of read bytes */
Bram Moolenaar8767f522016-07-01 17:17:39 +02002976 off_T *filesizep, /* nr of bytes used from file */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002977 int newfile, /* editing a new buffer */
2978 char_u *fname, /* file name to display */
2979 int *did_ask) /* flag: whether already asked for key */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002980{
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002981 int method = crypt_method_nr_from_magic((char *)ptr, *sizep);
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02002982 int b_p_ro = curbuf->b_p_ro;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002983
2984 if (method >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002985 {
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02002986 /* Mark the buffer as read-only until the decryption has taken place.
2987 * Avoids accidentally overwriting the file with garbage. */
2988 curbuf->b_p_ro = TRUE;
2989
Bram Moolenaar2be79502014-08-13 21:58:28 +02002990 /* Set the cryptmethod local to the buffer. */
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002991 crypt_set_cm_option(curbuf, method);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002992 if (cryptkey == NULL && !*did_ask)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002993 {
2994 if (*curbuf->b_p_key)
2995 cryptkey = curbuf->b_p_key;
2996 else
2997 {
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002998 /* When newfile is TRUE, store the typed key in the 'key'
2999 * option and don't free it. bf needs hash of the key saved.
Bram Moolenaarf50a2532010-05-21 15:36:08 +02003000 * Don't ask for the key again when first time Enter was hit.
3001 * Happens when retrying to detect encoding. */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003002 smsg((char_u *)_(need_key_msg), fname);
3003 msg_scroll = TRUE;
Bram Moolenaar3a0c9082014-11-12 15:15:42 +01003004 crypt_check_method(method);
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003005 cryptkey = crypt_get_key(newfile, FALSE);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02003006 *did_ask = TRUE;
3007
Bram Moolenaar071d4272004-06-13 20:20:40 +00003008 /* check if empty key entered */
3009 if (cryptkey != NULL && *cryptkey == NUL)
3010 {
3011 if (cryptkey != curbuf->b_p_key)
3012 vim_free(cryptkey);
3013 cryptkey = NULL;
3014 }
3015 }
3016 }
3017
3018 if (cryptkey != NULL)
3019 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003020 int header_len;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003021
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003022 curbuf->b_cryptstate = crypt_create_from_header(
3023 method, cryptkey, ptr);
3024 crypt_set_cm_option(curbuf, method);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003025
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003026 /* Remove cryptmethod specific header from the text. */
3027 header_len = crypt_get_header_len(method);
Bram Moolenaar680e0152016-09-25 20:54:11 +02003028 if (*sizep <= header_len)
3029 /* invalid header, buffer can't be encrypted */
3030 return NULL;
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003031 *filesizep += header_len;
3032 *sizep -= header_len;
3033 mch_memmove(ptr, ptr + header_len, (size_t)*sizep);
3034
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02003035 /* Restore the read-only flag. */
3036 curbuf->b_p_ro = b_p_ro;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003037 }
3038 }
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003039 /* When starting to edit a new file which does not have encryption, clear
3040 * the 'key' option, except when starting up (called with -x argument) */
Bram Moolenaarfa0ff9a2010-07-25 16:05:19 +02003041 else if (newfile && *curbuf->b_p_key != NUL && !starting)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003042 set_option_value((char_u *)"key", 0L, (char_u *)"", OPT_LOCAL);
3043
3044 return cryptkey;
3045}
Bram Moolenaar80794b12010-06-13 05:20:42 +02003046#endif /* FEAT_CRYPT */
3047
Bram Moolenaar071d4272004-06-13 20:20:40 +00003048#ifdef UNIX
3049 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003050set_file_time(
3051 char_u *fname,
3052 time_t atime, /* access time */
3053 time_t mtime) /* modification time */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003054{
3055# if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
3056 struct utimbuf buf;
3057
3058 buf.actime = atime;
3059 buf.modtime = mtime;
3060 (void)utime((char *)fname, &buf);
3061# else
3062# if defined(HAVE_UTIMES)
3063 struct timeval tvp[2];
3064
3065 tvp[0].tv_sec = atime;
3066 tvp[0].tv_usec = 0;
3067 tvp[1].tv_sec = mtime;
3068 tvp[1].tv_usec = 0;
3069# ifdef NeXT
3070 (void)utimes((char *)fname, tvp);
3071# else
3072 (void)utimes((char *)fname, (const struct timeval *)&tvp);
3073# endif
3074# endif
3075# endif
3076}
3077#endif /* UNIX */
3078
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003079#if defined(VMS) && !defined(MIN)
3080/* Older DECC compiler for VAX doesn't define MIN() */
3081# define MIN(a, b) ((a) < (b) ? (a) : (b))
3082#endif
3083
Bram Moolenaar071d4272004-06-13 20:20:40 +00003084/*
Bram Moolenaar5386a122007-06-28 20:02:32 +00003085 * Return TRUE if a file appears to be read-only from the file permissions.
3086 */
3087 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003088check_file_readonly(
3089 char_u *fname, /* full path to file */
3090 int perm) /* known permissions on file */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003091{
3092#ifndef USE_MCH_ACCESS
3093 int fd = 0;
3094#endif
3095
3096 return (
3097#ifdef USE_MCH_ACCESS
3098# ifdef UNIX
3099 (perm & 0222) == 0 ||
3100# endif
3101 mch_access((char *)fname, W_OK)
3102#else
3103 (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0
3104 ? TRUE : (close(fd), FALSE)
3105#endif
3106 );
3107}
3108
3109
3110/*
Bram Moolenaar292ad192005-12-11 21:29:51 +00003111 * buf_write() - write to file "fname" lines "start" through "end"
Bram Moolenaar071d4272004-06-13 20:20:40 +00003112 *
3113 * We do our own buffering here because fwrite() is so slow.
3114 *
Bram Moolenaar292ad192005-12-11 21:29:51 +00003115 * If "forceit" is true, we don't care for errors when attempting backups.
3116 * In case of an error everything possible is done to restore the original
Bram Moolenaare37d50a2008-08-06 17:06:04 +00003117 * file. But when "forceit" is TRUE, we risk losing it.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003118 *
3119 * When "reset_changed" is TRUE and "append" == FALSE and "start" == 1 and
3120 * "end" == curbuf->b_ml.ml_line_count, reset curbuf->b_changed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003121 *
3122 * This function must NOT use NameBuff (because it's called by autowrite()).
3123 *
3124 * return FAIL for failure, OK otherwise
3125 */
3126 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003127buf_write(
3128 buf_T *buf,
3129 char_u *fname,
3130 char_u *sfname,
3131 linenr_T start,
3132 linenr_T end,
3133 exarg_T *eap, /* for forced 'ff' and 'fenc', can be
Bram Moolenaar071d4272004-06-13 20:20:40 +00003134 NULL! */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003135 int append, /* append to the file */
3136 int forceit,
3137 int reset_changed,
3138 int filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003139{
3140 int fd;
3141 char_u *backup = NULL;
3142 int backup_copy = FALSE; /* copy the original file? */
3143 int dobackup;
3144 char_u *ffname;
3145 char_u *wfname = NULL; /* name of file to write to */
3146 char_u *s;
3147 char_u *ptr;
3148 char_u c;
3149 int len;
3150 linenr_T lnum;
3151 long nchars;
3152 char_u *errmsg = NULL;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003153 int errmsg_allocated = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003154 char_u *errnum = NULL;
3155 char_u *buffer;
3156 char_u smallbuf[SMBUFSIZE];
3157 char_u *backup_ext;
3158 int bufsize;
3159 long perm; /* file permissions */
3160 int retval = OK;
3161 int newfile = FALSE; /* TRUE if file doesn't exist yet */
3162 int msg_save = msg_scroll;
3163 int overwriting; /* TRUE if writing over original */
3164 int no_eol = FALSE; /* no end-of-line written */
3165 int device = FALSE; /* writing to a device */
Bram Moolenaar8767f522016-07-01 17:17:39 +02003166 stat_T st_old;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003167 int prev_got_int = got_int;
Bram Moolenaare6bf6552017-06-27 22:11:51 +02003168 int checking_conversion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003169 int file_readonly = FALSE; /* overwritten file is read-only */
3170 static char *err_readonly = "is read-only (cannot override: \"W\" in 'cpoptions')";
Bram Moolenaara06ecab2016-07-16 14:47:36 +02003171#if defined(UNIX) /*XXX fix me sometime? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003172 int made_writable = FALSE; /* 'w' bit has been set */
3173#endif
3174 /* writing everything */
3175 int whole = (start == 1 && end == buf->b_ml.ml_line_count);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003176 linenr_T old_line_count = buf->b_ml.ml_line_count;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003177 int attr;
3178 int fileformat;
3179 int write_bin;
3180 struct bw_info write_info; /* info for buf_write_bytes() */
3181#ifdef FEAT_MBYTE
3182 int converted = FALSE;
3183 int notconverted = FALSE;
3184 char_u *fenc; /* effective 'fileencoding' */
3185 char_u *fenc_tofree = NULL; /* allocated "fenc" */
3186#endif
3187#ifdef HAS_BW_FLAGS
3188 int wb_flags = 0;
3189#endif
3190#ifdef HAVE_ACL
3191 vim_acl_T acl = NULL; /* ACL copied from original file to
3192 backup or new file */
3193#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003194#ifdef FEAT_PERSISTENT_UNDO
3195 int write_undo_file = FALSE;
3196 context_sha256_T sha_ctx;
3197#endif
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003198 unsigned int bkc = get_bkc_value(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003199
3200 if (fname == NULL || *fname == NUL) /* safety check */
3201 return FAIL;
Bram Moolenaar70d60e92009-12-31 13:53:33 +00003202 if (buf->b_ml.ml_mfp == NULL)
3203 {
3204 /* This can happen during startup when there is a stray "w" in the
3205 * vimrc file. */
3206 EMSG(_(e_emptybuf));
3207 return FAIL;
3208 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003209
3210 /*
3211 * Disallow writing from .exrc and .vimrc in current directory for
3212 * security reasons.
3213 */
3214 if (check_secure())
3215 return FAIL;
3216
3217 /* Avoid a crash for a long name. */
3218 if (STRLEN(fname) >= MAXPATHL)
3219 {
3220 EMSG(_(e_longname));
3221 return FAIL;
3222 }
3223
3224#ifdef FEAT_MBYTE
3225 /* must init bw_conv_buf and bw_iconv_fd before jumping to "fail" */
3226 write_info.bw_conv_buf = NULL;
3227 write_info.bw_conv_error = FALSE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003228 write_info.bw_conv_error_lnum = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003229 write_info.bw_restlen = 0;
3230# ifdef USE_ICONV
3231 write_info.bw_iconv_fd = (iconv_t)-1;
3232# endif
3233#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003234#ifdef FEAT_CRYPT
3235 write_info.bw_buffer = buf;
3236#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003237
Bram Moolenaardf177f62005-02-22 08:39:57 +00003238 /* After writing a file changedtick changes but we don't want to display
3239 * the line. */
3240 ex_no_reprint = TRUE;
3241
Bram Moolenaar071d4272004-06-13 20:20:40 +00003242 /*
3243 * If there is no file name yet, use the one for the written file.
3244 * BF_NOTEDITED is set to reflect this (in case the write fails).
3245 * Don't do this when the write is for a filter command.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003246 * Don't do this when appending.
3247 * Only do this when 'cpoptions' contains the 'F' flag.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003248 */
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003249 if (buf->b_ffname == NULL
3250 && reset_changed
Bram Moolenaar071d4272004-06-13 20:20:40 +00003251 && whole
3252 && buf == curbuf
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00003253#ifdef FEAT_QUICKFIX
3254 && !bt_nofile(buf)
3255#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003256 && !filtering
Bram Moolenaar292ad192005-12-11 21:29:51 +00003257 && (!append || vim_strchr(p_cpo, CPO_FNAMEAPP) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003258 && vim_strchr(p_cpo, CPO_FNAMEW) != NULL)
3259 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003260 if (set_rw_fname(fname, sfname) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003261 return FAIL;
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003262 buf = curbuf; /* just in case autocmds made "buf" invalid */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003263 }
3264
3265 if (sfname == NULL)
3266 sfname = fname;
3267 /*
3268 * For Unix: Use the short file name whenever possible.
3269 * Avoids problems with networks and when directory names are changed.
3270 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
3271 * another directory, which we don't detect
3272 */
3273 ffname = fname; /* remember full fname */
3274#ifdef UNIX
3275 fname = sfname;
3276#endif
3277
3278 if (buf->b_ffname != NULL && fnamecmp(ffname, buf->b_ffname) == 0)
3279 overwriting = TRUE;
3280 else
3281 overwriting = FALSE;
3282
3283 if (exiting)
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003284 settmode(TMODE_COOK); /* when exiting allow typeahead now */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003285
3286 ++no_wait_return; /* don't wait for return yet */
3287
3288 /*
3289 * Set '[ and '] marks to the lines to be written.
3290 */
3291 buf->b_op_start.lnum = start;
3292 buf->b_op_start.col = 0;
3293 buf->b_op_end.lnum = end;
3294 buf->b_op_end.col = 0;
3295
Bram Moolenaar071d4272004-06-13 20:20:40 +00003296 {
3297 aco_save_T aco;
3298 int buf_ffname = FALSE;
3299 int buf_sfname = FALSE;
3300 int buf_fname_f = FALSE;
3301 int buf_fname_s = FALSE;
3302 int did_cmd = FALSE;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003303 int nofile_err = FALSE;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003304 int empty_memline = (buf->b_ml.ml_mfp == NULL);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003305 bufref_T bufref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003306
3307 /*
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003308 * Apply PRE autocommands.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003309 * Set curbuf to the buffer to be written.
3310 * Careful: The autocommands may call buf_write() recursively!
3311 */
3312 if (ffname == buf->b_ffname)
3313 buf_ffname = TRUE;
3314 if (sfname == buf->b_sfname)
3315 buf_sfname = TRUE;
3316 if (fname == buf->b_ffname)
3317 buf_fname_f = TRUE;
3318 if (fname == buf->b_sfname)
3319 buf_fname_s = TRUE;
3320
3321 /* set curwin/curbuf to buf and save a few things */
3322 aucmd_prepbuf(&aco, buf);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003323 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003324
3325 if (append)
3326 {
3327 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD,
3328 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003329 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003330#ifdef FEAT_QUICKFIX
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00003331 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003332 nofile_err = TRUE;
3333 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003334#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003335 apply_autocmds_exarg(EVENT_FILEAPPENDPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003336 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003337 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003338 }
3339 else if (filtering)
3340 {
3341 apply_autocmds_exarg(EVENT_FILTERWRITEPRE,
3342 NULL, sfname, FALSE, curbuf, eap);
3343 }
3344 else if (reset_changed && whole)
3345 {
Bram Moolenaar39fc42e2011-09-02 11:56:20 +02003346 int was_changed = curbufIsChanged();
3347
3348 did_cmd = apply_autocmds_exarg(EVENT_BUFWRITECMD,
3349 sfname, sfname, FALSE, curbuf, eap);
3350 if (did_cmd)
3351 {
3352 if (was_changed && !curbufIsChanged())
3353 {
3354 /* Written everything correctly and BufWriteCmd has reset
3355 * 'modified': Correct the undo information so that an
3356 * undo now sets 'modified'. */
3357 u_unchanged(curbuf);
3358 u_update_save_nr(curbuf);
3359 }
3360 }
3361 else
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003362 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003363#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003364 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003365 nofile_err = TRUE;
3366 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003367#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003368 apply_autocmds_exarg(EVENT_BUFWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003369 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003370 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003371 }
3372 else
3373 {
3374 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD,
3375 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003376 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003377#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003378 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003379 nofile_err = TRUE;
3380 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003381#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003382 apply_autocmds_exarg(EVENT_FILEWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003383 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003384 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003385 }
3386
3387 /* restore curwin/curbuf and a few other things */
3388 aucmd_restbuf(&aco);
3389
3390 /*
3391 * In three situations we return here and don't write the file:
3392 * 1. the autocommands deleted or unloaded the buffer.
3393 * 2. The autocommands abort script processing.
3394 * 3. If one of the "Cmd" autocommands was executed.
3395 */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003396 if (!bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003397 buf = NULL;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003398 if (buf == NULL || (buf->b_ml.ml_mfp == NULL && !empty_memline)
Bram Moolenaar1e015462005-09-25 22:16:38 +00003399 || did_cmd || nofile_err
3400#ifdef FEAT_EVAL
3401 || aborting()
3402#endif
3403 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003404 {
3405 --no_wait_return;
3406 msg_scroll = msg_save;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003407 if (nofile_err)
3408 EMSG(_("E676: No matching autocommands for acwrite buffer"));
3409
Bram Moolenaar1e015462005-09-25 22:16:38 +00003410 if (nofile_err
3411#ifdef FEAT_EVAL
3412 || aborting()
3413#endif
3414 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003415 /* An aborting error, interrupt or exception in the
3416 * autocommands. */
3417 return FAIL;
3418 if (did_cmd)
3419 {
3420 if (buf == NULL)
3421 /* The buffer was deleted. We assume it was written
3422 * (can't retry anyway). */
3423 return OK;
3424 if (overwriting)
3425 {
3426 /* Assume the buffer was written, update the timestamp. */
3427 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00003428 if (append)
3429 buf->b_flags &= ~BF_NEW;
3430 else
3431 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003432 }
Bram Moolenaar292ad192005-12-11 21:29:51 +00003433 if (reset_changed && buf->b_changed && !append
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003434 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003435 /* Buffer still changed, the autocommands didn't work
3436 * properly. */
3437 return FAIL;
3438 return OK;
3439 }
3440#ifdef FEAT_EVAL
3441 if (!aborting())
3442#endif
3443 EMSG(_("E203: Autocommands deleted or unloaded buffer to be written"));
3444 return FAIL;
3445 }
3446
3447 /*
3448 * The autocommands may have changed the number of lines in the file.
3449 * When writing the whole file, adjust the end.
3450 * When writing part of the file, assume that the autocommands only
3451 * changed the number of lines that are to be written (tricky!).
3452 */
3453 if (buf->b_ml.ml_line_count != old_line_count)
3454 {
3455 if (whole) /* write all */
3456 end = buf->b_ml.ml_line_count;
3457 else if (buf->b_ml.ml_line_count > old_line_count) /* more lines */
3458 end += buf->b_ml.ml_line_count - old_line_count;
3459 else /* less lines */
3460 {
3461 end -= old_line_count - buf->b_ml.ml_line_count;
3462 if (end < start)
3463 {
3464 --no_wait_return;
3465 msg_scroll = msg_save;
3466 EMSG(_("E204: Autocommand changed number of lines in unexpected way"));
3467 return FAIL;
3468 }
3469 }
3470 }
3471
3472 /*
3473 * The autocommands may have changed the name of the buffer, which may
3474 * be kept in fname, ffname and sfname.
3475 */
3476 if (buf_ffname)
3477 ffname = buf->b_ffname;
3478 if (buf_sfname)
3479 sfname = buf->b_sfname;
3480 if (buf_fname_f)
3481 fname = buf->b_ffname;
3482 if (buf_fname_s)
3483 fname = buf->b_sfname;
3484 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003485
3486#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003487 if (netbeans_active() && isNetbeansBuffer(buf))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003488 {
3489 if (whole)
3490 {
3491 /*
3492 * b_changed can be 0 after an undo, but we still need to write
3493 * the buffer to NetBeans.
3494 */
3495 if (buf->b_changed || isNetbeansModified(buf))
3496 {
Bram Moolenaar009b2592004-10-24 19:18:58 +00003497 --no_wait_return; /* may wait for return now */
3498 msg_scroll = msg_save;
3499 netbeans_save_buffer(buf); /* no error checking... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003500 return retval;
3501 }
3502 else
3503 {
3504 errnum = (char_u *)"E656: ";
Bram Moolenaared0e7452008-06-27 19:17:34 +00003505 errmsg = (char_u *)_("NetBeans disallows writes of unmodified buffers");
Bram Moolenaar071d4272004-06-13 20:20:40 +00003506 buffer = NULL;
3507 goto fail;
3508 }
3509 }
3510 else
3511 {
3512 errnum = (char_u *)"E657: ";
3513 errmsg = (char_u *)_("Partial writes disallowed for NetBeans buffers");
3514 buffer = NULL;
3515 goto fail;
3516 }
3517 }
3518#endif
3519
3520 if (shortmess(SHM_OVER) && !exiting)
3521 msg_scroll = FALSE; /* overwrite previous file message */
3522 else
3523 msg_scroll = TRUE; /* don't overwrite previous file message */
3524 if (!filtering)
3525 filemess(buf,
3526#ifndef UNIX
3527 sfname,
3528#else
3529 fname,
3530#endif
3531 (char_u *)"", 0); /* show that we are busy */
3532 msg_scroll = FALSE; /* always overwrite the file message now */
3533
3534 buffer = alloc(BUFSIZE);
3535 if (buffer == NULL) /* can't allocate big buffer, use small
3536 * one (to be able to write when out of
3537 * memory) */
3538 {
3539 buffer = smallbuf;
3540 bufsize = SMBUFSIZE;
3541 }
3542 else
3543 bufsize = BUFSIZE;
3544
3545 /*
3546 * Get information about original file (if there is one).
3547 */
Bram Moolenaar53076832015-12-31 19:53:21 +01003548#if defined(UNIX)
Bram Moolenaar6f192452007-11-08 19:49:02 +00003549 st_old.st_dev = 0;
3550 st_old.st_ino = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003551 perm = -1;
3552 if (mch_stat((char *)fname, &st_old) < 0)
3553 newfile = TRUE;
3554 else
3555 {
3556 perm = st_old.st_mode;
3557 if (!S_ISREG(st_old.st_mode)) /* not a file */
3558 {
3559 if (S_ISDIR(st_old.st_mode))
3560 {
3561 errnum = (char_u *)"E502: ";
3562 errmsg = (char_u *)_("is a directory");
3563 goto fail;
3564 }
3565 if (mch_nodetype(fname) != NODE_WRITABLE)
3566 {
3567 errnum = (char_u *)"E503: ";
3568 errmsg = (char_u *)_("is not a file or writable device");
3569 goto fail;
3570 }
3571 /* It's a device of some kind (or a fifo) which we can write to
3572 * but for which we can't make a backup. */
3573 device = TRUE;
3574 newfile = TRUE;
3575 perm = -1;
3576 }
3577 }
3578#else /* !UNIX */
3579 /*
3580 * Check for a writable device name.
3581 */
3582 c = mch_nodetype(fname);
3583 if (c == NODE_OTHER)
3584 {
3585 errnum = (char_u *)"E503: ";
3586 errmsg = (char_u *)_("is not a file or writable device");
3587 goto fail;
3588 }
3589 if (c == NODE_WRITABLE)
3590 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003591# if defined(MSWIN)
Bram Moolenaar043545e2006-10-10 16:44:07 +00003592 /* MS-Windows allows opening a device, but we will probably get stuck
3593 * trying to write to it. */
3594 if (!p_odev)
3595 {
3596 errnum = (char_u *)"E796: ";
3597 errmsg = (char_u *)_("writing to device disabled with 'opendevice' option");
3598 goto fail;
3599 }
3600# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003601 device = TRUE;
3602 newfile = TRUE;
3603 perm = -1;
3604 }
3605 else
3606 {
3607 perm = mch_getperm(fname);
3608 if (perm < 0)
3609 newfile = TRUE;
3610 else if (mch_isdir(fname))
3611 {
3612 errnum = (char_u *)"E502: ";
3613 errmsg = (char_u *)_("is a directory");
3614 goto fail;
3615 }
3616 if (overwriting)
3617 (void)mch_stat((char *)fname, &st_old);
3618 }
3619#endif /* !UNIX */
3620
3621 if (!device && !newfile)
3622 {
3623 /*
3624 * Check if the file is really writable (when renaming the file to
3625 * make a backup we won't discover it later).
3626 */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003627 file_readonly = check_file_readonly(fname, (int)perm);
3628
Bram Moolenaar071d4272004-06-13 20:20:40 +00003629 if (!forceit && file_readonly)
3630 {
3631 if (vim_strchr(p_cpo, CPO_FWRITE) != NULL)
3632 {
3633 errnum = (char_u *)"E504: ";
3634 errmsg = (char_u *)_(err_readonly);
3635 }
3636 else
3637 {
3638 errnum = (char_u *)"E505: ";
3639 errmsg = (char_u *)_("is read-only (add ! to override)");
3640 }
3641 goto fail;
3642 }
3643
3644 /*
3645 * Check if the timestamp hasn't changed since reading the file.
3646 */
3647 if (overwriting)
3648 {
3649 retval = check_mtime(buf, &st_old);
3650 if (retval == FAIL)
3651 goto fail;
3652 }
3653 }
3654
3655#ifdef HAVE_ACL
3656 /*
3657 * For systems that support ACL: get the ACL from the original file.
3658 */
3659 if (!newfile)
3660 acl = mch_get_acl(fname);
3661#endif
3662
3663 /*
3664 * If 'backupskip' is not empty, don't make a backup for some files.
3665 */
3666 dobackup = (p_wb || p_bk || *p_pm != NUL);
3667#ifdef FEAT_WILDIGN
3668 if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname))
3669 dobackup = FALSE;
3670#endif
3671
3672 /*
3673 * Save the value of got_int and reset it. We don't want a previous
3674 * interruption cancel writing, only hitting CTRL-C while writing should
3675 * abort it.
3676 */
3677 prev_got_int = got_int;
3678 got_int = FALSE;
3679
3680 /* Mark the buffer as 'being saved' to prevent changed buffer warnings */
3681 buf->b_saving = TRUE;
3682
3683 /*
3684 * If we are not appending or filtering, the file exists, and the
3685 * 'writebackup', 'backup' or 'patchmode' option is set, need a backup.
3686 * When 'patchmode' is set also make a backup when appending.
3687 *
3688 * Do not make any backup, if 'writebackup' and 'backup' are both switched
3689 * off. This helps when editing large files on almost-full disks.
3690 */
3691 if (!(append && *p_pm == NUL) && !filtering && perm >= 0 && dobackup)
3692 {
3693#if defined(UNIX) || defined(WIN32)
Bram Moolenaar8767f522016-07-01 17:17:39 +02003694 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003695#endif
3696
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003697 if ((bkc & BKC_YES) || append) /* "yes" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003698 backup_copy = TRUE;
3699#if defined(UNIX) || defined(WIN32)
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003700 else if ((bkc & BKC_AUTO)) /* "auto" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003701 {
3702 int i;
3703
3704# ifdef UNIX
3705 /*
3706 * Don't rename the file when:
3707 * - it's a hard link
3708 * - it's a symbolic link
3709 * - we don't have write permission in the directory
3710 * - we can't set the owner/group of the new file
3711 */
3712 if (st_old.st_nlink > 1
3713 || mch_lstat((char *)fname, &st) < 0
3714 || st.st_dev != st_old.st_dev
Bram Moolenaara5792f52005-11-23 21:25:05 +00003715 || st.st_ino != st_old.st_ino
3716# ifndef HAVE_FCHOWN
3717 || st.st_uid != st_old.st_uid
3718 || st.st_gid != st_old.st_gid
3719# endif
3720 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003721 backup_copy = TRUE;
3722 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003723# else
3724# ifdef WIN32
3725 /* On NTFS file systems hard links are possible. */
3726 if (mch_is_linked(fname))
3727 backup_copy = TRUE;
3728 else
3729# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003730# endif
3731 {
3732 /*
3733 * Check if we can create a file and set the owner/group to
3734 * the ones from the original file.
3735 * First find a file name that doesn't exist yet (use some
3736 * arbitrary numbers).
3737 */
3738 STRCPY(IObuff, fname);
3739 for (i = 4913; ; i += 123)
3740 {
3741 sprintf((char *)gettail(IObuff), "%d", i);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003742 if (mch_lstat((char *)IObuff, &st) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003743 break;
3744 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00003745 fd = mch_open((char *)IObuff,
3746 O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003747 if (fd < 0) /* can't write in directory */
3748 backup_copy = TRUE;
3749 else
3750 {
3751# ifdef UNIX
Bram Moolenaara5792f52005-11-23 21:25:05 +00003752# ifdef HAVE_FCHOWN
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00003753 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003754# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003755 if (mch_stat((char *)IObuff, &st) < 0
3756 || st.st_uid != st_old.st_uid
3757 || st.st_gid != st_old.st_gid
Bram Moolenaar78a15312009-05-15 19:33:18 +00003758 || (long)st.st_mode != perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003759 backup_copy = TRUE;
3760# endif
Bram Moolenaar98358622005-11-28 22:58:23 +00003761 /* Close the file before removing it, on MS-Windows we
3762 * can't delete an open file. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003763 close(fd);
Bram Moolenaar98358622005-11-28 22:58:23 +00003764 mch_remove(IObuff);
Bram Moolenaar3479c5d2010-08-08 18:46:06 +02003765# ifdef MSWIN
3766 /* MS-Windows may trigger a virus scanner to open the
3767 * file, we can't delete it then. Keep trying for half a
3768 * second. */
3769 {
3770 int try;
3771
3772 for (try = 0; try < 10; ++try)
3773 {
3774 if (mch_lstat((char *)IObuff, &st) < 0)
3775 break;
3776 ui_delay(50L, TRUE); /* wait 50 msec */
3777 mch_remove(IObuff);
3778 }
3779 }
3780# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003781 }
3782 }
3783 }
3784
Bram Moolenaar071d4272004-06-13 20:20:40 +00003785 /*
3786 * Break symlinks and/or hardlinks if we've been asked to.
3787 */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003788 if ((bkc & BKC_BREAKSYMLINK) || (bkc & BKC_BREAKHARDLINK))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003789 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003790# ifdef UNIX
Bram Moolenaar071d4272004-06-13 20:20:40 +00003791 int lstat_res;
3792
3793 lstat_res = mch_lstat((char *)fname, &st);
3794
3795 /* Symlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003796 if ((bkc & BKC_BREAKSYMLINK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003797 && lstat_res == 0
3798 && st.st_ino != st_old.st_ino)
3799 backup_copy = FALSE;
3800
3801 /* Hardlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003802 if ((bkc & BKC_BREAKHARDLINK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003803 && st_old.st_nlink > 1
3804 && (lstat_res != 0 || st.st_ino == st_old.st_ino))
3805 backup_copy = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003806# else
3807# if defined(WIN32)
3808 /* Symlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003809 if ((bkc & BKC_BREAKSYMLINK) && mch_is_symbolic_link(fname))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003810 backup_copy = FALSE;
3811
3812 /* Hardlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003813 if ((bkc & BKC_BREAKHARDLINK) && mch_is_hard_link(fname))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003814 backup_copy = FALSE;
3815# endif
3816# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003817 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003818
3819#endif
3820
3821 /* make sure we have a valid backup extension to use */
3822 if (*p_bex == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003823 backup_ext = (char_u *)".bak";
Bram Moolenaar071d4272004-06-13 20:20:40 +00003824 else
3825 backup_ext = p_bex;
3826
3827 if (backup_copy
3828 && (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) >= 0)
3829 {
3830 int bfd;
3831 char_u *copybuf, *wp;
3832 int some_error = FALSE;
Bram Moolenaar8767f522016-07-01 17:17:39 +02003833 stat_T st_new;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003834 char_u *dirp;
3835 char_u *rootname;
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003836#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003837 int did_set_shortname;
Bram Moolenaarcd142e32017-11-16 17:03:45 +01003838 mode_t umask_save;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003839#endif
3840
3841 copybuf = alloc(BUFSIZE + 1);
3842 if (copybuf == NULL)
3843 {
3844 some_error = TRUE; /* out of memory */
3845 goto nobackup;
3846 }
3847
3848 /*
3849 * Try to make the backup in each directory in the 'bdir' option.
3850 *
3851 * Unix semantics has it, that we may have a writable file,
3852 * that cannot be recreated with a simple open(..., O_CREAT, ) e.g:
3853 * - the directory is not writable,
3854 * - the file may be a symbolic link,
3855 * - the file may belong to another user/group, etc.
3856 *
3857 * For these reasons, the existing writable file must be truncated
3858 * and reused. Creation of a backup COPY will be attempted.
3859 */
3860 dirp = p_bdir;
3861 while (*dirp)
3862 {
3863#ifdef UNIX
3864 st_new.st_ino = 0;
3865 st_new.st_dev = 0;
3866 st_new.st_gid = 0;
3867#endif
3868
3869 /*
3870 * Isolate one directory name, using an entry in 'bdir'.
3871 */
3872 (void)copy_option_part(&dirp, copybuf, BUFSIZE, ",");
3873 rootname = get_file_in_dir(fname, copybuf);
3874 if (rootname == NULL)
3875 {
3876 some_error = TRUE; /* out of memory */
3877 goto nobackup;
3878 }
3879
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003880#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003881 did_set_shortname = FALSE;
3882#endif
3883
3884 /*
3885 * May try twice if 'shortname' not set.
3886 */
3887 for (;;)
3888 {
3889 /*
3890 * Make backup file name.
3891 */
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003892 backup = buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003893 rootname, backup_ext, FALSE);
3894 if (backup == NULL)
3895 {
3896 vim_free(rootname);
3897 some_error = TRUE; /* out of memory */
3898 goto nobackup;
3899 }
3900
3901 /*
3902 * Check if backup file already exists.
3903 */
3904 if (mch_stat((char *)backup, &st_new) >= 0)
3905 {
3906#ifdef UNIX
3907 /*
3908 * Check if backup file is same as original file.
3909 * May happen when modname() gave the same file back.
3910 * E.g. silly link, or file name-length reached.
3911 * If we don't check here, we either ruin the file
3912 * when copying or erase it after writing. jw.
3913 */
3914 if (st_new.st_dev == st_old.st_dev
3915 && st_new.st_ino == st_old.st_ino)
3916 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01003917 VIM_CLEAR(backup); /* no backup file to delete */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003918 /*
3919 * may try again with 'shortname' set
3920 */
3921 if (!(buf->b_shortname || buf->b_p_sn))
3922 {
3923 buf->b_shortname = TRUE;
3924 did_set_shortname = TRUE;
3925 continue;
3926 }
3927 /* setting shortname didn't help */
3928 if (did_set_shortname)
3929 buf->b_shortname = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003930 break;
3931 }
3932#endif
3933
3934 /*
3935 * If we are not going to keep the backup file, don't
3936 * delete an existing one, try to use another name.
3937 * Change one character, just before the extension.
3938 */
3939 if (!p_bk)
3940 {
3941 wp = backup + STRLEN(backup) - 1
3942 - STRLEN(backup_ext);
3943 if (wp < backup) /* empty file name ??? */
3944 wp = backup;
3945 *wp = 'z';
3946 while (*wp > 'a'
3947 && mch_stat((char *)backup, &st_new) >= 0)
3948 --*wp;
3949 /* They all exist??? Must be something wrong. */
3950 if (*wp == 'a')
Bram Moolenaard23a8232018-02-10 18:45:26 +01003951 VIM_CLEAR(backup);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003952 }
3953 }
3954 break;
3955 }
3956 vim_free(rootname);
3957
3958 /*
3959 * Try to create the backup file
3960 */
3961 if (backup != NULL)
3962 {
3963 /* remove old backup, if present */
3964 mch_remove(backup);
3965 /* Open with O_EXCL to avoid the file being created while
Bram Moolenaarcd142e32017-11-16 17:03:45 +01003966 * we were sleeping (symlink hacker attack?). Reset umask
3967 * if possible to avoid mch_setperm() below. */
3968#ifdef UNIX
3969 umask_save = umask(0);
3970#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003971 bfd = mch_open((char *)backup,
Bram Moolenaara5792f52005-11-23 21:25:05 +00003972 O_WRONLY|O_CREAT|O_EXTRA|O_EXCL|O_NOFOLLOW,
3973 perm & 0777);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01003974#ifdef UNIX
3975 (void)umask(umask_save);
3976#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003977 if (bfd < 0)
Bram Moolenaard23a8232018-02-10 18:45:26 +01003978 VIM_CLEAR(backup);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003979 else
3980 {
Bram Moolenaarcd142e32017-11-16 17:03:45 +01003981 /* Set file protection same as original file, but
3982 * strip s-bit. Only needed if umask() wasn't used
3983 * above. */
3984#ifndef UNIX
Bram Moolenaar071d4272004-06-13 20:20:40 +00003985 (void)mch_setperm(backup, perm & 0777);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01003986#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00003987 /*
3988 * Try to set the group of the backup same as the
3989 * original file. If this fails, set the protection
3990 * bits for the group same as the protection bits for
3991 * others.
3992 */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003993 if (st_new.st_gid != st_old.st_gid
Bram Moolenaar071d4272004-06-13 20:20:40 +00003994# ifdef HAVE_FCHOWN /* sequent-ptx lacks fchown() */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003995 && fchown(bfd, (uid_t)-1, st_old.st_gid) != 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00003996# endif
3997 )
3998 mch_setperm(backup,
3999 (perm & 0707) | ((perm & 07) << 3));
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004000# if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004001 mch_copy_sec(fname, backup);
4002# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004003#endif
4004
4005 /*
4006 * copy the file.
4007 */
4008 write_info.bw_fd = bfd;
4009 write_info.bw_buf = copybuf;
4010#ifdef HAS_BW_FLAGS
4011 write_info.bw_flags = FIO_NOCONVERT;
4012#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004013 while ((write_info.bw_len = read_eintr(fd, copybuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004014 BUFSIZE)) > 0)
4015 {
4016 if (buf_write_bytes(&write_info) == FAIL)
4017 {
4018 errmsg = (char_u *)_("E506: Can't write to backup file (add ! to override)");
4019 break;
4020 }
4021 ui_breakcheck();
4022 if (got_int)
4023 {
4024 errmsg = (char_u *)_(e_interr);
4025 break;
4026 }
4027 }
4028
4029 if (close(bfd) < 0 && errmsg == NULL)
4030 errmsg = (char_u *)_("E507: Close error for backup file (add ! to override)");
4031 if (write_info.bw_len < 0)
4032 errmsg = (char_u *)_("E508: Can't read file for backup (add ! to override)");
4033#ifdef UNIX
4034 set_file_time(backup, st_old.st_atime, st_old.st_mtime);
4035#endif
4036#ifdef HAVE_ACL
4037 mch_set_acl(backup, acl);
4038#endif
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004039#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004040 mch_copy_sec(fname, backup);
4041#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004042 break;
4043 }
4044 }
4045 }
4046 nobackup:
4047 close(fd); /* ignore errors for closing read file */
4048 vim_free(copybuf);
4049
4050 if (backup == NULL && errmsg == NULL)
4051 errmsg = (char_u *)_("E509: Cannot create backup file (add ! to override)");
4052 /* ignore errors when forceit is TRUE */
4053 if ((some_error || errmsg != NULL) && !forceit)
4054 {
4055 retval = FAIL;
4056 goto fail;
4057 }
4058 errmsg = NULL;
4059 }
4060 else
4061 {
4062 char_u *dirp;
4063 char_u *p;
4064 char_u *rootname;
4065
4066 /*
4067 * Make a backup by renaming the original file.
4068 */
4069 /*
4070 * If 'cpoptions' includes the "W" flag, we don't want to
4071 * overwrite a read-only file. But rename may be possible
4072 * anyway, thus we need an extra check here.
4073 */
4074 if (file_readonly && vim_strchr(p_cpo, CPO_FWRITE) != NULL)
4075 {
4076 errnum = (char_u *)"E504: ";
4077 errmsg = (char_u *)_(err_readonly);
4078 goto fail;
4079 }
4080
4081 /*
4082 *
4083 * Form the backup file name - change path/fo.o.h to
4084 * path/fo.o.h.bak Try all directories in 'backupdir', first one
4085 * that works is used.
4086 */
4087 dirp = p_bdir;
4088 while (*dirp)
4089 {
4090 /*
4091 * Isolate one directory name and make the backup file name.
4092 */
4093 (void)copy_option_part(&dirp, IObuff, IOSIZE, ",");
4094 rootname = get_file_in_dir(fname, IObuff);
4095 if (rootname == NULL)
4096 backup = NULL;
4097 else
4098 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01004099 backup = buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00004100 rootname, backup_ext, FALSE);
4101 vim_free(rootname);
4102 }
4103
4104 if (backup != NULL)
4105 {
4106 /*
4107 * If we are not going to keep the backup file, don't
4108 * delete an existing one, try to use another name.
4109 * Change one character, just before the extension.
4110 */
4111 if (!p_bk && mch_getperm(backup) >= 0)
4112 {
4113 p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext);
4114 if (p < backup) /* empty file name ??? */
4115 p = backup;
4116 *p = 'z';
4117 while (*p > 'a' && mch_getperm(backup) >= 0)
4118 --*p;
4119 /* They all exist??? Must be something wrong! */
4120 if (*p == 'a')
Bram Moolenaard23a8232018-02-10 18:45:26 +01004121 VIM_CLEAR(backup);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004122 }
4123 }
4124 if (backup != NULL)
4125 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004126 /*
Bram Moolenaarbfd8fc02005-09-20 23:22:24 +00004127 * Delete any existing backup and move the current version
4128 * to the backup. For safety, we don't remove the backup
4129 * until the write has finished successfully. And if the
4130 * 'backup' option is set, leave it around.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004131 */
4132 /*
4133 * If the renaming of the original file to the backup file
4134 * works, quit here.
4135 */
4136 if (vim_rename(fname, backup) == 0)
4137 break;
4138
Bram Moolenaard23a8232018-02-10 18:45:26 +01004139 VIM_CLEAR(backup); /* don't do the rename below */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004140 }
4141 }
4142 if (backup == NULL && !forceit)
4143 {
4144 errmsg = (char_u *)_("E510: Can't make backup file (add ! to override)");
4145 goto fail;
4146 }
4147 }
4148 }
4149
Bram Moolenaar53076832015-12-31 19:53:21 +01004150#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004151 /* When using ":w!" and the file was read-only: make it writable */
4152 if (forceit && perm >= 0 && !(perm & 0200) && st_old.st_uid == getuid()
4153 && vim_strchr(p_cpo, CPO_FWRITE) == NULL)
4154 {
4155 perm |= 0200;
4156 (void)mch_setperm(fname, perm);
4157 made_writable = TRUE;
4158 }
4159#endif
4160
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004161 /* When using ":w!" and writing to the current file, 'readonly' makes no
Bram Moolenaar4399ef42005-02-12 14:29:27 +00004162 * sense, reset it, unless 'Z' appears in 'cpoptions'. */
4163 if (forceit && overwriting && vim_strchr(p_cpo, CPO_KEEPRO) == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004164 {
4165 buf->b_p_ro = FALSE;
4166#ifdef FEAT_TITLE
4167 need_maketitle = TRUE; /* set window title later */
4168#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004169 status_redraw_all(); /* redraw status lines later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004170 }
4171
4172 if (end > buf->b_ml.ml_line_count)
4173 end = buf->b_ml.ml_line_count;
4174 if (buf->b_ml.ml_flags & ML_EMPTY)
4175 start = end + 1;
4176
4177 /*
4178 * If the original file is being overwritten, there is a small chance that
4179 * we crash in the middle of writing. Therefore the file is preserved now.
4180 * This makes all block numbers positive so that recovery does not need
4181 * the original file.
4182 * Don't do this if there is a backup file and we are exiting.
4183 */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004184 if (reset_changed && !newfile && overwriting
Bram Moolenaar071d4272004-06-13 20:20:40 +00004185 && !(exiting && backup != NULL))
4186 {
4187 ml_preserve(buf, FALSE);
4188 if (got_int)
4189 {
4190 errmsg = (char_u *)_(e_interr);
4191 goto restore_backup;
4192 }
4193 }
4194
Bram Moolenaar071d4272004-06-13 20:20:40 +00004195#ifdef VMS
4196 vms_remove_version(fname); /* remove version */
4197#endif
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00004198 /* Default: write the file directly. May write to a temp file for
Bram Moolenaar071d4272004-06-13 20:20:40 +00004199 * multi-byte conversion. */
4200 wfname = fname;
4201
4202#ifdef FEAT_MBYTE
4203 /* Check for forced 'fileencoding' from "++opt=val" argument. */
4204 if (eap != NULL && eap->force_enc != 0)
4205 {
4206 fenc = eap->cmd + eap->force_enc;
4207 fenc = enc_canonize(fenc);
4208 fenc_tofree = fenc;
4209 }
4210 else
4211 fenc = buf->b_p_fenc;
4212
4213 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004214 * Check if the file needs to be converted.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004215 */
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004216 converted = need_conversion(fenc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004217
4218 /*
4219 * Check if UTF-8 to UCS-2/4 or Latin1 conversion needs to be done. Or
4220 * Latin1 to Unicode conversion. This is handled in buf_write_bytes().
4221 * Prepare the flags for it and allocate bw_conv_buf when needed.
4222 */
4223 if (converted && (enc_utf8 || STRCMP(p_enc, "latin1") == 0))
4224 {
4225 wb_flags = get_fio_flags(fenc);
4226 if (wb_flags & (FIO_UCS2 | FIO_UCS4 | FIO_UTF16 | FIO_UTF8))
4227 {
4228 /* Need to allocate a buffer to translate into. */
4229 if (wb_flags & (FIO_UCS2 | FIO_UTF16 | FIO_UTF8))
4230 write_info.bw_conv_buflen = bufsize * 2;
4231 else /* FIO_UCS4 */
4232 write_info.bw_conv_buflen = bufsize * 4;
4233 write_info.bw_conv_buf
4234 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4235 if (write_info.bw_conv_buf == NULL)
4236 end = 0;
4237 }
4238 }
4239
4240# ifdef WIN3264
4241 if (converted && wb_flags == 0 && (wb_flags = get_win_fio_flags(fenc)) != 0)
4242 {
4243 /* Convert UTF-8 -> UCS-2 and UCS-2 -> DBCS. Worst-case * 4: */
4244 write_info.bw_conv_buflen = bufsize * 4;
4245 write_info.bw_conv_buf
4246 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4247 if (write_info.bw_conv_buf == NULL)
4248 end = 0;
4249 }
4250# endif
4251
Bram Moolenaard0573012017-10-28 21:11:06 +02004252# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00004253 if (converted && wb_flags == 0 && (wb_flags = get_mac_fio_flags(fenc)) != 0)
4254 {
4255 write_info.bw_conv_buflen = bufsize * 3;
4256 write_info.bw_conv_buf
4257 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4258 if (write_info.bw_conv_buf == NULL)
4259 end = 0;
4260 }
4261# endif
4262
4263# if defined(FEAT_EVAL) || defined(USE_ICONV)
4264 if (converted && wb_flags == 0)
4265 {
4266# ifdef USE_ICONV
4267 /*
4268 * Use iconv() conversion when conversion is needed and it's not done
4269 * internally.
4270 */
4271 write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc,
4272 enc_utf8 ? (char_u *)"utf-8" : p_enc);
4273 if (write_info.bw_iconv_fd != (iconv_t)-1)
4274 {
4275 /* We're going to use iconv(), allocate a buffer to convert in. */
4276 write_info.bw_conv_buflen = bufsize * ICONV_MULT;
4277 write_info.bw_conv_buf
4278 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4279 if (write_info.bw_conv_buf == NULL)
4280 end = 0;
4281 write_info.bw_first = TRUE;
4282 }
4283# ifdef FEAT_EVAL
4284 else
4285# endif
4286# endif
4287
4288# ifdef FEAT_EVAL
4289 /*
4290 * When the file needs to be converted with 'charconvert' after
4291 * writing, write to a temp file instead and let the conversion
4292 * overwrite the original file.
4293 */
4294 if (*p_ccv != NUL)
4295 {
Bram Moolenaare5c421c2015-03-31 13:33:08 +02004296 wfname = vim_tempname('w', FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004297 if (wfname == NULL) /* Can't write without a tempfile! */
4298 {
4299 errmsg = (char_u *)_("E214: Can't find temp file for writing");
4300 goto restore_backup;
4301 }
4302 }
4303# endif
4304 }
4305# endif
4306 if (converted && wb_flags == 0
4307# ifdef USE_ICONV
4308 && write_info.bw_iconv_fd == (iconv_t)-1
4309# endif
4310# ifdef FEAT_EVAL
4311 && wfname == fname
4312# endif
4313 )
4314 {
4315 if (!forceit)
4316 {
4317 errmsg = (char_u *)_("E213: Cannot convert (add ! to write without conversion)");
4318 goto restore_backup;
4319 }
4320 notconverted = TRUE;
4321 }
4322#endif
4323
4324 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004325 * If conversion is taking place, we may first pretend to write and check
4326 * for conversion errors. Then loop again to write for real.
4327 * When not doing conversion this writes for real right away.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004328 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004329 for (checking_conversion = TRUE; ; checking_conversion = FALSE)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004330 {
4331 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004332 * There is no need to check conversion when:
4333 * - there is no conversion
4334 * - we make a backup file, that can be restored in case of conversion
4335 * failure.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004336 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004337#ifdef FEAT_MBYTE
4338 if (!converted || dobackup)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004339#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004340 checking_conversion = FALSE;
4341
4342 if (checking_conversion)
4343 {
4344 /* Make sure we don't write anything. */
4345 fd = -1;
4346 write_info.bw_fd = fd;
4347 }
4348 else
4349 {
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004350#ifdef HAVE_FTRUNCATE
4351# define TRUNC_ON_OPEN 0
4352#else
4353# define TRUNC_ON_OPEN O_TRUNC
4354#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004355 /*
4356 * Open the file "wfname" for writing.
4357 * We may try to open the file twice: If we can't write to the file
4358 * and forceit is TRUE we delete the existing file and try to
4359 * create a new one. If this still fails we may have lost the
4360 * original file! (this may happen when the user reached his
4361 * quotum for number of files).
4362 * Appending will fail if the file does not exist and forceit is
4363 * FALSE.
4364 */
4365 while ((fd = mch_open((char *)wfname, O_WRONLY | O_EXTRA | (append
4366 ? (forceit ? (O_APPEND | O_CREAT) : O_APPEND)
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004367 : (O_CREAT | TRUNC_ON_OPEN))
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004368 , perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004369 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004370 /*
4371 * A forced write will try to create a new file if the old one
4372 * is still readonly. This may also happen when the directory
4373 * is read-only. In that case the mch_remove() will fail.
4374 */
4375 if (errmsg == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004376 {
4377#ifdef UNIX
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004378 stat_T st;
4379
4380 /* Don't delete the file when it's a hard or symbolic link.
4381 */
4382 if ((!newfile && st_old.st_nlink > 1)
4383 || (mch_lstat((char *)fname, &st) == 0
4384 && (st.st_dev != st_old.st_dev
4385 || st.st_ino != st_old.st_ino)))
4386 errmsg = (char_u *)_("E166: Can't open linked file for writing");
4387 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004388#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004389 {
4390 errmsg = (char_u *)_("E212: Can't open file for writing");
4391 if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL
4392 && perm >= 0)
4393 {
4394#ifdef UNIX
4395 /* we write to the file, thus it should be marked
4396 writable after all */
4397 if (!(perm & 0200))
4398 made_writable = TRUE;
4399 perm |= 0200;
4400 if (st_old.st_uid != getuid()
4401 || st_old.st_gid != getgid())
4402 perm &= 0777;
4403#endif
4404 if (!append) /* don't remove when appending */
4405 mch_remove(wfname);
4406 continue;
4407 }
4408 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004409 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004410
4411restore_backup:
Bram Moolenaar071d4272004-06-13 20:20:40 +00004412 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004413 stat_T st;
4414
Bram Moolenaar071d4272004-06-13 20:20:40 +00004415 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004416 * If we failed to open the file, we don't need a backup.
4417 * Throw it away. If we moved or removed the original file
4418 * try to put the backup in its place.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004419 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004420 if (backup != NULL && wfname == fname)
4421 {
4422 if (backup_copy)
4423 {
4424 /*
4425 * There is a small chance that we removed the
4426 * original, try to move the copy in its place.
4427 * This may not work if the vim_rename() fails.
4428 * In that case we leave the copy around.
4429 */
4430 /* If file does not exist, put the copy in its
4431 * place */
4432 if (mch_stat((char *)fname, &st) < 0)
4433 vim_rename(backup, fname);
4434 /* if original file does exist throw away the copy
4435 */
4436 if (mch_stat((char *)fname, &st) >= 0)
4437 mch_remove(backup);
4438 }
4439 else
4440 {
4441 /* try to put the original file back */
4442 vim_rename(backup, fname);
4443 }
4444 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004445
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004446 /* if original file no longer exists give an extra warning
4447 */
4448 if (!newfile && mch_stat((char *)fname, &st) < 0)
4449 end = 0;
4450 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004451
4452#ifdef FEAT_MBYTE
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004453 if (wfname != fname)
4454 vim_free(wfname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004455#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004456 goto fail;
4457 }
4458 write_info.bw_fd = fd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004459
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004460#if defined(UNIX)
4461 {
4462 stat_T st;
4463
4464 /* Double check we are writing the intended file before making
4465 * any changes. */
4466 if (overwriting
4467 && (!dobackup || backup_copy)
4468 && fname == wfname
4469 && perm >= 0
4470 && mch_fstat(fd, &st) == 0
4471 && st.st_ino != st_old.st_ino)
4472 {
4473 close(fd);
4474 errmsg = (char_u *)_("E949: File changed while writing");
4475 goto fail;
4476 }
4477 }
4478#endif
4479#ifdef HAVE_FTRUNCATE
4480 if (!append)
Bram Moolenaarae1e1082017-11-17 21:35:24 +01004481 ignored = ftruncate(fd, (off_t)0);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004482#endif
4483
Bram Moolenaard0573012017-10-28 21:11:06 +02004484#if defined(WIN3264)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004485 if (backup != NULL && overwriting && !append)
4486 {
4487 if (backup_copy)
4488 (void)mch_copy_file_attribute(wfname, backup);
4489 else
4490 (void)mch_copy_file_attribute(backup, wfname);
4491 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004492
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004493 if (!overwriting && !append)
4494 {
4495 if (buf->b_ffname != NULL)
4496 (void)mch_copy_file_attribute(buf->b_ffname, wfname);
4497 /* Should copy resource fork */
4498 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004499#endif
4500
Bram Moolenaar071d4272004-06-13 20:20:40 +00004501#ifdef FEAT_CRYPT
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004502 if (*buf->b_p_key != NUL && !filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004503 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004504 char_u *header;
4505 int header_len;
4506
4507 buf->b_cryptstate = crypt_create_for_writing(
4508 crypt_get_method_nr(buf),
4509 buf->b_p_key, &header, &header_len);
4510 if (buf->b_cryptstate == NULL || header == NULL)
4511 end = 0;
4512 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004513 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004514 /* Write magic number, so that Vim knows how this file is
4515 * encrypted when reading it back. */
4516 write_info.bw_buf = header;
4517 write_info.bw_len = header_len;
4518 write_info.bw_flags = FIO_NOCONVERT;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004519 if (buf_write_bytes(&write_info) == FAIL)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004520 end = 0;
4521 wb_flags |= FIO_ENCRYPTED;
4522 vim_free(header);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004523 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004524 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004525#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004526 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004527 errmsg = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004528
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004529 write_info.bw_buf = buffer;
4530 nchars = 0;
4531
4532 /* use "++bin", "++nobin" or 'binary' */
4533 if (eap != NULL && eap->force_bin != 0)
4534 write_bin = (eap->force_bin == FORCE_BIN);
4535 else
4536 write_bin = buf->b_p_bin;
4537
4538#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004539 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004540 * The BOM is written just after the encryption magic number.
4541 * Skip it when appending and the file already existed, the BOM only
4542 * makes sense at the start of the file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004543 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004544 if (buf->b_p_bomb && !write_bin && (!append || perm < 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004545 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004546 write_info.bw_len = make_bom(buffer, fenc);
4547 if (write_info.bw_len > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004548 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004549 /* don't convert, do encryption */
4550 write_info.bw_flags = FIO_NOCONVERT | wb_flags;
4551 if (buf_write_bytes(&write_info) == FAIL)
4552 end = 0;
4553 else
4554 nchars += write_info.bw_len;
4555 }
4556 }
4557 write_info.bw_start_lnum = start;
4558#endif
4559
4560#ifdef FEAT_PERSISTENT_UNDO
4561 write_undo_file = (buf->b_p_udf
4562 && overwriting
4563 && !append
4564 && !filtering
4565 && reset_changed
4566 && !checking_conversion);
4567 if (write_undo_file)
4568 /* Prepare for computing the hash value of the text. */
4569 sha256_start(&sha_ctx);
4570#endif
4571
4572 write_info.bw_len = bufsize;
4573#ifdef HAS_BW_FLAGS
4574 write_info.bw_flags = wb_flags;
4575#endif
4576 fileformat = get_fileformat_force(buf, eap);
4577 s = buffer;
4578 len = 0;
4579 for (lnum = start; lnum <= end; ++lnum)
4580 {
4581 /*
4582 * The next while loop is done once for each character written.
4583 * Keep it fast!
4584 */
4585 ptr = ml_get_buf(buf, lnum, FALSE) - 1;
4586#ifdef FEAT_PERSISTENT_UNDO
4587 if (write_undo_file)
4588 sha256_update(&sha_ctx, ptr + 1,
4589 (UINT32_T)(STRLEN(ptr + 1) + 1));
4590#endif
4591 while ((c = *++ptr) != NUL)
4592 {
4593 if (c == NL)
4594 *s = NUL; /* replace newlines with NULs */
4595 else if (c == CAR && fileformat == EOL_MAC)
4596 *s = NL; /* Mac: replace CRs with NLs */
4597 else
4598 *s = c;
4599 ++s;
4600 if (++len != bufsize)
4601 continue;
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004602 if (buf_write_bytes(&write_info) == FAIL)
4603 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004604 end = 0; /* write error: break loop */
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004605 break;
4606 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004607 nchars += bufsize;
4608 s = buffer;
4609 len = 0;
4610#ifdef FEAT_MBYTE
4611 write_info.bw_start_lnum = lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004612#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004613 }
4614 /* write failed or last line has no EOL: stop here */
4615 if (end == 0
4616 || (lnum == end
4617 && (write_bin || !buf->b_p_fixeol)
4618 && (lnum == buf->b_no_eol_lnum
4619 || (lnum == buf->b_ml.ml_line_count
4620 && !buf->b_p_eol))))
4621 {
4622 ++lnum; /* written the line, count it */
4623 no_eol = TRUE;
4624 break;
4625 }
4626 if (fileformat == EOL_UNIX)
4627 *s++ = NL;
4628 else
4629 {
4630 *s++ = CAR; /* EOL_MAC or EOL_DOS: write CR */
4631 if (fileformat == EOL_DOS) /* write CR-NL */
4632 {
4633 if (++len == bufsize)
4634 {
4635 if (buf_write_bytes(&write_info) == FAIL)
4636 {
4637 end = 0; /* write error: break loop */
4638 break;
4639 }
4640 nchars += bufsize;
4641 s = buffer;
4642 len = 0;
4643 }
4644 *s++ = NL;
4645 }
4646 }
4647 if (++len == bufsize && end)
4648 {
4649 if (buf_write_bytes(&write_info) == FAIL)
4650 {
4651 end = 0; /* write error: break loop */
4652 break;
4653 }
4654 nchars += bufsize;
4655 s = buffer;
4656 len = 0;
4657
4658 ui_breakcheck();
4659 if (got_int)
4660 {
4661 end = 0; /* Interrupted, break loop */
4662 break;
4663 }
4664 }
4665#ifdef VMS
4666 /*
4667 * On VMS there is a problem: newlines get added when writing
4668 * blocks at a time. Fix it by writing a line at a time.
4669 * This is much slower!
4670 * Explanation: VAX/DECC RTL insists that records in some RMS
4671 * structures end with a newline (carriage return) character, and
4672 * if they don't it adds one.
4673 * With other RMS structures it works perfect without this fix.
4674 */
4675 if (buf->b_fab_rfm == FAB$C_VFC
4676 || ((buf->b_fab_rat & (FAB$M_FTN | FAB$M_CR)) != 0))
4677 {
4678 int b2write;
4679
4680 buf->b_fab_mrs = (buf->b_fab_mrs == 0
4681 ? MIN(4096, bufsize)
4682 : MIN(buf->b_fab_mrs, bufsize));
4683
4684 b2write = len;
4685 while (b2write > 0)
4686 {
4687 write_info.bw_len = MIN(b2write, buf->b_fab_mrs);
4688 if (buf_write_bytes(&write_info) == FAIL)
4689 {
4690 end = 0;
4691 break;
4692 }
4693 b2write -= MIN(b2write, buf->b_fab_mrs);
4694 }
4695 write_info.bw_len = bufsize;
4696 nchars += len;
4697 s = buffer;
4698 len = 0;
4699 }
4700#endif
4701 }
4702 if (len > 0 && end > 0)
4703 {
4704 write_info.bw_len = len;
4705 if (buf_write_bytes(&write_info) == FAIL)
4706 end = 0; /* write error */
4707 nchars += len;
4708 }
4709
4710 /* Stop when writing done or an error was encountered. */
4711 if (!checking_conversion || end == 0)
4712 break;
4713
4714 /* If no error happened until now, writing should be ok, so loop to
4715 * really write the buffer. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004716 }
4717
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004718 /* If we started writing, finish writing. Also when an error was
4719 * encountered. */
4720 if (!checking_conversion)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004721 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004722#if defined(UNIX) && defined(HAVE_FSYNC)
4723 /*
4724 * On many journalling file systems there is a bug that causes both the
4725 * original and the backup file to be lost when halting the system
4726 * right after writing the file. That's because only the meta-data is
4727 * journalled. Syncing the file slows down the system, but assures it
4728 * has been written to disk and we don't lose it.
4729 * For a device do try the fsync() but don't complain if it does not
4730 * work (could be a pipe).
4731 * If the 'fsync' option is FALSE, don't fsync(). Useful for laptops.
4732 */
4733 if (p_fs && fsync(fd) != 0 && !device)
4734 {
Bram Moolenaar7567d0b2017-11-16 23:04:15 +01004735 errmsg = (char_u *)_(e_fsync);
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004736 end = 0;
4737 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004738#endif
4739
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004740#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004741 /* Probably need to set the security context. */
4742 if (!backup_copy)
4743 mch_copy_sec(backup, wfname);
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004744#endif
4745
Bram Moolenaara5792f52005-11-23 21:25:05 +00004746#ifdef UNIX
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004747 /* When creating a new file, set its owner/group to that of the
4748 * original file. Get the new device and inode number. */
4749 if (backup != NULL && !backup_copy)
Bram Moolenaara5792f52005-11-23 21:25:05 +00004750 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004751# ifdef HAVE_FCHOWN
4752 stat_T st;
4753
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004754 /* Don't change the owner when it's already OK, some systems remove
4755 * permission or ACL stuff. */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004756 if (mch_stat((char *)wfname, &st) < 0
4757 || st.st_uid != st_old.st_uid
4758 || st.st_gid != st_old.st_gid)
4759 {
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004760 /* changing owner might not be possible */
4761 ignored = fchown(fd, st_old.st_uid, -1);
4762 /* if changing group fails clear the group permissions */
4763 if (fchown(fd, -1, st_old.st_gid) == -1 && perm > 0)
4764 perm &= ~070;
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004765 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00004766# endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004767 buf_setino(buf);
4768 }
4769 else if (!buf->b_dev_valid)
4770 /* Set the inode when creating a new file. */
4771 buf_setino(buf);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004772#endif
4773
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004774#ifdef UNIX
4775 if (made_writable)
4776 perm &= ~0200; /* reset 'w' bit for security reasons */
4777#endif
4778#ifdef HAVE_FCHMOD
4779 /* set permission of new file same as old file */
4780 if (perm >= 0)
4781 (void)mch_fsetperm(fd, perm);
4782#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004783 if (close(fd) != 0)
4784 {
4785 errmsg = (char_u *)_("E512: Close failed");
4786 end = 0;
4787 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004788
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004789#ifndef HAVE_FCHMOD
4790 /* set permission of new file same as old file */
4791 if (perm >= 0)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004792 (void)mch_setperm(wfname, perm);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004793#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004794#ifdef HAVE_ACL
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004795 /*
4796 * Probably need to set the ACL before changing the user (can't set the
4797 * ACL on a file the user doesn't own).
4798 * On Solaris, with ZFS and the aclmode property set to "discard" (the
4799 * default), chmod() discards all part of a file's ACL that don't
4800 * represent the mode of the file. It's non-trivial for us to discover
4801 * whether we're in that situation, so we simply always re-set the ACL.
4802 */
Bram Moolenaarda412772016-07-14 20:37:07 +02004803# ifndef HAVE_SOLARIS_ZFS_ACL
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004804 if (!backup_copy)
Bram Moolenaarda412772016-07-14 20:37:07 +02004805# endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004806 mch_set_acl(wfname, acl);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004807#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004808#ifdef FEAT_CRYPT
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004809 if (buf->b_cryptstate != NULL)
4810 {
4811 crypt_free_state(buf->b_cryptstate);
4812 buf->b_cryptstate = NULL;
4813 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004814#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004815
Bram Moolenaar071d4272004-06-13 20:20:40 +00004816#if defined(FEAT_MBYTE) && defined(FEAT_EVAL)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004817 if (wfname != fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004818 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004819 /*
4820 * The file was written to a temp file, now it needs to be
4821 * converted with 'charconvert' to (overwrite) the output file.
4822 */
4823 if (end != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004824 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004825 if (eval_charconvert(enc_utf8 ? (char_u *)"utf-8" : p_enc,
4826 fenc, wfname, fname) == FAIL)
4827 {
4828 write_info.bw_conv_error = TRUE;
4829 end = 0;
4830 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004831 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004832 mch_remove(wfname);
4833 vim_free(wfname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004834 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004835#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004836 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004837
4838 if (end == 0)
4839 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004840 /*
4841 * Error encountered.
4842 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004843 if (errmsg == NULL)
4844 {
4845#ifdef FEAT_MBYTE
4846 if (write_info.bw_conv_error)
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004847 {
4848 if (write_info.bw_conv_error_lnum == 0)
4849 errmsg = (char_u *)_("E513: write error, conversion failed (make 'fenc' empty to override)");
4850 else
4851 {
4852 errmsg_allocated = TRUE;
4853 errmsg = alloc(300);
4854 vim_snprintf((char *)errmsg, 300, _("E513: write error, conversion failed in line %ld (make 'fenc' empty to override)"),
4855 (long)write_info.bw_conv_error_lnum);
4856 }
4857 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004858 else
4859#endif
4860 if (got_int)
4861 errmsg = (char_u *)_(e_interr);
4862 else
4863 errmsg = (char_u *)_("E514: write error (file system full?)");
4864 }
4865
4866 /*
4867 * If we have a backup file, try to put it in place of the new file,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004868 * because the new file is probably corrupt. This avoids losing the
Bram Moolenaar071d4272004-06-13 20:20:40 +00004869 * original file when trying to make a backup when writing the file a
4870 * second time.
4871 * When "backup_copy" is set we need to copy the backup over the new
4872 * file. Otherwise rename the backup file.
4873 * If this is OK, don't give the extra warning message.
4874 */
4875 if (backup != NULL)
4876 {
4877 if (backup_copy)
4878 {
4879 /* This may take a while, if we were interrupted let the user
4880 * know we got the message. */
4881 if (got_int)
4882 {
4883 MSG(_(e_interr));
4884 out_flush();
4885 }
4886 if ((fd = mch_open((char *)backup, O_RDONLY | O_EXTRA, 0)) >= 0)
4887 {
4888 if ((write_info.bw_fd = mch_open((char *)fname,
Bram Moolenaar9be038d2005-03-08 22:34:32 +00004889 O_WRONLY | O_CREAT | O_TRUNC | O_EXTRA,
4890 perm & 0777)) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004891 {
4892 /* copy the file. */
4893 write_info.bw_buf = smallbuf;
4894#ifdef HAS_BW_FLAGS
4895 write_info.bw_flags = FIO_NOCONVERT;
4896#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004897 while ((write_info.bw_len = read_eintr(fd, smallbuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004898 SMBUFSIZE)) > 0)
4899 if (buf_write_bytes(&write_info) == FAIL)
4900 break;
4901
4902 if (close(write_info.bw_fd) >= 0
4903 && write_info.bw_len == 0)
4904 end = 1; /* success */
4905 }
4906 close(fd); /* ignore errors for closing read file */
4907 }
4908 }
4909 else
4910 {
4911 if (vim_rename(backup, fname) == 0)
4912 end = 1;
4913 }
4914 }
4915 goto fail;
4916 }
4917
4918 lnum -= start; /* compute number of written lines */
4919 --no_wait_return; /* may wait for return now */
4920
4921#if !(defined(UNIX) || defined(VMS))
4922 fname = sfname; /* use shortname now, for the messages */
4923#endif
4924 if (!filtering)
4925 {
4926 msg_add_fname(buf, fname); /* put fname in IObuff with quotes */
4927 c = FALSE;
4928#ifdef FEAT_MBYTE
4929 if (write_info.bw_conv_error)
4930 {
4931 STRCAT(IObuff, _(" CONVERSION ERROR"));
4932 c = TRUE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004933 if (write_info.bw_conv_error_lnum != 0)
Bram Moolenaara800b422010-06-27 01:15:55 +02004934 vim_snprintf_add((char *)IObuff, IOSIZE, _(" in line %ld;"),
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004935 (long)write_info.bw_conv_error_lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004936 }
4937 else if (notconverted)
4938 {
4939 STRCAT(IObuff, _("[NOT converted]"));
4940 c = TRUE;
4941 }
4942 else if (converted)
4943 {
4944 STRCAT(IObuff, _("[converted]"));
4945 c = TRUE;
4946 }
4947#endif
4948 if (device)
4949 {
4950 STRCAT(IObuff, _("[Device]"));
4951 c = TRUE;
4952 }
4953 else if (newfile)
4954 {
4955 STRCAT(IObuff, shortmess(SHM_NEW) ? _("[New]") : _("[New File]"));
4956 c = TRUE;
4957 }
4958 if (no_eol)
4959 {
4960 msg_add_eol();
4961 c = TRUE;
4962 }
4963 /* may add [unix/dos/mac] */
4964 if (msg_add_fileformat(fileformat))
4965 c = TRUE;
4966#ifdef FEAT_CRYPT
4967 if (wb_flags & FIO_ENCRYPTED)
4968 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004969 crypt_append_msg(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004970 c = TRUE;
4971 }
4972#endif
4973 msg_add_lines(c, (long)lnum, nchars); /* add line/char count */
4974 if (!shortmess(SHM_WRITE))
4975 {
4976 if (append)
4977 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended"));
4978 else
4979 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written"));
4980 }
4981
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00004982 set_keep_msg(msg_trunc_attr(IObuff, FALSE, 0), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004983 }
4984
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004985 /* When written everything correctly: reset 'modified'. Unless not
4986 * writing to the original file and '+' is not in 'cpoptions'. */
Bram Moolenaar292ad192005-12-11 21:29:51 +00004987 if (reset_changed && whole && !append
Bram Moolenaar071d4272004-06-13 20:20:40 +00004988#ifdef FEAT_MBYTE
4989 && !write_info.bw_conv_error
4990#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004991 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL)
4992 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004993 {
4994 unchanged(buf, TRUE);
Bram Moolenaar95c526e2017-02-25 14:59:34 +01004995 /* b:changedtick is always incremented in unchanged() but that
Bram Moolenaar086329d2014-10-31 19:51:36 +01004996 * should not trigger a TextChanged event. */
Bram Moolenaar5a093432018-02-10 18:15:19 +01004997 if (buf->b_last_changedtick + 1 == CHANGEDTICK(buf))
4998 buf->b_last_changedtick = CHANGEDTICK(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004999 u_unchanged(buf);
Bram Moolenaar730cde92010-06-27 05:18:54 +02005000 u_update_save_nr(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005001 }
5002
5003 /*
5004 * If written to the current file, update the timestamp of the swap file
5005 * and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
5006 */
5007 if (overwriting)
5008 {
5009 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00005010 if (append)
5011 buf->b_flags &= ~BF_NEW;
5012 else
5013 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005014 }
5015
5016 /*
5017 * If we kept a backup until now, and we are in patch mode, then we make
5018 * the backup file our 'original' file.
5019 */
5020 if (*p_pm && dobackup)
5021 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01005022 char *org = (char *)buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005023 fname, p_pm, FALSE);
5024
5025 if (backup != NULL)
5026 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02005027 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005028
5029 /*
5030 * If the original file does not exist yet
5031 * the current backup file becomes the original file
5032 */
5033 if (org == NULL)
5034 EMSG(_("E205: Patchmode: can't save original file"));
5035 else if (mch_stat(org, &st) < 0)
5036 {
5037 vim_rename(backup, (char_u *)org);
Bram Moolenaard23a8232018-02-10 18:45:26 +01005038 VIM_CLEAR(backup); /* don't delete the file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005039#ifdef UNIX
5040 set_file_time((char_u *)org, st_old.st_atime, st_old.st_mtime);
5041#endif
5042 }
5043 }
5044 /*
5045 * If there is no backup file, remember that a (new) file was
5046 * created.
5047 */
5048 else
5049 {
5050 int empty_fd;
5051
5052 if (org == NULL
Bram Moolenaara5792f52005-11-23 21:25:05 +00005053 || (empty_fd = mch_open(org,
5054 O_CREAT | O_EXTRA | O_EXCL | O_NOFOLLOW,
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00005055 perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005056 EMSG(_("E206: patchmode: can't touch empty original file"));
5057 else
5058 close(empty_fd);
5059 }
5060 if (org != NULL)
5061 {
5062 mch_setperm((char_u *)org, mch_getperm(fname) & 0777);
5063 vim_free(org);
5064 }
5065 }
5066
5067 /*
5068 * Remove the backup unless 'backup' option is set
5069 */
5070 if (!p_bk && backup != NULL && mch_remove(backup) != 0)
5071 EMSG(_("E207: Can't delete backup file"));
5072
5073#ifdef FEAT_SUN_WORKSHOP
5074 if (usingSunWorkShop)
5075 workshop_file_saved((char *) ffname);
5076#endif
5077
5078 goto nofail;
5079
5080 /*
5081 * Finish up. We get here either after failure or success.
5082 */
5083fail:
5084 --no_wait_return; /* may wait for return now */
5085nofail:
5086
5087 /* Done saving, we accept changed buffer warnings again */
5088 buf->b_saving = FALSE;
5089
5090 vim_free(backup);
5091 if (buffer != smallbuf)
5092 vim_free(buffer);
5093#ifdef FEAT_MBYTE
5094 vim_free(fenc_tofree);
5095 vim_free(write_info.bw_conv_buf);
5096# ifdef USE_ICONV
5097 if (write_info.bw_iconv_fd != (iconv_t)-1)
5098 {
5099 iconv_close(write_info.bw_iconv_fd);
5100 write_info.bw_iconv_fd = (iconv_t)-1;
5101 }
5102# endif
5103#endif
5104#ifdef HAVE_ACL
5105 mch_free_acl(acl);
5106#endif
5107
5108 if (errmsg != NULL)
5109 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005110 int numlen = errnum != NULL ? (int)STRLEN(errnum) : 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005111
Bram Moolenaar8820b482017-03-16 17:23:31 +01005112 attr = HL_ATTR(HLF_E); /* set highlight for error messages */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005113 msg_add_fname(buf,
5114#ifndef UNIX
5115 sfname
5116#else
5117 fname
5118#endif
5119 ); /* put file name in IObuff with quotes */
5120 if (STRLEN(IObuff) + STRLEN(errmsg) + numlen >= IOSIZE)
5121 IObuff[IOSIZE - STRLEN(errmsg) - numlen - 1] = NUL;
5122 /* If the error message has the form "is ...", put the error number in
5123 * front of the file name. */
5124 if (errnum != NULL)
5125 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00005126 STRMOVE(IObuff + numlen, IObuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005127 mch_memmove(IObuff, errnum, (size_t)numlen);
5128 }
5129 STRCAT(IObuff, errmsg);
5130 emsg(IObuff);
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005131 if (errmsg_allocated)
5132 vim_free(errmsg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005133
5134 retval = FAIL;
5135 if (end == 0)
5136 {
5137 MSG_PUTS_ATTR(_("\nWARNING: Original file may be lost or damaged\n"),
5138 attr | MSG_HIST);
5139 MSG_PUTS_ATTR(_("don't quit the editor until the file is successfully written!"),
5140 attr | MSG_HIST);
5141
5142 /* Update the timestamp to avoid an "overwrite changed file"
5143 * prompt when writing again. */
5144 if (mch_stat((char *)fname, &st_old) >= 0)
5145 {
5146 buf_store_time(buf, &st_old, fname);
5147 buf->b_mtime_read = buf->b_mtime;
5148 }
5149 }
5150 }
5151 msg_scroll = msg_save;
5152
Bram Moolenaar55debbe2010-05-23 23:34:36 +02005153#ifdef FEAT_PERSISTENT_UNDO
5154 /*
5155 * When writing the whole file and 'undofile' is set, also write the undo
5156 * file.
5157 */
5158 if (retval == OK && write_undo_file)
5159 {
5160 char_u hash[UNDO_HASH_SIZE];
5161
5162 sha256_finish(&sha_ctx, hash);
5163 u_write_undo(NULL, FALSE, buf, hash);
5164 }
5165#endif
5166
Bram Moolenaar071d4272004-06-13 20:20:40 +00005167#ifdef FEAT_EVAL
5168 if (!should_abort(retval))
5169#else
5170 if (!got_int)
5171#endif
5172 {
5173 aco_save_T aco;
5174
Bram Moolenaar68a33fc2012-04-25 16:50:48 +02005175 curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */
5176
Bram Moolenaar071d4272004-06-13 20:20:40 +00005177 /*
5178 * Apply POST autocommands.
5179 * Careful: The autocommands may call buf_write() recursively!
5180 */
5181 aucmd_prepbuf(&aco, buf);
5182
5183 if (append)
5184 apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname,
5185 FALSE, curbuf, eap);
5186 else if (filtering)
5187 apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname,
5188 FALSE, curbuf, eap);
5189 else if (reset_changed && whole)
5190 apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname,
5191 FALSE, curbuf, eap);
5192 else
5193 apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname,
5194 FALSE, curbuf, eap);
5195
5196 /* restore curwin/curbuf and a few other things */
5197 aucmd_restbuf(&aco);
5198
5199#ifdef FEAT_EVAL
5200 if (aborting()) /* autocmds may abort script processing */
5201 retval = FALSE;
5202#endif
5203 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005204
5205 got_int |= prev_got_int;
5206
Bram Moolenaar071d4272004-06-13 20:20:40 +00005207 return retval;
5208}
5209
5210/*
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005211 * Set the name of the current buffer. Use when the buffer doesn't have a
5212 * name and a ":r" or ":w" command with a file name is used.
5213 */
5214 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005215set_rw_fname(char_u *fname, char_u *sfname)
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005216{
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005217 buf_T *buf = curbuf;
5218
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005219 /* It's like the unnamed buffer is deleted.... */
5220 if (curbuf->b_p_bl)
5221 apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
5222 apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf);
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01005223#ifdef FEAT_EVAL
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005224 if (aborting()) /* autocmds may abort script processing */
5225 return FAIL;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01005226#endif
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005227 if (curbuf != buf)
5228 {
5229 /* We are in another buffer now, don't do the renaming. */
5230 EMSG(_(e_auchangedbuf));
5231 return FAIL;
5232 }
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005233
5234 if (setfname(curbuf, fname, sfname, FALSE) == OK)
5235 curbuf->b_flags |= BF_NOTEDITED;
5236
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005237 /* ....and a new named one is created */
5238 apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, curbuf);
5239 if (curbuf->b_p_bl)
5240 apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf);
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01005241#ifdef FEAT_EVAL
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005242 if (aborting()) /* autocmds may abort script processing */
5243 return FAIL;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01005244#endif
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005245
5246 /* Do filetype detection now if 'filetype' is empty. */
5247 if (*curbuf->b_p_ft == NUL)
5248 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005249 if (au_has_group((char_u *)"filetypedetect"))
Bram Moolenaar1610d052016-06-09 22:53:01 +02005250 (void)do_doautocmd((char_u *)"filetypedetect BufRead", FALSE, NULL);
Bram Moolenaara3227e22006-03-08 21:32:40 +00005251 do_modelines(0);
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005252 }
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005253
5254 return OK;
5255}
5256
5257/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00005258 * Put file name into IObuff with quotes.
5259 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005260 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005261msg_add_fname(buf_T *buf, char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005262{
5263 if (fname == NULL)
5264 fname = (char_u *)"-stdin-";
5265 home_replace(buf, fname, IObuff + 1, IOSIZE - 4, TRUE);
5266 IObuff[0] = '"';
5267 STRCAT(IObuff, "\" ");
5268}
5269
5270/*
5271 * Append message for text mode to IObuff.
5272 * Return TRUE if something appended.
5273 */
5274 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005275msg_add_fileformat(int eol_type)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005276{
5277#ifndef USE_CRNL
5278 if (eol_type == EOL_DOS)
5279 {
5280 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[dos]") : _("[dos format]"));
5281 return TRUE;
5282 }
5283#endif
5284#ifndef USE_CR
5285 if (eol_type == EOL_MAC)
5286 {
5287 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[mac]") : _("[mac format]"));
5288 return TRUE;
5289 }
5290#endif
5291#if defined(USE_CRNL) || defined(USE_CR)
5292 if (eol_type == EOL_UNIX)
5293 {
5294 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[unix]") : _("[unix format]"));
5295 return TRUE;
5296 }
5297#endif
5298 return FALSE;
5299}
5300
5301/*
5302 * Append line and character count to IObuff.
5303 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005304 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005305msg_add_lines(
5306 int insert_space,
5307 long lnum,
Bram Moolenaar8767f522016-07-01 17:17:39 +02005308 off_T nchars)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005309{
5310 char_u *p;
5311
5312 p = IObuff + STRLEN(IObuff);
5313
5314 if (insert_space)
5315 *p++ = ' ';
5316 if (shortmess(SHM_LINES))
Bram Moolenaarbde98102016-07-01 20:03:42 +02005317 vim_snprintf((char *)p, IOSIZE - (p - IObuff),
5318 "%ldL, %lldC", lnum, (varnumber_T)nchars);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005319 else
5320 {
5321 if (lnum == 1)
5322 STRCPY(p, _("1 line, "));
5323 else
5324 sprintf((char *)p, _("%ld lines, "), lnum);
5325 p += STRLEN(p);
5326 if (nchars == 1)
5327 STRCPY(p, _("1 character"));
5328 else
Bram Moolenaarbde98102016-07-01 20:03:42 +02005329 vim_snprintf((char *)p, IOSIZE - (p - IObuff),
5330 _("%lld characters"), (varnumber_T)nchars);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005331 }
5332}
5333
5334/*
5335 * Append message for missing line separator to IObuff.
5336 */
5337 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005338msg_add_eol(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005339{
5340 STRCAT(IObuff, shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]"));
5341}
5342
5343/*
5344 * Check modification time of file, before writing to it.
5345 * The size isn't checked, because using a tool like "gzip" takes care of
5346 * using the same timestamp but can't set the size.
5347 */
5348 static int
Bram Moolenaar8767f522016-07-01 17:17:39 +02005349check_mtime(buf_T *buf, stat_T *st)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005350{
5351 if (buf->b_mtime_read != 0
5352 && time_differs((long)st->st_mtime, buf->b_mtime_read))
5353 {
5354 msg_scroll = TRUE; /* don't overwrite messages here */
5355 msg_silent = 0; /* must give this prompt */
5356 /* don't use emsg() here, don't want to flush the buffers */
5357 MSG_ATTR(_("WARNING: The file has been changed since reading it!!!"),
Bram Moolenaar8820b482017-03-16 17:23:31 +01005358 HL_ATTR(HLF_E));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005359 if (ask_yesno((char_u *)_("Do you really want to write to it"),
5360 TRUE) == 'n')
5361 return FAIL;
5362 msg_scroll = FALSE; /* always overwrite the file message now */
5363 }
5364 return OK;
5365}
5366
5367 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005368time_differs(long t1, long t2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005369{
Bram Moolenaar48e330a2016-02-23 14:53:34 +01005370#if defined(__linux__) || defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005371 /* On a FAT filesystem, esp. under Linux, there are only 5 bits to store
5372 * the seconds. Since the roundoff is done when flushing the inode, the
5373 * time may change unexpectedly by one second!!! */
5374 return (t1 - t2 > 1 || t2 - t1 > 1);
5375#else
5376 return (t1 != t2);
5377#endif
5378}
5379
5380/*
5381 * Call write() to write a number of bytes to the file.
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005382 * Handles encryption and 'encoding' conversion.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005383 *
5384 * Return FAIL for failure, OK otherwise.
5385 */
5386 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005387buf_write_bytes(struct bw_info *ip)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005388{
5389 int wlen;
5390 char_u *buf = ip->bw_buf; /* data to write */
5391 int len = ip->bw_len; /* length of data */
5392#ifdef HAS_BW_FLAGS
5393 int flags = ip->bw_flags; /* extra flags */
5394#endif
5395
5396#ifdef FEAT_MBYTE
5397 /*
5398 * Skip conversion when writing the crypt magic number or the BOM.
5399 */
5400 if (!(flags & FIO_NOCONVERT))
5401 {
5402 char_u *p;
5403 unsigned c;
5404 int n;
5405
5406 if (flags & FIO_UTF8)
5407 {
5408 /*
5409 * Convert latin1 in the buffer to UTF-8 in the file.
5410 */
5411 p = ip->bw_conv_buf; /* translate to buffer */
5412 for (wlen = 0; wlen < len; ++wlen)
5413 p += utf_char2bytes(buf[wlen], p);
5414 buf = ip->bw_conv_buf;
5415 len = (int)(p - ip->bw_conv_buf);
5416 }
5417 else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1))
5418 {
5419 /*
5420 * Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
5421 * Latin1 chars in the file.
5422 */
5423 if (flags & FIO_LATIN1)
5424 p = buf; /* translate in-place (can only get shorter) */
5425 else
5426 p = ip->bw_conv_buf; /* translate to buffer */
5427 for (wlen = 0; wlen < len; wlen += n)
5428 {
5429 if (wlen == 0 && ip->bw_restlen != 0)
5430 {
5431 int l;
5432
5433 /* Use remainder of previous call. Append the start of
5434 * buf[] to get a full sequence. Might still be too
5435 * short! */
5436 l = CONV_RESTLEN - ip->bw_restlen;
5437 if (l > len)
5438 l = len;
5439 mch_memmove(ip->bw_rest + ip->bw_restlen, buf, (size_t)l);
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005440 n = utf_ptr2len_len(ip->bw_rest, ip->bw_restlen + l);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005441 if (n > ip->bw_restlen + len)
5442 {
5443 /* We have an incomplete byte sequence at the end to
5444 * be written. We can't convert it without the
5445 * remaining bytes. Keep them for the next call. */
5446 if (ip->bw_restlen + len > CONV_RESTLEN)
5447 return FAIL;
5448 ip->bw_restlen += len;
5449 break;
5450 }
5451 if (n > 1)
5452 c = utf_ptr2char(ip->bw_rest);
5453 else
5454 c = ip->bw_rest[0];
5455 if (n >= ip->bw_restlen)
5456 {
5457 n -= ip->bw_restlen;
5458 ip->bw_restlen = 0;
5459 }
5460 else
5461 {
5462 ip->bw_restlen -= n;
5463 mch_memmove(ip->bw_rest, ip->bw_rest + n,
5464 (size_t)ip->bw_restlen);
5465 n = 0;
5466 }
5467 }
5468 else
5469 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005470 n = utf_ptr2len_len(buf + wlen, len - wlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005471 if (n > len - wlen)
5472 {
5473 /* We have an incomplete byte sequence at the end to
5474 * be written. We can't convert it without the
5475 * remaining bytes. Keep them for the next call. */
5476 if (len - wlen > CONV_RESTLEN)
5477 return FAIL;
5478 ip->bw_restlen = len - wlen;
5479 mch_memmove(ip->bw_rest, buf + wlen,
5480 (size_t)ip->bw_restlen);
5481 break;
5482 }
5483 if (n > 1)
5484 c = utf_ptr2char(buf + wlen);
5485 else
5486 c = buf[wlen];
5487 }
5488
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005489 if (ucs2bytes(c, &p, flags) && !ip->bw_conv_error)
5490 {
5491 ip->bw_conv_error = TRUE;
5492 ip->bw_conv_error_lnum = ip->bw_start_lnum;
5493 }
5494 if (c == NL)
5495 ++ip->bw_start_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005496 }
5497 if (flags & FIO_LATIN1)
5498 len = (int)(p - buf);
5499 else
5500 {
5501 buf = ip->bw_conv_buf;
5502 len = (int)(p - ip->bw_conv_buf);
5503 }
5504 }
5505
5506# ifdef WIN3264
5507 else if (flags & FIO_CODEPAGE)
5508 {
5509 /*
5510 * Convert UTF-8 or codepage to UCS-2 and then to MS-Windows
5511 * codepage.
5512 */
5513 char_u *from;
5514 size_t fromlen;
5515 char_u *to;
5516 int u8c;
5517 BOOL bad = FALSE;
5518 int needed;
5519
5520 if (ip->bw_restlen > 0)
5521 {
5522 /* Need to concatenate the remainder of the previous call and
5523 * the bytes of the current call. Use the end of the
5524 * conversion buffer for this. */
5525 fromlen = len + ip->bw_restlen;
5526 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5527 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5528 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5529 }
5530 else
5531 {
5532 from = buf;
5533 fromlen = len;
5534 }
5535
5536 to = ip->bw_conv_buf;
5537 if (enc_utf8)
5538 {
5539 /* Convert from UTF-8 to UCS-2, to the start of the buffer.
5540 * The buffer has been allocated to be big enough. */
5541 while (fromlen > 0)
5542 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005543 n = (int)utf_ptr2len_len(from, (int)fromlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005544 if (n > (int)fromlen) /* incomplete byte sequence */
5545 break;
5546 u8c = utf_ptr2char(from);
5547 *to++ = (u8c & 0xff);
5548 *to++ = (u8c >> 8);
5549 fromlen -= n;
5550 from += n;
5551 }
5552
5553 /* Copy remainder to ip->bw_rest[] to be used for the next
5554 * call. */
5555 if (fromlen > CONV_RESTLEN)
5556 {
5557 /* weird overlong sequence */
5558 ip->bw_conv_error = TRUE;
5559 return FAIL;
5560 }
5561 mch_memmove(ip->bw_rest, from, fromlen);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005562 ip->bw_restlen = (int)fromlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005563 }
5564 else
5565 {
5566 /* Convert from enc_codepage to UCS-2, to the start of the
5567 * buffer. The buffer has been allocated to be big enough. */
5568 ip->bw_restlen = 0;
5569 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005570 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005571 NULL, 0);
5572 if (needed == 0)
5573 {
5574 /* When conversion fails there may be a trailing byte. */
5575 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005576 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen - 1,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005577 NULL, 0);
5578 if (needed == 0)
5579 {
5580 /* Conversion doesn't work. */
5581 ip->bw_conv_error = TRUE;
5582 return FAIL;
5583 }
5584 /* Save the trailing byte for the next call. */
5585 ip->bw_rest[0] = from[fromlen - 1];
5586 ip->bw_restlen = 1;
5587 }
5588 needed = MultiByteToWideChar(enc_codepage, MB_ERR_INVALID_CHARS,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005589 (LPCSTR)from, (int)(fromlen - ip->bw_restlen),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005590 (LPWSTR)to, needed);
5591 if (needed == 0)
5592 {
5593 /* Safety check: Conversion doesn't work. */
5594 ip->bw_conv_error = TRUE;
5595 return FAIL;
5596 }
5597 to += needed * 2;
5598 }
5599
5600 fromlen = to - ip->bw_conv_buf;
5601 buf = to;
5602# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5603 if (FIO_GET_CP(flags) == CP_UTF8)
5604 {
5605 /* Convert from UCS-2 to UTF-8, using the remainder of the
5606 * conversion buffer. Fails when out of space. */
5607 for (from = ip->bw_conv_buf; fromlen > 1; fromlen -= 2)
5608 {
5609 u8c = *from++;
5610 u8c += (*from++ << 8);
5611 to += utf_char2bytes(u8c, to);
5612 if (to + 6 >= ip->bw_conv_buf + ip->bw_conv_buflen)
5613 {
5614 ip->bw_conv_error = TRUE;
5615 return FAIL;
5616 }
5617 }
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005618 len = (int)(to - buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005619 }
5620 else
5621#endif
5622 {
5623 /* Convert from UCS-2 to the codepage, using the remainder of
5624 * the conversion buffer. If the conversion uses the default
5625 * character "0", the data doesn't fit in this encoding, so
5626 * fail. */
5627 len = WideCharToMultiByte(FIO_GET_CP(flags), 0,
5628 (LPCWSTR)ip->bw_conv_buf, (int)fromlen / sizeof(WCHAR),
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005629 (LPSTR)to, (int)(ip->bw_conv_buflen - fromlen), 0,
5630 &bad);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005631 if (bad)
5632 {
5633 ip->bw_conv_error = TRUE;
5634 return FAIL;
5635 }
5636 }
5637 }
5638# endif
5639
Bram Moolenaar56718732006-03-15 22:53:57 +00005640# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00005641 else if (flags & FIO_MACROMAN)
5642 {
5643 /*
5644 * Convert UTF-8 or latin1 to Apple MacRoman.
5645 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005646 char_u *from;
5647 size_t fromlen;
5648
5649 if (ip->bw_restlen > 0)
5650 {
5651 /* Need to concatenate the remainder of the previous call and
5652 * the bytes of the current call. Use the end of the
5653 * conversion buffer for this. */
5654 fromlen = len + ip->bw_restlen;
5655 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5656 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5657 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5658 }
5659 else
5660 {
5661 from = buf;
5662 fromlen = len;
5663 }
5664
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00005665 if (enc2macroman(from, fromlen,
5666 ip->bw_conv_buf, &len, ip->bw_conv_buflen,
5667 ip->bw_rest, &ip->bw_restlen) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005668 {
5669 ip->bw_conv_error = TRUE;
5670 return FAIL;
5671 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005672 buf = ip->bw_conv_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005673 }
5674# endif
5675
5676# ifdef USE_ICONV
5677 if (ip->bw_iconv_fd != (iconv_t)-1)
5678 {
5679 const char *from;
5680 size_t fromlen;
5681 char *to;
5682 size_t tolen;
5683
5684 /* Convert with iconv(). */
5685 if (ip->bw_restlen > 0)
5686 {
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005687 char *fp;
5688
Bram Moolenaar071d4272004-06-13 20:20:40 +00005689 /* Need to concatenate the remainder of the previous call and
5690 * the bytes of the current call. Use the end of the
5691 * conversion buffer for this. */
5692 fromlen = len + ip->bw_restlen;
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005693 fp = (char *)ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5694 mch_memmove(fp, ip->bw_rest, (size_t)ip->bw_restlen);
5695 mch_memmove(fp + ip->bw_restlen, buf, (size_t)len);
5696 from = fp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005697 tolen = ip->bw_conv_buflen - fromlen;
5698 }
5699 else
5700 {
5701 from = (const char *)buf;
5702 fromlen = len;
5703 tolen = ip->bw_conv_buflen;
5704 }
5705 to = (char *)ip->bw_conv_buf;
5706
5707 if (ip->bw_first)
5708 {
5709 size_t save_len = tolen;
5710
5711 /* output the initial shift state sequence */
5712 (void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen);
5713
5714 /* There is a bug in iconv() on Linux (which appears to be
5715 * wide-spread) which sets "to" to NULL and messes up "tolen".
5716 */
5717 if (to == NULL)
5718 {
5719 to = (char *)ip->bw_conv_buf;
5720 tolen = save_len;
5721 }
5722 ip->bw_first = FALSE;
5723 }
5724
5725 /*
5726 * If iconv() has an error or there is not enough room, fail.
5727 */
5728 if ((iconv(ip->bw_iconv_fd, (void *)&from, &fromlen, &to, &tolen)
5729 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
5730 || fromlen > CONV_RESTLEN)
5731 {
5732 ip->bw_conv_error = TRUE;
5733 return FAIL;
5734 }
5735
5736 /* copy remainder to ip->bw_rest[] to be used for the next call. */
5737 if (fromlen > 0)
5738 mch_memmove(ip->bw_rest, (void *)from, fromlen);
5739 ip->bw_restlen = (int)fromlen;
5740
5741 buf = ip->bw_conv_buf;
5742 len = (int)((char_u *)to - ip->bw_conv_buf);
5743 }
5744# endif
5745 }
5746#endif /* FEAT_MBYTE */
5747
Bram Moolenaare6bf6552017-06-27 22:11:51 +02005748 if (ip->bw_fd < 0)
5749 /* Only checking conversion, which is OK if we get here. */
5750 return OK;
5751
Bram Moolenaar071d4272004-06-13 20:20:40 +00005752#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02005753 if (flags & FIO_ENCRYPTED)
5754 {
5755 /* Encrypt the data. Do it in-place if possible, otherwise use an
5756 * allocated buffer. */
5757 if (crypt_works_inplace(ip->bw_buffer->b_cryptstate))
5758 {
5759 crypt_encode_inplace(ip->bw_buffer->b_cryptstate, buf, len);
5760 }
5761 else
5762 {
5763 char_u *outbuf;
5764
5765 len = crypt_encode_alloc(curbuf->b_cryptstate, buf, len, &outbuf);
5766 if (len == 0)
5767 return OK; /* Crypt layer is buffering, will flush later. */
5768 wlen = write_eintr(ip->bw_fd, outbuf, len);
5769 vim_free(outbuf);
5770 return (wlen < len) ? FAIL : OK;
5771 }
5772 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005773#endif
5774
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005775 wlen = write_eintr(ip->bw_fd, buf, len);
5776 return (wlen < len) ? FAIL : OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005777}
5778
5779#ifdef FEAT_MBYTE
5780/*
5781 * Convert a Unicode character to bytes.
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005782 * Return TRUE for an error, FALSE when it's OK.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005783 */
5784 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005785ucs2bytes(
5786 unsigned c, /* in: character */
5787 char_u **pp, /* in/out: pointer to result */
5788 int flags) /* FIO_ flags */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005789{
5790 char_u *p = *pp;
5791 int error = FALSE;
5792 int cc;
5793
5794
5795 if (flags & FIO_UCS4)
5796 {
5797 if (flags & FIO_ENDIAN_L)
5798 {
5799 *p++ = c;
5800 *p++ = (c >> 8);
5801 *p++ = (c >> 16);
5802 *p++ = (c >> 24);
5803 }
5804 else
5805 {
5806 *p++ = (c >> 24);
5807 *p++ = (c >> 16);
5808 *p++ = (c >> 8);
5809 *p++ = c;
5810 }
5811 }
5812 else if (flags & (FIO_UCS2 | FIO_UTF16))
5813 {
5814 if (c >= 0x10000)
5815 {
5816 if (flags & FIO_UTF16)
5817 {
5818 /* Make two words, ten bits of the character in each. First
5819 * word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff */
5820 c -= 0x10000;
5821 if (c >= 0x100000)
5822 error = TRUE;
5823 cc = ((c >> 10) & 0x3ff) + 0xd800;
5824 if (flags & FIO_ENDIAN_L)
5825 {
5826 *p++ = cc;
5827 *p++ = ((unsigned)cc >> 8);
5828 }
5829 else
5830 {
5831 *p++ = ((unsigned)cc >> 8);
5832 *p++ = cc;
5833 }
5834 c = (c & 0x3ff) + 0xdc00;
5835 }
5836 else
5837 error = TRUE;
5838 }
5839 if (flags & FIO_ENDIAN_L)
5840 {
5841 *p++ = c;
5842 *p++ = (c >> 8);
5843 }
5844 else
5845 {
5846 *p++ = (c >> 8);
5847 *p++ = c;
5848 }
5849 }
5850 else /* Latin1 */
5851 {
5852 if (c >= 0x100)
5853 {
5854 error = TRUE;
5855 *p++ = 0xBF;
5856 }
5857 else
5858 *p++ = c;
5859 }
5860
5861 *pp = p;
5862 return error;
5863}
5864
5865/*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005866 * Return TRUE if file encoding "fenc" requires conversion from or to
5867 * 'encoding'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005868 */
5869 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005870need_conversion(char_u *fenc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005871{
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005872 int same_encoding;
5873 int enc_flags;
5874 int fenc_flags;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005875
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005876 if (*fenc == NUL || STRCMP(p_enc, fenc) == 0)
Bram Moolenaar442b4222010-05-24 21:34:22 +02005877 {
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005878 same_encoding = TRUE;
Bram Moolenaar442b4222010-05-24 21:34:22 +02005879 fenc_flags = 0;
5880 }
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005881 else
5882 {
5883 /* Ignore difference between "ansi" and "latin1", "ucs-4" and
5884 * "ucs-4be", etc. */
5885 enc_flags = get_fio_flags(p_enc);
5886 fenc_flags = get_fio_flags(fenc);
5887 same_encoding = (enc_flags != 0 && fenc_flags == enc_flags);
5888 }
5889 if (same_encoding)
5890 {
5891 /* Specified encoding matches with 'encoding'. This requires
5892 * conversion when 'encoding' is Unicode but not UTF-8. */
5893 return enc_unicode != 0;
5894 }
5895
5896 /* Encodings differ. However, conversion is not needed when 'enc' is any
5897 * Unicode encoding and the file is UTF-8. */
5898 return !(enc_utf8 && fenc_flags == FIO_UTF8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005899}
5900
5901/*
5902 * Check "ptr" for a unicode encoding and return the FIO_ flags needed for the
5903 * internal conversion.
5904 * if "ptr" is an empty string, use 'encoding'.
5905 */
5906 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005907get_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005908{
5909 int prop;
5910
5911 if (*ptr == NUL)
5912 ptr = p_enc;
5913
5914 prop = enc_canon_props(ptr);
5915 if (prop & ENC_UNICODE)
5916 {
5917 if (prop & ENC_2BYTE)
5918 {
5919 if (prop & ENC_ENDIAN_L)
5920 return FIO_UCS2 | FIO_ENDIAN_L;
5921 return FIO_UCS2;
5922 }
5923 if (prop & ENC_4BYTE)
5924 {
5925 if (prop & ENC_ENDIAN_L)
5926 return FIO_UCS4 | FIO_ENDIAN_L;
5927 return FIO_UCS4;
5928 }
5929 if (prop & ENC_2WORD)
5930 {
5931 if (prop & ENC_ENDIAN_L)
5932 return FIO_UTF16 | FIO_ENDIAN_L;
5933 return FIO_UTF16;
5934 }
5935 return FIO_UTF8;
5936 }
5937 if (prop & ENC_LATIN1)
5938 return FIO_LATIN1;
5939 /* must be ENC_DBCS, requires iconv() */
5940 return 0;
5941}
5942
5943#ifdef WIN3264
5944/*
5945 * Check "ptr" for a MS-Windows codepage name and return the FIO_ flags needed
5946 * for the conversion MS-Windows can do for us. Also accept "utf-8".
5947 * Used for conversion between 'encoding' and 'fileencoding'.
5948 */
5949 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005950get_win_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005951{
5952 int cp;
5953
5954 /* Cannot do this when 'encoding' is not utf-8 and not a codepage. */
5955 if (!enc_utf8 && enc_codepage <= 0)
5956 return 0;
5957
5958 cp = encname2codepage(ptr);
5959 if (cp == 0)
5960 {
5961# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5962 if (STRCMP(ptr, "utf-8") == 0)
5963 cp = CP_UTF8;
5964 else
5965# endif
5966 return 0;
5967 }
5968 return FIO_PUT_CP(cp) | FIO_CODEPAGE;
5969}
5970#endif
5971
Bram Moolenaard0573012017-10-28 21:11:06 +02005972#ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00005973/*
5974 * Check "ptr" for a Carbon supported encoding and return the FIO_ flags
5975 * needed for the internal conversion to/from utf-8 or latin1.
5976 */
5977 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005978get_mac_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005979{
5980 if ((enc_utf8 || STRCMP(p_enc, "latin1") == 0)
5981 && (enc_canon_props(ptr) & ENC_MACROMAN))
5982 return FIO_MACROMAN;
5983 return 0;
5984}
5985#endif
5986
5987/*
5988 * Check for a Unicode BOM (Byte Order Mark) at the start of p[size].
5989 * "size" must be at least 2.
5990 * Return the name of the encoding and set "*lenp" to the length.
5991 * Returns NULL when no BOM found.
5992 */
5993 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005994check_for_bom(
5995 char_u *p,
5996 long size,
5997 int *lenp,
5998 int flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005999{
6000 char *name = NULL;
6001 int len = 2;
6002
6003 if (p[0] == 0xef && p[1] == 0xbb && size >= 3 && p[2] == 0xbf
Bram Moolenaaree0f5a62008-07-24 20:09:16 +00006004 && (flags == FIO_ALL || flags == FIO_UTF8 || flags == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006005 {
6006 name = "utf-8"; /* EF BB BF */
6007 len = 3;
6008 }
6009 else if (p[0] == 0xff && p[1] == 0xfe)
6010 {
6011 if (size >= 4 && p[2] == 0 && p[3] == 0
6012 && (flags == FIO_ALL || flags == (FIO_UCS4 | FIO_ENDIAN_L)))
6013 {
6014 name = "ucs-4le"; /* FF FE 00 00 */
6015 len = 4;
6016 }
Bram Moolenaar223a1892008-11-11 20:57:11 +00006017 else if (flags == (FIO_UCS2 | FIO_ENDIAN_L))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006018 name = "ucs-2le"; /* FF FE */
Bram Moolenaar223a1892008-11-11 20:57:11 +00006019 else if (flags == FIO_ALL || flags == (FIO_UTF16 | FIO_ENDIAN_L))
6020 /* utf-16le is preferred, it also works for ucs-2le text */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006021 name = "utf-16le"; /* FF FE */
6022 }
6023 else if (p[0] == 0xfe && p[1] == 0xff
6024 && (flags == FIO_ALL || flags == FIO_UCS2 || flags == FIO_UTF16))
6025 {
Bram Moolenaarffd82c52008-02-20 17:15:26 +00006026 /* Default to utf-16, it works also for ucs-2 text. */
6027 if (flags == FIO_UCS2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006028 name = "ucs-2"; /* FE FF */
Bram Moolenaarffd82c52008-02-20 17:15:26 +00006029 else
6030 name = "utf-16"; /* FE FF */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006031 }
6032 else if (size >= 4 && p[0] == 0 && p[1] == 0 && p[2] == 0xfe
6033 && p[3] == 0xff && (flags == FIO_ALL || flags == FIO_UCS4))
6034 {
6035 name = "ucs-4"; /* 00 00 FE FF */
6036 len = 4;
6037 }
6038
6039 *lenp = len;
6040 return (char_u *)name;
6041}
6042
6043/*
6044 * Generate a BOM in "buf[4]" for encoding "name".
6045 * Return the length of the BOM (zero when no BOM).
6046 */
6047 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006048make_bom(char_u *buf, char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006049{
6050 int flags;
6051 char_u *p;
6052
6053 flags = get_fio_flags(name);
6054
6055 /* Can't put a BOM in a non-Unicode file. */
6056 if (flags == FIO_LATIN1 || flags == 0)
6057 return 0;
6058
6059 if (flags == FIO_UTF8) /* UTF-8 */
6060 {
6061 buf[0] = 0xef;
6062 buf[1] = 0xbb;
6063 buf[2] = 0xbf;
6064 return 3;
6065 }
6066 p = buf;
6067 (void)ucs2bytes(0xfeff, &p, flags);
6068 return (int)(p - buf);
6069}
6070#endif
6071
6072/*
6073 * Try to find a shortname by comparing the fullname with the current
6074 * directory.
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006075 * Returns "full_path" or pointer into "full_path" if shortened.
6076 */
6077 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006078shorten_fname1(char_u *full_path)
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006079{
Bram Moolenaard9462e32011-04-11 21:35:11 +02006080 char_u *dirname;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006081 char_u *p = full_path;
6082
Bram Moolenaard9462e32011-04-11 21:35:11 +02006083 dirname = alloc(MAXPATHL);
6084 if (dirname == NULL)
6085 return full_path;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006086 if (mch_dirname(dirname, MAXPATHL) == OK)
6087 {
6088 p = shorten_fname(full_path, dirname);
6089 if (p == NULL || *p == NUL)
6090 p = full_path;
6091 }
Bram Moolenaard9462e32011-04-11 21:35:11 +02006092 vim_free(dirname);
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006093 return p;
6094}
6095
6096/*
6097 * Try to find a shortname by comparing the fullname with the current
6098 * directory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006099 * Returns NULL if not shorter name possible, pointer into "full_path"
6100 * otherwise.
6101 */
6102 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006103shorten_fname(char_u *full_path, char_u *dir_name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006104{
6105 int len;
6106 char_u *p;
6107
6108 if (full_path == NULL)
6109 return NULL;
6110 len = (int)STRLEN(dir_name);
6111 if (fnamencmp(dir_name, full_path, len) == 0)
6112 {
6113 p = full_path + len;
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006114#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006115 /*
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006116 * MSWIN: when a file is in the root directory, dir_name will end in a
Bram Moolenaar071d4272004-06-13 20:20:40 +00006117 * slash, since C: by itself does not define a specific dir. In this
6118 * case p may already be correct. <negri>
6119 */
6120 if (!((len > 2) && (*(p - 2) == ':')))
6121#endif
6122 {
6123 if (vim_ispathsep(*p))
6124 ++p;
6125#ifndef VMS /* the path separator is always part of the path */
6126 else
6127 p = NULL;
6128#endif
6129 }
6130 }
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006131#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006132 /*
6133 * When using a file in the current drive, remove the drive name:
6134 * "A:\dir\file" -> "\dir\file". This helps when moving a session file on
6135 * a floppy from "A:\dir" to "B:\dir".
6136 */
6137 else if (len > 3
6138 && TOUPPER_LOC(full_path[0]) == TOUPPER_LOC(dir_name[0])
6139 && full_path[1] == ':'
6140 && vim_ispathsep(full_path[2]))
6141 p = full_path + 2;
6142#endif
6143 else
6144 p = NULL;
6145 return p;
6146}
6147
6148/*
6149 * Shorten filenames for all buffers.
6150 * When "force" is TRUE: Use full path from now on for files currently being
6151 * edited, both for file name and swap file name. Try to shorten the file
6152 * names a bit, if safe to do so.
6153 * When "force" is FALSE: Only try to shorten absolute file names.
6154 * For buffers that have buftype "nofile" or "scratch": never change the file
6155 * name.
6156 */
6157 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006158shorten_fnames(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006159{
6160 char_u dirname[MAXPATHL];
6161 buf_T *buf;
6162 char_u *p;
6163
6164 mch_dirname(dirname, MAXPATHL);
Bram Moolenaar29323592016-07-24 22:04:11 +02006165 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006166 {
6167 if (buf->b_fname != NULL
6168#ifdef FEAT_QUICKFIX
6169 && !bt_nofile(buf)
6170#endif
6171 && !path_with_url(buf->b_fname)
6172 && (force
6173 || buf->b_sfname == NULL
6174 || mch_isFullName(buf->b_sfname)))
6175 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01006176 VIM_CLEAR(buf->b_sfname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006177 p = shorten_fname(buf->b_ffname, dirname);
6178 if (p != NULL)
6179 {
6180 buf->b_sfname = vim_strsave(p);
6181 buf->b_fname = buf->b_sfname;
6182 }
6183 if (p == NULL || buf->b_fname == NULL)
6184 buf->b_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006185 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00006186
6187 /* Always make the swap file name a full path, a "nofile" buffer may
6188 * also have a swap file. */
6189 mf_fullname(buf->b_ml.ml_mfp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006190 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006191 status_redraw_all();
Bram Moolenaar49d7bf12006-02-17 21:45:41 +00006192 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006193}
6194
6195#if (defined(FEAT_DND) && defined(FEAT_GUI_GTK)) \
6196 || defined(FEAT_GUI_MSWIN) \
6197 || defined(FEAT_GUI_MAC) \
6198 || defined(PROTO)
6199/*
6200 * Shorten all filenames in "fnames[count]" by current directory.
6201 */
6202 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006203shorten_filenames(char_u **fnames, int count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006204{
6205 int i;
6206 char_u dirname[MAXPATHL];
6207 char_u *p;
6208
6209 if (fnames == NULL || count < 1)
6210 return;
6211 mch_dirname(dirname, sizeof(dirname));
6212 for (i = 0; i < count; ++i)
6213 {
6214 if ((p = shorten_fname(fnames[i], dirname)) != NULL)
6215 {
6216 /* shorten_fname() returns pointer in given "fnames[i]". If free
6217 * "fnames[i]" first, "p" becomes invalid. So we need to copy
6218 * "p" first then free fnames[i]. */
6219 p = vim_strsave(p);
6220 vim_free(fnames[i]);
6221 fnames[i] = p;
6222 }
6223 }
6224}
6225#endif
6226
6227/*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006228 * add extension to file name - change path/fo.o.h to path/fo.o.h.ext or
Bram Moolenaar071d4272004-06-13 20:20:40 +00006229 * fo_o_h.ext for MSDOS or when shortname option set.
6230 *
6231 * Assumed that fname is a valid name found in the filesystem we assure that
6232 * the return value is a different name and ends in 'ext'.
6233 * "ext" MUST be at most 4 characters long if it starts with a dot, 3
6234 * characters otherwise.
6235 * Space for the returned name is allocated, must be freed later.
6236 * Returns NULL when out of memory.
6237 */
6238 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006239modname(
6240 char_u *fname,
6241 char_u *ext,
6242 int prepend_dot) /* may prepend a '.' to file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006243{
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006244 return buf_modname((curbuf->b_p_sn || curbuf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00006245 fname, ext, prepend_dot);
6246}
6247
6248 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006249buf_modname(
6250 int shortname, /* use 8.3 file name */
6251 char_u *fname,
6252 char_u *ext,
6253 int prepend_dot) /* may prepend a '.' to file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006254{
6255 char_u *retval;
6256 char_u *s;
6257 char_u *e;
6258 char_u *ptr;
6259 int fnamelen, extlen;
6260
6261 extlen = (int)STRLEN(ext);
6262
6263 /*
6264 * If there is no file name we must get the name of the current directory
6265 * (we need the full path in case :cd is used).
6266 */
6267 if (fname == NULL || *fname == NUL)
6268 {
6269 retval = alloc((unsigned)(MAXPATHL + extlen + 3));
6270 if (retval == NULL)
6271 return NULL;
6272 if (mch_dirname(retval, MAXPATHL) == FAIL ||
6273 (fnamelen = (int)STRLEN(retval)) == 0)
6274 {
6275 vim_free(retval);
6276 return NULL;
6277 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006278 if (!after_pathsep(retval, retval + fnamelen))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006279 {
6280 retval[fnamelen++] = PATHSEP;
6281 retval[fnamelen] = NUL;
6282 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006283 prepend_dot = FALSE; /* nothing to prepend a dot to */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006284 }
6285 else
6286 {
6287 fnamelen = (int)STRLEN(fname);
6288 retval = alloc((unsigned)(fnamelen + extlen + 3));
6289 if (retval == NULL)
6290 return NULL;
6291 STRCPY(retval, fname);
6292#ifdef VMS
6293 vms_remove_version(retval); /* we do not need versions here */
6294#endif
6295 }
6296
6297 /*
6298 * search backwards until we hit a '/', '\' or ':' replacing all '.'
6299 * by '_' for MSDOS or when shortname option set and ext starts with a dot.
6300 * Then truncate what is after the '/', '\' or ':' to 8 characters for
6301 * MSDOS and 26 characters for AMIGA, a lot more for UNIX.
6302 */
Bram Moolenaar91acfff2017-03-12 19:22:36 +01006303 for (ptr = retval + fnamelen; ptr > retval; MB_PTR_BACK(retval, ptr))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006304 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006305 if (*ext == '.'
Bram Moolenaare60acc12011-05-10 16:41:25 +02006306#ifdef USE_LONG_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00006307 && (!USE_LONG_FNAME || shortname)
Bram Moolenaare60acc12011-05-10 16:41:25 +02006308#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006309 && shortname
Bram Moolenaare60acc12011-05-10 16:41:25 +02006310#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006311 )
6312 if (*ptr == '.') /* replace '.' by '_' */
6313 *ptr = '_';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006314 if (vim_ispathsep(*ptr))
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006315 {
6316 ++ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006317 break;
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006318 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006319 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006320
6321 /* the file name has at most BASENAMELEN characters. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006322 if (STRLEN(ptr) > (unsigned)BASENAMELEN)
6323 ptr[BASENAMELEN] = '\0';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006324
6325 s = ptr + STRLEN(ptr);
6326
6327 /*
6328 * For 8.3 file names we may have to reduce the length.
6329 */
6330#ifdef USE_LONG_FNAME
6331 if (!USE_LONG_FNAME || shortname)
6332#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006333 if (shortname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006334#endif
6335 {
6336 /*
6337 * If there is no file name, or the file name ends in '/', and the
6338 * extension starts with '.', put a '_' before the dot, because just
6339 * ".ext" is invalid.
6340 */
6341 if (fname == NULL || *fname == NUL
6342 || vim_ispathsep(fname[STRLEN(fname) - 1]))
6343 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006344 if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006345 *s++ = '_';
6346 }
6347 /*
6348 * If the extension starts with '.', truncate the base name at 8
6349 * characters
6350 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006351 else if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006352 {
Bram Moolenaar78a15312009-05-15 19:33:18 +00006353 if ((size_t)(s - ptr) > (size_t)8)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006354 {
6355 s = ptr + 8;
6356 *s = '\0';
6357 }
6358 }
6359 /*
6360 * If the extension doesn't start with '.', and the file name
6361 * doesn't have an extension yet, append a '.'
6362 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006363 else if ((e = vim_strchr(ptr, '.')) == NULL)
6364 *s++ = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006365 /*
6366 * If the extension doesn't start with '.', and there already is an
Bram Moolenaar7263a772007-05-10 17:35:54 +00006367 * extension, it may need to be truncated
Bram Moolenaar071d4272004-06-13 20:20:40 +00006368 */
6369 else if ((int)STRLEN(e) + extlen > 4)
6370 s = e + 4 - extlen;
6371 }
Bram Moolenaare7fedb62015-12-31 19:07:19 +01006372#if defined(USE_LONG_FNAME) || defined(WIN3264)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006373 /*
6374 * If there is no file name, and the extension starts with '.', put a
6375 * '_' before the dot, because just ".ext" may be invalid if it's on a
6376 * FAT partition, and on HPFS it doesn't matter.
6377 */
6378 else if ((fname == NULL || *fname == NUL) && *ext == '.')
6379 *s++ = '_';
6380#endif
6381
6382 /*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006383 * Append the extension.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006384 * ext can start with '.' and cannot exceed 3 more characters.
6385 */
6386 STRCPY(s, ext);
6387
Bram Moolenaar071d4272004-06-13 20:20:40 +00006388 /*
6389 * Prepend the dot.
6390 */
Bram Moolenaare60acc12011-05-10 16:41:25 +02006391 if (prepend_dot && !shortname && *(e = gettail(retval)) != '.'
Bram Moolenaar071d4272004-06-13 20:20:40 +00006392#ifdef USE_LONG_FNAME
6393 && USE_LONG_FNAME
6394#endif
6395 )
6396 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006397 STRMOVE(e + 1, e);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006398 *e = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006399 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006400
6401 /*
6402 * Check that, after appending the extension, the file name is really
6403 * different.
6404 */
6405 if (fname != NULL && STRCMP(fname, retval) == 0)
6406 {
6407 /* we search for a character that can be replaced by '_' */
6408 while (--s >= ptr)
6409 {
6410 if (*s != '_')
6411 {
6412 *s = '_';
6413 break;
6414 }
6415 }
6416 if (s < ptr) /* fname was "________.<ext>", how tricky! */
6417 *ptr = 'v';
6418 }
6419 return retval;
6420}
6421
6422/*
6423 * Like fgets(), but if the file line is too long, it is truncated and the
6424 * rest of the line is thrown away. Returns TRUE for end-of-file.
Bram Moolenaar7e1652c2017-12-16 18:27:02 +01006425 * If the line is truncated then buf[size - 2] will not be NUL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006426 */
6427 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006428vim_fgets(char_u *buf, int size, FILE *fp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006429{
6430 char *eof;
6431#define FGETS_SIZE 200
6432 char tbuf[FGETS_SIZE];
6433
6434 buf[size - 2] = NUL;
6435#ifdef USE_CR
6436 eof = fgets_cr((char *)buf, size, fp);
6437#else
6438 eof = fgets((char *)buf, size, fp);
6439#endif
6440 if (buf[size - 2] != NUL && buf[size - 2] != '\n')
6441 {
6442 buf[size - 1] = NUL; /* Truncate the line */
6443
6444 /* Now throw away the rest of the line: */
6445 do
6446 {
6447 tbuf[FGETS_SIZE - 2] = NUL;
6448#ifdef USE_CR
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006449 ignoredp = fgets_cr((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006450#else
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006451 ignoredp = fgets((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006452#endif
6453 } while (tbuf[FGETS_SIZE - 2] != NUL && tbuf[FGETS_SIZE - 2] != '\n');
6454 }
6455 return (eof == NULL);
6456}
6457
6458#if defined(USE_CR) || defined(PROTO)
6459/*
6460 * Like vim_fgets(), but accept any line terminator: CR, CR-LF or LF.
6461 * Returns TRUE for end-of-file.
6462 * Only used for the Mac, because it's much slower than vim_fgets().
6463 */
6464 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006465tag_fgets(char_u *buf, int size, FILE *fp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006466{
6467 int i = 0;
6468 int c;
6469 int eof = FALSE;
6470
6471 for (;;)
6472 {
6473 c = fgetc(fp);
6474 if (c == EOF)
6475 {
6476 eof = TRUE;
6477 break;
6478 }
6479 if (c == '\r')
6480 {
6481 /* Always store a NL for end-of-line. */
6482 if (i < size - 1)
6483 buf[i++] = '\n';
6484 c = fgetc(fp);
6485 if (c != '\n') /* Macintosh format: single CR. */
6486 ungetc(c, fp);
6487 break;
6488 }
6489 if (i < size - 1)
6490 buf[i++] = c;
6491 if (c == '\n')
6492 break;
6493 }
6494 buf[i] = NUL;
6495 return eof;
6496}
6497#endif
6498
6499/*
6500 * rename() only works if both files are on the same file system, this
6501 * function will (attempts to?) copy the file across if rename fails -- webb
6502 * Return -1 for failure, 0 for success.
6503 */
6504 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006505vim_rename(char_u *from, char_u *to)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006506{
6507 int fd_in;
6508 int fd_out;
6509 int n;
6510 char *errmsg = NULL;
6511 char *buffer;
6512#ifdef AMIGA
6513 BPTR flock;
6514#endif
Bram Moolenaar8767f522016-07-01 17:17:39 +02006515 stat_T st;
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006516 long perm;
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006517#ifdef HAVE_ACL
6518 vim_acl_T acl; /* ACL from original file */
6519#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006520 int use_tmp_file = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006521
6522 /*
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006523 * When the names are identical, there is nothing to do. When they refer
6524 * to the same file (ignoring case and slash/backslash differences) but
6525 * the file name differs we need to go through a temp file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006526 */
6527 if (fnamecmp(from, to) == 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006528 {
Bram Moolenaar71afbfe2013-03-19 16:49:16 +01006529 if (p_fic && STRCMP(gettail(from), gettail(to)) != 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006530 use_tmp_file = TRUE;
6531 else
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006532 return 0;
6533 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006534
6535 /*
6536 * Fail if the "from" file doesn't exist. Avoids that "to" is deleted.
6537 */
6538 if (mch_stat((char *)from, &st) < 0)
6539 return -1;
6540
Bram Moolenaar3576da72008-12-30 15:15:57 +00006541#ifdef UNIX
6542 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02006543 stat_T st_to;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006544
6545 /* It's possible for the source and destination to be the same file.
6546 * This happens when "from" and "to" differ in case and are on a FAT32
6547 * filesystem. In that case go through a temp file name. */
6548 if (mch_stat((char *)to, &st_to) >= 0
6549 && st.st_dev == st_to.st_dev
6550 && st.st_ino == st_to.st_ino)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006551 use_tmp_file = TRUE;
6552 }
6553#endif
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02006554#ifdef WIN3264
6555 {
6556 BY_HANDLE_FILE_INFORMATION info1, info2;
6557
6558 /* It's possible for the source and destination to be the same file.
6559 * In that case go through a temp file name. This makes rename("foo",
6560 * "./foo") a no-op (in a complicated way). */
6561 if (win32_fileinfo(from, &info1) == FILEINFO_OK
6562 && win32_fileinfo(to, &info2) == FILEINFO_OK
6563 && info1.dwVolumeSerialNumber == info2.dwVolumeSerialNumber
6564 && info1.nFileIndexHigh == info2.nFileIndexHigh
6565 && info1.nFileIndexLow == info2.nFileIndexLow)
6566 use_tmp_file = TRUE;
6567 }
6568#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006569
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006570 if (use_tmp_file)
6571 {
6572 char tempname[MAXPATHL + 1];
6573
6574 /*
6575 * Find a name that doesn't exist and is in the same directory.
6576 * Rename "from" to "tempname" and then rename "tempname" to "to".
6577 */
6578 if (STRLEN(from) >= MAXPATHL - 5)
6579 return -1;
6580 STRCPY(tempname, from);
6581 for (n = 123; n < 99999; ++n)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006582 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006583 sprintf((char *)gettail((char_u *)tempname), "%d", n);
6584 if (mch_stat(tempname, &st) < 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006585 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006586 if (mch_rename((char *)from, tempname) == 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006587 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006588 if (mch_rename(tempname, (char *)to) == 0)
6589 return 0;
6590 /* Strange, the second step failed. Try moving the
6591 * file back and return failure. */
6592 mch_rename(tempname, (char *)from);
Bram Moolenaar3576da72008-12-30 15:15:57 +00006593 return -1;
6594 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006595 /* If it fails for one temp name it will most likely fail
6596 * for any temp name, give up. */
6597 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006598 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006599 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006600 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006601 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006602
Bram Moolenaar071d4272004-06-13 20:20:40 +00006603 /*
6604 * Delete the "to" file, this is required on some systems to make the
6605 * mch_rename() work, on other systems it makes sure that we don't have
6606 * two files when the mch_rename() fails.
6607 */
6608
6609#ifdef AMIGA
6610 /*
6611 * With MSDOS-compatible filesystems (crossdos, messydos) it is possible
6612 * that the name of the "to" file is the same as the "from" file, even
Bram Moolenaar7263a772007-05-10 17:35:54 +00006613 * though the names are different. To avoid the chance of accidentally
Bram Moolenaar071d4272004-06-13 20:20:40 +00006614 * deleting the "from" file (horror!) we lock it during the remove.
6615 *
6616 * When used for making a backup before writing the file: This should not
6617 * happen with ":w", because startscript() should detect this problem and
6618 * set buf->b_shortname, causing modname() to return a correct ".bak" file
6619 * name. This problem does exist with ":w filename", but then the
6620 * original file will be somewhere else so the backup isn't really
6621 * important. If autoscripting is off the rename may fail.
6622 */
6623 flock = Lock((UBYTE *)from, (long)ACCESS_READ);
6624#endif
6625 mch_remove(to);
6626#ifdef AMIGA
6627 if (flock)
6628 UnLock(flock);
6629#endif
6630
6631 /*
6632 * First try a normal rename, return if it works.
6633 */
6634 if (mch_rename((char *)from, (char *)to) == 0)
6635 return 0;
6636
6637 /*
6638 * Rename() failed, try copying the file.
6639 */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006640 perm = mch_getperm(from);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006641#ifdef HAVE_ACL
6642 /* For systems that support ACL: get the ACL from the original file. */
6643 acl = mch_get_acl(from);
6644#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006645 fd_in = mch_open((char *)from, O_RDONLY|O_EXTRA, 0);
6646 if (fd_in == -1)
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006647 {
6648#ifdef HAVE_ACL
6649 mch_free_acl(acl);
6650#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006651 return -1;
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006652 }
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006653
6654 /* Create the new file with same permissions as the original. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00006655 fd_out = mch_open((char *)to,
6656 O_CREAT|O_EXCL|O_WRONLY|O_EXTRA|O_NOFOLLOW, (int)perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006657 if (fd_out == -1)
6658 {
6659 close(fd_in);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006660#ifdef HAVE_ACL
6661 mch_free_acl(acl);
6662#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006663 return -1;
6664 }
6665
6666 buffer = (char *)alloc(BUFSIZE);
6667 if (buffer == NULL)
6668 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006669 close(fd_out);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006670 close(fd_in);
6671#ifdef HAVE_ACL
6672 mch_free_acl(acl);
6673#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006674 return -1;
6675 }
6676
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01006677 while ((n = read_eintr(fd_in, buffer, BUFSIZE)) > 0)
6678 if (write_eintr(fd_out, buffer, n) != n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006679 {
6680 errmsg = _("E208: Error writing to \"%s\"");
6681 break;
6682 }
6683
6684 vim_free(buffer);
6685 close(fd_in);
6686 if (close(fd_out) < 0)
6687 errmsg = _("E209: Error closing \"%s\"");
6688 if (n < 0)
6689 {
6690 errmsg = _("E210: Error reading \"%s\"");
6691 to = from;
6692 }
Bram Moolenaar7263a772007-05-10 17:35:54 +00006693#ifndef UNIX /* for Unix mch_open() already set the permission */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006694 mch_setperm(to, perm);
Bram Moolenaarc6039d82005-12-02 00:44:04 +00006695#endif
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006696#ifdef HAVE_ACL
6697 mch_set_acl(to, acl);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006698 mch_free_acl(acl);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006699#endif
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02006700#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaare8747442013-11-12 18:09:29 +01006701 mch_copy_sec(from, to);
Bram Moolenaar0671de32013-11-12 05:12:03 +01006702#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006703 if (errmsg != NULL)
6704 {
6705 EMSG2(errmsg, to);
6706 return -1;
6707 }
6708 mch_remove(from);
6709 return 0;
6710}
6711
6712static int already_warned = FALSE;
6713
6714/*
6715 * Check if any not hidden buffer has been changed.
6716 * Postpone the check if there are characters in the stuff buffer, a global
6717 * command is being executed, a mapping is being executed or an autocommand is
6718 * busy.
6719 * Returns TRUE if some message was written (screen should be redrawn and
6720 * cursor positioned).
6721 */
6722 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006723check_timestamps(
6724 int focus) /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006725{
6726 buf_T *buf;
6727 int didit = 0;
6728 int n;
6729
6730 /* Don't check timestamps while system() or another low-level function may
6731 * cause us to lose and gain focus. */
6732 if (no_check_timestamps > 0)
6733 return FALSE;
6734
6735 /* Avoid doing a check twice. The OK/Reload dialog can cause a focus
6736 * event and we would keep on checking if the file is steadily growing.
6737 * Do check again after typing something. */
6738 if (focus && did_check_timestamps)
6739 {
6740 need_check_timestamps = TRUE;
6741 return FALSE;
6742 }
6743
6744 if (!stuff_empty() || global_busy || !typebuf_typed()
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006745 || autocmd_busy || curbuf_lock > 0 || allbuf_lock > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006746 need_check_timestamps = TRUE; /* check later */
6747 else
6748 {
6749 ++no_wait_return;
6750 did_check_timestamps = TRUE;
6751 already_warned = FALSE;
Bram Moolenaar29323592016-07-24 22:04:11 +02006752 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006753 {
6754 /* Only check buffers in a window. */
6755 if (buf->b_nwindows > 0)
6756 {
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006757 bufref_T bufref;
6758
6759 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006760 n = buf_check_timestamp(buf, focus);
6761 if (didit < n)
6762 didit = n;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006763 if (n > 0 && !bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006764 {
6765 /* Autocommands have removed the buffer, start at the
6766 * first one again. */
6767 buf = firstbuf;
6768 continue;
6769 }
6770 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006771 }
6772 --no_wait_return;
6773 need_check_timestamps = FALSE;
6774 if (need_wait_return && didit == 2)
6775 {
6776 /* make sure msg isn't overwritten */
6777 msg_puts((char_u *)"\n");
6778 out_flush();
6779 }
6780 }
6781 return didit;
6782}
6783
6784/*
6785 * Move all the lines from buffer "frombuf" to buffer "tobuf".
6786 * Return OK or FAIL. When FAIL "tobuf" is incomplete and/or "frombuf" is not
6787 * empty.
6788 */
6789 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006790move_lines(buf_T *frombuf, buf_T *tobuf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006791{
6792 buf_T *tbuf = curbuf;
6793 int retval = OK;
6794 linenr_T lnum;
6795 char_u *p;
6796
6797 /* Copy the lines in "frombuf" to "tobuf". */
6798 curbuf = tobuf;
6799 for (lnum = 1; lnum <= frombuf->b_ml.ml_line_count; ++lnum)
6800 {
6801 p = vim_strsave(ml_get_buf(frombuf, lnum, FALSE));
6802 if (p == NULL || ml_append(lnum - 1, p, 0, FALSE) == FAIL)
6803 {
6804 vim_free(p);
6805 retval = FAIL;
6806 break;
6807 }
6808 vim_free(p);
6809 }
6810
6811 /* Delete all the lines in "frombuf". */
6812 if (retval != FAIL)
6813 {
6814 curbuf = frombuf;
Bram Moolenaar9460b9d2007-01-09 14:37:01 +00006815 for (lnum = curbuf->b_ml.ml_line_count; lnum > 0; --lnum)
6816 if (ml_delete(lnum, FALSE) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006817 {
6818 /* Oops! We could try putting back the saved lines, but that
6819 * might fail again... */
6820 retval = FAIL;
6821 break;
6822 }
6823 }
6824
6825 curbuf = tbuf;
6826 return retval;
6827}
6828
6829/*
6830 * Check if buffer "buf" has been changed.
6831 * Also check if the file for a new buffer unexpectedly appeared.
6832 * return 1 if a changed buffer was found.
6833 * return 2 if a message has been displayed.
6834 * return 0 otherwise.
6835 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006836 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006837buf_check_timestamp(
6838 buf_T *buf,
6839 int focus UNUSED) /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006840{
Bram Moolenaar8767f522016-07-01 17:17:39 +02006841 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006842 int stat_res;
6843 int retval = 0;
6844 char_u *path;
6845 char_u *tbuf;
6846 char *mesg = NULL;
Bram Moolenaar44ecf652005-03-07 23:09:59 +00006847 char *mesg2 = "";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006848 int helpmesg = FALSE;
6849 int reload = FALSE;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006850 char *reason;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006851#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6852 int can_reload = FALSE;
6853#endif
Bram Moolenaar8767f522016-07-01 17:17:39 +02006854 off_T orig_size = buf->b_orig_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006855 int orig_mode = buf->b_orig_mode;
6856#ifdef FEAT_GUI
6857 int save_mouse_correct = need_mouse_correct;
6858#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006859 static int busy = FALSE;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006860 int n;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006861#ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006862 char_u *s;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006863#endif
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006864 bufref_T bufref;
6865
6866 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006867
6868 /* If there is no file name, the buffer is not loaded, 'buftype' is
6869 * set, we are in the middle of a save or being called recursively: ignore
6870 * this buffer. */
6871 if (buf->b_ffname == NULL
6872 || buf->b_ml.ml_mfp == NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00006873 || *buf->b_p_bt != NUL
Bram Moolenaar071d4272004-06-13 20:20:40 +00006874 || buf->b_saving
Bram Moolenaar071d4272004-06-13 20:20:40 +00006875 || busy
Bram Moolenaar009b2592004-10-24 19:18:58 +00006876#ifdef FEAT_NETBEANS_INTG
6877 || isNetbeansBuffer(buf)
6878#endif
Bram Moolenaar8cad9302017-08-12 14:32:32 +02006879#ifdef FEAT_TERMINAL
6880 || buf->b_term != NULL
6881#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006882 )
6883 return 0;
6884
6885 if ( !(buf->b_flags & BF_NOTEDITED)
6886 && buf->b_mtime != 0
6887 && ((stat_res = mch_stat((char *)buf->b_ffname, &st)) < 0
6888 || time_differs((long)st.st_mtime, buf->b_mtime)
Bram Moolenaara7611f62014-05-02 15:46:14 +02006889 || st.st_size != buf->b_orig_size
Bram Moolenaar071d4272004-06-13 20:20:40 +00006890#ifdef HAVE_ST_MODE
6891 || (int)st.st_mode != buf->b_orig_mode
6892#else
6893 || mch_getperm(buf->b_ffname) != buf->b_orig_mode
6894#endif
6895 ))
6896 {
6897 retval = 1;
6898
Bram Moolenaar316059c2006-01-14 21:18:42 +00006899 /* set b_mtime to stop further warnings (e.g., when executing
6900 * FileChangedShell autocmd) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006901 if (stat_res < 0)
6902 {
6903 buf->b_mtime = 0;
6904 buf->b_orig_size = 0;
6905 buf->b_orig_mode = 0;
6906 }
6907 else
6908 buf_store_time(buf, &st, buf->b_ffname);
6909
6910 /* Don't do anything for a directory. Might contain the file
6911 * explorer. */
6912 if (mch_isdir(buf->b_fname))
6913 ;
6914
6915 /*
6916 * If 'autoread' is set, the buffer has no changes and the file still
6917 * exists, reload the buffer. Use the buffer-local option value if it
6918 * was set, the global option value otherwise.
6919 */
6920 else if ((buf->b_p_ar >= 0 ? buf->b_p_ar : p_ar)
6921 && !bufIsChanged(buf) && stat_res >= 0)
6922 reload = TRUE;
6923 else
6924 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006925 if (stat_res < 0)
6926 reason = "deleted";
6927 else if (bufIsChanged(buf))
6928 reason = "conflict";
6929 else if (orig_size != buf->b_orig_size || buf_contents_changed(buf))
6930 reason = "changed";
6931 else if (orig_mode != buf->b_orig_mode)
6932 reason = "mode";
6933 else
6934 reason = "time";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006935
6936 /*
6937 * Only give the warning if there are no FileChangedShell
6938 * autocommands.
6939 * Avoid being called recursively by setting "busy".
6940 */
6941 busy = TRUE;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006942#ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006943 set_vim_var_string(VV_FCS_REASON, (char_u *)reason, -1);
6944 set_vim_var_string(VV_FCS_CHOICE, (char_u *)"", -1);
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006945#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006946 ++allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006947 n = apply_autocmds(EVENT_FILECHANGEDSHELL,
6948 buf->b_fname, buf->b_fname, FALSE, buf);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006949 --allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006950 busy = FALSE;
6951 if (n)
6952 {
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006953 if (!bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006954 EMSG(_("E246: FileChangedShell autocommand deleted buffer"));
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006955#ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006956 s = get_vim_var_str(VV_FCS_CHOICE);
6957 if (STRCMP(s, "reload") == 0 && *reason != 'd')
6958 reload = TRUE;
6959 else if (STRCMP(s, "ask") == 0)
6960 n = FALSE;
6961 else
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006962#endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006963 return 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006964 }
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006965 if (!n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006966 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006967 if (*reason == 'd')
6968 mesg = _("E211: File \"%s\" no longer available");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006969 else
6970 {
6971 helpmesg = TRUE;
6972#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6973 can_reload = TRUE;
6974#endif
6975 /*
6976 * Check if the file contents really changed to avoid
6977 * giving a warning when only the timestamp was set (e.g.,
6978 * checked out of CVS). Always warn when the buffer was
6979 * changed.
6980 */
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006981 if (reason[2] == 'n')
6982 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006983 mesg = _("W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006984 mesg2 = _("See \":help W12\" for more info.");
6985 }
6986 else if (reason[1] == 'h')
6987 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006988 mesg = _("W11: Warning: File \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006989 mesg2 = _("See \":help W11\" for more info.");
6990 }
6991 else if (*reason == 'm')
6992 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006993 mesg = _("W16: Warning: Mode of file \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006994 mesg2 = _("See \":help W16\" for more info.");
6995 }
Bram Moolenaar85388b52009-06-24 09:58:32 +00006996 else
6997 /* Only timestamp changed, store it to avoid a warning
6998 * in check_mtime() later. */
6999 buf->b_mtime_read = buf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007000 }
7001 }
7002 }
7003
7004 }
7005 else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W)
7006 && vim_fexists(buf->b_ffname))
7007 {
7008 retval = 1;
7009 mesg = _("W13: Warning: File \"%s\" has been created after editing started");
7010 buf->b_flags |= BF_NEW_W;
7011#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
7012 can_reload = TRUE;
7013#endif
7014 }
7015
7016 if (mesg != NULL)
7017 {
7018 path = home_replace_save(buf, buf->b_fname);
7019 if (path != NULL)
7020 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007021 if (!helpmesg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007022 mesg2 = "";
7023 tbuf = alloc((unsigned)(STRLEN(path) + STRLEN(mesg)
7024 + STRLEN(mesg2) + 2));
7025 sprintf((char *)tbuf, mesg, path);
Bram Moolenaar496c5262009-03-18 14:42:00 +00007026#ifdef FEAT_EVAL
7027 /* Set warningmsg here, before the unimportant and output-specific
7028 * mesg2 has been appended. */
7029 set_vim_var_string(VV_WARNINGMSG, tbuf, -1);
7030#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007031#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
7032 if (can_reload)
7033 {
7034 if (*mesg2 != NUL)
7035 {
7036 STRCAT(tbuf, "\n");
7037 STRCAT(tbuf, mesg2);
7038 }
7039 if (do_dialog(VIM_WARNING, (char_u *)_("Warning"), tbuf,
Bram Moolenaard2c340a2011-01-17 20:08:11 +01007040 (char_u *)_("&OK\n&Load File"), 1, NULL, TRUE) == 2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007041 reload = TRUE;
7042 }
7043 else
7044#endif
7045 if (State > NORMAL_BUSY || (State & CMDLINE) || already_warned)
7046 {
7047 if (*mesg2 != NUL)
7048 {
7049 STRCAT(tbuf, "; ");
7050 STRCAT(tbuf, mesg2);
7051 }
7052 EMSG(tbuf);
7053 retval = 2;
7054 }
7055 else
7056 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007057 if (!autocmd_busy)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007058 {
7059 msg_start();
Bram Moolenaar8820b482017-03-16 17:23:31 +01007060 msg_puts_attr(tbuf, HL_ATTR(HLF_E) + MSG_HIST);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007061 if (*mesg2 != NUL)
7062 msg_puts_attr((char_u *)mesg2,
Bram Moolenaar8820b482017-03-16 17:23:31 +01007063 HL_ATTR(HLF_W) + MSG_HIST);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007064 msg_clr_eos();
7065 (void)msg_end();
7066 if (emsg_silent == 0)
7067 {
7068 out_flush();
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01007069#ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00007070 if (!focus)
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01007071#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007072 /* give the user some time to think about it */
7073 ui_delay(1000L, TRUE);
7074
7075 /* don't redraw and erase the message */
7076 redraw_cmdline = FALSE;
7077 }
7078 }
7079 already_warned = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007080 }
7081
7082 vim_free(path);
7083 vim_free(tbuf);
7084 }
7085 }
7086
7087 if (reload)
Bram Moolenaar465748e2012-08-29 18:50:54 +02007088 {
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007089 /* Reload the buffer. */
Bram Moolenaar316059c2006-01-14 21:18:42 +00007090 buf_reload(buf, orig_mode);
Bram Moolenaar465748e2012-08-29 18:50:54 +02007091#ifdef FEAT_PERSISTENT_UNDO
7092 if (buf->b_p_udf && buf->b_ffname != NULL)
7093 {
7094 char_u hash[UNDO_HASH_SIZE];
7095 buf_T *save_curbuf = curbuf;
7096
7097 /* Any existing undo file is unusable, write it now. */
7098 curbuf = buf;
7099 u_compute_hash(hash);
7100 u_write_undo(NULL, FALSE, buf, hash);
7101 curbuf = save_curbuf;
7102 }
7103#endif
7104 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007105
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00007106 /* Trigger FileChangedShell when the file was changed in any way. */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007107 if (bufref_valid(&bufref) && retval != 0)
Bram Moolenaar56718732006-03-15 22:53:57 +00007108 (void)apply_autocmds(EVENT_FILECHANGEDSHELLPOST,
7109 buf->b_fname, buf->b_fname, FALSE, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007110#ifdef FEAT_GUI
7111 /* restore this in case an autocommand has set it; it would break
7112 * 'mousefocus' */
7113 need_mouse_correct = save_mouse_correct;
7114#endif
7115
7116 return retval;
7117}
7118
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007119/*
7120 * Reload a buffer that is already loaded.
7121 * Used when the file was changed outside of Vim.
Bram Moolenaar316059c2006-01-14 21:18:42 +00007122 * "orig_mode" is buf->b_orig_mode before the need for reloading was detected.
7123 * buf->b_orig_mode may have been reset already.
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007124 */
7125 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007126buf_reload(buf_T *buf, int orig_mode)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007127{
7128 exarg_T ea;
7129 pos_T old_cursor;
7130 linenr_T old_topline;
7131 int old_ro = buf->b_p_ro;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007132 buf_T *savebuf;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007133 bufref_T bufref;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007134 int saved = OK;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007135 aco_save_T aco;
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007136 int flags = READ_NEW;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007137
7138 /* set curwin/curbuf for "buf" and save some things */
7139 aucmd_prepbuf(&aco, buf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007140
7141 /* We only want to read the text from the file, not reset the syntax
7142 * highlighting, clear marks, diff status, etc. Force the fileformat
7143 * and encoding to be the same. */
7144 if (prep_exarg(&ea, buf) == OK)
7145 {
7146 old_cursor = curwin->w_cursor;
7147 old_topline = curwin->w_topline;
7148
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007149 if (p_ur < 0 || curbuf->b_ml.ml_line_count <= p_ur)
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007150 {
7151 /* Save all the text, so that the reload can be undone.
7152 * Sync first so that this is a separate undo-able action. */
7153 u_sync(FALSE);
7154 saved = u_savecommon(0, curbuf->b_ml.ml_line_count + 1, 0, TRUE);
7155 flags |= READ_KEEP_UNDO;
7156 }
7157
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007158 /*
7159 * To behave like when a new file is edited (matters for
7160 * BufReadPost autocommands) we first need to delete the current
7161 * buffer contents. But if reading the file fails we should keep
7162 * the old contents. Can't use memory only, the file might be
7163 * too big. Use a hidden buffer to move the buffer contents to.
7164 */
Bram Moolenaarb5aedf32017-03-12 18:23:53 +01007165 if (BUFEMPTY() || saved == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007166 savebuf = NULL;
7167 else
7168 {
7169 /* Allocate a buffer without putting it in the buffer list. */
7170 savebuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007171 set_bufref(&bufref, savebuf);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007172 if (savebuf != NULL && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007173 {
7174 /* Open the memline. */
7175 curbuf = savebuf;
7176 curwin->w_buffer = savebuf;
Bram Moolenaar4770d092006-01-12 23:22:24 +00007177 saved = ml_open(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007178 curbuf = buf;
7179 curwin->w_buffer = buf;
7180 }
Bram Moolenaar8424a622006-04-19 21:23:36 +00007181 if (savebuf == NULL || saved == FAIL || buf != curbuf
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007182 || move_lines(buf, savebuf) == FAIL)
7183 {
7184 EMSG2(_("E462: Could not prepare for reloading \"%s\""),
7185 buf->b_fname);
7186 saved = FAIL;
7187 }
7188 }
7189
7190 if (saved == OK)
7191 {
7192 curbuf->b_flags |= BF_CHECK_RO; /* check for RO again */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007193 keep_filetype = TRUE; /* don't detect 'filetype' */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007194 if (readfile(buf->b_ffname, buf->b_fname, (linenr_T)0,
7195 (linenr_T)0,
Bram Moolenaare13b9af2017-01-13 22:01:02 +01007196 (linenr_T)MAXLNUM, &ea, flags) != OK)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007197 {
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01007198#if defined(FEAT_EVAL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007199 if (!aborting())
7200#endif
7201 EMSG2(_("E321: Could not reload \"%s\""), buf->b_fname);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007202 if (savebuf != NULL && bufref_valid(&bufref) && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007203 {
7204 /* Put the text back from the save buffer. First
7205 * delete any lines that readfile() added. */
Bram Moolenaarb5aedf32017-03-12 18:23:53 +01007206 while (!BUFEMPTY())
Bram Moolenaar8424a622006-04-19 21:23:36 +00007207 if (ml_delete(buf->b_ml.ml_line_count, FALSE) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007208 break;
7209 (void)move_lines(savebuf, buf);
7210 }
7211 }
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007212 else if (buf == curbuf) /* "buf" still valid */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007213 {
7214 /* Mark the buffer as unmodified and free undo info. */
7215 unchanged(buf, TRUE);
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007216 if ((flags & READ_KEEP_UNDO) == 0)
7217 {
7218 u_blockfree(buf);
7219 u_clearall(buf);
7220 }
7221 else
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007222 {
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007223 /* Mark all undo states as changed. */
7224 u_unchanged(curbuf);
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007225 }
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007226 }
7227 }
7228 vim_free(ea.cmd);
7229
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007230 if (savebuf != NULL && bufref_valid(&bufref))
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007231 wipe_buffer(savebuf, FALSE);
7232
7233#ifdef FEAT_DIFF
7234 /* Invalidate diff info if necessary. */
Bram Moolenaar8424a622006-04-19 21:23:36 +00007235 diff_invalidate(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007236#endif
7237
7238 /* Restore the topline and cursor position and check it (lines may
7239 * have been removed). */
7240 if (old_topline > curbuf->b_ml.ml_line_count)
7241 curwin->w_topline = curbuf->b_ml.ml_line_count;
7242 else
7243 curwin->w_topline = old_topline;
7244 curwin->w_cursor = old_cursor;
7245 check_cursor();
7246 update_topline();
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007247 keep_filetype = FALSE;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007248#ifdef FEAT_FOLDING
7249 {
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007250 win_T *wp;
7251 tabpage_T *tp;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007252
7253 /* Update folds unless they are defined manually. */
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007254 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007255 if (wp->w_buffer == curwin->w_buffer
7256 && !foldmethodIsManual(wp))
7257 foldUpdateAll(wp);
7258 }
7259#endif
7260 /* If the mode didn't change and 'readonly' was set, keep the old
7261 * value; the user probably used the ":view" command. But don't
7262 * reset it, might have had a read error. */
7263 if (orig_mode == curbuf->b_orig_mode)
7264 curbuf->b_p_ro |= old_ro;
Bram Moolenaar52f85b72013-01-30 14:13:56 +01007265
7266 /* Modelines must override settings done by autocommands. */
7267 do_modelines(0);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007268 }
7269
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007270 /* restore curwin/curbuf and a few other things */
7271 aucmd_restbuf(&aco);
7272 /* Careful: autocommands may have made "buf" invalid! */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007273}
7274
Bram Moolenaar071d4272004-06-13 20:20:40 +00007275 void
Bram Moolenaar8767f522016-07-01 17:17:39 +02007276buf_store_time(buf_T *buf, stat_T *st, char_u *fname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007277{
7278 buf->b_mtime = (long)st->st_mtime;
Bram Moolenaar914703b2010-05-31 21:59:46 +02007279 buf->b_orig_size = st->st_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007280#ifdef HAVE_ST_MODE
7281 buf->b_orig_mode = (int)st->st_mode;
7282#else
7283 buf->b_orig_mode = mch_getperm(fname);
7284#endif
7285}
7286
7287/*
7288 * Adjust the line with missing eol, used for the next write.
7289 * Used for do_filter(), when the input lines for the filter are deleted.
7290 */
7291 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007292write_lnum_adjust(linenr_T offset)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007293{
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01007294 if (curbuf->b_no_eol_lnum != 0) /* only if there is a missing eol */
7295 curbuf->b_no_eol_lnum += offset;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007296}
7297
Bram Moolenaarda440d22016-01-16 21:27:23 +01007298#if defined(TEMPDIRNAMES) || defined(FEAT_EVAL) || defined(PROTO)
7299/*
7300 * Delete "name" and everything in it, recursively.
7301 * return 0 for succes, -1 if some file was not deleted.
7302 */
7303 int
7304delete_recursive(char_u *name)
7305{
7306 int result = 0;
7307 char_u **files;
7308 int file_count;
7309 int i;
7310 char_u *exp;
7311
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007312 /* A symbolic link to a directory itself is deleted, not the directory it
7313 * points to. */
7314 if (
Bram Moolenaar203258c2016-01-17 22:15:16 +01007315# if defined(UNIX) || defined(WIN32)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007316 mch_isrealdir(name)
Bram Moolenaar203258c2016-01-17 22:15:16 +01007317# else
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007318 mch_isdir(name)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007319# endif
7320 )
Bram Moolenaarda440d22016-01-16 21:27:23 +01007321 {
7322 vim_snprintf((char *)NameBuff, MAXPATHL, "%s/*", name);
7323 exp = vim_strsave(NameBuff);
7324 if (exp == NULL)
7325 return -1;
7326 if (gen_expand_wildcards(1, &exp, &file_count, &files,
Bram Moolenaar336bd622016-01-17 18:23:58 +01007327 EW_DIR|EW_FILE|EW_SILENT|EW_ALLLINKS|EW_DODOT|EW_EMPTYOK) == OK)
Bram Moolenaarda440d22016-01-16 21:27:23 +01007328 {
7329 for (i = 0; i < file_count; ++i)
7330 if (delete_recursive(files[i]) != 0)
7331 result = -1;
7332 FreeWild(file_count, files);
7333 }
7334 else
7335 result = -1;
7336 vim_free(exp);
7337 (void)mch_rmdir(name);
7338 }
7339 else
7340 result = mch_remove(name) == 0 ? 0 : -1;
7341
7342 return result;
7343}
7344#endif
7345
Bram Moolenaar071d4272004-06-13 20:20:40 +00007346#if defined(TEMPDIRNAMES) || defined(PROTO)
7347static long temp_count = 0; /* Temp filename counter. */
7348
7349/*
7350 * Delete the temp directory and all files it contains.
7351 */
7352 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007353vim_deltempdir(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007354{
Bram Moolenaar071d4272004-06-13 20:20:40 +00007355 if (vim_tempdir != NULL)
7356 {
Bram Moolenaarda440d22016-01-16 21:27:23 +01007357 /* remove the trailing path separator */
7358 gettail(vim_tempdir)[-1] = NUL;
7359 delete_recursive(vim_tempdir);
Bram Moolenaard23a8232018-02-10 18:45:26 +01007360 VIM_CLEAR(vim_tempdir);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007361 }
7362}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007363
7364/*
Bram Moolenaareaf03392009-11-17 11:08:52 +00007365 * Directory "tempdir" was created. Expand this name to a full path and put
7366 * it in "vim_tempdir". This avoids that using ":cd" would confuse us.
7367 * "tempdir" must be no longer than MAXPATHL.
7368 */
7369 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007370vim_settempdir(char_u *tempdir)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007371{
7372 char_u *buf;
7373
7374 buf = alloc((unsigned)MAXPATHL + 2);
7375 if (buf != NULL)
7376 {
7377 if (vim_FullName(tempdir, buf, MAXPATHL, FALSE) == FAIL)
7378 STRCPY(buf, tempdir);
Bram Moolenaara06ecab2016-07-16 14:47:36 +02007379 add_pathsep(buf);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007380 vim_tempdir = vim_strsave(buf);
7381 vim_free(buf);
7382 }
7383}
Bram Moolenaar4592dee2009-11-18 19:11:58 +00007384#endif
Bram Moolenaareaf03392009-11-17 11:08:52 +00007385
7386/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007387 * vim_tempname(): Return a unique name that can be used for a temp file.
7388 *
Bram Moolenaar76ae22f2016-06-13 20:00:29 +02007389 * The temp file is NOT guaranteed to be created. If "keep" is FALSE it is
7390 * guaranteed to NOT be created.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007391 *
7392 * The returned pointer is to allocated memory.
7393 * The returned pointer is NULL if no valid name was found.
7394 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007395 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007396vim_tempname(
7397 int extra_char UNUSED, /* char to use in the name instead of '?' */
7398 int keep UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007399{
7400#ifdef USE_TMPNAM
7401 char_u itmp[L_tmpnam]; /* use tmpnam() */
7402#else
7403 char_u itmp[TEMPNAMELEN];
7404#endif
7405
7406#ifdef TEMPDIRNAMES
7407 static char *(tempdirs[]) = {TEMPDIRNAMES};
7408 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007409# ifndef EEXIST
Bram Moolenaar8767f522016-07-01 17:17:39 +02007410 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007411# endif
7412
7413 /*
7414 * This will create a directory for private use by this instance of Vim.
7415 * This is done once, and the same directory is used for all temp files.
7416 * This method avoids security problems because of symlink attacks et al.
7417 * It's also a bit faster, because we only need to check for an existing
7418 * file when creating the directory and not for each temp file.
7419 */
7420 if (vim_tempdir == NULL)
7421 {
7422 /*
7423 * Try the entries in TEMPDIRNAMES to create the temp directory.
7424 */
Bram Moolenaar78a15312009-05-15 19:33:18 +00007425 for (i = 0; i < (int)(sizeof(tempdirs) / sizeof(char *)); ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007426 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007427# ifndef HAVE_MKDTEMP
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007428 size_t itmplen;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007429 long nr;
7430 long off;
7431# endif
7432
Bram Moolenaare1a61992015-12-03 21:02:27 +01007433 /* Expand $TMP, leave room for "/v1100000/999999999".
7434 * Skip the directory check if the expansion fails. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007435 expand_env((char_u *)tempdirs[i], itmp, TEMPNAMELEN - 20);
Bram Moolenaare1a61992015-12-03 21:02:27 +01007436 if (itmp[0] != '$' && mch_isdir(itmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007437 {
Bram Moolenaare1a61992015-12-03 21:02:27 +01007438 /* directory exists */
Bram Moolenaara06ecab2016-07-16 14:47:36 +02007439 add_pathsep(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007440
Bram Moolenaareaf03392009-11-17 11:08:52 +00007441# ifdef HAVE_MKDTEMP
Bram Moolenaar35d88f42016-06-04 14:52:00 +02007442 {
7443# if defined(UNIX) || defined(VMS)
7444 /* Make sure the umask doesn't remove the executable bit.
7445 * "repl" has been reported to use "177". */
7446 mode_t umask_save = umask(077);
7447# endif
7448 /* Leave room for filename */
7449 STRCAT(itmp, "vXXXXXX");
7450 if (mkdtemp((char *)itmp) != NULL)
7451 vim_settempdir(itmp);
7452# if defined(UNIX) || defined(VMS)
7453 (void)umask(umask_save);
7454# endif
7455 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007456# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007457 /* Get an arbitrary number of up to 6 digits. When it's
7458 * unlikely that it already exists it will be faster,
7459 * otherwise it doesn't matter. The use of mkdir() avoids any
7460 * security problems because of the predictable number. */
7461 nr = (mch_get_pid() + (long)time(NULL)) % 1000000L;
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007462 itmplen = STRLEN(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007463
7464 /* Try up to 10000 different values until we find a name that
7465 * doesn't exist. */
7466 for (off = 0; off < 10000L; ++off)
7467 {
7468 int r;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007469# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007470 mode_t umask_save;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007471# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007472
Bram Moolenaareaf03392009-11-17 11:08:52 +00007473 sprintf((char *)itmp + itmplen, "v%ld", nr + off);
7474# ifndef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007475 /* If mkdir() does not set errno to EEXIST, check for
7476 * existing file here. There is a race condition then,
7477 * although it's fail-safe. */
7478 if (mch_stat((char *)itmp, &st) >= 0)
7479 continue;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007480# endif
7481# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007482 /* Make sure the umask doesn't remove the executable bit.
7483 * "repl" has been reported to use "177". */
7484 umask_save = umask(077);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007485# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007486 r = vim_mkdir(itmp, 0700);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007487# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007488 (void)umask(umask_save);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007489# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007490 if (r == 0)
7491 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007492 vim_settempdir(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007493 break;
7494 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007495# ifdef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007496 /* If the mkdir() didn't fail because the file/dir exists,
7497 * we probably can't create any dir here, try another
7498 * place. */
7499 if (errno != EEXIST)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007500# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007501 break;
7502 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007503# endif /* HAVE_MKDTEMP */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007504 if (vim_tempdir != NULL)
7505 break;
7506 }
7507 }
7508 }
7509
7510 if (vim_tempdir != NULL)
7511 {
7512 /* There is no need to check if the file exists, because we own the
7513 * directory and nobody else creates a file in it. */
7514 sprintf((char *)itmp, "%s%ld", vim_tempdir, temp_count++);
7515 return vim_strsave(itmp);
7516 }
7517
7518 return NULL;
7519
7520#else /* TEMPDIRNAMES */
7521
7522# ifdef WIN3264
7523 char szTempFile[_MAX_PATH + 1];
7524 char buf4[4];
7525 char_u *retval;
7526 char_u *p;
7527
7528 STRCPY(itmp, "");
7529 if (GetTempPath(_MAX_PATH, szTempFile) == 0)
Bram Moolenaarb1891912011-02-09 14:47:03 +01007530 {
7531 szTempFile[0] = '.'; /* GetTempPath() failed, use current dir */
7532 szTempFile[1] = NUL;
7533 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007534 strcpy(buf4, "VIM");
7535 buf4[2] = extra_char; /* make it "VIa", "VIb", etc. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007536 if (GetTempFileName(szTempFile, buf4, 0, (LPSTR)itmp) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007537 return NULL;
Bram Moolenaare5c421c2015-03-31 13:33:08 +02007538 if (!keep)
7539 /* GetTempFileName() will create the file, we don't want that */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007540 (void)DeleteFile((LPSTR)itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007541
7542 /* Backslashes in a temp file name cause problems when filtering with
7543 * "sh". NOTE: This also checks 'shellcmdflag' to help those people who
7544 * didn't set 'shellslash'. */
7545 retval = vim_strsave(itmp);
7546 if (*p_shcf == '-' || p_ssl)
7547 for (p = retval; *p; ++p)
7548 if (*p == '\\')
7549 *p = '/';
7550 return retval;
7551
7552# else /* WIN3264 */
7553
7554# ifdef USE_TMPNAM
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007555 char_u *p;
7556
Bram Moolenaar071d4272004-06-13 20:20:40 +00007557 /* tmpnam() will make its own name */
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007558 p = tmpnam((char *)itmp);
7559 if (p == NULL || *p == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007560 return NULL;
7561# else
7562 char_u *p;
7563
7564# ifdef VMS_TEMPNAM
7565 /* mktemp() is not working on VMS. It seems to be
7566 * a do-nothing function. Therefore we use tempnam().
7567 */
7568 sprintf((char *)itmp, "VIM%c", extra_char);
7569 p = (char_u *)tempnam("tmp:", (char *)itmp);
7570 if (p != NULL)
7571 {
Bram Moolenaar206f0112014-03-12 16:51:55 +01007572 /* VMS will use '.LIS' if we don't explicitly specify an extension,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007573 * and VIM will then be unable to find the file later */
7574 STRCPY(itmp, p);
7575 STRCAT(itmp, ".txt");
7576 free(p);
7577 }
7578 else
7579 return NULL;
7580# else
7581 STRCPY(itmp, TEMPNAME);
7582 if ((p = vim_strchr(itmp, '?')) != NULL)
7583 *p = extra_char;
7584 if (mktemp((char *)itmp) == NULL)
7585 return NULL;
7586# endif
7587# endif
7588
7589 return vim_strsave(itmp);
7590# endif /* WIN3264 */
7591#endif /* TEMPDIRNAMES */
7592}
7593
7594#if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
7595/*
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02007596 * Convert all backslashes in fname to forward slashes in-place, unless when
7597 * it looks like a URL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007598 */
7599 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007600forward_slash(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007601{
7602 char_u *p;
7603
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02007604 if (path_with_url(fname))
7605 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007606 for (p = fname; *p != NUL; ++p)
7607# ifdef FEAT_MBYTE
7608 /* The Big5 encoding can have '\' in the trail byte. */
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00007609 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007610 ++p;
7611 else
7612# endif
7613 if (*p == '\\')
7614 *p = '/';
7615}
7616#endif
7617
7618
7619/*
7620 * Code for automatic commands.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007621 */
7622
Bram Moolenaar071d4272004-06-13 20:20:40 +00007623/*
7624 * The autocommands are stored in a list for each event.
7625 * Autocommands for the same pattern, that are consecutive, are joined
7626 * together, to avoid having to match the pattern too often.
7627 * The result is an array of Autopat lists, which point to AutoCmd lists:
7628 *
Bram Moolenaar462455e2017-11-10 21:53:11 +01007629 * last_autopat[0] -----------------------------+
7630 * V
Bram Moolenaar071d4272004-06-13 20:20:40 +00007631 * first_autopat[0] --> Autopat.next --> Autopat.next --> NULL
7632 * Autopat.cmds Autopat.cmds
7633 * | |
7634 * V V
7635 * AutoCmd.next AutoCmd.next
7636 * | |
7637 * V V
7638 * AutoCmd.next NULL
7639 * |
7640 * V
7641 * NULL
7642 *
Bram Moolenaar462455e2017-11-10 21:53:11 +01007643 * last_autopat[1] --------+
7644 * V
Bram Moolenaar071d4272004-06-13 20:20:40 +00007645 * first_autopat[1] --> Autopat.next --> NULL
7646 * Autopat.cmds
7647 * |
7648 * V
7649 * AutoCmd.next
7650 * |
7651 * V
7652 * NULL
7653 * etc.
7654 *
7655 * The order of AutoCmds is important, this is the order in which they were
7656 * defined and will have to be executed.
7657 */
7658typedef struct AutoCmd
7659{
7660 char_u *cmd; /* The command to be executed (NULL
7661 when command has been removed) */
7662 char nested; /* If autocommands nest here */
7663 char last; /* last command in list */
7664#ifdef FEAT_EVAL
7665 scid_T scriptID; /* script ID where defined */
7666#endif
7667 struct AutoCmd *next; /* Next AutoCmd in list */
7668} AutoCmd;
7669
7670typedef struct AutoPat
7671{
Bram Moolenaar462455e2017-11-10 21:53:11 +01007672 struct AutoPat *next; /* next AutoPat in AutoPat list; MUST
7673 * be the first entry */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007674 char_u *pat; /* pattern as typed (NULL when pattern
7675 has been removed) */
Bram Moolenaar748bf032005-02-02 23:04:36 +00007676 regprog_T *reg_prog; /* compiled regprog for pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007677 AutoCmd *cmds; /* list of commands to do */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007678 int group; /* group ID */
7679 int patlen; /* strlen() of pat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007680 int buflocal_nr; /* !=0 for buffer-local AutoPat */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007681 char allow_dirs; /* Pattern may match whole path */
7682 char last; /* last pattern for apply_autocmds() */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007683} AutoPat;
7684
7685static struct event_name
7686{
7687 char *name; /* event name */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007688 event_T event; /* event number */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007689} event_names[] =
7690{
7691 {"BufAdd", EVENT_BUFADD},
7692 {"BufCreate", EVENT_BUFADD},
7693 {"BufDelete", EVENT_BUFDELETE},
7694 {"BufEnter", EVENT_BUFENTER},
7695 {"BufFilePost", EVENT_BUFFILEPOST},
7696 {"BufFilePre", EVENT_BUFFILEPRE},
7697 {"BufHidden", EVENT_BUFHIDDEN},
7698 {"BufLeave", EVENT_BUFLEAVE},
7699 {"BufNew", EVENT_BUFNEW},
7700 {"BufNewFile", EVENT_BUFNEWFILE},
7701 {"BufRead", EVENT_BUFREADPOST},
7702 {"BufReadCmd", EVENT_BUFREADCMD},
7703 {"BufReadPost", EVENT_BUFREADPOST},
7704 {"BufReadPre", EVENT_BUFREADPRE},
7705 {"BufUnload", EVENT_BUFUNLOAD},
7706 {"BufWinEnter", EVENT_BUFWINENTER},
7707 {"BufWinLeave", EVENT_BUFWINLEAVE},
7708 {"BufWipeout", EVENT_BUFWIPEOUT},
7709 {"BufWrite", EVENT_BUFWRITEPRE},
7710 {"BufWritePost", EVENT_BUFWRITEPOST},
7711 {"BufWritePre", EVENT_BUFWRITEPRE},
7712 {"BufWriteCmd", EVENT_BUFWRITECMD},
Bram Moolenaar153b7042018-01-31 15:48:32 +01007713 {"CmdlineChanged", EVENT_CMDLINECHANGED},
Bram Moolenaarfafcf0d2017-10-19 18:35:51 +02007714 {"CmdlineEnter", EVENT_CMDLINEENTER},
7715 {"CmdlineLeave", EVENT_CMDLINELEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007716 {"CmdwinEnter", EVENT_CMDWINENTER},
7717 {"CmdwinLeave", EVENT_CMDWINLEAVE},
Bram Moolenaard5005162014-08-22 23:05:54 +02007718 {"CmdUndefined", EVENT_CMDUNDEFINED},
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007719 {"ColorScheme", EVENT_COLORSCHEME},
Bram Moolenaarcfa3cae2012-07-10 17:14:56 +02007720 {"CompleteDone", EVENT_COMPLETEDONE},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007721 {"CursorHold", EVENT_CURSORHOLD},
7722 {"CursorHoldI", EVENT_CURSORHOLDI},
7723 {"CursorMoved", EVENT_CURSORMOVED},
7724 {"CursorMovedI", EVENT_CURSORMOVEDI},
Bram Moolenaarb7407d32018-02-03 17:36:27 +01007725 {"DirChanged", EVENT_DIRCHANGED},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007726 {"EncodingChanged", EVENT_ENCODINGCHANGED},
Bram Moolenaar12a96de2018-03-11 14:44:18 +01007727 {"ExitPre", EVENT_EXITPRE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007728 {"FileEncoding", EVENT_ENCODINGCHANGED},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007729 {"FileAppendPost", EVENT_FILEAPPENDPOST},
7730 {"FileAppendPre", EVENT_FILEAPPENDPRE},
7731 {"FileAppendCmd", EVENT_FILEAPPENDCMD},
7732 {"FileChangedShell",EVENT_FILECHANGEDSHELL},
Bram Moolenaar56718732006-03-15 22:53:57 +00007733 {"FileChangedShellPost",EVENT_FILECHANGEDSHELLPOST},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007734 {"FileChangedRO", EVENT_FILECHANGEDRO},
7735 {"FileReadPost", EVENT_FILEREADPOST},
7736 {"FileReadPre", EVENT_FILEREADPRE},
7737 {"FileReadCmd", EVENT_FILEREADCMD},
7738 {"FileType", EVENT_FILETYPE},
7739 {"FileWritePost", EVENT_FILEWRITEPOST},
7740 {"FileWritePre", EVENT_FILEWRITEPRE},
7741 {"FileWriteCmd", EVENT_FILEWRITECMD},
7742 {"FilterReadPost", EVENT_FILTERREADPOST},
7743 {"FilterReadPre", EVENT_FILTERREADPRE},
7744 {"FilterWritePost", EVENT_FILTERWRITEPOST},
7745 {"FilterWritePre", EVENT_FILTERWRITEPRE},
7746 {"FocusGained", EVENT_FOCUSGAINED},
7747 {"FocusLost", EVENT_FOCUSLOST},
7748 {"FuncUndefined", EVENT_FUNCUNDEFINED},
7749 {"GUIEnter", EVENT_GUIENTER},
Bram Moolenaar265e5072006-08-29 16:13:22 +00007750 {"GUIFailed", EVENT_GUIFAILED},
Bram Moolenaar843ee412004-06-30 16:16:41 +00007751 {"InsertChange", EVENT_INSERTCHANGE},
7752 {"InsertEnter", EVENT_INSERTENTER},
7753 {"InsertLeave", EVENT_INSERTLEAVE},
Bram Moolenaare659c952011-05-19 17:25:41 +02007754 {"InsertCharPre", EVENT_INSERTCHARPRE},
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00007755 {"MenuPopup", EVENT_MENUPOPUP},
Bram Moolenaar53744302015-07-17 17:38:22 +02007756 {"OptionSet", EVENT_OPTIONSET},
Bram Moolenaar7c626922005-02-07 22:01:03 +00007757 {"QuickFixCmdPost", EVENT_QUICKFIXCMDPOST},
7758 {"QuickFixCmdPre", EVENT_QUICKFIXCMDPRE},
Bram Moolenaar3b53dfb2012-06-06 18:03:07 +02007759 {"QuitPre", EVENT_QUITPRE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007760 {"RemoteReply", EVENT_REMOTEREPLY},
Bram Moolenaar9372a112005-12-06 19:59:18 +00007761 {"SessionLoadPost", EVENT_SESSIONLOADPOST},
Bram Moolenaar5c4bab02006-03-10 21:37:46 +00007762 {"ShellCmdPost", EVENT_SHELLCMDPOST},
7763 {"ShellFilterPost", EVENT_SHELLFILTERPOST},
Bram Moolenaara2031822006-03-07 22:29:51 +00007764 {"SourcePre", EVENT_SOURCEPRE},
Bram Moolenaar8dd1aa52007-01-16 20:33:19 +00007765 {"SourceCmd", EVENT_SOURCECMD},
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00007766 {"SpellFileMissing",EVENT_SPELLFILEMISSING},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007767 {"StdinReadPost", EVENT_STDINREADPOST},
7768 {"StdinReadPre", EVENT_STDINREADPRE},
Bram Moolenaarb815dac2005-12-07 20:59:24 +00007769 {"SwapExists", EVENT_SWAPEXISTS},
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00007770 {"Syntax", EVENT_SYNTAX},
Bram Moolenaarc917da42016-07-19 22:31:36 +02007771 {"TabNew", EVENT_TABNEW},
Bram Moolenaar12c11d52016-07-19 23:13:03 +02007772 {"TabClosed", EVENT_TABCLOSED},
Bram Moolenaar70836c82006-02-20 21:28:49 +00007773 {"TabEnter", EVENT_TABENTER},
7774 {"TabLeave", EVENT_TABLEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007775 {"TermChanged", EVENT_TERMCHANGED},
Bram Moolenaarb852c3e2018-03-11 16:55:36 +01007776 {"TerminalOpen", EVENT_TERMINALOPEN},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007777 {"TermResponse", EVENT_TERMRESPONSE},
Bram Moolenaar186628f2013-03-19 13:33:23 +01007778 {"TextChanged", EVENT_TEXTCHANGED},
7779 {"TextChangedI", EVENT_TEXTCHANGEDI},
Bram Moolenaar5a093432018-02-10 18:15:19 +01007780 {"TextChangedP", EVENT_TEXTCHANGEDP},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007781 {"User", EVENT_USER},
7782 {"VimEnter", EVENT_VIMENTER},
7783 {"VimLeave", EVENT_VIMLEAVE},
7784 {"VimLeavePre", EVENT_VIMLEAVEPRE},
Bram Moolenaarc917da42016-07-19 22:31:36 +02007785 {"WinNew", EVENT_WINNEW},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007786 {"WinEnter", EVENT_WINENTER},
7787 {"WinLeave", EVENT_WINLEAVE},
Bram Moolenaar56718732006-03-15 22:53:57 +00007788 {"VimResized", EVENT_VIMRESIZED},
Bram Moolenaar7e1652c2017-12-16 18:27:02 +01007789 {"TextYankPost", EVENT_TEXTYANKPOST},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007790 {NULL, (event_T)0}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007791};
7792
7793static AutoPat *first_autopat[NUM_EVENTS] =
7794{
7795 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7796 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7797 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7798 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00007799 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaar53744302015-07-17 17:38:22 +02007800 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007801};
7802
Bram Moolenaar462455e2017-11-10 21:53:11 +01007803static AutoPat *last_autopat[NUM_EVENTS] =
7804{
7805 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7806 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7807 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7808 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7809 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7810 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
7811};
7812
Bram Moolenaar071d4272004-06-13 20:20:40 +00007813/*
7814 * struct used to keep status while executing autocommands for an event.
7815 */
7816typedef struct AutoPatCmd
7817{
7818 AutoPat *curpat; /* next AutoPat to examine */
7819 AutoCmd *nextcmd; /* next AutoCmd to execute */
7820 int group; /* group being used */
7821 char_u *fname; /* fname to match with */
7822 char_u *sfname; /* sfname to match with */
7823 char_u *tail; /* tail of fname */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007824 event_T event; /* current event */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007825 int arg_bufnr; /* initially equal to <abuf>, set to zero when
7826 buf is deleted */
7827 struct AutoPatCmd *next; /* chain of active apc-s for auto-invalidation*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00007828} AutoPatCmd;
7829
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007830static AutoPatCmd *active_apc_list = NULL; /* stack of active autocommands */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007831
Bram Moolenaar071d4272004-06-13 20:20:40 +00007832/*
7833 * augroups stores a list of autocmd group names.
7834 */
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007835static garray_T augroups = {0, 0, sizeof(char_u *), 10, NULL};
Bram Moolenaar071d4272004-06-13 20:20:40 +00007836#define AUGROUP_NAME(i) (((char_u **)augroups.ga_data)[i])
Bram Moolenaarb62cc362016-09-03 16:43:53 +02007837/* use get_deleted_augroup() to get this */
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02007838static char_u *deleted_augroup = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007839
7840/*
7841 * The ID of the current group. Group 0 is the default one.
7842 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007843static int current_augroup = AUGROUP_DEFAULT;
7844
7845static int au_need_clean = FALSE; /* need to delete marked patterns */
7846
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007847static void show_autocmd(AutoPat *ap, event_T event);
7848static void au_remove_pat(AutoPat *ap);
7849static void au_remove_cmds(AutoPat *ap);
7850static void au_cleanup(void);
7851static int au_new_group(char_u *name);
7852static void au_del_group(char_u *name);
7853static event_T event_name2nr(char_u *start, char_u **end);
7854static char_u *event_nr2name(event_T event);
7855static char_u *find_end_event(char_u *arg, int have_group);
7856static int event_ignored(event_T event);
7857static int au_get_grouparg(char_u **argp);
7858static int do_autocmd_event(event_T event, char_u *pat, int nested, char_u *cmd, int forceit, int group);
7859static int apply_autocmds_group(event_T event, char_u *fname, char_u *fname_io, int force, int group, buf_T *buf, exarg_T *eap);
7860static void auto_next_pat(AutoPatCmd *apc, int stop_at_last);
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007861static 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 +00007862
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007863
Bram Moolenaar754b5602006-02-09 23:53:20 +00007864static event_T last_event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007865static int last_group;
Bram Moolenaar78ab3312007-09-29 12:16:41 +00007866static int autocmd_blocked = 0; /* block all autocmds */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007867
Bram Moolenaarb62cc362016-09-03 16:43:53 +02007868 static char_u *
7869get_deleted_augroup(void)
7870{
7871 if (deleted_augroup == NULL)
7872 deleted_augroup = (char_u *)_("--Deleted--");
7873 return deleted_augroup;
7874}
7875
Bram Moolenaar071d4272004-06-13 20:20:40 +00007876/*
7877 * Show the autocommands for one AutoPat.
7878 */
7879 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007880show_autocmd(AutoPat *ap, event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007881{
7882 AutoCmd *ac;
7883
7884 /* Check for "got_int" (here and at various places below), which is set
7885 * when "q" has been hit for the "--more--" prompt */
7886 if (got_int)
7887 return;
7888 if (ap->pat == NULL) /* pattern has been removed */
7889 return;
7890
7891 msg_putchar('\n');
7892 if (got_int)
7893 return;
7894 if (event != last_event || ap->group != last_group)
7895 {
7896 if (ap->group != AUGROUP_DEFAULT)
7897 {
7898 if (AUGROUP_NAME(ap->group) == NULL)
Bram Moolenaar8820b482017-03-16 17:23:31 +01007899 msg_puts_attr(get_deleted_augroup(), HL_ATTR(HLF_E));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007900 else
Bram Moolenaar8820b482017-03-16 17:23:31 +01007901 msg_puts_attr(AUGROUP_NAME(ap->group), HL_ATTR(HLF_T));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007902 msg_puts((char_u *)" ");
7903 }
Bram Moolenaar8820b482017-03-16 17:23:31 +01007904 msg_puts_attr(event_nr2name(event), HL_ATTR(HLF_T));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007905 last_event = event;
7906 last_group = ap->group;
7907 msg_putchar('\n');
7908 if (got_int)
7909 return;
7910 }
7911 msg_col = 4;
7912 msg_outtrans(ap->pat);
7913
7914 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7915 {
7916 if (ac->cmd != NULL) /* skip removed commands */
7917 {
7918 if (msg_col >= 14)
7919 msg_putchar('\n');
7920 msg_col = 14;
7921 if (got_int)
7922 return;
7923 msg_outtrans(ac->cmd);
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00007924#ifdef FEAT_EVAL
7925 if (p_verbose > 0)
7926 last_set_msg(ac->scriptID);
7927#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007928 if (got_int)
7929 return;
7930 if (ac->next != NULL)
7931 {
7932 msg_putchar('\n');
7933 if (got_int)
7934 return;
7935 }
7936 }
7937 }
7938}
7939
7940/*
7941 * Mark an autocommand pattern for deletion.
7942 */
7943 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007944au_remove_pat(AutoPat *ap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007945{
Bram Moolenaard23a8232018-02-10 18:45:26 +01007946 VIM_CLEAR(ap->pat);
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007947 ap->buflocal_nr = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007948 au_need_clean = TRUE;
7949}
7950
7951/*
7952 * Mark all commands for a pattern for deletion.
7953 */
7954 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007955au_remove_cmds(AutoPat *ap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007956{
7957 AutoCmd *ac;
7958
7959 for (ac = ap->cmds; ac != NULL; ac = ac->next)
Bram Moolenaard23a8232018-02-10 18:45:26 +01007960 VIM_CLEAR(ac->cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007961 au_need_clean = TRUE;
7962}
7963
7964/*
7965 * Cleanup autocommands and patterns that have been deleted.
7966 * This is only done when not executing autocommands.
7967 */
7968 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007969au_cleanup(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007970{
7971 AutoPat *ap, **prev_ap;
7972 AutoCmd *ac, **prev_ac;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007973 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007974
7975 if (autocmd_busy || !au_need_clean)
7976 return;
7977
7978 /* loop over all events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007979 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7980 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007981 {
7982 /* loop over all autocommand patterns */
7983 prev_ap = &(first_autopat[(int)event]);
7984 for (ap = *prev_ap; ap != NULL; ap = *prev_ap)
7985 {
7986 /* loop over all commands for this pattern */
7987 prev_ac = &(ap->cmds);
7988 for (ac = *prev_ac; ac != NULL; ac = *prev_ac)
7989 {
7990 /* remove the command if the pattern is to be deleted or when
7991 * the command has been marked for deletion */
7992 if (ap->pat == NULL || ac->cmd == NULL)
7993 {
7994 *prev_ac = ac->next;
7995 vim_free(ac->cmd);
7996 vim_free(ac);
7997 }
7998 else
7999 prev_ac = &(ac->next);
8000 }
8001
8002 /* remove the pattern if it has been marked for deletion */
8003 if (ap->pat == NULL)
8004 {
Bram Moolenaar462455e2017-11-10 21:53:11 +01008005 if (ap->next == NULL)
8006 {
8007 if (prev_ap == &(first_autopat[(int)event]))
8008 last_autopat[(int)event] = NULL;
8009 else
8010 /* this depends on the "next" field being the first in
8011 * the struct */
8012 last_autopat[(int)event] = (AutoPat *)prev_ap;
8013 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008014 *prev_ap = ap->next;
Bram Moolenaar473de612013-06-08 18:19:48 +02008015 vim_regfree(ap->reg_prog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008016 vim_free(ap);
8017 }
8018 else
8019 prev_ap = &(ap->next);
8020 }
8021 }
8022
8023 au_need_clean = FALSE;
8024}
8025
8026/*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008027 * Called when buffer is freed, to remove/invalidate related buffer-local
8028 * autocmds.
8029 */
8030 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008031aubuflocal_remove(buf_T *buf)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008032{
8033 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008034 event_T event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008035 AutoPatCmd *apc;
8036
8037 /* invalidate currently executing autocommands */
8038 for (apc = active_apc_list; apc; apc = apc->next)
8039 if (buf->b_fnum == apc->arg_bufnr)
8040 apc->arg_bufnr = 0;
8041
8042 /* invalidate buflocals looping through events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008043 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8044 event = (event_T)((int)event + 1))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008045 /* loop over all autocommand patterns */
8046 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8047 if (ap->buflocal_nr == buf->b_fnum)
8048 {
8049 au_remove_pat(ap);
8050 if (p_verbose >= 6)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00008051 {
8052 verbose_enter();
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008053 smsg((char_u *)
8054 _("auto-removing autocommand: %s <buffer=%d>"),
8055 event_nr2name(event), buf->b_fnum);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00008056 verbose_leave();
8057 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008058 }
8059 au_cleanup();
8060}
8061
8062/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008063 * Add an autocmd group name.
8064 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
8065 */
8066 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008067au_new_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008068{
8069 int i;
8070
8071 i = au_find_group(name);
8072 if (i == AUGROUP_ERROR) /* the group doesn't exist yet, add it */
8073 {
8074 /* First try using a free entry. */
8075 for (i = 0; i < augroups.ga_len; ++i)
8076 if (AUGROUP_NAME(i) == NULL)
8077 break;
8078 if (i == augroups.ga_len && ga_grow(&augroups, 1) == FAIL)
8079 return AUGROUP_ERROR;
8080
8081 AUGROUP_NAME(i) = vim_strsave(name);
8082 if (AUGROUP_NAME(i) == NULL)
8083 return AUGROUP_ERROR;
8084 if (i == augroups.ga_len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008085 ++augroups.ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008086 }
8087
8088 return i;
8089}
8090
8091 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008092au_del_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008093{
8094 int i;
8095
8096 i = au_find_group(name);
8097 if (i == AUGROUP_ERROR) /* the group doesn't exist */
8098 EMSG2(_("E367: No such group: \"%s\""), name);
Bram Moolenaarde653f02016-09-03 16:59:06 +02008099 else if (i == current_augroup)
8100 EMSG(_("E936: Cannot delete the current group"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008101 else
8102 {
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008103 event_T event;
8104 AutoPat *ap;
8105 int in_use = FALSE;
8106
8107 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8108 event = (event_T)((int)event + 1))
8109 {
8110 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
Bram Moolenaar5c809082016-09-01 16:21:48 +02008111 if (ap->group == i && ap->pat != NULL)
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008112 {
8113 give_warning((char_u *)_("W19: Deleting augroup that is still in use"), TRUE);
8114 in_use = TRUE;
8115 event = NUM_EVENTS;
8116 break;
8117 }
8118 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008119 vim_free(AUGROUP_NAME(i));
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008120 if (in_use)
8121 {
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008122 AUGROUP_NAME(i) = get_deleted_augroup();
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008123 }
8124 else
8125 AUGROUP_NAME(i) = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008126 }
8127}
8128
8129/*
8130 * Find the ID of an autocmd group name.
8131 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
8132 */
8133 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008134au_find_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008135{
8136 int i;
8137
8138 for (i = 0; i < augroups.ga_len; ++i)
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008139 if (AUGROUP_NAME(i) != NULL && AUGROUP_NAME(i) != get_deleted_augroup()
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008140 && STRCMP(AUGROUP_NAME(i), name) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008141 return i;
8142 return AUGROUP_ERROR;
8143}
8144
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008145/*
8146 * Return TRUE if augroup "name" exists.
8147 */
8148 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008149au_has_group(char_u *name)
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008150{
8151 return au_find_group(name) != AUGROUP_ERROR;
8152}
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008153
Bram Moolenaar071d4272004-06-13 20:20:40 +00008154/*
8155 * ":augroup {name}".
8156 */
8157 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008158do_augroup(char_u *arg, int del_group)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008159{
8160 int i;
8161
8162 if (del_group)
8163 {
8164 if (*arg == NUL)
8165 EMSG(_(e_argreq));
8166 else
8167 au_del_group(arg);
8168 }
8169 else if (STRICMP(arg, "end") == 0) /* ":aug end": back to group 0 */
8170 current_augroup = AUGROUP_DEFAULT;
8171 else if (*arg) /* ":aug xxx": switch to group xxx */
8172 {
8173 i = au_new_group(arg);
8174 if (i != AUGROUP_ERROR)
8175 current_augroup = i;
8176 }
8177 else /* ":aug": list the group names */
8178 {
8179 msg_start();
8180 for (i = 0; i < augroups.ga_len; ++i)
8181 {
8182 if (AUGROUP_NAME(i) != NULL)
8183 {
8184 msg_puts(AUGROUP_NAME(i));
8185 msg_puts((char_u *)" ");
8186 }
8187 }
8188 msg_clr_eos();
8189 msg_end();
8190 }
8191}
8192
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008193#if defined(EXITFREE) || defined(PROTO)
8194 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008195free_all_autocmds(void)
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008196{
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008197 int i;
8198 char_u *s;
8199
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008200 for (current_augroup = -1; current_augroup < augroups.ga_len;
8201 ++current_augroup)
8202 do_autocmd((char_u *)"", TRUE);
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008203
8204 for (i = 0; i < augroups.ga_len; ++i)
8205 {
8206 s = ((char_u **)(augroups.ga_data))[i];
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008207 if (s != get_deleted_augroup())
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008208 vim_free(s);
8209 }
8210 ga_clear(&augroups);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008211}
8212#endif
8213
Bram Moolenaar071d4272004-06-13 20:20:40 +00008214/*
8215 * Return the event number for event name "start".
8216 * Return NUM_EVENTS if the event name was not found.
8217 * Return a pointer to the next event name in "end".
8218 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008219 static event_T
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008220event_name2nr(char_u *start, char_u **end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008221{
8222 char_u *p;
8223 int i;
8224 int len;
8225
Bram Moolenaare99e8442016-07-26 20:43:40 +02008226 /* the event name ends with end of line, '|', a blank or a comma */
Bram Moolenaar1c465442017-03-12 20:10:05 +01008227 for (p = start; *p && !VIM_ISWHITE(*p) && *p != ',' && *p != '|'; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008228 ;
8229 for (i = 0; event_names[i].name != NULL; ++i)
8230 {
8231 len = (int)STRLEN(event_names[i].name);
8232 if (len == p - start && STRNICMP(event_names[i].name, start, len) == 0)
8233 break;
8234 }
8235 if (*p == ',')
8236 ++p;
8237 *end = p;
8238 if (event_names[i].name == NULL)
8239 return NUM_EVENTS;
8240 return event_names[i].event;
8241}
8242
8243/*
8244 * Return the name for event "event".
8245 */
8246 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008247event_nr2name(event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008248{
8249 int i;
8250
8251 for (i = 0; event_names[i].name != NULL; ++i)
8252 if (event_names[i].event == event)
8253 return (char_u *)event_names[i].name;
8254 return (char_u *)"Unknown";
8255}
8256
8257/*
8258 * Scan over the events. "*" stands for all events.
8259 */
8260 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008261find_end_event(
8262 char_u *arg,
8263 int have_group) /* TRUE when group name was found */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008264{
8265 char_u *pat;
8266 char_u *p;
8267
8268 if (*arg == '*')
8269 {
Bram Moolenaar1c465442017-03-12 20:10:05 +01008270 if (arg[1] && !VIM_ISWHITE(arg[1]))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008271 {
8272 EMSG2(_("E215: Illegal character after *: %s"), arg);
8273 return NULL;
8274 }
8275 pat = arg + 1;
8276 }
8277 else
8278 {
Bram Moolenaar1c465442017-03-12 20:10:05 +01008279 for (pat = arg; *pat && *pat != '|' && !VIM_ISWHITE(*pat); pat = p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008280 {
8281 if ((int)event_name2nr(pat, &p) >= (int)NUM_EVENTS)
8282 {
8283 if (have_group)
8284 EMSG2(_("E216: No such event: %s"), pat);
8285 else
8286 EMSG2(_("E216: No such group or event: %s"), pat);
8287 return NULL;
8288 }
8289 }
8290 }
8291 return pat;
8292}
8293
8294/*
8295 * Return TRUE if "event" is included in 'eventignore'.
8296 */
8297 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008298event_ignored(event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008299{
8300 char_u *p = p_ei;
8301
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008302 while (*p != NUL)
8303 {
8304 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8305 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008306 if (event_name2nr(p, &p) == event)
8307 return TRUE;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008308 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008309
8310 return FALSE;
8311}
8312
8313/*
8314 * Return OK when the contents of p_ei is valid, FAIL otherwise.
8315 */
8316 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008317check_ei(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008318{
8319 char_u *p = p_ei;
8320
Bram Moolenaar071d4272004-06-13 20:20:40 +00008321 while (*p)
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008322 {
8323 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8324 {
8325 p += 3;
8326 if (*p == ',')
8327 ++p;
8328 }
8329 else if (event_name2nr(p, &p) == NUM_EVENTS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008330 return FAIL;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008331 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008332
8333 return OK;
8334}
8335
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008336# if defined(FEAT_SYN_HL) || defined(PROTO)
8337
8338/*
8339 * Add "what" to 'eventignore' to skip loading syntax highlighting for every
8340 * buffer loaded into the window. "what" must start with a comma.
8341 * Returns the old value of 'eventignore' in allocated memory.
8342 */
8343 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008344au_event_disable(char *what)
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008345{
8346 char_u *new_ei;
8347 char_u *save_ei;
8348
8349 save_ei = vim_strsave(p_ei);
8350 if (save_ei != NULL)
8351 {
Bram Moolenaara5792f52005-11-23 21:25:05 +00008352 new_ei = vim_strnsave(p_ei, (int)(STRLEN(p_ei) + STRLEN(what)));
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008353 if (new_ei != NULL)
8354 {
Bram Moolenaar8cac9fd2010-03-02 12:48:05 +01008355 if (*what == ',' && *p_ei == NUL)
8356 STRCPY(new_ei, what + 1);
8357 else
8358 STRCAT(new_ei, what);
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008359 set_string_option_direct((char_u *)"ei", -1, new_ei,
8360 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008361 vim_free(new_ei);
8362 }
8363 }
8364 return save_ei;
8365}
8366
8367 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008368au_event_restore(char_u *old_ei)
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008369{
8370 if (old_ei != NULL)
8371 {
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008372 set_string_option_direct((char_u *)"ei", -1, old_ei,
8373 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008374 vim_free(old_ei);
8375 }
8376}
8377# endif /* FEAT_SYN_HL */
8378
Bram Moolenaar071d4272004-06-13 20:20:40 +00008379/*
8380 * do_autocmd() -- implements the :autocmd command. Can be used in the
8381 * following ways:
8382 *
8383 * :autocmd <event> <pat> <cmd> Add <cmd> to the list of commands that
8384 * will be automatically executed for <event>
8385 * when editing a file matching <pat>, in
8386 * the current group.
8387 * :autocmd <event> <pat> Show the auto-commands associated with
8388 * <event> and <pat>.
8389 * :autocmd <event> Show the auto-commands associated with
8390 * <event>.
8391 * :autocmd Show all auto-commands.
8392 * :autocmd! <event> <pat> <cmd> Remove all auto-commands associated with
8393 * <event> and <pat>, and add the command
8394 * <cmd>, for the current group.
8395 * :autocmd! <event> <pat> Remove all auto-commands associated with
8396 * <event> and <pat> for the current group.
8397 * :autocmd! <event> Remove all auto-commands associated with
8398 * <event> for the current group.
8399 * :autocmd! Remove ALL auto-commands for the current
8400 * group.
8401 *
8402 * Multiple events and patterns may be given separated by commas. Here are
8403 * some examples:
8404 * :autocmd bufread,bufenter *.c,*.h set tw=0 smartindent noic
8405 * :autocmd bufleave * set tw=79 nosmartindent ic infercase
8406 *
8407 * :autocmd * *.c show all autocommands for *.c files.
Bram Moolenaard35f9712005-12-18 22:02:33 +00008408 *
8409 * Mostly a {group} argument can optionally appear before <event>.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008410 */
8411 void
Bram Moolenaare99e8442016-07-26 20:43:40 +02008412do_autocmd(char_u *arg_in, int forceit)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008413{
Bram Moolenaare99e8442016-07-26 20:43:40 +02008414 char_u *arg = arg_in;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008415 char_u *pat;
8416 char_u *envpat = NULL;
8417 char_u *cmd;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008418 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008419 int need_free = FALSE;
8420 int nested = FALSE;
8421 int group;
8422
Bram Moolenaare99e8442016-07-26 20:43:40 +02008423 if (*arg == '|')
8424 {
8425 arg = (char_u *)"";
8426 group = AUGROUP_ALL; /* no argument, use all groups */
8427 }
8428 else
8429 {
8430 /*
8431 * Check for a legal group name. If not, use AUGROUP_ALL.
8432 */
8433 group = au_get_grouparg(&arg);
8434 if (arg == NULL) /* out of memory */
8435 return;
8436 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008437
8438 /*
8439 * Scan over the events.
8440 * If we find an illegal name, return here, don't do anything.
8441 */
8442 pat = find_end_event(arg, group != AUGROUP_ALL);
8443 if (pat == NULL)
8444 return;
8445
Bram Moolenaar071d4272004-06-13 20:20:40 +00008446 pat = skipwhite(pat);
Bram Moolenaare99e8442016-07-26 20:43:40 +02008447 if (*pat == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008448 {
Bram Moolenaare99e8442016-07-26 20:43:40 +02008449 pat = (char_u *)"";
8450 cmd = (char_u *)"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00008451 }
Bram Moolenaare99e8442016-07-26 20:43:40 +02008452 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00008453 {
Bram Moolenaare99e8442016-07-26 20:43:40 +02008454 /*
8455 * Scan over the pattern. Put a NUL at the end.
8456 */
8457 cmd = pat;
Bram Moolenaar1c465442017-03-12 20:10:05 +01008458 while (*cmd && (!VIM_ISWHITE(*cmd) || cmd[-1] == '\\'))
Bram Moolenaare99e8442016-07-26 20:43:40 +02008459 cmd++;
8460 if (*cmd)
8461 *cmd++ = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008462
Bram Moolenaare99e8442016-07-26 20:43:40 +02008463 /* Expand environment variables in the pattern. Set 'shellslash', we want
8464 * forward slashes here. */
8465 if (vim_strchr(pat, '$') != NULL || vim_strchr(pat, '~') != NULL)
8466 {
8467#ifdef BACKSLASH_IN_FILENAME
8468 int p_ssl_save = p_ssl;
8469
8470 p_ssl = TRUE;
8471#endif
8472 envpat = expand_env_save(pat);
8473#ifdef BACKSLASH_IN_FILENAME
8474 p_ssl = p_ssl_save;
8475#endif
8476 if (envpat != NULL)
8477 pat = envpat;
8478 }
8479
8480 /*
8481 * Check for "nested" flag.
8482 */
8483 cmd = skipwhite(cmd);
Bram Moolenaar1c465442017-03-12 20:10:05 +01008484 if (*cmd != NUL && STRNCMP(cmd, "nested", 6) == 0 && VIM_ISWHITE(cmd[6]))
Bram Moolenaare99e8442016-07-26 20:43:40 +02008485 {
8486 nested = TRUE;
8487 cmd = skipwhite(cmd + 6);
8488 }
8489
8490 /*
8491 * Find the start of the commands.
8492 * Expand <sfile> in it.
8493 */
8494 if (*cmd != NUL)
8495 {
8496 cmd = expand_sfile(cmd);
8497 if (cmd == NULL) /* some error */
8498 return;
8499 need_free = TRUE;
8500 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008501 }
8502
8503 /*
8504 * Print header when showing autocommands.
8505 */
8506 if (!forceit && *cmd == NUL)
8507 {
8508 /* Highlight title */
8509 MSG_PUTS_TITLE(_("\n--- Auto-Commands ---"));
8510 }
8511
8512 /*
8513 * Loop over the events.
8514 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008515 last_event = (event_T)-1; /* for listing the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008516 last_group = AUGROUP_ERROR; /* for listing the group name */
Bram Moolenaare99e8442016-07-26 20:43:40 +02008517 if (*arg == '*' || *arg == NUL || *arg == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008518 {
Bram Moolenaar754b5602006-02-09 23:53:20 +00008519 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8520 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008521 if (do_autocmd_event(event, pat,
8522 nested, cmd, forceit, group) == FAIL)
8523 break;
8524 }
8525 else
8526 {
Bram Moolenaar1c465442017-03-12 20:10:05 +01008527 while (*arg && *arg != '|' && !VIM_ISWHITE(*arg))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008528 if (do_autocmd_event(event_name2nr(arg, &arg), pat,
8529 nested, cmd, forceit, group) == FAIL)
8530 break;
8531 }
8532
8533 if (need_free)
8534 vim_free(cmd);
8535 vim_free(envpat);
8536}
8537
8538/*
8539 * Find the group ID in a ":autocmd" or ":doautocmd" argument.
8540 * The "argp" argument is advanced to the following argument.
8541 *
8542 * Returns the group ID, AUGROUP_ERROR for error (out of memory).
8543 */
8544 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008545au_get_grouparg(char_u **argp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008546{
8547 char_u *group_name;
8548 char_u *p;
8549 char_u *arg = *argp;
8550 int group = AUGROUP_ALL;
8551
Bram Moolenaar1c465442017-03-12 20:10:05 +01008552 for (p = arg; *p && !VIM_ISWHITE(*p) && *p != '|'; ++p)
Bram Moolenaare99e8442016-07-26 20:43:40 +02008553 ;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008554 if (p > arg)
8555 {
8556 group_name = vim_strnsave(arg, (int)(p - arg));
8557 if (group_name == NULL) /* out of memory */
8558 return AUGROUP_ERROR;
8559 group = au_find_group(group_name);
8560 if (group == AUGROUP_ERROR)
8561 group = AUGROUP_ALL; /* no match, use all groups */
8562 else
8563 *argp = skipwhite(p); /* match, skip over group name */
8564 vim_free(group_name);
8565 }
8566 return group;
8567}
8568
8569/*
8570 * do_autocmd() for one event.
8571 * If *pat == NUL do for all patterns.
8572 * If *cmd == NUL show entries.
8573 * If forceit == TRUE delete entries.
8574 * If group is not AUGROUP_ALL, only use this group.
8575 */
8576 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008577do_autocmd_event(
8578 event_T event,
8579 char_u *pat,
8580 int nested,
8581 char_u *cmd,
8582 int forceit,
8583 int group)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008584{
8585 AutoPat *ap;
8586 AutoPat **prev_ap;
8587 AutoCmd *ac;
8588 AutoCmd **prev_ac;
8589 int brace_level;
8590 char_u *endpat;
8591 int findgroup;
8592 int allgroups;
8593 int patlen;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00008594 int is_buflocal;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008595 int buflocal_nr;
8596 char_u buflocal_pat[25]; /* for "<buffer=X>" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008597
8598 if (group == AUGROUP_ALL)
8599 findgroup = current_augroup;
8600 else
8601 findgroup = group;
8602 allgroups = (group == AUGROUP_ALL && !forceit && *cmd == NUL);
8603
8604 /*
8605 * Show or delete all patterns for an event.
8606 */
8607 if (*pat == NUL)
8608 {
8609 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8610 {
8611 if (forceit) /* delete the AutoPat, if it's in the current group */
8612 {
8613 if (ap->group == findgroup)
8614 au_remove_pat(ap);
8615 }
8616 else if (group == AUGROUP_ALL || ap->group == group)
8617 show_autocmd(ap, event);
8618 }
8619 }
8620
8621 /*
8622 * Loop through all the specified patterns.
8623 */
8624 for ( ; *pat; pat = (*endpat == ',' ? endpat + 1 : endpat))
8625 {
8626 /*
8627 * Find end of the pattern.
8628 * Watch out for a comma in braces, like "*.\{obj,o\}".
8629 */
8630 brace_level = 0;
8631 for (endpat = pat; *endpat && (*endpat != ',' || brace_level
Bram Moolenaar6b9be1b2015-07-28 13:33:45 +02008632 || (endpat > pat && endpat[-1] == '\\')); ++endpat)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008633 {
8634 if (*endpat == '{')
8635 brace_level++;
8636 else if (*endpat == '}')
8637 brace_level--;
8638 }
8639 if (pat == endpat) /* ignore single comma */
8640 continue;
8641 patlen = (int)(endpat - pat);
8642
8643 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008644 * detect special <buflocal[=X]> buffer-local patterns
8645 */
8646 is_buflocal = FALSE;
8647 buflocal_nr = 0;
8648
Bram Moolenaar1e997822015-02-17 16:04:57 +01008649 if (patlen >= 8 && STRNCMP(pat, "<buffer", 7) == 0
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008650 && pat[patlen - 1] == '>')
8651 {
Bram Moolenaar1e997822015-02-17 16:04:57 +01008652 /* "<buffer...>": Error will be printed only for addition.
8653 * printing and removing will proceed silently. */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008654 is_buflocal = TRUE;
8655 if (patlen == 8)
Bram Moolenaar1e997822015-02-17 16:04:57 +01008656 /* "<buffer>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008657 buflocal_nr = curbuf->b_fnum;
8658 else if (patlen > 9 && pat[7] == '=')
8659 {
Bram Moolenaar1e997822015-02-17 16:04:57 +01008660 if (patlen == 13 && STRNICMP(pat, "<buffer=abuf>", 13) == 0)
8661 /* "<buffer=abuf>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008662 buflocal_nr = autocmd_bufnr;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008663 else if (skipdigits(pat + 8) == pat + patlen - 1)
Bram Moolenaar1e997822015-02-17 16:04:57 +01008664 /* "<buffer=123>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008665 buflocal_nr = atoi((char *)pat + 8);
8666 }
8667 }
8668
8669 if (is_buflocal)
8670 {
8671 /* normalize pat into standard "<buffer>#N" form */
8672 sprintf((char *)buflocal_pat, "<buffer=%d>", buflocal_nr);
8673 pat = buflocal_pat; /* can modify pat and patlen */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008674 patlen = (int)STRLEN(buflocal_pat); /* but not endpat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008675 }
8676
8677 /*
Bram Moolenaar462455e2017-11-10 21:53:11 +01008678 * Find AutoPat entries with this pattern. When adding a command it
8679 * always goes at or after the last one, so start at the end.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008680 */
Bram Moolenaar462455e2017-11-10 21:53:11 +01008681 if (!forceit && *cmd != NUL && last_autopat[(int)event] != NULL)
8682 prev_ap = &last_autopat[(int)event];
8683 else
8684 prev_ap = &first_autopat[(int)event];
Bram Moolenaar071d4272004-06-13 20:20:40 +00008685 while ((ap = *prev_ap) != NULL)
8686 {
8687 if (ap->pat != NULL)
8688 {
8689 /* Accept a pattern when:
8690 * - a group was specified and it's that group, or a group was
8691 * not specified and it's the current group, or a group was
8692 * not specified and we are listing
8693 * - the length of the pattern matches
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008694 * - the pattern matches.
8695 * For <buffer[=X]>, this condition works because we normalize
8696 * all buffer-local patterns.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008697 */
8698 if ((allgroups || ap->group == findgroup)
8699 && ap->patlen == patlen
8700 && STRNCMP(pat, ap->pat, patlen) == 0)
8701 {
8702 /*
8703 * Remove existing autocommands.
8704 * If adding any new autocmd's for this AutoPat, don't
8705 * delete the pattern from the autopat list, append to
8706 * this list.
8707 */
8708 if (forceit)
8709 {
8710 if (*cmd != NUL && ap->next == NULL)
8711 {
8712 au_remove_cmds(ap);
8713 break;
8714 }
8715 au_remove_pat(ap);
8716 }
8717
8718 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008719 * Show autocmd's for this autopat, or buflocals <buffer=X>
Bram Moolenaar071d4272004-06-13 20:20:40 +00008720 */
8721 else if (*cmd == NUL)
8722 show_autocmd(ap, event);
8723
8724 /*
8725 * Add autocmd to this autopat, if it's the last one.
8726 */
8727 else if (ap->next == NULL)
8728 break;
8729 }
8730 }
8731 prev_ap = &ap->next;
8732 }
8733
8734 /*
8735 * Add a new command.
8736 */
8737 if (*cmd != NUL)
8738 {
8739 /*
8740 * If the pattern we want to add a command to does appear at the
8741 * end of the list (or not is not in the list at all), add the
8742 * pattern at the end of the list.
8743 */
8744 if (ap == NULL)
8745 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008746 /* refuse to add buffer-local ap if buffer number is invalid */
8747 if (is_buflocal && (buflocal_nr == 0
8748 || buflist_findnr(buflocal_nr) == NULL))
8749 {
8750 EMSGN(_("E680: <buffer=%d>: invalid buffer number "),
8751 buflocal_nr);
8752 return FAIL;
8753 }
8754
Bram Moolenaar071d4272004-06-13 20:20:40 +00008755 ap = (AutoPat *)alloc((unsigned)sizeof(AutoPat));
8756 if (ap == NULL)
8757 return FAIL;
8758 ap->pat = vim_strnsave(pat, patlen);
8759 ap->patlen = patlen;
8760 if (ap->pat == NULL)
8761 {
8762 vim_free(ap);
8763 return FAIL;
8764 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008765
8766 if (is_buflocal)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008767 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008768 ap->buflocal_nr = buflocal_nr;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008769 ap->reg_prog = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008770 }
8771 else
8772 {
Bram Moolenaar748bf032005-02-02 23:04:36 +00008773 char_u *reg_pat;
8774
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008775 ap->buflocal_nr = 0;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008776 reg_pat = file_pat_to_reg_pat(pat, endpat,
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008777 &ap->allow_dirs, TRUE);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008778 if (reg_pat != NULL)
8779 ap->reg_prog = vim_regcomp(reg_pat, RE_MAGIC);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008780 vim_free(reg_pat);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008781 if (reg_pat == NULL || ap->reg_prog == NULL)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008782 {
8783 vim_free(ap->pat);
8784 vim_free(ap);
8785 return FAIL;
8786 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008787 }
8788 ap->cmds = NULL;
8789 *prev_ap = ap;
Bram Moolenaar462455e2017-11-10 21:53:11 +01008790 last_autopat[(int)event] = ap;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008791 ap->next = NULL;
8792 if (group == AUGROUP_ALL)
8793 ap->group = current_augroup;
8794 else
8795 ap->group = group;
8796 }
8797
8798 /*
8799 * Add the autocmd at the end of the AutoCmd list.
8800 */
8801 prev_ac = &(ap->cmds);
8802 while ((ac = *prev_ac) != NULL)
8803 prev_ac = &ac->next;
8804 ac = (AutoCmd *)alloc((unsigned)sizeof(AutoCmd));
8805 if (ac == NULL)
8806 return FAIL;
8807 ac->cmd = vim_strsave(cmd);
8808#ifdef FEAT_EVAL
8809 ac->scriptID = current_SID;
8810#endif
8811 if (ac->cmd == NULL)
8812 {
8813 vim_free(ac);
8814 return FAIL;
8815 }
8816 ac->next = NULL;
8817 *prev_ac = ac;
8818 ac->nested = nested;
8819 }
8820 }
8821
8822 au_cleanup(); /* may really delete removed patterns/commands now */
8823 return OK;
8824}
8825
8826/*
8827 * Implementation of ":doautocmd [group] event [fname]".
8828 * Return OK for success, FAIL for failure;
8829 */
8830 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008831do_doautocmd(
8832 char_u *arg,
Bram Moolenaar1610d052016-06-09 22:53:01 +02008833 int do_msg, /* give message for no matching autocmds? */
8834 int *did_something)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008835{
8836 char_u *fname;
8837 int nothing_done = TRUE;
8838 int group;
8839
Bram Moolenaar1610d052016-06-09 22:53:01 +02008840 if (did_something != NULL)
Bram Moolenaar76ae22f2016-06-13 20:00:29 +02008841 *did_something = FALSE;
Bram Moolenaar1610d052016-06-09 22:53:01 +02008842
Bram Moolenaar071d4272004-06-13 20:20:40 +00008843 /*
8844 * Check for a legal group name. If not, use AUGROUP_ALL.
8845 */
8846 group = au_get_grouparg(&arg);
8847 if (arg == NULL) /* out of memory */
8848 return FAIL;
8849
8850 if (*arg == '*')
8851 {
8852 EMSG(_("E217: Can't execute autocommands for ALL events"));
8853 return FAIL;
8854 }
8855
8856 /*
8857 * Scan over the events.
8858 * If we find an illegal name, return here, don't do anything.
8859 */
8860 fname = find_end_event(arg, group != AUGROUP_ALL);
8861 if (fname == NULL)
8862 return FAIL;
8863
8864 fname = skipwhite(fname);
8865
8866 /*
8867 * Loop over the events.
8868 */
Bram Moolenaarfaf29d72017-07-09 11:07:16 +02008869 while (*arg && !ends_excmd(*arg) && !VIM_ISWHITE(*arg))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008870 if (apply_autocmds_group(event_name2nr(arg, &arg),
8871 fname, NULL, TRUE, group, curbuf, NULL))
8872 nothing_done = FALSE;
8873
8874 if (nothing_done && do_msg)
8875 MSG(_("No matching autocommands"));
Bram Moolenaar1610d052016-06-09 22:53:01 +02008876 if (did_something != NULL)
8877 *did_something = !nothing_done;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008878
8879#ifdef FEAT_EVAL
8880 return aborting() ? FAIL : OK;
8881#else
8882 return OK;
8883#endif
8884}
8885
8886/*
8887 * ":doautoall": execute autocommands for each loaded buffer.
8888 */
8889 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008890ex_doautoall(exarg_T *eap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008891{
8892 int retval;
8893 aco_save_T aco;
8894 buf_T *buf;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008895 bufref_T bufref;
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008896 char_u *arg = eap->arg;
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008897 int call_do_modelines = check_nomodeline(&arg);
Bram Moolenaar1610d052016-06-09 22:53:01 +02008898 int did_aucmd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008899
8900 /*
8901 * This is a bit tricky: For some commands curwin->w_buffer needs to be
8902 * equal to curbuf, but for some buffers there may not be a window.
8903 * So we change the buffer for the current window for a moment. This
8904 * gives problems when the autocommands make changes to the list of
8905 * buffers or windows...
8906 */
Bram Moolenaar29323592016-07-24 22:04:11 +02008907 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008908 {
Bram Moolenaar3a847972008-07-08 09:36:58 +00008909 if (buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008910 {
8911 /* find a window for this buffer and save some values */
8912 aucmd_prepbuf(&aco, buf);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008913 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008914
8915 /* execute the autocommands for this buffer */
Bram Moolenaar1610d052016-06-09 22:53:01 +02008916 retval = do_doautocmd(arg, FALSE, &did_aucmd);
Bram Moolenaareeefcc72007-05-01 21:21:21 +00008917
Bram Moolenaar1610d052016-06-09 22:53:01 +02008918 if (call_do_modelines && did_aucmd)
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008919 {
8920 /* Execute the modeline settings, but don't set window-local
8921 * options if we are using the current window for another
8922 * buffer. */
8923 do_modelines(curwin == aucmd_win ? OPT_NOWIN : 0);
8924 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008925
8926 /* restore the current window */
8927 aucmd_restbuf(&aco);
8928
8929 /* stop if there is some error or buffer was deleted */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008930 if (retval == FAIL || !bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008931 break;
8932 }
8933 }
8934
8935 check_cursor(); /* just in case lines got deleted */
8936}
8937
8938/*
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008939 * Check *argp for <nomodeline>. When it is present return FALSE, otherwise
8940 * return TRUE and advance *argp to after it.
8941 * Thus return TRUE when do_modelines() should be called.
8942 */
8943 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008944check_nomodeline(char_u **argp)
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008945{
8946 if (STRNCMP(*argp, "<nomodeline>", 12) == 0)
8947 {
8948 *argp = skipwhite(*argp + 12);
8949 return FALSE;
8950 }
8951 return TRUE;
8952}
8953
8954/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008955 * Prepare for executing autocommands for (hidden) buffer "buf".
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008956 * Search for a visible window containing the current buffer. If there isn't
8957 * one then use "aucmd_win".
Bram Moolenaar071d4272004-06-13 20:20:40 +00008958 * Set "curbuf" and "curwin" to match "buf".
8959 */
8960 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008961aucmd_prepbuf(
8962 aco_save_T *aco, /* structure to save values in */
8963 buf_T *buf) /* new curbuf */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008964{
8965 win_T *win;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008966 int save_ea;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008967#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008968 int save_acd;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008969#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008970
8971 /* Find a window that is for the new buffer */
8972 if (buf == curbuf) /* be quick when buf is curbuf */
8973 win = curwin;
8974 else
Bram Moolenaar29323592016-07-24 22:04:11 +02008975 FOR_ALL_WINDOWS(win)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008976 if (win->w_buffer == buf)
8977 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008978
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008979 /* Allocate "aucmd_win" when needed. If this fails (out of memory) fall
8980 * back to using the current window. */
8981 if (win == NULL && aucmd_win == NULL)
8982 {
8983 win_alloc_aucmd_win();
8984 if (aucmd_win == NULL)
8985 win = curwin;
8986 }
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008987 if (win == NULL && aucmd_win_used)
8988 /* Strange recursive autocommand, fall back to using the current
8989 * window. Expect a few side effects... */
8990 win = curwin;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008991
8992 aco->save_curwin = curwin;
8993 aco->save_curbuf = curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008994 if (win != NULL)
8995 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008996 /* There is a window for "buf" in the current tab page, make it the
8997 * curwin. This is preferred, it has the least side effects (esp. if
8998 * "buf" is curbuf). */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008999 aco->use_aucmd_win = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009000 curwin = win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009001 }
9002 else
9003 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009004 /* There is no window for "buf", use "aucmd_win". To minimize the side
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02009005 * effects, insert it in the current tab page.
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009006 * Anything related to a window (e.g., setting folds) may have
9007 * unexpected results. */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009008 aco->use_aucmd_win = TRUE;
9009 aucmd_win_used = TRUE;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00009010 aucmd_win->w_buffer = buf;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01009011#if defined(FEAT_SYN_HL) || defined(FEAT_SPELL)
Bram Moolenaarcdddaa42010-06-07 23:07:44 +02009012 aucmd_win->w_s = &buf->b_s;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01009013#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009014 ++buf->b_nwindows;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00009015 win_init_empty(aucmd_win); /* set cursor and topline to safe values */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009016
9017 /* Make sure w_localdir and globaldir are NULL to avoid a chdir() in
9018 * win_enter_ext(). */
Bram Moolenaard23a8232018-02-10 18:45:26 +01009019 VIM_CLEAR(aucmd_win->w_localdir);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009020 aco->globaldir = globaldir;
9021 globaldir = NULL;
9022
Bram Moolenaar071d4272004-06-13 20:20:40 +00009023
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00009024 /* Split the current window, put the aucmd_win in the upper half.
9025 * We don't want the BufEnter or WinEnter autocommands. */
9026 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009027 make_snapshot(SNAP_AUCMD_IDX);
9028 save_ea = p_ea;
9029 p_ea = FALSE;
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009030
Bram Moolenaar4033c552017-09-16 20:54:51 +02009031#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009032 /* Prevent chdir() call in win_enter_ext(), through do_autochdir(). */
9033 save_acd = p_acd;
9034 p_acd = FALSE;
Bram Moolenaar4033c552017-09-16 20:54:51 +02009035#endif
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009036
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009037 (void)win_split_ins(0, WSP_TOP, aucmd_win, 0);
9038 (void)win_comp_pos(); /* recompute window positions */
9039 p_ea = save_ea;
Bram Moolenaar4033c552017-09-16 20:54:51 +02009040#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009041 p_acd = save_acd;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009042#endif
Bram Moolenaar4033c552017-09-16 20:54:51 +02009043 unblock_autocmds();
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00009044 curwin = aucmd_win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009045 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009046 curbuf = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009047 aco->new_curwin = curwin;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009048 set_bufref(&aco->new_curbuf, curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009049}
9050
9051/*
9052 * Cleanup after executing autocommands for a (hidden) buffer.
9053 * Restore the window as it was (if possible).
9054 */
9055 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009056aucmd_restbuf(
9057 aco_save_T *aco) /* structure holding saved values */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009058{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009059 int dummy;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009060
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009061 if (aco->use_aucmd_win)
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009062 {
9063 --curbuf->b_nwindows;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009064 /* Find "aucmd_win", it can't be closed, but it may be in another tab
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00009065 * page. Do not trigger autocommands here. */
9066 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009067 if (curwin != aucmd_win)
9068 {
9069 tabpage_T *tp;
9070 win_T *wp;
9071
9072 FOR_ALL_TAB_WINDOWS(tp, wp)
9073 {
9074 if (wp == aucmd_win)
9075 {
9076 if (tp != curtab)
Bram Moolenaar49e649f2013-05-06 04:50:35 +02009077 goto_tabpage_tp(tp, TRUE, TRUE);
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009078 win_goto(aucmd_win);
Bram Moolenaar28f29082012-02-11 23:45:37 +01009079 goto win_found;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009080 }
9081 }
9082 }
Bram Moolenaar28f29082012-02-11 23:45:37 +01009083win_found:
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009084
9085 /* Remove the window and frame from the tree of frames. */
9086 (void)winframe_remove(curwin, &dummy, NULL);
9087 win_remove(curwin, NULL);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009088 aucmd_win_used = FALSE;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009089 last_status(FALSE); /* may need to remove last status line */
Bram Moolenaar8c752bd2017-03-19 17:09:56 +01009090
9091 if (!valid_tabpage_win(curtab))
9092 /* no valid window in current tabpage */
9093 close_tabpage(curtab);
9094
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009095 restore_snapshot(SNAP_AUCMD_IDX, FALSE);
9096 (void)win_comp_pos(); /* recompute window positions */
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00009097 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009098
9099 if (win_valid(aco->save_curwin))
9100 curwin = aco->save_curwin;
9101 else
9102 /* Hmm, original window disappeared. Just use the first one. */
9103 curwin = firstwin;
Bram Moolenaar4033c552017-09-16 20:54:51 +02009104#ifdef FEAT_EVAL
Bram Moolenaar429fa852013-04-15 12:27:36 +02009105 vars_clear(&aucmd_win->w_vars->dv_hashtab); /* free all w: variables */
9106 hash_init(&aucmd_win->w_vars->dv_hashtab); /* re-use the hashtab */
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009107#endif
9108 curbuf = curwin->w_buffer;
9109
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009110 vim_free(globaldir);
9111 globaldir = aco->globaldir;
9112
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009113 /* the buffer contents may have changed */
9114 check_cursor();
9115 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
9116 {
9117 curwin->w_topline = curbuf->b_ml.ml_line_count;
9118#ifdef FEAT_DIFF
9119 curwin->w_topfill = 0;
9120#endif
9121 }
9122#if defined(FEAT_GUI)
9123 /* Hide the scrollbars from the aucmd_win and update. */
9124 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_LEFT], FALSE);
9125 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_RIGHT], FALSE);
9126 gui_may_update_scrollbars();
9127#endif
9128 }
9129 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00009130 {
9131 /* restore curwin */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009132 if (win_valid(aco->save_curwin))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009133 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009134 /* Restore the buffer which was previously edited by curwin, if
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009135 * it was changed, we are still the same window and the buffer is
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009136 * valid. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009137 if (curwin == aco->new_curwin
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009138 && curbuf != aco->new_curbuf.br_buf
9139 && bufref_valid(&aco->new_curbuf)
9140 && aco->new_curbuf.br_buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009141 {
Bram Moolenaar7da9c372012-04-30 17:04:52 +02009142# if defined(FEAT_SYN_HL) || defined(FEAT_SPELL)
9143 if (curwin->w_s == &curbuf->b_s)
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009144 curwin->w_s = &aco->new_curbuf.br_buf->b_s;
Bram Moolenaar7da9c372012-04-30 17:04:52 +02009145# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009146 --curbuf->b_nwindows;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009147 curbuf = aco->new_curbuf.br_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009148 curwin->w_buffer = curbuf;
9149 ++curbuf->b_nwindows;
9150 }
9151
9152 curwin = aco->save_curwin;
9153 curbuf = curwin->w_buffer;
Bram Moolenaar371932a2014-09-09 16:59:38 +02009154 /* In case the autocommand move the cursor to a position that that
9155 * not exist in curbuf. */
9156 check_cursor();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009157 }
9158 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009159}
9160
9161static int autocmd_nested = FALSE;
9162
9163/*
9164 * Execute autocommands for "event" and file name "fname".
9165 * Return TRUE if some commands were executed.
9166 */
9167 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009168apply_autocmds(
9169 event_T event,
9170 char_u *fname, /* NULL or empty means use actual file name */
9171 char_u *fname_io, /* fname to use for <afile> on cmdline */
9172 int force, /* when TRUE, ignore autocmd_busy */
9173 buf_T *buf) /* buffer for <abuf> */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009174{
9175 return apply_autocmds_group(event, fname, fname_io, force,
9176 AUGROUP_ALL, buf, NULL);
9177}
9178
9179/*
9180 * Like apply_autocmds(), but with extra "eap" argument. This takes care of
9181 * setting v:filearg.
9182 */
9183 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009184apply_autocmds_exarg(
9185 event_T event,
9186 char_u *fname,
9187 char_u *fname_io,
9188 int force,
9189 buf_T *buf,
9190 exarg_T *eap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009191{
9192 return apply_autocmds_group(event, fname, fname_io, force,
9193 AUGROUP_ALL, buf, eap);
9194}
9195
9196/*
9197 * Like apply_autocmds(), but handles the caller's retval. If the script
9198 * processing is being aborted or if retval is FAIL when inside a try
9199 * conditional, no autocommands are executed. If otherwise the autocommands
9200 * cause the script to be aborted, retval is set to FAIL.
9201 */
9202 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009203apply_autocmds_retval(
9204 event_T event,
9205 char_u *fname, /* NULL or empty means use actual file name */
9206 char_u *fname_io, /* fname to use for <afile> on cmdline */
9207 int force, /* when TRUE, ignore autocmd_busy */
9208 buf_T *buf, /* buffer for <abuf> */
9209 int *retval) /* pointer to caller's retval */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009210{
9211 int did_cmd;
9212
Bram Moolenaar1e015462005-09-25 22:16:38 +00009213#ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00009214 if (should_abort(*retval))
9215 return FALSE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00009216#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009217
9218 did_cmd = apply_autocmds_group(event, fname, fname_io, force,
9219 AUGROUP_ALL, buf, NULL);
Bram Moolenaar1e015462005-09-25 22:16:38 +00009220 if (did_cmd
9221#ifdef FEAT_EVAL
9222 && aborting()
9223#endif
9224 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00009225 *retval = FAIL;
9226 return did_cmd;
9227}
9228
Bram Moolenaard35f9712005-12-18 22:02:33 +00009229/*
9230 * Return TRUE when there is a CursorHold autocommand defined.
9231 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009232 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009233has_cursorhold(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009234{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009235 return (first_autopat[(int)(get_real_state() == NORMAL_BUSY
9236 ? EVENT_CURSORHOLD : EVENT_CURSORHOLDI)] != NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009237}
Bram Moolenaard35f9712005-12-18 22:02:33 +00009238
9239/*
9240 * Return TRUE if the CursorHold event can be triggered.
9241 */
9242 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009243trigger_cursorhold(void)
Bram Moolenaard35f9712005-12-18 22:02:33 +00009244{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009245 int state;
9246
Bram Moolenaar05334432011-07-20 18:29:39 +02009247 if (!did_cursorhold
9248 && has_cursorhold()
9249 && !Recording
9250 && typebuf.tb_len == 0
Bram Moolenaard29a9ee2006-09-14 09:07:34 +00009251#ifdef FEAT_INS_EXPAND
9252 && !ins_compl_active()
9253#endif
9254 )
Bram Moolenaar754b5602006-02-09 23:53:20 +00009255 {
9256 state = get_real_state();
9257 if (state == NORMAL_BUSY || (state & INSERT) != 0)
9258 return TRUE;
9259 }
9260 return FALSE;
Bram Moolenaard35f9712005-12-18 22:02:33 +00009261}
Bram Moolenaar754b5602006-02-09 23:53:20 +00009262
9263/*
9264 * Return TRUE when there is a CursorMoved autocommand defined.
9265 */
9266 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009267has_cursormoved(void)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009268{
9269 return (first_autopat[(int)EVENT_CURSORMOVED] != NULL);
9270}
9271
9272/*
9273 * Return TRUE when there is a CursorMovedI autocommand defined.
9274 */
9275 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009276has_cursormovedI(void)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009277{
9278 return (first_autopat[(int)EVENT_CURSORMOVEDI] != NULL);
9279}
Bram Moolenaar071d4272004-06-13 20:20:40 +00009280
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009281/*
Bram Moolenaar186628f2013-03-19 13:33:23 +01009282 * Return TRUE when there is a TextChanged autocommand defined.
9283 */
9284 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009285has_textchanged(void)
Bram Moolenaar186628f2013-03-19 13:33:23 +01009286{
9287 return (first_autopat[(int)EVENT_TEXTCHANGED] != NULL);
9288}
9289
9290/*
9291 * Return TRUE when there is a TextChangedI autocommand defined.
9292 */
9293 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009294has_textchangedI(void)
Bram Moolenaar186628f2013-03-19 13:33:23 +01009295{
9296 return (first_autopat[(int)EVENT_TEXTCHANGEDI] != NULL);
9297}
9298
9299/*
Bram Moolenaar5a093432018-02-10 18:15:19 +01009300 * Return TRUE when there is a TextChangedP autocommand defined.
9301 */
9302 int
9303has_textchangedP(void)
9304{
9305 return (first_autopat[(int)EVENT_TEXTCHANGEDP] != NULL);
9306}
9307
9308/*
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009309 * Return TRUE when there is an InsertCharPre autocommand defined.
9310 */
9311 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009312has_insertcharpre(void)
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009313{
9314 return (first_autopat[(int)EVENT_INSERTCHARPRE] != NULL);
9315}
9316
Bram Moolenaard5005162014-08-22 23:05:54 +02009317/*
9318 * Return TRUE when there is an CmdUndefined autocommand defined.
9319 */
9320 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009321has_cmdundefined(void)
Bram Moolenaard5005162014-08-22 23:05:54 +02009322{
9323 return (first_autopat[(int)EVENT_CMDUNDEFINED] != NULL);
9324}
9325
9326/*
9327 * Return TRUE when there is an FuncUndefined autocommand defined.
9328 */
9329 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009330has_funcundefined(void)
Bram Moolenaard5005162014-08-22 23:05:54 +02009331{
9332 return (first_autopat[(int)EVENT_FUNCUNDEFINED] != NULL);
9333}
9334
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009335/*
Bram Moolenaar7e1652c2017-12-16 18:27:02 +01009336 * Return TRUE when there is a TextYankPost autocommand defined.
9337 */
9338 int
9339has_textyankpost(void)
9340{
9341 return (first_autopat[(int)EVENT_TEXTYANKPOST] != NULL);
9342}
9343
9344/*
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009345 * Execute autocommands for "event" and file name "fname".
9346 * Return TRUE if some commands were executed.
9347 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009348 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009349apply_autocmds_group(
9350 event_T event,
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01009351 char_u *fname, /* NULL or empty means use actual file name */
9352 char_u *fname_io, /* fname to use for <afile> on cmdline, NULL means
Bram Moolenaar071d4272004-06-13 20:20:40 +00009353 use fname */
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01009354 int force, /* when TRUE, ignore autocmd_busy */
9355 int group, /* group ID, or AUGROUP_ALL */
9356 buf_T *buf, /* buffer for <abuf> */
9357 exarg_T *eap UNUSED) /* command arguments */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009358{
9359 char_u *sfname = NULL; /* short file name */
9360 char_u *tail;
9361 int save_changed;
9362 buf_T *old_curbuf;
9363 int retval = FALSE;
9364 char_u *save_sourcing_name;
9365 linenr_T save_sourcing_lnum;
9366 char_u *save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009367 int save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009368 int save_autocmd_bufnr;
9369 char_u *save_autocmd_match;
9370 int save_autocmd_busy;
9371 int save_autocmd_nested;
9372 static int nesting = 0;
9373 AutoPatCmd patcmd;
9374 AutoPat *ap;
9375#ifdef FEAT_EVAL
9376 scid_T save_current_SID;
9377 void *save_funccalp;
9378 char_u *save_cmdarg;
9379 long save_cmdbang;
9380#endif
9381 static int filechangeshell_busy = FALSE;
Bram Moolenaar05159a02005-02-26 23:04:13 +00009382#ifdef FEAT_PROFILE
9383 proftime_T wait_time;
9384#endif
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009385 int did_save_redobuff = FALSE;
Bram Moolenaard4863aa2017-04-07 19:50:12 +02009386 save_redo_T save_redo;
Bram Moolenaarc9e9c712017-11-09 12:29:35 +01009387 int save_KeyTyped = KeyTyped;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009388
9389 /*
9390 * Quickly return if there are no autocommands for this event or
9391 * autocommands are blocked.
9392 */
Bram Moolenaarfaf29d72017-07-09 11:07:16 +02009393 if (event == NUM_EVENTS || first_autopat[(int)event] == NULL
9394 || autocmd_blocked > 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009395 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009396
9397 /*
9398 * When autocommands are busy, new autocommands are only executed when
9399 * explicitly enabled with the "nested" flag.
9400 */
9401 if (autocmd_busy && !(force || autocmd_nested))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009402 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009403
9404#ifdef FEAT_EVAL
9405 /*
Bram Moolenaar7263a772007-05-10 17:35:54 +00009406 * Quickly return when immediately aborting on error, or when an interrupt
Bram Moolenaar071d4272004-06-13 20:20:40 +00009407 * occurred or an exception was thrown but not caught.
9408 */
9409 if (aborting())
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009410 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009411#endif
9412
9413 /*
9414 * FileChangedShell never nests, because it can create an endless loop.
9415 */
Bram Moolenaar56718732006-03-15 22:53:57 +00009416 if (filechangeshell_busy && (event == EVENT_FILECHANGEDSHELL
9417 || event == EVENT_FILECHANGEDSHELLPOST))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009418 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009419
9420 /*
9421 * Ignore events in 'eventignore'.
9422 */
9423 if (event_ignored(event))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009424 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009425
9426 /*
9427 * Allow nesting of autocommands, but restrict the depth, because it's
9428 * possible to create an endless loop.
9429 */
9430 if (nesting == 10)
9431 {
9432 EMSG(_("E218: autocommand nesting too deep"));
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009433 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009434 }
9435
9436 /*
9437 * Check if these autocommands are disabled. Used when doing ":all" or
9438 * ":ball".
9439 */
9440 if ( (autocmd_no_enter
9441 && (event == EVENT_WINENTER || event == EVENT_BUFENTER))
9442 || (autocmd_no_leave
9443 && (event == EVENT_WINLEAVE || event == EVENT_BUFLEAVE)))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009444 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009445
9446 /*
9447 * Save the autocmd_* variables and info about the current buffer.
9448 */
9449 save_autocmd_fname = autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009450 save_autocmd_fname_full = autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009451 save_autocmd_bufnr = autocmd_bufnr;
9452 save_autocmd_match = autocmd_match;
9453 save_autocmd_busy = autocmd_busy;
9454 save_autocmd_nested = autocmd_nested;
9455 save_changed = curbuf->b_changed;
9456 old_curbuf = curbuf;
9457
9458 /*
9459 * Set the file name to be used for <afile>.
Bram Moolenaara0174af2008-01-02 20:08:25 +00009460 * Make a copy to avoid that changing a buffer name or directory makes it
9461 * invalid.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009462 */
9463 if (fname_io == NULL)
9464 {
Bram Moolenaar53744302015-07-17 17:38:22 +02009465 if (event == EVENT_COLORSCHEME || event == EVENT_OPTIONSET)
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009466 autocmd_fname = NULL;
Bram Moolenaarfaf29d72017-07-09 11:07:16 +02009467 else if (fname != NULL && !ends_excmd(*fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009468 autocmd_fname = fname;
9469 else if (buf != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009470 autocmd_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009471 else
9472 autocmd_fname = NULL;
9473 }
9474 else
9475 autocmd_fname = fname_io;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009476 if (autocmd_fname != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009477 autocmd_fname = vim_strsave(autocmd_fname);
9478 autocmd_fname_full = FALSE; /* call FullName_save() later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009479
9480 /*
9481 * Set the buffer number to be used for <abuf>.
9482 */
9483 if (buf == NULL)
9484 autocmd_bufnr = 0;
9485 else
9486 autocmd_bufnr = buf->b_fnum;
9487
9488 /*
9489 * When the file name is NULL or empty, use the file name of buffer "buf".
9490 * Always use the full path of the file name to match with, in case
9491 * "allow_dirs" is set.
9492 */
9493 if (fname == NULL || *fname == NUL)
9494 {
9495 if (buf == NULL)
9496 fname = NULL;
9497 else
9498 {
9499#ifdef FEAT_SYN_HL
9500 if (event == EVENT_SYNTAX)
9501 fname = buf->b_p_syn;
9502 else
9503#endif
9504 if (event == EVENT_FILETYPE)
9505 fname = buf->b_p_ft;
9506 else
9507 {
9508 if (buf->b_sfname != NULL)
9509 sfname = vim_strsave(buf->b_sfname);
9510 fname = buf->b_ffname;
9511 }
9512 }
9513 if (fname == NULL)
9514 fname = (char_u *)"";
9515 fname = vim_strsave(fname); /* make a copy, so we can change it */
9516 }
9517 else
9518 {
9519 sfname = vim_strsave(fname);
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009520 /* Don't try expanding FileType, Syntax, FuncUndefined, WindowID,
Bram Moolenaarb7407d32018-02-03 17:36:27 +01009521 * ColorScheme, QuickFixCmd* or DirChanged */
Bram Moolenaar7c626922005-02-07 22:01:03 +00009522 if (event == EVENT_FILETYPE
9523 || event == EVENT_SYNTAX
Bram Moolenaar5135d462009-04-29 16:03:38 +00009524 || event == EVENT_FUNCUNDEFINED
Bram Moolenaar7c626922005-02-07 22:01:03 +00009525 || event == EVENT_REMOTEREPLY
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00009526 || event == EVENT_SPELLFILEMISSING
Bram Moolenaar7c626922005-02-07 22:01:03 +00009527 || event == EVENT_QUICKFIXCMDPRE
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009528 || event == EVENT_COLORSCHEME
Bram Moolenaar53744302015-07-17 17:38:22 +02009529 || event == EVENT_OPTIONSET
Bram Moolenaarb7407d32018-02-03 17:36:27 +01009530 || event == EVENT_QUICKFIXCMDPOST
9531 || event == EVENT_DIRCHANGED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009532 fname = vim_strsave(fname);
9533 else
9534 fname = FullName_save(fname, FALSE);
9535 }
9536 if (fname == NULL) /* out of memory */
9537 {
9538 vim_free(sfname);
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009539 retval = FALSE;
9540 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009541 }
9542
9543#ifdef BACKSLASH_IN_FILENAME
9544 /*
9545 * Replace all backslashes with forward slashes. This makes the
9546 * autocommand patterns portable between Unix and MS-DOS.
9547 */
9548 if (sfname != NULL)
9549 forward_slash(sfname);
9550 forward_slash(fname);
9551#endif
9552
9553#ifdef VMS
9554 /* remove version for correct match */
9555 if (sfname != NULL)
9556 vms_remove_version(sfname);
9557 vms_remove_version(fname);
9558#endif
9559
9560 /*
9561 * Set the name to be used for <amatch>.
9562 */
9563 autocmd_match = fname;
9564
9565
9566 /* Don't redraw while doing auto commands. */
9567 ++RedrawingDisabled;
9568 save_sourcing_name = sourcing_name;
9569 sourcing_name = NULL; /* don't free this one */
9570 save_sourcing_lnum = sourcing_lnum;
9571 sourcing_lnum = 0; /* no line number here */
9572
9573#ifdef FEAT_EVAL
9574 save_current_SID = current_SID;
9575
Bram Moolenaar05159a02005-02-26 23:04:13 +00009576# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009577 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009578 prof_child_enter(&wait_time); /* doesn't count for the caller itself */
9579# endif
9580
Bram Moolenaar071d4272004-06-13 20:20:40 +00009581 /* Don't use local function variables, if called from a function */
9582 save_funccalp = save_funccal();
9583#endif
9584
9585 /*
9586 * When starting to execute autocommands, save the search patterns.
9587 */
9588 if (!autocmd_busy)
9589 {
9590 save_search_patterns();
Bram Moolenaar20ad69c2015-12-03 13:52:52 +01009591#ifdef FEAT_INS_EXPAND
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009592 if (!ins_compl_active())
Bram Moolenaar20ad69c2015-12-03 13:52:52 +01009593#endif
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009594 {
Bram Moolenaard4863aa2017-04-07 19:50:12 +02009595 saveRedobuff(&save_redo);
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009596 did_save_redobuff = TRUE;
9597 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009598 did_filetype = keep_filetype;
9599 }
9600
9601 /*
9602 * Note that we are applying autocmds. Some commands need to know.
9603 */
9604 autocmd_busy = TRUE;
9605 filechangeshell_busy = (event == EVENT_FILECHANGEDSHELL);
9606 ++nesting; /* see matching decrement below */
9607
9608 /* Remember that FileType was triggered. Used for did_filetype(). */
9609 if (event == EVENT_FILETYPE)
9610 did_filetype = TRUE;
9611
9612 tail = gettail(fname);
9613
9614 /* Find first autocommand that matches */
9615 patcmd.curpat = first_autopat[(int)event];
9616 patcmd.nextcmd = NULL;
9617 patcmd.group = group;
9618 patcmd.fname = fname;
9619 patcmd.sfname = sfname;
9620 patcmd.tail = tail;
9621 patcmd.event = event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009622 patcmd.arg_bufnr = autocmd_bufnr;
9623 patcmd.next = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009624 auto_next_pat(&patcmd, FALSE);
9625
9626 /* found one, start executing the autocommands */
9627 if (patcmd.curpat != NULL)
9628 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009629 /* add to active_apc_list */
9630 patcmd.next = active_apc_list;
9631 active_apc_list = &patcmd;
9632
Bram Moolenaar071d4272004-06-13 20:20:40 +00009633#ifdef FEAT_EVAL
9634 /* set v:cmdarg (only when there is a matching pattern) */
Bram Moolenaar22fcfad2016-07-01 18:17:26 +02009635 save_cmdbang = (long)get_vim_var_nr(VV_CMDBANG);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009636 if (eap != NULL)
9637 {
9638 save_cmdarg = set_cmdarg(eap, NULL);
9639 set_vim_var_nr(VV_CMDBANG, (long)eap->forceit);
9640 }
9641 else
9642 save_cmdarg = NULL; /* avoid gcc warning */
9643#endif
9644 retval = TRUE;
9645 /* mark the last pattern, to avoid an endless loop when more patterns
9646 * are added when executing autocommands */
9647 for (ap = patcmd.curpat; ap->next != NULL; ap = ap->next)
9648 ap->last = FALSE;
9649 ap->last = TRUE;
9650 check_lnums(TRUE); /* make sure cursor and topline are valid */
9651 do_cmdline(NULL, getnextac, (void *)&patcmd,
9652 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
9653#ifdef FEAT_EVAL
9654 if (eap != NULL)
9655 {
9656 (void)set_cmdarg(NULL, save_cmdarg);
9657 set_vim_var_nr(VV_CMDBANG, save_cmdbang);
9658 }
9659#endif
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009660 /* delete from active_apc_list */
9661 if (active_apc_list == &patcmd) /* just in case */
9662 active_apc_list = patcmd.next;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009663 }
9664
9665 --RedrawingDisabled;
9666 autocmd_busy = save_autocmd_busy;
9667 filechangeshell_busy = FALSE;
9668 autocmd_nested = save_autocmd_nested;
9669 vim_free(sourcing_name);
9670 sourcing_name = save_sourcing_name;
9671 sourcing_lnum = save_sourcing_lnum;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009672 vim_free(autocmd_fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009673 autocmd_fname = save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009674 autocmd_fname_full = save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009675 autocmd_bufnr = save_autocmd_bufnr;
9676 autocmd_match = save_autocmd_match;
9677#ifdef FEAT_EVAL
9678 current_SID = save_current_SID;
9679 restore_funccal(save_funccalp);
Bram Moolenaar05159a02005-02-26 23:04:13 +00009680# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009681 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009682 prof_child_exit(&wait_time);
9683# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009684#endif
Bram Moolenaarc9e9c712017-11-09 12:29:35 +01009685 KeyTyped = save_KeyTyped;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009686 vim_free(fname);
9687 vim_free(sfname);
9688 --nesting; /* see matching increment above */
9689
9690 /*
9691 * When stopping to execute autocommands, restore the search patterns and
Bram Moolenaar3be85852014-06-12 14:01:31 +02009692 * the redo buffer. Free any buffers in the au_pending_free_buf list and
9693 * free any windows in the au_pending_free_win list.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009694 */
9695 if (!autocmd_busy)
9696 {
9697 restore_search_patterns();
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009698 if (did_save_redobuff)
Bram Moolenaard4863aa2017-04-07 19:50:12 +02009699 restoreRedobuff(&save_redo);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009700 did_filetype = FALSE;
Bram Moolenaar4c7ab1b2014-04-06 20:45:43 +02009701 while (au_pending_free_buf != NULL)
9702 {
9703 buf_T *b = au_pending_free_buf->b_next;
9704 vim_free(au_pending_free_buf);
9705 au_pending_free_buf = b;
9706 }
Bram Moolenaar3be85852014-06-12 14:01:31 +02009707 while (au_pending_free_win != NULL)
9708 {
9709 win_T *w = au_pending_free_win->w_next;
9710 vim_free(au_pending_free_win);
9711 au_pending_free_win = w;
9712 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009713 }
9714
9715 /*
9716 * Some events don't set or reset the Changed flag.
9717 * Check if still in the same buffer!
9718 */
9719 if (curbuf == old_curbuf
9720 && (event == EVENT_BUFREADPOST
9721 || event == EVENT_BUFWRITEPOST
9722 || event == EVENT_FILEAPPENDPOST
9723 || event == EVENT_VIMLEAVE
9724 || event == EVENT_VIMLEAVEPRE))
9725 {
9726#ifdef FEAT_TITLE
9727 if (curbuf->b_changed != save_changed)
9728 need_maketitle = TRUE;
9729#endif
9730 curbuf->b_changed = save_changed;
9731 }
9732
9733 au_cleanup(); /* may really delete removed patterns/commands now */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009734
9735BYPASS_AU:
9736 /* When wiping out a buffer make sure all its buffer-local autocommands
9737 * are deleted. */
9738 if (event == EVENT_BUFWIPEOUT && buf != NULL)
9739 aubuflocal_remove(buf);
9740
Bram Moolenaarc3691332016-04-20 12:49:49 +02009741 if (retval == OK && event == EVENT_FILETYPE)
9742 au_did_filetype = TRUE;
9743
Bram Moolenaar071d4272004-06-13 20:20:40 +00009744 return retval;
9745}
9746
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009747# ifdef FEAT_EVAL
9748static char_u *old_termresponse = NULL;
9749# endif
9750
9751/*
9752 * Block triggering autocommands until unblock_autocmd() is called.
9753 * Can be used recursively, so long as it's symmetric.
9754 */
9755 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009756block_autocmds(void)
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009757{
9758# ifdef FEAT_EVAL
9759 /* Remember the value of v:termresponse. */
9760 if (autocmd_blocked == 0)
9761 old_termresponse = get_vim_var_str(VV_TERMRESPONSE);
9762# endif
9763 ++autocmd_blocked;
9764}
9765
9766 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009767unblock_autocmds(void)
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009768{
9769 --autocmd_blocked;
9770
9771# ifdef FEAT_EVAL
9772 /* When v:termresponse was set while autocommands were blocked, trigger
9773 * the autocommands now. Esp. useful when executing a shell command
9774 * during startup (vimdiff). */
9775 if (autocmd_blocked == 0
9776 && get_vim_var_str(VV_TERMRESPONSE) != old_termresponse)
9777 apply_autocmds(EVENT_TERMRESPONSE, NULL, NULL, FALSE, curbuf);
9778# endif
9779}
9780
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009781 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009782is_autocmd_blocked(void)
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009783{
9784 return autocmd_blocked != 0;
9785}
9786
Bram Moolenaar071d4272004-06-13 20:20:40 +00009787/*
9788 * Find next autocommand pattern that matches.
9789 */
9790 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009791auto_next_pat(
9792 AutoPatCmd *apc,
9793 int stop_at_last) /* stop when 'last' flag is set */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009794{
9795 AutoPat *ap;
9796 AutoCmd *cp;
9797 char_u *name;
9798 char *s;
9799
Bram Moolenaard23a8232018-02-10 18:45:26 +01009800 VIM_CLEAR(sourcing_name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009801
9802 for (ap = apc->curpat; ap != NULL && !got_int; ap = ap->next)
9803 {
9804 apc->curpat = NULL;
9805
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009806 /* Only use a pattern when it has not been removed, has commands and
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009807 * the group matches. For buffer-local autocommands only check the
9808 * buffer number. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009809 if (ap->pat != NULL && ap->cmds != NULL
9810 && (apc->group == AUGROUP_ALL || apc->group == ap->group))
9811 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009812 /* execution-condition */
9813 if (ap->buflocal_nr == 0
Bram Moolenaardffa5b82014-11-19 16:38:07 +01009814 ? (match_file_pat(NULL, &ap->reg_prog, apc->fname,
Bram Moolenaar748bf032005-02-02 23:04:36 +00009815 apc->sfname, apc->tail, ap->allow_dirs))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009816 : ap->buflocal_nr == apc->arg_bufnr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009817 {
9818 name = event_nr2name(apc->event);
9819 s = _("%s Auto commands for \"%s\"");
9820 sourcing_name = alloc((unsigned)(STRLEN(s)
9821 + STRLEN(name) + ap->patlen + 1));
9822 if (sourcing_name != NULL)
9823 {
9824 sprintf((char *)sourcing_name, s,
9825 (char *)name, (char *)ap->pat);
9826 if (p_verbose >= 8)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009827 {
9828 verbose_enter();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009829 smsg((char_u *)_("Executing %s"), sourcing_name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009830 verbose_leave();
9831 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009832 }
9833
9834 apc->curpat = ap;
9835 apc->nextcmd = ap->cmds;
9836 /* mark last command */
9837 for (cp = ap->cmds; cp->next != NULL; cp = cp->next)
9838 cp->last = FALSE;
9839 cp->last = TRUE;
9840 }
9841 line_breakcheck();
9842 if (apc->curpat != NULL) /* found a match */
9843 break;
9844 }
9845 if (stop_at_last && ap->last)
9846 break;
9847 }
9848}
9849
9850/*
9851 * Get next autocommand command.
9852 * Called by do_cmdline() to get the next line for ":if".
9853 * Returns allocated string, or NULL for end of autocommands.
9854 */
Bram Moolenaar21691f82012-12-05 19:13:18 +01009855 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009856getnextac(int c UNUSED, void *cookie, int indent UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009857{
9858 AutoPatCmd *acp = (AutoPatCmd *)cookie;
9859 char_u *retval;
9860 AutoCmd *ac;
9861
9862 /* Can be called again after returning the last line. */
9863 if (acp->curpat == NULL)
9864 return NULL;
9865
9866 /* repeat until we find an autocommand to execute */
9867 for (;;)
9868 {
9869 /* skip removed commands */
9870 while (acp->nextcmd != NULL && acp->nextcmd->cmd == NULL)
9871 if (acp->nextcmd->last)
9872 acp->nextcmd = NULL;
9873 else
9874 acp->nextcmd = acp->nextcmd->next;
9875
9876 if (acp->nextcmd != NULL)
9877 break;
9878
9879 /* at end of commands, find next pattern that matches */
9880 if (acp->curpat->last)
9881 acp->curpat = NULL;
9882 else
9883 acp->curpat = acp->curpat->next;
9884 if (acp->curpat != NULL)
9885 auto_next_pat(acp, TRUE);
9886 if (acp->curpat == NULL)
9887 return NULL;
9888 }
9889
9890 ac = acp->nextcmd;
9891
9892 if (p_verbose >= 9)
9893 {
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009894 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009895 smsg((char_u *)_("autocommand %s"), ac->cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009896 msg_puts((char_u *)"\n"); /* don't overwrite this either */
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009897 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009898 }
9899 retval = vim_strsave(ac->cmd);
9900 autocmd_nested = ac->nested;
9901#ifdef FEAT_EVAL
9902 current_SID = ac->scriptID;
9903#endif
9904 if (ac->last)
9905 acp->nextcmd = NULL;
9906 else
9907 acp->nextcmd = ac->next;
9908 return retval;
9909}
9910
9911/*
9912 * Return TRUE if there is a matching autocommand for "fname".
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009913 * To account for buffer-local autocommands, function needs to know
9914 * in which buffer the file will be opened.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009915 */
9916 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009917has_autocmd(event_T event, char_u *sfname, buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009918{
9919 AutoPat *ap;
9920 char_u *fname;
9921 char_u *tail = gettail(sfname);
9922 int retval = FALSE;
9923
9924 fname = FullName_save(sfname, FALSE);
9925 if (fname == NULL)
9926 return FALSE;
9927
9928#ifdef BACKSLASH_IN_FILENAME
9929 /*
9930 * Replace all backslashes with forward slashes. This makes the
9931 * autocommand patterns portable between Unix and MS-DOS.
9932 */
9933 sfname = vim_strsave(sfname);
9934 if (sfname != NULL)
9935 forward_slash(sfname);
9936 forward_slash(fname);
9937#endif
9938
9939 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
9940 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009941 && (ap->buflocal_nr == 0
Bram Moolenaardffa5b82014-11-19 16:38:07 +01009942 ? match_file_pat(NULL, &ap->reg_prog,
Bram Moolenaar748bf032005-02-02 23:04:36 +00009943 fname, sfname, tail, ap->allow_dirs)
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009944 : buf != NULL && ap->buflocal_nr == buf->b_fnum
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009945 ))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009946 {
9947 retval = TRUE;
9948 break;
9949 }
9950
9951 vim_free(fname);
9952#ifdef BACKSLASH_IN_FILENAME
9953 vim_free(sfname);
9954#endif
9955
9956 return retval;
9957}
9958
9959#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
9960/*
9961 * Function given to ExpandGeneric() to obtain the list of autocommand group
9962 * names.
9963 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009964 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009965get_augroup_name(expand_T *xp UNUSED, int idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009966{
9967 if (idx == augroups.ga_len) /* add "END" add the end */
9968 return (char_u *)"END";
9969 if (idx >= augroups.ga_len) /* end of list */
9970 return NULL;
Bram Moolenaarb62cc362016-09-03 16:43:53 +02009971 if (AUGROUP_NAME(idx) == NULL || AUGROUP_NAME(idx) == get_deleted_augroup())
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02009972 /* skip deleted entries */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009973 return (char_u *)"";
9974 return AUGROUP_NAME(idx); /* return a name */
9975}
9976
9977static int include_groups = FALSE;
9978
9979 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009980set_context_in_autocmd(
9981 expand_T *xp,
9982 char_u *arg,
9983 int doautocmd) /* TRUE for :doauto*, FALSE for :autocmd */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009984{
9985 char_u *p;
9986 int group;
9987
9988 /* check for a group name, skip it if present */
9989 include_groups = FALSE;
9990 p = arg;
9991 group = au_get_grouparg(&arg);
9992 if (group == AUGROUP_ERROR)
9993 return NULL;
9994 /* If there only is a group name that's what we expand. */
Bram Moolenaar1c465442017-03-12 20:10:05 +01009995 if (*arg == NUL && group != AUGROUP_ALL && !VIM_ISWHITE(arg[-1]))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009996 {
9997 arg = p;
9998 group = AUGROUP_ALL;
9999 }
10000
10001 /* skip over event name */
Bram Moolenaar1c465442017-03-12 20:10:05 +010010002 for (p = arg; *p != NUL && !VIM_ISWHITE(*p); ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010003 if (*p == ',')
10004 arg = p + 1;
10005 if (*p == NUL)
10006 {
10007 if (group == AUGROUP_ALL)
10008 include_groups = TRUE;
10009 xp->xp_context = EXPAND_EVENTS; /* expand event name */
10010 xp->xp_pattern = arg;
10011 return NULL;
10012 }
10013
10014 /* skip over pattern */
10015 arg = skipwhite(p);
Bram Moolenaar1c465442017-03-12 20:10:05 +010010016 while (*arg && (!VIM_ISWHITE(*arg) || arg[-1] == '\\'))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010017 arg++;
10018 if (*arg)
10019 return arg; /* expand (next) command */
10020
10021 if (doautocmd)
10022 xp->xp_context = EXPAND_FILES; /* expand file names */
10023 else
10024 xp->xp_context = EXPAND_NOTHING; /* pattern is not expanded */
10025 return NULL;
10026}
10027
10028/*
10029 * Function given to ExpandGeneric() to obtain the list of event names.
10030 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010031 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010032get_event_name(expand_T *xp UNUSED, int idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010033{
10034 if (idx < augroups.ga_len) /* First list group names, if wanted */
10035 {
Bram Moolenaarf2c4c392016-07-29 20:50:24 +020010036 if (!include_groups || AUGROUP_NAME(idx) == NULL
Bram Moolenaarb62cc362016-09-03 16:43:53 +020010037 || AUGROUP_NAME(idx) == get_deleted_augroup())
Bram Moolenaar071d4272004-06-13 20:20:40 +000010038 return (char_u *)""; /* skip deleted entries */
10039 return AUGROUP_NAME(idx); /* return a name */
10040 }
10041 return (char_u *)event_names[idx - augroups.ga_len].name;
10042}
10043
10044#endif /* FEAT_CMDL_COMPL */
10045
10046/*
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010047 * Return TRUE if autocmd is supported.
10048 */
10049 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010050autocmd_supported(char_u *name)
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010051{
10052 char_u *p;
10053
10054 return (event_name2nr(name, &p) != NUM_EVENTS);
10055}
10056
10057/*
Bram Moolenaar195d6352005-12-19 22:08:24 +000010058 * Return TRUE if an autocommand is defined for a group, event and
10059 * pattern: The group can be omitted to accept any group. "event" and "pattern"
10060 * can be NULL to accept any event and pattern. "pattern" can be NULL to accept
10061 * any pattern. Buffer-local patterns <buffer> or <buffer=N> are accepted.
10062 * Used for:
10063 * exists("#Group") or
10064 * exists("#Group#Event") or
10065 * exists("#Group#Event#pat") or
10066 * exists("#Event") or
10067 * exists("#Event#pat")
Bram Moolenaar071d4272004-06-13 20:20:40 +000010068 */
10069 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010070au_exists(char_u *arg)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010071{
Bram Moolenaar195d6352005-12-19 22:08:24 +000010072 char_u *arg_save;
10073 char_u *pattern = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010074 char_u *event_name;
10075 char_u *p;
Bram Moolenaar754b5602006-02-09 23:53:20 +000010076 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010077 AutoPat *ap;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010078 buf_T *buflocal_buf = NULL;
Bram Moolenaar195d6352005-12-19 22:08:24 +000010079 int group;
10080 int retval = FALSE;
10081
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010082 /* Make a copy so that we can change the '#' chars to a NUL. */
Bram Moolenaar195d6352005-12-19 22:08:24 +000010083 arg_save = vim_strsave(arg);
10084 if (arg_save == NULL)
10085 return FALSE;
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010086 p = vim_strchr(arg_save, '#');
Bram Moolenaar195d6352005-12-19 22:08:24 +000010087 if (p != NULL)
10088 *p++ = NUL;
10089
10090 /* First, look for an autocmd group name */
10091 group = au_find_group(arg_save);
10092 if (group == AUGROUP_ERROR)
10093 {
10094 /* Didn't match a group name, assume the first argument is an event. */
10095 group = AUGROUP_ALL;
10096 event_name = arg_save;
10097 }
10098 else
10099 {
10100 if (p == NULL)
10101 {
10102 /* "Group": group name is present and it's recognized */
10103 retval = TRUE;
10104 goto theend;
10105 }
10106
10107 /* Must be "Group#Event" or "Group#Event#pat". */
10108 event_name = p;
10109 p = vim_strchr(event_name, '#');
10110 if (p != NULL)
10111 *p++ = NUL; /* "Group#Event#pat" */
10112 }
10113
10114 pattern = p; /* "pattern" is NULL when there is no pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010115
10116 /* find the index (enum) for the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010117 event = event_name2nr(event_name, &p);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010118
10119 /* return FALSE if the event name is not recognized */
Bram Moolenaar195d6352005-12-19 22:08:24 +000010120 if (event == NUM_EVENTS)
10121 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010122
10123 /* Find the first autocommand for this event.
10124 * If there isn't any, return FALSE;
10125 * If there is one and no pattern given, return TRUE; */
10126 ap = first_autopat[(int)event];
10127 if (ap == NULL)
Bram Moolenaar195d6352005-12-19 22:08:24 +000010128 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010129
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010130 /* if pattern is "<buffer>", special handling is needed which uses curbuf */
10131 /* for pattern "<buffer=N>, fnamecmp() will work fine */
Bram Moolenaar5b7880d2009-09-11 15:24:31 +000010132 if (pattern != NULL && STRICMP(pattern, "<buffer>") == 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010133 buflocal_buf = curbuf;
10134
Bram Moolenaar071d4272004-06-13 20:20:40 +000010135 /* Check if there is an autocommand with the given pattern. */
10136 for ( ; ap != NULL; ap = ap->next)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010137 /* only use a pattern when it has not been removed and has commands. */
10138 /* For buffer-local autocommands, fnamecmp() works fine. */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010139 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaar195d6352005-12-19 22:08:24 +000010140 && (group == AUGROUP_ALL || ap->group == group)
Bram Moolenaar5b7880d2009-09-11 15:24:31 +000010141 && (pattern == NULL
10142 || (buflocal_buf == NULL
10143 ? fnamecmp(ap->pat, pattern) == 0
10144 : ap->buflocal_nr == buflocal_buf->b_fnum)))
Bram Moolenaar195d6352005-12-19 22:08:24 +000010145 {
10146 retval = TRUE;
10147 break;
10148 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010149
Bram Moolenaar195d6352005-12-19 22:08:24 +000010150theend:
10151 vim_free(arg_save);
10152 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010153}
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010154
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010155
10156/*
Bram Moolenaar748bf032005-02-02 23:04:36 +000010157 * Try matching a filename with a "pattern" ("prog" is NULL), or use the
10158 * precompiled regprog "prog" ("pattern" is NULL). That avoids calling
10159 * vim_regcomp() often.
Bram Moolenaar071d4272004-06-13 20:20:40 +000010160 * Used for autocommands and 'wildignore'.
10161 * Returns TRUE if there is a match, FALSE otherwise.
10162 */
Bram Moolenaardffa5b82014-11-19 16:38:07 +010010163 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010164match_file_pat(
10165 char_u *pattern, /* pattern to match with */
10166 regprog_T **prog, /* pre-compiled regprog or NULL */
10167 char_u *fname, /* full path of file name */
10168 char_u *sfname, /* short file name or NULL */
10169 char_u *tail, /* tail of path */
10170 int allow_dirs) /* allow matching with dir */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010171{
10172 regmatch_T regmatch;
10173 int result = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010174
Bram Moolenaar71afbfe2013-03-19 16:49:16 +010010175 regmatch.rm_ic = p_fic; /* ignore case if 'fileignorecase' is set */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010176 if (prog != NULL)
10177 regmatch.regprog = *prog;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010178 else
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010179 regmatch.regprog = vim_regcomp(pattern, RE_MAGIC);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010180
10181 /*
10182 * Try for a match with the pattern with:
10183 * 1. the full file name, when the pattern has a '/'.
10184 * 2. the short file name, when the pattern has a '/'.
10185 * 3. the tail of the file name, when the pattern has no '/'.
10186 */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010187 if (regmatch.regprog != NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +000010188 && ((allow_dirs
10189 && (vim_regexec(&regmatch, fname, (colnr_T)0)
10190 || (sfname != NULL
10191 && vim_regexec(&regmatch, sfname, (colnr_T)0))))
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010192 || (!allow_dirs && vim_regexec(&regmatch, tail, (colnr_T)0))))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010193 result = TRUE;
10194
Bram Moolenaardffa5b82014-11-19 16:38:07 +010010195 if (prog != NULL)
10196 *prog = regmatch.regprog;
10197 else
Bram Moolenaar473de612013-06-08 18:19:48 +020010198 vim_regfree(regmatch.regprog);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010199 return result;
10200}
Bram Moolenaar071d4272004-06-13 20:20:40 +000010201
10202#if defined(FEAT_WILDIGN) || defined(PROTO)
10203/*
10204 * Return TRUE if a file matches with a pattern in "list".
10205 * "list" is a comma-separated list of patterns, like 'wildignore'.
10206 * "sfname" is the short file name or NULL, "ffname" the long file name.
10207 */
10208 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010209match_file_list(char_u *list, char_u *sfname, char_u *ffname)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010210{
10211 char_u buf[100];
10212 char_u *tail;
10213 char_u *regpat;
10214 char allow_dirs;
10215 int match;
10216 char_u *p;
10217
10218 tail = gettail(sfname);
10219
10220 /* try all patterns in 'wildignore' */
10221 p = list;
10222 while (*p)
10223 {
10224 copy_option_part(&p, buf, 100, ",");
10225 regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, FALSE);
10226 if (regpat == NULL)
10227 break;
Bram Moolenaar748bf032005-02-02 23:04:36 +000010228 match = match_file_pat(regpat, NULL, ffname, sfname,
10229 tail, (int)allow_dirs);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010230 vim_free(regpat);
10231 if (match)
10232 return TRUE;
10233 }
10234 return FALSE;
10235}
10236#endif
10237
10238/*
10239 * Convert the given pattern "pat" which has shell style wildcards in it, into
10240 * a regular expression, and return the result in allocated memory. If there
10241 * is a directory path separator to be matched, then TRUE is put in
10242 * allow_dirs, otherwise FALSE is put there -- webb.
10243 * Handle backslashes before special characters, like "\*" and "\ ".
10244 *
Bram Moolenaar071d4272004-06-13 20:20:40 +000010245 * Returns NULL when out of memory.
10246 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010247 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010248file_pat_to_reg_pat(
10249 char_u *pat,
10250 char_u *pat_end, /* first char after pattern or NULL */
10251 char *allow_dirs, /* Result passed back out in here */
10252 int no_bslash UNUSED) /* Don't use a backward slash as pathsep */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010253{
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010254 int size = 2; /* '^' at start, '$' at end */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010255 char_u *endp;
10256 char_u *reg_pat;
10257 char_u *p;
10258 int i;
10259 int nested = 0;
10260 int add_dollar = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010261
10262 if (allow_dirs != NULL)
10263 *allow_dirs = FALSE;
10264 if (pat_end == NULL)
10265 pat_end = pat + STRLEN(pat);
10266
Bram Moolenaar071d4272004-06-13 20:20:40 +000010267 for (p = pat; p < pat_end; p++)
10268 {
10269 switch (*p)
10270 {
10271 case '*':
10272 case '.':
10273 case ',':
10274 case '{':
10275 case '}':
10276 case '~':
10277 size += 2; /* extra backslash */
10278 break;
10279#ifdef BACKSLASH_IN_FILENAME
10280 case '\\':
10281 case '/':
10282 size += 4; /* could become "[\/]" */
10283 break;
10284#endif
10285 default:
10286 size++;
Bram Moolenaar2288afe2015-08-11 16:20:05 +020010287# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010288 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010289 {
10290 ++p;
10291 ++size;
10292 }
10293# endif
10294 break;
10295 }
10296 }
10297 reg_pat = alloc(size + 1);
10298 if (reg_pat == NULL)
10299 return NULL;
10300
Bram Moolenaar071d4272004-06-13 20:20:40 +000010301 i = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010302
10303 if (pat[0] == '*')
10304 while (pat[0] == '*' && pat < pat_end - 1)
10305 pat++;
10306 else
10307 reg_pat[i++] = '^';
10308 endp = pat_end - 1;
Bram Moolenaar8fee8782015-08-11 18:45:48 +020010309 if (endp >= pat && *endp == '*')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010310 {
10311 while (endp - pat > 0 && *endp == '*')
10312 endp--;
10313 add_dollar = FALSE;
10314 }
10315 for (p = pat; *p && nested >= 0 && p <= endp; p++)
10316 {
10317 switch (*p)
10318 {
10319 case '*':
10320 reg_pat[i++] = '.';
10321 reg_pat[i++] = '*';
Bram Moolenaar02743632005-07-25 20:42:36 +000010322 while (p[1] == '*') /* "**" matches like "*" */
10323 ++p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010324 break;
10325 case '.':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010326 case '~':
10327 reg_pat[i++] = '\\';
10328 reg_pat[i++] = *p;
10329 break;
10330 case '?':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010331 reg_pat[i++] = '.';
10332 break;
10333 case '\\':
10334 if (p[1] == NUL)
10335 break;
10336#ifdef BACKSLASH_IN_FILENAME
10337 if (!no_bslash)
10338 {
10339 /* translate:
10340 * "\x" to "\\x" e.g., "dir\file"
10341 * "\*" to "\\.*" e.g., "dir\*.c"
10342 * "\?" to "\\." e.g., "dir\??.c"
10343 * "\+" to "\+" e.g., "fileX\+.c"
10344 */
10345 if ((vim_isfilec(p[1]) || p[1] == '*' || p[1] == '?')
10346 && p[1] != '+')
10347 {
10348 reg_pat[i++] = '[';
10349 reg_pat[i++] = '\\';
10350 reg_pat[i++] = '/';
10351 reg_pat[i++] = ']';
10352 if (allow_dirs != NULL)
10353 *allow_dirs = TRUE;
10354 break;
10355 }
10356 }
10357#endif
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010358 /* Undo escaping from ExpandEscape():
10359 * foo\?bar -> foo?bar
10360 * foo\%bar -> foo%bar
10361 * foo\,bar -> foo,bar
10362 * foo\ bar -> foo bar
10363 * Don't unescape \, * and others that are also special in a
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010364 * regexp.
10365 * An escaped { must be unescaped since we use magic not
Bram Moolenaara946afe2013-08-02 15:22:39 +020010366 * verymagic. Use "\\\{n,m\}"" to get "\{n,m}".
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010367 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010368 if (*++p == '?'
10369#ifdef BACKSLASH_IN_FILENAME
10370 && no_bslash
10371#endif
10372 )
10373 reg_pat[i++] = '?';
10374 else
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010375 if (*p == ',' || *p == '%' || *p == '#'
Bram Moolenaar2288afe2015-08-11 16:20:05 +020010376 || vim_isspace(*p) || *p == '{' || *p == '}')
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010377 reg_pat[i++] = *p;
Bram Moolenaara946afe2013-08-02 15:22:39 +020010378 else if (*p == '\\' && p[1] == '\\' && p[2] == '{')
10379 {
10380 reg_pat[i++] = '\\';
10381 reg_pat[i++] = '{';
10382 p += 2;
10383 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010384 else
10385 {
10386 if (allow_dirs != NULL && vim_ispathsep(*p)
10387#ifdef BACKSLASH_IN_FILENAME
10388 && (!no_bslash || *p != '\\')
10389#endif
10390 )
10391 *allow_dirs = TRUE;
10392 reg_pat[i++] = '\\';
10393 reg_pat[i++] = *p;
10394 }
10395 break;
10396#ifdef BACKSLASH_IN_FILENAME
10397 case '/':
10398 reg_pat[i++] = '[';
10399 reg_pat[i++] = '\\';
10400 reg_pat[i++] = '/';
10401 reg_pat[i++] = ']';
10402 if (allow_dirs != NULL)
10403 *allow_dirs = TRUE;
10404 break;
10405#endif
10406 case '{':
10407 reg_pat[i++] = '\\';
10408 reg_pat[i++] = '(';
10409 nested++;
10410 break;
10411 case '}':
10412 reg_pat[i++] = '\\';
10413 reg_pat[i++] = ')';
10414 --nested;
10415 break;
10416 case ',':
10417 if (nested)
10418 {
10419 reg_pat[i++] = '\\';
10420 reg_pat[i++] = '|';
10421 }
10422 else
10423 reg_pat[i++] = ',';
10424 break;
10425 default:
10426# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010427 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010428 reg_pat[i++] = *p++;
10429 else
10430# endif
10431 if (allow_dirs != NULL && vim_ispathsep(*p))
10432 *allow_dirs = TRUE;
10433 reg_pat[i++] = *p;
10434 break;
10435 }
10436 }
10437 if (add_dollar)
10438 reg_pat[i++] = '$';
10439 reg_pat[i] = NUL;
10440 if (nested != 0)
10441 {
10442 if (nested < 0)
10443 EMSG(_("E219: Missing {."));
10444 else
10445 EMSG(_("E220: Missing }."));
Bram Moolenaard23a8232018-02-10 18:45:26 +010010446 VIM_CLEAR(reg_pat);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010447 }
10448 return reg_pat;
10449}
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010450
10451#if defined(EINTR) || defined(PROTO)
10452/*
10453 * Version of read() that retries when interrupted by EINTR (possibly
10454 * by a SIGWINCH).
10455 */
10456 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010457read_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010458{
10459 long ret;
10460
10461 for (;;)
10462 {
10463 ret = vim_read(fd, buf, bufsize);
10464 if (ret >= 0 || errno != EINTR)
10465 break;
10466 }
10467 return ret;
10468}
10469
10470/*
10471 * Version of write() that retries when interrupted by EINTR (possibly
10472 * by a SIGWINCH).
10473 */
10474 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010475write_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010476{
10477 long ret = 0;
10478 long wlen;
10479
10480 /* Repeat the write() so long it didn't fail, other than being interrupted
10481 * by a signal. */
10482 while (ret < (long)bufsize)
10483 {
Bram Moolenaar9c263032010-12-17 18:06:06 +010010484 wlen = vim_write(fd, (char *)buf + ret, bufsize - ret);
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010485 if (wlen < 0)
10486 {
10487 if (errno != EINTR)
10488 break;
10489 }
10490 else
10491 ret += wlen;
10492 }
10493 return ret;
10494}
10495#endif