blob: 700bd3ea53de80e74624e771383526f1443fb689 [file] [log] [blame]
Bram Moolenaaredf3f972016-08-29 22:49:24 +02001/* vi:set ts=8 sts=4 sw=4 noet:
Bram Moolenaar071d4272004-06-13 20:20:40 +00002 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
11 * fileio.c: read from and write to a file
12 */
13
Bram Moolenaar071d4272004-06-13 20:20:40 +000014#include "vim.h"
15
Bram Moolenaarf4888d02009-12-02 12:31:27 +000016#if defined(__TANDEM) || defined(__MINT__)
Bram Moolenaar071d4272004-06-13 20:20:40 +000017# include <limits.h> /* for SSIZE_MAX */
18#endif
19
20#if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
21# include <utime.h> /* for struct utimbuf */
22#endif
23
24#define BUFSIZE 8192 /* size of normal write buffer */
25#define SMBUFSIZE 256 /* size of emergency write buffer */
26
Bram Moolenaar071d4272004-06-13 20:20:40 +000027/* Is there any system that doesn't have access()? */
Bram Moolenaar9372a112005-12-06 19:59:18 +000028#define USE_MCH_ACCESS
Bram Moolenaar071d4272004-06-13 20:20:40 +000029
30#ifdef FEAT_MBYTE
Bram Moolenaard25c16e2016-01-29 22:13:30 +010031static char_u *next_fenc(char_u **pp);
Bram Moolenaar071d4272004-06-13 20:20:40 +000032# ifdef FEAT_EVAL
Bram Moolenaard25c16e2016-01-29 22:13:30 +010033static char_u *readfile_charconvert(char_u *fname, char_u *fenc, int *fdp);
Bram Moolenaar071d4272004-06-13 20:20:40 +000034# endif
35#endif
36#ifdef FEAT_VIMINFO
Bram Moolenaard25c16e2016-01-29 22:13:30 +010037static void check_marks_read(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +000038#endif
39#ifdef FEAT_CRYPT
Bram Moolenaar8767f522016-07-01 17:17:39 +020040static char_u *check_for_cryptkey(char_u *cryptkey, char_u *ptr, long *sizep, off_T *filesizep, int newfile, char_u *fname, int *did_ask);
Bram Moolenaar071d4272004-06-13 20:20:40 +000041#endif
42#ifdef UNIX
Bram Moolenaard25c16e2016-01-29 22:13:30 +010043static void set_file_time(char_u *fname, time_t atime, time_t mtime);
Bram Moolenaar071d4272004-06-13 20:20:40 +000044#endif
Bram Moolenaard25c16e2016-01-29 22:13:30 +010045static int set_rw_fname(char_u *fname, char_u *sfname);
46static int msg_add_fileformat(int eol_type);
47static void msg_add_eol(void);
Bram Moolenaar8767f522016-07-01 17:17:39 +020048static int check_mtime(buf_T *buf, stat_T *s);
Bram Moolenaard25c16e2016-01-29 22:13:30 +010049static int time_differs(long t1, long t2);
Bram Moolenaard25c16e2016-01-29 22:13:30 +010050static int apply_autocmds_exarg(event_T event, char_u *fname, char_u *fname_io, int force, buf_T *buf, exarg_T *eap);
51static int au_find_group(char_u *name);
Bram Moolenaar70836c82006-02-20 21:28:49 +000052
53# define AUGROUP_DEFAULT -1 /* default autocmd group */
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +000054# define AUGROUP_ERROR -2 /* erroneous autocmd group */
Bram Moolenaar70836c82006-02-20 21:28:49 +000055# define AUGROUP_ALL -3 /* all autocmd groups */
Bram Moolenaar071d4272004-06-13 20:20:40 +000056
57#if defined(FEAT_CRYPT) || defined(FEAT_MBYTE)
58# define HAS_BW_FLAGS
59# define FIO_LATIN1 0x01 /* convert Latin1 */
60# define FIO_UTF8 0x02 /* convert UTF-8 */
61# define FIO_UCS2 0x04 /* convert UCS-2 */
62# define FIO_UCS4 0x08 /* convert UCS-4 */
63# define FIO_UTF16 0x10 /* convert UTF-16 */
64# ifdef WIN3264
65# define FIO_CODEPAGE 0x20 /* convert MS-Windows codepage */
66# define FIO_PUT_CP(x) (((x) & 0xffff) << 16) /* put codepage in top word */
67# define FIO_GET_CP(x) (((x)>>16) & 0xffff) /* get codepage from top word */
68# endif
Bram Moolenaard0573012017-10-28 21:11:06 +020069# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +000070# define FIO_MACROMAN 0x20 /* convert MacRoman */
71# endif
72# define FIO_ENDIAN_L 0x80 /* little endian */
73# define FIO_ENCRYPTED 0x1000 /* encrypt written bytes */
74# define FIO_NOCONVERT 0x2000 /* skip encoding conversion */
75# define FIO_UCSBOM 0x4000 /* check for BOM at start of file */
76# define FIO_ALL -1 /* allow all formats */
77#endif
78
79/* When converting, a read() or write() may leave some bytes to be converted
80 * for the next call. The value is guessed... */
81#define CONV_RESTLEN 30
82
83/* We have to guess how much a sequence of bytes may expand when converting
84 * with iconv() to be able to allocate a buffer. */
85#define ICONV_MULT 8
86
87/*
88 * Structure to pass arguments from buf_write() to buf_write_bytes().
89 */
90struct bw_info
91{
92 int bw_fd; /* file descriptor */
93 char_u *bw_buf; /* buffer with data to be written */
Bram Moolenaard089d9b2007-09-30 12:02:55 +000094 int bw_len; /* length of data */
Bram Moolenaar071d4272004-06-13 20:20:40 +000095#ifdef HAS_BW_FLAGS
96 int bw_flags; /* FIO_ flags */
97#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +020098#ifdef FEAT_CRYPT
99 buf_T *bw_buffer; /* buffer being written */
100#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000101#ifdef FEAT_MBYTE
102 char_u bw_rest[CONV_RESTLEN]; /* not converted bytes */
103 int bw_restlen; /* nr of bytes in bw_rest[] */
104 int bw_first; /* first write call */
105 char_u *bw_conv_buf; /* buffer for writing converted chars */
106 int bw_conv_buflen; /* size of bw_conv_buf */
107 int bw_conv_error; /* set for conversion error */
Bram Moolenaar32b485f2009-07-29 16:06:27 +0000108 linenr_T bw_conv_error_lnum; /* first line with error or zero */
109 linenr_T bw_start_lnum; /* line number at start of buffer */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000110# ifdef USE_ICONV
111 iconv_t bw_iconv_fd; /* descriptor for iconv() or -1 */
112# endif
113#endif
114};
115
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100116static int buf_write_bytes(struct bw_info *ip);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000117
118#ifdef FEAT_MBYTE
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100119static linenr_T readfile_linenr(linenr_T linecnt, char_u *p, char_u *endp);
120static int ucs2bytes(unsigned c, char_u **pp, int flags);
121static int need_conversion(char_u *fenc);
122static int get_fio_flags(char_u *ptr);
123static char_u *check_for_bom(char_u *p, long size, int *lenp, int flags);
124static int make_bom(char_u *buf, char_u *name);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000125# ifdef WIN3264
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100126static int get_win_fio_flags(char_u *ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000127# endif
Bram Moolenaard0573012017-10-28 21:11:06 +0200128# ifdef MACOS_CONVERT
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100129static int get_mac_fio_flags(char_u *ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000130# endif
131#endif
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100132static int move_lines(buf_T *frombuf, buf_T *tobuf);
Bram Moolenaar4592dee2009-11-18 19:11:58 +0000133#ifdef TEMPDIRNAMES
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100134static void vim_settempdir(char_u *tempdir);
Bram Moolenaar4592dee2009-11-18 19:11:58 +0000135#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000136static char *e_auchangedbuf = N_("E812: Autocommands changed buffer or buffer name");
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000137
Bram Moolenaarc3691332016-04-20 12:49:49 +0200138/*
139 * Set by the apply_autocmds_group function if the given event is equal to
140 * EVENT_FILETYPE. Used by the readfile function in order to determine if
141 * EVENT_BUFREADPOST triggered the EVENT_FILETYPE.
142 *
143 * Relying on this value requires one to reset it prior calling
144 * apply_autocmds_group.
145 */
146static int au_did_filetype INIT(= FALSE);
Bram Moolenaarc3691332016-04-20 12:49:49 +0200147
Bram Moolenaar071d4272004-06-13 20:20:40 +0000148 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +0100149filemess(
150 buf_T *buf,
151 char_u *name,
152 char_u *s,
153 int attr)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000154{
155 int msg_scroll_save;
156
157 if (msg_silent != 0)
158 return;
159 msg_add_fname(buf, name); /* put file name in IObuff with quotes */
160 /* If it's extremely long, truncate it. */
161 if (STRLEN(IObuff) > IOSIZE - 80)
162 IObuff[IOSIZE - 80] = NUL;
163 STRCAT(IObuff, s);
164 /*
165 * For the first message may have to start a new line.
166 * For further ones overwrite the previous one, reset msg_scroll before
167 * calling filemess().
168 */
169 msg_scroll_save = msg_scroll;
170 if (shortmess(SHM_OVERALL) && !exiting && p_verbose == 0)
171 msg_scroll = FALSE;
172 if (!msg_scroll) /* wait a bit when overwriting an error msg */
173 check_for_delay(FALSE);
174 msg_start();
175 msg_scroll = msg_scroll_save;
176 msg_scrolled_ign = TRUE;
177 /* may truncate the message to avoid a hit-return prompt */
178 msg_outtrans_attr(msg_may_trunc(FALSE, IObuff), attr);
179 msg_clr_eos();
180 out_flush();
181 msg_scrolled_ign = FALSE;
182}
183
184/*
185 * Read lines from file "fname" into the buffer after line "from".
186 *
187 * 1. We allocate blocks with lalloc, as big as possible.
188 * 2. Each block is filled with characters from the file with a single read().
189 * 3. The lines are inserted in the buffer with ml_append().
190 *
191 * (caller must check that fname != NULL, unless READ_STDIN is used)
192 *
193 * "lines_to_skip" is the number of lines that must be skipped
194 * "lines_to_read" is the number of lines that are appended
195 * When not recovering lines_to_skip is 0 and lines_to_read MAXLNUM.
196 *
197 * flags:
198 * READ_NEW starting to edit a new buffer
199 * READ_FILTER reading filter output
200 * READ_STDIN read from stdin instead of a file
201 * READ_BUFFER read from curbuf instead of a file (converting after reading
202 * stdin)
203 * READ_DUMMY read into a dummy buffer (to check if file contents changed)
Bram Moolenaar59f931e2010-07-24 20:27:03 +0200204 * READ_KEEP_UNDO don't clear undo info or read it from a file
Bram Moolenaarf71d7b92016-08-09 22:14:05 +0200205 * READ_FIFO read from fifo/socket instead of a file
Bram Moolenaar071d4272004-06-13 20:20:40 +0000206 *
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100207 * return FAIL for failure, NOTDONE for directory (failure), or OK
Bram Moolenaar071d4272004-06-13 20:20:40 +0000208 */
209 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +0100210readfile(
211 char_u *fname,
212 char_u *sfname,
213 linenr_T from,
214 linenr_T lines_to_skip,
215 linenr_T lines_to_read,
216 exarg_T *eap, /* can be NULL! */
217 int flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000218{
219 int fd = 0;
220 int newfile = (flags & READ_NEW);
221 int check_readonly;
222 int filtering = (flags & READ_FILTER);
223 int read_stdin = (flags & READ_STDIN);
224 int read_buffer = (flags & READ_BUFFER);
Bram Moolenaarf71d7b92016-08-09 22:14:05 +0200225 int read_fifo = (flags & READ_FIFO);
Bram Moolenaar690ffc02008-01-04 15:31:21 +0000226 int set_options = newfile || read_buffer
227 || (eap != NULL && eap->read_edit);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000228 linenr_T read_buf_lnum = 1; /* next line to read from curbuf */
229 colnr_T read_buf_col = 0; /* next char to read from this line */
230 char_u c;
231 linenr_T lnum = from;
232 char_u *ptr = NULL; /* pointer into read buffer */
233 char_u *buffer = NULL; /* read buffer */
234 char_u *new_buffer = NULL; /* init to shut up gcc */
235 char_u *line_start = NULL; /* init to shut up gcc */
236 int wasempty; /* buffer was empty before reading */
237 colnr_T len;
238 long size = 0;
239 char_u *p;
Bram Moolenaar8767f522016-07-01 17:17:39 +0200240 off_T filesize = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000241 int skip_read = FALSE;
242#ifdef FEAT_CRYPT
243 char_u *cryptkey = NULL;
Bram Moolenaarf50a2532010-05-21 15:36:08 +0200244 int did_ask_for_key = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000245#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +0200246#ifdef FEAT_PERSISTENT_UNDO
247 context_sha256_T sha_ctx;
248 int read_undo_file = FALSE;
249#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000250 int split = 0; /* number of split lines */
251#define UNKNOWN 0x0fffffff /* file size is unknown */
252 linenr_T linecnt;
253 int error = FALSE; /* errors encountered */
254 int ff_error = EOL_UNKNOWN; /* file format with errors */
255 long linerest = 0; /* remaining chars in line */
256#ifdef UNIX
257 int perm = 0;
258 int swap_mode = -1; /* protection bits for swap file */
259#else
260 int perm;
261#endif
262 int fileformat = 0; /* end-of-line format */
263 int keep_fileformat = FALSE;
Bram Moolenaar8767f522016-07-01 17:17:39 +0200264 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000265 int file_readonly;
266 linenr_T skip_count = 0;
267 linenr_T read_count = 0;
268 int msg_save = msg_scroll;
269 linenr_T read_no_eol_lnum = 0; /* non-zero lnum when last line of
270 * last read was missing the eol */
Bram Moolenaar7a2699e2017-01-23 21:31:09 +0100271 int try_mac;
272 int try_dos;
273 int try_unix;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000274 int file_rewind = FALSE;
275#ifdef FEAT_MBYTE
276 int can_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000277 linenr_T conv_error = 0; /* line nr with conversion error */
278 linenr_T illegal_byte = 0; /* line nr with illegal byte */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000279 int keep_dest_enc = FALSE; /* don't retry when char doesn't fit
280 in destination encoding */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000281 int bad_char_behavior = BAD_REPLACE;
282 /* BAD_KEEP, BAD_DROP or character to
283 * replace with */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000284 char_u *tmpname = NULL; /* name of 'charconvert' output file */
285 int fio_flags = 0;
286 char_u *fenc; /* fileencoding to use */
287 int fenc_alloced; /* fenc_next is in allocated memory */
288 char_u *fenc_next = NULL; /* next item in 'fencs' or NULL */
289 int advance_fenc = FALSE;
290 long real_size = 0;
291# ifdef USE_ICONV
292 iconv_t iconv_fd = (iconv_t)-1; /* descriptor for iconv() or -1 */
293# ifdef FEAT_EVAL
294 int did_iconv = FALSE; /* TRUE when iconv() failed and trying
295 'charconvert' next */
296# endif
297# endif
298 int converted = FALSE; /* TRUE if conversion done */
299 int notconverted = FALSE; /* TRUE if conversion wanted but it
300 wasn't possible */
301 char_u conv_rest[CONV_RESTLEN];
302 int conv_restlen = 0; /* nr of bytes in conv_rest[] */
303#endif
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200304 buf_T *old_curbuf;
305 char_u *old_b_ffname;
306 char_u *old_b_fname;
307 int using_b_ffname;
308 int using_b_fname;
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200309
Bram Moolenaarc3691332016-04-20 12:49:49 +0200310 au_did_filetype = FALSE; /* reset before triggering any autocommands */
Bram Moolenaarc3691332016-04-20 12:49:49 +0200311
Bram Moolenaarcab35ad2011-02-15 17:39:22 +0100312 curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000313
314 /*
315 * If there is no file name yet, use the one for the read file.
316 * BF_NOTEDITED is set to reflect this.
317 * Don't do this for a read from a filter.
318 * Only do this when 'cpoptions' contains the 'f' flag.
319 */
320 if (curbuf->b_ffname == NULL
321 && !filtering
322 && fname != NULL
323 && vim_strchr(p_cpo, CPO_FNAMER) != NULL
324 && !(flags & READ_DUMMY))
325 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000326 if (set_rw_fname(fname, sfname) == FAIL)
327 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000328 }
329
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200330 /* Remember the initial values of curbuf, curbuf->b_ffname and
331 * curbuf->b_fname to detect whether they are altered as a result of
332 * executing nasty autocommands. Also check if "fname" and "sfname"
333 * point to one of these values. */
334 old_curbuf = curbuf;
335 old_b_ffname = curbuf->b_ffname;
336 old_b_fname = curbuf->b_fname;
337 using_b_ffname = (fname == curbuf->b_ffname)
338 || (sfname == curbuf->b_ffname);
339 using_b_fname = (fname == curbuf->b_fname) || (sfname == curbuf->b_fname);
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200340
Bram Moolenaardf177f62005-02-22 08:39:57 +0000341 /* After reading a file the cursor line changes but we don't want to
342 * display the line. */
343 ex_no_reprint = TRUE;
344
Bram Moolenaar55b7cf82006-09-09 12:52:42 +0000345 /* don't display the file info for another buffer now */
346 need_fileinfo = FALSE;
347
Bram Moolenaar071d4272004-06-13 20:20:40 +0000348 /*
349 * For Unix: Use the short file name whenever possible.
350 * Avoids problems with networks and when directory names are changed.
351 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
352 * another directory, which we don't detect.
353 */
354 if (sfname == NULL)
355 sfname = fname;
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200356#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000357 fname = sfname;
358#endif
359
Bram Moolenaar071d4272004-06-13 20:20:40 +0000360 /*
361 * The BufReadCmd and FileReadCmd events intercept the reading process by
362 * executing the associated commands instead.
363 */
364 if (!filtering && !read_stdin && !read_buffer)
365 {
366 pos_T pos;
367
368 pos = curbuf->b_op_start;
369
370 /* Set '[ mark to the line above where the lines go (line 1 if zero). */
371 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
372 curbuf->b_op_start.col = 0;
373
374 if (newfile)
375 {
376 if (apply_autocmds_exarg(EVENT_BUFREADCMD, NULL, sfname,
377 FALSE, curbuf, eap))
378#ifdef FEAT_EVAL
379 return aborting() ? FAIL : OK;
380#else
381 return OK;
382#endif
383 }
384 else if (apply_autocmds_exarg(EVENT_FILEREADCMD, sfname, sfname,
385 FALSE, NULL, eap))
386#ifdef FEAT_EVAL
387 return aborting() ? FAIL : OK;
388#else
389 return OK;
390#endif
391
392 curbuf->b_op_start = pos;
393 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000394
395 if ((shortmess(SHM_OVER) || curbuf->b_help) && p_verbose == 0)
396 msg_scroll = FALSE; /* overwrite previous file message */
397 else
398 msg_scroll = TRUE; /* don't overwrite previous file message */
399
400 /*
401 * If the name ends in a path separator, we can't open it. Check here,
402 * because reading the file may actually work, but then creating the swap
403 * file may destroy it! Reported on MS-DOS and Win 95.
404 * If the name is too long we might crash further on, quit here.
405 */
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000406 if (fname != NULL && *fname != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000407 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000408 p = fname + STRLEN(fname);
409 if (after_pathsep(fname, p) || STRLEN(fname) >= MAXPATHL)
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000410 {
411 filemess(curbuf, fname, (char_u *)_("Illegal file name"), 0);
412 msg_end();
413 msg_scroll = msg_save;
414 return FAIL;
415 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000416 }
417
Bram Moolenaarf71d7b92016-08-09 22:14:05 +0200418 if (!read_stdin && !read_buffer && !read_fifo)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000419 {
Bram Moolenaar4e4f5292013-08-30 17:07:01 +0200420#ifdef UNIX
421 /*
422 * On Unix it is possible to read a directory, so we have to
423 * check for it before the mch_open().
424 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000425 perm = mch_getperm(fname);
426 if (perm >= 0 && !S_ISREG(perm) /* not a regular file ... */
427# ifdef S_ISFIFO
428 && !S_ISFIFO(perm) /* ... or fifo */
429# endif
430# ifdef S_ISSOCK
431 && !S_ISSOCK(perm) /* ... or socket */
432# endif
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +0000433# ifdef OPEN_CHR_FILES
434 && !(S_ISCHR(perm) && is_dev_fd_file(fname))
435 /* ... or a character special file named /dev/fd/<n> */
436# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000437 )
438 {
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100439 int retval = FAIL;
440
Bram Moolenaar071d4272004-06-13 20:20:40 +0000441 if (S_ISDIR(perm))
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100442 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000443 filemess(curbuf, fname, (char_u *)_("is a directory"), 0);
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100444 retval = NOTDONE;
445 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000446 else
447 filemess(curbuf, fname, (char_u *)_("is not a file"), 0);
448 msg_end();
449 msg_scroll = msg_save;
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100450 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000451 }
Bram Moolenaar4e4f5292013-08-30 17:07:01 +0200452#endif
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100453#if defined(MSWIN)
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000454 /*
455 * MS-Windows allows opening a device, but we will probably get stuck
456 * trying to read it.
457 */
458 if (!p_odev && mch_nodetype(fname) == NODE_WRITABLE)
459 {
Bram Moolenaar5386a122007-06-28 20:02:32 +0000460 filemess(curbuf, fname, (char_u *)_("is a device (disabled with 'opendevice' option)"), 0);
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000461 msg_end();
462 msg_scroll = msg_save;
463 return FAIL;
464 }
Bram Moolenaar043545e2006-10-10 16:44:07 +0000465#endif
Bram Moolenaar4e4f5292013-08-30 17:07:01 +0200466 }
Bram Moolenaar043545e2006-10-10 16:44:07 +0000467
Bram Moolenaarad875fb2013-07-24 15:02:03 +0200468 /* Set default or forced 'fileformat' and 'binary'. */
469 set_file_options(set_options, eap);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000470
471 /*
472 * When opening a new file we take the readonly flag from the file.
473 * Default is r/w, can be set to r/o below.
474 * Don't reset it when in readonly mode
475 * Only set/reset b_p_ro when BF_CHECK_RO is set.
476 */
477 check_readonly = (newfile && (curbuf->b_flags & BF_CHECK_RO));
Bram Moolenaar4399ef42005-02-12 14:29:27 +0000478 if (check_readonly && !readonlymode)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000479 curbuf->b_p_ro = FALSE;
480
Bram Moolenaarf71d7b92016-08-09 22:14:05 +0200481 if (newfile && !read_stdin && !read_buffer && !read_fifo)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000482 {
Bram Moolenaare60acc12011-05-10 16:41:25 +0200483 /* Remember time of file. */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000484 if (mch_stat((char *)fname, &st) >= 0)
485 {
486 buf_store_time(curbuf, &st, fname);
487 curbuf->b_mtime_read = curbuf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000488#ifdef UNIX
489 /*
490 * Use the protection bits of the original file for the swap file.
491 * This makes it possible for others to read the name of the
492 * edited file from the swapfile, but only if they can read the
493 * edited file.
494 * Remove the "write" and "execute" bits for group and others
495 * (they must not write the swapfile).
496 * Add the "read" and "write" bits for the user, otherwise we may
497 * not be able to write to the file ourselves.
498 * Setting the bits is done below, after creating the swap file.
499 */
500 swap_mode = (st.st_mode & 0644) | 0600;
501#endif
502#ifdef FEAT_CW_EDITOR
503 /* Get the FSSpec on MacOS
504 * TODO: Update it properly when the buffer name changes
505 */
506 (void)GetFSSpecFromPath(curbuf->b_ffname, &curbuf->b_FSSpec);
507#endif
508#ifdef VMS
509 curbuf->b_fab_rfm = st.st_fab_rfm;
Bram Moolenaard4755bb2004-09-02 19:12:26 +0000510 curbuf->b_fab_rat = st.st_fab_rat;
511 curbuf->b_fab_mrs = st.st_fab_mrs;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000512#endif
513 }
514 else
515 {
516 curbuf->b_mtime = 0;
517 curbuf->b_mtime_read = 0;
518 curbuf->b_orig_size = 0;
519 curbuf->b_orig_mode = 0;
520 }
521
522 /* Reset the "new file" flag. It will be set again below when the
523 * file doesn't exist. */
524 curbuf->b_flags &= ~(BF_NEW | BF_NEW_W);
525 }
526
527/*
528 * for UNIX: check readonly with perm and mch_access()
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100529 * for Amiga: check readonly by trying to open the file for writing
Bram Moolenaar071d4272004-06-13 20:20:40 +0000530 */
531 file_readonly = FALSE;
532 if (read_stdin)
533 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100534#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000535 /* Force binary I/O on stdin to avoid CR-LF -> LF conversion. */
536 setmode(0, O_BINARY);
537#endif
538 }
539 else if (!read_buffer)
540 {
541#ifdef USE_MCH_ACCESS
542 if (
543# ifdef UNIX
544 !(perm & 0222) ||
545# endif
546 mch_access((char *)fname, W_OK))
547 file_readonly = TRUE;
548 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
549#else
550 if (!newfile
551 || readonlymode
552 || (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0)
553 {
554 file_readonly = TRUE;
555 /* try to open ro */
556 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
557 }
558#endif
559 }
560
561 if (fd < 0) /* cannot open at all */
562 {
563#ifndef UNIX
564 int isdir_f;
565#endif
566 msg_scroll = msg_save;
567#ifndef UNIX
568 /*
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100569 * On Amiga we can't open a directory, check here.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000570 */
571 isdir_f = (mch_isdir(fname));
572 perm = mch_getperm(fname); /* check if the file exists */
573 if (isdir_f)
574 {
575 filemess(curbuf, sfname, (char_u *)_("is a directory"), 0);
576 curbuf->b_p_ro = TRUE; /* must use "w!" now */
577 }
578 else
579#endif
580 if (newfile)
581 {
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200582 if (perm < 0
583#ifdef ENOENT
584 && errno == ENOENT
585#endif
586 )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000587 {
588 /*
589 * Set the 'new-file' flag, so that when the file has
590 * been created by someone else, a ":w" will complain.
591 */
592 curbuf->b_flags |= BF_NEW;
593
594 /* Create a swap file now, so that other Vims are warned
595 * that we are editing this file. Don't do this for a
596 * "nofile" or "nowrite" buffer type. */
597#ifdef FEAT_QUICKFIX
598 if (!bt_dontwrite(curbuf))
599#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000600 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000601 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000602 /* SwapExists autocommand may mess things up */
603 if (curbuf != old_curbuf
604 || (using_b_ffname
605 && (old_b_ffname != curbuf->b_ffname))
606 || (using_b_fname
607 && (old_b_fname != curbuf->b_fname)))
608 {
609 EMSG(_(e_auchangedbuf));
610 return FAIL;
611 }
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000612 }
Bram Moolenaar5b962cf2005-12-12 21:58:40 +0000613 if (dir_of_file_exists(fname))
614 filemess(curbuf, sfname, (char_u *)_("[New File]"), 0);
615 else
616 filemess(curbuf, sfname,
617 (char_u *)_("[New DIRECTORY]"), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000618#ifdef FEAT_VIMINFO
619 /* Even though this is a new file, it might have been
620 * edited before and deleted. Get the old marks. */
621 check_marks_read();
622#endif
623#ifdef FEAT_MBYTE
Bram Moolenaarad875fb2013-07-24 15:02:03 +0200624 /* Set forced 'fileencoding'. */
625 if (eap != NULL)
626 set_forced_fenc(eap);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000627#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000628 apply_autocmds_exarg(EVENT_BUFNEWFILE, sfname, sfname,
629 FALSE, curbuf, eap);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000630 /* remember the current fileformat */
631 save_file_ff(curbuf);
632
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +0100633#if defined(FEAT_EVAL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000634 if (aborting()) /* autocmds may abort script processing */
635 return FAIL;
636#endif
637 return OK; /* a new file is not an error */
638 }
639 else
640 {
Bram Moolenaar202795b2005-10-11 20:29:39 +0000641 filemess(curbuf, sfname, (char_u *)(
642# ifdef EFBIG
643 (errno == EFBIG) ? _("[File too big]") :
644# endif
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200645# ifdef EOVERFLOW
646 (errno == EOVERFLOW) ? _("[File too big]") :
647# endif
Bram Moolenaar202795b2005-10-11 20:29:39 +0000648 _("[Permission Denied]")), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000649 curbuf->b_p_ro = TRUE; /* must use "w!" now */
650 }
651 }
652
653 return FAIL;
654 }
655
656 /*
657 * Only set the 'ro' flag for readonly files the first time they are
658 * loaded. Help files always get readonly mode
659 */
660 if ((check_readonly && file_readonly) || curbuf->b_help)
661 curbuf->b_p_ro = TRUE;
662
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000663 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000664 {
Bram Moolenaar690ffc02008-01-04 15:31:21 +0000665 /* Don't change 'eol' if reading from buffer as it will already be
666 * correctly set when reading stdin. */
667 if (!read_buffer)
668 {
669 curbuf->b_p_eol = TRUE;
670 curbuf->b_start_eol = TRUE;
671 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000672#ifdef FEAT_MBYTE
673 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000674 curbuf->b_start_bomb = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000675#endif
676 }
677
678 /* Create a swap file now, so that other Vims are warned that we are
679 * editing this file.
680 * Don't do this for a "nofile" or "nowrite" buffer type. */
681#ifdef FEAT_QUICKFIX
682 if (!bt_dontwrite(curbuf))
683#endif
684 {
685 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000686 if (!read_stdin && (curbuf != old_curbuf
687 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
688 || (using_b_fname && (old_b_fname != curbuf->b_fname))))
689 {
690 EMSG(_(e_auchangedbuf));
691 if (!read_buffer)
692 close(fd);
693 return FAIL;
694 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000695#ifdef UNIX
696 /* Set swap file protection bits after creating it. */
Bram Moolenaarf061e0b2009-06-24 15:32:01 +0000697 if (swap_mode > 0 && curbuf->b_ml.ml_mfp != NULL
698 && curbuf->b_ml.ml_mfp->mf_fname != NULL)
Bram Moolenaar5a73e0c2017-11-04 21:35:01 +0100699 {
700 char_u *swap_fname = curbuf->b_ml.ml_mfp->mf_fname;
701
702 /*
703 * If the group-read bit is set but not the world-read bit, then
704 * the group must be equal to the group of the original file. If
705 * we can't make that happen then reset the group-read bit. This
706 * avoids making the swap file readable to more users when the
707 * primary group of the user is too permissive.
708 */
709 if ((swap_mode & 044) == 040)
710 {
711 stat_T swap_st;
712
713 if (mch_stat((char *)swap_fname, &swap_st) >= 0
714 && st.st_gid != swap_st.st_gid
Bram Moolenaar02e802b2018-04-19 21:15:27 +0200715# ifdef HAVE_FCHOWN
Bram Moolenaar5a73e0c2017-11-04 21:35:01 +0100716 && fchown(curbuf->b_ml.ml_mfp->mf_fd, -1, st.st_gid)
Bram Moolenaar02e802b2018-04-19 21:15:27 +0200717# endif
718 == -1
719 )
Bram Moolenaar5a73e0c2017-11-04 21:35:01 +0100720 swap_mode &= 0600;
721 }
722
723 (void)mch_setperm(swap_fname, (long)swap_mode);
724 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000725#endif
726 }
727
Bram Moolenaarb815dac2005-12-07 20:59:24 +0000728#if defined(HAS_SWAP_EXISTS_ACTION)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000729 /* If "Quit" selected at ATTENTION dialog, don't load the file */
730 if (swap_exists_action == SEA_QUIT)
731 {
732 if (!read_buffer && !read_stdin)
733 close(fd);
734 return FAIL;
735 }
736#endif
737
738 ++no_wait_return; /* don't wait for return yet */
739
740 /*
741 * Set '[ mark to the line above where the lines go (line 1 if zero).
742 */
743 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
744 curbuf->b_op_start.col = 0;
745
Bram Moolenaar7a2699e2017-01-23 21:31:09 +0100746 try_mac = (vim_strchr(p_ffs, 'm') != NULL);
747 try_dos = (vim_strchr(p_ffs, 'd') != NULL);
748 try_unix = (vim_strchr(p_ffs, 'x') != NULL);
749
Bram Moolenaar071d4272004-06-13 20:20:40 +0000750 if (!read_buffer)
751 {
752 int m = msg_scroll;
753 int n = msg_scrolled;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000754
755 /*
756 * The file must be closed again, the autocommands may want to change
757 * the file before reading it.
758 */
759 if (!read_stdin)
760 close(fd); /* ignore errors */
761
762 /*
763 * The output from the autocommands should not overwrite anything and
764 * should not be overwritten: Set msg_scroll, restore its value if no
765 * output was done.
766 */
767 msg_scroll = TRUE;
768 if (filtering)
769 apply_autocmds_exarg(EVENT_FILTERREADPRE, NULL, sfname,
770 FALSE, curbuf, eap);
771 else if (read_stdin)
772 apply_autocmds_exarg(EVENT_STDINREADPRE, NULL, sfname,
773 FALSE, curbuf, eap);
774 else if (newfile)
775 apply_autocmds_exarg(EVENT_BUFREADPRE, NULL, sfname,
776 FALSE, curbuf, eap);
777 else
778 apply_autocmds_exarg(EVENT_FILEREADPRE, sfname, sfname,
779 FALSE, NULL, eap);
Bram Moolenaar7a2699e2017-01-23 21:31:09 +0100780 /* autocommands may have changed it */
781 try_mac = (vim_strchr(p_ffs, 'm') != NULL);
782 try_dos = (vim_strchr(p_ffs, 'd') != NULL);
783 try_unix = (vim_strchr(p_ffs, 'x') != NULL);
784
Bram Moolenaar071d4272004-06-13 20:20:40 +0000785 if (msg_scrolled == n)
786 msg_scroll = m;
787
788#ifdef FEAT_EVAL
789 if (aborting()) /* autocmds may abort script processing */
790 {
791 --no_wait_return;
792 msg_scroll = msg_save;
793 curbuf->b_p_ro = TRUE; /* must use "w!" now */
794 return FAIL;
795 }
796#endif
797 /*
798 * Don't allow the autocommands to change the current buffer.
799 * Try to re-open the file.
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000800 *
801 * Don't allow the autocommands to change the buffer name either
802 * (cd for example) if it invalidates fname or sfname.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000803 */
804 if (!read_stdin && (curbuf != old_curbuf
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000805 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
806 || (using_b_fname && (old_b_fname != curbuf->b_fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000807 || (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) < 0))
808 {
809 --no_wait_return;
810 msg_scroll = msg_save;
811 if (fd < 0)
812 EMSG(_("E200: *ReadPre autocommands made the file unreadable"));
813 else
814 EMSG(_("E201: *ReadPre autocommands must not change current buffer"));
815 curbuf->b_p_ro = TRUE; /* must use "w!" now */
816 return FAIL;
817 }
818 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000819
820 /* Autocommands may add lines to the file, need to check if it is empty */
821 wasempty = (curbuf->b_ml.ml_flags & ML_EMPTY);
822
823 if (!recoverymode && !filtering && !(flags & READ_DUMMY))
824 {
825 /*
826 * Show the user that we are busy reading the input. Sometimes this
827 * may take a while. When reading from stdin another program may
828 * still be running, don't move the cursor to the last line, unless
829 * always using the GUI.
830 */
831 if (read_stdin)
832 {
Bram Moolenaar234d1622017-11-18 14:55:23 +0100833 if (!is_not_a_term())
834 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000835#ifndef ALWAYS_USE_GUI
Bram Moolenaar234d1622017-11-18 14:55:23 +0100836 mch_msg(_("Vim: Reading from stdin...\n"));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000837#endif
838#ifdef FEAT_GUI
Bram Moolenaar234d1622017-11-18 14:55:23 +0100839 /* Also write a message in the GUI window, if there is one. */
840 if (gui.in_use && !gui.dying && !gui.starting)
841 {
842 p = (char_u *)_("Reading from stdin...");
843 gui_write(p, (int)STRLEN(p));
844 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000845#endif
Bram Moolenaar234d1622017-11-18 14:55:23 +0100846 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000847 }
848 else if (!read_buffer)
849 filemess(curbuf, sfname, (char_u *)"", 0);
850 }
851
852 msg_scroll = FALSE; /* overwrite the file message */
853
854 /*
855 * Set linecnt now, before the "retry" caused by a wrong guess for
856 * fileformat, and after the autocommands, which may change them.
857 */
858 linecnt = curbuf->b_ml.ml_line_count;
859
860#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000861 /* "++bad=" argument. */
862 if (eap != NULL && eap->bad_char != 0)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000863 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000864 bad_char_behavior = eap->bad_char;
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000865 if (set_options)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000866 curbuf->b_bad_char = eap->bad_char;
867 }
868 else
869 curbuf->b_bad_char = 0;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000870
Bram Moolenaar071d4272004-06-13 20:20:40 +0000871 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000872 * Decide which 'encoding' to use or use first.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000873 */
874 if (eap != NULL && eap->force_enc != 0)
875 {
876 fenc = enc_canonize(eap->cmd + eap->force_enc);
877 fenc_alloced = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000878 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000879 }
880 else if (curbuf->b_p_bin)
881 {
882 fenc = (char_u *)""; /* binary: don't convert */
883 fenc_alloced = FALSE;
884 }
885 else if (curbuf->b_help)
886 {
887 char_u firstline[80];
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000888 int fc;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000889
890 /* Help files are either utf-8 or latin1. Try utf-8 first, if this
891 * fails it must be latin1.
892 * Always do this when 'encoding' is "utf-8". Otherwise only do
893 * this when needed to avoid [converted] remarks all the time.
894 * It is needed when the first line contains non-ASCII characters.
895 * That is only in *.??x files. */
896 fenc = (char_u *)"latin1";
897 c = enc_utf8;
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000898 if (!c && !read_stdin)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000899 {
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000900 fc = fname[STRLEN(fname) - 1];
901 if (TOLOWER_ASC(fc) == 'x')
902 {
903 /* Read the first line (and a bit more). Immediately rewind to
904 * the start of the file. If the read() fails "len" is -1. */
Bram Moolenaar540fc6f2010-12-17 16:27:16 +0100905 len = read_eintr(fd, firstline, 80);
Bram Moolenaar8767f522016-07-01 17:17:39 +0200906 vim_lseek(fd, (off_T)0L, SEEK_SET);
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000907 for (p = firstline; p < firstline + len; ++p)
908 if (*p >= 0x80)
909 {
910 c = TRUE;
911 break;
912 }
913 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000914 }
915
916 if (c)
917 {
918 fenc_next = fenc;
919 fenc = (char_u *)"utf-8";
920
921 /* When the file is utf-8 but a character doesn't fit in
922 * 'encoding' don't retry. In help text editing utf-8 bytes
923 * doesn't make sense. */
Bram Moolenaarf193fff2006-04-27 00:02:13 +0000924 if (!enc_utf8)
925 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000926 }
927 fenc_alloced = FALSE;
928 }
929 else if (*p_fencs == NUL)
930 {
931 fenc = curbuf->b_p_fenc; /* use format from buffer */
932 fenc_alloced = FALSE;
933 }
934 else
935 {
936 fenc_next = p_fencs; /* try items in 'fileencodings' */
937 fenc = next_fenc(&fenc_next);
938 fenc_alloced = TRUE;
939 }
940#endif
941
942 /*
943 * Jump back here to retry reading the file in different ways.
944 * Reasons to retry:
945 * - encoding conversion failed: try another one from "fenc_next"
946 * - BOM detected and fenc was set, need to setup conversion
947 * - "fileformat" check failed: try another
948 *
949 * Variables set for special retry actions:
950 * "file_rewind" Rewind the file to start reading it again.
951 * "advance_fenc" Advance "fenc" using "fenc_next".
952 * "skip_read" Re-use already read bytes (BOM detected).
953 * "did_iconv" iconv() conversion failed, try 'charconvert'.
954 * "keep_fileformat" Don't reset "fileformat".
955 *
956 * Other status indicators:
957 * "tmpname" When != NULL did conversion with 'charconvert'.
958 * Output file has to be deleted afterwards.
959 * "iconv_fd" When != -1 did conversion with iconv().
960 */
961retry:
962
963 if (file_rewind)
964 {
965 if (read_buffer)
966 {
967 read_buf_lnum = 1;
968 read_buf_col = 0;
969 }
Bram Moolenaar8767f522016-07-01 17:17:39 +0200970 else if (read_stdin || vim_lseek(fd, (off_T)0L, SEEK_SET) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000971 {
972 /* Can't rewind the file, give up. */
973 error = TRUE;
974 goto failed;
975 }
976 /* Delete the previously read lines. */
977 while (lnum > from)
978 ml_delete(lnum--, FALSE);
979 file_rewind = FALSE;
980#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000981 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000982 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000983 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000984 curbuf->b_start_bomb = FALSE;
985 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000986 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000987#endif
988 }
989
990 /*
991 * When retrying with another "fenc" and the first time "fileformat"
992 * will be reset.
993 */
994 if (keep_fileformat)
995 keep_fileformat = FALSE;
996 else
997 {
998 if (eap != NULL && eap->force_ff != 0)
Bram Moolenaar1c860362008-11-12 15:05:21 +0000999 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001000 fileformat = get_fileformat_force(curbuf, eap);
Bram Moolenaar1c860362008-11-12 15:05:21 +00001001 try_unix = try_dos = try_mac = FALSE;
1002 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001003 else if (curbuf->b_p_bin)
1004 fileformat = EOL_UNIX; /* binary: use Unix format */
1005 else if (*p_ffs == NUL)
1006 fileformat = get_fileformat(curbuf);/* use format from buffer */
1007 else
1008 fileformat = EOL_UNKNOWN; /* detect from file */
1009 }
1010
1011#ifdef FEAT_MBYTE
1012# ifdef USE_ICONV
1013 if (iconv_fd != (iconv_t)-1)
1014 {
1015 /* aborted conversion with iconv(), close the descriptor */
1016 iconv_close(iconv_fd);
1017 iconv_fd = (iconv_t)-1;
1018 }
1019# endif
1020
1021 if (advance_fenc)
1022 {
1023 /*
1024 * Try the next entry in 'fileencodings'.
1025 */
1026 advance_fenc = FALSE;
1027
1028 if (eap != NULL && eap->force_enc != 0)
1029 {
1030 /* Conversion given with "++cc=" wasn't possible, read
1031 * without conversion. */
1032 notconverted = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001033 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001034 if (fenc_alloced)
1035 vim_free(fenc);
1036 fenc = (char_u *)"";
1037 fenc_alloced = FALSE;
1038 }
1039 else
1040 {
1041 if (fenc_alloced)
1042 vim_free(fenc);
1043 if (fenc_next != NULL)
1044 {
1045 fenc = next_fenc(&fenc_next);
1046 fenc_alloced = (fenc_next != NULL);
1047 }
1048 else
1049 {
1050 fenc = (char_u *)"";
1051 fenc_alloced = FALSE;
1052 }
1053 }
1054 if (tmpname != NULL)
1055 {
1056 mch_remove(tmpname); /* delete converted file */
Bram Moolenaard23a8232018-02-10 18:45:26 +01001057 VIM_CLEAR(tmpname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001058 }
1059 }
1060
1061 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001062 * Conversion may be required when the encoding of the file is different
1063 * from 'encoding' or 'encoding' is UTF-16, UCS-2 or UCS-4.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001064 */
1065 fio_flags = 0;
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001066 converted = need_conversion(fenc);
1067 if (converted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001068 {
1069
1070 /* "ucs-bom" means we need to check the first bytes of the file
1071 * for a BOM. */
1072 if (STRCMP(fenc, ENC_UCSBOM) == 0)
1073 fio_flags = FIO_UCSBOM;
1074
1075 /*
1076 * Check if UCS-2/4 or Latin1 to UTF-8 conversion needs to be
1077 * done. This is handled below after read(). Prepare the
1078 * fio_flags to avoid having to parse the string each time.
1079 * Also check for Unicode to Latin1 conversion, because iconv()
1080 * appears not to handle this correctly. This works just like
1081 * conversion to UTF-8 except how the resulting character is put in
1082 * the buffer.
1083 */
1084 else if (enc_utf8 || STRCMP(p_enc, "latin1") == 0)
1085 fio_flags = get_fio_flags(fenc);
1086
1087# ifdef WIN3264
1088 /*
1089 * Conversion from an MS-Windows codepage to UTF-8 or another codepage
1090 * is handled with MultiByteToWideChar().
1091 */
1092 if (fio_flags == 0)
1093 fio_flags = get_win_fio_flags(fenc);
1094# endif
1095
Bram Moolenaard0573012017-10-28 21:11:06 +02001096# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001097 /* Conversion from Apple MacRoman to latin1 or UTF-8 */
1098 if (fio_flags == 0)
1099 fio_flags = get_mac_fio_flags(fenc);
1100# endif
1101
1102# ifdef USE_ICONV
1103 /*
1104 * Try using iconv() if we can't convert internally.
1105 */
1106 if (fio_flags == 0
1107# ifdef FEAT_EVAL
1108 && !did_iconv
1109# endif
1110 )
1111 iconv_fd = (iconv_t)my_iconv_open(
1112 enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc);
1113# endif
1114
1115# ifdef FEAT_EVAL
1116 /*
1117 * Use the 'charconvert' expression when conversion is required
1118 * and we can't do it internally or with iconv().
1119 */
1120 if (fio_flags == 0 && !read_stdin && !read_buffer && *p_ccv != NUL
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02001121 && !read_fifo
Bram Moolenaar071d4272004-06-13 20:20:40 +00001122# ifdef USE_ICONV
1123 && iconv_fd == (iconv_t)-1
1124# endif
1125 )
1126 {
1127# ifdef USE_ICONV
1128 did_iconv = FALSE;
1129# endif
1130 /* Skip conversion when it's already done (retry for wrong
1131 * "fileformat"). */
1132 if (tmpname == NULL)
1133 {
1134 tmpname = readfile_charconvert(fname, fenc, &fd);
1135 if (tmpname == NULL)
1136 {
1137 /* Conversion failed. Try another one. */
1138 advance_fenc = TRUE;
1139 if (fd < 0)
1140 {
1141 /* Re-opening the original file failed! */
1142 EMSG(_("E202: Conversion made file unreadable!"));
1143 error = TRUE;
1144 goto failed;
1145 }
1146 goto retry;
1147 }
1148 }
1149 }
1150 else
1151# endif
1152 {
1153 if (fio_flags == 0
1154# ifdef USE_ICONV
1155 && iconv_fd == (iconv_t)-1
1156# endif
1157 )
1158 {
1159 /* Conversion wanted but we can't.
1160 * Try the next conversion in 'fileencodings' */
1161 advance_fenc = TRUE;
1162 goto retry;
1163 }
1164 }
1165 }
1166
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001167 /* Set "can_retry" when it's possible to rewind the file and try with
Bram Moolenaar071d4272004-06-13 20:20:40 +00001168 * another "fenc" value. It's FALSE when no other "fenc" to try, reading
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001169 * stdin or fixed at a specific encoding. */
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02001170 can_retry = (*fenc != NUL && !read_stdin && !read_fifo && !keep_dest_enc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001171#endif
1172
1173 if (!skip_read)
1174 {
1175 linerest = 0;
1176 filesize = 0;
1177 skip_count = lines_to_skip;
1178 read_count = lines_to_read;
1179#ifdef FEAT_MBYTE
1180 conv_restlen = 0;
1181#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001182#ifdef FEAT_PERSISTENT_UNDO
Bram Moolenaar59f931e2010-07-24 20:27:03 +02001183 read_undo_file = (newfile && (flags & READ_KEEP_UNDO) == 0
1184 && curbuf->b_ffname != NULL
1185 && curbuf->b_p_udf
1186 && !filtering
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02001187 && !read_fifo
Bram Moolenaar59f931e2010-07-24 20:27:03 +02001188 && !read_stdin
1189 && !read_buffer);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001190 if (read_undo_file)
1191 sha256_start(&sha_ctx);
1192#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001193#ifdef FEAT_CRYPT
1194 if (curbuf->b_cryptstate != NULL)
1195 {
1196 /* Need to free the state, but keep the key, don't want to ask for
1197 * it again. */
1198 crypt_free_state(curbuf->b_cryptstate);
1199 curbuf->b_cryptstate = NULL;
1200 }
1201#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001202 }
1203
1204 while (!error && !got_int)
1205 {
1206 /*
1207 * We allocate as much space for the file as we can get, plus
1208 * space for the old line plus room for one terminating NUL.
1209 * The amount is limited by the fact that read() only can read
1210 * upto max_unsigned characters (and other things).
1211 */
Bram Moolenaara2aa31a2014-02-23 22:52:40 +01001212#if VIM_SIZEOF_INT <= 2
Bram Moolenaar071d4272004-06-13 20:20:40 +00001213 if (linerest >= 0x7ff0)
1214 {
1215 ++split;
1216 *ptr = NL; /* split line by inserting a NL */
1217 size = 1;
1218 }
1219 else
1220#endif
1221 {
1222 if (!skip_read)
1223 {
Bram Moolenaara2aa31a2014-02-23 22:52:40 +01001224#if VIM_SIZEOF_INT > 2
Bram Moolenaar311d9822007-02-27 15:48:28 +00001225# if defined(SSIZE_MAX) && (SSIZE_MAX < 0x10000L)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001226 size = SSIZE_MAX; /* use max I/O size, 52K */
1227# else
1228 size = 0x10000L; /* use buffer >= 64K */
1229# endif
1230#else
1231 size = 0x7ff0L - linerest; /* limit buffer to 32K */
1232#endif
1233
Bram Moolenaarc1e37902006-04-18 21:55:01 +00001234 for ( ; size >= 10; size = (long)((long_u)size >> 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001235 {
1236 if ((new_buffer = lalloc((long_u)(size + linerest + 1),
1237 FALSE)) != NULL)
1238 break;
1239 }
1240 if (new_buffer == NULL)
1241 {
1242 do_outofmem_msg((long_u)(size * 2 + linerest + 1));
1243 error = TRUE;
1244 break;
1245 }
1246 if (linerest) /* copy characters from the previous buffer */
1247 mch_memmove(new_buffer, ptr - linerest, (size_t)linerest);
1248 vim_free(buffer);
1249 buffer = new_buffer;
1250 ptr = buffer + linerest;
1251 line_start = buffer;
1252
1253#ifdef FEAT_MBYTE
1254 /* May need room to translate into.
1255 * For iconv() we don't really know the required space, use a
1256 * factor ICONV_MULT.
1257 * latin1 to utf-8: 1 byte becomes up to 2 bytes
1258 * utf-16 to utf-8: 2 bytes become up to 3 bytes, 4 bytes
1259 * become up to 4 bytes, size must be multiple of 2
1260 * ucs-2 to utf-8: 2 bytes become up to 3 bytes, size must be
1261 * multiple of 2
1262 * ucs-4 to utf-8: 4 bytes become up to 6 bytes, size must be
1263 * multiple of 4 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001264 real_size = (int)size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001265# ifdef USE_ICONV
1266 if (iconv_fd != (iconv_t)-1)
1267 size = size / ICONV_MULT;
1268 else
1269# endif
1270 if (fio_flags & FIO_LATIN1)
1271 size = size / 2;
1272 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1273 size = (size * 2 / 3) & ~1;
1274 else if (fio_flags & FIO_UCS4)
1275 size = (size * 2 / 3) & ~3;
1276 else if (fio_flags == FIO_UCSBOM)
1277 size = size / ICONV_MULT; /* worst case */
1278# ifdef WIN3264
1279 else if (fio_flags & FIO_CODEPAGE)
1280 size = size / ICONV_MULT; /* also worst case */
1281# endif
Bram Moolenaard0573012017-10-28 21:11:06 +02001282# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001283 else if (fio_flags & FIO_MACROMAN)
1284 size = size / ICONV_MULT; /* also worst case */
1285# endif
1286#endif
1287
1288#ifdef FEAT_MBYTE
1289 if (conv_restlen > 0)
1290 {
1291 /* Insert unconverted bytes from previous line. */
1292 mch_memmove(ptr, conv_rest, conv_restlen);
1293 ptr += conv_restlen;
1294 size -= conv_restlen;
1295 }
1296#endif
1297
1298 if (read_buffer)
1299 {
1300 /*
1301 * Read bytes from curbuf. Used for converting text read
1302 * from stdin.
1303 */
1304 if (read_buf_lnum > from)
1305 size = 0;
1306 else
1307 {
1308 int n, ni;
1309 long tlen;
1310
1311 tlen = 0;
1312 for (;;)
1313 {
1314 p = ml_get(read_buf_lnum) + read_buf_col;
1315 n = (int)STRLEN(p);
1316 if ((int)tlen + n + 1 > size)
1317 {
1318 /* Filled up to "size", append partial line.
1319 * Change NL to NUL to reverse the effect done
1320 * below. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001321 n = (int)(size - tlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001322 for (ni = 0; ni < n; ++ni)
1323 {
1324 if (p[ni] == NL)
1325 ptr[tlen++] = NUL;
1326 else
1327 ptr[tlen++] = p[ni];
1328 }
1329 read_buf_col += n;
1330 break;
1331 }
1332 else
1333 {
1334 /* Append whole line and new-line. Change NL
1335 * to NUL to reverse the effect done below. */
1336 for (ni = 0; ni < n; ++ni)
1337 {
1338 if (p[ni] == NL)
1339 ptr[tlen++] = NUL;
1340 else
1341 ptr[tlen++] = p[ni];
1342 }
1343 ptr[tlen++] = NL;
1344 read_buf_col = 0;
1345 if (++read_buf_lnum > from)
1346 {
1347 /* When the last line didn't have an
1348 * end-of-line don't add it now either. */
1349 if (!curbuf->b_p_eol)
1350 --tlen;
1351 size = tlen;
1352 break;
1353 }
1354 }
1355 }
1356 }
1357 }
1358 else
1359 {
1360 /*
1361 * Read bytes from the file.
1362 */
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01001363 size = read_eintr(fd, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001364 }
1365
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001366#ifdef FEAT_CRYPT
1367 /*
1368 * At start of file: Check for magic number of encryption.
1369 */
1370 if (filesize == 0 && size > 0)
1371 cryptkey = check_for_cryptkey(cryptkey, ptr, &size,
1372 &filesize, newfile, sfname,
1373 &did_ask_for_key);
1374 /*
1375 * Decrypt the read bytes. This is done before checking for
1376 * EOF because the crypt layer may be buffering.
1377 */
Bram Moolenaar829aa642017-08-23 22:32:35 +02001378 if (cryptkey != NULL && curbuf->b_cryptstate != NULL
1379 && size > 0)
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001380 {
1381 if (crypt_works_inplace(curbuf->b_cryptstate))
1382 {
1383 crypt_decode_inplace(curbuf->b_cryptstate, ptr, size);
1384 }
1385 else
1386 {
1387 char_u *newptr = NULL;
1388 int decrypted_size;
1389
1390 decrypted_size = crypt_decode_alloc(
1391 curbuf->b_cryptstate, ptr, size, &newptr);
1392
1393 /* If the crypt layer is buffering, not producing
1394 * anything yet, need to read more. */
1395 if (size > 0 && decrypted_size == 0)
1396 continue;
1397
1398 if (linerest == 0)
1399 {
1400 /* Simple case: reuse returned buffer (may be
1401 * NULL, checked later). */
1402 new_buffer = newptr;
1403 }
1404 else
1405 {
1406 long_u new_size;
1407
1408 /* Need new buffer to add bytes carried over. */
1409 new_size = (long_u)(decrypted_size + linerest + 1);
1410 new_buffer = lalloc(new_size, FALSE);
1411 if (new_buffer == NULL)
1412 {
1413 do_outofmem_msg(new_size);
1414 error = TRUE;
1415 break;
1416 }
1417
1418 mch_memmove(new_buffer, buffer, linerest);
1419 if (newptr != NULL)
1420 mch_memmove(new_buffer + linerest, newptr,
1421 decrypted_size);
1422 }
1423
1424 if (new_buffer != NULL)
1425 {
1426 vim_free(buffer);
1427 buffer = new_buffer;
1428 new_buffer = NULL;
1429 line_start = buffer;
1430 ptr = buffer + linerest;
1431 }
1432 size = decrypted_size;
1433 }
1434 }
1435#endif
1436
Bram Moolenaar071d4272004-06-13 20:20:40 +00001437 if (size <= 0)
1438 {
1439 if (size < 0) /* read error */
1440 error = TRUE;
1441#ifdef FEAT_MBYTE
1442 else if (conv_restlen > 0)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001443 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001444 /*
1445 * Reached end-of-file but some trailing bytes could
1446 * not be converted. Truncated file?
1447 */
1448
1449 /* When we did a conversion report an error. */
1450 if (fio_flags != 0
1451# ifdef USE_ICONV
1452 || iconv_fd != (iconv_t)-1
1453# endif
1454 )
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001455 {
Bram Moolenaare8d95302013-04-24 16:34:02 +02001456 if (can_retry)
1457 goto rewind_retry;
Bram Moolenaarf453d352008-06-04 17:37:34 +00001458 if (conv_error == 0)
1459 conv_error = curbuf->b_ml.ml_line_count
1460 - linecnt + 1;
1461 }
1462 /* Remember the first linenr with an illegal byte */
1463 else if (illegal_byte == 0)
1464 illegal_byte = curbuf->b_ml.ml_line_count
1465 - linecnt + 1;
1466 if (bad_char_behavior == BAD_DROP)
1467 {
1468 *(ptr - conv_restlen) = NUL;
1469 conv_restlen = 0;
1470 }
1471 else
1472 {
1473 /* Replace the trailing bytes with the replacement
1474 * character if we were converting; if we weren't,
1475 * leave the UTF8 checking code to do it, as it
1476 * works slightly differently. */
1477 if (bad_char_behavior != BAD_KEEP && (fio_flags != 0
1478# ifdef USE_ICONV
1479 || iconv_fd != (iconv_t)-1
1480# endif
1481 ))
1482 {
1483 while (conv_restlen > 0)
1484 {
1485 *(--ptr) = bad_char_behavior;
1486 --conv_restlen;
1487 }
1488 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001489 fio_flags = 0; /* don't convert this */
Bram Moolenaarb21e5842006-04-16 18:30:08 +00001490# ifdef USE_ICONV
1491 if (iconv_fd != (iconv_t)-1)
1492 {
1493 iconv_close(iconv_fd);
1494 iconv_fd = (iconv_t)-1;
1495 }
1496# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001497 }
1498 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001499#endif
1500 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001501 }
1502 skip_read = FALSE;
1503
1504#ifdef FEAT_MBYTE
1505 /*
1506 * At start of file (or after crypt magic number): Check for BOM.
1507 * Also check for a BOM for other Unicode encodings, but not after
1508 * converting with 'charconvert' or when a BOM has already been
1509 * found.
1510 */
1511 if ((filesize == 0
1512# ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001513 || (cryptkey != NULL
1514 && filesize == crypt_get_header_len(
1515 crypt_get_method_nr(curbuf)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001516# endif
1517 )
1518 && (fio_flags == FIO_UCSBOM
1519 || (!curbuf->b_p_bomb
1520 && tmpname == NULL
1521 && (*fenc == 'u' || (*fenc == NUL && enc_utf8)))))
1522 {
1523 char_u *ccname;
1524 int blen;
1525
1526 /* no BOM detection in a short file or in binary mode */
1527 if (size < 2 || curbuf->b_p_bin)
1528 ccname = NULL;
1529 else
1530 ccname = check_for_bom(ptr, size, &blen,
1531 fio_flags == FIO_UCSBOM ? FIO_ALL : get_fio_flags(fenc));
1532 if (ccname != NULL)
1533 {
1534 /* Remove BOM from the text */
1535 filesize += blen;
1536 size -= blen;
1537 mch_memmove(ptr, ptr + blen, (size_t)size);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00001538 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001539 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001540 curbuf->b_p_bomb = TRUE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001541 curbuf->b_start_bomb = TRUE;
1542 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001543 }
1544
1545 if (fio_flags == FIO_UCSBOM)
1546 {
1547 if (ccname == NULL)
1548 {
1549 /* No BOM detected: retry with next encoding. */
1550 advance_fenc = TRUE;
1551 }
1552 else
1553 {
1554 /* BOM detected: set "fenc" and jump back */
1555 if (fenc_alloced)
1556 vim_free(fenc);
1557 fenc = ccname;
1558 fenc_alloced = FALSE;
1559 }
1560 /* retry reading without getting new bytes or rewinding */
1561 skip_read = TRUE;
1562 goto retry;
1563 }
1564 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001565
1566 /* Include not converted bytes. */
1567 ptr -= conv_restlen;
1568 size += conv_restlen;
1569 conv_restlen = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001570#endif
1571 /*
1572 * Break here for a read error or end-of-file.
1573 */
1574 if (size <= 0)
1575 break;
1576
1577#ifdef FEAT_MBYTE
1578
Bram Moolenaar071d4272004-06-13 20:20:40 +00001579# ifdef USE_ICONV
1580 if (iconv_fd != (iconv_t)-1)
1581 {
1582 /*
1583 * Attempt conversion of the read bytes to 'encoding' using
1584 * iconv().
1585 */
1586 const char *fromp;
1587 char *top;
1588 size_t from_size;
1589 size_t to_size;
1590
1591 fromp = (char *)ptr;
1592 from_size = size;
1593 ptr += size;
1594 top = (char *)ptr;
1595 to_size = real_size - size;
1596
1597 /*
1598 * If there is conversion error or not enough room try using
Bram Moolenaar19a09a12005-03-04 23:39:37 +00001599 * another conversion. Except for when there is no
1600 * alternative (help files).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001601 */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001602 while ((iconv(iconv_fd, (void *)&fromp, &from_size,
1603 &top, &to_size)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001604 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
1605 || from_size > CONV_RESTLEN)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001606 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001607 if (can_retry)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001608 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001609 if (conv_error == 0)
1610 conv_error = readfile_linenr(linecnt,
1611 ptr, (char_u *)top);
Bram Moolenaar42eeac32005-06-29 22:40:58 +00001612
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001613 /* Deal with a bad byte and continue with the next. */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001614 ++fromp;
1615 --from_size;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001616 if (bad_char_behavior == BAD_KEEP)
1617 {
1618 *top++ = *(fromp - 1);
1619 --to_size;
1620 }
1621 else if (bad_char_behavior != BAD_DROP)
1622 {
1623 *top++ = bad_char_behavior;
1624 --to_size;
1625 }
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001626 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001627
1628 if (from_size > 0)
1629 {
1630 /* Some remaining characters, keep them for the next
1631 * round. */
1632 mch_memmove(conv_rest, (char_u *)fromp, from_size);
1633 conv_restlen = (int)from_size;
1634 }
1635
1636 /* move the linerest to before the converted characters */
1637 line_start = ptr - linerest;
1638 mch_memmove(line_start, buffer, (size_t)linerest);
1639 size = (long)((char_u *)top - ptr);
1640 }
1641# endif
1642
1643# ifdef WIN3264
1644 if (fio_flags & FIO_CODEPAGE)
1645 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001646 char_u *src, *dst;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001647 WCHAR ucs2buf[3];
1648 int ucs2len;
1649 int codepage = FIO_GET_CP(fio_flags);
1650 int bytelen;
1651 int found_bad;
1652 char replstr[2];
1653
Bram Moolenaar071d4272004-06-13 20:20:40 +00001654 /*
1655 * Conversion from an MS-Windows codepage or UTF-8 to UTF-8 or
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001656 * a codepage, using standard MS-Windows functions. This
1657 * requires two steps:
1658 * 1. convert from 'fileencoding' to ucs-2
1659 * 2. convert from ucs-2 to 'encoding'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001660 *
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001661 * Because there may be illegal bytes AND an incomplete byte
1662 * sequence at the end, we may have to do the conversion one
1663 * character at a time to get it right.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001664 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001665
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001666 /* Replacement string for WideCharToMultiByte(). */
1667 if (bad_char_behavior > 0)
1668 replstr[0] = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001669 else
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001670 replstr[0] = '?';
1671 replstr[1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001672
1673 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001674 * Move the bytes to the end of the buffer, so that we have
1675 * room to put the result at the start.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001676 */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001677 src = ptr + real_size - size;
1678 mch_memmove(src, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001679
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001680 /*
1681 * Do the conversion.
1682 */
1683 dst = ptr;
1684 size = size;
1685 while (size > 0)
1686 {
1687 found_bad = FALSE;
1688
1689# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
1690 if (codepage == CP_UTF8)
1691 {
1692 /* Handle CP_UTF8 input ourselves to be able to handle
1693 * trailing bytes properly.
1694 * Get one UTF-8 character from src. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001695 bytelen = (int)utf_ptr2len_len(src, size);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001696 if (bytelen > size)
1697 {
1698 /* Only got some bytes of a character. Normally
1699 * it's put in "conv_rest", but if it's too long
1700 * deal with it as if they were illegal bytes. */
1701 if (bytelen <= CONV_RESTLEN)
1702 break;
1703
1704 /* weird overlong byte sequence */
1705 bytelen = size;
1706 found_bad = TRUE;
1707 }
1708 else
1709 {
Bram Moolenaarc01140a2006-03-24 22:21:52 +00001710 int u8c = utf_ptr2char(src);
1711
Bram Moolenaar86e01082005-12-29 22:45:34 +00001712 if (u8c > 0xffff || (*src >= 0x80 && bytelen == 1))
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001713 found_bad = TRUE;
1714 ucs2buf[0] = u8c;
1715 ucs2len = 1;
1716 }
1717 }
1718 else
1719# endif
1720 {
1721 /* We don't know how long the byte sequence is, try
1722 * from one to three bytes. */
1723 for (bytelen = 1; bytelen <= size && bytelen <= 3;
1724 ++bytelen)
1725 {
1726 ucs2len = MultiByteToWideChar(codepage,
1727 MB_ERR_INVALID_CHARS,
1728 (LPCSTR)src, bytelen,
1729 ucs2buf, 3);
1730 if (ucs2len > 0)
1731 break;
1732 }
1733 if (ucs2len == 0)
1734 {
1735 /* If we have only one byte then it's probably an
1736 * incomplete byte sequence. Otherwise discard
1737 * one byte as a bad character. */
1738 if (size == 1)
1739 break;
1740 found_bad = TRUE;
1741 bytelen = 1;
1742 }
1743 }
1744
1745 if (!found_bad)
1746 {
1747 int i;
1748
1749 /* Convert "ucs2buf[ucs2len]" to 'enc' in "dst". */
1750 if (enc_utf8)
1751 {
1752 /* From UCS-2 to UTF-8. Cannot fail. */
1753 for (i = 0; i < ucs2len; ++i)
1754 dst += utf_char2bytes(ucs2buf[i], dst);
1755 }
1756 else
1757 {
1758 BOOL bad = FALSE;
1759 int dstlen;
1760
1761 /* From UCS-2 to "enc_codepage". If the
1762 * conversion uses the default character "?",
1763 * the data doesn't fit in this encoding. */
1764 dstlen = WideCharToMultiByte(enc_codepage, 0,
1765 (LPCWSTR)ucs2buf, ucs2len,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001766 (LPSTR)dst, (int)(src - dst),
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001767 replstr, &bad);
1768 if (bad)
1769 found_bad = TRUE;
1770 else
1771 dst += dstlen;
1772 }
1773 }
1774
1775 if (found_bad)
1776 {
1777 /* Deal with bytes we can't convert. */
1778 if (can_retry)
1779 goto rewind_retry;
1780 if (conv_error == 0)
1781 conv_error = readfile_linenr(linecnt, ptr, dst);
1782 if (bad_char_behavior != BAD_DROP)
1783 {
1784 if (bad_char_behavior == BAD_KEEP)
1785 {
1786 mch_memmove(dst, src, bytelen);
1787 dst += bytelen;
1788 }
1789 else
1790 *dst++ = bad_char_behavior;
1791 }
1792 }
1793
1794 src += bytelen;
1795 size -= bytelen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001796 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001797
1798 if (size > 0)
1799 {
1800 /* An incomplete byte sequence remaining. */
1801 mch_memmove(conv_rest, src, size);
1802 conv_restlen = size;
1803 }
1804
1805 /* The new size is equal to how much "dst" was advanced. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001806 size = (long)(dst - ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001807 }
1808 else
1809# endif
Bram Moolenaar56718732006-03-15 22:53:57 +00001810# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001811 if (fio_flags & FIO_MACROMAN)
1812 {
1813 /*
1814 * Conversion from Apple MacRoman char encoding to UTF-8 or
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001815 * latin1. This is in os_mac_conv.c.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001816 */
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001817 if (macroman2enc(ptr, &size, real_size) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001818 goto rewind_retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001819 }
1820 else
1821# endif
1822 if (fio_flags != 0)
1823 {
1824 int u8c;
1825 char_u *dest;
1826 char_u *tail = NULL;
1827
1828 /*
1829 * "enc_utf8" set: Convert Unicode or Latin1 to UTF-8.
1830 * "enc_utf8" not set: Convert Unicode to Latin1.
1831 * Go from end to start through the buffer, because the number
1832 * of bytes may increase.
1833 * "dest" points to after where the UTF-8 bytes go, "p" points
1834 * to after the next character to convert.
1835 */
1836 dest = ptr + real_size;
1837 if (fio_flags == FIO_LATIN1 || fio_flags == FIO_UTF8)
1838 {
1839 p = ptr + size;
1840 if (fio_flags == FIO_UTF8)
1841 {
1842 /* Check for a trailing incomplete UTF-8 sequence */
1843 tail = ptr + size - 1;
1844 while (tail > ptr && (*tail & 0xc0) == 0x80)
1845 --tail;
1846 if (tail + utf_byte2len(*tail) <= ptr + size)
1847 tail = NULL;
1848 else
1849 p = tail;
1850 }
1851 }
1852 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1853 {
1854 /* Check for a trailing byte */
1855 p = ptr + (size & ~1);
1856 if (size & 1)
1857 tail = p;
1858 if ((fio_flags & FIO_UTF16) && p > ptr)
1859 {
1860 /* Check for a trailing leading word */
1861 if (fio_flags & FIO_ENDIAN_L)
1862 {
1863 u8c = (*--p << 8);
1864 u8c += *--p;
1865 }
1866 else
1867 {
1868 u8c = *--p;
1869 u8c += (*--p << 8);
1870 }
1871 if (u8c >= 0xd800 && u8c <= 0xdbff)
1872 tail = p;
1873 else
1874 p += 2;
1875 }
1876 }
1877 else /* FIO_UCS4 */
1878 {
1879 /* Check for trailing 1, 2 or 3 bytes */
1880 p = ptr + (size & ~3);
1881 if (size & 3)
1882 tail = p;
1883 }
1884
1885 /* If there is a trailing incomplete sequence move it to
1886 * conv_rest[]. */
1887 if (tail != NULL)
1888 {
1889 conv_restlen = (int)((ptr + size) - tail);
1890 mch_memmove(conv_rest, (char_u *)tail, conv_restlen);
1891 size -= conv_restlen;
1892 }
1893
1894
1895 while (p > ptr)
1896 {
1897 if (fio_flags & FIO_LATIN1)
1898 u8c = *--p;
1899 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1900 {
1901 if (fio_flags & FIO_ENDIAN_L)
1902 {
1903 u8c = (*--p << 8);
1904 u8c += *--p;
1905 }
1906 else
1907 {
1908 u8c = *--p;
1909 u8c += (*--p << 8);
1910 }
1911 if ((fio_flags & FIO_UTF16)
1912 && u8c >= 0xdc00 && u8c <= 0xdfff)
1913 {
1914 int u16c;
1915
1916 if (p == ptr)
1917 {
1918 /* Missing leading word. */
1919 if (can_retry)
1920 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001921 if (conv_error == 0)
1922 conv_error = readfile_linenr(linecnt,
1923 ptr, p);
1924 if (bad_char_behavior == BAD_DROP)
1925 continue;
1926 if (bad_char_behavior != BAD_KEEP)
1927 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001928 }
1929
1930 /* found second word of double-word, get the first
1931 * word and compute the resulting character */
1932 if (fio_flags & FIO_ENDIAN_L)
1933 {
1934 u16c = (*--p << 8);
1935 u16c += *--p;
1936 }
1937 else
1938 {
1939 u16c = *--p;
1940 u16c += (*--p << 8);
1941 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001942 u8c = 0x10000 + ((u16c & 0x3ff) << 10)
1943 + (u8c & 0x3ff);
1944
Bram Moolenaar071d4272004-06-13 20:20:40 +00001945 /* Check if the word is indeed a leading word. */
1946 if (u16c < 0xd800 || u16c > 0xdbff)
1947 {
1948 if (can_retry)
1949 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001950 if (conv_error == 0)
1951 conv_error = readfile_linenr(linecnt,
1952 ptr, p);
1953 if (bad_char_behavior == BAD_DROP)
1954 continue;
1955 if (bad_char_behavior != BAD_KEEP)
1956 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001957 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001958 }
1959 }
1960 else if (fio_flags & FIO_UCS4)
1961 {
1962 if (fio_flags & FIO_ENDIAN_L)
1963 {
Bram Moolenaardc1c9812017-10-27 22:15:24 +02001964 u8c = (unsigned)*--p << 24;
1965 u8c += (unsigned)*--p << 16;
1966 u8c += (unsigned)*--p << 8;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001967 u8c += *--p;
1968 }
1969 else /* big endian */
1970 {
1971 u8c = *--p;
Bram Moolenaardc1c9812017-10-27 22:15:24 +02001972 u8c += (unsigned)*--p << 8;
1973 u8c += (unsigned)*--p << 16;
1974 u8c += (unsigned)*--p << 24;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001975 }
1976 }
1977 else /* UTF-8 */
1978 {
1979 if (*--p < 0x80)
1980 u8c = *p;
1981 else
1982 {
1983 len = utf_head_off(ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001984 p -= len;
1985 u8c = utf_ptr2char(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001986 if (len == 0)
1987 {
1988 /* Not a valid UTF-8 character, retry with
1989 * another fenc when possible, otherwise just
1990 * report the error. */
1991 if (can_retry)
1992 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001993 if (conv_error == 0)
1994 conv_error = readfile_linenr(linecnt,
1995 ptr, p);
1996 if (bad_char_behavior == BAD_DROP)
1997 continue;
1998 if (bad_char_behavior != BAD_KEEP)
1999 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002000 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002001 }
2002 }
2003 if (enc_utf8) /* produce UTF-8 */
2004 {
2005 dest -= utf_char2len(u8c);
2006 (void)utf_char2bytes(u8c, dest);
2007 }
2008 else /* produce Latin1 */
2009 {
2010 --dest;
2011 if (u8c >= 0x100)
2012 {
2013 /* character doesn't fit in latin1, retry with
2014 * another fenc when possible, otherwise just
2015 * report the error. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002016 if (can_retry)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002017 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002018 if (conv_error == 0)
2019 conv_error = readfile_linenr(linecnt, ptr, p);
2020 if (bad_char_behavior == BAD_DROP)
2021 ++dest;
2022 else if (bad_char_behavior == BAD_KEEP)
2023 *dest = u8c;
2024 else if (eap != NULL && eap->bad_char != 0)
2025 *dest = bad_char_behavior;
2026 else
2027 *dest = 0xBF;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002028 }
2029 else
2030 *dest = u8c;
2031 }
2032 }
2033
2034 /* move the linerest to before the converted characters */
2035 line_start = dest - linerest;
2036 mch_memmove(line_start, buffer, (size_t)linerest);
2037 size = (long)((ptr + real_size) - dest);
2038 ptr = dest;
2039 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002040 else if (enc_utf8 && !curbuf->b_p_bin)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002041 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002042 int incomplete_tail = FALSE;
2043
2044 /* Reading UTF-8: Check if the bytes are valid UTF-8. */
2045 for (p = ptr; ; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002046 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002047 int todo = (int)((ptr + size) - p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002048 int l;
2049
2050 if (todo <= 0)
2051 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002052 if (*p >= 0x80)
2053 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002054 /* A length of 1 means it's an illegal byte. Accept
2055 * an incomplete character at the end though, the next
2056 * read() will get the next bytes, we'll check it
2057 * then. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002058 l = utf_ptr2len_len(p, todo);
Bram Moolenaarf453d352008-06-04 17:37:34 +00002059 if (l > todo && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002060 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002061 /* Avoid retrying with a different encoding when
2062 * a truncated file is more likely, or attempting
2063 * to read the rest of an incomplete sequence when
2064 * we have already done so. */
2065 if (p > ptr || filesize > 0)
2066 incomplete_tail = TRUE;
2067 /* Incomplete byte sequence, move it to conv_rest[]
2068 * and try to read the rest of it, unless we've
2069 * already done so. */
2070 if (p > ptr)
2071 {
2072 conv_restlen = todo;
2073 mch_memmove(conv_rest, p, conv_restlen);
2074 size -= conv_restlen;
2075 break;
2076 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002077 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002078 if (l == 1 || l > todo)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002079 {
2080 /* Illegal byte. If we can try another encoding
Bram Moolenaarf453d352008-06-04 17:37:34 +00002081 * do that, unless at EOF where a truncated
2082 * file is more likely than a conversion error. */
2083 if (can_retry && !incomplete_tail)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002084 break;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002085# ifdef USE_ICONV
2086 /* When we did a conversion report an error. */
2087 if (iconv_fd != (iconv_t)-1 && conv_error == 0)
2088 conv_error = readfile_linenr(linecnt, ptr, p);
2089# endif
Bram Moolenaarf453d352008-06-04 17:37:34 +00002090 /* Remember the first linenr with an illegal byte */
2091 if (conv_error == 0 && illegal_byte == 0)
2092 illegal_byte = readfile_linenr(linecnt, ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002093
2094 /* Drop, keep or replace the bad byte. */
2095 if (bad_char_behavior == BAD_DROP)
2096 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002097 mch_memmove(p, p + 1, todo - 1);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002098 --p;
2099 --size;
2100 }
2101 else if (bad_char_behavior != BAD_KEEP)
2102 *p = bad_char_behavior;
2103 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002104 else
2105 p += l - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002106 }
2107 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002108 if (p < ptr + size && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002109 {
2110 /* Detected a UTF-8 error. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002111rewind_retry:
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002112 /* Retry reading with another conversion. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002113# if defined(FEAT_EVAL) && defined(USE_ICONV)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002114 if (*p_ccv != NUL && iconv_fd != (iconv_t)-1)
2115 /* iconv() failed, try 'charconvert' */
2116 did_iconv = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002117 else
2118# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002119 /* use next item from 'fileencodings' */
2120 advance_fenc = TRUE;
2121 file_rewind = TRUE;
2122 goto retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002123 }
2124 }
2125#endif
2126
2127 /* count the number of characters (after conversion!) */
2128 filesize += size;
2129
2130 /*
2131 * when reading the first part of a file: guess EOL type
2132 */
2133 if (fileformat == EOL_UNKNOWN)
2134 {
2135 /* First try finding a NL, for Dos and Unix */
2136 if (try_dos || try_unix)
2137 {
Bram Moolenaarc6b72172015-02-27 17:48:09 +01002138 /* Reset the carriage return counter. */
2139 if (try_mac)
2140 try_mac = 1;
2141
Bram Moolenaar071d4272004-06-13 20:20:40 +00002142 for (p = ptr; p < ptr + size; ++p)
2143 {
2144 if (*p == NL)
2145 {
2146 if (!try_unix
2147 || (try_dos && p > ptr && p[-1] == CAR))
2148 fileformat = EOL_DOS;
2149 else
2150 fileformat = EOL_UNIX;
2151 break;
2152 }
Bram Moolenaar05eb6122015-02-17 14:15:19 +01002153 else if (*p == CAR && try_mac)
2154 try_mac++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002155 }
2156
2157 /* Don't give in to EOL_UNIX if EOL_MAC is more likely */
2158 if (fileformat == EOL_UNIX && try_mac)
2159 {
2160 /* Need to reset the counters when retrying fenc. */
2161 try_mac = 1;
2162 try_unix = 1;
2163 for (; p >= ptr && *p != CAR; p--)
2164 ;
2165 if (p >= ptr)
2166 {
2167 for (p = ptr; p < ptr + size; ++p)
2168 {
2169 if (*p == NL)
2170 try_unix++;
2171 else if (*p == CAR)
2172 try_mac++;
2173 }
2174 if (try_mac > try_unix)
2175 fileformat = EOL_MAC;
2176 }
2177 }
Bram Moolenaar05eb6122015-02-17 14:15:19 +01002178 else if (fileformat == EOL_UNKNOWN && try_mac == 1)
2179 /* Looking for CR but found no end-of-line markers at
2180 * all: use the default format. */
2181 fileformat = default_fileformat();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002182 }
2183
2184 /* No NL found: may use Mac format */
2185 if (fileformat == EOL_UNKNOWN && try_mac)
2186 fileformat = EOL_MAC;
2187
2188 /* Still nothing found? Use first format in 'ffs' */
2189 if (fileformat == EOL_UNKNOWN)
2190 fileformat = default_fileformat();
2191
2192 /* if editing a new file: may set p_tx and p_ff */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002193 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002194 set_fileformat(fileformat, OPT_LOCAL);
2195 }
2196 }
2197
2198 /*
2199 * This loop is executed once for every character read.
2200 * Keep it fast!
2201 */
2202 if (fileformat == EOL_MAC)
2203 {
2204 --ptr;
2205 while (++ptr, --size >= 0)
2206 {
2207 /* catch most common case first */
2208 if ((c = *ptr) != NUL && c != CAR && c != NL)
2209 continue;
2210 if (c == NUL)
2211 *ptr = NL; /* NULs are replaced by newlines! */
2212 else if (c == NL)
2213 *ptr = CAR; /* NLs are replaced by CRs! */
2214 else
2215 {
2216 if (skip_count == 0)
2217 {
2218 *ptr = NUL; /* end of line */
2219 len = (colnr_T) (ptr - line_start + 1);
2220 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2221 {
2222 error = TRUE;
2223 break;
2224 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002225#ifdef FEAT_PERSISTENT_UNDO
2226 if (read_undo_file)
2227 sha256_update(&sha_ctx, line_start, len);
2228#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002229 ++lnum;
2230 if (--read_count == 0)
2231 {
2232 error = TRUE; /* break loop */
2233 line_start = ptr; /* nothing left to write */
2234 break;
2235 }
2236 }
2237 else
2238 --skip_count;
2239 line_start = ptr + 1;
2240 }
2241 }
2242 }
2243 else
2244 {
2245 --ptr;
2246 while (++ptr, --size >= 0)
2247 {
2248 if ((c = *ptr) != NUL && c != NL) /* catch most common case */
2249 continue;
2250 if (c == NUL)
2251 *ptr = NL; /* NULs are replaced by newlines! */
2252 else
2253 {
2254 if (skip_count == 0)
2255 {
2256 *ptr = NUL; /* end of line */
2257 len = (colnr_T)(ptr - line_start + 1);
2258 if (fileformat == EOL_DOS)
2259 {
Bram Moolenaar2aa5f692017-01-24 15:46:48 +01002260 if (ptr > line_start && ptr[-1] == CAR)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002261 {
Bram Moolenaar2aa5f692017-01-24 15:46:48 +01002262 /* remove CR before NL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002263 ptr[-1] = NUL;
2264 --len;
2265 }
2266 /*
2267 * Reading in Dos format, but no CR-LF found!
2268 * When 'fileformats' includes "unix", delete all
2269 * the lines read so far and start all over again.
2270 * Otherwise give an error message later.
2271 */
2272 else if (ff_error != EOL_DOS)
2273 {
2274 if ( try_unix
2275 && !read_stdin
2276 && (read_buffer
Bram Moolenaar8767f522016-07-01 17:17:39 +02002277 || vim_lseek(fd, (off_T)0L, SEEK_SET)
2278 == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002279 {
2280 fileformat = EOL_UNIX;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002281 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002282 set_fileformat(EOL_UNIX, OPT_LOCAL);
2283 file_rewind = TRUE;
2284 keep_fileformat = TRUE;
2285 goto retry;
2286 }
2287 ff_error = EOL_DOS;
2288 }
2289 }
2290 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2291 {
2292 error = TRUE;
2293 break;
2294 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002295#ifdef FEAT_PERSISTENT_UNDO
2296 if (read_undo_file)
2297 sha256_update(&sha_ctx, line_start, len);
2298#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002299 ++lnum;
2300 if (--read_count == 0)
2301 {
2302 error = TRUE; /* break loop */
2303 line_start = ptr; /* nothing left to write */
2304 break;
2305 }
2306 }
2307 else
2308 --skip_count;
2309 line_start = ptr + 1;
2310 }
2311 }
2312 }
2313 linerest = (long)(ptr - line_start);
2314 ui_breakcheck();
2315 }
2316
2317failed:
2318 /* not an error, max. number of lines reached */
2319 if (error && read_count == 0)
2320 error = FALSE;
2321
2322 /*
2323 * If we get EOF in the middle of a line, note the fact and
2324 * complete the line ourselves.
2325 * In Dos format ignore a trailing CTRL-Z, unless 'binary' set.
2326 */
2327 if (!error
2328 && !got_int
2329 && linerest != 0
2330 && !(!curbuf->b_p_bin
2331 && fileformat == EOL_DOS
2332 && *line_start == Ctrl_Z
2333 && ptr == line_start + 1))
2334 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002335 /* remember for when writing */
2336 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002337 curbuf->b_p_eol = FALSE;
2338 *ptr = NUL;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002339 len = (colnr_T)(ptr - line_start + 1);
2340 if (ml_append(lnum, line_start, len, newfile) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002341 error = TRUE;
2342 else
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002343 {
2344#ifdef FEAT_PERSISTENT_UNDO
2345 if (read_undo_file)
2346 sha256_update(&sha_ctx, line_start, len);
2347#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002348 read_no_eol_lnum = ++lnum;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002349 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002350 }
2351
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002352 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002353 save_file_ff(curbuf); /* remember the current file format */
2354
2355#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002356 if (curbuf->b_cryptstate != NULL)
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002357 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002358 crypt_free_state(curbuf->b_cryptstate);
2359 curbuf->b_cryptstate = NULL;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002360 }
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002361 if (cryptkey != NULL && cryptkey != curbuf->b_p_key)
2362 crypt_free_key(cryptkey);
2363 /* Don't set cryptkey to NULL, it's used below as a flag that
2364 * encryption was used. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002365#endif
2366
2367#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002368 /* If editing a new file: set 'fenc' for the current buffer.
2369 * Also for ":read ++edit file". */
2370 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002371 set_string_option_direct((char_u *)"fenc", -1, fenc,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00002372 OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002373 if (fenc_alloced)
2374 vim_free(fenc);
2375# ifdef USE_ICONV
2376 if (iconv_fd != (iconv_t)-1)
2377 {
2378 iconv_close(iconv_fd);
2379 iconv_fd = (iconv_t)-1;
2380 }
2381# endif
2382#endif
2383
2384 if (!read_buffer && !read_stdin)
2385 close(fd); /* errors are ignored */
Bram Moolenaarf05da212009-11-17 16:13:15 +00002386#ifdef HAVE_FD_CLOEXEC
2387 else
2388 {
2389 int fdflags = fcntl(fd, F_GETFD);
2390 if (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0)
Bram Moolenaarfbc4b4d2016-02-07 15:14:01 +01002391 (void)fcntl(fd, F_SETFD, fdflags | FD_CLOEXEC);
Bram Moolenaarf05da212009-11-17 16:13:15 +00002392 }
2393#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002394 vim_free(buffer);
2395
2396#ifdef HAVE_DUP
2397 if (read_stdin)
2398 {
2399 /* Use stderr for stdin, makes shell commands work. */
2400 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00002401 ignored = dup(2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002402 }
2403#endif
2404
2405#ifdef FEAT_MBYTE
2406 if (tmpname != NULL)
2407 {
2408 mch_remove(tmpname); /* delete converted file */
2409 vim_free(tmpname);
2410 }
2411#endif
2412 --no_wait_return; /* may wait for return now */
2413
2414 /*
2415 * In recovery mode everything but autocommands is skipped.
2416 */
2417 if (!recoverymode)
2418 {
2419 /* need to delete the last line, which comes from the empty buffer */
2420 if (newfile && wasempty && !(curbuf->b_ml.ml_flags & ML_EMPTY))
2421 {
2422#ifdef FEAT_NETBEANS_INTG
2423 netbeansFireChanges = 0;
2424#endif
2425 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
2426#ifdef FEAT_NETBEANS_INTG
2427 netbeansFireChanges = 1;
2428#endif
2429 --linecnt;
2430 }
2431 linecnt = curbuf->b_ml.ml_line_count - linecnt;
2432 if (filesize == 0)
2433 linecnt = 0;
2434 if (newfile || read_buffer)
Bram Moolenaar7263a772007-05-10 17:35:54 +00002435 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002436 redraw_curbuf_later(NOT_VALID);
Bram Moolenaar7263a772007-05-10 17:35:54 +00002437#ifdef FEAT_DIFF
2438 /* After reading the text into the buffer the diff info needs to
2439 * be updated. */
2440 diff_invalidate(curbuf);
2441#endif
2442#ifdef FEAT_FOLDING
2443 /* All folds in the window are invalid now. Mark them for update
2444 * before triggering autocommands. */
2445 foldUpdateAll(curwin);
2446#endif
2447 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002448 else if (linecnt) /* appended at least one line */
2449 appended_lines_mark(from, linecnt);
2450
Bram Moolenaar071d4272004-06-13 20:20:40 +00002451#ifndef ALWAYS_USE_GUI
2452 /*
2453 * If we were reading from the same terminal as where messages go,
2454 * the screen will have been messed up.
2455 * Switch on raw mode now and clear the screen.
2456 */
2457 if (read_stdin)
2458 {
2459 settmode(TMODE_RAW); /* set to raw mode */
2460 starttermcap();
2461 screenclear();
2462 }
2463#endif
2464
2465 if (got_int)
2466 {
2467 if (!(flags & READ_DUMMY))
2468 {
2469 filemess(curbuf, sfname, (char_u *)_(e_interr), 0);
2470 if (newfile)
2471 curbuf->b_p_ro = TRUE; /* must use "w!" now */
2472 }
2473 msg_scroll = msg_save;
2474#ifdef FEAT_VIMINFO
2475 check_marks_read();
2476#endif
2477 return OK; /* an interrupt isn't really an error */
2478 }
2479
2480 if (!filtering && !(flags & READ_DUMMY))
2481 {
2482 msg_add_fname(curbuf, sfname); /* fname in IObuff with quotes */
2483 c = FALSE;
2484
2485#ifdef UNIX
2486# ifdef S_ISFIFO
2487 if (S_ISFIFO(perm)) /* fifo or socket */
2488 {
2489 STRCAT(IObuff, _("[fifo/socket]"));
2490 c = TRUE;
2491 }
2492# else
2493# ifdef S_IFIFO
2494 if ((perm & S_IFMT) == S_IFIFO) /* fifo */
2495 {
2496 STRCAT(IObuff, _("[fifo]"));
2497 c = TRUE;
2498 }
2499# endif
2500# ifdef S_IFSOCK
2501 if ((perm & S_IFMT) == S_IFSOCK) /* or socket */
2502 {
2503 STRCAT(IObuff, _("[socket]"));
2504 c = TRUE;
2505 }
2506# endif
2507# endif
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002508# ifdef OPEN_CHR_FILES
2509 if (S_ISCHR(perm)) /* or character special */
2510 {
2511 STRCAT(IObuff, _("[character special]"));
2512 c = TRUE;
2513 }
2514# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002515#endif
2516 if (curbuf->b_p_ro)
2517 {
2518 STRCAT(IObuff, shortmess(SHM_RO) ? _("[RO]") : _("[readonly]"));
2519 c = TRUE;
2520 }
2521 if (read_no_eol_lnum)
2522 {
2523 msg_add_eol();
2524 c = TRUE;
2525 }
2526 if (ff_error == EOL_DOS)
2527 {
2528 STRCAT(IObuff, _("[CR missing]"));
2529 c = TRUE;
2530 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002531 if (split)
2532 {
2533 STRCAT(IObuff, _("[long lines split]"));
2534 c = TRUE;
2535 }
2536#ifdef FEAT_MBYTE
2537 if (notconverted)
2538 {
2539 STRCAT(IObuff, _("[NOT converted]"));
2540 c = TRUE;
2541 }
2542 else if (converted)
2543 {
2544 STRCAT(IObuff, _("[converted]"));
2545 c = TRUE;
2546 }
2547#endif
2548#ifdef FEAT_CRYPT
2549 if (cryptkey != NULL)
2550 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002551 crypt_append_msg(curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002552 c = TRUE;
2553 }
2554#endif
2555#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002556 if (conv_error != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002557 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002558 sprintf((char *)IObuff + STRLEN(IObuff),
2559 _("[CONVERSION ERROR in line %ld]"), (long)conv_error);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002560 c = TRUE;
2561 }
2562 else if (illegal_byte > 0)
2563 {
2564 sprintf((char *)IObuff + STRLEN(IObuff),
2565 _("[ILLEGAL BYTE in line %ld]"), (long)illegal_byte);
2566 c = TRUE;
2567 }
2568 else
2569#endif
2570 if (error)
2571 {
2572 STRCAT(IObuff, _("[READ ERRORS]"));
2573 c = TRUE;
2574 }
2575 if (msg_add_fileformat(fileformat))
2576 c = TRUE;
2577#ifdef FEAT_CRYPT
2578 if (cryptkey != NULL)
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002579 msg_add_lines(c, (long)linecnt, filesize
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002580 - crypt_get_header_len(crypt_get_method_nr(curbuf)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002581 else
2582#endif
2583 msg_add_lines(c, (long)linecnt, filesize);
2584
Bram Moolenaard23a8232018-02-10 18:45:26 +01002585 VIM_CLEAR(keep_msg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002586 msg_scrolled_ign = TRUE;
2587#ifdef ALWAYS_USE_GUI
2588 /* Don't show the message when reading stdin, it would end up in a
2589 * message box (which might be shown when exiting!) */
2590 if (read_stdin || read_buffer)
2591 p = msg_may_trunc(FALSE, IObuff);
2592 else
2593#endif
2594 p = msg_trunc_attr(IObuff, FALSE, 0);
2595 if (read_stdin || read_buffer || restart_edit != 0
Bram Moolenaar1c7715d2005-10-03 22:02:18 +00002596 || (msg_scrolled != 0 && !need_wait_return))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002597 /* Need to repeat the message after redrawing when:
2598 * - When reading from stdin (the screen will be cleared next).
2599 * - When restart_edit is set (otherwise there will be a delay
2600 * before redrawing).
2601 * - When the screen was scrolled but there is no wait-return
2602 * prompt. */
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002603 set_keep_msg(p, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002604 msg_scrolled_ign = FALSE;
2605 }
2606
2607 /* with errors writing the file requires ":w!" */
2608 if (newfile && (error
2609#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002610 || conv_error != 0
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002611 || (illegal_byte > 0 && bad_char_behavior != BAD_KEEP)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002612#endif
2613 ))
2614 curbuf->b_p_ro = TRUE;
2615
2616 u_clearline(); /* cannot use "U" command after adding lines */
2617
2618 /*
2619 * In Ex mode: cursor at last new line.
2620 * Otherwise: cursor at first new line.
2621 */
2622 if (exmode_active)
2623 curwin->w_cursor.lnum = from + linecnt;
2624 else
2625 curwin->w_cursor.lnum = from + 1;
2626 check_cursor_lnum();
2627 beginline(BL_WHITE | BL_FIX); /* on first non-blank */
2628
2629 /*
2630 * Set '[ and '] marks to the newly read lines.
2631 */
2632 curbuf->b_op_start.lnum = from + 1;
2633 curbuf->b_op_start.col = 0;
2634 curbuf->b_op_end.lnum = from + linecnt;
2635 curbuf->b_op_end.col = 0;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002636
2637#ifdef WIN32
2638 /*
2639 * Work around a weird problem: When a file has two links (only
2640 * possible on NTFS) and we write through one link, then stat() it
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00002641 * through the other link, the timestamp information may be wrong.
Bram Moolenaar03f48552006-02-28 23:52:23 +00002642 * It's correct again after reading the file, thus reset the timestamp
2643 * here.
2644 */
2645 if (newfile && !read_stdin && !read_buffer
2646 && mch_stat((char *)fname, &st) >= 0)
2647 {
2648 buf_store_time(curbuf, &st, fname);
2649 curbuf->b_mtime_read = curbuf->b_mtime;
2650 }
2651#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002652 }
2653 msg_scroll = msg_save;
2654
2655#ifdef FEAT_VIMINFO
2656 /*
2657 * Get the marks before executing autocommands, so they can be used there.
2658 */
2659 check_marks_read();
2660#endif
2661
Bram Moolenaar071d4272004-06-13 20:20:40 +00002662 /*
Bram Moolenaar34d72d42015-07-17 14:18:08 +02002663 * We remember if the last line of the read didn't have
2664 * an eol even when 'binary' is off, to support turning 'fixeol' off,
2665 * or writing the read again with 'binary' on. The latter is required
2666 * for ":autocmd FileReadPost *.gz set bin|'[,']!gunzip" to work.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002667 */
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002668 curbuf->b_no_eol_lnum = read_no_eol_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002669
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02002670 /* When reloading a buffer put the cursor at the first line that is
2671 * different. */
2672 if (flags & READ_KEEP_UNDO)
2673 u_find_first_changed();
2674
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002675#ifdef FEAT_PERSISTENT_UNDO
2676 /*
2677 * When opening a new file locate undo info and read it.
2678 */
2679 if (read_undo_file)
2680 {
2681 char_u hash[UNDO_HASH_SIZE];
2682
2683 sha256_finish(&sha_ctx, hash);
Bram Moolenaar6ed8ed82010-05-30 20:40:11 +02002684 u_read_undo(NULL, hash, fname);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002685 }
2686#endif
2687
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02002688 if (!read_stdin && !read_fifo && (!read_buffer || sfname != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002689 {
2690 int m = msg_scroll;
2691 int n = msg_scrolled;
2692
2693 /* Save the fileformat now, otherwise the buffer will be considered
2694 * modified if the format/encoding was automatically detected. */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002695 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002696 save_file_ff(curbuf);
2697
2698 /*
2699 * The output from the autocommands should not overwrite anything and
2700 * should not be overwritten: Set msg_scroll, restore its value if no
2701 * output was done.
2702 */
2703 msg_scroll = TRUE;
2704 if (filtering)
2705 apply_autocmds_exarg(EVENT_FILTERREADPOST, NULL, sfname,
2706 FALSE, curbuf, eap);
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02002707 else if (newfile || (read_buffer && sfname != NULL))
Bram Moolenaarc3691332016-04-20 12:49:49 +02002708 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002709 apply_autocmds_exarg(EVENT_BUFREADPOST, NULL, sfname,
2710 FALSE, curbuf, eap);
Bram Moolenaarc3691332016-04-20 12:49:49 +02002711 if (!au_did_filetype && *curbuf->b_p_ft != NUL)
2712 /*
2713 * EVENT_FILETYPE was not triggered but the buffer already has a
2714 * filetype. Trigger EVENT_FILETYPE using the existing filetype.
2715 */
2716 apply_autocmds(EVENT_FILETYPE, curbuf->b_p_ft, curbuf->b_fname,
2717 TRUE, curbuf);
2718 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002719 else
2720 apply_autocmds_exarg(EVENT_FILEREADPOST, sfname, sfname,
2721 FALSE, NULL, eap);
2722 if (msg_scrolled == n)
2723 msg_scroll = m;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002724# ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002725 if (aborting()) /* autocmds may abort script processing */
2726 return FAIL;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002727# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002728 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002729
2730 if (recoverymode && error)
2731 return FAIL;
2732 return OK;
2733}
2734
Bram Moolenaarf04507d2016-08-20 15:05:39 +02002735#if defined(OPEN_CHR_FILES) || defined(PROTO)
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002736/*
2737 * Returns TRUE if the file name argument is of the form "/dev/fd/\d\+",
2738 * which is the name of files used for process substitution output by
2739 * some shells on some operating systems, e.g., bash on SunOS.
2740 * Do not accept "/dev/fd/[012]", opening these may hang Vim.
2741 */
Bram Moolenaarf04507d2016-08-20 15:05:39 +02002742 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002743is_dev_fd_file(char_u *fname)
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002744{
2745 return (STRNCMP(fname, "/dev/fd/", 8) == 0
2746 && VIM_ISDIGIT(fname[8])
2747 && *skipdigits(fname + 9) == NUL
2748 && (fname[9] != NUL
2749 || (fname[8] != '0' && fname[8] != '1' && fname[8] != '2')));
2750}
2751#endif
2752
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002753#ifdef FEAT_MBYTE
2754
2755/*
2756 * From the current line count and characters read after that, estimate the
2757 * line number where we are now.
2758 * Used for error messages that include a line number.
2759 */
2760 static linenr_T
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002761readfile_linenr(
2762 linenr_T linecnt, /* line count before reading more bytes */
2763 char_u *p, /* start of more bytes read */
2764 char_u *endp) /* end of more bytes read */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002765{
2766 char_u *s;
2767 linenr_T lnum;
2768
2769 lnum = curbuf->b_ml.ml_line_count - linecnt + 1;
2770 for (s = p; s < endp; ++s)
2771 if (*s == '\n')
2772 ++lnum;
2773 return lnum;
2774}
2775#endif
2776
Bram Moolenaar071d4272004-06-13 20:20:40 +00002777/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00002778 * Fill "*eap" to force the 'fileencoding', 'fileformat' and 'binary to be
2779 * equal to the buffer "buf". Used for calling readfile().
Bram Moolenaar071d4272004-06-13 20:20:40 +00002780 * Returns OK or FAIL.
2781 */
2782 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002783prep_exarg(exarg_T *eap, buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002784{
Bram Moolenaar333b80a2018-04-04 22:57:29 +02002785 eap->cmd = alloc(15
Bram Moolenaar071d4272004-06-13 20:20:40 +00002786#ifdef FEAT_MBYTE
Bram Moolenaar333b80a2018-04-04 22:57:29 +02002787 + (unsigned)STRLEN(buf->b_p_fenc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002788#endif
Bram Moolenaar333b80a2018-04-04 22:57:29 +02002789 );
Bram Moolenaar071d4272004-06-13 20:20:40 +00002790 if (eap->cmd == NULL)
2791 return FAIL;
2792
2793#ifdef FEAT_MBYTE
Bram Moolenaar333b80a2018-04-04 22:57:29 +02002794 sprintf((char *)eap->cmd, "e ++enc=%s", buf->b_p_fenc);
2795 eap->force_enc = 8;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002796 eap->bad_char = buf->b_bad_char;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002797#else
Bram Moolenaar333b80a2018-04-04 22:57:29 +02002798 sprintf((char *)eap->cmd, "e");
Bram Moolenaar071d4272004-06-13 20:20:40 +00002799#endif
Bram Moolenaar333b80a2018-04-04 22:57:29 +02002800 eap->force_ff = *buf->b_p_ff;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002801
2802 eap->force_bin = buf->b_p_bin ? FORCE_BIN : FORCE_NOBIN;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002803 eap->read_edit = FALSE;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002804 eap->forceit = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002805 return OK;
2806}
2807
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002808/*
2809 * Set default or forced 'fileformat' and 'binary'.
2810 */
2811 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002812set_file_options(int set_options, exarg_T *eap)
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002813{
2814 /* set default 'fileformat' */
2815 if (set_options)
2816 {
2817 if (eap != NULL && eap->force_ff != 0)
2818 set_fileformat(get_fileformat_force(curbuf, eap), OPT_LOCAL);
2819 else if (*p_ffs != NUL)
2820 set_fileformat(default_fileformat(), OPT_LOCAL);
2821 }
2822
2823 /* set or reset 'binary' */
2824 if (eap != NULL && eap->force_bin != 0)
2825 {
2826 int oldval = curbuf->b_p_bin;
2827
2828 curbuf->b_p_bin = (eap->force_bin == FORCE_BIN);
2829 set_options_bin(oldval, curbuf->b_p_bin, OPT_LOCAL);
2830 }
2831}
2832
2833#if defined(FEAT_MBYTE) || defined(PROTO)
2834/*
2835 * Set forced 'fileencoding'.
2836 */
2837 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002838set_forced_fenc(exarg_T *eap)
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002839{
2840 if (eap->force_enc != 0)
2841 {
2842 char_u *fenc = enc_canonize(eap->cmd + eap->force_enc);
2843
2844 if (fenc != NULL)
2845 set_string_option_direct((char_u *)"fenc", -1,
2846 fenc, OPT_FREE|OPT_LOCAL, 0);
2847 vim_free(fenc);
2848 }
2849}
2850
Bram Moolenaar071d4272004-06-13 20:20:40 +00002851/*
2852 * Find next fileencoding to use from 'fileencodings'.
2853 * "pp" points to fenc_next. It's advanced to the next item.
2854 * When there are no more items, an empty string is returned and *pp is set to
2855 * NULL.
2856 * When *pp is not set to NULL, the result is in allocated memory.
2857 */
2858 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002859next_fenc(char_u **pp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002860{
2861 char_u *p;
2862 char_u *r;
2863
2864 if (**pp == NUL)
2865 {
2866 *pp = NULL;
2867 return (char_u *)"";
2868 }
2869 p = vim_strchr(*pp, ',');
2870 if (p == NULL)
2871 {
2872 r = enc_canonize(*pp);
2873 *pp += STRLEN(*pp);
2874 }
2875 else
2876 {
2877 r = vim_strnsave(*pp, (int)(p - *pp));
2878 *pp = p + 1;
2879 if (r != NULL)
2880 {
2881 p = enc_canonize(r);
2882 vim_free(r);
2883 r = p;
2884 }
2885 }
2886 if (r == NULL) /* out of memory */
2887 {
2888 r = (char_u *)"";
2889 *pp = NULL;
2890 }
2891 return r;
2892}
2893
2894# ifdef FEAT_EVAL
2895/*
2896 * Convert a file with the 'charconvert' expression.
2897 * This closes the file which is to be read, converts it and opens the
2898 * resulting file for reading.
2899 * Returns name of the resulting converted file (the caller should delete it
2900 * after reading it).
2901 * Returns NULL if the conversion failed ("*fdp" is not set) .
2902 */
2903 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002904readfile_charconvert(
2905 char_u *fname, /* name of input file */
2906 char_u *fenc, /* converted from */
2907 int *fdp) /* in/out: file descriptor of file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002908{
2909 char_u *tmpname;
2910 char_u *errmsg = NULL;
2911
Bram Moolenaare5c421c2015-03-31 13:33:08 +02002912 tmpname = vim_tempname('r', FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002913 if (tmpname == NULL)
2914 errmsg = (char_u *)_("Can't find temp file for conversion");
2915 else
2916 {
2917 close(*fdp); /* close the input file, ignore errors */
2918 *fdp = -1;
2919 if (eval_charconvert(fenc, enc_utf8 ? (char_u *)"utf-8" : p_enc,
2920 fname, tmpname) == FAIL)
2921 errmsg = (char_u *)_("Conversion with 'charconvert' failed");
2922 if (errmsg == NULL && (*fdp = mch_open((char *)tmpname,
2923 O_RDONLY | O_EXTRA, 0)) < 0)
2924 errmsg = (char_u *)_("can't read output of 'charconvert'");
2925 }
2926
2927 if (errmsg != NULL)
2928 {
2929 /* Don't use emsg(), it breaks mappings, the retry with
2930 * another type of conversion might still work. */
2931 MSG(errmsg);
2932 if (tmpname != NULL)
2933 {
2934 mch_remove(tmpname); /* delete converted file */
Bram Moolenaard23a8232018-02-10 18:45:26 +01002935 VIM_CLEAR(tmpname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002936 }
2937 }
2938
2939 /* If the input file is closed, open it (caller should check for error). */
2940 if (*fdp < 0)
2941 *fdp = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
2942
2943 return tmpname;
2944}
2945# endif
2946
2947#endif
2948
2949#ifdef FEAT_VIMINFO
2950/*
2951 * Read marks for the current buffer from the viminfo file, when we support
2952 * buffer marks and the buffer has a name.
2953 */
2954 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002955check_marks_read(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002956{
2957 if (!curbuf->b_marks_read && get_viminfo_parameter('\'') > 0
2958 && curbuf->b_ffname != NULL)
Bram Moolenaard812df62008-11-09 12:46:09 +00002959 read_viminfo(NULL, VIF_WANT_MARKS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002960
2961 /* Always set b_marks_read; needed when 'viminfo' is changed to include
2962 * the ' parameter after opening a buffer. */
2963 curbuf->b_marks_read = TRUE;
2964}
2965#endif
2966
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002967#if defined(FEAT_CRYPT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002968/*
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002969 * Check for magic number used for encryption. Applies to the current buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002970 * If found, the magic number is removed from ptr[*sizep] and *sizep and
2971 * *filesizep are updated.
2972 * Return the (new) encryption key, NULL for no encryption.
2973 */
2974 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002975check_for_cryptkey(
2976 char_u *cryptkey, /* previous encryption key or NULL */
2977 char_u *ptr, /* pointer to read bytes */
2978 long *sizep, /* length of read bytes */
Bram Moolenaar8767f522016-07-01 17:17:39 +02002979 off_T *filesizep, /* nr of bytes used from file */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002980 int newfile, /* editing a new buffer */
2981 char_u *fname, /* file name to display */
2982 int *did_ask) /* flag: whether already asked for key */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002983{
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002984 int method = crypt_method_nr_from_magic((char *)ptr, *sizep);
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02002985 int b_p_ro = curbuf->b_p_ro;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002986
2987 if (method >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002988 {
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02002989 /* Mark the buffer as read-only until the decryption has taken place.
2990 * Avoids accidentally overwriting the file with garbage. */
2991 curbuf->b_p_ro = TRUE;
2992
Bram Moolenaar2be79502014-08-13 21:58:28 +02002993 /* Set the cryptmethod local to the buffer. */
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002994 crypt_set_cm_option(curbuf, method);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002995 if (cryptkey == NULL && !*did_ask)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002996 {
2997 if (*curbuf->b_p_key)
2998 cryptkey = curbuf->b_p_key;
2999 else
3000 {
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003001 /* When newfile is TRUE, store the typed key in the 'key'
3002 * option and don't free it. bf needs hash of the key saved.
Bram Moolenaarf50a2532010-05-21 15:36:08 +02003003 * Don't ask for the key again when first time Enter was hit.
3004 * Happens when retrying to detect encoding. */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003005 smsg((char_u *)_(need_key_msg), fname);
3006 msg_scroll = TRUE;
Bram Moolenaar3a0c9082014-11-12 15:15:42 +01003007 crypt_check_method(method);
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003008 cryptkey = crypt_get_key(newfile, FALSE);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02003009 *did_ask = TRUE;
3010
Bram Moolenaar071d4272004-06-13 20:20:40 +00003011 /* check if empty key entered */
3012 if (cryptkey != NULL && *cryptkey == NUL)
3013 {
3014 if (cryptkey != curbuf->b_p_key)
3015 vim_free(cryptkey);
3016 cryptkey = NULL;
3017 }
3018 }
3019 }
3020
3021 if (cryptkey != NULL)
3022 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003023 int header_len;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003024
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003025 curbuf->b_cryptstate = crypt_create_from_header(
3026 method, cryptkey, ptr);
3027 crypt_set_cm_option(curbuf, method);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003028
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003029 /* Remove cryptmethod specific header from the text. */
3030 header_len = crypt_get_header_len(method);
Bram Moolenaar680e0152016-09-25 20:54:11 +02003031 if (*sizep <= header_len)
3032 /* invalid header, buffer can't be encrypted */
3033 return NULL;
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003034 *filesizep += header_len;
3035 *sizep -= header_len;
3036 mch_memmove(ptr, ptr + header_len, (size_t)*sizep);
3037
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02003038 /* Restore the read-only flag. */
3039 curbuf->b_p_ro = b_p_ro;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003040 }
3041 }
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003042 /* When starting to edit a new file which does not have encryption, clear
3043 * the 'key' option, except when starting up (called with -x argument) */
Bram Moolenaarfa0ff9a2010-07-25 16:05:19 +02003044 else if (newfile && *curbuf->b_p_key != NUL && !starting)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003045 set_option_value((char_u *)"key", 0L, (char_u *)"", OPT_LOCAL);
3046
3047 return cryptkey;
3048}
Bram Moolenaar80794b12010-06-13 05:20:42 +02003049#endif /* FEAT_CRYPT */
3050
Bram Moolenaar071d4272004-06-13 20:20:40 +00003051#ifdef UNIX
3052 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003053set_file_time(
3054 char_u *fname,
3055 time_t atime, /* access time */
3056 time_t mtime) /* modification time */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003057{
3058# if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
3059 struct utimbuf buf;
3060
3061 buf.actime = atime;
3062 buf.modtime = mtime;
3063 (void)utime((char *)fname, &buf);
3064# else
3065# if defined(HAVE_UTIMES)
3066 struct timeval tvp[2];
3067
3068 tvp[0].tv_sec = atime;
3069 tvp[0].tv_usec = 0;
3070 tvp[1].tv_sec = mtime;
3071 tvp[1].tv_usec = 0;
3072# ifdef NeXT
3073 (void)utimes((char *)fname, tvp);
3074# else
3075 (void)utimes((char *)fname, (const struct timeval *)&tvp);
3076# endif
3077# endif
3078# endif
3079}
3080#endif /* UNIX */
3081
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003082#if defined(VMS) && !defined(MIN)
3083/* Older DECC compiler for VAX doesn't define MIN() */
3084# define MIN(a, b) ((a) < (b) ? (a) : (b))
3085#endif
3086
Bram Moolenaar071d4272004-06-13 20:20:40 +00003087/*
Bram Moolenaar5386a122007-06-28 20:02:32 +00003088 * Return TRUE if a file appears to be read-only from the file permissions.
3089 */
3090 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003091check_file_readonly(
3092 char_u *fname, /* full path to file */
3093 int perm) /* known permissions on file */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003094{
3095#ifndef USE_MCH_ACCESS
3096 int fd = 0;
3097#endif
3098
3099 return (
3100#ifdef USE_MCH_ACCESS
3101# ifdef UNIX
3102 (perm & 0222) == 0 ||
3103# endif
3104 mch_access((char *)fname, W_OK)
3105#else
3106 (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0
3107 ? TRUE : (close(fd), FALSE)
3108#endif
3109 );
3110}
3111
3112
3113/*
Bram Moolenaar292ad192005-12-11 21:29:51 +00003114 * buf_write() - write to file "fname" lines "start" through "end"
Bram Moolenaar071d4272004-06-13 20:20:40 +00003115 *
3116 * We do our own buffering here because fwrite() is so slow.
3117 *
Bram Moolenaar292ad192005-12-11 21:29:51 +00003118 * If "forceit" is true, we don't care for errors when attempting backups.
3119 * In case of an error everything possible is done to restore the original
Bram Moolenaare37d50a2008-08-06 17:06:04 +00003120 * file. But when "forceit" is TRUE, we risk losing it.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003121 *
3122 * When "reset_changed" is TRUE and "append" == FALSE and "start" == 1 and
3123 * "end" == curbuf->b_ml.ml_line_count, reset curbuf->b_changed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003124 *
3125 * This function must NOT use NameBuff (because it's called by autowrite()).
3126 *
3127 * return FAIL for failure, OK otherwise
3128 */
3129 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003130buf_write(
3131 buf_T *buf,
3132 char_u *fname,
3133 char_u *sfname,
3134 linenr_T start,
3135 linenr_T end,
3136 exarg_T *eap, /* for forced 'ff' and 'fenc', can be
Bram Moolenaar071d4272004-06-13 20:20:40 +00003137 NULL! */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003138 int append, /* append to the file */
3139 int forceit,
3140 int reset_changed,
3141 int filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003142{
3143 int fd;
3144 char_u *backup = NULL;
3145 int backup_copy = FALSE; /* copy the original file? */
3146 int dobackup;
3147 char_u *ffname;
3148 char_u *wfname = NULL; /* name of file to write to */
3149 char_u *s;
3150 char_u *ptr;
3151 char_u c;
3152 int len;
3153 linenr_T lnum;
3154 long nchars;
3155 char_u *errmsg = NULL;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003156 int errmsg_allocated = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003157 char_u *errnum = NULL;
3158 char_u *buffer;
3159 char_u smallbuf[SMBUFSIZE];
3160 char_u *backup_ext;
3161 int bufsize;
3162 long perm; /* file permissions */
3163 int retval = OK;
3164 int newfile = FALSE; /* TRUE if file doesn't exist yet */
3165 int msg_save = msg_scroll;
3166 int overwriting; /* TRUE if writing over original */
3167 int no_eol = FALSE; /* no end-of-line written */
3168 int device = FALSE; /* writing to a device */
Bram Moolenaar8767f522016-07-01 17:17:39 +02003169 stat_T st_old;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003170 int prev_got_int = got_int;
Bram Moolenaare6bf6552017-06-27 22:11:51 +02003171 int checking_conversion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003172 int file_readonly = FALSE; /* overwritten file is read-only */
3173 static char *err_readonly = "is read-only (cannot override: \"W\" in 'cpoptions')";
Bram Moolenaara06ecab2016-07-16 14:47:36 +02003174#if defined(UNIX) /*XXX fix me sometime? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003175 int made_writable = FALSE; /* 'w' bit has been set */
3176#endif
3177 /* writing everything */
3178 int whole = (start == 1 && end == buf->b_ml.ml_line_count);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003179 linenr_T old_line_count = buf->b_ml.ml_line_count;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003180 int attr;
3181 int fileformat;
3182 int write_bin;
3183 struct bw_info write_info; /* info for buf_write_bytes() */
3184#ifdef FEAT_MBYTE
3185 int converted = FALSE;
3186 int notconverted = FALSE;
3187 char_u *fenc; /* effective 'fileencoding' */
3188 char_u *fenc_tofree = NULL; /* allocated "fenc" */
3189#endif
3190#ifdef HAS_BW_FLAGS
3191 int wb_flags = 0;
3192#endif
3193#ifdef HAVE_ACL
3194 vim_acl_T acl = NULL; /* ACL copied from original file to
3195 backup or new file */
3196#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003197#ifdef FEAT_PERSISTENT_UNDO
3198 int write_undo_file = FALSE;
3199 context_sha256_T sha_ctx;
3200#endif
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003201 unsigned int bkc = get_bkc_value(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003202
3203 if (fname == NULL || *fname == NUL) /* safety check */
3204 return FAIL;
Bram Moolenaar70d60e92009-12-31 13:53:33 +00003205 if (buf->b_ml.ml_mfp == NULL)
3206 {
3207 /* This can happen during startup when there is a stray "w" in the
3208 * vimrc file. */
3209 EMSG(_(e_emptybuf));
3210 return FAIL;
3211 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003212
3213 /*
3214 * Disallow writing from .exrc and .vimrc in current directory for
3215 * security reasons.
3216 */
3217 if (check_secure())
3218 return FAIL;
3219
3220 /* Avoid a crash for a long name. */
3221 if (STRLEN(fname) >= MAXPATHL)
3222 {
3223 EMSG(_(e_longname));
3224 return FAIL;
3225 }
3226
3227#ifdef FEAT_MBYTE
3228 /* must init bw_conv_buf and bw_iconv_fd before jumping to "fail" */
3229 write_info.bw_conv_buf = NULL;
3230 write_info.bw_conv_error = FALSE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003231 write_info.bw_conv_error_lnum = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003232 write_info.bw_restlen = 0;
3233# ifdef USE_ICONV
3234 write_info.bw_iconv_fd = (iconv_t)-1;
3235# endif
3236#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003237#ifdef FEAT_CRYPT
3238 write_info.bw_buffer = buf;
3239#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003240
Bram Moolenaardf177f62005-02-22 08:39:57 +00003241 /* After writing a file changedtick changes but we don't want to display
3242 * the line. */
3243 ex_no_reprint = TRUE;
3244
Bram Moolenaar071d4272004-06-13 20:20:40 +00003245 /*
3246 * If there is no file name yet, use the one for the written file.
3247 * BF_NOTEDITED is set to reflect this (in case the write fails).
3248 * Don't do this when the write is for a filter command.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003249 * Don't do this when appending.
3250 * Only do this when 'cpoptions' contains the 'F' flag.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003251 */
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003252 if (buf->b_ffname == NULL
3253 && reset_changed
Bram Moolenaar071d4272004-06-13 20:20:40 +00003254 && whole
3255 && buf == curbuf
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00003256#ifdef FEAT_QUICKFIX
3257 && !bt_nofile(buf)
3258#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003259 && !filtering
Bram Moolenaar292ad192005-12-11 21:29:51 +00003260 && (!append || vim_strchr(p_cpo, CPO_FNAMEAPP) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003261 && vim_strchr(p_cpo, CPO_FNAMEW) != NULL)
3262 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003263 if (set_rw_fname(fname, sfname) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003264 return FAIL;
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003265 buf = curbuf; /* just in case autocmds made "buf" invalid */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003266 }
3267
3268 if (sfname == NULL)
3269 sfname = fname;
3270 /*
3271 * For Unix: Use the short file name whenever possible.
3272 * Avoids problems with networks and when directory names are changed.
3273 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
3274 * another directory, which we don't detect
3275 */
3276 ffname = fname; /* remember full fname */
3277#ifdef UNIX
3278 fname = sfname;
3279#endif
3280
3281 if (buf->b_ffname != NULL && fnamecmp(ffname, buf->b_ffname) == 0)
3282 overwriting = TRUE;
3283 else
3284 overwriting = FALSE;
3285
3286 if (exiting)
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003287 settmode(TMODE_COOK); /* when exiting allow typeahead now */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003288
3289 ++no_wait_return; /* don't wait for return yet */
3290
3291 /*
3292 * Set '[ and '] marks to the lines to be written.
3293 */
3294 buf->b_op_start.lnum = start;
3295 buf->b_op_start.col = 0;
3296 buf->b_op_end.lnum = end;
3297 buf->b_op_end.col = 0;
3298
Bram Moolenaar071d4272004-06-13 20:20:40 +00003299 {
3300 aco_save_T aco;
3301 int buf_ffname = FALSE;
3302 int buf_sfname = FALSE;
3303 int buf_fname_f = FALSE;
3304 int buf_fname_s = FALSE;
3305 int did_cmd = FALSE;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003306 int nofile_err = FALSE;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003307 int empty_memline = (buf->b_ml.ml_mfp == NULL);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003308 bufref_T bufref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003309
3310 /*
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003311 * Apply PRE autocommands.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003312 * Set curbuf to the buffer to be written.
3313 * Careful: The autocommands may call buf_write() recursively!
3314 */
3315 if (ffname == buf->b_ffname)
3316 buf_ffname = TRUE;
3317 if (sfname == buf->b_sfname)
3318 buf_sfname = TRUE;
3319 if (fname == buf->b_ffname)
3320 buf_fname_f = TRUE;
3321 if (fname == buf->b_sfname)
3322 buf_fname_s = TRUE;
3323
3324 /* set curwin/curbuf to buf and save a few things */
3325 aucmd_prepbuf(&aco, buf);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003326 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003327
3328 if (append)
3329 {
3330 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD,
3331 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003332 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003333#ifdef FEAT_QUICKFIX
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00003334 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003335 nofile_err = TRUE;
3336 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003337#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003338 apply_autocmds_exarg(EVENT_FILEAPPENDPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003339 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003340 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003341 }
3342 else if (filtering)
3343 {
3344 apply_autocmds_exarg(EVENT_FILTERWRITEPRE,
3345 NULL, sfname, FALSE, curbuf, eap);
3346 }
3347 else if (reset_changed && whole)
3348 {
Bram Moolenaar39fc42e2011-09-02 11:56:20 +02003349 int was_changed = curbufIsChanged();
3350
3351 did_cmd = apply_autocmds_exarg(EVENT_BUFWRITECMD,
3352 sfname, sfname, FALSE, curbuf, eap);
3353 if (did_cmd)
3354 {
3355 if (was_changed && !curbufIsChanged())
3356 {
3357 /* Written everything correctly and BufWriteCmd has reset
3358 * 'modified': Correct the undo information so that an
3359 * undo now sets 'modified'. */
3360 u_unchanged(curbuf);
3361 u_update_save_nr(curbuf);
3362 }
3363 }
3364 else
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003365 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003366#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003367 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003368 nofile_err = TRUE;
3369 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003370#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003371 apply_autocmds_exarg(EVENT_BUFWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003372 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003373 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003374 }
3375 else
3376 {
3377 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD,
3378 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003379 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003380#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003381 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003382 nofile_err = TRUE;
3383 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003384#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003385 apply_autocmds_exarg(EVENT_FILEWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003386 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003387 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003388 }
3389
3390 /* restore curwin/curbuf and a few other things */
3391 aucmd_restbuf(&aco);
3392
3393 /*
3394 * In three situations we return here and don't write the file:
3395 * 1. the autocommands deleted or unloaded the buffer.
3396 * 2. The autocommands abort script processing.
3397 * 3. If one of the "Cmd" autocommands was executed.
3398 */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003399 if (!bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003400 buf = NULL;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003401 if (buf == NULL || (buf->b_ml.ml_mfp == NULL && !empty_memline)
Bram Moolenaar1e015462005-09-25 22:16:38 +00003402 || did_cmd || nofile_err
3403#ifdef FEAT_EVAL
3404 || aborting()
3405#endif
3406 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003407 {
3408 --no_wait_return;
3409 msg_scroll = msg_save;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003410 if (nofile_err)
3411 EMSG(_("E676: No matching autocommands for acwrite buffer"));
3412
Bram Moolenaar1e015462005-09-25 22:16:38 +00003413 if (nofile_err
3414#ifdef FEAT_EVAL
3415 || aborting()
3416#endif
3417 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003418 /* An aborting error, interrupt or exception in the
3419 * autocommands. */
3420 return FAIL;
3421 if (did_cmd)
3422 {
3423 if (buf == NULL)
3424 /* The buffer was deleted. We assume it was written
3425 * (can't retry anyway). */
3426 return OK;
3427 if (overwriting)
3428 {
3429 /* Assume the buffer was written, update the timestamp. */
3430 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00003431 if (append)
3432 buf->b_flags &= ~BF_NEW;
3433 else
3434 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003435 }
Bram Moolenaar292ad192005-12-11 21:29:51 +00003436 if (reset_changed && buf->b_changed && !append
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003437 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003438 /* Buffer still changed, the autocommands didn't work
3439 * properly. */
3440 return FAIL;
3441 return OK;
3442 }
3443#ifdef FEAT_EVAL
3444 if (!aborting())
3445#endif
3446 EMSG(_("E203: Autocommands deleted or unloaded buffer to be written"));
3447 return FAIL;
3448 }
3449
3450 /*
3451 * The autocommands may have changed the number of lines in the file.
3452 * When writing the whole file, adjust the end.
3453 * When writing part of the file, assume that the autocommands only
3454 * changed the number of lines that are to be written (tricky!).
3455 */
3456 if (buf->b_ml.ml_line_count != old_line_count)
3457 {
3458 if (whole) /* write all */
3459 end = buf->b_ml.ml_line_count;
3460 else if (buf->b_ml.ml_line_count > old_line_count) /* more lines */
3461 end += buf->b_ml.ml_line_count - old_line_count;
3462 else /* less lines */
3463 {
3464 end -= old_line_count - buf->b_ml.ml_line_count;
3465 if (end < start)
3466 {
3467 --no_wait_return;
3468 msg_scroll = msg_save;
3469 EMSG(_("E204: Autocommand changed number of lines in unexpected way"));
3470 return FAIL;
3471 }
3472 }
3473 }
3474
3475 /*
3476 * The autocommands may have changed the name of the buffer, which may
3477 * be kept in fname, ffname and sfname.
3478 */
3479 if (buf_ffname)
3480 ffname = buf->b_ffname;
3481 if (buf_sfname)
3482 sfname = buf->b_sfname;
3483 if (buf_fname_f)
3484 fname = buf->b_ffname;
3485 if (buf_fname_s)
3486 fname = buf->b_sfname;
3487 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003488
3489#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003490 if (netbeans_active() && isNetbeansBuffer(buf))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003491 {
3492 if (whole)
3493 {
3494 /*
3495 * b_changed can be 0 after an undo, but we still need to write
3496 * the buffer to NetBeans.
3497 */
3498 if (buf->b_changed || isNetbeansModified(buf))
3499 {
Bram Moolenaar009b2592004-10-24 19:18:58 +00003500 --no_wait_return; /* may wait for return now */
3501 msg_scroll = msg_save;
3502 netbeans_save_buffer(buf); /* no error checking... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003503 return retval;
3504 }
3505 else
3506 {
3507 errnum = (char_u *)"E656: ";
Bram Moolenaared0e7452008-06-27 19:17:34 +00003508 errmsg = (char_u *)_("NetBeans disallows writes of unmodified buffers");
Bram Moolenaar071d4272004-06-13 20:20:40 +00003509 buffer = NULL;
3510 goto fail;
3511 }
3512 }
3513 else
3514 {
3515 errnum = (char_u *)"E657: ";
3516 errmsg = (char_u *)_("Partial writes disallowed for NetBeans buffers");
3517 buffer = NULL;
3518 goto fail;
3519 }
3520 }
3521#endif
3522
3523 if (shortmess(SHM_OVER) && !exiting)
3524 msg_scroll = FALSE; /* overwrite previous file message */
3525 else
3526 msg_scroll = TRUE; /* don't overwrite previous file message */
3527 if (!filtering)
3528 filemess(buf,
3529#ifndef UNIX
3530 sfname,
3531#else
3532 fname,
3533#endif
3534 (char_u *)"", 0); /* show that we are busy */
3535 msg_scroll = FALSE; /* always overwrite the file message now */
3536
3537 buffer = alloc(BUFSIZE);
3538 if (buffer == NULL) /* can't allocate big buffer, use small
3539 * one (to be able to write when out of
3540 * memory) */
3541 {
3542 buffer = smallbuf;
3543 bufsize = SMBUFSIZE;
3544 }
3545 else
3546 bufsize = BUFSIZE;
3547
3548 /*
3549 * Get information about original file (if there is one).
3550 */
Bram Moolenaar53076832015-12-31 19:53:21 +01003551#if defined(UNIX)
Bram Moolenaar6f192452007-11-08 19:49:02 +00003552 st_old.st_dev = 0;
3553 st_old.st_ino = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003554 perm = -1;
3555 if (mch_stat((char *)fname, &st_old) < 0)
3556 newfile = TRUE;
3557 else
3558 {
3559 perm = st_old.st_mode;
3560 if (!S_ISREG(st_old.st_mode)) /* not a file */
3561 {
3562 if (S_ISDIR(st_old.st_mode))
3563 {
3564 errnum = (char_u *)"E502: ";
3565 errmsg = (char_u *)_("is a directory");
3566 goto fail;
3567 }
3568 if (mch_nodetype(fname) != NODE_WRITABLE)
3569 {
3570 errnum = (char_u *)"E503: ";
3571 errmsg = (char_u *)_("is not a file or writable device");
3572 goto fail;
3573 }
3574 /* It's a device of some kind (or a fifo) which we can write to
3575 * but for which we can't make a backup. */
3576 device = TRUE;
3577 newfile = TRUE;
3578 perm = -1;
3579 }
3580 }
3581#else /* !UNIX */
3582 /*
3583 * Check for a writable device name.
3584 */
3585 c = mch_nodetype(fname);
3586 if (c == NODE_OTHER)
3587 {
3588 errnum = (char_u *)"E503: ";
3589 errmsg = (char_u *)_("is not a file or writable device");
3590 goto fail;
3591 }
3592 if (c == NODE_WRITABLE)
3593 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003594# if defined(MSWIN)
Bram Moolenaar043545e2006-10-10 16:44:07 +00003595 /* MS-Windows allows opening a device, but we will probably get stuck
3596 * trying to write to it. */
3597 if (!p_odev)
3598 {
3599 errnum = (char_u *)"E796: ";
3600 errmsg = (char_u *)_("writing to device disabled with 'opendevice' option");
3601 goto fail;
3602 }
3603# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003604 device = TRUE;
3605 newfile = TRUE;
3606 perm = -1;
3607 }
3608 else
3609 {
3610 perm = mch_getperm(fname);
3611 if (perm < 0)
3612 newfile = TRUE;
3613 else if (mch_isdir(fname))
3614 {
3615 errnum = (char_u *)"E502: ";
3616 errmsg = (char_u *)_("is a directory");
3617 goto fail;
3618 }
3619 if (overwriting)
3620 (void)mch_stat((char *)fname, &st_old);
3621 }
3622#endif /* !UNIX */
3623
3624 if (!device && !newfile)
3625 {
3626 /*
3627 * Check if the file is really writable (when renaming the file to
3628 * make a backup we won't discover it later).
3629 */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003630 file_readonly = check_file_readonly(fname, (int)perm);
3631
Bram Moolenaar071d4272004-06-13 20:20:40 +00003632 if (!forceit && file_readonly)
3633 {
3634 if (vim_strchr(p_cpo, CPO_FWRITE) != NULL)
3635 {
3636 errnum = (char_u *)"E504: ";
3637 errmsg = (char_u *)_(err_readonly);
3638 }
3639 else
3640 {
3641 errnum = (char_u *)"E505: ";
3642 errmsg = (char_u *)_("is read-only (add ! to override)");
3643 }
3644 goto fail;
3645 }
3646
3647 /*
3648 * Check if the timestamp hasn't changed since reading the file.
3649 */
3650 if (overwriting)
3651 {
3652 retval = check_mtime(buf, &st_old);
3653 if (retval == FAIL)
3654 goto fail;
3655 }
3656 }
3657
3658#ifdef HAVE_ACL
3659 /*
3660 * For systems that support ACL: get the ACL from the original file.
3661 */
3662 if (!newfile)
3663 acl = mch_get_acl(fname);
3664#endif
3665
3666 /*
3667 * If 'backupskip' is not empty, don't make a backup for some files.
3668 */
3669 dobackup = (p_wb || p_bk || *p_pm != NUL);
3670#ifdef FEAT_WILDIGN
3671 if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname))
3672 dobackup = FALSE;
3673#endif
3674
3675 /*
3676 * Save the value of got_int and reset it. We don't want a previous
3677 * interruption cancel writing, only hitting CTRL-C while writing should
3678 * abort it.
3679 */
3680 prev_got_int = got_int;
3681 got_int = FALSE;
3682
3683 /* Mark the buffer as 'being saved' to prevent changed buffer warnings */
3684 buf->b_saving = TRUE;
3685
3686 /*
3687 * If we are not appending or filtering, the file exists, and the
3688 * 'writebackup', 'backup' or 'patchmode' option is set, need a backup.
3689 * When 'patchmode' is set also make a backup when appending.
3690 *
3691 * Do not make any backup, if 'writebackup' and 'backup' are both switched
3692 * off. This helps when editing large files on almost-full disks.
3693 */
3694 if (!(append && *p_pm == NUL) && !filtering && perm >= 0 && dobackup)
3695 {
3696#if defined(UNIX) || defined(WIN32)
Bram Moolenaar8767f522016-07-01 17:17:39 +02003697 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003698#endif
3699
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003700 if ((bkc & BKC_YES) || append) /* "yes" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003701 backup_copy = TRUE;
3702#if defined(UNIX) || defined(WIN32)
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003703 else if ((bkc & BKC_AUTO)) /* "auto" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003704 {
3705 int i;
3706
3707# ifdef UNIX
3708 /*
3709 * Don't rename the file when:
3710 * - it's a hard link
3711 * - it's a symbolic link
3712 * - we don't have write permission in the directory
3713 * - we can't set the owner/group of the new file
3714 */
3715 if (st_old.st_nlink > 1
3716 || mch_lstat((char *)fname, &st) < 0
3717 || st.st_dev != st_old.st_dev
Bram Moolenaara5792f52005-11-23 21:25:05 +00003718 || st.st_ino != st_old.st_ino
3719# ifndef HAVE_FCHOWN
3720 || st.st_uid != st_old.st_uid
3721 || st.st_gid != st_old.st_gid
3722# endif
3723 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003724 backup_copy = TRUE;
3725 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003726# else
3727# ifdef WIN32
3728 /* On NTFS file systems hard links are possible. */
3729 if (mch_is_linked(fname))
3730 backup_copy = TRUE;
3731 else
3732# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003733# endif
3734 {
3735 /*
3736 * Check if we can create a file and set the owner/group to
3737 * the ones from the original file.
3738 * First find a file name that doesn't exist yet (use some
3739 * arbitrary numbers).
3740 */
3741 STRCPY(IObuff, fname);
3742 for (i = 4913; ; i += 123)
3743 {
3744 sprintf((char *)gettail(IObuff), "%d", i);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003745 if (mch_lstat((char *)IObuff, &st) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003746 break;
3747 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00003748 fd = mch_open((char *)IObuff,
3749 O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003750 if (fd < 0) /* can't write in directory */
3751 backup_copy = TRUE;
3752 else
3753 {
3754# ifdef UNIX
Bram Moolenaara5792f52005-11-23 21:25:05 +00003755# ifdef HAVE_FCHOWN
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00003756 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003757# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003758 if (mch_stat((char *)IObuff, &st) < 0
3759 || st.st_uid != st_old.st_uid
3760 || st.st_gid != st_old.st_gid
Bram Moolenaar78a15312009-05-15 19:33:18 +00003761 || (long)st.st_mode != perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003762 backup_copy = TRUE;
3763# endif
Bram Moolenaar98358622005-11-28 22:58:23 +00003764 /* Close the file before removing it, on MS-Windows we
3765 * can't delete an open file. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003766 close(fd);
Bram Moolenaar98358622005-11-28 22:58:23 +00003767 mch_remove(IObuff);
Bram Moolenaar3479c5d2010-08-08 18:46:06 +02003768# ifdef MSWIN
3769 /* MS-Windows may trigger a virus scanner to open the
3770 * file, we can't delete it then. Keep trying for half a
3771 * second. */
3772 {
3773 int try;
3774
3775 for (try = 0; try < 10; ++try)
3776 {
3777 if (mch_lstat((char *)IObuff, &st) < 0)
3778 break;
3779 ui_delay(50L, TRUE); /* wait 50 msec */
3780 mch_remove(IObuff);
3781 }
3782 }
3783# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003784 }
3785 }
3786 }
3787
Bram Moolenaar071d4272004-06-13 20:20:40 +00003788 /*
3789 * Break symlinks and/or hardlinks if we've been asked to.
3790 */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003791 if ((bkc & BKC_BREAKSYMLINK) || (bkc & BKC_BREAKHARDLINK))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003792 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003793# ifdef UNIX
Bram Moolenaar071d4272004-06-13 20:20:40 +00003794 int lstat_res;
3795
3796 lstat_res = mch_lstat((char *)fname, &st);
3797
3798 /* Symlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003799 if ((bkc & BKC_BREAKSYMLINK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003800 && lstat_res == 0
3801 && st.st_ino != st_old.st_ino)
3802 backup_copy = FALSE;
3803
3804 /* Hardlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003805 if ((bkc & BKC_BREAKHARDLINK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003806 && st_old.st_nlink > 1
3807 && (lstat_res != 0 || st.st_ino == st_old.st_ino))
3808 backup_copy = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003809# else
3810# if defined(WIN32)
3811 /* Symlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003812 if ((bkc & BKC_BREAKSYMLINK) && mch_is_symbolic_link(fname))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003813 backup_copy = FALSE;
3814
3815 /* Hardlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003816 if ((bkc & BKC_BREAKHARDLINK) && mch_is_hard_link(fname))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003817 backup_copy = FALSE;
3818# endif
3819# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003820 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003821
3822#endif
3823
3824 /* make sure we have a valid backup extension to use */
3825 if (*p_bex == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003826 backup_ext = (char_u *)".bak";
Bram Moolenaar071d4272004-06-13 20:20:40 +00003827 else
3828 backup_ext = p_bex;
3829
3830 if (backup_copy
3831 && (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) >= 0)
3832 {
3833 int bfd;
3834 char_u *copybuf, *wp;
3835 int some_error = FALSE;
Bram Moolenaar8767f522016-07-01 17:17:39 +02003836 stat_T st_new;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003837 char_u *dirp;
3838 char_u *rootname;
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003839#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003840 int did_set_shortname;
Bram Moolenaarcd142e32017-11-16 17:03:45 +01003841 mode_t umask_save;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003842#endif
3843
3844 copybuf = alloc(BUFSIZE + 1);
3845 if (copybuf == NULL)
3846 {
3847 some_error = TRUE; /* out of memory */
3848 goto nobackup;
3849 }
3850
3851 /*
3852 * Try to make the backup in each directory in the 'bdir' option.
3853 *
3854 * Unix semantics has it, that we may have a writable file,
3855 * that cannot be recreated with a simple open(..., O_CREAT, ) e.g:
3856 * - the directory is not writable,
3857 * - the file may be a symbolic link,
3858 * - the file may belong to another user/group, etc.
3859 *
3860 * For these reasons, the existing writable file must be truncated
3861 * and reused. Creation of a backup COPY will be attempted.
3862 */
3863 dirp = p_bdir;
3864 while (*dirp)
3865 {
3866#ifdef UNIX
3867 st_new.st_ino = 0;
3868 st_new.st_dev = 0;
3869 st_new.st_gid = 0;
3870#endif
3871
3872 /*
3873 * Isolate one directory name, using an entry in 'bdir'.
3874 */
3875 (void)copy_option_part(&dirp, copybuf, BUFSIZE, ",");
3876 rootname = get_file_in_dir(fname, copybuf);
3877 if (rootname == NULL)
3878 {
3879 some_error = TRUE; /* out of memory */
3880 goto nobackup;
3881 }
3882
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003883#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003884 did_set_shortname = FALSE;
3885#endif
3886
3887 /*
3888 * May try twice if 'shortname' not set.
3889 */
3890 for (;;)
3891 {
3892 /*
3893 * Make backup file name.
3894 */
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003895 backup = buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003896 rootname, backup_ext, FALSE);
3897 if (backup == NULL)
3898 {
3899 vim_free(rootname);
3900 some_error = TRUE; /* out of memory */
3901 goto nobackup;
3902 }
3903
3904 /*
3905 * Check if backup file already exists.
3906 */
3907 if (mch_stat((char *)backup, &st_new) >= 0)
3908 {
3909#ifdef UNIX
3910 /*
3911 * Check if backup file is same as original file.
3912 * May happen when modname() gave the same file back.
3913 * E.g. silly link, or file name-length reached.
3914 * If we don't check here, we either ruin the file
3915 * when copying or erase it after writing. jw.
3916 */
3917 if (st_new.st_dev == st_old.st_dev
3918 && st_new.st_ino == st_old.st_ino)
3919 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01003920 VIM_CLEAR(backup); /* no backup file to delete */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003921 /*
3922 * may try again with 'shortname' set
3923 */
3924 if (!(buf->b_shortname || buf->b_p_sn))
3925 {
3926 buf->b_shortname = TRUE;
3927 did_set_shortname = TRUE;
3928 continue;
3929 }
3930 /* setting shortname didn't help */
3931 if (did_set_shortname)
3932 buf->b_shortname = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003933 break;
3934 }
3935#endif
3936
3937 /*
3938 * If we are not going to keep the backup file, don't
3939 * delete an existing one, try to use another name.
3940 * Change one character, just before the extension.
3941 */
3942 if (!p_bk)
3943 {
3944 wp = backup + STRLEN(backup) - 1
3945 - STRLEN(backup_ext);
3946 if (wp < backup) /* empty file name ??? */
3947 wp = backup;
3948 *wp = 'z';
3949 while (*wp > 'a'
3950 && mch_stat((char *)backup, &st_new) >= 0)
3951 --*wp;
3952 /* They all exist??? Must be something wrong. */
3953 if (*wp == 'a')
Bram Moolenaard23a8232018-02-10 18:45:26 +01003954 VIM_CLEAR(backup);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003955 }
3956 }
3957 break;
3958 }
3959 vim_free(rootname);
3960
3961 /*
3962 * Try to create the backup file
3963 */
3964 if (backup != NULL)
3965 {
3966 /* remove old backup, if present */
3967 mch_remove(backup);
3968 /* Open with O_EXCL to avoid the file being created while
Bram Moolenaarcd142e32017-11-16 17:03:45 +01003969 * we were sleeping (symlink hacker attack?). Reset umask
3970 * if possible to avoid mch_setperm() below. */
3971#ifdef UNIX
3972 umask_save = umask(0);
3973#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003974 bfd = mch_open((char *)backup,
Bram Moolenaara5792f52005-11-23 21:25:05 +00003975 O_WRONLY|O_CREAT|O_EXTRA|O_EXCL|O_NOFOLLOW,
3976 perm & 0777);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01003977#ifdef UNIX
3978 (void)umask(umask_save);
3979#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003980 if (bfd < 0)
Bram Moolenaard23a8232018-02-10 18:45:26 +01003981 VIM_CLEAR(backup);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003982 else
3983 {
Bram Moolenaarcd142e32017-11-16 17:03:45 +01003984 /* Set file protection same as original file, but
3985 * strip s-bit. Only needed if umask() wasn't used
3986 * above. */
3987#ifndef UNIX
Bram Moolenaar071d4272004-06-13 20:20:40 +00003988 (void)mch_setperm(backup, perm & 0777);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01003989#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00003990 /*
3991 * Try to set the group of the backup same as the
3992 * original file. If this fails, set the protection
3993 * bits for the group same as the protection bits for
3994 * others.
3995 */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003996 if (st_new.st_gid != st_old.st_gid
Bram Moolenaar071d4272004-06-13 20:20:40 +00003997# ifdef HAVE_FCHOWN /* sequent-ptx lacks fchown() */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003998 && fchown(bfd, (uid_t)-1, st_old.st_gid) != 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00003999# endif
4000 )
4001 mch_setperm(backup,
4002 (perm & 0707) | ((perm & 07) << 3));
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004003# if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004004 mch_copy_sec(fname, backup);
4005# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004006#endif
4007
4008 /*
4009 * copy the file.
4010 */
4011 write_info.bw_fd = bfd;
4012 write_info.bw_buf = copybuf;
4013#ifdef HAS_BW_FLAGS
4014 write_info.bw_flags = FIO_NOCONVERT;
4015#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004016 while ((write_info.bw_len = read_eintr(fd, copybuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004017 BUFSIZE)) > 0)
4018 {
4019 if (buf_write_bytes(&write_info) == FAIL)
4020 {
4021 errmsg = (char_u *)_("E506: Can't write to backup file (add ! to override)");
4022 break;
4023 }
4024 ui_breakcheck();
4025 if (got_int)
4026 {
4027 errmsg = (char_u *)_(e_interr);
4028 break;
4029 }
4030 }
4031
4032 if (close(bfd) < 0 && errmsg == NULL)
4033 errmsg = (char_u *)_("E507: Close error for backup file (add ! to override)");
4034 if (write_info.bw_len < 0)
4035 errmsg = (char_u *)_("E508: Can't read file for backup (add ! to override)");
4036#ifdef UNIX
4037 set_file_time(backup, st_old.st_atime, st_old.st_mtime);
4038#endif
4039#ifdef HAVE_ACL
4040 mch_set_acl(backup, acl);
4041#endif
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004042#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004043 mch_copy_sec(fname, backup);
4044#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004045 break;
4046 }
4047 }
4048 }
4049 nobackup:
4050 close(fd); /* ignore errors for closing read file */
4051 vim_free(copybuf);
4052
4053 if (backup == NULL && errmsg == NULL)
4054 errmsg = (char_u *)_("E509: Cannot create backup file (add ! to override)");
4055 /* ignore errors when forceit is TRUE */
4056 if ((some_error || errmsg != NULL) && !forceit)
4057 {
4058 retval = FAIL;
4059 goto fail;
4060 }
4061 errmsg = NULL;
4062 }
4063 else
4064 {
4065 char_u *dirp;
4066 char_u *p;
4067 char_u *rootname;
4068
4069 /*
4070 * Make a backup by renaming the original file.
4071 */
4072 /*
4073 * If 'cpoptions' includes the "W" flag, we don't want to
4074 * overwrite a read-only file. But rename may be possible
4075 * anyway, thus we need an extra check here.
4076 */
4077 if (file_readonly && vim_strchr(p_cpo, CPO_FWRITE) != NULL)
4078 {
4079 errnum = (char_u *)"E504: ";
4080 errmsg = (char_u *)_(err_readonly);
4081 goto fail;
4082 }
4083
4084 /*
4085 *
4086 * Form the backup file name - change path/fo.o.h to
4087 * path/fo.o.h.bak Try all directories in 'backupdir', first one
4088 * that works is used.
4089 */
4090 dirp = p_bdir;
4091 while (*dirp)
4092 {
4093 /*
4094 * Isolate one directory name and make the backup file name.
4095 */
4096 (void)copy_option_part(&dirp, IObuff, IOSIZE, ",");
4097 rootname = get_file_in_dir(fname, IObuff);
4098 if (rootname == NULL)
4099 backup = NULL;
4100 else
4101 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01004102 backup = buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00004103 rootname, backup_ext, FALSE);
4104 vim_free(rootname);
4105 }
4106
4107 if (backup != NULL)
4108 {
4109 /*
4110 * If we are not going to keep the backup file, don't
4111 * delete an existing one, try to use another name.
4112 * Change one character, just before the extension.
4113 */
4114 if (!p_bk && mch_getperm(backup) >= 0)
4115 {
4116 p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext);
4117 if (p < backup) /* empty file name ??? */
4118 p = backup;
4119 *p = 'z';
4120 while (*p > 'a' && mch_getperm(backup) >= 0)
4121 --*p;
4122 /* They all exist??? Must be something wrong! */
4123 if (*p == 'a')
Bram Moolenaard23a8232018-02-10 18:45:26 +01004124 VIM_CLEAR(backup);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004125 }
4126 }
4127 if (backup != NULL)
4128 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004129 /*
Bram Moolenaarbfd8fc02005-09-20 23:22:24 +00004130 * Delete any existing backup and move the current version
4131 * to the backup. For safety, we don't remove the backup
4132 * until the write has finished successfully. And if the
4133 * 'backup' option is set, leave it around.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004134 */
4135 /*
4136 * If the renaming of the original file to the backup file
4137 * works, quit here.
4138 */
4139 if (vim_rename(fname, backup) == 0)
4140 break;
4141
Bram Moolenaard23a8232018-02-10 18:45:26 +01004142 VIM_CLEAR(backup); /* don't do the rename below */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004143 }
4144 }
4145 if (backup == NULL && !forceit)
4146 {
4147 errmsg = (char_u *)_("E510: Can't make backup file (add ! to override)");
4148 goto fail;
4149 }
4150 }
4151 }
4152
Bram Moolenaar53076832015-12-31 19:53:21 +01004153#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004154 /* When using ":w!" and the file was read-only: make it writable */
4155 if (forceit && perm >= 0 && !(perm & 0200) && st_old.st_uid == getuid()
4156 && vim_strchr(p_cpo, CPO_FWRITE) == NULL)
4157 {
4158 perm |= 0200;
4159 (void)mch_setperm(fname, perm);
4160 made_writable = TRUE;
4161 }
4162#endif
4163
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004164 /* When using ":w!" and writing to the current file, 'readonly' makes no
Bram Moolenaar4399ef42005-02-12 14:29:27 +00004165 * sense, reset it, unless 'Z' appears in 'cpoptions'. */
4166 if (forceit && overwriting && vim_strchr(p_cpo, CPO_KEEPRO) == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004167 {
4168 buf->b_p_ro = FALSE;
4169#ifdef FEAT_TITLE
4170 need_maketitle = TRUE; /* set window title later */
4171#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004172 status_redraw_all(); /* redraw status lines later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004173 }
4174
4175 if (end > buf->b_ml.ml_line_count)
4176 end = buf->b_ml.ml_line_count;
4177 if (buf->b_ml.ml_flags & ML_EMPTY)
4178 start = end + 1;
4179
4180 /*
4181 * If the original file is being overwritten, there is a small chance that
4182 * we crash in the middle of writing. Therefore the file is preserved now.
4183 * This makes all block numbers positive so that recovery does not need
4184 * the original file.
4185 * Don't do this if there is a backup file and we are exiting.
4186 */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004187 if (reset_changed && !newfile && overwriting
Bram Moolenaar071d4272004-06-13 20:20:40 +00004188 && !(exiting && backup != NULL))
4189 {
4190 ml_preserve(buf, FALSE);
4191 if (got_int)
4192 {
4193 errmsg = (char_u *)_(e_interr);
4194 goto restore_backup;
4195 }
4196 }
4197
Bram Moolenaar071d4272004-06-13 20:20:40 +00004198#ifdef VMS
4199 vms_remove_version(fname); /* remove version */
4200#endif
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00004201 /* Default: write the file directly. May write to a temp file for
Bram Moolenaar071d4272004-06-13 20:20:40 +00004202 * multi-byte conversion. */
4203 wfname = fname;
4204
4205#ifdef FEAT_MBYTE
4206 /* Check for forced 'fileencoding' from "++opt=val" argument. */
4207 if (eap != NULL && eap->force_enc != 0)
4208 {
4209 fenc = eap->cmd + eap->force_enc;
4210 fenc = enc_canonize(fenc);
4211 fenc_tofree = fenc;
4212 }
4213 else
4214 fenc = buf->b_p_fenc;
4215
4216 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004217 * Check if the file needs to be converted.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004218 */
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004219 converted = need_conversion(fenc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004220
4221 /*
4222 * Check if UTF-8 to UCS-2/4 or Latin1 conversion needs to be done. Or
4223 * Latin1 to Unicode conversion. This is handled in buf_write_bytes().
4224 * Prepare the flags for it and allocate bw_conv_buf when needed.
4225 */
4226 if (converted && (enc_utf8 || STRCMP(p_enc, "latin1") == 0))
4227 {
4228 wb_flags = get_fio_flags(fenc);
4229 if (wb_flags & (FIO_UCS2 | FIO_UCS4 | FIO_UTF16 | FIO_UTF8))
4230 {
4231 /* Need to allocate a buffer to translate into. */
4232 if (wb_flags & (FIO_UCS2 | FIO_UTF16 | FIO_UTF8))
4233 write_info.bw_conv_buflen = bufsize * 2;
4234 else /* FIO_UCS4 */
4235 write_info.bw_conv_buflen = bufsize * 4;
4236 write_info.bw_conv_buf
4237 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4238 if (write_info.bw_conv_buf == NULL)
4239 end = 0;
4240 }
4241 }
4242
4243# ifdef WIN3264
4244 if (converted && wb_flags == 0 && (wb_flags = get_win_fio_flags(fenc)) != 0)
4245 {
4246 /* Convert UTF-8 -> UCS-2 and UCS-2 -> DBCS. Worst-case * 4: */
4247 write_info.bw_conv_buflen = bufsize * 4;
4248 write_info.bw_conv_buf
4249 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4250 if (write_info.bw_conv_buf == NULL)
4251 end = 0;
4252 }
4253# endif
4254
Bram Moolenaard0573012017-10-28 21:11:06 +02004255# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00004256 if (converted && wb_flags == 0 && (wb_flags = get_mac_fio_flags(fenc)) != 0)
4257 {
4258 write_info.bw_conv_buflen = bufsize * 3;
4259 write_info.bw_conv_buf
4260 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4261 if (write_info.bw_conv_buf == NULL)
4262 end = 0;
4263 }
4264# endif
4265
4266# if defined(FEAT_EVAL) || defined(USE_ICONV)
4267 if (converted && wb_flags == 0)
4268 {
4269# ifdef USE_ICONV
4270 /*
4271 * Use iconv() conversion when conversion is needed and it's not done
4272 * internally.
4273 */
4274 write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc,
4275 enc_utf8 ? (char_u *)"utf-8" : p_enc);
4276 if (write_info.bw_iconv_fd != (iconv_t)-1)
4277 {
4278 /* We're going to use iconv(), allocate a buffer to convert in. */
4279 write_info.bw_conv_buflen = bufsize * ICONV_MULT;
4280 write_info.bw_conv_buf
4281 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4282 if (write_info.bw_conv_buf == NULL)
4283 end = 0;
4284 write_info.bw_first = TRUE;
4285 }
4286# ifdef FEAT_EVAL
4287 else
4288# endif
4289# endif
4290
4291# ifdef FEAT_EVAL
4292 /*
4293 * When the file needs to be converted with 'charconvert' after
4294 * writing, write to a temp file instead and let the conversion
4295 * overwrite the original file.
4296 */
4297 if (*p_ccv != NUL)
4298 {
Bram Moolenaare5c421c2015-03-31 13:33:08 +02004299 wfname = vim_tempname('w', FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004300 if (wfname == NULL) /* Can't write without a tempfile! */
4301 {
4302 errmsg = (char_u *)_("E214: Can't find temp file for writing");
4303 goto restore_backup;
4304 }
4305 }
4306# endif
4307 }
4308# endif
4309 if (converted && wb_flags == 0
4310# ifdef USE_ICONV
4311 && write_info.bw_iconv_fd == (iconv_t)-1
4312# endif
4313# ifdef FEAT_EVAL
4314 && wfname == fname
4315# endif
4316 )
4317 {
4318 if (!forceit)
4319 {
4320 errmsg = (char_u *)_("E213: Cannot convert (add ! to write without conversion)");
4321 goto restore_backup;
4322 }
4323 notconverted = TRUE;
4324 }
4325#endif
4326
4327 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004328 * If conversion is taking place, we may first pretend to write and check
4329 * for conversion errors. Then loop again to write for real.
4330 * When not doing conversion this writes for real right away.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004331 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004332 for (checking_conversion = TRUE; ; checking_conversion = FALSE)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004333 {
4334 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004335 * There is no need to check conversion when:
4336 * - there is no conversion
4337 * - we make a backup file, that can be restored in case of conversion
4338 * failure.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004339 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004340#ifdef FEAT_MBYTE
4341 if (!converted || dobackup)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004342#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004343 checking_conversion = FALSE;
4344
4345 if (checking_conversion)
4346 {
4347 /* Make sure we don't write anything. */
4348 fd = -1;
4349 write_info.bw_fd = fd;
4350 }
4351 else
4352 {
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004353#ifdef HAVE_FTRUNCATE
4354# define TRUNC_ON_OPEN 0
4355#else
4356# define TRUNC_ON_OPEN O_TRUNC
4357#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004358 /*
4359 * Open the file "wfname" for writing.
4360 * We may try to open the file twice: If we can't write to the file
4361 * and forceit is TRUE we delete the existing file and try to
4362 * create a new one. If this still fails we may have lost the
4363 * original file! (this may happen when the user reached his
4364 * quotum for number of files).
4365 * Appending will fail if the file does not exist and forceit is
4366 * FALSE.
4367 */
4368 while ((fd = mch_open((char *)wfname, O_WRONLY | O_EXTRA | (append
4369 ? (forceit ? (O_APPEND | O_CREAT) : O_APPEND)
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004370 : (O_CREAT | TRUNC_ON_OPEN))
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004371 , perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004372 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004373 /*
4374 * A forced write will try to create a new file if the old one
4375 * is still readonly. This may also happen when the directory
4376 * is read-only. In that case the mch_remove() will fail.
4377 */
4378 if (errmsg == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004379 {
4380#ifdef UNIX
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004381 stat_T st;
4382
4383 /* Don't delete the file when it's a hard or symbolic link.
4384 */
4385 if ((!newfile && st_old.st_nlink > 1)
4386 || (mch_lstat((char *)fname, &st) == 0
4387 && (st.st_dev != st_old.st_dev
4388 || st.st_ino != st_old.st_ino)))
4389 errmsg = (char_u *)_("E166: Can't open linked file for writing");
4390 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004391#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004392 {
4393 errmsg = (char_u *)_("E212: Can't open file for writing");
4394 if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL
4395 && perm >= 0)
4396 {
4397#ifdef UNIX
4398 /* we write to the file, thus it should be marked
4399 writable after all */
4400 if (!(perm & 0200))
4401 made_writable = TRUE;
4402 perm |= 0200;
4403 if (st_old.st_uid != getuid()
4404 || st_old.st_gid != getgid())
4405 perm &= 0777;
4406#endif
4407 if (!append) /* don't remove when appending */
4408 mch_remove(wfname);
4409 continue;
4410 }
4411 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004412 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004413
4414restore_backup:
Bram Moolenaar071d4272004-06-13 20:20:40 +00004415 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004416 stat_T st;
4417
Bram Moolenaar071d4272004-06-13 20:20:40 +00004418 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004419 * If we failed to open the file, we don't need a backup.
4420 * Throw it away. If we moved or removed the original file
4421 * try to put the backup in its place.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004422 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004423 if (backup != NULL && wfname == fname)
4424 {
4425 if (backup_copy)
4426 {
4427 /*
4428 * There is a small chance that we removed the
4429 * original, try to move the copy in its place.
4430 * This may not work if the vim_rename() fails.
4431 * In that case we leave the copy around.
4432 */
4433 /* If file does not exist, put the copy in its
4434 * place */
4435 if (mch_stat((char *)fname, &st) < 0)
4436 vim_rename(backup, fname);
4437 /* if original file does exist throw away the copy
4438 */
4439 if (mch_stat((char *)fname, &st) >= 0)
4440 mch_remove(backup);
4441 }
4442 else
4443 {
4444 /* try to put the original file back */
4445 vim_rename(backup, fname);
4446 }
4447 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004448
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004449 /* if original file no longer exists give an extra warning
4450 */
4451 if (!newfile && mch_stat((char *)fname, &st) < 0)
4452 end = 0;
4453 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004454
4455#ifdef FEAT_MBYTE
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004456 if (wfname != fname)
4457 vim_free(wfname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004458#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004459 goto fail;
4460 }
4461 write_info.bw_fd = fd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004462
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004463#if defined(UNIX)
4464 {
4465 stat_T st;
4466
4467 /* Double check we are writing the intended file before making
4468 * any changes. */
4469 if (overwriting
4470 && (!dobackup || backup_copy)
4471 && fname == wfname
4472 && perm >= 0
4473 && mch_fstat(fd, &st) == 0
4474 && st.st_ino != st_old.st_ino)
4475 {
4476 close(fd);
4477 errmsg = (char_u *)_("E949: File changed while writing");
4478 goto fail;
4479 }
4480 }
4481#endif
4482#ifdef HAVE_FTRUNCATE
4483 if (!append)
Bram Moolenaarae1e1082017-11-17 21:35:24 +01004484 ignored = ftruncate(fd, (off_t)0);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004485#endif
4486
Bram Moolenaard0573012017-10-28 21:11:06 +02004487#if defined(WIN3264)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004488 if (backup != NULL && overwriting && !append)
4489 {
4490 if (backup_copy)
4491 (void)mch_copy_file_attribute(wfname, backup);
4492 else
4493 (void)mch_copy_file_attribute(backup, wfname);
4494 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004495
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004496 if (!overwriting && !append)
4497 {
4498 if (buf->b_ffname != NULL)
4499 (void)mch_copy_file_attribute(buf->b_ffname, wfname);
4500 /* Should copy resource fork */
4501 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004502#endif
4503
Bram Moolenaar071d4272004-06-13 20:20:40 +00004504#ifdef FEAT_CRYPT
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004505 if (*buf->b_p_key != NUL && !filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004506 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004507 char_u *header;
4508 int header_len;
4509
4510 buf->b_cryptstate = crypt_create_for_writing(
4511 crypt_get_method_nr(buf),
4512 buf->b_p_key, &header, &header_len);
4513 if (buf->b_cryptstate == NULL || header == NULL)
4514 end = 0;
4515 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004516 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004517 /* Write magic number, so that Vim knows how this file is
4518 * encrypted when reading it back. */
4519 write_info.bw_buf = header;
4520 write_info.bw_len = header_len;
4521 write_info.bw_flags = FIO_NOCONVERT;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004522 if (buf_write_bytes(&write_info) == FAIL)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004523 end = 0;
4524 wb_flags |= FIO_ENCRYPTED;
4525 vim_free(header);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004526 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004527 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004528#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004529 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004530 errmsg = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004531
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004532 write_info.bw_buf = buffer;
4533 nchars = 0;
4534
4535 /* use "++bin", "++nobin" or 'binary' */
4536 if (eap != NULL && eap->force_bin != 0)
4537 write_bin = (eap->force_bin == FORCE_BIN);
4538 else
4539 write_bin = buf->b_p_bin;
4540
4541#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004542 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004543 * The BOM is written just after the encryption magic number.
4544 * Skip it when appending and the file already existed, the BOM only
4545 * makes sense at the start of the file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004546 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004547 if (buf->b_p_bomb && !write_bin && (!append || perm < 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004548 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004549 write_info.bw_len = make_bom(buffer, fenc);
4550 if (write_info.bw_len > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004551 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004552 /* don't convert, do encryption */
4553 write_info.bw_flags = FIO_NOCONVERT | wb_flags;
4554 if (buf_write_bytes(&write_info) == FAIL)
4555 end = 0;
4556 else
4557 nchars += write_info.bw_len;
4558 }
4559 }
4560 write_info.bw_start_lnum = start;
4561#endif
4562
4563#ifdef FEAT_PERSISTENT_UNDO
4564 write_undo_file = (buf->b_p_udf
4565 && overwriting
4566 && !append
4567 && !filtering
4568 && reset_changed
4569 && !checking_conversion);
4570 if (write_undo_file)
4571 /* Prepare for computing the hash value of the text. */
4572 sha256_start(&sha_ctx);
4573#endif
4574
4575 write_info.bw_len = bufsize;
4576#ifdef HAS_BW_FLAGS
4577 write_info.bw_flags = wb_flags;
4578#endif
4579 fileformat = get_fileformat_force(buf, eap);
4580 s = buffer;
4581 len = 0;
4582 for (lnum = start; lnum <= end; ++lnum)
4583 {
4584 /*
4585 * The next while loop is done once for each character written.
4586 * Keep it fast!
4587 */
4588 ptr = ml_get_buf(buf, lnum, FALSE) - 1;
4589#ifdef FEAT_PERSISTENT_UNDO
4590 if (write_undo_file)
4591 sha256_update(&sha_ctx, ptr + 1,
4592 (UINT32_T)(STRLEN(ptr + 1) + 1));
4593#endif
4594 while ((c = *++ptr) != NUL)
4595 {
4596 if (c == NL)
4597 *s = NUL; /* replace newlines with NULs */
4598 else if (c == CAR && fileformat == EOL_MAC)
4599 *s = NL; /* Mac: replace CRs with NLs */
4600 else
4601 *s = c;
4602 ++s;
4603 if (++len != bufsize)
4604 continue;
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004605 if (buf_write_bytes(&write_info) == FAIL)
4606 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004607 end = 0; /* write error: break loop */
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004608 break;
4609 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004610 nchars += bufsize;
4611 s = buffer;
4612 len = 0;
4613#ifdef FEAT_MBYTE
4614 write_info.bw_start_lnum = lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004615#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004616 }
4617 /* write failed or last line has no EOL: stop here */
4618 if (end == 0
4619 || (lnum == end
4620 && (write_bin || !buf->b_p_fixeol)
4621 && (lnum == buf->b_no_eol_lnum
4622 || (lnum == buf->b_ml.ml_line_count
4623 && !buf->b_p_eol))))
4624 {
4625 ++lnum; /* written the line, count it */
4626 no_eol = TRUE;
4627 break;
4628 }
4629 if (fileformat == EOL_UNIX)
4630 *s++ = NL;
4631 else
4632 {
4633 *s++ = CAR; /* EOL_MAC or EOL_DOS: write CR */
4634 if (fileformat == EOL_DOS) /* write CR-NL */
4635 {
4636 if (++len == bufsize)
4637 {
4638 if (buf_write_bytes(&write_info) == FAIL)
4639 {
4640 end = 0; /* write error: break loop */
4641 break;
4642 }
4643 nchars += bufsize;
4644 s = buffer;
4645 len = 0;
4646 }
4647 *s++ = NL;
4648 }
4649 }
4650 if (++len == bufsize && end)
4651 {
4652 if (buf_write_bytes(&write_info) == FAIL)
4653 {
4654 end = 0; /* write error: break loop */
4655 break;
4656 }
4657 nchars += bufsize;
4658 s = buffer;
4659 len = 0;
4660
4661 ui_breakcheck();
4662 if (got_int)
4663 {
4664 end = 0; /* Interrupted, break loop */
4665 break;
4666 }
4667 }
4668#ifdef VMS
4669 /*
4670 * On VMS there is a problem: newlines get added when writing
4671 * blocks at a time. Fix it by writing a line at a time.
4672 * This is much slower!
4673 * Explanation: VAX/DECC RTL insists that records in some RMS
4674 * structures end with a newline (carriage return) character, and
4675 * if they don't it adds one.
4676 * With other RMS structures it works perfect without this fix.
4677 */
4678 if (buf->b_fab_rfm == FAB$C_VFC
4679 || ((buf->b_fab_rat & (FAB$M_FTN | FAB$M_CR)) != 0))
4680 {
4681 int b2write;
4682
4683 buf->b_fab_mrs = (buf->b_fab_mrs == 0
4684 ? MIN(4096, bufsize)
4685 : MIN(buf->b_fab_mrs, bufsize));
4686
4687 b2write = len;
4688 while (b2write > 0)
4689 {
4690 write_info.bw_len = MIN(b2write, buf->b_fab_mrs);
4691 if (buf_write_bytes(&write_info) == FAIL)
4692 {
4693 end = 0;
4694 break;
4695 }
4696 b2write -= MIN(b2write, buf->b_fab_mrs);
4697 }
4698 write_info.bw_len = bufsize;
4699 nchars += len;
4700 s = buffer;
4701 len = 0;
4702 }
4703#endif
4704 }
4705 if (len > 0 && end > 0)
4706 {
4707 write_info.bw_len = len;
4708 if (buf_write_bytes(&write_info) == FAIL)
4709 end = 0; /* write error */
4710 nchars += len;
4711 }
4712
4713 /* Stop when writing done or an error was encountered. */
4714 if (!checking_conversion || end == 0)
4715 break;
4716
4717 /* If no error happened until now, writing should be ok, so loop to
4718 * really write the buffer. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004719 }
4720
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004721 /* If we started writing, finish writing. Also when an error was
4722 * encountered. */
4723 if (!checking_conversion)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004724 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004725#if defined(UNIX) && defined(HAVE_FSYNC)
4726 /*
4727 * On many journalling file systems there is a bug that causes both the
4728 * original and the backup file to be lost when halting the system
4729 * right after writing the file. That's because only the meta-data is
4730 * journalled. Syncing the file slows down the system, but assures it
4731 * has been written to disk and we don't lose it.
4732 * For a device do try the fsync() but don't complain if it does not
4733 * work (could be a pipe).
4734 * If the 'fsync' option is FALSE, don't fsync(). Useful for laptops.
4735 */
4736 if (p_fs && fsync(fd) != 0 && !device)
4737 {
Bram Moolenaar7567d0b2017-11-16 23:04:15 +01004738 errmsg = (char_u *)_(e_fsync);
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004739 end = 0;
4740 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004741#endif
4742
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004743#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004744 /* Probably need to set the security context. */
4745 if (!backup_copy)
4746 mch_copy_sec(backup, wfname);
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004747#endif
4748
Bram Moolenaara5792f52005-11-23 21:25:05 +00004749#ifdef UNIX
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004750 /* When creating a new file, set its owner/group to that of the
4751 * original file. Get the new device and inode number. */
4752 if (backup != NULL && !backup_copy)
Bram Moolenaara5792f52005-11-23 21:25:05 +00004753 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004754# ifdef HAVE_FCHOWN
4755 stat_T st;
4756
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004757 /* Don't change the owner when it's already OK, some systems remove
4758 * permission or ACL stuff. */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004759 if (mch_stat((char *)wfname, &st) < 0
4760 || st.st_uid != st_old.st_uid
4761 || st.st_gid != st_old.st_gid)
4762 {
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004763 /* changing owner might not be possible */
4764 ignored = fchown(fd, st_old.st_uid, -1);
4765 /* if changing group fails clear the group permissions */
4766 if (fchown(fd, -1, st_old.st_gid) == -1 && perm > 0)
4767 perm &= ~070;
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004768 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00004769# endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004770 buf_setino(buf);
4771 }
4772 else if (!buf->b_dev_valid)
4773 /* Set the inode when creating a new file. */
4774 buf_setino(buf);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004775#endif
4776
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004777#ifdef UNIX
4778 if (made_writable)
4779 perm &= ~0200; /* reset 'w' bit for security reasons */
4780#endif
4781#ifdef HAVE_FCHMOD
4782 /* set permission of new file same as old file */
4783 if (perm >= 0)
4784 (void)mch_fsetperm(fd, perm);
4785#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004786 if (close(fd) != 0)
4787 {
4788 errmsg = (char_u *)_("E512: Close failed");
4789 end = 0;
4790 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004791
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004792#ifndef HAVE_FCHMOD
4793 /* set permission of new file same as old file */
4794 if (perm >= 0)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004795 (void)mch_setperm(wfname, perm);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004796#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004797#ifdef HAVE_ACL
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004798 /*
4799 * Probably need to set the ACL before changing the user (can't set the
4800 * ACL on a file the user doesn't own).
4801 * On Solaris, with ZFS and the aclmode property set to "discard" (the
4802 * default), chmod() discards all part of a file's ACL that don't
4803 * represent the mode of the file. It's non-trivial for us to discover
4804 * whether we're in that situation, so we simply always re-set the ACL.
4805 */
Bram Moolenaarda412772016-07-14 20:37:07 +02004806# ifndef HAVE_SOLARIS_ZFS_ACL
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004807 if (!backup_copy)
Bram Moolenaarda412772016-07-14 20:37:07 +02004808# endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004809 mch_set_acl(wfname, acl);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004810#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004811#ifdef FEAT_CRYPT
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004812 if (buf->b_cryptstate != NULL)
4813 {
4814 crypt_free_state(buf->b_cryptstate);
4815 buf->b_cryptstate = NULL;
4816 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004817#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004818
Bram Moolenaar071d4272004-06-13 20:20:40 +00004819#if defined(FEAT_MBYTE) && defined(FEAT_EVAL)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004820 if (wfname != fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004821 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004822 /*
4823 * The file was written to a temp file, now it needs to be
4824 * converted with 'charconvert' to (overwrite) the output file.
4825 */
4826 if (end != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004827 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004828 if (eval_charconvert(enc_utf8 ? (char_u *)"utf-8" : p_enc,
4829 fenc, wfname, fname) == FAIL)
4830 {
4831 write_info.bw_conv_error = TRUE;
4832 end = 0;
4833 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004834 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004835 mch_remove(wfname);
4836 vim_free(wfname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004837 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004838#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004839 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004840
4841 if (end == 0)
4842 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004843 /*
4844 * Error encountered.
4845 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004846 if (errmsg == NULL)
4847 {
4848#ifdef FEAT_MBYTE
4849 if (write_info.bw_conv_error)
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004850 {
4851 if (write_info.bw_conv_error_lnum == 0)
4852 errmsg = (char_u *)_("E513: write error, conversion failed (make 'fenc' empty to override)");
4853 else
4854 {
4855 errmsg_allocated = TRUE;
4856 errmsg = alloc(300);
4857 vim_snprintf((char *)errmsg, 300, _("E513: write error, conversion failed in line %ld (make 'fenc' empty to override)"),
4858 (long)write_info.bw_conv_error_lnum);
4859 }
4860 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004861 else
4862#endif
4863 if (got_int)
4864 errmsg = (char_u *)_(e_interr);
4865 else
4866 errmsg = (char_u *)_("E514: write error (file system full?)");
4867 }
4868
4869 /*
4870 * If we have a backup file, try to put it in place of the new file,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004871 * because the new file is probably corrupt. This avoids losing the
Bram Moolenaar071d4272004-06-13 20:20:40 +00004872 * original file when trying to make a backup when writing the file a
4873 * second time.
4874 * When "backup_copy" is set we need to copy the backup over the new
4875 * file. Otherwise rename the backup file.
4876 * If this is OK, don't give the extra warning message.
4877 */
4878 if (backup != NULL)
4879 {
4880 if (backup_copy)
4881 {
4882 /* This may take a while, if we were interrupted let the user
4883 * know we got the message. */
4884 if (got_int)
4885 {
4886 MSG(_(e_interr));
4887 out_flush();
4888 }
4889 if ((fd = mch_open((char *)backup, O_RDONLY | O_EXTRA, 0)) >= 0)
4890 {
4891 if ((write_info.bw_fd = mch_open((char *)fname,
Bram Moolenaar9be038d2005-03-08 22:34:32 +00004892 O_WRONLY | O_CREAT | O_TRUNC | O_EXTRA,
4893 perm & 0777)) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004894 {
4895 /* copy the file. */
4896 write_info.bw_buf = smallbuf;
4897#ifdef HAS_BW_FLAGS
4898 write_info.bw_flags = FIO_NOCONVERT;
4899#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004900 while ((write_info.bw_len = read_eintr(fd, smallbuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004901 SMBUFSIZE)) > 0)
4902 if (buf_write_bytes(&write_info) == FAIL)
4903 break;
4904
4905 if (close(write_info.bw_fd) >= 0
4906 && write_info.bw_len == 0)
4907 end = 1; /* success */
4908 }
4909 close(fd); /* ignore errors for closing read file */
4910 }
4911 }
4912 else
4913 {
4914 if (vim_rename(backup, fname) == 0)
4915 end = 1;
4916 }
4917 }
4918 goto fail;
4919 }
4920
4921 lnum -= start; /* compute number of written lines */
4922 --no_wait_return; /* may wait for return now */
4923
4924#if !(defined(UNIX) || defined(VMS))
4925 fname = sfname; /* use shortname now, for the messages */
4926#endif
4927 if (!filtering)
4928 {
4929 msg_add_fname(buf, fname); /* put fname in IObuff with quotes */
4930 c = FALSE;
4931#ifdef FEAT_MBYTE
4932 if (write_info.bw_conv_error)
4933 {
4934 STRCAT(IObuff, _(" CONVERSION ERROR"));
4935 c = TRUE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004936 if (write_info.bw_conv_error_lnum != 0)
Bram Moolenaara800b422010-06-27 01:15:55 +02004937 vim_snprintf_add((char *)IObuff, IOSIZE, _(" in line %ld;"),
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004938 (long)write_info.bw_conv_error_lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004939 }
4940 else if (notconverted)
4941 {
4942 STRCAT(IObuff, _("[NOT converted]"));
4943 c = TRUE;
4944 }
4945 else if (converted)
4946 {
4947 STRCAT(IObuff, _("[converted]"));
4948 c = TRUE;
4949 }
4950#endif
4951 if (device)
4952 {
4953 STRCAT(IObuff, _("[Device]"));
4954 c = TRUE;
4955 }
4956 else if (newfile)
4957 {
4958 STRCAT(IObuff, shortmess(SHM_NEW) ? _("[New]") : _("[New File]"));
4959 c = TRUE;
4960 }
4961 if (no_eol)
4962 {
4963 msg_add_eol();
4964 c = TRUE;
4965 }
4966 /* may add [unix/dos/mac] */
4967 if (msg_add_fileformat(fileformat))
4968 c = TRUE;
4969#ifdef FEAT_CRYPT
4970 if (wb_flags & FIO_ENCRYPTED)
4971 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004972 crypt_append_msg(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004973 c = TRUE;
4974 }
4975#endif
4976 msg_add_lines(c, (long)lnum, nchars); /* add line/char count */
4977 if (!shortmess(SHM_WRITE))
4978 {
4979 if (append)
4980 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended"));
4981 else
4982 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written"));
4983 }
4984
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00004985 set_keep_msg(msg_trunc_attr(IObuff, FALSE, 0), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004986 }
4987
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004988 /* When written everything correctly: reset 'modified'. Unless not
4989 * writing to the original file and '+' is not in 'cpoptions'. */
Bram Moolenaar292ad192005-12-11 21:29:51 +00004990 if (reset_changed && whole && !append
Bram Moolenaar071d4272004-06-13 20:20:40 +00004991#ifdef FEAT_MBYTE
4992 && !write_info.bw_conv_error
4993#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004994 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL)
4995 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004996 {
4997 unchanged(buf, TRUE);
Bram Moolenaar95c526e2017-02-25 14:59:34 +01004998 /* b:changedtick is always incremented in unchanged() but that
Bram Moolenaar086329d2014-10-31 19:51:36 +01004999 * should not trigger a TextChanged event. */
Bram Moolenaar5a093432018-02-10 18:15:19 +01005000 if (buf->b_last_changedtick + 1 == CHANGEDTICK(buf))
5001 buf->b_last_changedtick = CHANGEDTICK(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005002 u_unchanged(buf);
Bram Moolenaar730cde92010-06-27 05:18:54 +02005003 u_update_save_nr(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005004 }
5005
5006 /*
5007 * If written to the current file, update the timestamp of the swap file
5008 * and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
5009 */
5010 if (overwriting)
5011 {
5012 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00005013 if (append)
5014 buf->b_flags &= ~BF_NEW;
5015 else
5016 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005017 }
5018
5019 /*
5020 * If we kept a backup until now, and we are in patch mode, then we make
5021 * the backup file our 'original' file.
5022 */
5023 if (*p_pm && dobackup)
5024 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01005025 char *org = (char *)buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005026 fname, p_pm, FALSE);
5027
5028 if (backup != NULL)
5029 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02005030 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005031
5032 /*
5033 * If the original file does not exist yet
5034 * the current backup file becomes the original file
5035 */
5036 if (org == NULL)
5037 EMSG(_("E205: Patchmode: can't save original file"));
5038 else if (mch_stat(org, &st) < 0)
5039 {
5040 vim_rename(backup, (char_u *)org);
Bram Moolenaard23a8232018-02-10 18:45:26 +01005041 VIM_CLEAR(backup); /* don't delete the file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005042#ifdef UNIX
5043 set_file_time((char_u *)org, st_old.st_atime, st_old.st_mtime);
5044#endif
5045 }
5046 }
5047 /*
5048 * If there is no backup file, remember that a (new) file was
5049 * created.
5050 */
5051 else
5052 {
5053 int empty_fd;
5054
5055 if (org == NULL
Bram Moolenaara5792f52005-11-23 21:25:05 +00005056 || (empty_fd = mch_open(org,
5057 O_CREAT | O_EXTRA | O_EXCL | O_NOFOLLOW,
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00005058 perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005059 EMSG(_("E206: patchmode: can't touch empty original file"));
5060 else
5061 close(empty_fd);
5062 }
5063 if (org != NULL)
5064 {
5065 mch_setperm((char_u *)org, mch_getperm(fname) & 0777);
5066 vim_free(org);
5067 }
5068 }
5069
5070 /*
5071 * Remove the backup unless 'backup' option is set
5072 */
5073 if (!p_bk && backup != NULL && mch_remove(backup) != 0)
5074 EMSG(_("E207: Can't delete backup file"));
5075
5076#ifdef FEAT_SUN_WORKSHOP
5077 if (usingSunWorkShop)
5078 workshop_file_saved((char *) ffname);
5079#endif
5080
5081 goto nofail;
5082
5083 /*
5084 * Finish up. We get here either after failure or success.
5085 */
5086fail:
5087 --no_wait_return; /* may wait for return now */
5088nofail:
5089
5090 /* Done saving, we accept changed buffer warnings again */
5091 buf->b_saving = FALSE;
5092
5093 vim_free(backup);
5094 if (buffer != smallbuf)
5095 vim_free(buffer);
5096#ifdef FEAT_MBYTE
5097 vim_free(fenc_tofree);
5098 vim_free(write_info.bw_conv_buf);
5099# ifdef USE_ICONV
5100 if (write_info.bw_iconv_fd != (iconv_t)-1)
5101 {
5102 iconv_close(write_info.bw_iconv_fd);
5103 write_info.bw_iconv_fd = (iconv_t)-1;
5104 }
5105# endif
5106#endif
5107#ifdef HAVE_ACL
5108 mch_free_acl(acl);
5109#endif
5110
5111 if (errmsg != NULL)
5112 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005113 int numlen = errnum != NULL ? (int)STRLEN(errnum) : 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005114
Bram Moolenaar8820b482017-03-16 17:23:31 +01005115 attr = HL_ATTR(HLF_E); /* set highlight for error messages */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005116 msg_add_fname(buf,
5117#ifndef UNIX
5118 sfname
5119#else
5120 fname
5121#endif
5122 ); /* put file name in IObuff with quotes */
5123 if (STRLEN(IObuff) + STRLEN(errmsg) + numlen >= IOSIZE)
5124 IObuff[IOSIZE - STRLEN(errmsg) - numlen - 1] = NUL;
5125 /* If the error message has the form "is ...", put the error number in
5126 * front of the file name. */
5127 if (errnum != NULL)
5128 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00005129 STRMOVE(IObuff + numlen, IObuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005130 mch_memmove(IObuff, errnum, (size_t)numlen);
5131 }
5132 STRCAT(IObuff, errmsg);
5133 emsg(IObuff);
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005134 if (errmsg_allocated)
5135 vim_free(errmsg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005136
5137 retval = FAIL;
5138 if (end == 0)
5139 {
5140 MSG_PUTS_ATTR(_("\nWARNING: Original file may be lost or damaged\n"),
5141 attr | MSG_HIST);
5142 MSG_PUTS_ATTR(_("don't quit the editor until the file is successfully written!"),
5143 attr | MSG_HIST);
5144
5145 /* Update the timestamp to avoid an "overwrite changed file"
5146 * prompt when writing again. */
5147 if (mch_stat((char *)fname, &st_old) >= 0)
5148 {
5149 buf_store_time(buf, &st_old, fname);
5150 buf->b_mtime_read = buf->b_mtime;
5151 }
5152 }
5153 }
5154 msg_scroll = msg_save;
5155
Bram Moolenaar55debbe2010-05-23 23:34:36 +02005156#ifdef FEAT_PERSISTENT_UNDO
5157 /*
5158 * When writing the whole file and 'undofile' is set, also write the undo
5159 * file.
5160 */
5161 if (retval == OK && write_undo_file)
5162 {
5163 char_u hash[UNDO_HASH_SIZE];
5164
5165 sha256_finish(&sha_ctx, hash);
5166 u_write_undo(NULL, FALSE, buf, hash);
5167 }
5168#endif
5169
Bram Moolenaar071d4272004-06-13 20:20:40 +00005170#ifdef FEAT_EVAL
5171 if (!should_abort(retval))
5172#else
5173 if (!got_int)
5174#endif
5175 {
5176 aco_save_T aco;
5177
Bram Moolenaar68a33fc2012-04-25 16:50:48 +02005178 curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */
5179
Bram Moolenaar071d4272004-06-13 20:20:40 +00005180 /*
5181 * Apply POST autocommands.
5182 * Careful: The autocommands may call buf_write() recursively!
5183 */
5184 aucmd_prepbuf(&aco, buf);
5185
5186 if (append)
5187 apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname,
5188 FALSE, curbuf, eap);
5189 else if (filtering)
5190 apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname,
5191 FALSE, curbuf, eap);
5192 else if (reset_changed && whole)
5193 apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname,
5194 FALSE, curbuf, eap);
5195 else
5196 apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname,
5197 FALSE, curbuf, eap);
5198
5199 /* restore curwin/curbuf and a few other things */
5200 aucmd_restbuf(&aco);
5201
5202#ifdef FEAT_EVAL
5203 if (aborting()) /* autocmds may abort script processing */
5204 retval = FALSE;
5205#endif
5206 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005207
5208 got_int |= prev_got_int;
5209
Bram Moolenaar071d4272004-06-13 20:20:40 +00005210 return retval;
5211}
5212
5213/*
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005214 * Set the name of the current buffer. Use when the buffer doesn't have a
5215 * name and a ":r" or ":w" command with a file name is used.
5216 */
5217 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005218set_rw_fname(char_u *fname, char_u *sfname)
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005219{
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005220 buf_T *buf = curbuf;
5221
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005222 /* It's like the unnamed buffer is deleted.... */
5223 if (curbuf->b_p_bl)
5224 apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
5225 apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf);
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01005226#ifdef FEAT_EVAL
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005227 if (aborting()) /* autocmds may abort script processing */
5228 return FAIL;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01005229#endif
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005230 if (curbuf != buf)
5231 {
5232 /* We are in another buffer now, don't do the renaming. */
5233 EMSG(_(e_auchangedbuf));
5234 return FAIL;
5235 }
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005236
5237 if (setfname(curbuf, fname, sfname, FALSE) == OK)
5238 curbuf->b_flags |= BF_NOTEDITED;
5239
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005240 /* ....and a new named one is created */
5241 apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, curbuf);
5242 if (curbuf->b_p_bl)
5243 apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf);
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01005244#ifdef FEAT_EVAL
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005245 if (aborting()) /* autocmds may abort script processing */
5246 return FAIL;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01005247#endif
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005248
5249 /* Do filetype detection now if 'filetype' is empty. */
5250 if (*curbuf->b_p_ft == NUL)
5251 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005252 if (au_has_group((char_u *)"filetypedetect"))
Bram Moolenaar1610d052016-06-09 22:53:01 +02005253 (void)do_doautocmd((char_u *)"filetypedetect BufRead", FALSE, NULL);
Bram Moolenaara3227e22006-03-08 21:32:40 +00005254 do_modelines(0);
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005255 }
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005256
5257 return OK;
5258}
5259
5260/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00005261 * Put file name into IObuff with quotes.
5262 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005263 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005264msg_add_fname(buf_T *buf, char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005265{
5266 if (fname == NULL)
5267 fname = (char_u *)"-stdin-";
5268 home_replace(buf, fname, IObuff + 1, IOSIZE - 4, TRUE);
5269 IObuff[0] = '"';
5270 STRCAT(IObuff, "\" ");
5271}
5272
5273/*
5274 * Append message for text mode to IObuff.
5275 * Return TRUE if something appended.
5276 */
5277 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005278msg_add_fileformat(int eol_type)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005279{
5280#ifndef USE_CRNL
5281 if (eol_type == EOL_DOS)
5282 {
5283 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[dos]") : _("[dos format]"));
5284 return TRUE;
5285 }
5286#endif
5287#ifndef USE_CR
5288 if (eol_type == EOL_MAC)
5289 {
5290 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[mac]") : _("[mac format]"));
5291 return TRUE;
5292 }
5293#endif
5294#if defined(USE_CRNL) || defined(USE_CR)
5295 if (eol_type == EOL_UNIX)
5296 {
5297 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[unix]") : _("[unix format]"));
5298 return TRUE;
5299 }
5300#endif
5301 return FALSE;
5302}
5303
5304/*
5305 * Append line and character count to IObuff.
5306 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005307 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005308msg_add_lines(
5309 int insert_space,
5310 long lnum,
Bram Moolenaar8767f522016-07-01 17:17:39 +02005311 off_T nchars)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005312{
5313 char_u *p;
5314
5315 p = IObuff + STRLEN(IObuff);
5316
5317 if (insert_space)
5318 *p++ = ' ';
5319 if (shortmess(SHM_LINES))
Bram Moolenaarbde98102016-07-01 20:03:42 +02005320 vim_snprintf((char *)p, IOSIZE - (p - IObuff),
Bram Moolenaarea391762018-04-08 13:07:22 +02005321 "%ldL, %lldC", lnum, (long long)nchars);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005322 else
5323 {
5324 if (lnum == 1)
5325 STRCPY(p, _("1 line, "));
5326 else
5327 sprintf((char *)p, _("%ld lines, "), lnum);
5328 p += STRLEN(p);
5329 if (nchars == 1)
5330 STRCPY(p, _("1 character"));
5331 else
Bram Moolenaarbde98102016-07-01 20:03:42 +02005332 vim_snprintf((char *)p, IOSIZE - (p - IObuff),
Bram Moolenaarea391762018-04-08 13:07:22 +02005333 _("%lld characters"), (long long)nchars);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005334 }
5335}
5336
5337/*
5338 * Append message for missing line separator to IObuff.
5339 */
5340 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005341msg_add_eol(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005342{
5343 STRCAT(IObuff, shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]"));
5344}
5345
5346/*
5347 * Check modification time of file, before writing to it.
5348 * The size isn't checked, because using a tool like "gzip" takes care of
5349 * using the same timestamp but can't set the size.
5350 */
5351 static int
Bram Moolenaar8767f522016-07-01 17:17:39 +02005352check_mtime(buf_T *buf, stat_T *st)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005353{
5354 if (buf->b_mtime_read != 0
5355 && time_differs((long)st->st_mtime, buf->b_mtime_read))
5356 {
5357 msg_scroll = TRUE; /* don't overwrite messages here */
5358 msg_silent = 0; /* must give this prompt */
5359 /* don't use emsg() here, don't want to flush the buffers */
5360 MSG_ATTR(_("WARNING: The file has been changed since reading it!!!"),
Bram Moolenaar8820b482017-03-16 17:23:31 +01005361 HL_ATTR(HLF_E));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005362 if (ask_yesno((char_u *)_("Do you really want to write to it"),
5363 TRUE) == 'n')
5364 return FAIL;
5365 msg_scroll = FALSE; /* always overwrite the file message now */
5366 }
5367 return OK;
5368}
5369
5370 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005371time_differs(long t1, long t2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005372{
Bram Moolenaar48e330a2016-02-23 14:53:34 +01005373#if defined(__linux__) || defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005374 /* On a FAT filesystem, esp. under Linux, there are only 5 bits to store
5375 * the seconds. Since the roundoff is done when flushing the inode, the
5376 * time may change unexpectedly by one second!!! */
5377 return (t1 - t2 > 1 || t2 - t1 > 1);
5378#else
5379 return (t1 != t2);
5380#endif
5381}
5382
5383/*
5384 * Call write() to write a number of bytes to the file.
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005385 * Handles encryption and 'encoding' conversion.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005386 *
5387 * Return FAIL for failure, OK otherwise.
5388 */
5389 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005390buf_write_bytes(struct bw_info *ip)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005391{
5392 int wlen;
5393 char_u *buf = ip->bw_buf; /* data to write */
5394 int len = ip->bw_len; /* length of data */
5395#ifdef HAS_BW_FLAGS
5396 int flags = ip->bw_flags; /* extra flags */
5397#endif
5398
5399#ifdef FEAT_MBYTE
5400 /*
5401 * Skip conversion when writing the crypt magic number or the BOM.
5402 */
5403 if (!(flags & FIO_NOCONVERT))
5404 {
5405 char_u *p;
5406 unsigned c;
5407 int n;
5408
5409 if (flags & FIO_UTF8)
5410 {
5411 /*
5412 * Convert latin1 in the buffer to UTF-8 in the file.
5413 */
5414 p = ip->bw_conv_buf; /* translate to buffer */
5415 for (wlen = 0; wlen < len; ++wlen)
5416 p += utf_char2bytes(buf[wlen], p);
5417 buf = ip->bw_conv_buf;
5418 len = (int)(p - ip->bw_conv_buf);
5419 }
5420 else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1))
5421 {
5422 /*
5423 * Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
5424 * Latin1 chars in the file.
5425 */
5426 if (flags & FIO_LATIN1)
5427 p = buf; /* translate in-place (can only get shorter) */
5428 else
5429 p = ip->bw_conv_buf; /* translate to buffer */
5430 for (wlen = 0; wlen < len; wlen += n)
5431 {
5432 if (wlen == 0 && ip->bw_restlen != 0)
5433 {
5434 int l;
5435
5436 /* Use remainder of previous call. Append the start of
5437 * buf[] to get a full sequence. Might still be too
5438 * short! */
5439 l = CONV_RESTLEN - ip->bw_restlen;
5440 if (l > len)
5441 l = len;
5442 mch_memmove(ip->bw_rest + ip->bw_restlen, buf, (size_t)l);
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005443 n = utf_ptr2len_len(ip->bw_rest, ip->bw_restlen + l);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005444 if (n > ip->bw_restlen + len)
5445 {
5446 /* We have an incomplete byte sequence at the end to
5447 * be written. We can't convert it without the
5448 * remaining bytes. Keep them for the next call. */
5449 if (ip->bw_restlen + len > CONV_RESTLEN)
5450 return FAIL;
5451 ip->bw_restlen += len;
5452 break;
5453 }
5454 if (n > 1)
5455 c = utf_ptr2char(ip->bw_rest);
5456 else
5457 c = ip->bw_rest[0];
5458 if (n >= ip->bw_restlen)
5459 {
5460 n -= ip->bw_restlen;
5461 ip->bw_restlen = 0;
5462 }
5463 else
5464 {
5465 ip->bw_restlen -= n;
5466 mch_memmove(ip->bw_rest, ip->bw_rest + n,
5467 (size_t)ip->bw_restlen);
5468 n = 0;
5469 }
5470 }
5471 else
5472 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005473 n = utf_ptr2len_len(buf + wlen, len - wlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005474 if (n > len - wlen)
5475 {
5476 /* We have an incomplete byte sequence at the end to
5477 * be written. We can't convert it without the
5478 * remaining bytes. Keep them for the next call. */
5479 if (len - wlen > CONV_RESTLEN)
5480 return FAIL;
5481 ip->bw_restlen = len - wlen;
5482 mch_memmove(ip->bw_rest, buf + wlen,
5483 (size_t)ip->bw_restlen);
5484 break;
5485 }
5486 if (n > 1)
5487 c = utf_ptr2char(buf + wlen);
5488 else
5489 c = buf[wlen];
5490 }
5491
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005492 if (ucs2bytes(c, &p, flags) && !ip->bw_conv_error)
5493 {
5494 ip->bw_conv_error = TRUE;
5495 ip->bw_conv_error_lnum = ip->bw_start_lnum;
5496 }
5497 if (c == NL)
5498 ++ip->bw_start_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005499 }
5500 if (flags & FIO_LATIN1)
5501 len = (int)(p - buf);
5502 else
5503 {
5504 buf = ip->bw_conv_buf;
5505 len = (int)(p - ip->bw_conv_buf);
5506 }
5507 }
5508
5509# ifdef WIN3264
5510 else if (flags & FIO_CODEPAGE)
5511 {
5512 /*
5513 * Convert UTF-8 or codepage to UCS-2 and then to MS-Windows
5514 * codepage.
5515 */
5516 char_u *from;
5517 size_t fromlen;
5518 char_u *to;
5519 int u8c;
5520 BOOL bad = FALSE;
5521 int needed;
5522
5523 if (ip->bw_restlen > 0)
5524 {
5525 /* Need to concatenate the remainder of the previous call and
5526 * the bytes of the current call. Use the end of the
5527 * conversion buffer for this. */
5528 fromlen = len + ip->bw_restlen;
5529 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5530 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5531 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5532 }
5533 else
5534 {
5535 from = buf;
5536 fromlen = len;
5537 }
5538
5539 to = ip->bw_conv_buf;
5540 if (enc_utf8)
5541 {
5542 /* Convert from UTF-8 to UCS-2, to the start of the buffer.
5543 * The buffer has been allocated to be big enough. */
5544 while (fromlen > 0)
5545 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005546 n = (int)utf_ptr2len_len(from, (int)fromlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005547 if (n > (int)fromlen) /* incomplete byte sequence */
5548 break;
5549 u8c = utf_ptr2char(from);
5550 *to++ = (u8c & 0xff);
5551 *to++ = (u8c >> 8);
5552 fromlen -= n;
5553 from += n;
5554 }
5555
5556 /* Copy remainder to ip->bw_rest[] to be used for the next
5557 * call. */
5558 if (fromlen > CONV_RESTLEN)
5559 {
5560 /* weird overlong sequence */
5561 ip->bw_conv_error = TRUE;
5562 return FAIL;
5563 }
5564 mch_memmove(ip->bw_rest, from, fromlen);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005565 ip->bw_restlen = (int)fromlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005566 }
5567 else
5568 {
5569 /* Convert from enc_codepage to UCS-2, to the start of the
5570 * buffer. The buffer has been allocated to be big enough. */
5571 ip->bw_restlen = 0;
5572 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005573 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005574 NULL, 0);
5575 if (needed == 0)
5576 {
5577 /* When conversion fails there may be a trailing byte. */
5578 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005579 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen - 1,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005580 NULL, 0);
5581 if (needed == 0)
5582 {
5583 /* Conversion doesn't work. */
5584 ip->bw_conv_error = TRUE;
5585 return FAIL;
5586 }
5587 /* Save the trailing byte for the next call. */
5588 ip->bw_rest[0] = from[fromlen - 1];
5589 ip->bw_restlen = 1;
5590 }
5591 needed = MultiByteToWideChar(enc_codepage, MB_ERR_INVALID_CHARS,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005592 (LPCSTR)from, (int)(fromlen - ip->bw_restlen),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005593 (LPWSTR)to, needed);
5594 if (needed == 0)
5595 {
5596 /* Safety check: Conversion doesn't work. */
5597 ip->bw_conv_error = TRUE;
5598 return FAIL;
5599 }
5600 to += needed * 2;
5601 }
5602
5603 fromlen = to - ip->bw_conv_buf;
5604 buf = to;
5605# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5606 if (FIO_GET_CP(flags) == CP_UTF8)
5607 {
5608 /* Convert from UCS-2 to UTF-8, using the remainder of the
5609 * conversion buffer. Fails when out of space. */
5610 for (from = ip->bw_conv_buf; fromlen > 1; fromlen -= 2)
5611 {
5612 u8c = *from++;
5613 u8c += (*from++ << 8);
5614 to += utf_char2bytes(u8c, to);
5615 if (to + 6 >= ip->bw_conv_buf + ip->bw_conv_buflen)
5616 {
5617 ip->bw_conv_error = TRUE;
5618 return FAIL;
5619 }
5620 }
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005621 len = (int)(to - buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005622 }
5623 else
5624#endif
5625 {
5626 /* Convert from UCS-2 to the codepage, using the remainder of
5627 * the conversion buffer. If the conversion uses the default
5628 * character "0", the data doesn't fit in this encoding, so
5629 * fail. */
5630 len = WideCharToMultiByte(FIO_GET_CP(flags), 0,
5631 (LPCWSTR)ip->bw_conv_buf, (int)fromlen / sizeof(WCHAR),
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005632 (LPSTR)to, (int)(ip->bw_conv_buflen - fromlen), 0,
5633 &bad);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005634 if (bad)
5635 {
5636 ip->bw_conv_error = TRUE;
5637 return FAIL;
5638 }
5639 }
5640 }
5641# endif
5642
Bram Moolenaar56718732006-03-15 22:53:57 +00005643# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00005644 else if (flags & FIO_MACROMAN)
5645 {
5646 /*
5647 * Convert UTF-8 or latin1 to Apple MacRoman.
5648 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005649 char_u *from;
5650 size_t fromlen;
5651
5652 if (ip->bw_restlen > 0)
5653 {
5654 /* Need to concatenate the remainder of the previous call and
5655 * the bytes of the current call. Use the end of the
5656 * conversion buffer for this. */
5657 fromlen = len + ip->bw_restlen;
5658 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5659 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5660 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5661 }
5662 else
5663 {
5664 from = buf;
5665 fromlen = len;
5666 }
5667
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00005668 if (enc2macroman(from, fromlen,
5669 ip->bw_conv_buf, &len, ip->bw_conv_buflen,
5670 ip->bw_rest, &ip->bw_restlen) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005671 {
5672 ip->bw_conv_error = TRUE;
5673 return FAIL;
5674 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005675 buf = ip->bw_conv_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005676 }
5677# endif
5678
5679# ifdef USE_ICONV
5680 if (ip->bw_iconv_fd != (iconv_t)-1)
5681 {
5682 const char *from;
5683 size_t fromlen;
5684 char *to;
5685 size_t tolen;
5686
5687 /* Convert with iconv(). */
5688 if (ip->bw_restlen > 0)
5689 {
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005690 char *fp;
5691
Bram Moolenaar071d4272004-06-13 20:20:40 +00005692 /* Need to concatenate the remainder of the previous call and
5693 * the bytes of the current call. Use the end of the
5694 * conversion buffer for this. */
5695 fromlen = len + ip->bw_restlen;
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005696 fp = (char *)ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5697 mch_memmove(fp, ip->bw_rest, (size_t)ip->bw_restlen);
5698 mch_memmove(fp + ip->bw_restlen, buf, (size_t)len);
5699 from = fp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005700 tolen = ip->bw_conv_buflen - fromlen;
5701 }
5702 else
5703 {
5704 from = (const char *)buf;
5705 fromlen = len;
5706 tolen = ip->bw_conv_buflen;
5707 }
5708 to = (char *)ip->bw_conv_buf;
5709
5710 if (ip->bw_first)
5711 {
5712 size_t save_len = tolen;
5713
5714 /* output the initial shift state sequence */
5715 (void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen);
5716
5717 /* There is a bug in iconv() on Linux (which appears to be
5718 * wide-spread) which sets "to" to NULL and messes up "tolen".
5719 */
5720 if (to == NULL)
5721 {
5722 to = (char *)ip->bw_conv_buf;
5723 tolen = save_len;
5724 }
5725 ip->bw_first = FALSE;
5726 }
5727
5728 /*
5729 * If iconv() has an error or there is not enough room, fail.
5730 */
5731 if ((iconv(ip->bw_iconv_fd, (void *)&from, &fromlen, &to, &tolen)
5732 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
5733 || fromlen > CONV_RESTLEN)
5734 {
5735 ip->bw_conv_error = TRUE;
5736 return FAIL;
5737 }
5738
5739 /* copy remainder to ip->bw_rest[] to be used for the next call. */
5740 if (fromlen > 0)
5741 mch_memmove(ip->bw_rest, (void *)from, fromlen);
5742 ip->bw_restlen = (int)fromlen;
5743
5744 buf = ip->bw_conv_buf;
5745 len = (int)((char_u *)to - ip->bw_conv_buf);
5746 }
5747# endif
5748 }
5749#endif /* FEAT_MBYTE */
5750
Bram Moolenaare6bf6552017-06-27 22:11:51 +02005751 if (ip->bw_fd < 0)
5752 /* Only checking conversion, which is OK if we get here. */
5753 return OK;
5754
Bram Moolenaar071d4272004-06-13 20:20:40 +00005755#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02005756 if (flags & FIO_ENCRYPTED)
5757 {
5758 /* Encrypt the data. Do it in-place if possible, otherwise use an
5759 * allocated buffer. */
5760 if (crypt_works_inplace(ip->bw_buffer->b_cryptstate))
5761 {
5762 crypt_encode_inplace(ip->bw_buffer->b_cryptstate, buf, len);
5763 }
5764 else
5765 {
5766 char_u *outbuf;
5767
5768 len = crypt_encode_alloc(curbuf->b_cryptstate, buf, len, &outbuf);
5769 if (len == 0)
5770 return OK; /* Crypt layer is buffering, will flush later. */
5771 wlen = write_eintr(ip->bw_fd, outbuf, len);
5772 vim_free(outbuf);
5773 return (wlen < len) ? FAIL : OK;
5774 }
5775 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005776#endif
5777
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005778 wlen = write_eintr(ip->bw_fd, buf, len);
5779 return (wlen < len) ? FAIL : OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005780}
5781
5782#ifdef FEAT_MBYTE
5783/*
5784 * Convert a Unicode character to bytes.
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005785 * Return TRUE for an error, FALSE when it's OK.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005786 */
5787 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005788ucs2bytes(
5789 unsigned c, /* in: character */
5790 char_u **pp, /* in/out: pointer to result */
5791 int flags) /* FIO_ flags */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005792{
5793 char_u *p = *pp;
5794 int error = FALSE;
5795 int cc;
5796
5797
5798 if (flags & FIO_UCS4)
5799 {
5800 if (flags & FIO_ENDIAN_L)
5801 {
5802 *p++ = c;
5803 *p++ = (c >> 8);
5804 *p++ = (c >> 16);
5805 *p++ = (c >> 24);
5806 }
5807 else
5808 {
5809 *p++ = (c >> 24);
5810 *p++ = (c >> 16);
5811 *p++ = (c >> 8);
5812 *p++ = c;
5813 }
5814 }
5815 else if (flags & (FIO_UCS2 | FIO_UTF16))
5816 {
5817 if (c >= 0x10000)
5818 {
5819 if (flags & FIO_UTF16)
5820 {
5821 /* Make two words, ten bits of the character in each. First
5822 * word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff */
5823 c -= 0x10000;
5824 if (c >= 0x100000)
5825 error = TRUE;
5826 cc = ((c >> 10) & 0x3ff) + 0xd800;
5827 if (flags & FIO_ENDIAN_L)
5828 {
5829 *p++ = cc;
5830 *p++ = ((unsigned)cc >> 8);
5831 }
5832 else
5833 {
5834 *p++ = ((unsigned)cc >> 8);
5835 *p++ = cc;
5836 }
5837 c = (c & 0x3ff) + 0xdc00;
5838 }
5839 else
5840 error = TRUE;
5841 }
5842 if (flags & FIO_ENDIAN_L)
5843 {
5844 *p++ = c;
5845 *p++ = (c >> 8);
5846 }
5847 else
5848 {
5849 *p++ = (c >> 8);
5850 *p++ = c;
5851 }
5852 }
5853 else /* Latin1 */
5854 {
5855 if (c >= 0x100)
5856 {
5857 error = TRUE;
5858 *p++ = 0xBF;
5859 }
5860 else
5861 *p++ = c;
5862 }
5863
5864 *pp = p;
5865 return error;
5866}
5867
5868/*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005869 * Return TRUE if file encoding "fenc" requires conversion from or to
5870 * 'encoding'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005871 */
5872 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005873need_conversion(char_u *fenc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005874{
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005875 int same_encoding;
5876 int enc_flags;
5877 int fenc_flags;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005878
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005879 if (*fenc == NUL || STRCMP(p_enc, fenc) == 0)
Bram Moolenaar442b4222010-05-24 21:34:22 +02005880 {
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005881 same_encoding = TRUE;
Bram Moolenaar442b4222010-05-24 21:34:22 +02005882 fenc_flags = 0;
5883 }
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005884 else
5885 {
5886 /* Ignore difference between "ansi" and "latin1", "ucs-4" and
5887 * "ucs-4be", etc. */
5888 enc_flags = get_fio_flags(p_enc);
5889 fenc_flags = get_fio_flags(fenc);
5890 same_encoding = (enc_flags != 0 && fenc_flags == enc_flags);
5891 }
5892 if (same_encoding)
5893 {
5894 /* Specified encoding matches with 'encoding'. This requires
5895 * conversion when 'encoding' is Unicode but not UTF-8. */
5896 return enc_unicode != 0;
5897 }
5898
5899 /* Encodings differ. However, conversion is not needed when 'enc' is any
5900 * Unicode encoding and the file is UTF-8. */
5901 return !(enc_utf8 && fenc_flags == FIO_UTF8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005902}
5903
5904/*
5905 * Check "ptr" for a unicode encoding and return the FIO_ flags needed for the
5906 * internal conversion.
5907 * if "ptr" is an empty string, use 'encoding'.
5908 */
5909 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005910get_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005911{
5912 int prop;
5913
5914 if (*ptr == NUL)
5915 ptr = p_enc;
5916
5917 prop = enc_canon_props(ptr);
5918 if (prop & ENC_UNICODE)
5919 {
5920 if (prop & ENC_2BYTE)
5921 {
5922 if (prop & ENC_ENDIAN_L)
5923 return FIO_UCS2 | FIO_ENDIAN_L;
5924 return FIO_UCS2;
5925 }
5926 if (prop & ENC_4BYTE)
5927 {
5928 if (prop & ENC_ENDIAN_L)
5929 return FIO_UCS4 | FIO_ENDIAN_L;
5930 return FIO_UCS4;
5931 }
5932 if (prop & ENC_2WORD)
5933 {
5934 if (prop & ENC_ENDIAN_L)
5935 return FIO_UTF16 | FIO_ENDIAN_L;
5936 return FIO_UTF16;
5937 }
5938 return FIO_UTF8;
5939 }
5940 if (prop & ENC_LATIN1)
5941 return FIO_LATIN1;
5942 /* must be ENC_DBCS, requires iconv() */
5943 return 0;
5944}
5945
5946#ifdef WIN3264
5947/*
5948 * Check "ptr" for a MS-Windows codepage name and return the FIO_ flags needed
5949 * for the conversion MS-Windows can do for us. Also accept "utf-8".
5950 * Used for conversion between 'encoding' and 'fileencoding'.
5951 */
5952 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005953get_win_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005954{
5955 int cp;
5956
5957 /* Cannot do this when 'encoding' is not utf-8 and not a codepage. */
5958 if (!enc_utf8 && enc_codepage <= 0)
5959 return 0;
5960
5961 cp = encname2codepage(ptr);
5962 if (cp == 0)
5963 {
5964# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5965 if (STRCMP(ptr, "utf-8") == 0)
5966 cp = CP_UTF8;
5967 else
5968# endif
5969 return 0;
5970 }
5971 return FIO_PUT_CP(cp) | FIO_CODEPAGE;
5972}
5973#endif
5974
Bram Moolenaard0573012017-10-28 21:11:06 +02005975#ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00005976/*
5977 * Check "ptr" for a Carbon supported encoding and return the FIO_ flags
5978 * needed for the internal conversion to/from utf-8 or latin1.
5979 */
5980 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005981get_mac_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005982{
5983 if ((enc_utf8 || STRCMP(p_enc, "latin1") == 0)
5984 && (enc_canon_props(ptr) & ENC_MACROMAN))
5985 return FIO_MACROMAN;
5986 return 0;
5987}
5988#endif
5989
5990/*
5991 * Check for a Unicode BOM (Byte Order Mark) at the start of p[size].
5992 * "size" must be at least 2.
5993 * Return the name of the encoding and set "*lenp" to the length.
5994 * Returns NULL when no BOM found.
5995 */
5996 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005997check_for_bom(
5998 char_u *p,
5999 long size,
6000 int *lenp,
6001 int flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006002{
6003 char *name = NULL;
6004 int len = 2;
6005
6006 if (p[0] == 0xef && p[1] == 0xbb && size >= 3 && p[2] == 0xbf
Bram Moolenaaree0f5a62008-07-24 20:09:16 +00006007 && (flags == FIO_ALL || flags == FIO_UTF8 || flags == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006008 {
6009 name = "utf-8"; /* EF BB BF */
6010 len = 3;
6011 }
6012 else if (p[0] == 0xff && p[1] == 0xfe)
6013 {
6014 if (size >= 4 && p[2] == 0 && p[3] == 0
6015 && (flags == FIO_ALL || flags == (FIO_UCS4 | FIO_ENDIAN_L)))
6016 {
6017 name = "ucs-4le"; /* FF FE 00 00 */
6018 len = 4;
6019 }
Bram Moolenaar223a1892008-11-11 20:57:11 +00006020 else if (flags == (FIO_UCS2 | FIO_ENDIAN_L))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006021 name = "ucs-2le"; /* FF FE */
Bram Moolenaar223a1892008-11-11 20:57:11 +00006022 else if (flags == FIO_ALL || flags == (FIO_UTF16 | FIO_ENDIAN_L))
6023 /* utf-16le is preferred, it also works for ucs-2le text */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006024 name = "utf-16le"; /* FF FE */
6025 }
6026 else if (p[0] == 0xfe && p[1] == 0xff
6027 && (flags == FIO_ALL || flags == FIO_UCS2 || flags == FIO_UTF16))
6028 {
Bram Moolenaarffd82c52008-02-20 17:15:26 +00006029 /* Default to utf-16, it works also for ucs-2 text. */
6030 if (flags == FIO_UCS2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006031 name = "ucs-2"; /* FE FF */
Bram Moolenaarffd82c52008-02-20 17:15:26 +00006032 else
6033 name = "utf-16"; /* FE FF */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006034 }
6035 else if (size >= 4 && p[0] == 0 && p[1] == 0 && p[2] == 0xfe
6036 && p[3] == 0xff && (flags == FIO_ALL || flags == FIO_UCS4))
6037 {
6038 name = "ucs-4"; /* 00 00 FE FF */
6039 len = 4;
6040 }
6041
6042 *lenp = len;
6043 return (char_u *)name;
6044}
6045
6046/*
6047 * Generate a BOM in "buf[4]" for encoding "name".
6048 * Return the length of the BOM (zero when no BOM).
6049 */
6050 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006051make_bom(char_u *buf, char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006052{
6053 int flags;
6054 char_u *p;
6055
6056 flags = get_fio_flags(name);
6057
6058 /* Can't put a BOM in a non-Unicode file. */
6059 if (flags == FIO_LATIN1 || flags == 0)
6060 return 0;
6061
6062 if (flags == FIO_UTF8) /* UTF-8 */
6063 {
6064 buf[0] = 0xef;
6065 buf[1] = 0xbb;
6066 buf[2] = 0xbf;
6067 return 3;
6068 }
6069 p = buf;
6070 (void)ucs2bytes(0xfeff, &p, flags);
6071 return (int)(p - buf);
6072}
6073#endif
6074
6075/*
6076 * Try to find a shortname by comparing the fullname with the current
6077 * directory.
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006078 * Returns "full_path" or pointer into "full_path" if shortened.
6079 */
6080 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006081shorten_fname1(char_u *full_path)
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006082{
Bram Moolenaard9462e32011-04-11 21:35:11 +02006083 char_u *dirname;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006084 char_u *p = full_path;
6085
Bram Moolenaard9462e32011-04-11 21:35:11 +02006086 dirname = alloc(MAXPATHL);
6087 if (dirname == NULL)
6088 return full_path;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006089 if (mch_dirname(dirname, MAXPATHL) == OK)
6090 {
6091 p = shorten_fname(full_path, dirname);
6092 if (p == NULL || *p == NUL)
6093 p = full_path;
6094 }
Bram Moolenaard9462e32011-04-11 21:35:11 +02006095 vim_free(dirname);
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006096 return p;
6097}
6098
6099/*
6100 * Try to find a shortname by comparing the fullname with the current
6101 * directory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006102 * Returns NULL if not shorter name possible, pointer into "full_path"
6103 * otherwise.
6104 */
6105 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006106shorten_fname(char_u *full_path, char_u *dir_name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006107{
6108 int len;
6109 char_u *p;
6110
6111 if (full_path == NULL)
6112 return NULL;
6113 len = (int)STRLEN(dir_name);
6114 if (fnamencmp(dir_name, full_path, len) == 0)
6115 {
6116 p = full_path + len;
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006117#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006118 /*
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006119 * MSWIN: when a file is in the root directory, dir_name will end in a
Bram Moolenaar071d4272004-06-13 20:20:40 +00006120 * slash, since C: by itself does not define a specific dir. In this
6121 * case p may already be correct. <negri>
6122 */
6123 if (!((len > 2) && (*(p - 2) == ':')))
6124#endif
6125 {
6126 if (vim_ispathsep(*p))
6127 ++p;
6128#ifndef VMS /* the path separator is always part of the path */
6129 else
6130 p = NULL;
6131#endif
6132 }
6133 }
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006134#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006135 /*
6136 * When using a file in the current drive, remove the drive name:
6137 * "A:\dir\file" -> "\dir\file". This helps when moving a session file on
6138 * a floppy from "A:\dir" to "B:\dir".
6139 */
6140 else if (len > 3
6141 && TOUPPER_LOC(full_path[0]) == TOUPPER_LOC(dir_name[0])
6142 && full_path[1] == ':'
6143 && vim_ispathsep(full_path[2]))
6144 p = full_path + 2;
6145#endif
6146 else
6147 p = NULL;
6148 return p;
6149}
6150
6151/*
6152 * Shorten filenames for all buffers.
6153 * When "force" is TRUE: Use full path from now on for files currently being
6154 * edited, both for file name and swap file name. Try to shorten the file
6155 * names a bit, if safe to do so.
6156 * When "force" is FALSE: Only try to shorten absolute file names.
6157 * For buffers that have buftype "nofile" or "scratch": never change the file
6158 * name.
6159 */
6160 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006161shorten_fnames(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006162{
6163 char_u dirname[MAXPATHL];
6164 buf_T *buf;
6165 char_u *p;
6166
6167 mch_dirname(dirname, MAXPATHL);
Bram Moolenaar29323592016-07-24 22:04:11 +02006168 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006169 {
6170 if (buf->b_fname != NULL
6171#ifdef FEAT_QUICKFIX
6172 && !bt_nofile(buf)
6173#endif
6174 && !path_with_url(buf->b_fname)
6175 && (force
6176 || buf->b_sfname == NULL
6177 || mch_isFullName(buf->b_sfname)))
6178 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01006179 VIM_CLEAR(buf->b_sfname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006180 p = shorten_fname(buf->b_ffname, dirname);
6181 if (p != NULL)
6182 {
6183 buf->b_sfname = vim_strsave(p);
6184 buf->b_fname = buf->b_sfname;
6185 }
6186 if (p == NULL || buf->b_fname == NULL)
6187 buf->b_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006188 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00006189
6190 /* Always make the swap file name a full path, a "nofile" buffer may
6191 * also have a swap file. */
6192 mf_fullname(buf->b_ml.ml_mfp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006193 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006194 status_redraw_all();
Bram Moolenaar49d7bf12006-02-17 21:45:41 +00006195 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006196}
6197
6198#if (defined(FEAT_DND) && defined(FEAT_GUI_GTK)) \
6199 || defined(FEAT_GUI_MSWIN) \
6200 || defined(FEAT_GUI_MAC) \
6201 || defined(PROTO)
6202/*
6203 * Shorten all filenames in "fnames[count]" by current directory.
6204 */
6205 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006206shorten_filenames(char_u **fnames, int count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006207{
6208 int i;
6209 char_u dirname[MAXPATHL];
6210 char_u *p;
6211
6212 if (fnames == NULL || count < 1)
6213 return;
6214 mch_dirname(dirname, sizeof(dirname));
6215 for (i = 0; i < count; ++i)
6216 {
6217 if ((p = shorten_fname(fnames[i], dirname)) != NULL)
6218 {
6219 /* shorten_fname() returns pointer in given "fnames[i]". If free
6220 * "fnames[i]" first, "p" becomes invalid. So we need to copy
6221 * "p" first then free fnames[i]. */
6222 p = vim_strsave(p);
6223 vim_free(fnames[i]);
6224 fnames[i] = p;
6225 }
6226 }
6227}
6228#endif
6229
6230/*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006231 * add extension to file name - change path/fo.o.h to path/fo.o.h.ext or
Bram Moolenaar071d4272004-06-13 20:20:40 +00006232 * fo_o_h.ext for MSDOS or when shortname option set.
6233 *
6234 * Assumed that fname is a valid name found in the filesystem we assure that
6235 * the return value is a different name and ends in 'ext'.
6236 * "ext" MUST be at most 4 characters long if it starts with a dot, 3
6237 * characters otherwise.
6238 * Space for the returned name is allocated, must be freed later.
6239 * Returns NULL when out of memory.
6240 */
6241 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006242modname(
6243 char_u *fname,
6244 char_u *ext,
6245 int prepend_dot) /* may prepend a '.' to file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006246{
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006247 return buf_modname((curbuf->b_p_sn || curbuf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00006248 fname, ext, prepend_dot);
6249}
6250
6251 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006252buf_modname(
6253 int shortname, /* use 8.3 file name */
6254 char_u *fname,
6255 char_u *ext,
6256 int prepend_dot) /* may prepend a '.' to file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006257{
6258 char_u *retval;
6259 char_u *s;
6260 char_u *e;
6261 char_u *ptr;
6262 int fnamelen, extlen;
6263
6264 extlen = (int)STRLEN(ext);
6265
6266 /*
6267 * If there is no file name we must get the name of the current directory
6268 * (we need the full path in case :cd is used).
6269 */
6270 if (fname == NULL || *fname == NUL)
6271 {
6272 retval = alloc((unsigned)(MAXPATHL + extlen + 3));
6273 if (retval == NULL)
6274 return NULL;
6275 if (mch_dirname(retval, MAXPATHL) == FAIL ||
6276 (fnamelen = (int)STRLEN(retval)) == 0)
6277 {
6278 vim_free(retval);
6279 return NULL;
6280 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006281 if (!after_pathsep(retval, retval + fnamelen))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006282 {
6283 retval[fnamelen++] = PATHSEP;
6284 retval[fnamelen] = NUL;
6285 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006286 prepend_dot = FALSE; /* nothing to prepend a dot to */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006287 }
6288 else
6289 {
6290 fnamelen = (int)STRLEN(fname);
6291 retval = alloc((unsigned)(fnamelen + extlen + 3));
6292 if (retval == NULL)
6293 return NULL;
6294 STRCPY(retval, fname);
6295#ifdef VMS
6296 vms_remove_version(retval); /* we do not need versions here */
6297#endif
6298 }
6299
6300 /*
6301 * search backwards until we hit a '/', '\' or ':' replacing all '.'
6302 * by '_' for MSDOS or when shortname option set and ext starts with a dot.
6303 * Then truncate what is after the '/', '\' or ':' to 8 characters for
6304 * MSDOS and 26 characters for AMIGA, a lot more for UNIX.
6305 */
Bram Moolenaar91acfff2017-03-12 19:22:36 +01006306 for (ptr = retval + fnamelen; ptr > retval; MB_PTR_BACK(retval, ptr))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006307 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006308 if (*ext == '.'
Bram Moolenaare60acc12011-05-10 16:41:25 +02006309#ifdef USE_LONG_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00006310 && (!USE_LONG_FNAME || shortname)
Bram Moolenaare60acc12011-05-10 16:41:25 +02006311#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006312 && shortname
Bram Moolenaare60acc12011-05-10 16:41:25 +02006313#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006314 )
6315 if (*ptr == '.') /* replace '.' by '_' */
6316 *ptr = '_';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006317 if (vim_ispathsep(*ptr))
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006318 {
6319 ++ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006320 break;
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006321 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006322 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006323
6324 /* the file name has at most BASENAMELEN characters. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006325 if (STRLEN(ptr) > (unsigned)BASENAMELEN)
6326 ptr[BASENAMELEN] = '\0';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006327
6328 s = ptr + STRLEN(ptr);
6329
6330 /*
6331 * For 8.3 file names we may have to reduce the length.
6332 */
6333#ifdef USE_LONG_FNAME
6334 if (!USE_LONG_FNAME || shortname)
6335#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006336 if (shortname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006337#endif
6338 {
6339 /*
6340 * If there is no file name, or the file name ends in '/', and the
6341 * extension starts with '.', put a '_' before the dot, because just
6342 * ".ext" is invalid.
6343 */
6344 if (fname == NULL || *fname == NUL
6345 || vim_ispathsep(fname[STRLEN(fname) - 1]))
6346 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006347 if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006348 *s++ = '_';
6349 }
6350 /*
6351 * If the extension starts with '.', truncate the base name at 8
6352 * characters
6353 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006354 else if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006355 {
Bram Moolenaar78a15312009-05-15 19:33:18 +00006356 if ((size_t)(s - ptr) > (size_t)8)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006357 {
6358 s = ptr + 8;
6359 *s = '\0';
6360 }
6361 }
6362 /*
6363 * If the extension doesn't start with '.', and the file name
6364 * doesn't have an extension yet, append a '.'
6365 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006366 else if ((e = vim_strchr(ptr, '.')) == NULL)
6367 *s++ = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006368 /*
6369 * If the extension doesn't start with '.', and there already is an
Bram Moolenaar7263a772007-05-10 17:35:54 +00006370 * extension, it may need to be truncated
Bram Moolenaar071d4272004-06-13 20:20:40 +00006371 */
6372 else if ((int)STRLEN(e) + extlen > 4)
6373 s = e + 4 - extlen;
6374 }
Bram Moolenaare7fedb62015-12-31 19:07:19 +01006375#if defined(USE_LONG_FNAME) || defined(WIN3264)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006376 /*
6377 * If there is no file name, and the extension starts with '.', put a
6378 * '_' before the dot, because just ".ext" may be invalid if it's on a
6379 * FAT partition, and on HPFS it doesn't matter.
6380 */
6381 else if ((fname == NULL || *fname == NUL) && *ext == '.')
6382 *s++ = '_';
6383#endif
6384
6385 /*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006386 * Append the extension.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006387 * ext can start with '.' and cannot exceed 3 more characters.
6388 */
6389 STRCPY(s, ext);
6390
Bram Moolenaar071d4272004-06-13 20:20:40 +00006391 /*
6392 * Prepend the dot.
6393 */
Bram Moolenaare60acc12011-05-10 16:41:25 +02006394 if (prepend_dot && !shortname && *(e = gettail(retval)) != '.'
Bram Moolenaar071d4272004-06-13 20:20:40 +00006395#ifdef USE_LONG_FNAME
6396 && USE_LONG_FNAME
6397#endif
6398 )
6399 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006400 STRMOVE(e + 1, e);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006401 *e = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006402 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006403
6404 /*
6405 * Check that, after appending the extension, the file name is really
6406 * different.
6407 */
6408 if (fname != NULL && STRCMP(fname, retval) == 0)
6409 {
6410 /* we search for a character that can be replaced by '_' */
6411 while (--s >= ptr)
6412 {
6413 if (*s != '_')
6414 {
6415 *s = '_';
6416 break;
6417 }
6418 }
6419 if (s < ptr) /* fname was "________.<ext>", how tricky! */
6420 *ptr = 'v';
6421 }
6422 return retval;
6423}
6424
6425/*
6426 * Like fgets(), but if the file line is too long, it is truncated and the
6427 * rest of the line is thrown away. Returns TRUE for end-of-file.
Bram Moolenaar7e1652c2017-12-16 18:27:02 +01006428 * If the line is truncated then buf[size - 2] will not be NUL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006429 */
6430 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006431vim_fgets(char_u *buf, int size, FILE *fp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006432{
6433 char *eof;
6434#define FGETS_SIZE 200
6435 char tbuf[FGETS_SIZE];
6436
6437 buf[size - 2] = NUL;
6438#ifdef USE_CR
6439 eof = fgets_cr((char *)buf, size, fp);
6440#else
6441 eof = fgets((char *)buf, size, fp);
6442#endif
6443 if (buf[size - 2] != NUL && buf[size - 2] != '\n')
6444 {
6445 buf[size - 1] = NUL; /* Truncate the line */
6446
6447 /* Now throw away the rest of the line: */
6448 do
6449 {
6450 tbuf[FGETS_SIZE - 2] = NUL;
6451#ifdef USE_CR
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006452 ignoredp = fgets_cr((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006453#else
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006454 ignoredp = fgets((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006455#endif
6456 } while (tbuf[FGETS_SIZE - 2] != NUL && tbuf[FGETS_SIZE - 2] != '\n');
6457 }
6458 return (eof == NULL);
6459}
6460
6461#if defined(USE_CR) || defined(PROTO)
6462/*
6463 * Like vim_fgets(), but accept any line terminator: CR, CR-LF or LF.
6464 * Returns TRUE for end-of-file.
6465 * Only used for the Mac, because it's much slower than vim_fgets().
6466 */
6467 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006468tag_fgets(char_u *buf, int size, FILE *fp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006469{
6470 int i = 0;
6471 int c;
6472 int eof = FALSE;
6473
6474 for (;;)
6475 {
6476 c = fgetc(fp);
6477 if (c == EOF)
6478 {
6479 eof = TRUE;
6480 break;
6481 }
6482 if (c == '\r')
6483 {
6484 /* Always store a NL for end-of-line. */
6485 if (i < size - 1)
6486 buf[i++] = '\n';
6487 c = fgetc(fp);
6488 if (c != '\n') /* Macintosh format: single CR. */
6489 ungetc(c, fp);
6490 break;
6491 }
6492 if (i < size - 1)
6493 buf[i++] = c;
6494 if (c == '\n')
6495 break;
6496 }
6497 buf[i] = NUL;
6498 return eof;
6499}
6500#endif
6501
6502/*
6503 * rename() only works if both files are on the same file system, this
6504 * function will (attempts to?) copy the file across if rename fails -- webb
6505 * Return -1 for failure, 0 for success.
6506 */
6507 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006508vim_rename(char_u *from, char_u *to)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006509{
6510 int fd_in;
6511 int fd_out;
6512 int n;
6513 char *errmsg = NULL;
6514 char *buffer;
6515#ifdef AMIGA
6516 BPTR flock;
6517#endif
Bram Moolenaar8767f522016-07-01 17:17:39 +02006518 stat_T st;
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006519 long perm;
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006520#ifdef HAVE_ACL
6521 vim_acl_T acl; /* ACL from original file */
6522#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006523 int use_tmp_file = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006524
6525 /*
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006526 * When the names are identical, there is nothing to do. When they refer
6527 * to the same file (ignoring case and slash/backslash differences) but
6528 * the file name differs we need to go through a temp file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006529 */
6530 if (fnamecmp(from, to) == 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006531 {
Bram Moolenaar71afbfe2013-03-19 16:49:16 +01006532 if (p_fic && STRCMP(gettail(from), gettail(to)) != 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006533 use_tmp_file = TRUE;
6534 else
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006535 return 0;
6536 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006537
6538 /*
6539 * Fail if the "from" file doesn't exist. Avoids that "to" is deleted.
6540 */
6541 if (mch_stat((char *)from, &st) < 0)
6542 return -1;
6543
Bram Moolenaar3576da72008-12-30 15:15:57 +00006544#ifdef UNIX
6545 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02006546 stat_T st_to;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006547
6548 /* It's possible for the source and destination to be the same file.
6549 * This happens when "from" and "to" differ in case and are on a FAT32
6550 * filesystem. In that case go through a temp file name. */
6551 if (mch_stat((char *)to, &st_to) >= 0
6552 && st.st_dev == st_to.st_dev
6553 && st.st_ino == st_to.st_ino)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006554 use_tmp_file = TRUE;
6555 }
6556#endif
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02006557#ifdef WIN3264
6558 {
6559 BY_HANDLE_FILE_INFORMATION info1, info2;
6560
6561 /* It's possible for the source and destination to be the same file.
6562 * In that case go through a temp file name. This makes rename("foo",
6563 * "./foo") a no-op (in a complicated way). */
6564 if (win32_fileinfo(from, &info1) == FILEINFO_OK
6565 && win32_fileinfo(to, &info2) == FILEINFO_OK
6566 && info1.dwVolumeSerialNumber == info2.dwVolumeSerialNumber
6567 && info1.nFileIndexHigh == info2.nFileIndexHigh
6568 && info1.nFileIndexLow == info2.nFileIndexLow)
6569 use_tmp_file = TRUE;
6570 }
6571#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006572
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006573 if (use_tmp_file)
6574 {
6575 char tempname[MAXPATHL + 1];
6576
6577 /*
6578 * Find a name that doesn't exist and is in the same directory.
6579 * Rename "from" to "tempname" and then rename "tempname" to "to".
6580 */
6581 if (STRLEN(from) >= MAXPATHL - 5)
6582 return -1;
6583 STRCPY(tempname, from);
6584 for (n = 123; n < 99999; ++n)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006585 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006586 sprintf((char *)gettail((char_u *)tempname), "%d", n);
6587 if (mch_stat(tempname, &st) < 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006588 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006589 if (mch_rename((char *)from, tempname) == 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006590 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006591 if (mch_rename(tempname, (char *)to) == 0)
6592 return 0;
6593 /* Strange, the second step failed. Try moving the
6594 * file back and return failure. */
6595 mch_rename(tempname, (char *)from);
Bram Moolenaar3576da72008-12-30 15:15:57 +00006596 return -1;
6597 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006598 /* If it fails for one temp name it will most likely fail
6599 * for any temp name, give up. */
6600 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006601 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006602 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006603 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006604 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006605
Bram Moolenaar071d4272004-06-13 20:20:40 +00006606 /*
6607 * Delete the "to" file, this is required on some systems to make the
6608 * mch_rename() work, on other systems it makes sure that we don't have
6609 * two files when the mch_rename() fails.
6610 */
6611
6612#ifdef AMIGA
6613 /*
6614 * With MSDOS-compatible filesystems (crossdos, messydos) it is possible
6615 * that the name of the "to" file is the same as the "from" file, even
Bram Moolenaar7263a772007-05-10 17:35:54 +00006616 * though the names are different. To avoid the chance of accidentally
Bram Moolenaar071d4272004-06-13 20:20:40 +00006617 * deleting the "from" file (horror!) we lock it during the remove.
6618 *
6619 * When used for making a backup before writing the file: This should not
6620 * happen with ":w", because startscript() should detect this problem and
6621 * set buf->b_shortname, causing modname() to return a correct ".bak" file
6622 * name. This problem does exist with ":w filename", but then the
6623 * original file will be somewhere else so the backup isn't really
6624 * important. If autoscripting is off the rename may fail.
6625 */
6626 flock = Lock((UBYTE *)from, (long)ACCESS_READ);
6627#endif
6628 mch_remove(to);
6629#ifdef AMIGA
6630 if (flock)
6631 UnLock(flock);
6632#endif
6633
6634 /*
6635 * First try a normal rename, return if it works.
6636 */
6637 if (mch_rename((char *)from, (char *)to) == 0)
6638 return 0;
6639
6640 /*
6641 * Rename() failed, try copying the file.
6642 */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006643 perm = mch_getperm(from);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006644#ifdef HAVE_ACL
6645 /* For systems that support ACL: get the ACL from the original file. */
6646 acl = mch_get_acl(from);
6647#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006648 fd_in = mch_open((char *)from, O_RDONLY|O_EXTRA, 0);
6649 if (fd_in == -1)
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006650 {
6651#ifdef HAVE_ACL
6652 mch_free_acl(acl);
6653#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006654 return -1;
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006655 }
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006656
6657 /* Create the new file with same permissions as the original. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00006658 fd_out = mch_open((char *)to,
6659 O_CREAT|O_EXCL|O_WRONLY|O_EXTRA|O_NOFOLLOW, (int)perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006660 if (fd_out == -1)
6661 {
6662 close(fd_in);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006663#ifdef HAVE_ACL
6664 mch_free_acl(acl);
6665#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006666 return -1;
6667 }
6668
6669 buffer = (char *)alloc(BUFSIZE);
6670 if (buffer == NULL)
6671 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006672 close(fd_out);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006673 close(fd_in);
6674#ifdef HAVE_ACL
6675 mch_free_acl(acl);
6676#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006677 return -1;
6678 }
6679
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01006680 while ((n = read_eintr(fd_in, buffer, BUFSIZE)) > 0)
6681 if (write_eintr(fd_out, buffer, n) != n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006682 {
6683 errmsg = _("E208: Error writing to \"%s\"");
6684 break;
6685 }
6686
6687 vim_free(buffer);
6688 close(fd_in);
6689 if (close(fd_out) < 0)
6690 errmsg = _("E209: Error closing \"%s\"");
6691 if (n < 0)
6692 {
6693 errmsg = _("E210: Error reading \"%s\"");
6694 to = from;
6695 }
Bram Moolenaar7263a772007-05-10 17:35:54 +00006696#ifndef UNIX /* for Unix mch_open() already set the permission */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006697 mch_setperm(to, perm);
Bram Moolenaarc6039d82005-12-02 00:44:04 +00006698#endif
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006699#ifdef HAVE_ACL
6700 mch_set_acl(to, acl);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006701 mch_free_acl(acl);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006702#endif
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02006703#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaare8747442013-11-12 18:09:29 +01006704 mch_copy_sec(from, to);
Bram Moolenaar0671de32013-11-12 05:12:03 +01006705#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006706 if (errmsg != NULL)
6707 {
6708 EMSG2(errmsg, to);
6709 return -1;
6710 }
6711 mch_remove(from);
6712 return 0;
6713}
6714
6715static int already_warned = FALSE;
6716
6717/*
6718 * Check if any not hidden buffer has been changed.
6719 * Postpone the check if there are characters in the stuff buffer, a global
6720 * command is being executed, a mapping is being executed or an autocommand is
6721 * busy.
6722 * Returns TRUE if some message was written (screen should be redrawn and
6723 * cursor positioned).
6724 */
6725 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006726check_timestamps(
6727 int focus) /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006728{
6729 buf_T *buf;
6730 int didit = 0;
6731 int n;
6732
6733 /* Don't check timestamps while system() or another low-level function may
6734 * cause us to lose and gain focus. */
6735 if (no_check_timestamps > 0)
6736 return FALSE;
6737
6738 /* Avoid doing a check twice. The OK/Reload dialog can cause a focus
6739 * event and we would keep on checking if the file is steadily growing.
6740 * Do check again after typing something. */
6741 if (focus && did_check_timestamps)
6742 {
6743 need_check_timestamps = TRUE;
6744 return FALSE;
6745 }
6746
6747 if (!stuff_empty() || global_busy || !typebuf_typed()
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006748 || autocmd_busy || curbuf_lock > 0 || allbuf_lock > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006749 need_check_timestamps = TRUE; /* check later */
6750 else
6751 {
6752 ++no_wait_return;
6753 did_check_timestamps = TRUE;
6754 already_warned = FALSE;
Bram Moolenaar29323592016-07-24 22:04:11 +02006755 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006756 {
6757 /* Only check buffers in a window. */
6758 if (buf->b_nwindows > 0)
6759 {
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006760 bufref_T bufref;
6761
6762 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006763 n = buf_check_timestamp(buf, focus);
6764 if (didit < n)
6765 didit = n;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006766 if (n > 0 && !bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006767 {
6768 /* Autocommands have removed the buffer, start at the
6769 * first one again. */
6770 buf = firstbuf;
6771 continue;
6772 }
6773 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006774 }
6775 --no_wait_return;
6776 need_check_timestamps = FALSE;
6777 if (need_wait_return && didit == 2)
6778 {
6779 /* make sure msg isn't overwritten */
6780 msg_puts((char_u *)"\n");
6781 out_flush();
6782 }
6783 }
6784 return didit;
6785}
6786
6787/*
6788 * Move all the lines from buffer "frombuf" to buffer "tobuf".
6789 * Return OK or FAIL. When FAIL "tobuf" is incomplete and/or "frombuf" is not
6790 * empty.
6791 */
6792 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006793move_lines(buf_T *frombuf, buf_T *tobuf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006794{
6795 buf_T *tbuf = curbuf;
6796 int retval = OK;
6797 linenr_T lnum;
6798 char_u *p;
6799
6800 /* Copy the lines in "frombuf" to "tobuf". */
6801 curbuf = tobuf;
6802 for (lnum = 1; lnum <= frombuf->b_ml.ml_line_count; ++lnum)
6803 {
6804 p = vim_strsave(ml_get_buf(frombuf, lnum, FALSE));
6805 if (p == NULL || ml_append(lnum - 1, p, 0, FALSE) == FAIL)
6806 {
6807 vim_free(p);
6808 retval = FAIL;
6809 break;
6810 }
6811 vim_free(p);
6812 }
6813
6814 /* Delete all the lines in "frombuf". */
6815 if (retval != FAIL)
6816 {
6817 curbuf = frombuf;
Bram Moolenaar9460b9d2007-01-09 14:37:01 +00006818 for (lnum = curbuf->b_ml.ml_line_count; lnum > 0; --lnum)
6819 if (ml_delete(lnum, FALSE) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006820 {
6821 /* Oops! We could try putting back the saved lines, but that
6822 * might fail again... */
6823 retval = FAIL;
6824 break;
6825 }
6826 }
6827
6828 curbuf = tbuf;
6829 return retval;
6830}
6831
6832/*
6833 * Check if buffer "buf" has been changed.
6834 * Also check if the file for a new buffer unexpectedly appeared.
6835 * return 1 if a changed buffer was found.
6836 * return 2 if a message has been displayed.
6837 * return 0 otherwise.
6838 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006839 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006840buf_check_timestamp(
6841 buf_T *buf,
6842 int focus UNUSED) /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006843{
Bram Moolenaar8767f522016-07-01 17:17:39 +02006844 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006845 int stat_res;
6846 int retval = 0;
6847 char_u *path;
6848 char_u *tbuf;
6849 char *mesg = NULL;
Bram Moolenaar44ecf652005-03-07 23:09:59 +00006850 char *mesg2 = "";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006851 int helpmesg = FALSE;
6852 int reload = FALSE;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006853 char *reason;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006854#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6855 int can_reload = FALSE;
6856#endif
Bram Moolenaar8767f522016-07-01 17:17:39 +02006857 off_T orig_size = buf->b_orig_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006858 int orig_mode = buf->b_orig_mode;
6859#ifdef FEAT_GUI
6860 int save_mouse_correct = need_mouse_correct;
6861#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006862 static int busy = FALSE;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006863 int n;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006864#ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006865 char_u *s;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006866#endif
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006867 bufref_T bufref;
6868
6869 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006870
6871 /* If there is no file name, the buffer is not loaded, 'buftype' is
6872 * set, we are in the middle of a save or being called recursively: ignore
6873 * this buffer. */
6874 if (buf->b_ffname == NULL
6875 || buf->b_ml.ml_mfp == NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00006876 || *buf->b_p_bt != NUL
Bram Moolenaar071d4272004-06-13 20:20:40 +00006877 || buf->b_saving
Bram Moolenaar071d4272004-06-13 20:20:40 +00006878 || busy
Bram Moolenaar009b2592004-10-24 19:18:58 +00006879#ifdef FEAT_NETBEANS_INTG
6880 || isNetbeansBuffer(buf)
6881#endif
Bram Moolenaar8cad9302017-08-12 14:32:32 +02006882#ifdef FEAT_TERMINAL
6883 || buf->b_term != NULL
6884#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006885 )
6886 return 0;
6887
6888 if ( !(buf->b_flags & BF_NOTEDITED)
6889 && buf->b_mtime != 0
6890 && ((stat_res = mch_stat((char *)buf->b_ffname, &st)) < 0
6891 || time_differs((long)st.st_mtime, buf->b_mtime)
Bram Moolenaara7611f62014-05-02 15:46:14 +02006892 || st.st_size != buf->b_orig_size
Bram Moolenaar071d4272004-06-13 20:20:40 +00006893#ifdef HAVE_ST_MODE
6894 || (int)st.st_mode != buf->b_orig_mode
6895#else
6896 || mch_getperm(buf->b_ffname) != buf->b_orig_mode
6897#endif
6898 ))
6899 {
6900 retval = 1;
6901
Bram Moolenaar316059c2006-01-14 21:18:42 +00006902 /* set b_mtime to stop further warnings (e.g., when executing
6903 * FileChangedShell autocmd) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006904 if (stat_res < 0)
6905 {
6906 buf->b_mtime = 0;
6907 buf->b_orig_size = 0;
6908 buf->b_orig_mode = 0;
6909 }
6910 else
6911 buf_store_time(buf, &st, buf->b_ffname);
6912
6913 /* Don't do anything for a directory. Might contain the file
6914 * explorer. */
6915 if (mch_isdir(buf->b_fname))
6916 ;
6917
6918 /*
6919 * If 'autoread' is set, the buffer has no changes and the file still
6920 * exists, reload the buffer. Use the buffer-local option value if it
6921 * was set, the global option value otherwise.
6922 */
6923 else if ((buf->b_p_ar >= 0 ? buf->b_p_ar : p_ar)
6924 && !bufIsChanged(buf) && stat_res >= 0)
6925 reload = TRUE;
6926 else
6927 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006928 if (stat_res < 0)
6929 reason = "deleted";
6930 else if (bufIsChanged(buf))
6931 reason = "conflict";
6932 else if (orig_size != buf->b_orig_size || buf_contents_changed(buf))
6933 reason = "changed";
6934 else if (orig_mode != buf->b_orig_mode)
6935 reason = "mode";
6936 else
6937 reason = "time";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006938
6939 /*
6940 * Only give the warning if there are no FileChangedShell
6941 * autocommands.
6942 * Avoid being called recursively by setting "busy".
6943 */
6944 busy = TRUE;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006945#ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006946 set_vim_var_string(VV_FCS_REASON, (char_u *)reason, -1);
6947 set_vim_var_string(VV_FCS_CHOICE, (char_u *)"", -1);
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006948#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006949 ++allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006950 n = apply_autocmds(EVENT_FILECHANGEDSHELL,
6951 buf->b_fname, buf->b_fname, FALSE, buf);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006952 --allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006953 busy = FALSE;
6954 if (n)
6955 {
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006956 if (!bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006957 EMSG(_("E246: FileChangedShell autocommand deleted buffer"));
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006958#ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006959 s = get_vim_var_str(VV_FCS_CHOICE);
6960 if (STRCMP(s, "reload") == 0 && *reason != 'd')
6961 reload = TRUE;
6962 else if (STRCMP(s, "ask") == 0)
6963 n = FALSE;
6964 else
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006965#endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006966 return 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006967 }
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006968 if (!n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006969 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006970 if (*reason == 'd')
6971 mesg = _("E211: File \"%s\" no longer available");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006972 else
6973 {
6974 helpmesg = TRUE;
6975#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6976 can_reload = TRUE;
6977#endif
6978 /*
6979 * Check if the file contents really changed to avoid
6980 * giving a warning when only the timestamp was set (e.g.,
6981 * checked out of CVS). Always warn when the buffer was
6982 * changed.
6983 */
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006984 if (reason[2] == 'n')
6985 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006986 mesg = _("W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006987 mesg2 = _("See \":help W12\" for more info.");
6988 }
6989 else if (reason[1] == 'h')
6990 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006991 mesg = _("W11: Warning: File \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006992 mesg2 = _("See \":help W11\" for more info.");
6993 }
6994 else if (*reason == 'm')
6995 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006996 mesg = _("W16: Warning: Mode of file \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006997 mesg2 = _("See \":help W16\" for more info.");
6998 }
Bram Moolenaar85388b52009-06-24 09:58:32 +00006999 else
7000 /* Only timestamp changed, store it to avoid a warning
7001 * in check_mtime() later. */
7002 buf->b_mtime_read = buf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007003 }
7004 }
7005 }
7006
7007 }
7008 else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W)
7009 && vim_fexists(buf->b_ffname))
7010 {
7011 retval = 1;
7012 mesg = _("W13: Warning: File \"%s\" has been created after editing started");
7013 buf->b_flags |= BF_NEW_W;
7014#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
7015 can_reload = TRUE;
7016#endif
7017 }
7018
7019 if (mesg != NULL)
7020 {
7021 path = home_replace_save(buf, buf->b_fname);
7022 if (path != NULL)
7023 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007024 if (!helpmesg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007025 mesg2 = "";
7026 tbuf = alloc((unsigned)(STRLEN(path) + STRLEN(mesg)
7027 + STRLEN(mesg2) + 2));
7028 sprintf((char *)tbuf, mesg, path);
Bram Moolenaar496c5262009-03-18 14:42:00 +00007029#ifdef FEAT_EVAL
7030 /* Set warningmsg here, before the unimportant and output-specific
7031 * mesg2 has been appended. */
7032 set_vim_var_string(VV_WARNINGMSG, tbuf, -1);
7033#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007034#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
7035 if (can_reload)
7036 {
7037 if (*mesg2 != NUL)
7038 {
7039 STRCAT(tbuf, "\n");
7040 STRCAT(tbuf, mesg2);
7041 }
7042 if (do_dialog(VIM_WARNING, (char_u *)_("Warning"), tbuf,
Bram Moolenaard2c340a2011-01-17 20:08:11 +01007043 (char_u *)_("&OK\n&Load File"), 1, NULL, TRUE) == 2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007044 reload = TRUE;
7045 }
7046 else
7047#endif
7048 if (State > NORMAL_BUSY || (State & CMDLINE) || already_warned)
7049 {
7050 if (*mesg2 != NUL)
7051 {
7052 STRCAT(tbuf, "; ");
7053 STRCAT(tbuf, mesg2);
7054 }
7055 EMSG(tbuf);
7056 retval = 2;
7057 }
7058 else
7059 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007060 if (!autocmd_busy)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007061 {
7062 msg_start();
Bram Moolenaar8820b482017-03-16 17:23:31 +01007063 msg_puts_attr(tbuf, HL_ATTR(HLF_E) + MSG_HIST);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007064 if (*mesg2 != NUL)
7065 msg_puts_attr((char_u *)mesg2,
Bram Moolenaar8820b482017-03-16 17:23:31 +01007066 HL_ATTR(HLF_W) + MSG_HIST);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007067 msg_clr_eos();
7068 (void)msg_end();
7069 if (emsg_silent == 0)
7070 {
7071 out_flush();
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01007072#ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00007073 if (!focus)
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01007074#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007075 /* give the user some time to think about it */
7076 ui_delay(1000L, TRUE);
7077
7078 /* don't redraw and erase the message */
7079 redraw_cmdline = FALSE;
7080 }
7081 }
7082 already_warned = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007083 }
7084
7085 vim_free(path);
7086 vim_free(tbuf);
7087 }
7088 }
7089
7090 if (reload)
Bram Moolenaar465748e2012-08-29 18:50:54 +02007091 {
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007092 /* Reload the buffer. */
Bram Moolenaar316059c2006-01-14 21:18:42 +00007093 buf_reload(buf, orig_mode);
Bram Moolenaar465748e2012-08-29 18:50:54 +02007094#ifdef FEAT_PERSISTENT_UNDO
7095 if (buf->b_p_udf && buf->b_ffname != NULL)
7096 {
7097 char_u hash[UNDO_HASH_SIZE];
7098 buf_T *save_curbuf = curbuf;
7099
7100 /* Any existing undo file is unusable, write it now. */
7101 curbuf = buf;
7102 u_compute_hash(hash);
7103 u_write_undo(NULL, FALSE, buf, hash);
7104 curbuf = save_curbuf;
7105 }
7106#endif
7107 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007108
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00007109 /* Trigger FileChangedShell when the file was changed in any way. */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007110 if (bufref_valid(&bufref) && retval != 0)
Bram Moolenaar56718732006-03-15 22:53:57 +00007111 (void)apply_autocmds(EVENT_FILECHANGEDSHELLPOST,
7112 buf->b_fname, buf->b_fname, FALSE, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007113#ifdef FEAT_GUI
7114 /* restore this in case an autocommand has set it; it would break
7115 * 'mousefocus' */
7116 need_mouse_correct = save_mouse_correct;
7117#endif
7118
7119 return retval;
7120}
7121
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007122/*
7123 * Reload a buffer that is already loaded.
7124 * Used when the file was changed outside of Vim.
Bram Moolenaar316059c2006-01-14 21:18:42 +00007125 * "orig_mode" is buf->b_orig_mode before the need for reloading was detected.
7126 * buf->b_orig_mode may have been reset already.
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007127 */
7128 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007129buf_reload(buf_T *buf, int orig_mode)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007130{
7131 exarg_T ea;
7132 pos_T old_cursor;
7133 linenr_T old_topline;
7134 int old_ro = buf->b_p_ro;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007135 buf_T *savebuf;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007136 bufref_T bufref;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007137 int saved = OK;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007138 aco_save_T aco;
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007139 int flags = READ_NEW;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007140
7141 /* set curwin/curbuf for "buf" and save some things */
7142 aucmd_prepbuf(&aco, buf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007143
7144 /* We only want to read the text from the file, not reset the syntax
7145 * highlighting, clear marks, diff status, etc. Force the fileformat
7146 * and encoding to be the same. */
7147 if (prep_exarg(&ea, buf) == OK)
7148 {
7149 old_cursor = curwin->w_cursor;
7150 old_topline = curwin->w_topline;
7151
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007152 if (p_ur < 0 || curbuf->b_ml.ml_line_count <= p_ur)
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007153 {
7154 /* Save all the text, so that the reload can be undone.
7155 * Sync first so that this is a separate undo-able action. */
7156 u_sync(FALSE);
7157 saved = u_savecommon(0, curbuf->b_ml.ml_line_count + 1, 0, TRUE);
7158 flags |= READ_KEEP_UNDO;
7159 }
7160
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007161 /*
7162 * To behave like when a new file is edited (matters for
7163 * BufReadPost autocommands) we first need to delete the current
7164 * buffer contents. But if reading the file fails we should keep
7165 * the old contents. Can't use memory only, the file might be
7166 * too big. Use a hidden buffer to move the buffer contents to.
7167 */
Bram Moolenaarb5aedf32017-03-12 18:23:53 +01007168 if (BUFEMPTY() || saved == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007169 savebuf = NULL;
7170 else
7171 {
7172 /* Allocate a buffer without putting it in the buffer list. */
7173 savebuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007174 set_bufref(&bufref, savebuf);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007175 if (savebuf != NULL && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007176 {
7177 /* Open the memline. */
7178 curbuf = savebuf;
7179 curwin->w_buffer = savebuf;
Bram Moolenaar4770d092006-01-12 23:22:24 +00007180 saved = ml_open(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007181 curbuf = buf;
7182 curwin->w_buffer = buf;
7183 }
Bram Moolenaar8424a622006-04-19 21:23:36 +00007184 if (savebuf == NULL || saved == FAIL || buf != curbuf
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007185 || move_lines(buf, savebuf) == FAIL)
7186 {
7187 EMSG2(_("E462: Could not prepare for reloading \"%s\""),
7188 buf->b_fname);
7189 saved = FAIL;
7190 }
7191 }
7192
7193 if (saved == OK)
7194 {
7195 curbuf->b_flags |= BF_CHECK_RO; /* check for RO again */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007196 keep_filetype = TRUE; /* don't detect 'filetype' */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007197 if (readfile(buf->b_ffname, buf->b_fname, (linenr_T)0,
7198 (linenr_T)0,
Bram Moolenaare13b9af2017-01-13 22:01:02 +01007199 (linenr_T)MAXLNUM, &ea, flags) != OK)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007200 {
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01007201#if defined(FEAT_EVAL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007202 if (!aborting())
7203#endif
7204 EMSG2(_("E321: Could not reload \"%s\""), buf->b_fname);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007205 if (savebuf != NULL && bufref_valid(&bufref) && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007206 {
7207 /* Put the text back from the save buffer. First
7208 * delete any lines that readfile() added. */
Bram Moolenaarb5aedf32017-03-12 18:23:53 +01007209 while (!BUFEMPTY())
Bram Moolenaar8424a622006-04-19 21:23:36 +00007210 if (ml_delete(buf->b_ml.ml_line_count, FALSE) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007211 break;
7212 (void)move_lines(savebuf, buf);
7213 }
7214 }
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007215 else if (buf == curbuf) /* "buf" still valid */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007216 {
7217 /* Mark the buffer as unmodified and free undo info. */
7218 unchanged(buf, TRUE);
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007219 if ((flags & READ_KEEP_UNDO) == 0)
7220 {
7221 u_blockfree(buf);
7222 u_clearall(buf);
7223 }
7224 else
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007225 {
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007226 /* Mark all undo states as changed. */
7227 u_unchanged(curbuf);
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007228 }
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007229 }
7230 }
7231 vim_free(ea.cmd);
7232
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007233 if (savebuf != NULL && bufref_valid(&bufref))
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007234 wipe_buffer(savebuf, FALSE);
7235
7236#ifdef FEAT_DIFF
7237 /* Invalidate diff info if necessary. */
Bram Moolenaar8424a622006-04-19 21:23:36 +00007238 diff_invalidate(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007239#endif
7240
7241 /* Restore the topline and cursor position and check it (lines may
7242 * have been removed). */
7243 if (old_topline > curbuf->b_ml.ml_line_count)
7244 curwin->w_topline = curbuf->b_ml.ml_line_count;
7245 else
7246 curwin->w_topline = old_topline;
7247 curwin->w_cursor = old_cursor;
7248 check_cursor();
7249 update_topline();
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007250 keep_filetype = FALSE;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007251#ifdef FEAT_FOLDING
7252 {
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007253 win_T *wp;
7254 tabpage_T *tp;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007255
7256 /* Update folds unless they are defined manually. */
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007257 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007258 if (wp->w_buffer == curwin->w_buffer
7259 && !foldmethodIsManual(wp))
7260 foldUpdateAll(wp);
7261 }
7262#endif
7263 /* If the mode didn't change and 'readonly' was set, keep the old
7264 * value; the user probably used the ":view" command. But don't
7265 * reset it, might have had a read error. */
7266 if (orig_mode == curbuf->b_orig_mode)
7267 curbuf->b_p_ro |= old_ro;
Bram Moolenaar52f85b72013-01-30 14:13:56 +01007268
7269 /* Modelines must override settings done by autocommands. */
7270 do_modelines(0);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007271 }
7272
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007273 /* restore curwin/curbuf and a few other things */
7274 aucmd_restbuf(&aco);
7275 /* Careful: autocommands may have made "buf" invalid! */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007276}
7277
Bram Moolenaar071d4272004-06-13 20:20:40 +00007278 void
Bram Moolenaar8767f522016-07-01 17:17:39 +02007279buf_store_time(buf_T *buf, stat_T *st, char_u *fname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007280{
7281 buf->b_mtime = (long)st->st_mtime;
Bram Moolenaar914703b2010-05-31 21:59:46 +02007282 buf->b_orig_size = st->st_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007283#ifdef HAVE_ST_MODE
7284 buf->b_orig_mode = (int)st->st_mode;
7285#else
7286 buf->b_orig_mode = mch_getperm(fname);
7287#endif
7288}
7289
7290/*
7291 * Adjust the line with missing eol, used for the next write.
7292 * Used for do_filter(), when the input lines for the filter are deleted.
7293 */
7294 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007295write_lnum_adjust(linenr_T offset)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007296{
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01007297 if (curbuf->b_no_eol_lnum != 0) /* only if there is a missing eol */
7298 curbuf->b_no_eol_lnum += offset;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007299}
7300
Bram Moolenaarda440d22016-01-16 21:27:23 +01007301#if defined(TEMPDIRNAMES) || defined(FEAT_EVAL) || defined(PROTO)
7302/*
7303 * Delete "name" and everything in it, recursively.
7304 * return 0 for succes, -1 if some file was not deleted.
7305 */
7306 int
7307delete_recursive(char_u *name)
7308{
7309 int result = 0;
7310 char_u **files;
7311 int file_count;
7312 int i;
7313 char_u *exp;
7314
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007315 /* A symbolic link to a directory itself is deleted, not the directory it
7316 * points to. */
7317 if (
Bram Moolenaar203258c2016-01-17 22:15:16 +01007318# if defined(UNIX) || defined(WIN32)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007319 mch_isrealdir(name)
Bram Moolenaar203258c2016-01-17 22:15:16 +01007320# else
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007321 mch_isdir(name)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007322# endif
7323 )
Bram Moolenaarda440d22016-01-16 21:27:23 +01007324 {
7325 vim_snprintf((char *)NameBuff, MAXPATHL, "%s/*", name);
7326 exp = vim_strsave(NameBuff);
7327 if (exp == NULL)
7328 return -1;
7329 if (gen_expand_wildcards(1, &exp, &file_count, &files,
Bram Moolenaar336bd622016-01-17 18:23:58 +01007330 EW_DIR|EW_FILE|EW_SILENT|EW_ALLLINKS|EW_DODOT|EW_EMPTYOK) == OK)
Bram Moolenaarda440d22016-01-16 21:27:23 +01007331 {
7332 for (i = 0; i < file_count; ++i)
7333 if (delete_recursive(files[i]) != 0)
7334 result = -1;
7335 FreeWild(file_count, files);
7336 }
7337 else
7338 result = -1;
7339 vim_free(exp);
7340 (void)mch_rmdir(name);
7341 }
7342 else
7343 result = mch_remove(name) == 0 ? 0 : -1;
7344
7345 return result;
7346}
7347#endif
7348
Bram Moolenaar071d4272004-06-13 20:20:40 +00007349#if defined(TEMPDIRNAMES) || defined(PROTO)
7350static long temp_count = 0; /* Temp filename counter. */
7351
7352/*
7353 * Delete the temp directory and all files it contains.
7354 */
7355 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007356vim_deltempdir(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007357{
Bram Moolenaar071d4272004-06-13 20:20:40 +00007358 if (vim_tempdir != NULL)
7359 {
Bram Moolenaarda440d22016-01-16 21:27:23 +01007360 /* remove the trailing path separator */
7361 gettail(vim_tempdir)[-1] = NUL;
7362 delete_recursive(vim_tempdir);
Bram Moolenaard23a8232018-02-10 18:45:26 +01007363 VIM_CLEAR(vim_tempdir);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007364 }
7365}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007366
7367/*
Bram Moolenaareaf03392009-11-17 11:08:52 +00007368 * Directory "tempdir" was created. Expand this name to a full path and put
7369 * it in "vim_tempdir". This avoids that using ":cd" would confuse us.
7370 * "tempdir" must be no longer than MAXPATHL.
7371 */
7372 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007373vim_settempdir(char_u *tempdir)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007374{
7375 char_u *buf;
7376
7377 buf = alloc((unsigned)MAXPATHL + 2);
7378 if (buf != NULL)
7379 {
7380 if (vim_FullName(tempdir, buf, MAXPATHL, FALSE) == FAIL)
7381 STRCPY(buf, tempdir);
Bram Moolenaara06ecab2016-07-16 14:47:36 +02007382 add_pathsep(buf);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007383 vim_tempdir = vim_strsave(buf);
7384 vim_free(buf);
7385 }
7386}
Bram Moolenaar4592dee2009-11-18 19:11:58 +00007387#endif
Bram Moolenaareaf03392009-11-17 11:08:52 +00007388
7389/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007390 * vim_tempname(): Return a unique name that can be used for a temp file.
7391 *
Bram Moolenaar76ae22f2016-06-13 20:00:29 +02007392 * The temp file is NOT guaranteed to be created. If "keep" is FALSE it is
7393 * guaranteed to NOT be created.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007394 *
7395 * The returned pointer is to allocated memory.
7396 * The returned pointer is NULL if no valid name was found.
7397 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007398 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007399vim_tempname(
7400 int extra_char UNUSED, /* char to use in the name instead of '?' */
7401 int keep UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007402{
7403#ifdef USE_TMPNAM
7404 char_u itmp[L_tmpnam]; /* use tmpnam() */
7405#else
7406 char_u itmp[TEMPNAMELEN];
7407#endif
7408
7409#ifdef TEMPDIRNAMES
7410 static char *(tempdirs[]) = {TEMPDIRNAMES};
7411 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007412# ifndef EEXIST
Bram Moolenaar8767f522016-07-01 17:17:39 +02007413 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007414# endif
7415
7416 /*
7417 * This will create a directory for private use by this instance of Vim.
7418 * This is done once, and the same directory is used for all temp files.
7419 * This method avoids security problems because of symlink attacks et al.
7420 * It's also a bit faster, because we only need to check for an existing
7421 * file when creating the directory and not for each temp file.
7422 */
7423 if (vim_tempdir == NULL)
7424 {
7425 /*
7426 * Try the entries in TEMPDIRNAMES to create the temp directory.
7427 */
Bram Moolenaar78a15312009-05-15 19:33:18 +00007428 for (i = 0; i < (int)(sizeof(tempdirs) / sizeof(char *)); ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007429 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007430# ifndef HAVE_MKDTEMP
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007431 size_t itmplen;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007432 long nr;
7433 long off;
7434# endif
7435
Bram Moolenaare1a61992015-12-03 21:02:27 +01007436 /* Expand $TMP, leave room for "/v1100000/999999999".
7437 * Skip the directory check if the expansion fails. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007438 expand_env((char_u *)tempdirs[i], itmp, TEMPNAMELEN - 20);
Bram Moolenaare1a61992015-12-03 21:02:27 +01007439 if (itmp[0] != '$' && mch_isdir(itmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007440 {
Bram Moolenaare1a61992015-12-03 21:02:27 +01007441 /* directory exists */
Bram Moolenaara06ecab2016-07-16 14:47:36 +02007442 add_pathsep(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007443
Bram Moolenaareaf03392009-11-17 11:08:52 +00007444# ifdef HAVE_MKDTEMP
Bram Moolenaar35d88f42016-06-04 14:52:00 +02007445 {
7446# if defined(UNIX) || defined(VMS)
7447 /* Make sure the umask doesn't remove the executable bit.
7448 * "repl" has been reported to use "177". */
7449 mode_t umask_save = umask(077);
7450# endif
7451 /* Leave room for filename */
7452 STRCAT(itmp, "vXXXXXX");
7453 if (mkdtemp((char *)itmp) != NULL)
7454 vim_settempdir(itmp);
7455# if defined(UNIX) || defined(VMS)
7456 (void)umask(umask_save);
7457# endif
7458 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007459# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007460 /* Get an arbitrary number of up to 6 digits. When it's
7461 * unlikely that it already exists it will be faster,
7462 * otherwise it doesn't matter. The use of mkdir() avoids any
7463 * security problems because of the predictable number. */
7464 nr = (mch_get_pid() + (long)time(NULL)) % 1000000L;
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007465 itmplen = STRLEN(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007466
7467 /* Try up to 10000 different values until we find a name that
7468 * doesn't exist. */
7469 for (off = 0; off < 10000L; ++off)
7470 {
7471 int r;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007472# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007473 mode_t umask_save;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007474# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007475
Bram Moolenaareaf03392009-11-17 11:08:52 +00007476 sprintf((char *)itmp + itmplen, "v%ld", nr + off);
7477# ifndef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007478 /* If mkdir() does not set errno to EEXIST, check for
7479 * existing file here. There is a race condition then,
7480 * although it's fail-safe. */
7481 if (mch_stat((char *)itmp, &st) >= 0)
7482 continue;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007483# endif
7484# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007485 /* Make sure the umask doesn't remove the executable bit.
7486 * "repl" has been reported to use "177". */
7487 umask_save = umask(077);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007488# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007489 r = vim_mkdir(itmp, 0700);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007490# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007491 (void)umask(umask_save);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007492# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007493 if (r == 0)
7494 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007495 vim_settempdir(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007496 break;
7497 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007498# ifdef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007499 /* If the mkdir() didn't fail because the file/dir exists,
7500 * we probably can't create any dir here, try another
7501 * place. */
7502 if (errno != EEXIST)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007503# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007504 break;
7505 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007506# endif /* HAVE_MKDTEMP */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007507 if (vim_tempdir != NULL)
7508 break;
7509 }
7510 }
7511 }
7512
7513 if (vim_tempdir != NULL)
7514 {
7515 /* There is no need to check if the file exists, because we own the
7516 * directory and nobody else creates a file in it. */
7517 sprintf((char *)itmp, "%s%ld", vim_tempdir, temp_count++);
7518 return vim_strsave(itmp);
7519 }
7520
7521 return NULL;
7522
7523#else /* TEMPDIRNAMES */
7524
7525# ifdef WIN3264
7526 char szTempFile[_MAX_PATH + 1];
7527 char buf4[4];
7528 char_u *retval;
7529 char_u *p;
7530
7531 STRCPY(itmp, "");
7532 if (GetTempPath(_MAX_PATH, szTempFile) == 0)
Bram Moolenaarb1891912011-02-09 14:47:03 +01007533 {
7534 szTempFile[0] = '.'; /* GetTempPath() failed, use current dir */
7535 szTempFile[1] = NUL;
7536 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007537 strcpy(buf4, "VIM");
7538 buf4[2] = extra_char; /* make it "VIa", "VIb", etc. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007539 if (GetTempFileName(szTempFile, buf4, 0, (LPSTR)itmp) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007540 return NULL;
Bram Moolenaare5c421c2015-03-31 13:33:08 +02007541 if (!keep)
7542 /* GetTempFileName() will create the file, we don't want that */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007543 (void)DeleteFile((LPSTR)itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007544
7545 /* Backslashes in a temp file name cause problems when filtering with
7546 * "sh". NOTE: This also checks 'shellcmdflag' to help those people who
7547 * didn't set 'shellslash'. */
7548 retval = vim_strsave(itmp);
7549 if (*p_shcf == '-' || p_ssl)
7550 for (p = retval; *p; ++p)
7551 if (*p == '\\')
7552 *p = '/';
7553 return retval;
7554
7555# else /* WIN3264 */
7556
7557# ifdef USE_TMPNAM
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007558 char_u *p;
7559
Bram Moolenaar071d4272004-06-13 20:20:40 +00007560 /* tmpnam() will make its own name */
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007561 p = tmpnam((char *)itmp);
7562 if (p == NULL || *p == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007563 return NULL;
7564# else
7565 char_u *p;
7566
7567# ifdef VMS_TEMPNAM
7568 /* mktemp() is not working on VMS. It seems to be
7569 * a do-nothing function. Therefore we use tempnam().
7570 */
7571 sprintf((char *)itmp, "VIM%c", extra_char);
7572 p = (char_u *)tempnam("tmp:", (char *)itmp);
7573 if (p != NULL)
7574 {
Bram Moolenaar206f0112014-03-12 16:51:55 +01007575 /* VMS will use '.LIS' if we don't explicitly specify an extension,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007576 * and VIM will then be unable to find the file later */
7577 STRCPY(itmp, p);
7578 STRCAT(itmp, ".txt");
7579 free(p);
7580 }
7581 else
7582 return NULL;
7583# else
7584 STRCPY(itmp, TEMPNAME);
7585 if ((p = vim_strchr(itmp, '?')) != NULL)
7586 *p = extra_char;
7587 if (mktemp((char *)itmp) == NULL)
7588 return NULL;
7589# endif
7590# endif
7591
7592 return vim_strsave(itmp);
7593# endif /* WIN3264 */
7594#endif /* TEMPDIRNAMES */
7595}
7596
7597#if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
7598/*
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02007599 * Convert all backslashes in fname to forward slashes in-place, unless when
7600 * it looks like a URL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007601 */
7602 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007603forward_slash(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007604{
7605 char_u *p;
7606
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02007607 if (path_with_url(fname))
7608 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007609 for (p = fname; *p != NUL; ++p)
7610# ifdef FEAT_MBYTE
7611 /* The Big5 encoding can have '\' in the trail byte. */
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00007612 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007613 ++p;
7614 else
7615# endif
7616 if (*p == '\\')
7617 *p = '/';
7618}
7619#endif
7620
7621
7622/*
7623 * Code for automatic commands.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007624 */
7625
Bram Moolenaar071d4272004-06-13 20:20:40 +00007626/*
7627 * The autocommands are stored in a list for each event.
7628 * Autocommands for the same pattern, that are consecutive, are joined
7629 * together, to avoid having to match the pattern too often.
7630 * The result is an array of Autopat lists, which point to AutoCmd lists:
7631 *
Bram Moolenaar462455e2017-11-10 21:53:11 +01007632 * last_autopat[0] -----------------------------+
7633 * V
Bram Moolenaar071d4272004-06-13 20:20:40 +00007634 * first_autopat[0] --> Autopat.next --> Autopat.next --> NULL
7635 * Autopat.cmds Autopat.cmds
7636 * | |
7637 * V V
7638 * AutoCmd.next AutoCmd.next
7639 * | |
7640 * V V
7641 * AutoCmd.next NULL
7642 * |
7643 * V
7644 * NULL
7645 *
Bram Moolenaar462455e2017-11-10 21:53:11 +01007646 * last_autopat[1] --------+
7647 * V
Bram Moolenaar071d4272004-06-13 20:20:40 +00007648 * first_autopat[1] --> Autopat.next --> NULL
7649 * Autopat.cmds
7650 * |
7651 * V
7652 * AutoCmd.next
7653 * |
7654 * V
7655 * NULL
7656 * etc.
7657 *
7658 * The order of AutoCmds is important, this is the order in which they were
7659 * defined and will have to be executed.
7660 */
7661typedef struct AutoCmd
7662{
7663 char_u *cmd; /* The command to be executed (NULL
7664 when command has been removed) */
7665 char nested; /* If autocommands nest here */
7666 char last; /* last command in list */
7667#ifdef FEAT_EVAL
7668 scid_T scriptID; /* script ID where defined */
7669#endif
7670 struct AutoCmd *next; /* Next AutoCmd in list */
7671} AutoCmd;
7672
7673typedef struct AutoPat
7674{
Bram Moolenaar462455e2017-11-10 21:53:11 +01007675 struct AutoPat *next; /* next AutoPat in AutoPat list; MUST
7676 * be the first entry */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007677 char_u *pat; /* pattern as typed (NULL when pattern
7678 has been removed) */
Bram Moolenaar748bf032005-02-02 23:04:36 +00007679 regprog_T *reg_prog; /* compiled regprog for pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007680 AutoCmd *cmds; /* list of commands to do */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007681 int group; /* group ID */
7682 int patlen; /* strlen() of pat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007683 int buflocal_nr; /* !=0 for buffer-local AutoPat */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007684 char allow_dirs; /* Pattern may match whole path */
7685 char last; /* last pattern for apply_autocmds() */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007686} AutoPat;
7687
7688static struct event_name
7689{
7690 char *name; /* event name */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007691 event_T event; /* event number */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007692} event_names[] =
7693{
7694 {"BufAdd", EVENT_BUFADD},
7695 {"BufCreate", EVENT_BUFADD},
7696 {"BufDelete", EVENT_BUFDELETE},
7697 {"BufEnter", EVENT_BUFENTER},
7698 {"BufFilePost", EVENT_BUFFILEPOST},
7699 {"BufFilePre", EVENT_BUFFILEPRE},
7700 {"BufHidden", EVENT_BUFHIDDEN},
7701 {"BufLeave", EVENT_BUFLEAVE},
7702 {"BufNew", EVENT_BUFNEW},
7703 {"BufNewFile", EVENT_BUFNEWFILE},
7704 {"BufRead", EVENT_BUFREADPOST},
7705 {"BufReadCmd", EVENT_BUFREADCMD},
7706 {"BufReadPost", EVENT_BUFREADPOST},
7707 {"BufReadPre", EVENT_BUFREADPRE},
7708 {"BufUnload", EVENT_BUFUNLOAD},
7709 {"BufWinEnter", EVENT_BUFWINENTER},
7710 {"BufWinLeave", EVENT_BUFWINLEAVE},
7711 {"BufWipeout", EVENT_BUFWIPEOUT},
7712 {"BufWrite", EVENT_BUFWRITEPRE},
7713 {"BufWritePost", EVENT_BUFWRITEPOST},
7714 {"BufWritePre", EVENT_BUFWRITEPRE},
7715 {"BufWriteCmd", EVENT_BUFWRITECMD},
Bram Moolenaar153b7042018-01-31 15:48:32 +01007716 {"CmdlineChanged", EVENT_CMDLINECHANGED},
Bram Moolenaarfafcf0d2017-10-19 18:35:51 +02007717 {"CmdlineEnter", EVENT_CMDLINEENTER},
7718 {"CmdlineLeave", EVENT_CMDLINELEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007719 {"CmdwinEnter", EVENT_CMDWINENTER},
7720 {"CmdwinLeave", EVENT_CMDWINLEAVE},
Bram Moolenaard5005162014-08-22 23:05:54 +02007721 {"CmdUndefined", EVENT_CMDUNDEFINED},
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007722 {"ColorScheme", EVENT_COLORSCHEME},
Bram Moolenaarcfa3cae2012-07-10 17:14:56 +02007723 {"CompleteDone", EVENT_COMPLETEDONE},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007724 {"CursorHold", EVENT_CURSORHOLD},
7725 {"CursorHoldI", EVENT_CURSORHOLDI},
7726 {"CursorMoved", EVENT_CURSORMOVED},
7727 {"CursorMovedI", EVENT_CURSORMOVEDI},
Bram Moolenaarb7407d32018-02-03 17:36:27 +01007728 {"DirChanged", EVENT_DIRCHANGED},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007729 {"EncodingChanged", EVENT_ENCODINGCHANGED},
Bram Moolenaar12a96de2018-03-11 14:44:18 +01007730 {"ExitPre", EVENT_EXITPRE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007731 {"FileEncoding", EVENT_ENCODINGCHANGED},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007732 {"FileAppendPost", EVENT_FILEAPPENDPOST},
7733 {"FileAppendPre", EVENT_FILEAPPENDPRE},
7734 {"FileAppendCmd", EVENT_FILEAPPENDCMD},
7735 {"FileChangedShell",EVENT_FILECHANGEDSHELL},
Bram Moolenaar56718732006-03-15 22:53:57 +00007736 {"FileChangedShellPost",EVENT_FILECHANGEDSHELLPOST},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007737 {"FileChangedRO", EVENT_FILECHANGEDRO},
7738 {"FileReadPost", EVENT_FILEREADPOST},
7739 {"FileReadPre", EVENT_FILEREADPRE},
7740 {"FileReadCmd", EVENT_FILEREADCMD},
7741 {"FileType", EVENT_FILETYPE},
7742 {"FileWritePost", EVENT_FILEWRITEPOST},
7743 {"FileWritePre", EVENT_FILEWRITEPRE},
7744 {"FileWriteCmd", EVENT_FILEWRITECMD},
7745 {"FilterReadPost", EVENT_FILTERREADPOST},
7746 {"FilterReadPre", EVENT_FILTERREADPRE},
7747 {"FilterWritePost", EVENT_FILTERWRITEPOST},
7748 {"FilterWritePre", EVENT_FILTERWRITEPRE},
7749 {"FocusGained", EVENT_FOCUSGAINED},
7750 {"FocusLost", EVENT_FOCUSLOST},
7751 {"FuncUndefined", EVENT_FUNCUNDEFINED},
7752 {"GUIEnter", EVENT_GUIENTER},
Bram Moolenaar265e5072006-08-29 16:13:22 +00007753 {"GUIFailed", EVENT_GUIFAILED},
Bram Moolenaar843ee412004-06-30 16:16:41 +00007754 {"InsertChange", EVENT_INSERTCHANGE},
7755 {"InsertEnter", EVENT_INSERTENTER},
7756 {"InsertLeave", EVENT_INSERTLEAVE},
Bram Moolenaare659c952011-05-19 17:25:41 +02007757 {"InsertCharPre", EVENT_INSERTCHARPRE},
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00007758 {"MenuPopup", EVENT_MENUPOPUP},
Bram Moolenaar53744302015-07-17 17:38:22 +02007759 {"OptionSet", EVENT_OPTIONSET},
Bram Moolenaar7c626922005-02-07 22:01:03 +00007760 {"QuickFixCmdPost", EVENT_QUICKFIXCMDPOST},
7761 {"QuickFixCmdPre", EVENT_QUICKFIXCMDPRE},
Bram Moolenaar3b53dfb2012-06-06 18:03:07 +02007762 {"QuitPre", EVENT_QUITPRE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007763 {"RemoteReply", EVENT_REMOTEREPLY},
Bram Moolenaar9372a112005-12-06 19:59:18 +00007764 {"SessionLoadPost", EVENT_SESSIONLOADPOST},
Bram Moolenaar5c4bab02006-03-10 21:37:46 +00007765 {"ShellCmdPost", EVENT_SHELLCMDPOST},
7766 {"ShellFilterPost", EVENT_SHELLFILTERPOST},
Bram Moolenaara2031822006-03-07 22:29:51 +00007767 {"SourcePre", EVENT_SOURCEPRE},
Bram Moolenaar8dd1aa52007-01-16 20:33:19 +00007768 {"SourceCmd", EVENT_SOURCECMD},
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00007769 {"SpellFileMissing",EVENT_SPELLFILEMISSING},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007770 {"StdinReadPost", EVENT_STDINREADPOST},
7771 {"StdinReadPre", EVENT_STDINREADPRE},
Bram Moolenaarb815dac2005-12-07 20:59:24 +00007772 {"SwapExists", EVENT_SWAPEXISTS},
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00007773 {"Syntax", EVENT_SYNTAX},
Bram Moolenaarc917da42016-07-19 22:31:36 +02007774 {"TabNew", EVENT_TABNEW},
Bram Moolenaar12c11d52016-07-19 23:13:03 +02007775 {"TabClosed", EVENT_TABCLOSED},
Bram Moolenaar70836c82006-02-20 21:28:49 +00007776 {"TabEnter", EVENT_TABENTER},
7777 {"TabLeave", EVENT_TABLEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007778 {"TermChanged", EVENT_TERMCHANGED},
Bram Moolenaarb852c3e2018-03-11 16:55:36 +01007779 {"TerminalOpen", EVENT_TERMINALOPEN},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007780 {"TermResponse", EVENT_TERMRESPONSE},
Bram Moolenaar186628f2013-03-19 13:33:23 +01007781 {"TextChanged", EVENT_TEXTCHANGED},
7782 {"TextChangedI", EVENT_TEXTCHANGEDI},
Bram Moolenaar5a093432018-02-10 18:15:19 +01007783 {"TextChangedP", EVENT_TEXTCHANGEDP},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007784 {"User", EVENT_USER},
7785 {"VimEnter", EVENT_VIMENTER},
7786 {"VimLeave", EVENT_VIMLEAVE},
7787 {"VimLeavePre", EVENT_VIMLEAVEPRE},
Bram Moolenaarc917da42016-07-19 22:31:36 +02007788 {"WinNew", EVENT_WINNEW},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007789 {"WinEnter", EVENT_WINENTER},
7790 {"WinLeave", EVENT_WINLEAVE},
Bram Moolenaar56718732006-03-15 22:53:57 +00007791 {"VimResized", EVENT_VIMRESIZED},
Bram Moolenaar7e1652c2017-12-16 18:27:02 +01007792 {"TextYankPost", EVENT_TEXTYANKPOST},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007793 {NULL, (event_T)0}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007794};
7795
7796static AutoPat *first_autopat[NUM_EVENTS] =
7797{
7798 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7799 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7800 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7801 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00007802 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaar53744302015-07-17 17:38:22 +02007803 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007804};
7805
Bram Moolenaar462455e2017-11-10 21:53:11 +01007806static AutoPat *last_autopat[NUM_EVENTS] =
7807{
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 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7812 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7813 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
7814};
7815
Bram Moolenaar071d4272004-06-13 20:20:40 +00007816/*
7817 * struct used to keep status while executing autocommands for an event.
7818 */
7819typedef struct AutoPatCmd
7820{
7821 AutoPat *curpat; /* next AutoPat to examine */
7822 AutoCmd *nextcmd; /* next AutoCmd to execute */
7823 int group; /* group being used */
7824 char_u *fname; /* fname to match with */
7825 char_u *sfname; /* sfname to match with */
7826 char_u *tail; /* tail of fname */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007827 event_T event; /* current event */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007828 int arg_bufnr; /* initially equal to <abuf>, set to zero when
7829 buf is deleted */
7830 struct AutoPatCmd *next; /* chain of active apc-s for auto-invalidation*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00007831} AutoPatCmd;
7832
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007833static AutoPatCmd *active_apc_list = NULL; /* stack of active autocommands */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007834
Bram Moolenaar071d4272004-06-13 20:20:40 +00007835/*
7836 * augroups stores a list of autocmd group names.
7837 */
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007838static garray_T augroups = {0, 0, sizeof(char_u *), 10, NULL};
Bram Moolenaar071d4272004-06-13 20:20:40 +00007839#define AUGROUP_NAME(i) (((char_u **)augroups.ga_data)[i])
Bram Moolenaarb62cc362016-09-03 16:43:53 +02007840/* use get_deleted_augroup() to get this */
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02007841static char_u *deleted_augroup = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007842
7843/*
7844 * The ID of the current group. Group 0 is the default one.
7845 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007846static int current_augroup = AUGROUP_DEFAULT;
7847
7848static int au_need_clean = FALSE; /* need to delete marked patterns */
7849
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007850static void show_autocmd(AutoPat *ap, event_T event);
7851static void au_remove_pat(AutoPat *ap);
7852static void au_remove_cmds(AutoPat *ap);
7853static void au_cleanup(void);
7854static int au_new_group(char_u *name);
7855static void au_del_group(char_u *name);
7856static event_T event_name2nr(char_u *start, char_u **end);
7857static char_u *event_nr2name(event_T event);
7858static char_u *find_end_event(char_u *arg, int have_group);
7859static int event_ignored(event_T event);
7860static int au_get_grouparg(char_u **argp);
7861static int do_autocmd_event(event_T event, char_u *pat, int nested, char_u *cmd, int forceit, int group);
7862static int apply_autocmds_group(event_T event, char_u *fname, char_u *fname_io, int force, int group, buf_T *buf, exarg_T *eap);
7863static void auto_next_pat(AutoPatCmd *apc, int stop_at_last);
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007864static 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 +00007865
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007866
Bram Moolenaar754b5602006-02-09 23:53:20 +00007867static event_T last_event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007868static int last_group;
Bram Moolenaar78ab3312007-09-29 12:16:41 +00007869static int autocmd_blocked = 0; /* block all autocmds */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007870
Bram Moolenaarb62cc362016-09-03 16:43:53 +02007871 static char_u *
7872get_deleted_augroup(void)
7873{
7874 if (deleted_augroup == NULL)
7875 deleted_augroup = (char_u *)_("--Deleted--");
7876 return deleted_augroup;
7877}
7878
Bram Moolenaar071d4272004-06-13 20:20:40 +00007879/*
7880 * Show the autocommands for one AutoPat.
7881 */
7882 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007883show_autocmd(AutoPat *ap, event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007884{
7885 AutoCmd *ac;
7886
7887 /* Check for "got_int" (here and at various places below), which is set
7888 * when "q" has been hit for the "--more--" prompt */
7889 if (got_int)
7890 return;
7891 if (ap->pat == NULL) /* pattern has been removed */
7892 return;
7893
7894 msg_putchar('\n');
7895 if (got_int)
7896 return;
7897 if (event != last_event || ap->group != last_group)
7898 {
7899 if (ap->group != AUGROUP_DEFAULT)
7900 {
7901 if (AUGROUP_NAME(ap->group) == NULL)
Bram Moolenaar8820b482017-03-16 17:23:31 +01007902 msg_puts_attr(get_deleted_augroup(), HL_ATTR(HLF_E));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007903 else
Bram Moolenaar8820b482017-03-16 17:23:31 +01007904 msg_puts_attr(AUGROUP_NAME(ap->group), HL_ATTR(HLF_T));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007905 msg_puts((char_u *)" ");
7906 }
Bram Moolenaar8820b482017-03-16 17:23:31 +01007907 msg_puts_attr(event_nr2name(event), HL_ATTR(HLF_T));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007908 last_event = event;
7909 last_group = ap->group;
7910 msg_putchar('\n');
7911 if (got_int)
7912 return;
7913 }
7914 msg_col = 4;
7915 msg_outtrans(ap->pat);
7916
7917 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7918 {
7919 if (ac->cmd != NULL) /* skip removed commands */
7920 {
7921 if (msg_col >= 14)
7922 msg_putchar('\n');
7923 msg_col = 14;
7924 if (got_int)
7925 return;
7926 msg_outtrans(ac->cmd);
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00007927#ifdef FEAT_EVAL
7928 if (p_verbose > 0)
7929 last_set_msg(ac->scriptID);
7930#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007931 if (got_int)
7932 return;
7933 if (ac->next != NULL)
7934 {
7935 msg_putchar('\n');
7936 if (got_int)
7937 return;
7938 }
7939 }
7940 }
7941}
7942
7943/*
7944 * Mark an autocommand pattern for deletion.
7945 */
7946 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007947au_remove_pat(AutoPat *ap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007948{
Bram Moolenaard23a8232018-02-10 18:45:26 +01007949 VIM_CLEAR(ap->pat);
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007950 ap->buflocal_nr = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007951 au_need_clean = TRUE;
7952}
7953
7954/*
7955 * Mark all commands for a pattern for deletion.
7956 */
7957 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007958au_remove_cmds(AutoPat *ap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007959{
7960 AutoCmd *ac;
7961
7962 for (ac = ap->cmds; ac != NULL; ac = ac->next)
Bram Moolenaard23a8232018-02-10 18:45:26 +01007963 VIM_CLEAR(ac->cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007964 au_need_clean = TRUE;
7965}
7966
7967/*
7968 * Cleanup autocommands and patterns that have been deleted.
7969 * This is only done when not executing autocommands.
7970 */
7971 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007972au_cleanup(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007973{
7974 AutoPat *ap, **prev_ap;
7975 AutoCmd *ac, **prev_ac;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007976 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007977
7978 if (autocmd_busy || !au_need_clean)
7979 return;
7980
7981 /* loop over all events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007982 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7983 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007984 {
7985 /* loop over all autocommand patterns */
7986 prev_ap = &(first_autopat[(int)event]);
7987 for (ap = *prev_ap; ap != NULL; ap = *prev_ap)
7988 {
7989 /* loop over all commands for this pattern */
7990 prev_ac = &(ap->cmds);
7991 for (ac = *prev_ac; ac != NULL; ac = *prev_ac)
7992 {
7993 /* remove the command if the pattern is to be deleted or when
7994 * the command has been marked for deletion */
7995 if (ap->pat == NULL || ac->cmd == NULL)
7996 {
7997 *prev_ac = ac->next;
7998 vim_free(ac->cmd);
7999 vim_free(ac);
8000 }
8001 else
8002 prev_ac = &(ac->next);
8003 }
8004
8005 /* remove the pattern if it has been marked for deletion */
8006 if (ap->pat == NULL)
8007 {
Bram Moolenaar462455e2017-11-10 21:53:11 +01008008 if (ap->next == NULL)
8009 {
8010 if (prev_ap == &(first_autopat[(int)event]))
8011 last_autopat[(int)event] = NULL;
8012 else
8013 /* this depends on the "next" field being the first in
8014 * the struct */
8015 last_autopat[(int)event] = (AutoPat *)prev_ap;
8016 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008017 *prev_ap = ap->next;
Bram Moolenaar473de612013-06-08 18:19:48 +02008018 vim_regfree(ap->reg_prog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008019 vim_free(ap);
8020 }
8021 else
8022 prev_ap = &(ap->next);
8023 }
8024 }
8025
8026 au_need_clean = FALSE;
8027}
8028
8029/*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008030 * Called when buffer is freed, to remove/invalidate related buffer-local
8031 * autocmds.
8032 */
8033 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008034aubuflocal_remove(buf_T *buf)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008035{
8036 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008037 event_T event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008038 AutoPatCmd *apc;
8039
8040 /* invalidate currently executing autocommands */
8041 for (apc = active_apc_list; apc; apc = apc->next)
8042 if (buf->b_fnum == apc->arg_bufnr)
8043 apc->arg_bufnr = 0;
8044
8045 /* invalidate buflocals looping through events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008046 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8047 event = (event_T)((int)event + 1))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008048 /* loop over all autocommand patterns */
8049 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8050 if (ap->buflocal_nr == buf->b_fnum)
8051 {
8052 au_remove_pat(ap);
8053 if (p_verbose >= 6)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00008054 {
8055 verbose_enter();
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008056 smsg((char_u *)
8057 _("auto-removing autocommand: %s <buffer=%d>"),
8058 event_nr2name(event), buf->b_fnum);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00008059 verbose_leave();
8060 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008061 }
8062 au_cleanup();
8063}
8064
8065/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008066 * Add an autocmd group name.
8067 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
8068 */
8069 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008070au_new_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008071{
8072 int i;
8073
8074 i = au_find_group(name);
8075 if (i == AUGROUP_ERROR) /* the group doesn't exist yet, add it */
8076 {
8077 /* First try using a free entry. */
8078 for (i = 0; i < augroups.ga_len; ++i)
8079 if (AUGROUP_NAME(i) == NULL)
8080 break;
8081 if (i == augroups.ga_len && ga_grow(&augroups, 1) == FAIL)
8082 return AUGROUP_ERROR;
8083
8084 AUGROUP_NAME(i) = vim_strsave(name);
8085 if (AUGROUP_NAME(i) == NULL)
8086 return AUGROUP_ERROR;
8087 if (i == augroups.ga_len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008088 ++augroups.ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008089 }
8090
8091 return i;
8092}
8093
8094 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008095au_del_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008096{
8097 int i;
8098
8099 i = au_find_group(name);
8100 if (i == AUGROUP_ERROR) /* the group doesn't exist */
8101 EMSG2(_("E367: No such group: \"%s\""), name);
Bram Moolenaarde653f02016-09-03 16:59:06 +02008102 else if (i == current_augroup)
8103 EMSG(_("E936: Cannot delete the current group"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008104 else
8105 {
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008106 event_T event;
8107 AutoPat *ap;
8108 int in_use = FALSE;
8109
8110 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8111 event = (event_T)((int)event + 1))
8112 {
8113 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
Bram Moolenaar5c809082016-09-01 16:21:48 +02008114 if (ap->group == i && ap->pat != NULL)
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008115 {
8116 give_warning((char_u *)_("W19: Deleting augroup that is still in use"), TRUE);
8117 in_use = TRUE;
8118 event = NUM_EVENTS;
8119 break;
8120 }
8121 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008122 vim_free(AUGROUP_NAME(i));
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008123 if (in_use)
8124 {
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008125 AUGROUP_NAME(i) = get_deleted_augroup();
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008126 }
8127 else
8128 AUGROUP_NAME(i) = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008129 }
8130}
8131
8132/*
8133 * Find the ID of an autocmd group name.
8134 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
8135 */
8136 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008137au_find_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008138{
8139 int i;
8140
8141 for (i = 0; i < augroups.ga_len; ++i)
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008142 if (AUGROUP_NAME(i) != NULL && AUGROUP_NAME(i) != get_deleted_augroup()
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008143 && STRCMP(AUGROUP_NAME(i), name) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008144 return i;
8145 return AUGROUP_ERROR;
8146}
8147
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008148/*
8149 * Return TRUE if augroup "name" exists.
8150 */
8151 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008152au_has_group(char_u *name)
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008153{
8154 return au_find_group(name) != AUGROUP_ERROR;
8155}
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008156
Bram Moolenaar071d4272004-06-13 20:20:40 +00008157/*
8158 * ":augroup {name}".
8159 */
8160 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008161do_augroup(char_u *arg, int del_group)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008162{
8163 int i;
8164
8165 if (del_group)
8166 {
8167 if (*arg == NUL)
8168 EMSG(_(e_argreq));
8169 else
8170 au_del_group(arg);
8171 }
8172 else if (STRICMP(arg, "end") == 0) /* ":aug end": back to group 0 */
8173 current_augroup = AUGROUP_DEFAULT;
8174 else if (*arg) /* ":aug xxx": switch to group xxx */
8175 {
8176 i = au_new_group(arg);
8177 if (i != AUGROUP_ERROR)
8178 current_augroup = i;
8179 }
8180 else /* ":aug": list the group names */
8181 {
8182 msg_start();
8183 for (i = 0; i < augroups.ga_len; ++i)
8184 {
8185 if (AUGROUP_NAME(i) != NULL)
8186 {
8187 msg_puts(AUGROUP_NAME(i));
8188 msg_puts((char_u *)" ");
8189 }
8190 }
8191 msg_clr_eos();
8192 msg_end();
8193 }
8194}
8195
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008196#if defined(EXITFREE) || defined(PROTO)
8197 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008198free_all_autocmds(void)
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008199{
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008200 int i;
8201 char_u *s;
8202
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008203 for (current_augroup = -1; current_augroup < augroups.ga_len;
8204 ++current_augroup)
8205 do_autocmd((char_u *)"", TRUE);
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008206
8207 for (i = 0; i < augroups.ga_len; ++i)
8208 {
8209 s = ((char_u **)(augroups.ga_data))[i];
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008210 if (s != get_deleted_augroup())
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008211 vim_free(s);
8212 }
8213 ga_clear(&augroups);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008214}
8215#endif
8216
Bram Moolenaar071d4272004-06-13 20:20:40 +00008217/*
8218 * Return the event number for event name "start".
8219 * Return NUM_EVENTS if the event name was not found.
8220 * Return a pointer to the next event name in "end".
8221 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008222 static event_T
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008223event_name2nr(char_u *start, char_u **end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008224{
8225 char_u *p;
8226 int i;
8227 int len;
8228
Bram Moolenaare99e8442016-07-26 20:43:40 +02008229 /* the event name ends with end of line, '|', a blank or a comma */
Bram Moolenaar1c465442017-03-12 20:10:05 +01008230 for (p = start; *p && !VIM_ISWHITE(*p) && *p != ',' && *p != '|'; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008231 ;
8232 for (i = 0; event_names[i].name != NULL; ++i)
8233 {
8234 len = (int)STRLEN(event_names[i].name);
8235 if (len == p - start && STRNICMP(event_names[i].name, start, len) == 0)
8236 break;
8237 }
8238 if (*p == ',')
8239 ++p;
8240 *end = p;
8241 if (event_names[i].name == NULL)
8242 return NUM_EVENTS;
8243 return event_names[i].event;
8244}
8245
8246/*
8247 * Return the name for event "event".
8248 */
8249 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008250event_nr2name(event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008251{
8252 int i;
8253
8254 for (i = 0; event_names[i].name != NULL; ++i)
8255 if (event_names[i].event == event)
8256 return (char_u *)event_names[i].name;
8257 return (char_u *)"Unknown";
8258}
8259
8260/*
8261 * Scan over the events. "*" stands for all events.
8262 */
8263 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008264find_end_event(
8265 char_u *arg,
8266 int have_group) /* TRUE when group name was found */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008267{
8268 char_u *pat;
8269 char_u *p;
8270
8271 if (*arg == '*')
8272 {
Bram Moolenaar1c465442017-03-12 20:10:05 +01008273 if (arg[1] && !VIM_ISWHITE(arg[1]))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008274 {
8275 EMSG2(_("E215: Illegal character after *: %s"), arg);
8276 return NULL;
8277 }
8278 pat = arg + 1;
8279 }
8280 else
8281 {
Bram Moolenaar1c465442017-03-12 20:10:05 +01008282 for (pat = arg; *pat && *pat != '|' && !VIM_ISWHITE(*pat); pat = p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008283 {
8284 if ((int)event_name2nr(pat, &p) >= (int)NUM_EVENTS)
8285 {
8286 if (have_group)
8287 EMSG2(_("E216: No such event: %s"), pat);
8288 else
8289 EMSG2(_("E216: No such group or event: %s"), pat);
8290 return NULL;
8291 }
8292 }
8293 }
8294 return pat;
8295}
8296
8297/*
8298 * Return TRUE if "event" is included in 'eventignore'.
8299 */
8300 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008301event_ignored(event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008302{
8303 char_u *p = p_ei;
8304
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008305 while (*p != NUL)
8306 {
8307 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8308 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008309 if (event_name2nr(p, &p) == event)
8310 return TRUE;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008311 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008312
8313 return FALSE;
8314}
8315
8316/*
8317 * Return OK when the contents of p_ei is valid, FAIL otherwise.
8318 */
8319 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008320check_ei(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008321{
8322 char_u *p = p_ei;
8323
Bram Moolenaar071d4272004-06-13 20:20:40 +00008324 while (*p)
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008325 {
8326 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8327 {
8328 p += 3;
8329 if (*p == ',')
8330 ++p;
8331 }
8332 else if (event_name2nr(p, &p) == NUM_EVENTS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008333 return FAIL;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008334 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008335
8336 return OK;
8337}
8338
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008339# if defined(FEAT_SYN_HL) || defined(PROTO)
8340
8341/*
8342 * Add "what" to 'eventignore' to skip loading syntax highlighting for every
8343 * buffer loaded into the window. "what" must start with a comma.
8344 * Returns the old value of 'eventignore' in allocated memory.
8345 */
8346 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008347au_event_disable(char *what)
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008348{
8349 char_u *new_ei;
8350 char_u *save_ei;
8351
8352 save_ei = vim_strsave(p_ei);
8353 if (save_ei != NULL)
8354 {
Bram Moolenaara5792f52005-11-23 21:25:05 +00008355 new_ei = vim_strnsave(p_ei, (int)(STRLEN(p_ei) + STRLEN(what)));
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008356 if (new_ei != NULL)
8357 {
Bram Moolenaar8cac9fd2010-03-02 12:48:05 +01008358 if (*what == ',' && *p_ei == NUL)
8359 STRCPY(new_ei, what + 1);
8360 else
8361 STRCAT(new_ei, what);
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008362 set_string_option_direct((char_u *)"ei", -1, new_ei,
8363 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008364 vim_free(new_ei);
8365 }
8366 }
8367 return save_ei;
8368}
8369
8370 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008371au_event_restore(char_u *old_ei)
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008372{
8373 if (old_ei != NULL)
8374 {
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008375 set_string_option_direct((char_u *)"ei", -1, old_ei,
8376 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008377 vim_free(old_ei);
8378 }
8379}
8380# endif /* FEAT_SYN_HL */
8381
Bram Moolenaar071d4272004-06-13 20:20:40 +00008382/*
8383 * do_autocmd() -- implements the :autocmd command. Can be used in the
8384 * following ways:
8385 *
8386 * :autocmd <event> <pat> <cmd> Add <cmd> to the list of commands that
8387 * will be automatically executed for <event>
8388 * when editing a file matching <pat>, in
8389 * the current group.
8390 * :autocmd <event> <pat> Show the auto-commands associated with
8391 * <event> and <pat>.
8392 * :autocmd <event> Show the auto-commands associated with
8393 * <event>.
8394 * :autocmd Show all auto-commands.
8395 * :autocmd! <event> <pat> <cmd> Remove all auto-commands associated with
8396 * <event> and <pat>, and add the command
8397 * <cmd>, for the current group.
8398 * :autocmd! <event> <pat> Remove all auto-commands associated with
8399 * <event> and <pat> for the current group.
8400 * :autocmd! <event> Remove all auto-commands associated with
8401 * <event> for the current group.
8402 * :autocmd! Remove ALL auto-commands for the current
8403 * group.
8404 *
8405 * Multiple events and patterns may be given separated by commas. Here are
8406 * some examples:
8407 * :autocmd bufread,bufenter *.c,*.h set tw=0 smartindent noic
8408 * :autocmd bufleave * set tw=79 nosmartindent ic infercase
8409 *
8410 * :autocmd * *.c show all autocommands for *.c files.
Bram Moolenaard35f9712005-12-18 22:02:33 +00008411 *
8412 * Mostly a {group} argument can optionally appear before <event>.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008413 */
8414 void
Bram Moolenaare99e8442016-07-26 20:43:40 +02008415do_autocmd(char_u *arg_in, int forceit)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008416{
Bram Moolenaare99e8442016-07-26 20:43:40 +02008417 char_u *arg = arg_in;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008418 char_u *pat;
8419 char_u *envpat = NULL;
8420 char_u *cmd;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008421 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008422 int need_free = FALSE;
8423 int nested = FALSE;
8424 int group;
8425
Bram Moolenaare99e8442016-07-26 20:43:40 +02008426 if (*arg == '|')
8427 {
8428 arg = (char_u *)"";
8429 group = AUGROUP_ALL; /* no argument, use all groups */
8430 }
8431 else
8432 {
8433 /*
8434 * Check for a legal group name. If not, use AUGROUP_ALL.
8435 */
8436 group = au_get_grouparg(&arg);
8437 if (arg == NULL) /* out of memory */
8438 return;
8439 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008440
8441 /*
8442 * Scan over the events.
8443 * If we find an illegal name, return here, don't do anything.
8444 */
8445 pat = find_end_event(arg, group != AUGROUP_ALL);
8446 if (pat == NULL)
8447 return;
8448
Bram Moolenaar071d4272004-06-13 20:20:40 +00008449 pat = skipwhite(pat);
Bram Moolenaare99e8442016-07-26 20:43:40 +02008450 if (*pat == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008451 {
Bram Moolenaare99e8442016-07-26 20:43:40 +02008452 pat = (char_u *)"";
8453 cmd = (char_u *)"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00008454 }
Bram Moolenaare99e8442016-07-26 20:43:40 +02008455 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00008456 {
Bram Moolenaare99e8442016-07-26 20:43:40 +02008457 /*
8458 * Scan over the pattern. Put a NUL at the end.
8459 */
8460 cmd = pat;
Bram Moolenaar1c465442017-03-12 20:10:05 +01008461 while (*cmd && (!VIM_ISWHITE(*cmd) || cmd[-1] == '\\'))
Bram Moolenaare99e8442016-07-26 20:43:40 +02008462 cmd++;
8463 if (*cmd)
8464 *cmd++ = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008465
Bram Moolenaare99e8442016-07-26 20:43:40 +02008466 /* Expand environment variables in the pattern. Set 'shellslash', we want
8467 * forward slashes here. */
8468 if (vim_strchr(pat, '$') != NULL || vim_strchr(pat, '~') != NULL)
8469 {
8470#ifdef BACKSLASH_IN_FILENAME
8471 int p_ssl_save = p_ssl;
8472
8473 p_ssl = TRUE;
8474#endif
8475 envpat = expand_env_save(pat);
8476#ifdef BACKSLASH_IN_FILENAME
8477 p_ssl = p_ssl_save;
8478#endif
8479 if (envpat != NULL)
8480 pat = envpat;
8481 }
8482
8483 /*
8484 * Check for "nested" flag.
8485 */
8486 cmd = skipwhite(cmd);
Bram Moolenaar1c465442017-03-12 20:10:05 +01008487 if (*cmd != NUL && STRNCMP(cmd, "nested", 6) == 0 && VIM_ISWHITE(cmd[6]))
Bram Moolenaare99e8442016-07-26 20:43:40 +02008488 {
8489 nested = TRUE;
8490 cmd = skipwhite(cmd + 6);
8491 }
8492
8493 /*
8494 * Find the start of the commands.
8495 * Expand <sfile> in it.
8496 */
8497 if (*cmd != NUL)
8498 {
8499 cmd = expand_sfile(cmd);
8500 if (cmd == NULL) /* some error */
8501 return;
8502 need_free = TRUE;
8503 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008504 }
8505
8506 /*
8507 * Print header when showing autocommands.
8508 */
8509 if (!forceit && *cmd == NUL)
8510 {
8511 /* Highlight title */
8512 MSG_PUTS_TITLE(_("\n--- Auto-Commands ---"));
8513 }
8514
8515 /*
8516 * Loop over the events.
8517 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008518 last_event = (event_T)-1; /* for listing the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008519 last_group = AUGROUP_ERROR; /* for listing the group name */
Bram Moolenaare99e8442016-07-26 20:43:40 +02008520 if (*arg == '*' || *arg == NUL || *arg == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008521 {
Bram Moolenaar754b5602006-02-09 23:53:20 +00008522 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8523 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008524 if (do_autocmd_event(event, pat,
8525 nested, cmd, forceit, group) == FAIL)
8526 break;
8527 }
8528 else
8529 {
Bram Moolenaar1c465442017-03-12 20:10:05 +01008530 while (*arg && *arg != '|' && !VIM_ISWHITE(*arg))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008531 if (do_autocmd_event(event_name2nr(arg, &arg), pat,
8532 nested, cmd, forceit, group) == FAIL)
8533 break;
8534 }
8535
8536 if (need_free)
8537 vim_free(cmd);
8538 vim_free(envpat);
8539}
8540
8541/*
8542 * Find the group ID in a ":autocmd" or ":doautocmd" argument.
8543 * The "argp" argument is advanced to the following argument.
8544 *
8545 * Returns the group ID, AUGROUP_ERROR for error (out of memory).
8546 */
8547 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008548au_get_grouparg(char_u **argp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008549{
8550 char_u *group_name;
8551 char_u *p;
8552 char_u *arg = *argp;
8553 int group = AUGROUP_ALL;
8554
Bram Moolenaar1c465442017-03-12 20:10:05 +01008555 for (p = arg; *p && !VIM_ISWHITE(*p) && *p != '|'; ++p)
Bram Moolenaare99e8442016-07-26 20:43:40 +02008556 ;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008557 if (p > arg)
8558 {
8559 group_name = vim_strnsave(arg, (int)(p - arg));
8560 if (group_name == NULL) /* out of memory */
8561 return AUGROUP_ERROR;
8562 group = au_find_group(group_name);
8563 if (group == AUGROUP_ERROR)
8564 group = AUGROUP_ALL; /* no match, use all groups */
8565 else
8566 *argp = skipwhite(p); /* match, skip over group name */
8567 vim_free(group_name);
8568 }
8569 return group;
8570}
8571
8572/*
8573 * do_autocmd() for one event.
8574 * If *pat == NUL do for all patterns.
8575 * If *cmd == NUL show entries.
8576 * If forceit == TRUE delete entries.
8577 * If group is not AUGROUP_ALL, only use this group.
8578 */
8579 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008580do_autocmd_event(
8581 event_T event,
8582 char_u *pat,
8583 int nested,
8584 char_u *cmd,
8585 int forceit,
8586 int group)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008587{
8588 AutoPat *ap;
8589 AutoPat **prev_ap;
8590 AutoCmd *ac;
8591 AutoCmd **prev_ac;
8592 int brace_level;
8593 char_u *endpat;
8594 int findgroup;
8595 int allgroups;
8596 int patlen;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00008597 int is_buflocal;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008598 int buflocal_nr;
8599 char_u buflocal_pat[25]; /* for "<buffer=X>" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008600
8601 if (group == AUGROUP_ALL)
8602 findgroup = current_augroup;
8603 else
8604 findgroup = group;
8605 allgroups = (group == AUGROUP_ALL && !forceit && *cmd == NUL);
8606
8607 /*
8608 * Show or delete all patterns for an event.
8609 */
8610 if (*pat == NUL)
8611 {
8612 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8613 {
8614 if (forceit) /* delete the AutoPat, if it's in the current group */
8615 {
8616 if (ap->group == findgroup)
8617 au_remove_pat(ap);
8618 }
8619 else if (group == AUGROUP_ALL || ap->group == group)
8620 show_autocmd(ap, event);
8621 }
8622 }
8623
8624 /*
8625 * Loop through all the specified patterns.
8626 */
8627 for ( ; *pat; pat = (*endpat == ',' ? endpat + 1 : endpat))
8628 {
8629 /*
8630 * Find end of the pattern.
8631 * Watch out for a comma in braces, like "*.\{obj,o\}".
8632 */
8633 brace_level = 0;
8634 for (endpat = pat; *endpat && (*endpat != ',' || brace_level
Bram Moolenaar6b9be1b2015-07-28 13:33:45 +02008635 || (endpat > pat && endpat[-1] == '\\')); ++endpat)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008636 {
8637 if (*endpat == '{')
8638 brace_level++;
8639 else if (*endpat == '}')
8640 brace_level--;
8641 }
8642 if (pat == endpat) /* ignore single comma */
8643 continue;
8644 patlen = (int)(endpat - pat);
8645
8646 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008647 * detect special <buflocal[=X]> buffer-local patterns
8648 */
8649 is_buflocal = FALSE;
8650 buflocal_nr = 0;
8651
Bram Moolenaar1e997822015-02-17 16:04:57 +01008652 if (patlen >= 8 && STRNCMP(pat, "<buffer", 7) == 0
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008653 && pat[patlen - 1] == '>')
8654 {
Bram Moolenaar1e997822015-02-17 16:04:57 +01008655 /* "<buffer...>": Error will be printed only for addition.
8656 * printing and removing will proceed silently. */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008657 is_buflocal = TRUE;
8658 if (patlen == 8)
Bram Moolenaar1e997822015-02-17 16:04:57 +01008659 /* "<buffer>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008660 buflocal_nr = curbuf->b_fnum;
8661 else if (patlen > 9 && pat[7] == '=')
8662 {
Bram Moolenaar1e997822015-02-17 16:04:57 +01008663 if (patlen == 13 && STRNICMP(pat, "<buffer=abuf>", 13) == 0)
8664 /* "<buffer=abuf>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008665 buflocal_nr = autocmd_bufnr;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008666 else if (skipdigits(pat + 8) == pat + patlen - 1)
Bram Moolenaar1e997822015-02-17 16:04:57 +01008667 /* "<buffer=123>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008668 buflocal_nr = atoi((char *)pat + 8);
8669 }
8670 }
8671
8672 if (is_buflocal)
8673 {
8674 /* normalize pat into standard "<buffer>#N" form */
8675 sprintf((char *)buflocal_pat, "<buffer=%d>", buflocal_nr);
8676 pat = buflocal_pat; /* can modify pat and patlen */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008677 patlen = (int)STRLEN(buflocal_pat); /* but not endpat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008678 }
8679
8680 /*
Bram Moolenaar462455e2017-11-10 21:53:11 +01008681 * Find AutoPat entries with this pattern. When adding a command it
8682 * always goes at or after the last one, so start at the end.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008683 */
Bram Moolenaar462455e2017-11-10 21:53:11 +01008684 if (!forceit && *cmd != NUL && last_autopat[(int)event] != NULL)
8685 prev_ap = &last_autopat[(int)event];
8686 else
8687 prev_ap = &first_autopat[(int)event];
Bram Moolenaar071d4272004-06-13 20:20:40 +00008688 while ((ap = *prev_ap) != NULL)
8689 {
8690 if (ap->pat != NULL)
8691 {
8692 /* Accept a pattern when:
8693 * - a group was specified and it's that group, or a group was
8694 * not specified and it's the current group, or a group was
8695 * not specified and we are listing
8696 * - the length of the pattern matches
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008697 * - the pattern matches.
8698 * For <buffer[=X]>, this condition works because we normalize
8699 * all buffer-local patterns.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008700 */
8701 if ((allgroups || ap->group == findgroup)
8702 && ap->patlen == patlen
8703 && STRNCMP(pat, ap->pat, patlen) == 0)
8704 {
8705 /*
8706 * Remove existing autocommands.
8707 * If adding any new autocmd's for this AutoPat, don't
8708 * delete the pattern from the autopat list, append to
8709 * this list.
8710 */
8711 if (forceit)
8712 {
8713 if (*cmd != NUL && ap->next == NULL)
8714 {
8715 au_remove_cmds(ap);
8716 break;
8717 }
8718 au_remove_pat(ap);
8719 }
8720
8721 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008722 * Show autocmd's for this autopat, or buflocals <buffer=X>
Bram Moolenaar071d4272004-06-13 20:20:40 +00008723 */
8724 else if (*cmd == NUL)
8725 show_autocmd(ap, event);
8726
8727 /*
8728 * Add autocmd to this autopat, if it's the last one.
8729 */
8730 else if (ap->next == NULL)
8731 break;
8732 }
8733 }
8734 prev_ap = &ap->next;
8735 }
8736
8737 /*
8738 * Add a new command.
8739 */
8740 if (*cmd != NUL)
8741 {
8742 /*
8743 * If the pattern we want to add a command to does appear at the
8744 * end of the list (or not is not in the list at all), add the
8745 * pattern at the end of the list.
8746 */
8747 if (ap == NULL)
8748 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008749 /* refuse to add buffer-local ap if buffer number is invalid */
8750 if (is_buflocal && (buflocal_nr == 0
8751 || buflist_findnr(buflocal_nr) == NULL))
8752 {
8753 EMSGN(_("E680: <buffer=%d>: invalid buffer number "),
8754 buflocal_nr);
8755 return FAIL;
8756 }
8757
Bram Moolenaar071d4272004-06-13 20:20:40 +00008758 ap = (AutoPat *)alloc((unsigned)sizeof(AutoPat));
8759 if (ap == NULL)
8760 return FAIL;
8761 ap->pat = vim_strnsave(pat, patlen);
8762 ap->patlen = patlen;
8763 if (ap->pat == NULL)
8764 {
8765 vim_free(ap);
8766 return FAIL;
8767 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008768
8769 if (is_buflocal)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008770 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008771 ap->buflocal_nr = buflocal_nr;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008772 ap->reg_prog = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008773 }
8774 else
8775 {
Bram Moolenaar748bf032005-02-02 23:04:36 +00008776 char_u *reg_pat;
8777
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008778 ap->buflocal_nr = 0;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008779 reg_pat = file_pat_to_reg_pat(pat, endpat,
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008780 &ap->allow_dirs, TRUE);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008781 if (reg_pat != NULL)
8782 ap->reg_prog = vim_regcomp(reg_pat, RE_MAGIC);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008783 vim_free(reg_pat);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008784 if (reg_pat == NULL || ap->reg_prog == NULL)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008785 {
8786 vim_free(ap->pat);
8787 vim_free(ap);
8788 return FAIL;
8789 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008790 }
8791 ap->cmds = NULL;
8792 *prev_ap = ap;
Bram Moolenaar462455e2017-11-10 21:53:11 +01008793 last_autopat[(int)event] = ap;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008794 ap->next = NULL;
8795 if (group == AUGROUP_ALL)
8796 ap->group = current_augroup;
8797 else
8798 ap->group = group;
8799 }
8800
8801 /*
8802 * Add the autocmd at the end of the AutoCmd list.
8803 */
8804 prev_ac = &(ap->cmds);
8805 while ((ac = *prev_ac) != NULL)
8806 prev_ac = &ac->next;
8807 ac = (AutoCmd *)alloc((unsigned)sizeof(AutoCmd));
8808 if (ac == NULL)
8809 return FAIL;
8810 ac->cmd = vim_strsave(cmd);
8811#ifdef FEAT_EVAL
8812 ac->scriptID = current_SID;
8813#endif
8814 if (ac->cmd == NULL)
8815 {
8816 vim_free(ac);
8817 return FAIL;
8818 }
8819 ac->next = NULL;
8820 *prev_ac = ac;
8821 ac->nested = nested;
8822 }
8823 }
8824
8825 au_cleanup(); /* may really delete removed patterns/commands now */
8826 return OK;
8827}
8828
8829/*
8830 * Implementation of ":doautocmd [group] event [fname]".
8831 * Return OK for success, FAIL for failure;
8832 */
8833 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008834do_doautocmd(
8835 char_u *arg,
Bram Moolenaar1610d052016-06-09 22:53:01 +02008836 int do_msg, /* give message for no matching autocmds? */
8837 int *did_something)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008838{
8839 char_u *fname;
8840 int nothing_done = TRUE;
8841 int group;
8842
Bram Moolenaar1610d052016-06-09 22:53:01 +02008843 if (did_something != NULL)
Bram Moolenaar76ae22f2016-06-13 20:00:29 +02008844 *did_something = FALSE;
Bram Moolenaar1610d052016-06-09 22:53:01 +02008845
Bram Moolenaar071d4272004-06-13 20:20:40 +00008846 /*
8847 * Check for a legal group name. If not, use AUGROUP_ALL.
8848 */
8849 group = au_get_grouparg(&arg);
8850 if (arg == NULL) /* out of memory */
8851 return FAIL;
8852
8853 if (*arg == '*')
8854 {
8855 EMSG(_("E217: Can't execute autocommands for ALL events"));
8856 return FAIL;
8857 }
8858
8859 /*
8860 * Scan over the events.
8861 * If we find an illegal name, return here, don't do anything.
8862 */
8863 fname = find_end_event(arg, group != AUGROUP_ALL);
8864 if (fname == NULL)
8865 return FAIL;
8866
8867 fname = skipwhite(fname);
8868
8869 /*
8870 * Loop over the events.
8871 */
Bram Moolenaarfaf29d72017-07-09 11:07:16 +02008872 while (*arg && !ends_excmd(*arg) && !VIM_ISWHITE(*arg))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008873 if (apply_autocmds_group(event_name2nr(arg, &arg),
8874 fname, NULL, TRUE, group, curbuf, NULL))
8875 nothing_done = FALSE;
8876
8877 if (nothing_done && do_msg)
8878 MSG(_("No matching autocommands"));
Bram Moolenaar1610d052016-06-09 22:53:01 +02008879 if (did_something != NULL)
8880 *did_something = !nothing_done;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008881
8882#ifdef FEAT_EVAL
8883 return aborting() ? FAIL : OK;
8884#else
8885 return OK;
8886#endif
8887}
8888
8889/*
8890 * ":doautoall": execute autocommands for each loaded buffer.
8891 */
8892 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008893ex_doautoall(exarg_T *eap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008894{
8895 int retval;
8896 aco_save_T aco;
8897 buf_T *buf;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008898 bufref_T bufref;
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008899 char_u *arg = eap->arg;
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008900 int call_do_modelines = check_nomodeline(&arg);
Bram Moolenaar1610d052016-06-09 22:53:01 +02008901 int did_aucmd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008902
8903 /*
8904 * This is a bit tricky: For some commands curwin->w_buffer needs to be
8905 * equal to curbuf, but for some buffers there may not be a window.
8906 * So we change the buffer for the current window for a moment. This
8907 * gives problems when the autocommands make changes to the list of
8908 * buffers or windows...
8909 */
Bram Moolenaar29323592016-07-24 22:04:11 +02008910 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008911 {
Bram Moolenaar3a847972008-07-08 09:36:58 +00008912 if (buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008913 {
8914 /* find a window for this buffer and save some values */
8915 aucmd_prepbuf(&aco, buf);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008916 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008917
8918 /* execute the autocommands for this buffer */
Bram Moolenaar1610d052016-06-09 22:53:01 +02008919 retval = do_doautocmd(arg, FALSE, &did_aucmd);
Bram Moolenaareeefcc72007-05-01 21:21:21 +00008920
Bram Moolenaar1610d052016-06-09 22:53:01 +02008921 if (call_do_modelines && did_aucmd)
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008922 {
8923 /* Execute the modeline settings, but don't set window-local
8924 * options if we are using the current window for another
8925 * buffer. */
8926 do_modelines(curwin == aucmd_win ? OPT_NOWIN : 0);
8927 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008928
8929 /* restore the current window */
8930 aucmd_restbuf(&aco);
8931
8932 /* stop if there is some error or buffer was deleted */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008933 if (retval == FAIL || !bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008934 break;
8935 }
8936 }
8937
8938 check_cursor(); /* just in case lines got deleted */
8939}
8940
8941/*
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008942 * Check *argp for <nomodeline>. When it is present return FALSE, otherwise
8943 * return TRUE and advance *argp to after it.
8944 * Thus return TRUE when do_modelines() should be called.
8945 */
8946 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008947check_nomodeline(char_u **argp)
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008948{
8949 if (STRNCMP(*argp, "<nomodeline>", 12) == 0)
8950 {
8951 *argp = skipwhite(*argp + 12);
8952 return FALSE;
8953 }
8954 return TRUE;
8955}
8956
8957/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008958 * Prepare for executing autocommands for (hidden) buffer "buf".
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008959 * Search for a visible window containing the current buffer. If there isn't
8960 * one then use "aucmd_win".
Bram Moolenaar071d4272004-06-13 20:20:40 +00008961 * Set "curbuf" and "curwin" to match "buf".
8962 */
8963 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008964aucmd_prepbuf(
8965 aco_save_T *aco, /* structure to save values in */
8966 buf_T *buf) /* new curbuf */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008967{
8968 win_T *win;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008969 int save_ea;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008970#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008971 int save_acd;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008972#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008973
8974 /* Find a window that is for the new buffer */
8975 if (buf == curbuf) /* be quick when buf is curbuf */
8976 win = curwin;
8977 else
Bram Moolenaar29323592016-07-24 22:04:11 +02008978 FOR_ALL_WINDOWS(win)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008979 if (win->w_buffer == buf)
8980 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008981
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008982 /* Allocate "aucmd_win" when needed. If this fails (out of memory) fall
8983 * back to using the current window. */
8984 if (win == NULL && aucmd_win == NULL)
8985 {
8986 win_alloc_aucmd_win();
8987 if (aucmd_win == NULL)
8988 win = curwin;
8989 }
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008990 if (win == NULL && aucmd_win_used)
8991 /* Strange recursive autocommand, fall back to using the current
8992 * window. Expect a few side effects... */
8993 win = curwin;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008994
8995 aco->save_curwin = curwin;
8996 aco->save_curbuf = curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008997 if (win != NULL)
8998 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008999 /* There is a window for "buf" in the current tab page, make it the
9000 * curwin. This is preferred, it has the least side effects (esp. if
9001 * "buf" is curbuf). */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009002 aco->use_aucmd_win = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009003 curwin = win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009004 }
9005 else
9006 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009007 /* There is no window for "buf", use "aucmd_win". To minimize the side
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02009008 * effects, insert it in the current tab page.
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009009 * Anything related to a window (e.g., setting folds) may have
9010 * unexpected results. */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009011 aco->use_aucmd_win = TRUE;
9012 aucmd_win_used = TRUE;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00009013 aucmd_win->w_buffer = buf;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01009014#if defined(FEAT_SYN_HL) || defined(FEAT_SPELL)
Bram Moolenaarcdddaa42010-06-07 23:07:44 +02009015 aucmd_win->w_s = &buf->b_s;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01009016#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009017 ++buf->b_nwindows;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00009018 win_init_empty(aucmd_win); /* set cursor and topline to safe values */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009019
9020 /* Make sure w_localdir and globaldir are NULL to avoid a chdir() in
9021 * win_enter_ext(). */
Bram Moolenaard23a8232018-02-10 18:45:26 +01009022 VIM_CLEAR(aucmd_win->w_localdir);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009023 aco->globaldir = globaldir;
9024 globaldir = NULL;
9025
Bram Moolenaar071d4272004-06-13 20:20:40 +00009026
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00009027 /* Split the current window, put the aucmd_win in the upper half.
9028 * We don't want the BufEnter or WinEnter autocommands. */
9029 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009030 make_snapshot(SNAP_AUCMD_IDX);
9031 save_ea = p_ea;
9032 p_ea = FALSE;
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009033
Bram Moolenaar4033c552017-09-16 20:54:51 +02009034#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009035 /* Prevent chdir() call in win_enter_ext(), through do_autochdir(). */
9036 save_acd = p_acd;
9037 p_acd = FALSE;
Bram Moolenaar4033c552017-09-16 20:54:51 +02009038#endif
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009039
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009040 (void)win_split_ins(0, WSP_TOP, aucmd_win, 0);
9041 (void)win_comp_pos(); /* recompute window positions */
9042 p_ea = save_ea;
Bram Moolenaar4033c552017-09-16 20:54:51 +02009043#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009044 p_acd = save_acd;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009045#endif
Bram Moolenaar4033c552017-09-16 20:54:51 +02009046 unblock_autocmds();
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00009047 curwin = aucmd_win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009048 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009049 curbuf = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009050 aco->new_curwin = curwin;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009051 set_bufref(&aco->new_curbuf, curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009052}
9053
9054/*
9055 * Cleanup after executing autocommands for a (hidden) buffer.
9056 * Restore the window as it was (if possible).
9057 */
9058 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009059aucmd_restbuf(
9060 aco_save_T *aco) /* structure holding saved values */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009061{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009062 int dummy;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009063
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009064 if (aco->use_aucmd_win)
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009065 {
9066 --curbuf->b_nwindows;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009067 /* Find "aucmd_win", it can't be closed, but it may be in another tab
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00009068 * page. Do not trigger autocommands here. */
9069 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009070 if (curwin != aucmd_win)
9071 {
9072 tabpage_T *tp;
9073 win_T *wp;
9074
9075 FOR_ALL_TAB_WINDOWS(tp, wp)
9076 {
9077 if (wp == aucmd_win)
9078 {
9079 if (tp != curtab)
Bram Moolenaar49e649f2013-05-06 04:50:35 +02009080 goto_tabpage_tp(tp, TRUE, TRUE);
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009081 win_goto(aucmd_win);
Bram Moolenaar28f29082012-02-11 23:45:37 +01009082 goto win_found;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009083 }
9084 }
9085 }
Bram Moolenaar28f29082012-02-11 23:45:37 +01009086win_found:
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009087
9088 /* Remove the window and frame from the tree of frames. */
9089 (void)winframe_remove(curwin, &dummy, NULL);
9090 win_remove(curwin, NULL);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009091 aucmd_win_used = FALSE;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009092 last_status(FALSE); /* may need to remove last status line */
Bram Moolenaar8c752bd2017-03-19 17:09:56 +01009093
9094 if (!valid_tabpage_win(curtab))
9095 /* no valid window in current tabpage */
9096 close_tabpage(curtab);
9097
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009098 restore_snapshot(SNAP_AUCMD_IDX, FALSE);
9099 (void)win_comp_pos(); /* recompute window positions */
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00009100 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009101
9102 if (win_valid(aco->save_curwin))
9103 curwin = aco->save_curwin;
9104 else
9105 /* Hmm, original window disappeared. Just use the first one. */
9106 curwin = firstwin;
Bram Moolenaar4033c552017-09-16 20:54:51 +02009107#ifdef FEAT_EVAL
Bram Moolenaar429fa852013-04-15 12:27:36 +02009108 vars_clear(&aucmd_win->w_vars->dv_hashtab); /* free all w: variables */
9109 hash_init(&aucmd_win->w_vars->dv_hashtab); /* re-use the hashtab */
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009110#endif
9111 curbuf = curwin->w_buffer;
9112
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009113 vim_free(globaldir);
9114 globaldir = aco->globaldir;
9115
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009116 /* the buffer contents may have changed */
9117 check_cursor();
9118 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
9119 {
9120 curwin->w_topline = curbuf->b_ml.ml_line_count;
9121#ifdef FEAT_DIFF
9122 curwin->w_topfill = 0;
9123#endif
9124 }
9125#if defined(FEAT_GUI)
9126 /* Hide the scrollbars from the aucmd_win and update. */
9127 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_LEFT], FALSE);
9128 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_RIGHT], FALSE);
9129 gui_may_update_scrollbars();
9130#endif
9131 }
9132 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00009133 {
9134 /* restore curwin */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009135 if (win_valid(aco->save_curwin))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009136 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009137 /* Restore the buffer which was previously edited by curwin, if
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009138 * it was changed, we are still the same window and the buffer is
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009139 * valid. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009140 if (curwin == aco->new_curwin
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009141 && curbuf != aco->new_curbuf.br_buf
9142 && bufref_valid(&aco->new_curbuf)
9143 && aco->new_curbuf.br_buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009144 {
Bram Moolenaar7da9c372012-04-30 17:04:52 +02009145# if defined(FEAT_SYN_HL) || defined(FEAT_SPELL)
9146 if (curwin->w_s == &curbuf->b_s)
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009147 curwin->w_s = &aco->new_curbuf.br_buf->b_s;
Bram Moolenaar7da9c372012-04-30 17:04:52 +02009148# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009149 --curbuf->b_nwindows;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009150 curbuf = aco->new_curbuf.br_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009151 curwin->w_buffer = curbuf;
9152 ++curbuf->b_nwindows;
9153 }
9154
9155 curwin = aco->save_curwin;
9156 curbuf = curwin->w_buffer;
Bram Moolenaar371932a2014-09-09 16:59:38 +02009157 /* In case the autocommand move the cursor to a position that that
9158 * not exist in curbuf. */
9159 check_cursor();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009160 }
9161 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009162}
9163
9164static int autocmd_nested = FALSE;
9165
9166/*
9167 * Execute autocommands for "event" and file name "fname".
9168 * Return TRUE if some commands were executed.
9169 */
9170 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009171apply_autocmds(
9172 event_T event,
9173 char_u *fname, /* NULL or empty means use actual file name */
9174 char_u *fname_io, /* fname to use for <afile> on cmdline */
9175 int force, /* when TRUE, ignore autocmd_busy */
9176 buf_T *buf) /* buffer for <abuf> */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009177{
9178 return apply_autocmds_group(event, fname, fname_io, force,
9179 AUGROUP_ALL, buf, NULL);
9180}
9181
9182/*
9183 * Like apply_autocmds(), but with extra "eap" argument. This takes care of
9184 * setting v:filearg.
9185 */
9186 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009187apply_autocmds_exarg(
9188 event_T event,
9189 char_u *fname,
9190 char_u *fname_io,
9191 int force,
9192 buf_T *buf,
9193 exarg_T *eap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009194{
9195 return apply_autocmds_group(event, fname, fname_io, force,
9196 AUGROUP_ALL, buf, eap);
9197}
9198
9199/*
9200 * Like apply_autocmds(), but handles the caller's retval. If the script
9201 * processing is being aborted or if retval is FAIL when inside a try
9202 * conditional, no autocommands are executed. If otherwise the autocommands
9203 * cause the script to be aborted, retval is set to FAIL.
9204 */
9205 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009206apply_autocmds_retval(
9207 event_T event,
9208 char_u *fname, /* NULL or empty means use actual file name */
9209 char_u *fname_io, /* fname to use for <afile> on cmdline */
9210 int force, /* when TRUE, ignore autocmd_busy */
9211 buf_T *buf, /* buffer for <abuf> */
9212 int *retval) /* pointer to caller's retval */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009213{
9214 int did_cmd;
9215
Bram Moolenaar1e015462005-09-25 22:16:38 +00009216#ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00009217 if (should_abort(*retval))
9218 return FALSE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00009219#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009220
9221 did_cmd = apply_autocmds_group(event, fname, fname_io, force,
9222 AUGROUP_ALL, buf, NULL);
Bram Moolenaar1e015462005-09-25 22:16:38 +00009223 if (did_cmd
9224#ifdef FEAT_EVAL
9225 && aborting()
9226#endif
9227 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00009228 *retval = FAIL;
9229 return did_cmd;
9230}
9231
Bram Moolenaard35f9712005-12-18 22:02:33 +00009232/*
9233 * Return TRUE when there is a CursorHold autocommand defined.
9234 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009235 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009236has_cursorhold(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009237{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009238 return (first_autopat[(int)(get_real_state() == NORMAL_BUSY
9239 ? EVENT_CURSORHOLD : EVENT_CURSORHOLDI)] != NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009240}
Bram Moolenaard35f9712005-12-18 22:02:33 +00009241
9242/*
9243 * Return TRUE if the CursorHold event can be triggered.
9244 */
9245 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009246trigger_cursorhold(void)
Bram Moolenaard35f9712005-12-18 22:02:33 +00009247{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009248 int state;
9249
Bram Moolenaar05334432011-07-20 18:29:39 +02009250 if (!did_cursorhold
9251 && has_cursorhold()
9252 && !Recording
9253 && typebuf.tb_len == 0
Bram Moolenaard29a9ee2006-09-14 09:07:34 +00009254#ifdef FEAT_INS_EXPAND
9255 && !ins_compl_active()
9256#endif
9257 )
Bram Moolenaar754b5602006-02-09 23:53:20 +00009258 {
9259 state = get_real_state();
9260 if (state == NORMAL_BUSY || (state & INSERT) != 0)
9261 return TRUE;
9262 }
9263 return FALSE;
Bram Moolenaard35f9712005-12-18 22:02:33 +00009264}
Bram Moolenaar754b5602006-02-09 23:53:20 +00009265
9266/*
9267 * Return TRUE when there is a CursorMoved autocommand defined.
9268 */
9269 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009270has_cursormoved(void)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009271{
9272 return (first_autopat[(int)EVENT_CURSORMOVED] != NULL);
9273}
9274
9275/*
9276 * Return TRUE when there is a CursorMovedI autocommand defined.
9277 */
9278 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009279has_cursormovedI(void)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009280{
9281 return (first_autopat[(int)EVENT_CURSORMOVEDI] != NULL);
9282}
Bram Moolenaar071d4272004-06-13 20:20:40 +00009283
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009284/*
Bram Moolenaar186628f2013-03-19 13:33:23 +01009285 * Return TRUE when there is a TextChanged autocommand defined.
9286 */
9287 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009288has_textchanged(void)
Bram Moolenaar186628f2013-03-19 13:33:23 +01009289{
9290 return (first_autopat[(int)EVENT_TEXTCHANGED] != NULL);
9291}
9292
9293/*
9294 * Return TRUE when there is a TextChangedI autocommand defined.
9295 */
9296 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009297has_textchangedI(void)
Bram Moolenaar186628f2013-03-19 13:33:23 +01009298{
9299 return (first_autopat[(int)EVENT_TEXTCHANGEDI] != NULL);
9300}
9301
9302/*
Bram Moolenaar5a093432018-02-10 18:15:19 +01009303 * Return TRUE when there is a TextChangedP autocommand defined.
9304 */
9305 int
9306has_textchangedP(void)
9307{
9308 return (first_autopat[(int)EVENT_TEXTCHANGEDP] != NULL);
9309}
9310
9311/*
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009312 * Return TRUE when there is an InsertCharPre autocommand defined.
9313 */
9314 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009315has_insertcharpre(void)
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009316{
9317 return (first_autopat[(int)EVENT_INSERTCHARPRE] != NULL);
9318}
9319
Bram Moolenaard5005162014-08-22 23:05:54 +02009320/*
9321 * Return TRUE when there is an CmdUndefined autocommand defined.
9322 */
9323 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009324has_cmdundefined(void)
Bram Moolenaard5005162014-08-22 23:05:54 +02009325{
9326 return (first_autopat[(int)EVENT_CMDUNDEFINED] != NULL);
9327}
9328
9329/*
9330 * Return TRUE when there is an FuncUndefined autocommand defined.
9331 */
9332 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009333has_funcundefined(void)
Bram Moolenaard5005162014-08-22 23:05:54 +02009334{
9335 return (first_autopat[(int)EVENT_FUNCUNDEFINED] != NULL);
9336}
9337
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009338/*
Bram Moolenaar7e1652c2017-12-16 18:27:02 +01009339 * Return TRUE when there is a TextYankPost autocommand defined.
9340 */
9341 int
9342has_textyankpost(void)
9343{
9344 return (first_autopat[(int)EVENT_TEXTYANKPOST] != NULL);
9345}
9346
9347/*
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009348 * Execute autocommands for "event" and file name "fname".
9349 * Return TRUE if some commands were executed.
9350 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009351 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009352apply_autocmds_group(
9353 event_T event,
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01009354 char_u *fname, /* NULL or empty means use actual file name */
9355 char_u *fname_io, /* fname to use for <afile> on cmdline, NULL means
Bram Moolenaar071d4272004-06-13 20:20:40 +00009356 use fname */
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01009357 int force, /* when TRUE, ignore autocmd_busy */
9358 int group, /* group ID, or AUGROUP_ALL */
9359 buf_T *buf, /* buffer for <abuf> */
9360 exarg_T *eap UNUSED) /* command arguments */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009361{
9362 char_u *sfname = NULL; /* short file name */
9363 char_u *tail;
9364 int save_changed;
9365 buf_T *old_curbuf;
9366 int retval = FALSE;
9367 char_u *save_sourcing_name;
9368 linenr_T save_sourcing_lnum;
9369 char_u *save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009370 int save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009371 int save_autocmd_bufnr;
9372 char_u *save_autocmd_match;
9373 int save_autocmd_busy;
9374 int save_autocmd_nested;
9375 static int nesting = 0;
9376 AutoPatCmd patcmd;
9377 AutoPat *ap;
9378#ifdef FEAT_EVAL
9379 scid_T save_current_SID;
9380 void *save_funccalp;
9381 char_u *save_cmdarg;
9382 long save_cmdbang;
9383#endif
9384 static int filechangeshell_busy = FALSE;
Bram Moolenaar05159a02005-02-26 23:04:13 +00009385#ifdef FEAT_PROFILE
9386 proftime_T wait_time;
9387#endif
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009388 int did_save_redobuff = FALSE;
Bram Moolenaard4863aa2017-04-07 19:50:12 +02009389 save_redo_T save_redo;
Bram Moolenaarc9e9c712017-11-09 12:29:35 +01009390 int save_KeyTyped = KeyTyped;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009391
9392 /*
9393 * Quickly return if there are no autocommands for this event or
9394 * autocommands are blocked.
9395 */
Bram Moolenaarfaf29d72017-07-09 11:07:16 +02009396 if (event == NUM_EVENTS || first_autopat[(int)event] == NULL
9397 || autocmd_blocked > 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009398 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009399
9400 /*
9401 * When autocommands are busy, new autocommands are only executed when
9402 * explicitly enabled with the "nested" flag.
9403 */
9404 if (autocmd_busy && !(force || autocmd_nested))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009405 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009406
9407#ifdef FEAT_EVAL
9408 /*
Bram Moolenaar7263a772007-05-10 17:35:54 +00009409 * Quickly return when immediately aborting on error, or when an interrupt
Bram Moolenaar071d4272004-06-13 20:20:40 +00009410 * occurred or an exception was thrown but not caught.
9411 */
9412 if (aborting())
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009413 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009414#endif
9415
9416 /*
9417 * FileChangedShell never nests, because it can create an endless loop.
9418 */
Bram Moolenaar56718732006-03-15 22:53:57 +00009419 if (filechangeshell_busy && (event == EVENT_FILECHANGEDSHELL
9420 || event == EVENT_FILECHANGEDSHELLPOST))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009421 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009422
9423 /*
9424 * Ignore events in 'eventignore'.
9425 */
9426 if (event_ignored(event))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009427 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009428
9429 /*
9430 * Allow nesting of autocommands, but restrict the depth, because it's
9431 * possible to create an endless loop.
9432 */
9433 if (nesting == 10)
9434 {
9435 EMSG(_("E218: autocommand nesting too deep"));
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009436 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009437 }
9438
9439 /*
9440 * Check if these autocommands are disabled. Used when doing ":all" or
9441 * ":ball".
9442 */
9443 if ( (autocmd_no_enter
9444 && (event == EVENT_WINENTER || event == EVENT_BUFENTER))
9445 || (autocmd_no_leave
9446 && (event == EVENT_WINLEAVE || event == EVENT_BUFLEAVE)))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009447 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009448
9449 /*
9450 * Save the autocmd_* variables and info about the current buffer.
9451 */
9452 save_autocmd_fname = autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009453 save_autocmd_fname_full = autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009454 save_autocmd_bufnr = autocmd_bufnr;
9455 save_autocmd_match = autocmd_match;
9456 save_autocmd_busy = autocmd_busy;
9457 save_autocmd_nested = autocmd_nested;
9458 save_changed = curbuf->b_changed;
9459 old_curbuf = curbuf;
9460
9461 /*
9462 * Set the file name to be used for <afile>.
Bram Moolenaara0174af2008-01-02 20:08:25 +00009463 * Make a copy to avoid that changing a buffer name or directory makes it
9464 * invalid.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009465 */
9466 if (fname_io == NULL)
9467 {
Bram Moolenaar53744302015-07-17 17:38:22 +02009468 if (event == EVENT_COLORSCHEME || event == EVENT_OPTIONSET)
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009469 autocmd_fname = NULL;
Bram Moolenaarfaf29d72017-07-09 11:07:16 +02009470 else if (fname != NULL && !ends_excmd(*fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009471 autocmd_fname = fname;
9472 else if (buf != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009473 autocmd_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009474 else
9475 autocmd_fname = NULL;
9476 }
9477 else
9478 autocmd_fname = fname_io;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009479 if (autocmd_fname != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009480 autocmd_fname = vim_strsave(autocmd_fname);
9481 autocmd_fname_full = FALSE; /* call FullName_save() later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009482
9483 /*
9484 * Set the buffer number to be used for <abuf>.
9485 */
9486 if (buf == NULL)
9487 autocmd_bufnr = 0;
9488 else
9489 autocmd_bufnr = buf->b_fnum;
9490
9491 /*
9492 * When the file name is NULL or empty, use the file name of buffer "buf".
9493 * Always use the full path of the file name to match with, in case
9494 * "allow_dirs" is set.
9495 */
9496 if (fname == NULL || *fname == NUL)
9497 {
9498 if (buf == NULL)
9499 fname = NULL;
9500 else
9501 {
9502#ifdef FEAT_SYN_HL
9503 if (event == EVENT_SYNTAX)
9504 fname = buf->b_p_syn;
9505 else
9506#endif
9507 if (event == EVENT_FILETYPE)
9508 fname = buf->b_p_ft;
9509 else
9510 {
9511 if (buf->b_sfname != NULL)
9512 sfname = vim_strsave(buf->b_sfname);
9513 fname = buf->b_ffname;
9514 }
9515 }
9516 if (fname == NULL)
9517 fname = (char_u *)"";
9518 fname = vim_strsave(fname); /* make a copy, so we can change it */
9519 }
9520 else
9521 {
9522 sfname = vim_strsave(fname);
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009523 /* Don't try expanding FileType, Syntax, FuncUndefined, WindowID,
Bram Moolenaarb7407d32018-02-03 17:36:27 +01009524 * ColorScheme, QuickFixCmd* or DirChanged */
Bram Moolenaar7c626922005-02-07 22:01:03 +00009525 if (event == EVENT_FILETYPE
9526 || event == EVENT_SYNTAX
Bram Moolenaara4baf5b2018-04-22 13:27:44 +02009527 || event == EVENT_CMDLINECHANGED
9528 || event == EVENT_CMDLINEENTER
9529 || event == EVENT_CMDLINELEAVE
9530 || event == EVENT_CMDWINENTER
9531 || event == EVENT_CMDWINLEAVE
9532 || event == EVENT_CMDUNDEFINED
Bram Moolenaar5135d462009-04-29 16:03:38 +00009533 || event == EVENT_FUNCUNDEFINED
Bram Moolenaar7c626922005-02-07 22:01:03 +00009534 || event == EVENT_REMOTEREPLY
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00009535 || event == EVENT_SPELLFILEMISSING
Bram Moolenaar7c626922005-02-07 22:01:03 +00009536 || event == EVENT_QUICKFIXCMDPRE
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009537 || event == EVENT_COLORSCHEME
Bram Moolenaar53744302015-07-17 17:38:22 +02009538 || event == EVENT_OPTIONSET
Bram Moolenaarb7407d32018-02-03 17:36:27 +01009539 || event == EVENT_QUICKFIXCMDPOST
9540 || event == EVENT_DIRCHANGED)
Bram Moolenaara4baf5b2018-04-22 13:27:44 +02009541 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00009542 fname = vim_strsave(fname);
Bram Moolenaara4baf5b2018-04-22 13:27:44 +02009543 autocmd_fname_full = TRUE; /* don't expand it later */
9544 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009545 else
9546 fname = FullName_save(fname, FALSE);
9547 }
9548 if (fname == NULL) /* out of memory */
9549 {
9550 vim_free(sfname);
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009551 retval = FALSE;
9552 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009553 }
9554
9555#ifdef BACKSLASH_IN_FILENAME
9556 /*
9557 * Replace all backslashes with forward slashes. This makes the
9558 * autocommand patterns portable between Unix and MS-DOS.
9559 */
9560 if (sfname != NULL)
9561 forward_slash(sfname);
9562 forward_slash(fname);
9563#endif
9564
9565#ifdef VMS
9566 /* remove version for correct match */
9567 if (sfname != NULL)
9568 vms_remove_version(sfname);
9569 vms_remove_version(fname);
9570#endif
9571
9572 /*
9573 * Set the name to be used for <amatch>.
9574 */
9575 autocmd_match = fname;
9576
9577
9578 /* Don't redraw while doing auto commands. */
9579 ++RedrawingDisabled;
9580 save_sourcing_name = sourcing_name;
9581 sourcing_name = NULL; /* don't free this one */
9582 save_sourcing_lnum = sourcing_lnum;
9583 sourcing_lnum = 0; /* no line number here */
9584
9585#ifdef FEAT_EVAL
9586 save_current_SID = current_SID;
9587
Bram Moolenaar05159a02005-02-26 23:04:13 +00009588# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009589 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009590 prof_child_enter(&wait_time); /* doesn't count for the caller itself */
9591# endif
9592
Bram Moolenaar071d4272004-06-13 20:20:40 +00009593 /* Don't use local function variables, if called from a function */
9594 save_funccalp = save_funccal();
9595#endif
9596
9597 /*
9598 * When starting to execute autocommands, save the search patterns.
9599 */
9600 if (!autocmd_busy)
9601 {
9602 save_search_patterns();
Bram Moolenaar20ad69c2015-12-03 13:52:52 +01009603#ifdef FEAT_INS_EXPAND
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009604 if (!ins_compl_active())
Bram Moolenaar20ad69c2015-12-03 13:52:52 +01009605#endif
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009606 {
Bram Moolenaard4863aa2017-04-07 19:50:12 +02009607 saveRedobuff(&save_redo);
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009608 did_save_redobuff = TRUE;
9609 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009610 did_filetype = keep_filetype;
9611 }
9612
9613 /*
9614 * Note that we are applying autocmds. Some commands need to know.
9615 */
9616 autocmd_busy = TRUE;
9617 filechangeshell_busy = (event == EVENT_FILECHANGEDSHELL);
9618 ++nesting; /* see matching decrement below */
9619
9620 /* Remember that FileType was triggered. Used for did_filetype(). */
9621 if (event == EVENT_FILETYPE)
9622 did_filetype = TRUE;
9623
9624 tail = gettail(fname);
9625
9626 /* Find first autocommand that matches */
9627 patcmd.curpat = first_autopat[(int)event];
9628 patcmd.nextcmd = NULL;
9629 patcmd.group = group;
9630 patcmd.fname = fname;
9631 patcmd.sfname = sfname;
9632 patcmd.tail = tail;
9633 patcmd.event = event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009634 patcmd.arg_bufnr = autocmd_bufnr;
9635 patcmd.next = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009636 auto_next_pat(&patcmd, FALSE);
9637
9638 /* found one, start executing the autocommands */
9639 if (patcmd.curpat != NULL)
9640 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009641 /* add to active_apc_list */
9642 patcmd.next = active_apc_list;
9643 active_apc_list = &patcmd;
9644
Bram Moolenaar071d4272004-06-13 20:20:40 +00009645#ifdef FEAT_EVAL
9646 /* set v:cmdarg (only when there is a matching pattern) */
Bram Moolenaar22fcfad2016-07-01 18:17:26 +02009647 save_cmdbang = (long)get_vim_var_nr(VV_CMDBANG);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009648 if (eap != NULL)
9649 {
9650 save_cmdarg = set_cmdarg(eap, NULL);
9651 set_vim_var_nr(VV_CMDBANG, (long)eap->forceit);
9652 }
9653 else
9654 save_cmdarg = NULL; /* avoid gcc warning */
9655#endif
9656 retval = TRUE;
9657 /* mark the last pattern, to avoid an endless loop when more patterns
9658 * are added when executing autocommands */
9659 for (ap = patcmd.curpat; ap->next != NULL; ap = ap->next)
9660 ap->last = FALSE;
9661 ap->last = TRUE;
9662 check_lnums(TRUE); /* make sure cursor and topline are valid */
9663 do_cmdline(NULL, getnextac, (void *)&patcmd,
9664 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
9665#ifdef FEAT_EVAL
9666 if (eap != NULL)
9667 {
9668 (void)set_cmdarg(NULL, save_cmdarg);
9669 set_vim_var_nr(VV_CMDBANG, save_cmdbang);
9670 }
9671#endif
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009672 /* delete from active_apc_list */
9673 if (active_apc_list == &patcmd) /* just in case */
9674 active_apc_list = patcmd.next;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009675 }
9676
9677 --RedrawingDisabled;
9678 autocmd_busy = save_autocmd_busy;
9679 filechangeshell_busy = FALSE;
9680 autocmd_nested = save_autocmd_nested;
9681 vim_free(sourcing_name);
9682 sourcing_name = save_sourcing_name;
9683 sourcing_lnum = save_sourcing_lnum;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009684 vim_free(autocmd_fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009685 autocmd_fname = save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009686 autocmd_fname_full = save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009687 autocmd_bufnr = save_autocmd_bufnr;
9688 autocmd_match = save_autocmd_match;
9689#ifdef FEAT_EVAL
9690 current_SID = save_current_SID;
9691 restore_funccal(save_funccalp);
Bram Moolenaar05159a02005-02-26 23:04:13 +00009692# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009693 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009694 prof_child_exit(&wait_time);
9695# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009696#endif
Bram Moolenaarc9e9c712017-11-09 12:29:35 +01009697 KeyTyped = save_KeyTyped;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009698 vim_free(fname);
9699 vim_free(sfname);
9700 --nesting; /* see matching increment above */
9701
9702 /*
9703 * When stopping to execute autocommands, restore the search patterns and
Bram Moolenaar3be85852014-06-12 14:01:31 +02009704 * the redo buffer. Free any buffers in the au_pending_free_buf list and
9705 * free any windows in the au_pending_free_win list.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009706 */
9707 if (!autocmd_busy)
9708 {
9709 restore_search_patterns();
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009710 if (did_save_redobuff)
Bram Moolenaard4863aa2017-04-07 19:50:12 +02009711 restoreRedobuff(&save_redo);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009712 did_filetype = FALSE;
Bram Moolenaar4c7ab1b2014-04-06 20:45:43 +02009713 while (au_pending_free_buf != NULL)
9714 {
9715 buf_T *b = au_pending_free_buf->b_next;
9716 vim_free(au_pending_free_buf);
9717 au_pending_free_buf = b;
9718 }
Bram Moolenaar3be85852014-06-12 14:01:31 +02009719 while (au_pending_free_win != NULL)
9720 {
9721 win_T *w = au_pending_free_win->w_next;
9722 vim_free(au_pending_free_win);
9723 au_pending_free_win = w;
9724 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009725 }
9726
9727 /*
9728 * Some events don't set or reset the Changed flag.
9729 * Check if still in the same buffer!
9730 */
9731 if (curbuf == old_curbuf
9732 && (event == EVENT_BUFREADPOST
9733 || event == EVENT_BUFWRITEPOST
9734 || event == EVENT_FILEAPPENDPOST
9735 || event == EVENT_VIMLEAVE
9736 || event == EVENT_VIMLEAVEPRE))
9737 {
9738#ifdef FEAT_TITLE
9739 if (curbuf->b_changed != save_changed)
9740 need_maketitle = TRUE;
9741#endif
9742 curbuf->b_changed = save_changed;
9743 }
9744
9745 au_cleanup(); /* may really delete removed patterns/commands now */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009746
9747BYPASS_AU:
9748 /* When wiping out a buffer make sure all its buffer-local autocommands
9749 * are deleted. */
9750 if (event == EVENT_BUFWIPEOUT && buf != NULL)
9751 aubuflocal_remove(buf);
9752
Bram Moolenaarc3691332016-04-20 12:49:49 +02009753 if (retval == OK && event == EVENT_FILETYPE)
9754 au_did_filetype = TRUE;
9755
Bram Moolenaar071d4272004-06-13 20:20:40 +00009756 return retval;
9757}
9758
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009759# ifdef FEAT_EVAL
9760static char_u *old_termresponse = NULL;
9761# endif
9762
9763/*
9764 * Block triggering autocommands until unblock_autocmd() is called.
9765 * Can be used recursively, so long as it's symmetric.
9766 */
9767 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009768block_autocmds(void)
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009769{
9770# ifdef FEAT_EVAL
9771 /* Remember the value of v:termresponse. */
9772 if (autocmd_blocked == 0)
9773 old_termresponse = get_vim_var_str(VV_TERMRESPONSE);
9774# endif
9775 ++autocmd_blocked;
9776}
9777
9778 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009779unblock_autocmds(void)
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009780{
9781 --autocmd_blocked;
9782
9783# ifdef FEAT_EVAL
9784 /* When v:termresponse was set while autocommands were blocked, trigger
9785 * the autocommands now. Esp. useful when executing a shell command
9786 * during startup (vimdiff). */
9787 if (autocmd_blocked == 0
9788 && get_vim_var_str(VV_TERMRESPONSE) != old_termresponse)
9789 apply_autocmds(EVENT_TERMRESPONSE, NULL, NULL, FALSE, curbuf);
9790# endif
9791}
9792
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009793 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009794is_autocmd_blocked(void)
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009795{
9796 return autocmd_blocked != 0;
9797}
9798
Bram Moolenaar071d4272004-06-13 20:20:40 +00009799/*
9800 * Find next autocommand pattern that matches.
9801 */
9802 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009803auto_next_pat(
9804 AutoPatCmd *apc,
9805 int stop_at_last) /* stop when 'last' flag is set */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009806{
9807 AutoPat *ap;
9808 AutoCmd *cp;
9809 char_u *name;
9810 char *s;
9811
Bram Moolenaard23a8232018-02-10 18:45:26 +01009812 VIM_CLEAR(sourcing_name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009813
9814 for (ap = apc->curpat; ap != NULL && !got_int; ap = ap->next)
9815 {
9816 apc->curpat = NULL;
9817
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009818 /* Only use a pattern when it has not been removed, has commands and
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009819 * the group matches. For buffer-local autocommands only check the
9820 * buffer number. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009821 if (ap->pat != NULL && ap->cmds != NULL
9822 && (apc->group == AUGROUP_ALL || apc->group == ap->group))
9823 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009824 /* execution-condition */
9825 if (ap->buflocal_nr == 0
Bram Moolenaardffa5b82014-11-19 16:38:07 +01009826 ? (match_file_pat(NULL, &ap->reg_prog, apc->fname,
Bram Moolenaar748bf032005-02-02 23:04:36 +00009827 apc->sfname, apc->tail, ap->allow_dirs))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009828 : ap->buflocal_nr == apc->arg_bufnr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009829 {
9830 name = event_nr2name(apc->event);
9831 s = _("%s Auto commands for \"%s\"");
9832 sourcing_name = alloc((unsigned)(STRLEN(s)
9833 + STRLEN(name) + ap->patlen + 1));
9834 if (sourcing_name != NULL)
9835 {
9836 sprintf((char *)sourcing_name, s,
9837 (char *)name, (char *)ap->pat);
9838 if (p_verbose >= 8)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009839 {
9840 verbose_enter();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009841 smsg((char_u *)_("Executing %s"), sourcing_name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009842 verbose_leave();
9843 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009844 }
9845
9846 apc->curpat = ap;
9847 apc->nextcmd = ap->cmds;
9848 /* mark last command */
9849 for (cp = ap->cmds; cp->next != NULL; cp = cp->next)
9850 cp->last = FALSE;
9851 cp->last = TRUE;
9852 }
9853 line_breakcheck();
9854 if (apc->curpat != NULL) /* found a match */
9855 break;
9856 }
9857 if (stop_at_last && ap->last)
9858 break;
9859 }
9860}
9861
9862/*
9863 * Get next autocommand command.
9864 * Called by do_cmdline() to get the next line for ":if".
9865 * Returns allocated string, or NULL for end of autocommands.
9866 */
Bram Moolenaar21691f82012-12-05 19:13:18 +01009867 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009868getnextac(int c UNUSED, void *cookie, int indent UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009869{
9870 AutoPatCmd *acp = (AutoPatCmd *)cookie;
9871 char_u *retval;
9872 AutoCmd *ac;
9873
9874 /* Can be called again after returning the last line. */
9875 if (acp->curpat == NULL)
9876 return NULL;
9877
9878 /* repeat until we find an autocommand to execute */
9879 for (;;)
9880 {
9881 /* skip removed commands */
9882 while (acp->nextcmd != NULL && acp->nextcmd->cmd == NULL)
9883 if (acp->nextcmd->last)
9884 acp->nextcmd = NULL;
9885 else
9886 acp->nextcmd = acp->nextcmd->next;
9887
9888 if (acp->nextcmd != NULL)
9889 break;
9890
9891 /* at end of commands, find next pattern that matches */
9892 if (acp->curpat->last)
9893 acp->curpat = NULL;
9894 else
9895 acp->curpat = acp->curpat->next;
9896 if (acp->curpat != NULL)
9897 auto_next_pat(acp, TRUE);
9898 if (acp->curpat == NULL)
9899 return NULL;
9900 }
9901
9902 ac = acp->nextcmd;
9903
9904 if (p_verbose >= 9)
9905 {
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009906 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009907 smsg((char_u *)_("autocommand %s"), ac->cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009908 msg_puts((char_u *)"\n"); /* don't overwrite this either */
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009909 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009910 }
9911 retval = vim_strsave(ac->cmd);
9912 autocmd_nested = ac->nested;
9913#ifdef FEAT_EVAL
9914 current_SID = ac->scriptID;
9915#endif
9916 if (ac->last)
9917 acp->nextcmd = NULL;
9918 else
9919 acp->nextcmd = ac->next;
9920 return retval;
9921}
9922
9923/*
9924 * Return TRUE if there is a matching autocommand for "fname".
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009925 * To account for buffer-local autocommands, function needs to know
9926 * in which buffer the file will be opened.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009927 */
9928 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009929has_autocmd(event_T event, char_u *sfname, buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009930{
9931 AutoPat *ap;
9932 char_u *fname;
9933 char_u *tail = gettail(sfname);
9934 int retval = FALSE;
9935
9936 fname = FullName_save(sfname, FALSE);
9937 if (fname == NULL)
9938 return FALSE;
9939
9940#ifdef BACKSLASH_IN_FILENAME
9941 /*
9942 * Replace all backslashes with forward slashes. This makes the
9943 * autocommand patterns portable between Unix and MS-DOS.
9944 */
9945 sfname = vim_strsave(sfname);
9946 if (sfname != NULL)
9947 forward_slash(sfname);
9948 forward_slash(fname);
9949#endif
9950
9951 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
9952 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009953 && (ap->buflocal_nr == 0
Bram Moolenaardffa5b82014-11-19 16:38:07 +01009954 ? match_file_pat(NULL, &ap->reg_prog,
Bram Moolenaar748bf032005-02-02 23:04:36 +00009955 fname, sfname, tail, ap->allow_dirs)
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009956 : buf != NULL && ap->buflocal_nr == buf->b_fnum
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009957 ))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009958 {
9959 retval = TRUE;
9960 break;
9961 }
9962
9963 vim_free(fname);
9964#ifdef BACKSLASH_IN_FILENAME
9965 vim_free(sfname);
9966#endif
9967
9968 return retval;
9969}
9970
9971#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
9972/*
9973 * Function given to ExpandGeneric() to obtain the list of autocommand group
9974 * names.
9975 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009976 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009977get_augroup_name(expand_T *xp UNUSED, int idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009978{
9979 if (idx == augroups.ga_len) /* add "END" add the end */
9980 return (char_u *)"END";
9981 if (idx >= augroups.ga_len) /* end of list */
9982 return NULL;
Bram Moolenaarb62cc362016-09-03 16:43:53 +02009983 if (AUGROUP_NAME(idx) == NULL || AUGROUP_NAME(idx) == get_deleted_augroup())
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02009984 /* skip deleted entries */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009985 return (char_u *)"";
9986 return AUGROUP_NAME(idx); /* return a name */
9987}
9988
9989static int include_groups = FALSE;
9990
9991 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009992set_context_in_autocmd(
9993 expand_T *xp,
9994 char_u *arg,
9995 int doautocmd) /* TRUE for :doauto*, FALSE for :autocmd */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009996{
9997 char_u *p;
9998 int group;
9999
10000 /* check for a group name, skip it if present */
10001 include_groups = FALSE;
10002 p = arg;
10003 group = au_get_grouparg(&arg);
10004 if (group == AUGROUP_ERROR)
10005 return NULL;
10006 /* If there only is a group name that's what we expand. */
Bram Moolenaar1c465442017-03-12 20:10:05 +010010007 if (*arg == NUL && group != AUGROUP_ALL && !VIM_ISWHITE(arg[-1]))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010008 {
10009 arg = p;
10010 group = AUGROUP_ALL;
10011 }
10012
10013 /* skip over event name */
Bram Moolenaar1c465442017-03-12 20:10:05 +010010014 for (p = arg; *p != NUL && !VIM_ISWHITE(*p); ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010015 if (*p == ',')
10016 arg = p + 1;
10017 if (*p == NUL)
10018 {
10019 if (group == AUGROUP_ALL)
10020 include_groups = TRUE;
10021 xp->xp_context = EXPAND_EVENTS; /* expand event name */
10022 xp->xp_pattern = arg;
10023 return NULL;
10024 }
10025
10026 /* skip over pattern */
10027 arg = skipwhite(p);
Bram Moolenaar1c465442017-03-12 20:10:05 +010010028 while (*arg && (!VIM_ISWHITE(*arg) || arg[-1] == '\\'))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010029 arg++;
10030 if (*arg)
10031 return arg; /* expand (next) command */
10032
10033 if (doautocmd)
10034 xp->xp_context = EXPAND_FILES; /* expand file names */
10035 else
10036 xp->xp_context = EXPAND_NOTHING; /* pattern is not expanded */
10037 return NULL;
10038}
10039
10040/*
10041 * Function given to ExpandGeneric() to obtain the list of event names.
10042 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010043 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010044get_event_name(expand_T *xp UNUSED, int idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010045{
10046 if (idx < augroups.ga_len) /* First list group names, if wanted */
10047 {
Bram Moolenaarf2c4c392016-07-29 20:50:24 +020010048 if (!include_groups || AUGROUP_NAME(idx) == NULL
Bram Moolenaarb62cc362016-09-03 16:43:53 +020010049 || AUGROUP_NAME(idx) == get_deleted_augroup())
Bram Moolenaar071d4272004-06-13 20:20:40 +000010050 return (char_u *)""; /* skip deleted entries */
10051 return AUGROUP_NAME(idx); /* return a name */
10052 }
10053 return (char_u *)event_names[idx - augroups.ga_len].name;
10054}
10055
10056#endif /* FEAT_CMDL_COMPL */
10057
10058/*
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010059 * Return TRUE if autocmd is supported.
10060 */
10061 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010062autocmd_supported(char_u *name)
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010063{
10064 char_u *p;
10065
10066 return (event_name2nr(name, &p) != NUM_EVENTS);
10067}
10068
10069/*
Bram Moolenaar195d6352005-12-19 22:08:24 +000010070 * Return TRUE if an autocommand is defined for a group, event and
10071 * pattern: The group can be omitted to accept any group. "event" and "pattern"
10072 * can be NULL to accept any event and pattern. "pattern" can be NULL to accept
10073 * any pattern. Buffer-local patterns <buffer> or <buffer=N> are accepted.
10074 * Used for:
10075 * exists("#Group") or
10076 * exists("#Group#Event") or
10077 * exists("#Group#Event#pat") or
10078 * exists("#Event") or
10079 * exists("#Event#pat")
Bram Moolenaar071d4272004-06-13 20:20:40 +000010080 */
10081 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010082au_exists(char_u *arg)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010083{
Bram Moolenaar195d6352005-12-19 22:08:24 +000010084 char_u *arg_save;
10085 char_u *pattern = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010086 char_u *event_name;
10087 char_u *p;
Bram Moolenaar754b5602006-02-09 23:53:20 +000010088 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010089 AutoPat *ap;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010090 buf_T *buflocal_buf = NULL;
Bram Moolenaar195d6352005-12-19 22:08:24 +000010091 int group;
10092 int retval = FALSE;
10093
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010094 /* Make a copy so that we can change the '#' chars to a NUL. */
Bram Moolenaar195d6352005-12-19 22:08:24 +000010095 arg_save = vim_strsave(arg);
10096 if (arg_save == NULL)
10097 return FALSE;
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010098 p = vim_strchr(arg_save, '#');
Bram Moolenaar195d6352005-12-19 22:08:24 +000010099 if (p != NULL)
10100 *p++ = NUL;
10101
10102 /* First, look for an autocmd group name */
10103 group = au_find_group(arg_save);
10104 if (group == AUGROUP_ERROR)
10105 {
10106 /* Didn't match a group name, assume the first argument is an event. */
10107 group = AUGROUP_ALL;
10108 event_name = arg_save;
10109 }
10110 else
10111 {
10112 if (p == NULL)
10113 {
10114 /* "Group": group name is present and it's recognized */
10115 retval = TRUE;
10116 goto theend;
10117 }
10118
10119 /* Must be "Group#Event" or "Group#Event#pat". */
10120 event_name = p;
10121 p = vim_strchr(event_name, '#');
10122 if (p != NULL)
10123 *p++ = NUL; /* "Group#Event#pat" */
10124 }
10125
10126 pattern = p; /* "pattern" is NULL when there is no pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010127
10128 /* find the index (enum) for the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010129 event = event_name2nr(event_name, &p);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010130
10131 /* return FALSE if the event name is not recognized */
Bram Moolenaar195d6352005-12-19 22:08:24 +000010132 if (event == NUM_EVENTS)
10133 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010134
10135 /* Find the first autocommand for this event.
10136 * If there isn't any, return FALSE;
10137 * If there is one and no pattern given, return TRUE; */
10138 ap = first_autopat[(int)event];
10139 if (ap == NULL)
Bram Moolenaar195d6352005-12-19 22:08:24 +000010140 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010141
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010142 /* if pattern is "<buffer>", special handling is needed which uses curbuf */
10143 /* for pattern "<buffer=N>, fnamecmp() will work fine */
Bram Moolenaar5b7880d2009-09-11 15:24:31 +000010144 if (pattern != NULL && STRICMP(pattern, "<buffer>") == 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010145 buflocal_buf = curbuf;
10146
Bram Moolenaar071d4272004-06-13 20:20:40 +000010147 /* Check if there is an autocommand with the given pattern. */
10148 for ( ; ap != NULL; ap = ap->next)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010149 /* only use a pattern when it has not been removed and has commands. */
10150 /* For buffer-local autocommands, fnamecmp() works fine. */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010151 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaar195d6352005-12-19 22:08:24 +000010152 && (group == AUGROUP_ALL || ap->group == group)
Bram Moolenaar5b7880d2009-09-11 15:24:31 +000010153 && (pattern == NULL
10154 || (buflocal_buf == NULL
10155 ? fnamecmp(ap->pat, pattern) == 0
10156 : ap->buflocal_nr == buflocal_buf->b_fnum)))
Bram Moolenaar195d6352005-12-19 22:08:24 +000010157 {
10158 retval = TRUE;
10159 break;
10160 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010161
Bram Moolenaar195d6352005-12-19 22:08:24 +000010162theend:
10163 vim_free(arg_save);
10164 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010165}
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010166
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010167
10168/*
Bram Moolenaar748bf032005-02-02 23:04:36 +000010169 * Try matching a filename with a "pattern" ("prog" is NULL), or use the
10170 * precompiled regprog "prog" ("pattern" is NULL). That avoids calling
10171 * vim_regcomp() often.
Bram Moolenaar071d4272004-06-13 20:20:40 +000010172 * Used for autocommands and 'wildignore'.
10173 * Returns TRUE if there is a match, FALSE otherwise.
10174 */
Bram Moolenaardffa5b82014-11-19 16:38:07 +010010175 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010176match_file_pat(
10177 char_u *pattern, /* pattern to match with */
10178 regprog_T **prog, /* pre-compiled regprog or NULL */
10179 char_u *fname, /* full path of file name */
10180 char_u *sfname, /* short file name or NULL */
10181 char_u *tail, /* tail of path */
10182 int allow_dirs) /* allow matching with dir */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010183{
10184 regmatch_T regmatch;
10185 int result = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010186
Bram Moolenaar71afbfe2013-03-19 16:49:16 +010010187 regmatch.rm_ic = p_fic; /* ignore case if 'fileignorecase' is set */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010188 if (prog != NULL)
10189 regmatch.regprog = *prog;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010190 else
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010191 regmatch.regprog = vim_regcomp(pattern, RE_MAGIC);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010192
10193 /*
10194 * Try for a match with the pattern with:
10195 * 1. the full file name, when the pattern has a '/'.
10196 * 2. the short file name, when the pattern has a '/'.
10197 * 3. the tail of the file name, when the pattern has no '/'.
10198 */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010199 if (regmatch.regprog != NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +000010200 && ((allow_dirs
10201 && (vim_regexec(&regmatch, fname, (colnr_T)0)
10202 || (sfname != NULL
10203 && vim_regexec(&regmatch, sfname, (colnr_T)0))))
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010204 || (!allow_dirs && vim_regexec(&regmatch, tail, (colnr_T)0))))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010205 result = TRUE;
10206
Bram Moolenaardffa5b82014-11-19 16:38:07 +010010207 if (prog != NULL)
10208 *prog = regmatch.regprog;
10209 else
Bram Moolenaar473de612013-06-08 18:19:48 +020010210 vim_regfree(regmatch.regprog);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010211 return result;
10212}
Bram Moolenaar071d4272004-06-13 20:20:40 +000010213
10214#if defined(FEAT_WILDIGN) || defined(PROTO)
10215/*
10216 * Return TRUE if a file matches with a pattern in "list".
10217 * "list" is a comma-separated list of patterns, like 'wildignore'.
10218 * "sfname" is the short file name or NULL, "ffname" the long file name.
10219 */
10220 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010221match_file_list(char_u *list, char_u *sfname, char_u *ffname)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010222{
10223 char_u buf[100];
10224 char_u *tail;
10225 char_u *regpat;
10226 char allow_dirs;
10227 int match;
10228 char_u *p;
10229
10230 tail = gettail(sfname);
10231
10232 /* try all patterns in 'wildignore' */
10233 p = list;
10234 while (*p)
10235 {
10236 copy_option_part(&p, buf, 100, ",");
10237 regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, FALSE);
10238 if (regpat == NULL)
10239 break;
Bram Moolenaar748bf032005-02-02 23:04:36 +000010240 match = match_file_pat(regpat, NULL, ffname, sfname,
10241 tail, (int)allow_dirs);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010242 vim_free(regpat);
10243 if (match)
10244 return TRUE;
10245 }
10246 return FALSE;
10247}
10248#endif
10249
10250/*
10251 * Convert the given pattern "pat" which has shell style wildcards in it, into
10252 * a regular expression, and return the result in allocated memory. If there
10253 * is a directory path separator to be matched, then TRUE is put in
10254 * allow_dirs, otherwise FALSE is put there -- webb.
10255 * Handle backslashes before special characters, like "\*" and "\ ".
10256 *
Bram Moolenaar071d4272004-06-13 20:20:40 +000010257 * Returns NULL when out of memory.
10258 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010259 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010260file_pat_to_reg_pat(
10261 char_u *pat,
10262 char_u *pat_end, /* first char after pattern or NULL */
10263 char *allow_dirs, /* Result passed back out in here */
10264 int no_bslash UNUSED) /* Don't use a backward slash as pathsep */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010265{
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010266 int size = 2; /* '^' at start, '$' at end */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010267 char_u *endp;
10268 char_u *reg_pat;
10269 char_u *p;
10270 int i;
10271 int nested = 0;
10272 int add_dollar = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010273
10274 if (allow_dirs != NULL)
10275 *allow_dirs = FALSE;
10276 if (pat_end == NULL)
10277 pat_end = pat + STRLEN(pat);
10278
Bram Moolenaar071d4272004-06-13 20:20:40 +000010279 for (p = pat; p < pat_end; p++)
10280 {
10281 switch (*p)
10282 {
10283 case '*':
10284 case '.':
10285 case ',':
10286 case '{':
10287 case '}':
10288 case '~':
10289 size += 2; /* extra backslash */
10290 break;
10291#ifdef BACKSLASH_IN_FILENAME
10292 case '\\':
10293 case '/':
10294 size += 4; /* could become "[\/]" */
10295 break;
10296#endif
10297 default:
10298 size++;
Bram Moolenaar2288afe2015-08-11 16:20:05 +020010299# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010300 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010301 {
10302 ++p;
10303 ++size;
10304 }
10305# endif
10306 break;
10307 }
10308 }
10309 reg_pat = alloc(size + 1);
10310 if (reg_pat == NULL)
10311 return NULL;
10312
Bram Moolenaar071d4272004-06-13 20:20:40 +000010313 i = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010314
10315 if (pat[0] == '*')
10316 while (pat[0] == '*' && pat < pat_end - 1)
10317 pat++;
10318 else
10319 reg_pat[i++] = '^';
10320 endp = pat_end - 1;
Bram Moolenaar8fee8782015-08-11 18:45:48 +020010321 if (endp >= pat && *endp == '*')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010322 {
10323 while (endp - pat > 0 && *endp == '*')
10324 endp--;
10325 add_dollar = FALSE;
10326 }
10327 for (p = pat; *p && nested >= 0 && p <= endp; p++)
10328 {
10329 switch (*p)
10330 {
10331 case '*':
10332 reg_pat[i++] = '.';
10333 reg_pat[i++] = '*';
Bram Moolenaar02743632005-07-25 20:42:36 +000010334 while (p[1] == '*') /* "**" matches like "*" */
10335 ++p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010336 break;
10337 case '.':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010338 case '~':
10339 reg_pat[i++] = '\\';
10340 reg_pat[i++] = *p;
10341 break;
10342 case '?':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010343 reg_pat[i++] = '.';
10344 break;
10345 case '\\':
10346 if (p[1] == NUL)
10347 break;
10348#ifdef BACKSLASH_IN_FILENAME
10349 if (!no_bslash)
10350 {
10351 /* translate:
10352 * "\x" to "\\x" e.g., "dir\file"
10353 * "\*" to "\\.*" e.g., "dir\*.c"
10354 * "\?" to "\\." e.g., "dir\??.c"
10355 * "\+" to "\+" e.g., "fileX\+.c"
10356 */
10357 if ((vim_isfilec(p[1]) || p[1] == '*' || p[1] == '?')
10358 && p[1] != '+')
10359 {
10360 reg_pat[i++] = '[';
10361 reg_pat[i++] = '\\';
10362 reg_pat[i++] = '/';
10363 reg_pat[i++] = ']';
10364 if (allow_dirs != NULL)
10365 *allow_dirs = TRUE;
10366 break;
10367 }
10368 }
10369#endif
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010370 /* Undo escaping from ExpandEscape():
10371 * foo\?bar -> foo?bar
10372 * foo\%bar -> foo%bar
10373 * foo\,bar -> foo,bar
10374 * foo\ bar -> foo bar
10375 * Don't unescape \, * and others that are also special in a
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010376 * regexp.
10377 * An escaped { must be unescaped since we use magic not
Bram Moolenaara946afe2013-08-02 15:22:39 +020010378 * verymagic. Use "\\\{n,m\}"" to get "\{n,m}".
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010379 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010380 if (*++p == '?'
10381#ifdef BACKSLASH_IN_FILENAME
10382 && no_bslash
10383#endif
10384 )
10385 reg_pat[i++] = '?';
10386 else
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010387 if (*p == ',' || *p == '%' || *p == '#'
Bram Moolenaar2288afe2015-08-11 16:20:05 +020010388 || vim_isspace(*p) || *p == '{' || *p == '}')
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010389 reg_pat[i++] = *p;
Bram Moolenaara946afe2013-08-02 15:22:39 +020010390 else if (*p == '\\' && p[1] == '\\' && p[2] == '{')
10391 {
10392 reg_pat[i++] = '\\';
10393 reg_pat[i++] = '{';
10394 p += 2;
10395 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010396 else
10397 {
10398 if (allow_dirs != NULL && vim_ispathsep(*p)
10399#ifdef BACKSLASH_IN_FILENAME
10400 && (!no_bslash || *p != '\\')
10401#endif
10402 )
10403 *allow_dirs = TRUE;
10404 reg_pat[i++] = '\\';
10405 reg_pat[i++] = *p;
10406 }
10407 break;
10408#ifdef BACKSLASH_IN_FILENAME
10409 case '/':
10410 reg_pat[i++] = '[';
10411 reg_pat[i++] = '\\';
10412 reg_pat[i++] = '/';
10413 reg_pat[i++] = ']';
10414 if (allow_dirs != NULL)
10415 *allow_dirs = TRUE;
10416 break;
10417#endif
10418 case '{':
10419 reg_pat[i++] = '\\';
10420 reg_pat[i++] = '(';
10421 nested++;
10422 break;
10423 case '}':
10424 reg_pat[i++] = '\\';
10425 reg_pat[i++] = ')';
10426 --nested;
10427 break;
10428 case ',':
10429 if (nested)
10430 {
10431 reg_pat[i++] = '\\';
10432 reg_pat[i++] = '|';
10433 }
10434 else
10435 reg_pat[i++] = ',';
10436 break;
10437 default:
10438# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010439 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010440 reg_pat[i++] = *p++;
10441 else
10442# endif
10443 if (allow_dirs != NULL && vim_ispathsep(*p))
10444 *allow_dirs = TRUE;
10445 reg_pat[i++] = *p;
10446 break;
10447 }
10448 }
10449 if (add_dollar)
10450 reg_pat[i++] = '$';
10451 reg_pat[i] = NUL;
10452 if (nested != 0)
10453 {
10454 if (nested < 0)
10455 EMSG(_("E219: Missing {."));
10456 else
10457 EMSG(_("E220: Missing }."));
Bram Moolenaard23a8232018-02-10 18:45:26 +010010458 VIM_CLEAR(reg_pat);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010459 }
10460 return reg_pat;
10461}
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010462
10463#if defined(EINTR) || defined(PROTO)
10464/*
10465 * Version of read() that retries when interrupted by EINTR (possibly
10466 * by a SIGWINCH).
10467 */
10468 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010469read_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010470{
10471 long ret;
10472
10473 for (;;)
10474 {
10475 ret = vim_read(fd, buf, bufsize);
10476 if (ret >= 0 || errno != EINTR)
10477 break;
10478 }
10479 return ret;
10480}
10481
10482/*
10483 * Version of write() that retries when interrupted by EINTR (possibly
10484 * by a SIGWINCH).
10485 */
10486 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010487write_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010488{
10489 long ret = 0;
10490 long wlen;
10491
10492 /* Repeat the write() so long it didn't fail, other than being interrupted
10493 * by a signal. */
10494 while (ret < (long)bufsize)
10495 {
Bram Moolenaar9c263032010-12-17 18:06:06 +010010496 wlen = vim_write(fd, (char *)buf + ret, bufsize - ret);
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010497 if (wlen < 0)
10498 {
10499 if (errno != EINTR)
10500 break;
10501 }
10502 else
10503 ret += wlen;
10504 }
10505 return ret;
10506}
10507#endif