blob: fd8fd243fd5ab02123e0662ed5a86c8c4e20a77a [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
Bram Moolenaard25c16e2016-01-29 22:13:30 +010042static int set_rw_fname(char_u *fname, char_u *sfname);
43static int msg_add_fileformat(int eol_type);
44static void msg_add_eol(void);
Bram Moolenaar8767f522016-07-01 17:17:39 +020045static int check_mtime(buf_T *buf, stat_T *s);
Bram Moolenaard25c16e2016-01-29 22:13:30 +010046static int time_differs(long t1, long t2);
Bram Moolenaard25c16e2016-01-29 22:13:30 +010047static int apply_autocmds_exarg(event_T event, char_u *fname, char_u *fname_io, int force, buf_T *buf, exarg_T *eap);
48static int au_find_group(char_u *name);
Bram Moolenaar70836c82006-02-20 21:28:49 +000049
50# define AUGROUP_DEFAULT -1 /* default autocmd group */
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +000051# define AUGROUP_ERROR -2 /* erroneous autocmd group */
Bram Moolenaar70836c82006-02-20 21:28:49 +000052# define AUGROUP_ALL -3 /* all autocmd groups */
Bram Moolenaar071d4272004-06-13 20:20:40 +000053
54#if defined(FEAT_CRYPT) || defined(FEAT_MBYTE)
55# define HAS_BW_FLAGS
56# define FIO_LATIN1 0x01 /* convert Latin1 */
57# define FIO_UTF8 0x02 /* convert UTF-8 */
58# define FIO_UCS2 0x04 /* convert UCS-2 */
59# define FIO_UCS4 0x08 /* convert UCS-4 */
60# define FIO_UTF16 0x10 /* convert UTF-16 */
61# ifdef WIN3264
62# define FIO_CODEPAGE 0x20 /* convert MS-Windows codepage */
63# define FIO_PUT_CP(x) (((x) & 0xffff) << 16) /* put codepage in top word */
64# define FIO_GET_CP(x) (((x)>>16) & 0xffff) /* get codepage from top word */
65# endif
Bram Moolenaard0573012017-10-28 21:11:06 +020066# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +000067# define FIO_MACROMAN 0x20 /* convert MacRoman */
68# endif
69# define FIO_ENDIAN_L 0x80 /* little endian */
70# define FIO_ENCRYPTED 0x1000 /* encrypt written bytes */
71# define FIO_NOCONVERT 0x2000 /* skip encoding conversion */
72# define FIO_UCSBOM 0x4000 /* check for BOM at start of file */
73# define FIO_ALL -1 /* allow all formats */
74#endif
75
76/* When converting, a read() or write() may leave some bytes to be converted
77 * for the next call. The value is guessed... */
78#define CONV_RESTLEN 30
79
80/* We have to guess how much a sequence of bytes may expand when converting
81 * with iconv() to be able to allocate a buffer. */
82#define ICONV_MULT 8
83
84/*
85 * Structure to pass arguments from buf_write() to buf_write_bytes().
86 */
87struct bw_info
88{
89 int bw_fd; /* file descriptor */
90 char_u *bw_buf; /* buffer with data to be written */
Bram Moolenaard089d9b2007-09-30 12:02:55 +000091 int bw_len; /* length of data */
Bram Moolenaar071d4272004-06-13 20:20:40 +000092#ifdef HAS_BW_FLAGS
93 int bw_flags; /* FIO_ flags */
94#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +020095#ifdef FEAT_CRYPT
96 buf_T *bw_buffer; /* buffer being written */
97#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000098#ifdef FEAT_MBYTE
99 char_u bw_rest[CONV_RESTLEN]; /* not converted bytes */
100 int bw_restlen; /* nr of bytes in bw_rest[] */
101 int bw_first; /* first write call */
102 char_u *bw_conv_buf; /* buffer for writing converted chars */
103 int bw_conv_buflen; /* size of bw_conv_buf */
104 int bw_conv_error; /* set for conversion error */
Bram Moolenaar32b485f2009-07-29 16:06:27 +0000105 linenr_T bw_conv_error_lnum; /* first line with error or zero */
106 linenr_T bw_start_lnum; /* line number at start of buffer */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000107# ifdef USE_ICONV
108 iconv_t bw_iconv_fd; /* descriptor for iconv() or -1 */
109# endif
110#endif
111};
112
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100113static int buf_write_bytes(struct bw_info *ip);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000114
115#ifdef FEAT_MBYTE
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100116static linenr_T readfile_linenr(linenr_T linecnt, char_u *p, char_u *endp);
117static int ucs2bytes(unsigned c, char_u **pp, int flags);
118static int need_conversion(char_u *fenc);
119static int get_fio_flags(char_u *ptr);
120static char_u *check_for_bom(char_u *p, long size, int *lenp, int flags);
121static int make_bom(char_u *buf, char_u *name);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000122# ifdef WIN3264
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100123static int get_win_fio_flags(char_u *ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000124# endif
Bram Moolenaard0573012017-10-28 21:11:06 +0200125# ifdef MACOS_CONVERT
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100126static int get_mac_fio_flags(char_u *ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000127# endif
128#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000129static char *e_auchangedbuf = N_("E812: Autocommands changed buffer or buffer name");
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000130
Bram Moolenaarc3691332016-04-20 12:49:49 +0200131/*
132 * Set by the apply_autocmds_group function if the given event is equal to
133 * EVENT_FILETYPE. Used by the readfile function in order to determine if
134 * EVENT_BUFREADPOST triggered the EVENT_FILETYPE.
135 *
136 * Relying on this value requires one to reset it prior calling
137 * apply_autocmds_group.
138 */
139static int au_did_filetype INIT(= FALSE);
Bram Moolenaarc3691332016-04-20 12:49:49 +0200140
Bram Moolenaar071d4272004-06-13 20:20:40 +0000141 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +0100142filemess(
143 buf_T *buf,
144 char_u *name,
145 char_u *s,
146 int attr)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000147{
148 int msg_scroll_save;
149
150 if (msg_silent != 0)
151 return;
152 msg_add_fname(buf, name); /* put file name in IObuff with quotes */
153 /* If it's extremely long, truncate it. */
154 if (STRLEN(IObuff) > IOSIZE - 80)
155 IObuff[IOSIZE - 80] = NUL;
156 STRCAT(IObuff, s);
157 /*
158 * For the first message may have to start a new line.
159 * For further ones overwrite the previous one, reset msg_scroll before
160 * calling filemess().
161 */
162 msg_scroll_save = msg_scroll;
163 if (shortmess(SHM_OVERALL) && !exiting && p_verbose == 0)
164 msg_scroll = FALSE;
165 if (!msg_scroll) /* wait a bit when overwriting an error msg */
166 check_for_delay(FALSE);
167 msg_start();
168 msg_scroll = msg_scroll_save;
169 msg_scrolled_ign = TRUE;
170 /* may truncate the message to avoid a hit-return prompt */
171 msg_outtrans_attr(msg_may_trunc(FALSE, IObuff), attr);
172 msg_clr_eos();
173 out_flush();
174 msg_scrolled_ign = FALSE;
175}
176
177/*
178 * Read lines from file "fname" into the buffer after line "from".
179 *
180 * 1. We allocate blocks with lalloc, as big as possible.
181 * 2. Each block is filled with characters from the file with a single read().
182 * 3. The lines are inserted in the buffer with ml_append().
183 *
184 * (caller must check that fname != NULL, unless READ_STDIN is used)
185 *
186 * "lines_to_skip" is the number of lines that must be skipped
187 * "lines_to_read" is the number of lines that are appended
188 * When not recovering lines_to_skip is 0 and lines_to_read MAXLNUM.
189 *
190 * flags:
191 * READ_NEW starting to edit a new buffer
192 * READ_FILTER reading filter output
193 * READ_STDIN read from stdin instead of a file
194 * READ_BUFFER read from curbuf instead of a file (converting after reading
195 * stdin)
196 * READ_DUMMY read into a dummy buffer (to check if file contents changed)
Bram Moolenaar59f931e2010-07-24 20:27:03 +0200197 * READ_KEEP_UNDO don't clear undo info or read it from a file
Bram Moolenaarf71d7b92016-08-09 22:14:05 +0200198 * READ_FIFO read from fifo/socket instead of a file
Bram Moolenaar071d4272004-06-13 20:20:40 +0000199 *
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100200 * return FAIL for failure, NOTDONE for directory (failure), or OK
Bram Moolenaar071d4272004-06-13 20:20:40 +0000201 */
202 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +0100203readfile(
204 char_u *fname,
205 char_u *sfname,
206 linenr_T from,
207 linenr_T lines_to_skip,
208 linenr_T lines_to_read,
209 exarg_T *eap, /* can be NULL! */
210 int flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000211{
212 int fd = 0;
213 int newfile = (flags & READ_NEW);
214 int check_readonly;
215 int filtering = (flags & READ_FILTER);
216 int read_stdin = (flags & READ_STDIN);
217 int read_buffer = (flags & READ_BUFFER);
Bram Moolenaarf71d7b92016-08-09 22:14:05 +0200218 int read_fifo = (flags & READ_FIFO);
Bram Moolenaar690ffc02008-01-04 15:31:21 +0000219 int set_options = newfile || read_buffer
220 || (eap != NULL && eap->read_edit);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000221 linenr_T read_buf_lnum = 1; /* next line to read from curbuf */
222 colnr_T read_buf_col = 0; /* next char to read from this line */
223 char_u c;
224 linenr_T lnum = from;
225 char_u *ptr = NULL; /* pointer into read buffer */
226 char_u *buffer = NULL; /* read buffer */
227 char_u *new_buffer = NULL; /* init to shut up gcc */
228 char_u *line_start = NULL; /* init to shut up gcc */
229 int wasempty; /* buffer was empty before reading */
230 colnr_T len;
231 long size = 0;
232 char_u *p;
Bram Moolenaar8767f522016-07-01 17:17:39 +0200233 off_T filesize = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000234 int skip_read = FALSE;
235#ifdef FEAT_CRYPT
236 char_u *cryptkey = NULL;
Bram Moolenaarf50a2532010-05-21 15:36:08 +0200237 int did_ask_for_key = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000238#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +0200239#ifdef FEAT_PERSISTENT_UNDO
240 context_sha256_T sha_ctx;
241 int read_undo_file = FALSE;
242#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000243 int split = 0; /* number of split lines */
244#define UNKNOWN 0x0fffffff /* file size is unknown */
245 linenr_T linecnt;
246 int error = FALSE; /* errors encountered */
247 int ff_error = EOL_UNKNOWN; /* file format with errors */
248 long linerest = 0; /* remaining chars in line */
249#ifdef UNIX
250 int perm = 0;
251 int swap_mode = -1; /* protection bits for swap file */
252#else
253 int perm;
254#endif
255 int fileformat = 0; /* end-of-line format */
256 int keep_fileformat = FALSE;
Bram Moolenaar8767f522016-07-01 17:17:39 +0200257 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000258 int file_readonly;
259 linenr_T skip_count = 0;
260 linenr_T read_count = 0;
261 int msg_save = msg_scroll;
262 linenr_T read_no_eol_lnum = 0; /* non-zero lnum when last line of
263 * last read was missing the eol */
Bram Moolenaar7a2699e2017-01-23 21:31:09 +0100264 int try_mac;
265 int try_dos;
266 int try_unix;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000267 int file_rewind = FALSE;
268#ifdef FEAT_MBYTE
269 int can_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000270 linenr_T conv_error = 0; /* line nr with conversion error */
271 linenr_T illegal_byte = 0; /* line nr with illegal byte */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000272 int keep_dest_enc = FALSE; /* don't retry when char doesn't fit
273 in destination encoding */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000274 int bad_char_behavior = BAD_REPLACE;
275 /* BAD_KEEP, BAD_DROP or character to
276 * replace with */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000277 char_u *tmpname = NULL; /* name of 'charconvert' output file */
278 int fio_flags = 0;
279 char_u *fenc; /* fileencoding to use */
280 int fenc_alloced; /* fenc_next is in allocated memory */
281 char_u *fenc_next = NULL; /* next item in 'fencs' or NULL */
282 int advance_fenc = FALSE;
283 long real_size = 0;
284# ifdef USE_ICONV
285 iconv_t iconv_fd = (iconv_t)-1; /* descriptor for iconv() or -1 */
286# ifdef FEAT_EVAL
287 int did_iconv = FALSE; /* TRUE when iconv() failed and trying
288 'charconvert' next */
289# endif
290# endif
291 int converted = FALSE; /* TRUE if conversion done */
292 int notconverted = FALSE; /* TRUE if conversion wanted but it
293 wasn't possible */
294 char_u conv_rest[CONV_RESTLEN];
295 int conv_restlen = 0; /* nr of bytes in conv_rest[] */
296#endif
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200297 buf_T *old_curbuf;
298 char_u *old_b_ffname;
299 char_u *old_b_fname;
300 int using_b_ffname;
301 int using_b_fname;
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200302
Bram Moolenaarc3691332016-04-20 12:49:49 +0200303 au_did_filetype = FALSE; /* reset before triggering any autocommands */
Bram Moolenaarc3691332016-04-20 12:49:49 +0200304
Bram Moolenaarcab35ad2011-02-15 17:39:22 +0100305 curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000306
307 /*
308 * If there is no file name yet, use the one for the read file.
309 * BF_NOTEDITED is set to reflect this.
310 * Don't do this for a read from a filter.
311 * Only do this when 'cpoptions' contains the 'f' flag.
312 */
313 if (curbuf->b_ffname == NULL
314 && !filtering
315 && fname != NULL
316 && vim_strchr(p_cpo, CPO_FNAMER) != NULL
317 && !(flags & READ_DUMMY))
318 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000319 if (set_rw_fname(fname, sfname) == FAIL)
320 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000321 }
322
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200323 /* Remember the initial values of curbuf, curbuf->b_ffname and
324 * curbuf->b_fname to detect whether they are altered as a result of
325 * executing nasty autocommands. Also check if "fname" and "sfname"
326 * point to one of these values. */
327 old_curbuf = curbuf;
328 old_b_ffname = curbuf->b_ffname;
329 old_b_fname = curbuf->b_fname;
330 using_b_ffname = (fname == curbuf->b_ffname)
331 || (sfname == curbuf->b_ffname);
332 using_b_fname = (fname == curbuf->b_fname) || (sfname == curbuf->b_fname);
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200333
Bram Moolenaardf177f62005-02-22 08:39:57 +0000334 /* After reading a file the cursor line changes but we don't want to
335 * display the line. */
336 ex_no_reprint = TRUE;
337
Bram Moolenaar55b7cf82006-09-09 12:52:42 +0000338 /* don't display the file info for another buffer now */
339 need_fileinfo = FALSE;
340
Bram Moolenaar071d4272004-06-13 20:20:40 +0000341 /*
342 * For Unix: Use the short file name whenever possible.
343 * Avoids problems with networks and when directory names are changed.
344 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
345 * another directory, which we don't detect.
346 */
347 if (sfname == NULL)
348 sfname = fname;
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200349#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000350 fname = sfname;
351#endif
352
Bram Moolenaar071d4272004-06-13 20:20:40 +0000353 /*
354 * The BufReadCmd and FileReadCmd events intercept the reading process by
355 * executing the associated commands instead.
356 */
357 if (!filtering && !read_stdin && !read_buffer)
358 {
359 pos_T pos;
360
361 pos = curbuf->b_op_start;
362
363 /* Set '[ mark to the line above where the lines go (line 1 if zero). */
364 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
365 curbuf->b_op_start.col = 0;
366
367 if (newfile)
368 {
369 if (apply_autocmds_exarg(EVENT_BUFREADCMD, NULL, sfname,
370 FALSE, curbuf, eap))
371#ifdef FEAT_EVAL
372 return aborting() ? FAIL : OK;
373#else
374 return OK;
375#endif
376 }
377 else if (apply_autocmds_exarg(EVENT_FILEREADCMD, sfname, sfname,
378 FALSE, NULL, eap))
379#ifdef FEAT_EVAL
380 return aborting() ? FAIL : OK;
381#else
382 return OK;
383#endif
384
385 curbuf->b_op_start = pos;
386 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000387
388 if ((shortmess(SHM_OVER) || curbuf->b_help) && p_verbose == 0)
389 msg_scroll = FALSE; /* overwrite previous file message */
390 else
391 msg_scroll = TRUE; /* don't overwrite previous file message */
392
393 /*
394 * If the name ends in a path separator, we can't open it. Check here,
395 * because reading the file may actually work, but then creating the swap
396 * file may destroy it! Reported on MS-DOS and Win 95.
397 * If the name is too long we might crash further on, quit here.
398 */
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000399 if (fname != NULL && *fname != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000400 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000401 p = fname + STRLEN(fname);
402 if (after_pathsep(fname, p) || STRLEN(fname) >= MAXPATHL)
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000403 {
404 filemess(curbuf, fname, (char_u *)_("Illegal file name"), 0);
405 msg_end();
406 msg_scroll = msg_save;
407 return FAIL;
408 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000409 }
410
Bram Moolenaarf71d7b92016-08-09 22:14:05 +0200411 if (!read_stdin && !read_buffer && !read_fifo)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000412 {
Bram Moolenaar4e4f5292013-08-30 17:07:01 +0200413#ifdef UNIX
414 /*
415 * On Unix it is possible to read a directory, so we have to
416 * check for it before the mch_open().
417 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000418 perm = mch_getperm(fname);
419 if (perm >= 0 && !S_ISREG(perm) /* not a regular file ... */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000420 && !S_ISFIFO(perm) /* ... or fifo */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000421 && !S_ISSOCK(perm) /* ... or socket */
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +0000422# ifdef OPEN_CHR_FILES
423 && !(S_ISCHR(perm) && is_dev_fd_file(fname))
424 /* ... or a character special file named /dev/fd/<n> */
425# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000426 )
427 {
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100428 int retval = FAIL;
429
Bram Moolenaar071d4272004-06-13 20:20:40 +0000430 if (S_ISDIR(perm))
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100431 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000432 filemess(curbuf, fname, (char_u *)_("is a directory"), 0);
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100433 retval = NOTDONE;
434 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000435 else
436 filemess(curbuf, fname, (char_u *)_("is not a file"), 0);
437 msg_end();
438 msg_scroll = msg_save;
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100439 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000440 }
Bram Moolenaar4e4f5292013-08-30 17:07:01 +0200441#endif
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100442#if defined(MSWIN)
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000443 /*
444 * MS-Windows allows opening a device, but we will probably get stuck
445 * trying to read it.
446 */
447 if (!p_odev && mch_nodetype(fname) == NODE_WRITABLE)
448 {
Bram Moolenaar5386a122007-06-28 20:02:32 +0000449 filemess(curbuf, fname, (char_u *)_("is a device (disabled with 'opendevice' option)"), 0);
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000450 msg_end();
451 msg_scroll = msg_save;
452 return FAIL;
453 }
Bram Moolenaar043545e2006-10-10 16:44:07 +0000454#endif
Bram Moolenaar4e4f5292013-08-30 17:07:01 +0200455 }
Bram Moolenaar043545e2006-10-10 16:44:07 +0000456
Bram Moolenaarad875fb2013-07-24 15:02:03 +0200457 /* Set default or forced 'fileformat' and 'binary'. */
458 set_file_options(set_options, eap);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000459
460 /*
461 * When opening a new file we take the readonly flag from the file.
462 * Default is r/w, can be set to r/o below.
463 * Don't reset it when in readonly mode
464 * Only set/reset b_p_ro when BF_CHECK_RO is set.
465 */
466 check_readonly = (newfile && (curbuf->b_flags & BF_CHECK_RO));
Bram Moolenaar4399ef42005-02-12 14:29:27 +0000467 if (check_readonly && !readonlymode)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000468 curbuf->b_p_ro = FALSE;
469
Bram Moolenaarf71d7b92016-08-09 22:14:05 +0200470 if (newfile && !read_stdin && !read_buffer && !read_fifo)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000471 {
Bram Moolenaare60acc12011-05-10 16:41:25 +0200472 /* Remember time of file. */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000473 if (mch_stat((char *)fname, &st) >= 0)
474 {
475 buf_store_time(curbuf, &st, fname);
476 curbuf->b_mtime_read = curbuf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000477#ifdef UNIX
478 /*
479 * Use the protection bits of the original file for the swap file.
480 * This makes it possible for others to read the name of the
481 * edited file from the swapfile, but only if they can read the
482 * edited file.
483 * Remove the "write" and "execute" bits for group and others
484 * (they must not write the swapfile).
485 * Add the "read" and "write" bits for the user, otherwise we may
486 * not be able to write to the file ourselves.
487 * Setting the bits is done below, after creating the swap file.
488 */
489 swap_mode = (st.st_mode & 0644) | 0600;
490#endif
491#ifdef FEAT_CW_EDITOR
492 /* Get the FSSpec on MacOS
493 * TODO: Update it properly when the buffer name changes
494 */
495 (void)GetFSSpecFromPath(curbuf->b_ffname, &curbuf->b_FSSpec);
496#endif
497#ifdef VMS
498 curbuf->b_fab_rfm = st.st_fab_rfm;
Bram Moolenaard4755bb2004-09-02 19:12:26 +0000499 curbuf->b_fab_rat = st.st_fab_rat;
500 curbuf->b_fab_mrs = st.st_fab_mrs;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000501#endif
502 }
503 else
504 {
505 curbuf->b_mtime = 0;
506 curbuf->b_mtime_read = 0;
507 curbuf->b_orig_size = 0;
508 curbuf->b_orig_mode = 0;
509 }
510
511 /* Reset the "new file" flag. It will be set again below when the
512 * file doesn't exist. */
513 curbuf->b_flags &= ~(BF_NEW | BF_NEW_W);
514 }
515
516/*
517 * for UNIX: check readonly with perm and mch_access()
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100518 * for Amiga: check readonly by trying to open the file for writing
Bram Moolenaar071d4272004-06-13 20:20:40 +0000519 */
520 file_readonly = FALSE;
521 if (read_stdin)
522 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100523#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000524 /* Force binary I/O on stdin to avoid CR-LF -> LF conversion. */
525 setmode(0, O_BINARY);
526#endif
527 }
528 else if (!read_buffer)
529 {
530#ifdef USE_MCH_ACCESS
531 if (
532# ifdef UNIX
533 !(perm & 0222) ||
534# endif
535 mch_access((char *)fname, W_OK))
536 file_readonly = TRUE;
537 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
538#else
539 if (!newfile
540 || readonlymode
541 || (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0)
542 {
543 file_readonly = TRUE;
544 /* try to open ro */
545 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
546 }
547#endif
548 }
549
550 if (fd < 0) /* cannot open at all */
551 {
552#ifndef UNIX
553 int isdir_f;
554#endif
555 msg_scroll = msg_save;
556#ifndef UNIX
557 /*
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100558 * On Amiga we can't open a directory, check here.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000559 */
560 isdir_f = (mch_isdir(fname));
561 perm = mch_getperm(fname); /* check if the file exists */
562 if (isdir_f)
563 {
564 filemess(curbuf, sfname, (char_u *)_("is a directory"), 0);
565 curbuf->b_p_ro = TRUE; /* must use "w!" now */
566 }
567 else
568#endif
569 if (newfile)
570 {
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200571 if (perm < 0
572#ifdef ENOENT
573 && errno == ENOENT
574#endif
575 )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000576 {
577 /*
578 * Set the 'new-file' flag, so that when the file has
579 * been created by someone else, a ":w" will complain.
580 */
581 curbuf->b_flags |= BF_NEW;
582
583 /* Create a swap file now, so that other Vims are warned
584 * that we are editing this file. Don't do this for a
585 * "nofile" or "nowrite" buffer type. */
586#ifdef FEAT_QUICKFIX
587 if (!bt_dontwrite(curbuf))
588#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000589 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000590 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000591 /* SwapExists autocommand may mess things up */
592 if (curbuf != old_curbuf
593 || (using_b_ffname
594 && (old_b_ffname != curbuf->b_ffname))
595 || (using_b_fname
596 && (old_b_fname != curbuf->b_fname)))
597 {
598 EMSG(_(e_auchangedbuf));
599 return FAIL;
600 }
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000601 }
Bram Moolenaar5b962cf2005-12-12 21:58:40 +0000602 if (dir_of_file_exists(fname))
603 filemess(curbuf, sfname, (char_u *)_("[New File]"), 0);
604 else
605 filemess(curbuf, sfname,
606 (char_u *)_("[New DIRECTORY]"), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000607#ifdef FEAT_VIMINFO
608 /* Even though this is a new file, it might have been
609 * edited before and deleted. Get the old marks. */
610 check_marks_read();
611#endif
612#ifdef FEAT_MBYTE
Bram Moolenaarad875fb2013-07-24 15:02:03 +0200613 /* Set forced 'fileencoding'. */
614 if (eap != NULL)
615 set_forced_fenc(eap);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000616#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000617 apply_autocmds_exarg(EVENT_BUFNEWFILE, sfname, sfname,
618 FALSE, curbuf, eap);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000619 /* remember the current fileformat */
620 save_file_ff(curbuf);
621
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +0100622#if defined(FEAT_EVAL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000623 if (aborting()) /* autocmds may abort script processing */
624 return FAIL;
625#endif
626 return OK; /* a new file is not an error */
627 }
628 else
629 {
Bram Moolenaar202795b2005-10-11 20:29:39 +0000630 filemess(curbuf, sfname, (char_u *)(
631# ifdef EFBIG
632 (errno == EFBIG) ? _("[File too big]") :
633# endif
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200634# ifdef EOVERFLOW
635 (errno == EOVERFLOW) ? _("[File too big]") :
636# endif
Bram Moolenaar202795b2005-10-11 20:29:39 +0000637 _("[Permission Denied]")), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000638 curbuf->b_p_ro = TRUE; /* must use "w!" now */
639 }
640 }
641
642 return FAIL;
643 }
644
645 /*
646 * Only set the 'ro' flag for readonly files the first time they are
647 * loaded. Help files always get readonly mode
648 */
649 if ((check_readonly && file_readonly) || curbuf->b_help)
650 curbuf->b_p_ro = TRUE;
651
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000652 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000653 {
Bram Moolenaar690ffc02008-01-04 15:31:21 +0000654 /* Don't change 'eol' if reading from buffer as it will already be
655 * correctly set when reading stdin. */
656 if (!read_buffer)
657 {
658 curbuf->b_p_eol = TRUE;
659 curbuf->b_start_eol = TRUE;
660 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000661#ifdef FEAT_MBYTE
662 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000663 curbuf->b_start_bomb = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000664#endif
665 }
666
667 /* Create a swap file now, so that other Vims are warned that we are
668 * editing this file.
669 * Don't do this for a "nofile" or "nowrite" buffer type. */
670#ifdef FEAT_QUICKFIX
671 if (!bt_dontwrite(curbuf))
672#endif
673 {
674 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000675 if (!read_stdin && (curbuf != old_curbuf
676 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
677 || (using_b_fname && (old_b_fname != curbuf->b_fname))))
678 {
679 EMSG(_(e_auchangedbuf));
680 if (!read_buffer)
681 close(fd);
682 return FAIL;
683 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000684#ifdef UNIX
685 /* Set swap file protection bits after creating it. */
Bram Moolenaarf061e0b2009-06-24 15:32:01 +0000686 if (swap_mode > 0 && curbuf->b_ml.ml_mfp != NULL
687 && curbuf->b_ml.ml_mfp->mf_fname != NULL)
Bram Moolenaar5a73e0c2017-11-04 21:35:01 +0100688 {
689 char_u *swap_fname = curbuf->b_ml.ml_mfp->mf_fname;
690
691 /*
692 * If the group-read bit is set but not the world-read bit, then
693 * the group must be equal to the group of the original file. If
694 * we can't make that happen then reset the group-read bit. This
695 * avoids making the swap file readable to more users when the
696 * primary group of the user is too permissive.
697 */
698 if ((swap_mode & 044) == 040)
699 {
700 stat_T swap_st;
701
702 if (mch_stat((char *)swap_fname, &swap_st) >= 0
703 && st.st_gid != swap_st.st_gid
Bram Moolenaar02e802b2018-04-19 21:15:27 +0200704# ifdef HAVE_FCHOWN
Bram Moolenaar5a73e0c2017-11-04 21:35:01 +0100705 && fchown(curbuf->b_ml.ml_mfp->mf_fd, -1, st.st_gid)
Bram Moolenaar02e802b2018-04-19 21:15:27 +0200706 == -1
Bram Moolenaar1f131ae2018-05-21 13:39:40 +0200707# endif
Bram Moolenaar02e802b2018-04-19 21:15:27 +0200708 )
Bram Moolenaar5a73e0c2017-11-04 21:35:01 +0100709 swap_mode &= 0600;
710 }
711
712 (void)mch_setperm(swap_fname, (long)swap_mode);
713 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000714#endif
715 }
716
Bram Moolenaarb815dac2005-12-07 20:59:24 +0000717#if defined(HAS_SWAP_EXISTS_ACTION)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000718 /* If "Quit" selected at ATTENTION dialog, don't load the file */
719 if (swap_exists_action == SEA_QUIT)
720 {
721 if (!read_buffer && !read_stdin)
722 close(fd);
723 return FAIL;
724 }
725#endif
726
727 ++no_wait_return; /* don't wait for return yet */
728
729 /*
730 * Set '[ mark to the line above where the lines go (line 1 if zero).
731 */
732 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
733 curbuf->b_op_start.col = 0;
734
Bram Moolenaar7a2699e2017-01-23 21:31:09 +0100735 try_mac = (vim_strchr(p_ffs, 'm') != NULL);
736 try_dos = (vim_strchr(p_ffs, 'd') != NULL);
737 try_unix = (vim_strchr(p_ffs, 'x') != NULL);
738
Bram Moolenaar071d4272004-06-13 20:20:40 +0000739 if (!read_buffer)
740 {
741 int m = msg_scroll;
742 int n = msg_scrolled;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000743
744 /*
745 * The file must be closed again, the autocommands may want to change
746 * the file before reading it.
747 */
748 if (!read_stdin)
749 close(fd); /* ignore errors */
750
751 /*
752 * The output from the autocommands should not overwrite anything and
753 * should not be overwritten: Set msg_scroll, restore its value if no
754 * output was done.
755 */
756 msg_scroll = TRUE;
757 if (filtering)
758 apply_autocmds_exarg(EVENT_FILTERREADPRE, NULL, sfname,
759 FALSE, curbuf, eap);
760 else if (read_stdin)
761 apply_autocmds_exarg(EVENT_STDINREADPRE, NULL, sfname,
762 FALSE, curbuf, eap);
763 else if (newfile)
764 apply_autocmds_exarg(EVENT_BUFREADPRE, NULL, sfname,
765 FALSE, curbuf, eap);
766 else
767 apply_autocmds_exarg(EVENT_FILEREADPRE, sfname, sfname,
768 FALSE, NULL, eap);
Bram Moolenaar7a2699e2017-01-23 21:31:09 +0100769 /* autocommands may have changed it */
770 try_mac = (vim_strchr(p_ffs, 'm') != NULL);
771 try_dos = (vim_strchr(p_ffs, 'd') != NULL);
772 try_unix = (vim_strchr(p_ffs, 'x') != NULL);
773
Bram Moolenaar071d4272004-06-13 20:20:40 +0000774 if (msg_scrolled == n)
775 msg_scroll = m;
776
777#ifdef FEAT_EVAL
778 if (aborting()) /* autocmds may abort script processing */
779 {
780 --no_wait_return;
781 msg_scroll = msg_save;
782 curbuf->b_p_ro = TRUE; /* must use "w!" now */
783 return FAIL;
784 }
785#endif
786 /*
787 * Don't allow the autocommands to change the current buffer.
788 * Try to re-open the file.
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000789 *
790 * Don't allow the autocommands to change the buffer name either
791 * (cd for example) if it invalidates fname or sfname.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000792 */
793 if (!read_stdin && (curbuf != old_curbuf
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000794 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
795 || (using_b_fname && (old_b_fname != curbuf->b_fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000796 || (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) < 0))
797 {
798 --no_wait_return;
799 msg_scroll = msg_save;
800 if (fd < 0)
801 EMSG(_("E200: *ReadPre autocommands made the file unreadable"));
802 else
803 EMSG(_("E201: *ReadPre autocommands must not change current buffer"));
804 curbuf->b_p_ro = TRUE; /* must use "w!" now */
805 return FAIL;
806 }
807 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000808
809 /* Autocommands may add lines to the file, need to check if it is empty */
810 wasempty = (curbuf->b_ml.ml_flags & ML_EMPTY);
811
812 if (!recoverymode && !filtering && !(flags & READ_DUMMY))
813 {
814 /*
815 * Show the user that we are busy reading the input. Sometimes this
816 * may take a while. When reading from stdin another program may
817 * still be running, don't move the cursor to the last line, unless
818 * always using the GUI.
819 */
820 if (read_stdin)
821 {
Bram Moolenaar234d1622017-11-18 14:55:23 +0100822 if (!is_not_a_term())
823 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000824#ifndef ALWAYS_USE_GUI
Bram Moolenaar234d1622017-11-18 14:55:23 +0100825 mch_msg(_("Vim: Reading from stdin...\n"));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000826#endif
827#ifdef FEAT_GUI
Bram Moolenaar234d1622017-11-18 14:55:23 +0100828 /* Also write a message in the GUI window, if there is one. */
829 if (gui.in_use && !gui.dying && !gui.starting)
830 {
831 p = (char_u *)_("Reading from stdin...");
832 gui_write(p, (int)STRLEN(p));
833 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000834#endif
Bram Moolenaar234d1622017-11-18 14:55:23 +0100835 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000836 }
837 else if (!read_buffer)
838 filemess(curbuf, sfname, (char_u *)"", 0);
839 }
840
841 msg_scroll = FALSE; /* overwrite the file message */
842
843 /*
844 * Set linecnt now, before the "retry" caused by a wrong guess for
845 * fileformat, and after the autocommands, which may change them.
846 */
847 linecnt = curbuf->b_ml.ml_line_count;
848
849#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000850 /* "++bad=" argument. */
851 if (eap != NULL && eap->bad_char != 0)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000852 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000853 bad_char_behavior = eap->bad_char;
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000854 if (set_options)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000855 curbuf->b_bad_char = eap->bad_char;
856 }
857 else
858 curbuf->b_bad_char = 0;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000859
Bram Moolenaar071d4272004-06-13 20:20:40 +0000860 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000861 * Decide which 'encoding' to use or use first.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000862 */
863 if (eap != NULL && eap->force_enc != 0)
864 {
865 fenc = enc_canonize(eap->cmd + eap->force_enc);
866 fenc_alloced = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000867 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000868 }
869 else if (curbuf->b_p_bin)
870 {
871 fenc = (char_u *)""; /* binary: don't convert */
872 fenc_alloced = FALSE;
873 }
874 else if (curbuf->b_help)
875 {
876 char_u firstline[80];
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000877 int fc;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000878
879 /* Help files are either utf-8 or latin1. Try utf-8 first, if this
880 * fails it must be latin1.
881 * Always do this when 'encoding' is "utf-8". Otherwise only do
882 * this when needed to avoid [converted] remarks all the time.
883 * It is needed when the first line contains non-ASCII characters.
884 * That is only in *.??x files. */
885 fenc = (char_u *)"latin1";
886 c = enc_utf8;
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000887 if (!c && !read_stdin)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000888 {
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000889 fc = fname[STRLEN(fname) - 1];
890 if (TOLOWER_ASC(fc) == 'x')
891 {
892 /* Read the first line (and a bit more). Immediately rewind to
893 * the start of the file. If the read() fails "len" is -1. */
Bram Moolenaar540fc6f2010-12-17 16:27:16 +0100894 len = read_eintr(fd, firstline, 80);
Bram Moolenaar8767f522016-07-01 17:17:39 +0200895 vim_lseek(fd, (off_T)0L, SEEK_SET);
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000896 for (p = firstline; p < firstline + len; ++p)
897 if (*p >= 0x80)
898 {
899 c = TRUE;
900 break;
901 }
902 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000903 }
904
905 if (c)
906 {
907 fenc_next = fenc;
908 fenc = (char_u *)"utf-8";
909
910 /* When the file is utf-8 but a character doesn't fit in
911 * 'encoding' don't retry. In help text editing utf-8 bytes
912 * doesn't make sense. */
Bram Moolenaarf193fff2006-04-27 00:02:13 +0000913 if (!enc_utf8)
914 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000915 }
916 fenc_alloced = FALSE;
917 }
918 else if (*p_fencs == NUL)
919 {
920 fenc = curbuf->b_p_fenc; /* use format from buffer */
921 fenc_alloced = FALSE;
922 }
923 else
924 {
925 fenc_next = p_fencs; /* try items in 'fileencodings' */
926 fenc = next_fenc(&fenc_next);
927 fenc_alloced = TRUE;
928 }
929#endif
930
931 /*
932 * Jump back here to retry reading the file in different ways.
933 * Reasons to retry:
934 * - encoding conversion failed: try another one from "fenc_next"
935 * - BOM detected and fenc was set, need to setup conversion
936 * - "fileformat" check failed: try another
937 *
938 * Variables set for special retry actions:
939 * "file_rewind" Rewind the file to start reading it again.
940 * "advance_fenc" Advance "fenc" using "fenc_next".
941 * "skip_read" Re-use already read bytes (BOM detected).
942 * "did_iconv" iconv() conversion failed, try 'charconvert'.
943 * "keep_fileformat" Don't reset "fileformat".
944 *
945 * Other status indicators:
946 * "tmpname" When != NULL did conversion with 'charconvert'.
947 * Output file has to be deleted afterwards.
948 * "iconv_fd" When != -1 did conversion with iconv().
949 */
950retry:
951
952 if (file_rewind)
953 {
954 if (read_buffer)
955 {
956 read_buf_lnum = 1;
957 read_buf_col = 0;
958 }
Bram Moolenaar8767f522016-07-01 17:17:39 +0200959 else if (read_stdin || vim_lseek(fd, (off_T)0L, SEEK_SET) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000960 {
961 /* Can't rewind the file, give up. */
962 error = TRUE;
963 goto failed;
964 }
965 /* Delete the previously read lines. */
966 while (lnum > from)
967 ml_delete(lnum--, FALSE);
968 file_rewind = FALSE;
969#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000970 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000971 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000972 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000973 curbuf->b_start_bomb = FALSE;
974 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000975 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000976#endif
977 }
978
979 /*
980 * When retrying with another "fenc" and the first time "fileformat"
981 * will be reset.
982 */
983 if (keep_fileformat)
984 keep_fileformat = FALSE;
985 else
986 {
987 if (eap != NULL && eap->force_ff != 0)
Bram Moolenaar1c860362008-11-12 15:05:21 +0000988 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000989 fileformat = get_fileformat_force(curbuf, eap);
Bram Moolenaar1c860362008-11-12 15:05:21 +0000990 try_unix = try_dos = try_mac = FALSE;
991 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000992 else if (curbuf->b_p_bin)
993 fileformat = EOL_UNIX; /* binary: use Unix format */
994 else if (*p_ffs == NUL)
995 fileformat = get_fileformat(curbuf);/* use format from buffer */
996 else
997 fileformat = EOL_UNKNOWN; /* detect from file */
998 }
999
1000#ifdef FEAT_MBYTE
1001# ifdef USE_ICONV
1002 if (iconv_fd != (iconv_t)-1)
1003 {
1004 /* aborted conversion with iconv(), close the descriptor */
1005 iconv_close(iconv_fd);
1006 iconv_fd = (iconv_t)-1;
1007 }
1008# endif
1009
1010 if (advance_fenc)
1011 {
1012 /*
1013 * Try the next entry in 'fileencodings'.
1014 */
1015 advance_fenc = FALSE;
1016
1017 if (eap != NULL && eap->force_enc != 0)
1018 {
1019 /* Conversion given with "++cc=" wasn't possible, read
1020 * without conversion. */
1021 notconverted = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001022 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001023 if (fenc_alloced)
1024 vim_free(fenc);
1025 fenc = (char_u *)"";
1026 fenc_alloced = FALSE;
1027 }
1028 else
1029 {
1030 if (fenc_alloced)
1031 vim_free(fenc);
1032 if (fenc_next != NULL)
1033 {
1034 fenc = next_fenc(&fenc_next);
1035 fenc_alloced = (fenc_next != NULL);
1036 }
1037 else
1038 {
1039 fenc = (char_u *)"";
1040 fenc_alloced = FALSE;
1041 }
1042 }
1043 if (tmpname != NULL)
1044 {
1045 mch_remove(tmpname); /* delete converted file */
Bram Moolenaard23a8232018-02-10 18:45:26 +01001046 VIM_CLEAR(tmpname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001047 }
1048 }
1049
1050 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001051 * Conversion may be required when the encoding of the file is different
1052 * from 'encoding' or 'encoding' is UTF-16, UCS-2 or UCS-4.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001053 */
1054 fio_flags = 0;
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001055 converted = need_conversion(fenc);
1056 if (converted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001057 {
1058
1059 /* "ucs-bom" means we need to check the first bytes of the file
1060 * for a BOM. */
1061 if (STRCMP(fenc, ENC_UCSBOM) == 0)
1062 fio_flags = FIO_UCSBOM;
1063
1064 /*
1065 * Check if UCS-2/4 or Latin1 to UTF-8 conversion needs to be
1066 * done. This is handled below after read(). Prepare the
1067 * fio_flags to avoid having to parse the string each time.
1068 * Also check for Unicode to Latin1 conversion, because iconv()
1069 * appears not to handle this correctly. This works just like
1070 * conversion to UTF-8 except how the resulting character is put in
1071 * the buffer.
1072 */
1073 else if (enc_utf8 || STRCMP(p_enc, "latin1") == 0)
1074 fio_flags = get_fio_flags(fenc);
1075
1076# ifdef WIN3264
1077 /*
1078 * Conversion from an MS-Windows codepage to UTF-8 or another codepage
1079 * is handled with MultiByteToWideChar().
1080 */
1081 if (fio_flags == 0)
1082 fio_flags = get_win_fio_flags(fenc);
1083# endif
1084
Bram Moolenaard0573012017-10-28 21:11:06 +02001085# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001086 /* Conversion from Apple MacRoman to latin1 or UTF-8 */
1087 if (fio_flags == 0)
1088 fio_flags = get_mac_fio_flags(fenc);
1089# endif
1090
1091# ifdef USE_ICONV
1092 /*
1093 * Try using iconv() if we can't convert internally.
1094 */
1095 if (fio_flags == 0
1096# ifdef FEAT_EVAL
1097 && !did_iconv
1098# endif
1099 )
1100 iconv_fd = (iconv_t)my_iconv_open(
1101 enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc);
1102# endif
1103
1104# ifdef FEAT_EVAL
1105 /*
1106 * Use the 'charconvert' expression when conversion is required
1107 * and we can't do it internally or with iconv().
1108 */
1109 if (fio_flags == 0 && !read_stdin && !read_buffer && *p_ccv != NUL
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02001110 && !read_fifo
Bram Moolenaar071d4272004-06-13 20:20:40 +00001111# ifdef USE_ICONV
1112 && iconv_fd == (iconv_t)-1
1113# endif
1114 )
1115 {
1116# ifdef USE_ICONV
1117 did_iconv = FALSE;
1118# endif
1119 /* Skip conversion when it's already done (retry for wrong
1120 * "fileformat"). */
1121 if (tmpname == NULL)
1122 {
1123 tmpname = readfile_charconvert(fname, fenc, &fd);
1124 if (tmpname == NULL)
1125 {
1126 /* Conversion failed. Try another one. */
1127 advance_fenc = TRUE;
1128 if (fd < 0)
1129 {
1130 /* Re-opening the original file failed! */
1131 EMSG(_("E202: Conversion made file unreadable!"));
1132 error = TRUE;
1133 goto failed;
1134 }
1135 goto retry;
1136 }
1137 }
1138 }
1139 else
1140# endif
1141 {
1142 if (fio_flags == 0
1143# ifdef USE_ICONV
1144 && iconv_fd == (iconv_t)-1
1145# endif
1146 )
1147 {
1148 /* Conversion wanted but we can't.
1149 * Try the next conversion in 'fileencodings' */
1150 advance_fenc = TRUE;
1151 goto retry;
1152 }
1153 }
1154 }
1155
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001156 /* Set "can_retry" when it's possible to rewind the file and try with
Bram Moolenaar071d4272004-06-13 20:20:40 +00001157 * another "fenc" value. It's FALSE when no other "fenc" to try, reading
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001158 * stdin or fixed at a specific encoding. */
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02001159 can_retry = (*fenc != NUL && !read_stdin && !read_fifo && !keep_dest_enc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001160#endif
1161
1162 if (!skip_read)
1163 {
1164 linerest = 0;
1165 filesize = 0;
1166 skip_count = lines_to_skip;
1167 read_count = lines_to_read;
1168#ifdef FEAT_MBYTE
1169 conv_restlen = 0;
1170#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001171#ifdef FEAT_PERSISTENT_UNDO
Bram Moolenaar59f931e2010-07-24 20:27:03 +02001172 read_undo_file = (newfile && (flags & READ_KEEP_UNDO) == 0
1173 && curbuf->b_ffname != NULL
1174 && curbuf->b_p_udf
1175 && !filtering
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02001176 && !read_fifo
Bram Moolenaar59f931e2010-07-24 20:27:03 +02001177 && !read_stdin
1178 && !read_buffer);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001179 if (read_undo_file)
1180 sha256_start(&sha_ctx);
1181#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001182#ifdef FEAT_CRYPT
1183 if (curbuf->b_cryptstate != NULL)
1184 {
1185 /* Need to free the state, but keep the key, don't want to ask for
1186 * it again. */
1187 crypt_free_state(curbuf->b_cryptstate);
1188 curbuf->b_cryptstate = NULL;
1189 }
1190#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001191 }
1192
1193 while (!error && !got_int)
1194 {
1195 /*
1196 * We allocate as much space for the file as we can get, plus
1197 * space for the old line plus room for one terminating NUL.
1198 * The amount is limited by the fact that read() only can read
1199 * upto max_unsigned characters (and other things).
1200 */
Bram Moolenaar13d3b052018-04-29 13:34:47 +02001201 if (!skip_read)
1202 {
1203#if VIM_SIZEOF_INT > 2
1204# if defined(SSIZE_MAX) && (SSIZE_MAX < 0x10000L)
1205 size = SSIZE_MAX; /* use max I/O size, 52K */
1206# else
1207 /* Use buffer >= 64K. Add linerest to double the size if the
1208 * line gets very long, to avoid a lot of copying. But don't
1209 * read more than 1 Mbyte at a time, so we can be interrupted.
1210 */
1211 size = 0x10000L + linerest;
1212 if (size > 0x100000L)
1213 size = 0x100000L;
1214# endif
1215#else
1216 size = 0x7ff0L - linerest; /* limit buffer to 32K */
1217#endif
1218 }
1219
1220 /* Protect against the argument of lalloc() going negative. */
1221 if (
Bram Moolenaara2aa31a2014-02-23 22:52:40 +01001222#if VIM_SIZEOF_INT <= 2
Bram Moolenaar13d3b052018-04-29 13:34:47 +02001223 linerest >= 0x7ff0
1224#else
1225 size < 0 || size + linerest + 1 < 0 || linerest >= MAXCOL
1226#endif
1227 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001228 {
1229 ++split;
1230 *ptr = NL; /* split line by inserting a NL */
1231 size = 1;
1232 }
1233 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001234 {
1235 if (!skip_read)
1236 {
Bram Moolenaarc1e37902006-04-18 21:55:01 +00001237 for ( ; size >= 10; size = (long)((long_u)size >> 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001238 {
1239 if ((new_buffer = lalloc((long_u)(size + linerest + 1),
1240 FALSE)) != NULL)
1241 break;
1242 }
1243 if (new_buffer == NULL)
1244 {
1245 do_outofmem_msg((long_u)(size * 2 + linerest + 1));
1246 error = TRUE;
1247 break;
1248 }
1249 if (linerest) /* copy characters from the previous buffer */
1250 mch_memmove(new_buffer, ptr - linerest, (size_t)linerest);
1251 vim_free(buffer);
1252 buffer = new_buffer;
1253 ptr = buffer + linerest;
1254 line_start = buffer;
1255
1256#ifdef FEAT_MBYTE
1257 /* May need room to translate into.
1258 * For iconv() we don't really know the required space, use a
1259 * factor ICONV_MULT.
1260 * latin1 to utf-8: 1 byte becomes up to 2 bytes
1261 * utf-16 to utf-8: 2 bytes become up to 3 bytes, 4 bytes
1262 * become up to 4 bytes, size must be multiple of 2
1263 * ucs-2 to utf-8: 2 bytes become up to 3 bytes, size must be
1264 * multiple of 2
1265 * ucs-4 to utf-8: 4 bytes become up to 6 bytes, size must be
1266 * multiple of 4 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001267 real_size = (int)size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001268# ifdef USE_ICONV
1269 if (iconv_fd != (iconv_t)-1)
1270 size = size / ICONV_MULT;
1271 else
1272# endif
1273 if (fio_flags & FIO_LATIN1)
1274 size = size / 2;
1275 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1276 size = (size * 2 / 3) & ~1;
1277 else if (fio_flags & FIO_UCS4)
1278 size = (size * 2 / 3) & ~3;
1279 else if (fio_flags == FIO_UCSBOM)
1280 size = size / ICONV_MULT; /* worst case */
1281# ifdef WIN3264
1282 else if (fio_flags & FIO_CODEPAGE)
1283 size = size / ICONV_MULT; /* also worst case */
1284# endif
Bram Moolenaard0573012017-10-28 21:11:06 +02001285# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001286 else if (fio_flags & FIO_MACROMAN)
1287 size = size / ICONV_MULT; /* also worst case */
1288# endif
1289#endif
1290
1291#ifdef FEAT_MBYTE
1292 if (conv_restlen > 0)
1293 {
1294 /* Insert unconverted bytes from previous line. */
1295 mch_memmove(ptr, conv_rest, conv_restlen);
1296 ptr += conv_restlen;
1297 size -= conv_restlen;
1298 }
1299#endif
1300
1301 if (read_buffer)
1302 {
1303 /*
1304 * Read bytes from curbuf. Used for converting text read
1305 * from stdin.
1306 */
1307 if (read_buf_lnum > from)
1308 size = 0;
1309 else
1310 {
1311 int n, ni;
1312 long tlen;
1313
1314 tlen = 0;
1315 for (;;)
1316 {
1317 p = ml_get(read_buf_lnum) + read_buf_col;
1318 n = (int)STRLEN(p);
1319 if ((int)tlen + n + 1 > size)
1320 {
1321 /* Filled up to "size", append partial line.
1322 * Change NL to NUL to reverse the effect done
1323 * below. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001324 n = (int)(size - tlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001325 for (ni = 0; ni < n; ++ni)
1326 {
1327 if (p[ni] == NL)
1328 ptr[tlen++] = NUL;
1329 else
1330 ptr[tlen++] = p[ni];
1331 }
1332 read_buf_col += n;
1333 break;
1334 }
1335 else
1336 {
1337 /* Append whole line and new-line. Change NL
1338 * to NUL to reverse the effect done below. */
1339 for (ni = 0; ni < n; ++ni)
1340 {
1341 if (p[ni] == NL)
1342 ptr[tlen++] = NUL;
1343 else
1344 ptr[tlen++] = p[ni];
1345 }
1346 ptr[tlen++] = NL;
1347 read_buf_col = 0;
1348 if (++read_buf_lnum > from)
1349 {
1350 /* When the last line didn't have an
1351 * end-of-line don't add it now either. */
1352 if (!curbuf->b_p_eol)
1353 --tlen;
1354 size = tlen;
1355 break;
1356 }
1357 }
1358 }
1359 }
1360 }
1361 else
1362 {
1363 /*
1364 * Read bytes from the file.
1365 */
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01001366 size = read_eintr(fd, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001367 }
1368
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001369#ifdef FEAT_CRYPT
1370 /*
1371 * At start of file: Check for magic number of encryption.
1372 */
1373 if (filesize == 0 && size > 0)
1374 cryptkey = check_for_cryptkey(cryptkey, ptr, &size,
1375 &filesize, newfile, sfname,
1376 &did_ask_for_key);
1377 /*
1378 * Decrypt the read bytes. This is done before checking for
1379 * EOF because the crypt layer may be buffering.
1380 */
Bram Moolenaar829aa642017-08-23 22:32:35 +02001381 if (cryptkey != NULL && curbuf->b_cryptstate != NULL
1382 && size > 0)
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001383 {
1384 if (crypt_works_inplace(curbuf->b_cryptstate))
1385 {
1386 crypt_decode_inplace(curbuf->b_cryptstate, ptr, size);
1387 }
1388 else
1389 {
1390 char_u *newptr = NULL;
1391 int decrypted_size;
1392
1393 decrypted_size = crypt_decode_alloc(
1394 curbuf->b_cryptstate, ptr, size, &newptr);
1395
1396 /* If the crypt layer is buffering, not producing
1397 * anything yet, need to read more. */
Bram Moolenaar1c17ffa2018-04-24 15:19:04 +02001398 if (decrypted_size == 0)
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001399 continue;
1400
1401 if (linerest == 0)
1402 {
1403 /* Simple case: reuse returned buffer (may be
1404 * NULL, checked later). */
1405 new_buffer = newptr;
1406 }
1407 else
1408 {
1409 long_u new_size;
1410
1411 /* Need new buffer to add bytes carried over. */
1412 new_size = (long_u)(decrypted_size + linerest + 1);
1413 new_buffer = lalloc(new_size, FALSE);
1414 if (new_buffer == NULL)
1415 {
1416 do_outofmem_msg(new_size);
1417 error = TRUE;
1418 break;
1419 }
1420
1421 mch_memmove(new_buffer, buffer, linerest);
1422 if (newptr != NULL)
1423 mch_memmove(new_buffer + linerest, newptr,
1424 decrypted_size);
1425 }
1426
1427 if (new_buffer != NULL)
1428 {
1429 vim_free(buffer);
1430 buffer = new_buffer;
1431 new_buffer = NULL;
1432 line_start = buffer;
1433 ptr = buffer + linerest;
1434 }
1435 size = decrypted_size;
1436 }
1437 }
1438#endif
1439
Bram Moolenaar071d4272004-06-13 20:20:40 +00001440 if (size <= 0)
1441 {
1442 if (size < 0) /* read error */
1443 error = TRUE;
1444#ifdef FEAT_MBYTE
1445 else if (conv_restlen > 0)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001446 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001447 /*
1448 * Reached end-of-file but some trailing bytes could
1449 * not be converted. Truncated file?
1450 */
1451
1452 /* When we did a conversion report an error. */
1453 if (fio_flags != 0
1454# ifdef USE_ICONV
1455 || iconv_fd != (iconv_t)-1
1456# endif
1457 )
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001458 {
Bram Moolenaare8d95302013-04-24 16:34:02 +02001459 if (can_retry)
1460 goto rewind_retry;
Bram Moolenaarf453d352008-06-04 17:37:34 +00001461 if (conv_error == 0)
1462 conv_error = curbuf->b_ml.ml_line_count
1463 - linecnt + 1;
1464 }
1465 /* Remember the first linenr with an illegal byte */
1466 else if (illegal_byte == 0)
1467 illegal_byte = curbuf->b_ml.ml_line_count
1468 - linecnt + 1;
1469 if (bad_char_behavior == BAD_DROP)
1470 {
1471 *(ptr - conv_restlen) = NUL;
1472 conv_restlen = 0;
1473 }
1474 else
1475 {
1476 /* Replace the trailing bytes with the replacement
1477 * character if we were converting; if we weren't,
1478 * leave the UTF8 checking code to do it, as it
1479 * works slightly differently. */
1480 if (bad_char_behavior != BAD_KEEP && (fio_flags != 0
1481# ifdef USE_ICONV
1482 || iconv_fd != (iconv_t)-1
1483# endif
1484 ))
1485 {
1486 while (conv_restlen > 0)
1487 {
1488 *(--ptr) = bad_char_behavior;
1489 --conv_restlen;
1490 }
1491 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001492 fio_flags = 0; /* don't convert this */
Bram Moolenaarb21e5842006-04-16 18:30:08 +00001493# ifdef USE_ICONV
1494 if (iconv_fd != (iconv_t)-1)
1495 {
1496 iconv_close(iconv_fd);
1497 iconv_fd = (iconv_t)-1;
1498 }
1499# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001500 }
1501 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001502#endif
1503 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001504 }
1505 skip_read = FALSE;
1506
1507#ifdef FEAT_MBYTE
1508 /*
1509 * At start of file (or after crypt magic number): Check for BOM.
1510 * Also check for a BOM for other Unicode encodings, but not after
1511 * converting with 'charconvert' or when a BOM has already been
1512 * found.
1513 */
1514 if ((filesize == 0
1515# ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001516 || (cryptkey != NULL
1517 && filesize == crypt_get_header_len(
1518 crypt_get_method_nr(curbuf)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001519# endif
1520 )
1521 && (fio_flags == FIO_UCSBOM
1522 || (!curbuf->b_p_bomb
1523 && tmpname == NULL
1524 && (*fenc == 'u' || (*fenc == NUL && enc_utf8)))))
1525 {
1526 char_u *ccname;
1527 int blen;
1528
1529 /* no BOM detection in a short file or in binary mode */
1530 if (size < 2 || curbuf->b_p_bin)
1531 ccname = NULL;
1532 else
1533 ccname = check_for_bom(ptr, size, &blen,
1534 fio_flags == FIO_UCSBOM ? FIO_ALL : get_fio_flags(fenc));
1535 if (ccname != NULL)
1536 {
1537 /* Remove BOM from the text */
1538 filesize += blen;
1539 size -= blen;
1540 mch_memmove(ptr, ptr + blen, (size_t)size);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00001541 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001542 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001543 curbuf->b_p_bomb = TRUE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001544 curbuf->b_start_bomb = TRUE;
1545 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001546 }
1547
1548 if (fio_flags == FIO_UCSBOM)
1549 {
1550 if (ccname == NULL)
1551 {
1552 /* No BOM detected: retry with next encoding. */
1553 advance_fenc = TRUE;
1554 }
1555 else
1556 {
1557 /* BOM detected: set "fenc" and jump back */
1558 if (fenc_alloced)
1559 vim_free(fenc);
1560 fenc = ccname;
1561 fenc_alloced = FALSE;
1562 }
1563 /* retry reading without getting new bytes or rewinding */
1564 skip_read = TRUE;
1565 goto retry;
1566 }
1567 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001568
1569 /* Include not converted bytes. */
1570 ptr -= conv_restlen;
1571 size += conv_restlen;
1572 conv_restlen = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001573#endif
1574 /*
1575 * Break here for a read error or end-of-file.
1576 */
1577 if (size <= 0)
1578 break;
1579
1580#ifdef FEAT_MBYTE
1581
Bram Moolenaar071d4272004-06-13 20:20:40 +00001582# ifdef USE_ICONV
1583 if (iconv_fd != (iconv_t)-1)
1584 {
1585 /*
1586 * Attempt conversion of the read bytes to 'encoding' using
1587 * iconv().
1588 */
1589 const char *fromp;
1590 char *top;
1591 size_t from_size;
1592 size_t to_size;
1593
1594 fromp = (char *)ptr;
1595 from_size = size;
1596 ptr += size;
1597 top = (char *)ptr;
1598 to_size = real_size - size;
1599
1600 /*
1601 * If there is conversion error or not enough room try using
Bram Moolenaar19a09a12005-03-04 23:39:37 +00001602 * another conversion. Except for when there is no
1603 * alternative (help files).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001604 */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001605 while ((iconv(iconv_fd, (void *)&fromp, &from_size,
1606 &top, &to_size)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001607 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
1608 || from_size > CONV_RESTLEN)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001609 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001610 if (can_retry)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001611 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001612 if (conv_error == 0)
1613 conv_error = readfile_linenr(linecnt,
1614 ptr, (char_u *)top);
Bram Moolenaar42eeac32005-06-29 22:40:58 +00001615
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001616 /* Deal with a bad byte and continue with the next. */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001617 ++fromp;
1618 --from_size;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001619 if (bad_char_behavior == BAD_KEEP)
1620 {
1621 *top++ = *(fromp - 1);
1622 --to_size;
1623 }
1624 else if (bad_char_behavior != BAD_DROP)
1625 {
1626 *top++ = bad_char_behavior;
1627 --to_size;
1628 }
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001629 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001630
1631 if (from_size > 0)
1632 {
1633 /* Some remaining characters, keep them for the next
1634 * round. */
1635 mch_memmove(conv_rest, (char_u *)fromp, from_size);
1636 conv_restlen = (int)from_size;
1637 }
1638
1639 /* move the linerest to before the converted characters */
1640 line_start = ptr - linerest;
1641 mch_memmove(line_start, buffer, (size_t)linerest);
1642 size = (long)((char_u *)top - ptr);
1643 }
1644# endif
1645
1646# ifdef WIN3264
1647 if (fio_flags & FIO_CODEPAGE)
1648 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001649 char_u *src, *dst;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001650 WCHAR ucs2buf[3];
1651 int ucs2len;
1652 int codepage = FIO_GET_CP(fio_flags);
1653 int bytelen;
1654 int found_bad;
1655 char replstr[2];
1656
Bram Moolenaar071d4272004-06-13 20:20:40 +00001657 /*
1658 * Conversion from an MS-Windows codepage or UTF-8 to UTF-8 or
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001659 * a codepage, using standard MS-Windows functions. This
1660 * requires two steps:
1661 * 1. convert from 'fileencoding' to ucs-2
1662 * 2. convert from ucs-2 to 'encoding'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001663 *
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001664 * Because there may be illegal bytes AND an incomplete byte
1665 * sequence at the end, we may have to do the conversion one
1666 * character at a time to get it right.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001667 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001668
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001669 /* Replacement string for WideCharToMultiByte(). */
1670 if (bad_char_behavior > 0)
1671 replstr[0] = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001672 else
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001673 replstr[0] = '?';
1674 replstr[1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001675
1676 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001677 * Move the bytes to the end of the buffer, so that we have
1678 * room to put the result at the start.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001679 */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001680 src = ptr + real_size - size;
1681 mch_memmove(src, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001682
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001683 /*
1684 * Do the conversion.
1685 */
1686 dst = ptr;
1687 size = size;
1688 while (size > 0)
1689 {
1690 found_bad = FALSE;
1691
1692# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
1693 if (codepage == CP_UTF8)
1694 {
1695 /* Handle CP_UTF8 input ourselves to be able to handle
1696 * trailing bytes properly.
1697 * Get one UTF-8 character from src. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001698 bytelen = (int)utf_ptr2len_len(src, size);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001699 if (bytelen > size)
1700 {
1701 /* Only got some bytes of a character. Normally
1702 * it's put in "conv_rest", but if it's too long
1703 * deal with it as if they were illegal bytes. */
1704 if (bytelen <= CONV_RESTLEN)
1705 break;
1706
1707 /* weird overlong byte sequence */
1708 bytelen = size;
1709 found_bad = TRUE;
1710 }
1711 else
1712 {
Bram Moolenaarc01140a2006-03-24 22:21:52 +00001713 int u8c = utf_ptr2char(src);
1714
Bram Moolenaar86e01082005-12-29 22:45:34 +00001715 if (u8c > 0xffff || (*src >= 0x80 && bytelen == 1))
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001716 found_bad = TRUE;
1717 ucs2buf[0] = u8c;
1718 ucs2len = 1;
1719 }
1720 }
1721 else
1722# endif
1723 {
1724 /* We don't know how long the byte sequence is, try
1725 * from one to three bytes. */
1726 for (bytelen = 1; bytelen <= size && bytelen <= 3;
1727 ++bytelen)
1728 {
1729 ucs2len = MultiByteToWideChar(codepage,
1730 MB_ERR_INVALID_CHARS,
1731 (LPCSTR)src, bytelen,
1732 ucs2buf, 3);
1733 if (ucs2len > 0)
1734 break;
1735 }
1736 if (ucs2len == 0)
1737 {
1738 /* If we have only one byte then it's probably an
1739 * incomplete byte sequence. Otherwise discard
1740 * one byte as a bad character. */
1741 if (size == 1)
1742 break;
1743 found_bad = TRUE;
1744 bytelen = 1;
1745 }
1746 }
1747
1748 if (!found_bad)
1749 {
1750 int i;
1751
1752 /* Convert "ucs2buf[ucs2len]" to 'enc' in "dst". */
1753 if (enc_utf8)
1754 {
1755 /* From UCS-2 to UTF-8. Cannot fail. */
1756 for (i = 0; i < ucs2len; ++i)
1757 dst += utf_char2bytes(ucs2buf[i], dst);
1758 }
1759 else
1760 {
1761 BOOL bad = FALSE;
1762 int dstlen;
1763
1764 /* From UCS-2 to "enc_codepage". If the
1765 * conversion uses the default character "?",
1766 * the data doesn't fit in this encoding. */
1767 dstlen = WideCharToMultiByte(enc_codepage, 0,
1768 (LPCWSTR)ucs2buf, ucs2len,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001769 (LPSTR)dst, (int)(src - dst),
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001770 replstr, &bad);
1771 if (bad)
1772 found_bad = TRUE;
1773 else
1774 dst += dstlen;
1775 }
1776 }
1777
1778 if (found_bad)
1779 {
1780 /* Deal with bytes we can't convert. */
1781 if (can_retry)
1782 goto rewind_retry;
1783 if (conv_error == 0)
1784 conv_error = readfile_linenr(linecnt, ptr, dst);
1785 if (bad_char_behavior != BAD_DROP)
1786 {
1787 if (bad_char_behavior == BAD_KEEP)
1788 {
1789 mch_memmove(dst, src, bytelen);
1790 dst += bytelen;
1791 }
1792 else
1793 *dst++ = bad_char_behavior;
1794 }
1795 }
1796
1797 src += bytelen;
1798 size -= bytelen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001799 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001800
1801 if (size > 0)
1802 {
1803 /* An incomplete byte sequence remaining. */
1804 mch_memmove(conv_rest, src, size);
1805 conv_restlen = size;
1806 }
1807
1808 /* The new size is equal to how much "dst" was advanced. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001809 size = (long)(dst - ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001810 }
1811 else
1812# endif
Bram Moolenaar56718732006-03-15 22:53:57 +00001813# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001814 if (fio_flags & FIO_MACROMAN)
1815 {
1816 /*
1817 * Conversion from Apple MacRoman char encoding to UTF-8 or
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001818 * latin1. This is in os_mac_conv.c.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001819 */
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001820 if (macroman2enc(ptr, &size, real_size) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001821 goto rewind_retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001822 }
1823 else
1824# endif
1825 if (fio_flags != 0)
1826 {
1827 int u8c;
1828 char_u *dest;
1829 char_u *tail = NULL;
1830
1831 /*
1832 * "enc_utf8" set: Convert Unicode or Latin1 to UTF-8.
1833 * "enc_utf8" not set: Convert Unicode to Latin1.
1834 * Go from end to start through the buffer, because the number
1835 * of bytes may increase.
1836 * "dest" points to after where the UTF-8 bytes go, "p" points
1837 * to after the next character to convert.
1838 */
1839 dest = ptr + real_size;
1840 if (fio_flags == FIO_LATIN1 || fio_flags == FIO_UTF8)
1841 {
1842 p = ptr + size;
1843 if (fio_flags == FIO_UTF8)
1844 {
1845 /* Check for a trailing incomplete UTF-8 sequence */
1846 tail = ptr + size - 1;
1847 while (tail > ptr && (*tail & 0xc0) == 0x80)
1848 --tail;
1849 if (tail + utf_byte2len(*tail) <= ptr + size)
1850 tail = NULL;
1851 else
1852 p = tail;
1853 }
1854 }
1855 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1856 {
1857 /* Check for a trailing byte */
1858 p = ptr + (size & ~1);
1859 if (size & 1)
1860 tail = p;
1861 if ((fio_flags & FIO_UTF16) && p > ptr)
1862 {
1863 /* Check for a trailing leading word */
1864 if (fio_flags & FIO_ENDIAN_L)
1865 {
1866 u8c = (*--p << 8);
1867 u8c += *--p;
1868 }
1869 else
1870 {
1871 u8c = *--p;
1872 u8c += (*--p << 8);
1873 }
1874 if (u8c >= 0xd800 && u8c <= 0xdbff)
1875 tail = p;
1876 else
1877 p += 2;
1878 }
1879 }
1880 else /* FIO_UCS4 */
1881 {
1882 /* Check for trailing 1, 2 or 3 bytes */
1883 p = ptr + (size & ~3);
1884 if (size & 3)
1885 tail = p;
1886 }
1887
1888 /* If there is a trailing incomplete sequence move it to
1889 * conv_rest[]. */
1890 if (tail != NULL)
1891 {
1892 conv_restlen = (int)((ptr + size) - tail);
1893 mch_memmove(conv_rest, (char_u *)tail, conv_restlen);
1894 size -= conv_restlen;
1895 }
1896
1897
1898 while (p > ptr)
1899 {
1900 if (fio_flags & FIO_LATIN1)
1901 u8c = *--p;
1902 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1903 {
1904 if (fio_flags & FIO_ENDIAN_L)
1905 {
1906 u8c = (*--p << 8);
1907 u8c += *--p;
1908 }
1909 else
1910 {
1911 u8c = *--p;
1912 u8c += (*--p << 8);
1913 }
1914 if ((fio_flags & FIO_UTF16)
1915 && u8c >= 0xdc00 && u8c <= 0xdfff)
1916 {
1917 int u16c;
1918
1919 if (p == ptr)
1920 {
1921 /* Missing leading word. */
1922 if (can_retry)
1923 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001924 if (conv_error == 0)
1925 conv_error = readfile_linenr(linecnt,
1926 ptr, p);
1927 if (bad_char_behavior == BAD_DROP)
1928 continue;
1929 if (bad_char_behavior != BAD_KEEP)
1930 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001931 }
1932
1933 /* found second word of double-word, get the first
1934 * word and compute the resulting character */
1935 if (fio_flags & FIO_ENDIAN_L)
1936 {
1937 u16c = (*--p << 8);
1938 u16c += *--p;
1939 }
1940 else
1941 {
1942 u16c = *--p;
1943 u16c += (*--p << 8);
1944 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001945 u8c = 0x10000 + ((u16c & 0x3ff) << 10)
1946 + (u8c & 0x3ff);
1947
Bram Moolenaar071d4272004-06-13 20:20:40 +00001948 /* Check if the word is indeed a leading word. */
1949 if (u16c < 0xd800 || u16c > 0xdbff)
1950 {
1951 if (can_retry)
1952 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001953 if (conv_error == 0)
1954 conv_error = readfile_linenr(linecnt,
1955 ptr, p);
1956 if (bad_char_behavior == BAD_DROP)
1957 continue;
1958 if (bad_char_behavior != BAD_KEEP)
1959 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001960 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001961 }
1962 }
1963 else if (fio_flags & FIO_UCS4)
1964 {
1965 if (fio_flags & FIO_ENDIAN_L)
1966 {
Bram Moolenaardc1c9812017-10-27 22:15:24 +02001967 u8c = (unsigned)*--p << 24;
1968 u8c += (unsigned)*--p << 16;
1969 u8c += (unsigned)*--p << 8;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001970 u8c += *--p;
1971 }
1972 else /* big endian */
1973 {
1974 u8c = *--p;
Bram Moolenaardc1c9812017-10-27 22:15:24 +02001975 u8c += (unsigned)*--p << 8;
1976 u8c += (unsigned)*--p << 16;
1977 u8c += (unsigned)*--p << 24;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001978 }
1979 }
1980 else /* UTF-8 */
1981 {
1982 if (*--p < 0x80)
1983 u8c = *p;
1984 else
1985 {
1986 len = utf_head_off(ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001987 p -= len;
1988 u8c = utf_ptr2char(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001989 if (len == 0)
1990 {
1991 /* Not a valid UTF-8 character, retry with
1992 * another fenc when possible, otherwise just
1993 * report the error. */
1994 if (can_retry)
1995 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001996 if (conv_error == 0)
1997 conv_error = readfile_linenr(linecnt,
1998 ptr, p);
1999 if (bad_char_behavior == BAD_DROP)
2000 continue;
2001 if (bad_char_behavior != BAD_KEEP)
2002 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002003 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002004 }
2005 }
2006 if (enc_utf8) /* produce UTF-8 */
2007 {
2008 dest -= utf_char2len(u8c);
2009 (void)utf_char2bytes(u8c, dest);
2010 }
2011 else /* produce Latin1 */
2012 {
2013 --dest;
2014 if (u8c >= 0x100)
2015 {
2016 /* character doesn't fit in latin1, retry with
2017 * another fenc when possible, otherwise just
2018 * report the error. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002019 if (can_retry)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002020 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002021 if (conv_error == 0)
2022 conv_error = readfile_linenr(linecnt, ptr, p);
2023 if (bad_char_behavior == BAD_DROP)
2024 ++dest;
2025 else if (bad_char_behavior == BAD_KEEP)
2026 *dest = u8c;
2027 else if (eap != NULL && eap->bad_char != 0)
2028 *dest = bad_char_behavior;
2029 else
2030 *dest = 0xBF;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002031 }
2032 else
2033 *dest = u8c;
2034 }
2035 }
2036
2037 /* move the linerest to before the converted characters */
2038 line_start = dest - linerest;
2039 mch_memmove(line_start, buffer, (size_t)linerest);
2040 size = (long)((ptr + real_size) - dest);
2041 ptr = dest;
2042 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002043 else if (enc_utf8 && !curbuf->b_p_bin)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002044 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002045 int incomplete_tail = FALSE;
2046
2047 /* Reading UTF-8: Check if the bytes are valid UTF-8. */
2048 for (p = ptr; ; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002049 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002050 int todo = (int)((ptr + size) - p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002051 int l;
2052
2053 if (todo <= 0)
2054 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002055 if (*p >= 0x80)
2056 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002057 /* A length of 1 means it's an illegal byte. Accept
2058 * an incomplete character at the end though, the next
2059 * read() will get the next bytes, we'll check it
2060 * then. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002061 l = utf_ptr2len_len(p, todo);
Bram Moolenaarf453d352008-06-04 17:37:34 +00002062 if (l > todo && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002063 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002064 /* Avoid retrying with a different encoding when
2065 * a truncated file is more likely, or attempting
2066 * to read the rest of an incomplete sequence when
2067 * we have already done so. */
2068 if (p > ptr || filesize > 0)
2069 incomplete_tail = TRUE;
2070 /* Incomplete byte sequence, move it to conv_rest[]
2071 * and try to read the rest of it, unless we've
2072 * already done so. */
2073 if (p > ptr)
2074 {
2075 conv_restlen = todo;
2076 mch_memmove(conv_rest, p, conv_restlen);
2077 size -= conv_restlen;
2078 break;
2079 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002080 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002081 if (l == 1 || l > todo)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002082 {
2083 /* Illegal byte. If we can try another encoding
Bram Moolenaarf453d352008-06-04 17:37:34 +00002084 * do that, unless at EOF where a truncated
2085 * file is more likely than a conversion error. */
2086 if (can_retry && !incomplete_tail)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002087 break;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002088# ifdef USE_ICONV
2089 /* When we did a conversion report an error. */
2090 if (iconv_fd != (iconv_t)-1 && conv_error == 0)
2091 conv_error = readfile_linenr(linecnt, ptr, p);
2092# endif
Bram Moolenaarf453d352008-06-04 17:37:34 +00002093 /* Remember the first linenr with an illegal byte */
2094 if (conv_error == 0 && illegal_byte == 0)
2095 illegal_byte = readfile_linenr(linecnt, ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002096
2097 /* Drop, keep or replace the bad byte. */
2098 if (bad_char_behavior == BAD_DROP)
2099 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002100 mch_memmove(p, p + 1, todo - 1);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002101 --p;
2102 --size;
2103 }
2104 else if (bad_char_behavior != BAD_KEEP)
2105 *p = bad_char_behavior;
2106 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002107 else
2108 p += l - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002109 }
2110 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002111 if (p < ptr + size && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002112 {
2113 /* Detected a UTF-8 error. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002114rewind_retry:
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002115 /* Retry reading with another conversion. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002116# if defined(FEAT_EVAL) && defined(USE_ICONV)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002117 if (*p_ccv != NUL && iconv_fd != (iconv_t)-1)
2118 /* iconv() failed, try 'charconvert' */
2119 did_iconv = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002120 else
2121# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002122 /* use next item from 'fileencodings' */
2123 advance_fenc = TRUE;
2124 file_rewind = TRUE;
2125 goto retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002126 }
2127 }
2128#endif
2129
2130 /* count the number of characters (after conversion!) */
2131 filesize += size;
2132
2133 /*
2134 * when reading the first part of a file: guess EOL type
2135 */
2136 if (fileformat == EOL_UNKNOWN)
2137 {
2138 /* First try finding a NL, for Dos and Unix */
2139 if (try_dos || try_unix)
2140 {
Bram Moolenaarc6b72172015-02-27 17:48:09 +01002141 /* Reset the carriage return counter. */
2142 if (try_mac)
2143 try_mac = 1;
2144
Bram Moolenaar071d4272004-06-13 20:20:40 +00002145 for (p = ptr; p < ptr + size; ++p)
2146 {
2147 if (*p == NL)
2148 {
2149 if (!try_unix
2150 || (try_dos && p > ptr && p[-1] == CAR))
2151 fileformat = EOL_DOS;
2152 else
2153 fileformat = EOL_UNIX;
2154 break;
2155 }
Bram Moolenaar05eb6122015-02-17 14:15:19 +01002156 else if (*p == CAR && try_mac)
2157 try_mac++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002158 }
2159
2160 /* Don't give in to EOL_UNIX if EOL_MAC is more likely */
2161 if (fileformat == EOL_UNIX && try_mac)
2162 {
2163 /* Need to reset the counters when retrying fenc. */
2164 try_mac = 1;
2165 try_unix = 1;
2166 for (; p >= ptr && *p != CAR; p--)
2167 ;
2168 if (p >= ptr)
2169 {
2170 for (p = ptr; p < ptr + size; ++p)
2171 {
2172 if (*p == NL)
2173 try_unix++;
2174 else if (*p == CAR)
2175 try_mac++;
2176 }
2177 if (try_mac > try_unix)
2178 fileformat = EOL_MAC;
2179 }
2180 }
Bram Moolenaar05eb6122015-02-17 14:15:19 +01002181 else if (fileformat == EOL_UNKNOWN && try_mac == 1)
2182 /* Looking for CR but found no end-of-line markers at
2183 * all: use the default format. */
2184 fileformat = default_fileformat();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002185 }
2186
2187 /* No NL found: may use Mac format */
2188 if (fileformat == EOL_UNKNOWN && try_mac)
2189 fileformat = EOL_MAC;
2190
2191 /* Still nothing found? Use first format in 'ffs' */
2192 if (fileformat == EOL_UNKNOWN)
2193 fileformat = default_fileformat();
2194
2195 /* if editing a new file: may set p_tx and p_ff */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002196 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002197 set_fileformat(fileformat, OPT_LOCAL);
2198 }
2199 }
2200
2201 /*
2202 * This loop is executed once for every character read.
2203 * Keep it fast!
2204 */
2205 if (fileformat == EOL_MAC)
2206 {
2207 --ptr;
2208 while (++ptr, --size >= 0)
2209 {
2210 /* catch most common case first */
2211 if ((c = *ptr) != NUL && c != CAR && c != NL)
2212 continue;
2213 if (c == NUL)
2214 *ptr = NL; /* NULs are replaced by newlines! */
2215 else if (c == NL)
2216 *ptr = CAR; /* NLs are replaced by CRs! */
2217 else
2218 {
2219 if (skip_count == 0)
2220 {
2221 *ptr = NUL; /* end of line */
2222 len = (colnr_T) (ptr - line_start + 1);
2223 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2224 {
2225 error = TRUE;
2226 break;
2227 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002228#ifdef FEAT_PERSISTENT_UNDO
2229 if (read_undo_file)
2230 sha256_update(&sha_ctx, line_start, len);
2231#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002232 ++lnum;
2233 if (--read_count == 0)
2234 {
2235 error = TRUE; /* break loop */
2236 line_start = ptr; /* nothing left to write */
2237 break;
2238 }
2239 }
2240 else
2241 --skip_count;
2242 line_start = ptr + 1;
2243 }
2244 }
2245 }
2246 else
2247 {
2248 --ptr;
2249 while (++ptr, --size >= 0)
2250 {
2251 if ((c = *ptr) != NUL && c != NL) /* catch most common case */
2252 continue;
2253 if (c == NUL)
2254 *ptr = NL; /* NULs are replaced by newlines! */
2255 else
2256 {
2257 if (skip_count == 0)
2258 {
2259 *ptr = NUL; /* end of line */
2260 len = (colnr_T)(ptr - line_start + 1);
2261 if (fileformat == EOL_DOS)
2262 {
Bram Moolenaar2aa5f692017-01-24 15:46:48 +01002263 if (ptr > line_start && ptr[-1] == CAR)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002264 {
Bram Moolenaar2aa5f692017-01-24 15:46:48 +01002265 /* remove CR before NL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002266 ptr[-1] = NUL;
2267 --len;
2268 }
2269 /*
2270 * Reading in Dos format, but no CR-LF found!
2271 * When 'fileformats' includes "unix", delete all
2272 * the lines read so far and start all over again.
2273 * Otherwise give an error message later.
2274 */
2275 else if (ff_error != EOL_DOS)
2276 {
2277 if ( try_unix
2278 && !read_stdin
2279 && (read_buffer
Bram Moolenaar8767f522016-07-01 17:17:39 +02002280 || vim_lseek(fd, (off_T)0L, SEEK_SET)
2281 == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002282 {
2283 fileformat = EOL_UNIX;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002284 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002285 set_fileformat(EOL_UNIX, OPT_LOCAL);
2286 file_rewind = TRUE;
2287 keep_fileformat = TRUE;
2288 goto retry;
2289 }
2290 ff_error = EOL_DOS;
2291 }
2292 }
2293 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2294 {
2295 error = TRUE;
2296 break;
2297 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002298#ifdef FEAT_PERSISTENT_UNDO
2299 if (read_undo_file)
2300 sha256_update(&sha_ctx, line_start, len);
2301#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002302 ++lnum;
2303 if (--read_count == 0)
2304 {
2305 error = TRUE; /* break loop */
2306 line_start = ptr; /* nothing left to write */
2307 break;
2308 }
2309 }
2310 else
2311 --skip_count;
2312 line_start = ptr + 1;
2313 }
2314 }
2315 }
2316 linerest = (long)(ptr - line_start);
2317 ui_breakcheck();
2318 }
2319
2320failed:
2321 /* not an error, max. number of lines reached */
2322 if (error && read_count == 0)
2323 error = FALSE;
2324
2325 /*
2326 * If we get EOF in the middle of a line, note the fact and
2327 * complete the line ourselves.
2328 * In Dos format ignore a trailing CTRL-Z, unless 'binary' set.
2329 */
2330 if (!error
2331 && !got_int
2332 && linerest != 0
2333 && !(!curbuf->b_p_bin
2334 && fileformat == EOL_DOS
2335 && *line_start == Ctrl_Z
2336 && ptr == line_start + 1))
2337 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002338 /* remember for when writing */
2339 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002340 curbuf->b_p_eol = FALSE;
2341 *ptr = NUL;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002342 len = (colnr_T)(ptr - line_start + 1);
2343 if (ml_append(lnum, line_start, len, newfile) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002344 error = TRUE;
2345 else
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002346 {
2347#ifdef FEAT_PERSISTENT_UNDO
2348 if (read_undo_file)
2349 sha256_update(&sha_ctx, line_start, len);
2350#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002351 read_no_eol_lnum = ++lnum;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002352 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002353 }
2354
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002355 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002356 save_file_ff(curbuf); /* remember the current file format */
2357
2358#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002359 if (curbuf->b_cryptstate != NULL)
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002360 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002361 crypt_free_state(curbuf->b_cryptstate);
2362 curbuf->b_cryptstate = NULL;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002363 }
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002364 if (cryptkey != NULL && cryptkey != curbuf->b_p_key)
2365 crypt_free_key(cryptkey);
2366 /* Don't set cryptkey to NULL, it's used below as a flag that
2367 * encryption was used. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002368#endif
2369
2370#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002371 /* If editing a new file: set 'fenc' for the current buffer.
2372 * Also for ":read ++edit file". */
2373 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002374 set_string_option_direct((char_u *)"fenc", -1, fenc,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00002375 OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002376 if (fenc_alloced)
2377 vim_free(fenc);
2378# ifdef USE_ICONV
2379 if (iconv_fd != (iconv_t)-1)
2380 {
2381 iconv_close(iconv_fd);
2382 iconv_fd = (iconv_t)-1;
2383 }
2384# endif
2385#endif
2386
2387 if (!read_buffer && !read_stdin)
2388 close(fd); /* errors are ignored */
Bram Moolenaarf05da212009-11-17 16:13:15 +00002389#ifdef HAVE_FD_CLOEXEC
2390 else
2391 {
2392 int fdflags = fcntl(fd, F_GETFD);
2393 if (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0)
Bram Moolenaarfbc4b4d2016-02-07 15:14:01 +01002394 (void)fcntl(fd, F_SETFD, fdflags | FD_CLOEXEC);
Bram Moolenaarf05da212009-11-17 16:13:15 +00002395 }
2396#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002397 vim_free(buffer);
2398
2399#ifdef HAVE_DUP
2400 if (read_stdin)
2401 {
2402 /* Use stderr for stdin, makes shell commands work. */
2403 close(0);
Bram Moolenaar42335f52018-09-13 15:33:43 +02002404 vim_ignored = dup(2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002405 }
2406#endif
2407
2408#ifdef FEAT_MBYTE
2409 if (tmpname != NULL)
2410 {
2411 mch_remove(tmpname); /* delete converted file */
2412 vim_free(tmpname);
2413 }
2414#endif
2415 --no_wait_return; /* may wait for return now */
2416
2417 /*
2418 * In recovery mode everything but autocommands is skipped.
2419 */
2420 if (!recoverymode)
2421 {
2422 /* need to delete the last line, which comes from the empty buffer */
2423 if (newfile && wasempty && !(curbuf->b_ml.ml_flags & ML_EMPTY))
2424 {
2425#ifdef FEAT_NETBEANS_INTG
2426 netbeansFireChanges = 0;
2427#endif
2428 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
2429#ifdef FEAT_NETBEANS_INTG
2430 netbeansFireChanges = 1;
2431#endif
2432 --linecnt;
2433 }
2434 linecnt = curbuf->b_ml.ml_line_count - linecnt;
2435 if (filesize == 0)
2436 linecnt = 0;
2437 if (newfile || read_buffer)
Bram Moolenaar7263a772007-05-10 17:35:54 +00002438 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002439 redraw_curbuf_later(NOT_VALID);
Bram Moolenaar7263a772007-05-10 17:35:54 +00002440#ifdef FEAT_DIFF
2441 /* After reading the text into the buffer the diff info needs to
2442 * be updated. */
2443 diff_invalidate(curbuf);
2444#endif
2445#ifdef FEAT_FOLDING
2446 /* All folds in the window are invalid now. Mark them for update
2447 * before triggering autocommands. */
2448 foldUpdateAll(curwin);
2449#endif
2450 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002451 else if (linecnt) /* appended at least one line */
2452 appended_lines_mark(from, linecnt);
2453
Bram Moolenaar071d4272004-06-13 20:20:40 +00002454#ifndef ALWAYS_USE_GUI
2455 /*
2456 * If we were reading from the same terminal as where messages go,
2457 * the screen will have been messed up.
2458 * Switch on raw mode now and clear the screen.
2459 */
2460 if (read_stdin)
2461 {
2462 settmode(TMODE_RAW); /* set to raw mode */
2463 starttermcap();
2464 screenclear();
2465 }
2466#endif
2467
2468 if (got_int)
2469 {
2470 if (!(flags & READ_DUMMY))
2471 {
2472 filemess(curbuf, sfname, (char_u *)_(e_interr), 0);
2473 if (newfile)
2474 curbuf->b_p_ro = TRUE; /* must use "w!" now */
2475 }
2476 msg_scroll = msg_save;
2477#ifdef FEAT_VIMINFO
2478 check_marks_read();
2479#endif
2480 return OK; /* an interrupt isn't really an error */
2481 }
2482
2483 if (!filtering && !(flags & READ_DUMMY))
2484 {
2485 msg_add_fname(curbuf, sfname); /* fname in IObuff with quotes */
2486 c = FALSE;
2487
2488#ifdef UNIX
Bram Moolenaard569bb02018-08-11 13:57:20 +02002489 if (S_ISFIFO(perm)) /* fifo */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002490 {
2491 STRCAT(IObuff, _("[fifo]"));
2492 c = TRUE;
2493 }
Bram Moolenaard569bb02018-08-11 13:57:20 +02002494 if (S_ISSOCK(perm)) /* or socket */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002495 {
2496 STRCAT(IObuff, _("[socket]"));
2497 c = TRUE;
2498 }
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002499# ifdef OPEN_CHR_FILES
2500 if (S_ISCHR(perm)) /* or character special */
2501 {
2502 STRCAT(IObuff, _("[character special]"));
2503 c = TRUE;
2504 }
2505# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002506#endif
2507 if (curbuf->b_p_ro)
2508 {
2509 STRCAT(IObuff, shortmess(SHM_RO) ? _("[RO]") : _("[readonly]"));
2510 c = TRUE;
2511 }
2512 if (read_no_eol_lnum)
2513 {
2514 msg_add_eol();
2515 c = TRUE;
2516 }
2517 if (ff_error == EOL_DOS)
2518 {
2519 STRCAT(IObuff, _("[CR missing]"));
2520 c = TRUE;
2521 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002522 if (split)
2523 {
2524 STRCAT(IObuff, _("[long lines split]"));
2525 c = TRUE;
2526 }
2527#ifdef FEAT_MBYTE
2528 if (notconverted)
2529 {
2530 STRCAT(IObuff, _("[NOT converted]"));
2531 c = TRUE;
2532 }
2533 else if (converted)
2534 {
2535 STRCAT(IObuff, _("[converted]"));
2536 c = TRUE;
2537 }
2538#endif
2539#ifdef FEAT_CRYPT
2540 if (cryptkey != NULL)
2541 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002542 crypt_append_msg(curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002543 c = TRUE;
2544 }
2545#endif
2546#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002547 if (conv_error != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002548 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002549 sprintf((char *)IObuff + STRLEN(IObuff),
2550 _("[CONVERSION ERROR in line %ld]"), (long)conv_error);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002551 c = TRUE;
2552 }
2553 else if (illegal_byte > 0)
2554 {
2555 sprintf((char *)IObuff + STRLEN(IObuff),
2556 _("[ILLEGAL BYTE in line %ld]"), (long)illegal_byte);
2557 c = TRUE;
2558 }
2559 else
2560#endif
2561 if (error)
2562 {
2563 STRCAT(IObuff, _("[READ ERRORS]"));
2564 c = TRUE;
2565 }
2566 if (msg_add_fileformat(fileformat))
2567 c = TRUE;
2568#ifdef FEAT_CRYPT
2569 if (cryptkey != NULL)
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002570 msg_add_lines(c, (long)linecnt, filesize
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002571 - crypt_get_header_len(crypt_get_method_nr(curbuf)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002572 else
2573#endif
2574 msg_add_lines(c, (long)linecnt, filesize);
2575
Bram Moolenaard23a8232018-02-10 18:45:26 +01002576 VIM_CLEAR(keep_msg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002577 msg_scrolled_ign = TRUE;
2578#ifdef ALWAYS_USE_GUI
2579 /* Don't show the message when reading stdin, it would end up in a
2580 * message box (which might be shown when exiting!) */
2581 if (read_stdin || read_buffer)
2582 p = msg_may_trunc(FALSE, IObuff);
2583 else
2584#endif
2585 p = msg_trunc_attr(IObuff, FALSE, 0);
2586 if (read_stdin || read_buffer || restart_edit != 0
Bram Moolenaar1c7715d2005-10-03 22:02:18 +00002587 || (msg_scrolled != 0 && !need_wait_return))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002588 /* Need to repeat the message after redrawing when:
2589 * - When reading from stdin (the screen will be cleared next).
2590 * - When restart_edit is set (otherwise there will be a delay
2591 * before redrawing).
2592 * - When the screen was scrolled but there is no wait-return
2593 * prompt. */
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002594 set_keep_msg(p, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002595 msg_scrolled_ign = FALSE;
2596 }
2597
2598 /* with errors writing the file requires ":w!" */
2599 if (newfile && (error
2600#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002601 || conv_error != 0
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002602 || (illegal_byte > 0 && bad_char_behavior != BAD_KEEP)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002603#endif
2604 ))
2605 curbuf->b_p_ro = TRUE;
2606
2607 u_clearline(); /* cannot use "U" command after adding lines */
2608
2609 /*
2610 * In Ex mode: cursor at last new line.
2611 * Otherwise: cursor at first new line.
2612 */
2613 if (exmode_active)
2614 curwin->w_cursor.lnum = from + linecnt;
2615 else
2616 curwin->w_cursor.lnum = from + 1;
2617 check_cursor_lnum();
2618 beginline(BL_WHITE | BL_FIX); /* on first non-blank */
2619
2620 /*
2621 * Set '[ and '] marks to the newly read lines.
2622 */
2623 curbuf->b_op_start.lnum = from + 1;
2624 curbuf->b_op_start.col = 0;
2625 curbuf->b_op_end.lnum = from + linecnt;
2626 curbuf->b_op_end.col = 0;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002627
2628#ifdef WIN32
2629 /*
2630 * Work around a weird problem: When a file has two links (only
2631 * possible on NTFS) and we write through one link, then stat() it
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00002632 * through the other link, the timestamp information may be wrong.
Bram Moolenaar03f48552006-02-28 23:52:23 +00002633 * It's correct again after reading the file, thus reset the timestamp
2634 * here.
2635 */
2636 if (newfile && !read_stdin && !read_buffer
2637 && mch_stat((char *)fname, &st) >= 0)
2638 {
2639 buf_store_time(curbuf, &st, fname);
2640 curbuf->b_mtime_read = curbuf->b_mtime;
2641 }
2642#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002643 }
2644 msg_scroll = msg_save;
2645
2646#ifdef FEAT_VIMINFO
2647 /*
2648 * Get the marks before executing autocommands, so they can be used there.
2649 */
2650 check_marks_read();
2651#endif
2652
Bram Moolenaar071d4272004-06-13 20:20:40 +00002653 /*
Bram Moolenaar34d72d42015-07-17 14:18:08 +02002654 * We remember if the last line of the read didn't have
2655 * an eol even when 'binary' is off, to support turning 'fixeol' off,
2656 * or writing the read again with 'binary' on. The latter is required
2657 * for ":autocmd FileReadPost *.gz set bin|'[,']!gunzip" to work.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002658 */
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002659 curbuf->b_no_eol_lnum = read_no_eol_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002660
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02002661 /* When reloading a buffer put the cursor at the first line that is
2662 * different. */
2663 if (flags & READ_KEEP_UNDO)
2664 u_find_first_changed();
2665
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002666#ifdef FEAT_PERSISTENT_UNDO
2667 /*
2668 * When opening a new file locate undo info and read it.
2669 */
2670 if (read_undo_file)
2671 {
2672 char_u hash[UNDO_HASH_SIZE];
2673
2674 sha256_finish(&sha_ctx, hash);
Bram Moolenaar6ed8ed82010-05-30 20:40:11 +02002675 u_read_undo(NULL, hash, fname);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002676 }
2677#endif
2678
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02002679 if (!read_stdin && !read_fifo && (!read_buffer || sfname != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002680 {
2681 int m = msg_scroll;
2682 int n = msg_scrolled;
2683
2684 /* Save the fileformat now, otherwise the buffer will be considered
2685 * modified if the format/encoding was automatically detected. */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002686 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002687 save_file_ff(curbuf);
2688
2689 /*
2690 * The output from the autocommands should not overwrite anything and
2691 * should not be overwritten: Set msg_scroll, restore its value if no
2692 * output was done.
2693 */
2694 msg_scroll = TRUE;
2695 if (filtering)
2696 apply_autocmds_exarg(EVENT_FILTERREADPOST, NULL, sfname,
2697 FALSE, curbuf, eap);
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02002698 else if (newfile || (read_buffer && sfname != NULL))
Bram Moolenaarc3691332016-04-20 12:49:49 +02002699 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002700 apply_autocmds_exarg(EVENT_BUFREADPOST, NULL, sfname,
2701 FALSE, curbuf, eap);
Bram Moolenaarc3691332016-04-20 12:49:49 +02002702 if (!au_did_filetype && *curbuf->b_p_ft != NUL)
2703 /*
2704 * EVENT_FILETYPE was not triggered but the buffer already has a
2705 * filetype. Trigger EVENT_FILETYPE using the existing filetype.
2706 */
2707 apply_autocmds(EVENT_FILETYPE, curbuf->b_p_ft, curbuf->b_fname,
2708 TRUE, curbuf);
2709 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002710 else
2711 apply_autocmds_exarg(EVENT_FILEREADPOST, sfname, sfname,
2712 FALSE, NULL, eap);
2713 if (msg_scrolled == n)
2714 msg_scroll = m;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002715# ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002716 if (aborting()) /* autocmds may abort script processing */
2717 return FAIL;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002718# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002719 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002720
2721 if (recoverymode && error)
2722 return FAIL;
2723 return OK;
2724}
2725
Bram Moolenaarf04507d2016-08-20 15:05:39 +02002726#if defined(OPEN_CHR_FILES) || defined(PROTO)
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002727/*
2728 * Returns TRUE if the file name argument is of the form "/dev/fd/\d\+",
2729 * which is the name of files used for process substitution output by
2730 * some shells on some operating systems, e.g., bash on SunOS.
2731 * Do not accept "/dev/fd/[012]", opening these may hang Vim.
2732 */
Bram Moolenaarf04507d2016-08-20 15:05:39 +02002733 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002734is_dev_fd_file(char_u *fname)
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002735{
2736 return (STRNCMP(fname, "/dev/fd/", 8) == 0
2737 && VIM_ISDIGIT(fname[8])
2738 && *skipdigits(fname + 9) == NUL
2739 && (fname[9] != NUL
2740 || (fname[8] != '0' && fname[8] != '1' && fname[8] != '2')));
2741}
2742#endif
2743
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002744#ifdef FEAT_MBYTE
2745
2746/*
2747 * From the current line count and characters read after that, estimate the
2748 * line number where we are now.
2749 * Used for error messages that include a line number.
2750 */
2751 static linenr_T
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002752readfile_linenr(
2753 linenr_T linecnt, /* line count before reading more bytes */
2754 char_u *p, /* start of more bytes read */
2755 char_u *endp) /* end of more bytes read */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002756{
2757 char_u *s;
2758 linenr_T lnum;
2759
2760 lnum = curbuf->b_ml.ml_line_count - linecnt + 1;
2761 for (s = p; s < endp; ++s)
2762 if (*s == '\n')
2763 ++lnum;
2764 return lnum;
2765}
2766#endif
2767
Bram Moolenaar071d4272004-06-13 20:20:40 +00002768/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00002769 * Fill "*eap" to force the 'fileencoding', 'fileformat' and 'binary to be
2770 * equal to the buffer "buf". Used for calling readfile().
Bram Moolenaar071d4272004-06-13 20:20:40 +00002771 * Returns OK or FAIL.
2772 */
2773 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002774prep_exarg(exarg_T *eap, buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002775{
Bram Moolenaar333b80a2018-04-04 22:57:29 +02002776 eap->cmd = alloc(15
Bram Moolenaar071d4272004-06-13 20:20:40 +00002777#ifdef FEAT_MBYTE
Bram Moolenaar333b80a2018-04-04 22:57:29 +02002778 + (unsigned)STRLEN(buf->b_p_fenc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002779#endif
Bram Moolenaar333b80a2018-04-04 22:57:29 +02002780 );
Bram Moolenaar071d4272004-06-13 20:20:40 +00002781 if (eap->cmd == NULL)
2782 return FAIL;
2783
2784#ifdef FEAT_MBYTE
Bram Moolenaar333b80a2018-04-04 22:57:29 +02002785 sprintf((char *)eap->cmd, "e ++enc=%s", buf->b_p_fenc);
2786 eap->force_enc = 8;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002787 eap->bad_char = buf->b_bad_char;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002788#else
Bram Moolenaar333b80a2018-04-04 22:57:29 +02002789 sprintf((char *)eap->cmd, "e");
Bram Moolenaar071d4272004-06-13 20:20:40 +00002790#endif
Bram Moolenaar333b80a2018-04-04 22:57:29 +02002791 eap->force_ff = *buf->b_p_ff;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002792
2793 eap->force_bin = buf->b_p_bin ? FORCE_BIN : FORCE_NOBIN;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002794 eap->read_edit = FALSE;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002795 eap->forceit = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002796 return OK;
2797}
2798
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002799/*
2800 * Set default or forced 'fileformat' and 'binary'.
2801 */
2802 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002803set_file_options(int set_options, exarg_T *eap)
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002804{
2805 /* set default 'fileformat' */
2806 if (set_options)
2807 {
2808 if (eap != NULL && eap->force_ff != 0)
2809 set_fileformat(get_fileformat_force(curbuf, eap), OPT_LOCAL);
2810 else if (*p_ffs != NUL)
2811 set_fileformat(default_fileformat(), OPT_LOCAL);
2812 }
2813
2814 /* set or reset 'binary' */
2815 if (eap != NULL && eap->force_bin != 0)
2816 {
2817 int oldval = curbuf->b_p_bin;
2818
2819 curbuf->b_p_bin = (eap->force_bin == FORCE_BIN);
2820 set_options_bin(oldval, curbuf->b_p_bin, OPT_LOCAL);
2821 }
2822}
2823
2824#if defined(FEAT_MBYTE) || defined(PROTO)
2825/*
2826 * Set forced 'fileencoding'.
2827 */
2828 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002829set_forced_fenc(exarg_T *eap)
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002830{
2831 if (eap->force_enc != 0)
2832 {
2833 char_u *fenc = enc_canonize(eap->cmd + eap->force_enc);
2834
2835 if (fenc != NULL)
2836 set_string_option_direct((char_u *)"fenc", -1,
2837 fenc, OPT_FREE|OPT_LOCAL, 0);
2838 vim_free(fenc);
2839 }
2840}
2841
Bram Moolenaar071d4272004-06-13 20:20:40 +00002842/*
2843 * Find next fileencoding to use from 'fileencodings'.
2844 * "pp" points to fenc_next. It's advanced to the next item.
2845 * When there are no more items, an empty string is returned and *pp is set to
2846 * NULL.
2847 * When *pp is not set to NULL, the result is in allocated memory.
2848 */
2849 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002850next_fenc(char_u **pp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002851{
2852 char_u *p;
2853 char_u *r;
2854
2855 if (**pp == NUL)
2856 {
2857 *pp = NULL;
2858 return (char_u *)"";
2859 }
2860 p = vim_strchr(*pp, ',');
2861 if (p == NULL)
2862 {
2863 r = enc_canonize(*pp);
2864 *pp += STRLEN(*pp);
2865 }
2866 else
2867 {
2868 r = vim_strnsave(*pp, (int)(p - *pp));
2869 *pp = p + 1;
2870 if (r != NULL)
2871 {
2872 p = enc_canonize(r);
2873 vim_free(r);
2874 r = p;
2875 }
2876 }
2877 if (r == NULL) /* out of memory */
2878 {
2879 r = (char_u *)"";
2880 *pp = NULL;
2881 }
2882 return r;
2883}
2884
2885# ifdef FEAT_EVAL
2886/*
2887 * Convert a file with the 'charconvert' expression.
2888 * This closes the file which is to be read, converts it and opens the
2889 * resulting file for reading.
2890 * Returns name of the resulting converted file (the caller should delete it
2891 * after reading it).
2892 * Returns NULL if the conversion failed ("*fdp" is not set) .
2893 */
2894 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002895readfile_charconvert(
2896 char_u *fname, /* name of input file */
2897 char_u *fenc, /* converted from */
2898 int *fdp) /* in/out: file descriptor of file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002899{
2900 char_u *tmpname;
2901 char_u *errmsg = NULL;
2902
Bram Moolenaare5c421c2015-03-31 13:33:08 +02002903 tmpname = vim_tempname('r', FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002904 if (tmpname == NULL)
2905 errmsg = (char_u *)_("Can't find temp file for conversion");
2906 else
2907 {
2908 close(*fdp); /* close the input file, ignore errors */
2909 *fdp = -1;
2910 if (eval_charconvert(fenc, enc_utf8 ? (char_u *)"utf-8" : p_enc,
2911 fname, tmpname) == FAIL)
2912 errmsg = (char_u *)_("Conversion with 'charconvert' failed");
2913 if (errmsg == NULL && (*fdp = mch_open((char *)tmpname,
2914 O_RDONLY | O_EXTRA, 0)) < 0)
2915 errmsg = (char_u *)_("can't read output of 'charconvert'");
2916 }
2917
2918 if (errmsg != NULL)
2919 {
2920 /* Don't use emsg(), it breaks mappings, the retry with
2921 * another type of conversion might still work. */
2922 MSG(errmsg);
2923 if (tmpname != NULL)
2924 {
2925 mch_remove(tmpname); /* delete converted file */
Bram Moolenaard23a8232018-02-10 18:45:26 +01002926 VIM_CLEAR(tmpname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002927 }
2928 }
2929
2930 /* If the input file is closed, open it (caller should check for error). */
2931 if (*fdp < 0)
2932 *fdp = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
2933
2934 return tmpname;
2935}
2936# endif
2937
2938#endif
2939
2940#ifdef FEAT_VIMINFO
2941/*
2942 * Read marks for the current buffer from the viminfo file, when we support
2943 * buffer marks and the buffer has a name.
2944 */
2945 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002946check_marks_read(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002947{
2948 if (!curbuf->b_marks_read && get_viminfo_parameter('\'') > 0
2949 && curbuf->b_ffname != NULL)
Bram Moolenaard812df62008-11-09 12:46:09 +00002950 read_viminfo(NULL, VIF_WANT_MARKS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002951
2952 /* Always set b_marks_read; needed when 'viminfo' is changed to include
2953 * the ' parameter after opening a buffer. */
2954 curbuf->b_marks_read = TRUE;
2955}
2956#endif
2957
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002958#if defined(FEAT_CRYPT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002959/*
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002960 * Check for magic number used for encryption. Applies to the current buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002961 * If found, the magic number is removed from ptr[*sizep] and *sizep and
2962 * *filesizep are updated.
2963 * Return the (new) encryption key, NULL for no encryption.
2964 */
2965 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002966check_for_cryptkey(
2967 char_u *cryptkey, /* previous encryption key or NULL */
2968 char_u *ptr, /* pointer to read bytes */
2969 long *sizep, /* length of read bytes */
Bram Moolenaar8767f522016-07-01 17:17:39 +02002970 off_T *filesizep, /* nr of bytes used from file */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002971 int newfile, /* editing a new buffer */
2972 char_u *fname, /* file name to display */
2973 int *did_ask) /* flag: whether already asked for key */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002974{
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002975 int method = crypt_method_nr_from_magic((char *)ptr, *sizep);
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02002976 int b_p_ro = curbuf->b_p_ro;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002977
2978 if (method >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002979 {
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02002980 /* Mark the buffer as read-only until the decryption has taken place.
2981 * Avoids accidentally overwriting the file with garbage. */
2982 curbuf->b_p_ro = TRUE;
2983
Bram Moolenaar2be79502014-08-13 21:58:28 +02002984 /* Set the cryptmethod local to the buffer. */
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002985 crypt_set_cm_option(curbuf, method);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002986 if (cryptkey == NULL && !*did_ask)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002987 {
2988 if (*curbuf->b_p_key)
2989 cryptkey = curbuf->b_p_key;
2990 else
2991 {
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002992 /* When newfile is TRUE, store the typed key in the 'key'
2993 * option and don't free it. bf needs hash of the key saved.
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002994 * Don't ask for the key again when first time Enter was hit.
2995 * Happens when retrying to detect encoding. */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002996 smsg((char_u *)_(need_key_msg), fname);
2997 msg_scroll = TRUE;
Bram Moolenaar3a0c9082014-11-12 15:15:42 +01002998 crypt_check_method(method);
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002999 cryptkey = crypt_get_key(newfile, FALSE);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02003000 *did_ask = TRUE;
3001
Bram Moolenaar071d4272004-06-13 20:20:40 +00003002 /* check if empty key entered */
3003 if (cryptkey != NULL && *cryptkey == NUL)
3004 {
3005 if (cryptkey != curbuf->b_p_key)
3006 vim_free(cryptkey);
3007 cryptkey = NULL;
3008 }
3009 }
3010 }
3011
3012 if (cryptkey != NULL)
3013 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003014 int header_len;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003015
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003016 curbuf->b_cryptstate = crypt_create_from_header(
3017 method, cryptkey, ptr);
3018 crypt_set_cm_option(curbuf, method);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003019
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003020 /* Remove cryptmethod specific header from the text. */
3021 header_len = crypt_get_header_len(method);
Bram Moolenaar680e0152016-09-25 20:54:11 +02003022 if (*sizep <= header_len)
3023 /* invalid header, buffer can't be encrypted */
3024 return NULL;
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003025 *filesizep += header_len;
3026 *sizep -= header_len;
3027 mch_memmove(ptr, ptr + header_len, (size_t)*sizep);
3028
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02003029 /* Restore the read-only flag. */
3030 curbuf->b_p_ro = b_p_ro;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003031 }
3032 }
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003033 /* When starting to edit a new file which does not have encryption, clear
3034 * the 'key' option, except when starting up (called with -x argument) */
Bram Moolenaarfa0ff9a2010-07-25 16:05:19 +02003035 else if (newfile && *curbuf->b_p_key != NUL && !starting)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003036 set_option_value((char_u *)"key", 0L, (char_u *)"", OPT_LOCAL);
3037
3038 return cryptkey;
3039}
Bram Moolenaar80794b12010-06-13 05:20:42 +02003040#endif /* FEAT_CRYPT */
3041
Bram Moolenaar071d4272004-06-13 20:20:40 +00003042#ifdef UNIX
3043 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003044set_file_time(
3045 char_u *fname,
3046 time_t atime, /* access time */
3047 time_t mtime) /* modification time */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003048{
3049# if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
3050 struct utimbuf buf;
3051
3052 buf.actime = atime;
3053 buf.modtime = mtime;
3054 (void)utime((char *)fname, &buf);
3055# else
3056# if defined(HAVE_UTIMES)
3057 struct timeval tvp[2];
3058
3059 tvp[0].tv_sec = atime;
3060 tvp[0].tv_usec = 0;
3061 tvp[1].tv_sec = mtime;
3062 tvp[1].tv_usec = 0;
3063# ifdef NeXT
3064 (void)utimes((char *)fname, tvp);
3065# else
3066 (void)utimes((char *)fname, (const struct timeval *)&tvp);
3067# endif
3068# endif
3069# endif
3070}
3071#endif /* UNIX */
3072
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003073#if defined(VMS) && !defined(MIN)
3074/* Older DECC compiler for VAX doesn't define MIN() */
3075# define MIN(a, b) ((a) < (b) ? (a) : (b))
3076#endif
3077
Bram Moolenaar071d4272004-06-13 20:20:40 +00003078/*
Bram Moolenaar5386a122007-06-28 20:02:32 +00003079 * Return TRUE if a file appears to be read-only from the file permissions.
3080 */
3081 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003082check_file_readonly(
3083 char_u *fname, /* full path to file */
3084 int perm) /* known permissions on file */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003085{
3086#ifndef USE_MCH_ACCESS
3087 int fd = 0;
3088#endif
3089
3090 return (
3091#ifdef USE_MCH_ACCESS
3092# ifdef UNIX
3093 (perm & 0222) == 0 ||
3094# endif
3095 mch_access((char *)fname, W_OK)
3096#else
3097 (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0
3098 ? TRUE : (close(fd), FALSE)
3099#endif
3100 );
3101}
3102
3103
3104/*
Bram Moolenaar292ad192005-12-11 21:29:51 +00003105 * buf_write() - write to file "fname" lines "start" through "end"
Bram Moolenaar071d4272004-06-13 20:20:40 +00003106 *
3107 * We do our own buffering here because fwrite() is so slow.
3108 *
Bram Moolenaar292ad192005-12-11 21:29:51 +00003109 * If "forceit" is true, we don't care for errors when attempting backups.
3110 * In case of an error everything possible is done to restore the original
Bram Moolenaare37d50a2008-08-06 17:06:04 +00003111 * file. But when "forceit" is TRUE, we risk losing it.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003112 *
3113 * When "reset_changed" is TRUE and "append" == FALSE and "start" == 1 and
3114 * "end" == curbuf->b_ml.ml_line_count, reset curbuf->b_changed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003115 *
3116 * This function must NOT use NameBuff (because it's called by autowrite()).
3117 *
3118 * return FAIL for failure, OK otherwise
3119 */
3120 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003121buf_write(
3122 buf_T *buf,
3123 char_u *fname,
3124 char_u *sfname,
3125 linenr_T start,
3126 linenr_T end,
3127 exarg_T *eap, /* for forced 'ff' and 'fenc', can be
Bram Moolenaar071d4272004-06-13 20:20:40 +00003128 NULL! */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003129 int append, /* append to the file */
3130 int forceit,
3131 int reset_changed,
3132 int filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003133{
3134 int fd;
3135 char_u *backup = NULL;
3136 int backup_copy = FALSE; /* copy the original file? */
3137 int dobackup;
3138 char_u *ffname;
3139 char_u *wfname = NULL; /* name of file to write to */
3140 char_u *s;
3141 char_u *ptr;
3142 char_u c;
3143 int len;
3144 linenr_T lnum;
3145 long nchars;
3146 char_u *errmsg = NULL;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003147 int errmsg_allocated = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003148 char_u *errnum = NULL;
3149 char_u *buffer;
3150 char_u smallbuf[SMBUFSIZE];
3151 char_u *backup_ext;
3152 int bufsize;
3153 long perm; /* file permissions */
3154 int retval = OK;
3155 int newfile = FALSE; /* TRUE if file doesn't exist yet */
3156 int msg_save = msg_scroll;
3157 int overwriting; /* TRUE if writing over original */
3158 int no_eol = FALSE; /* no end-of-line written */
3159 int device = FALSE; /* writing to a device */
Bram Moolenaar8767f522016-07-01 17:17:39 +02003160 stat_T st_old;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003161 int prev_got_int = got_int;
Bram Moolenaare6bf6552017-06-27 22:11:51 +02003162 int checking_conversion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003163 int file_readonly = FALSE; /* overwritten file is read-only */
3164 static char *err_readonly = "is read-only (cannot override: \"W\" in 'cpoptions')";
Bram Moolenaara06ecab2016-07-16 14:47:36 +02003165#if defined(UNIX) /*XXX fix me sometime? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003166 int made_writable = FALSE; /* 'w' bit has been set */
3167#endif
3168 /* writing everything */
3169 int whole = (start == 1 && end == buf->b_ml.ml_line_count);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003170 linenr_T old_line_count = buf->b_ml.ml_line_count;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003171 int attr;
3172 int fileformat;
3173 int write_bin;
3174 struct bw_info write_info; /* info for buf_write_bytes() */
3175#ifdef FEAT_MBYTE
3176 int converted = FALSE;
3177 int notconverted = FALSE;
3178 char_u *fenc; /* effective 'fileencoding' */
3179 char_u *fenc_tofree = NULL; /* allocated "fenc" */
3180#endif
3181#ifdef HAS_BW_FLAGS
3182 int wb_flags = 0;
3183#endif
3184#ifdef HAVE_ACL
3185 vim_acl_T acl = NULL; /* ACL copied from original file to
3186 backup or new file */
3187#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003188#ifdef FEAT_PERSISTENT_UNDO
3189 int write_undo_file = FALSE;
3190 context_sha256_T sha_ctx;
3191#endif
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003192 unsigned int bkc = get_bkc_value(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003193
3194 if (fname == NULL || *fname == NUL) /* safety check */
3195 return FAIL;
Bram Moolenaar70d60e92009-12-31 13:53:33 +00003196 if (buf->b_ml.ml_mfp == NULL)
3197 {
3198 /* This can happen during startup when there is a stray "w" in the
3199 * vimrc file. */
3200 EMSG(_(e_emptybuf));
3201 return FAIL;
3202 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003203
3204 /*
3205 * Disallow writing from .exrc and .vimrc in current directory for
3206 * security reasons.
3207 */
3208 if (check_secure())
3209 return FAIL;
3210
3211 /* Avoid a crash for a long name. */
3212 if (STRLEN(fname) >= MAXPATHL)
3213 {
3214 EMSG(_(e_longname));
3215 return FAIL;
3216 }
3217
3218#ifdef FEAT_MBYTE
3219 /* must init bw_conv_buf and bw_iconv_fd before jumping to "fail" */
3220 write_info.bw_conv_buf = NULL;
3221 write_info.bw_conv_error = FALSE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003222 write_info.bw_conv_error_lnum = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003223 write_info.bw_restlen = 0;
3224# ifdef USE_ICONV
3225 write_info.bw_iconv_fd = (iconv_t)-1;
3226# endif
3227#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003228#ifdef FEAT_CRYPT
3229 write_info.bw_buffer = buf;
3230#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003231
Bram Moolenaardf177f62005-02-22 08:39:57 +00003232 /* After writing a file changedtick changes but we don't want to display
3233 * the line. */
3234 ex_no_reprint = TRUE;
3235
Bram Moolenaar071d4272004-06-13 20:20:40 +00003236 /*
3237 * If there is no file name yet, use the one for the written file.
3238 * BF_NOTEDITED is set to reflect this (in case the write fails).
3239 * Don't do this when the write is for a filter command.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003240 * Don't do this when appending.
3241 * Only do this when 'cpoptions' contains the 'F' flag.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003242 */
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003243 if (buf->b_ffname == NULL
3244 && reset_changed
Bram Moolenaar071d4272004-06-13 20:20:40 +00003245 && whole
3246 && buf == curbuf
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00003247#ifdef FEAT_QUICKFIX
3248 && !bt_nofile(buf)
3249#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003250 && !filtering
Bram Moolenaar292ad192005-12-11 21:29:51 +00003251 && (!append || vim_strchr(p_cpo, CPO_FNAMEAPP) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003252 && vim_strchr(p_cpo, CPO_FNAMEW) != NULL)
3253 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003254 if (set_rw_fname(fname, sfname) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003255 return FAIL;
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003256 buf = curbuf; /* just in case autocmds made "buf" invalid */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003257 }
3258
3259 if (sfname == NULL)
3260 sfname = fname;
3261 /*
3262 * For Unix: Use the short file name whenever possible.
3263 * Avoids problems with networks and when directory names are changed.
3264 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
3265 * another directory, which we don't detect
3266 */
3267 ffname = fname; /* remember full fname */
3268#ifdef UNIX
3269 fname = sfname;
3270#endif
3271
3272 if (buf->b_ffname != NULL && fnamecmp(ffname, buf->b_ffname) == 0)
3273 overwriting = TRUE;
3274 else
3275 overwriting = FALSE;
3276
3277 if (exiting)
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003278 settmode(TMODE_COOK); /* when exiting allow typeahead now */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003279
3280 ++no_wait_return; /* don't wait for return yet */
3281
3282 /*
3283 * Set '[ and '] marks to the lines to be written.
3284 */
3285 buf->b_op_start.lnum = start;
3286 buf->b_op_start.col = 0;
3287 buf->b_op_end.lnum = end;
3288 buf->b_op_end.col = 0;
3289
Bram Moolenaar071d4272004-06-13 20:20:40 +00003290 {
3291 aco_save_T aco;
3292 int buf_ffname = FALSE;
3293 int buf_sfname = FALSE;
3294 int buf_fname_f = FALSE;
3295 int buf_fname_s = FALSE;
3296 int did_cmd = FALSE;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003297 int nofile_err = FALSE;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003298 int empty_memline = (buf->b_ml.ml_mfp == NULL);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003299 bufref_T bufref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003300
3301 /*
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003302 * Apply PRE autocommands.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003303 * Set curbuf to the buffer to be written.
3304 * Careful: The autocommands may call buf_write() recursively!
3305 */
3306 if (ffname == buf->b_ffname)
3307 buf_ffname = TRUE;
3308 if (sfname == buf->b_sfname)
3309 buf_sfname = TRUE;
3310 if (fname == buf->b_ffname)
3311 buf_fname_f = TRUE;
3312 if (fname == buf->b_sfname)
3313 buf_fname_s = TRUE;
3314
3315 /* set curwin/curbuf to buf and save a few things */
3316 aucmd_prepbuf(&aco, buf);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003317 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003318
3319 if (append)
3320 {
3321 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD,
3322 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003323 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003324#ifdef FEAT_QUICKFIX
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00003325 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003326 nofile_err = TRUE;
3327 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003328#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003329 apply_autocmds_exarg(EVENT_FILEAPPENDPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003330 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003331 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003332 }
3333 else if (filtering)
3334 {
3335 apply_autocmds_exarg(EVENT_FILTERWRITEPRE,
3336 NULL, sfname, FALSE, curbuf, eap);
3337 }
3338 else if (reset_changed && whole)
3339 {
Bram Moolenaar39fc42e2011-09-02 11:56:20 +02003340 int was_changed = curbufIsChanged();
3341
3342 did_cmd = apply_autocmds_exarg(EVENT_BUFWRITECMD,
3343 sfname, sfname, FALSE, curbuf, eap);
3344 if (did_cmd)
3345 {
3346 if (was_changed && !curbufIsChanged())
3347 {
3348 /* Written everything correctly and BufWriteCmd has reset
3349 * 'modified': Correct the undo information so that an
3350 * undo now sets 'modified'. */
3351 u_unchanged(curbuf);
3352 u_update_save_nr(curbuf);
3353 }
3354 }
3355 else
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003356 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003357#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003358 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003359 nofile_err = TRUE;
3360 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003361#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003362 apply_autocmds_exarg(EVENT_BUFWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003363 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003364 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003365 }
3366 else
3367 {
3368 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD,
3369 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003370 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003371#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003372 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003373 nofile_err = TRUE;
3374 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003375#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003376 apply_autocmds_exarg(EVENT_FILEWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003377 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003378 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003379 }
3380
3381 /* restore curwin/curbuf and a few other things */
3382 aucmd_restbuf(&aco);
3383
3384 /*
3385 * In three situations we return here and don't write the file:
3386 * 1. the autocommands deleted or unloaded the buffer.
3387 * 2. The autocommands abort script processing.
3388 * 3. If one of the "Cmd" autocommands was executed.
3389 */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003390 if (!bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003391 buf = NULL;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003392 if (buf == NULL || (buf->b_ml.ml_mfp == NULL && !empty_memline)
Bram Moolenaar1e015462005-09-25 22:16:38 +00003393 || did_cmd || nofile_err
3394#ifdef FEAT_EVAL
3395 || aborting()
3396#endif
3397 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003398 {
3399 --no_wait_return;
3400 msg_scroll = msg_save;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003401 if (nofile_err)
3402 EMSG(_("E676: No matching autocommands for acwrite buffer"));
3403
Bram Moolenaar1e015462005-09-25 22:16:38 +00003404 if (nofile_err
3405#ifdef FEAT_EVAL
3406 || aborting()
3407#endif
3408 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003409 /* An aborting error, interrupt or exception in the
3410 * autocommands. */
3411 return FAIL;
3412 if (did_cmd)
3413 {
3414 if (buf == NULL)
3415 /* The buffer was deleted. We assume it was written
3416 * (can't retry anyway). */
3417 return OK;
3418 if (overwriting)
3419 {
3420 /* Assume the buffer was written, update the timestamp. */
3421 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00003422 if (append)
3423 buf->b_flags &= ~BF_NEW;
3424 else
3425 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003426 }
Bram Moolenaar292ad192005-12-11 21:29:51 +00003427 if (reset_changed && buf->b_changed && !append
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003428 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003429 /* Buffer still changed, the autocommands didn't work
3430 * properly. */
3431 return FAIL;
3432 return OK;
3433 }
3434#ifdef FEAT_EVAL
3435 if (!aborting())
3436#endif
3437 EMSG(_("E203: Autocommands deleted or unloaded buffer to be written"));
3438 return FAIL;
3439 }
3440
3441 /*
3442 * The autocommands may have changed the number of lines in the file.
3443 * When writing the whole file, adjust the end.
3444 * When writing part of the file, assume that the autocommands only
3445 * changed the number of lines that are to be written (tricky!).
3446 */
3447 if (buf->b_ml.ml_line_count != old_line_count)
3448 {
3449 if (whole) /* write all */
3450 end = buf->b_ml.ml_line_count;
3451 else if (buf->b_ml.ml_line_count > old_line_count) /* more lines */
3452 end += buf->b_ml.ml_line_count - old_line_count;
3453 else /* less lines */
3454 {
3455 end -= old_line_count - buf->b_ml.ml_line_count;
3456 if (end < start)
3457 {
3458 --no_wait_return;
3459 msg_scroll = msg_save;
3460 EMSG(_("E204: Autocommand changed number of lines in unexpected way"));
3461 return FAIL;
3462 }
3463 }
3464 }
3465
3466 /*
3467 * The autocommands may have changed the name of the buffer, which may
3468 * be kept in fname, ffname and sfname.
3469 */
3470 if (buf_ffname)
3471 ffname = buf->b_ffname;
3472 if (buf_sfname)
3473 sfname = buf->b_sfname;
3474 if (buf_fname_f)
3475 fname = buf->b_ffname;
3476 if (buf_fname_s)
3477 fname = buf->b_sfname;
3478 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003479
3480#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003481 if (netbeans_active() && isNetbeansBuffer(buf))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003482 {
3483 if (whole)
3484 {
3485 /*
3486 * b_changed can be 0 after an undo, but we still need to write
3487 * the buffer to NetBeans.
3488 */
3489 if (buf->b_changed || isNetbeansModified(buf))
3490 {
Bram Moolenaar009b2592004-10-24 19:18:58 +00003491 --no_wait_return; /* may wait for return now */
3492 msg_scroll = msg_save;
3493 netbeans_save_buffer(buf); /* no error checking... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003494 return retval;
3495 }
3496 else
3497 {
3498 errnum = (char_u *)"E656: ";
Bram Moolenaared0e7452008-06-27 19:17:34 +00003499 errmsg = (char_u *)_("NetBeans disallows writes of unmodified buffers");
Bram Moolenaar071d4272004-06-13 20:20:40 +00003500 buffer = NULL;
3501 goto fail;
3502 }
3503 }
3504 else
3505 {
3506 errnum = (char_u *)"E657: ";
3507 errmsg = (char_u *)_("Partial writes disallowed for NetBeans buffers");
3508 buffer = NULL;
3509 goto fail;
3510 }
3511 }
3512#endif
3513
3514 if (shortmess(SHM_OVER) && !exiting)
3515 msg_scroll = FALSE; /* overwrite previous file message */
3516 else
3517 msg_scroll = TRUE; /* don't overwrite previous file message */
3518 if (!filtering)
3519 filemess(buf,
3520#ifndef UNIX
3521 sfname,
3522#else
3523 fname,
3524#endif
3525 (char_u *)"", 0); /* show that we are busy */
3526 msg_scroll = FALSE; /* always overwrite the file message now */
3527
3528 buffer = alloc(BUFSIZE);
3529 if (buffer == NULL) /* can't allocate big buffer, use small
3530 * one (to be able to write when out of
3531 * memory) */
3532 {
3533 buffer = smallbuf;
3534 bufsize = SMBUFSIZE;
3535 }
3536 else
3537 bufsize = BUFSIZE;
3538
3539 /*
3540 * Get information about original file (if there is one).
3541 */
Bram Moolenaar53076832015-12-31 19:53:21 +01003542#if defined(UNIX)
Bram Moolenaar6f192452007-11-08 19:49:02 +00003543 st_old.st_dev = 0;
3544 st_old.st_ino = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003545 perm = -1;
3546 if (mch_stat((char *)fname, &st_old) < 0)
3547 newfile = TRUE;
3548 else
3549 {
3550 perm = st_old.st_mode;
3551 if (!S_ISREG(st_old.st_mode)) /* not a file */
3552 {
3553 if (S_ISDIR(st_old.st_mode))
3554 {
3555 errnum = (char_u *)"E502: ";
3556 errmsg = (char_u *)_("is a directory");
3557 goto fail;
3558 }
3559 if (mch_nodetype(fname) != NODE_WRITABLE)
3560 {
3561 errnum = (char_u *)"E503: ";
3562 errmsg = (char_u *)_("is not a file or writable device");
3563 goto fail;
3564 }
3565 /* It's a device of some kind (or a fifo) which we can write to
3566 * but for which we can't make a backup. */
3567 device = TRUE;
3568 newfile = TRUE;
3569 perm = -1;
3570 }
3571 }
3572#else /* !UNIX */
3573 /*
3574 * Check for a writable device name.
3575 */
3576 c = mch_nodetype(fname);
3577 if (c == NODE_OTHER)
3578 {
3579 errnum = (char_u *)"E503: ";
3580 errmsg = (char_u *)_("is not a file or writable device");
3581 goto fail;
3582 }
3583 if (c == NODE_WRITABLE)
3584 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003585# if defined(MSWIN)
Bram Moolenaar043545e2006-10-10 16:44:07 +00003586 /* MS-Windows allows opening a device, but we will probably get stuck
3587 * trying to write to it. */
3588 if (!p_odev)
3589 {
3590 errnum = (char_u *)"E796: ";
3591 errmsg = (char_u *)_("writing to device disabled with 'opendevice' option");
3592 goto fail;
3593 }
3594# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003595 device = TRUE;
3596 newfile = TRUE;
3597 perm = -1;
3598 }
3599 else
3600 {
3601 perm = mch_getperm(fname);
3602 if (perm < 0)
3603 newfile = TRUE;
3604 else if (mch_isdir(fname))
3605 {
3606 errnum = (char_u *)"E502: ";
3607 errmsg = (char_u *)_("is a directory");
3608 goto fail;
3609 }
3610 if (overwriting)
3611 (void)mch_stat((char *)fname, &st_old);
3612 }
3613#endif /* !UNIX */
3614
3615 if (!device && !newfile)
3616 {
3617 /*
3618 * Check if the file is really writable (when renaming the file to
3619 * make a backup we won't discover it later).
3620 */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003621 file_readonly = check_file_readonly(fname, (int)perm);
3622
Bram Moolenaar071d4272004-06-13 20:20:40 +00003623 if (!forceit && file_readonly)
3624 {
3625 if (vim_strchr(p_cpo, CPO_FWRITE) != NULL)
3626 {
3627 errnum = (char_u *)"E504: ";
3628 errmsg = (char_u *)_(err_readonly);
3629 }
3630 else
3631 {
3632 errnum = (char_u *)"E505: ";
3633 errmsg = (char_u *)_("is read-only (add ! to override)");
3634 }
3635 goto fail;
3636 }
3637
3638 /*
3639 * Check if the timestamp hasn't changed since reading the file.
3640 */
3641 if (overwriting)
3642 {
3643 retval = check_mtime(buf, &st_old);
3644 if (retval == FAIL)
3645 goto fail;
3646 }
3647 }
3648
3649#ifdef HAVE_ACL
3650 /*
3651 * For systems that support ACL: get the ACL from the original file.
3652 */
3653 if (!newfile)
3654 acl = mch_get_acl(fname);
3655#endif
3656
3657 /*
3658 * If 'backupskip' is not empty, don't make a backup for some files.
3659 */
3660 dobackup = (p_wb || p_bk || *p_pm != NUL);
3661#ifdef FEAT_WILDIGN
3662 if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname))
3663 dobackup = FALSE;
3664#endif
3665
3666 /*
3667 * Save the value of got_int and reset it. We don't want a previous
3668 * interruption cancel writing, only hitting CTRL-C while writing should
3669 * abort it.
3670 */
3671 prev_got_int = got_int;
3672 got_int = FALSE;
3673
3674 /* Mark the buffer as 'being saved' to prevent changed buffer warnings */
3675 buf->b_saving = TRUE;
3676
3677 /*
3678 * If we are not appending or filtering, the file exists, and the
3679 * 'writebackup', 'backup' or 'patchmode' option is set, need a backup.
3680 * When 'patchmode' is set also make a backup when appending.
3681 *
3682 * Do not make any backup, if 'writebackup' and 'backup' are both switched
3683 * off. This helps when editing large files on almost-full disks.
3684 */
3685 if (!(append && *p_pm == NUL) && !filtering && perm >= 0 && dobackup)
3686 {
3687#if defined(UNIX) || defined(WIN32)
Bram Moolenaar8767f522016-07-01 17:17:39 +02003688 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003689#endif
3690
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003691 if ((bkc & BKC_YES) || append) /* "yes" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003692 backup_copy = TRUE;
3693#if defined(UNIX) || defined(WIN32)
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003694 else if ((bkc & BKC_AUTO)) /* "auto" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003695 {
3696 int i;
3697
3698# ifdef UNIX
3699 /*
3700 * Don't rename the file when:
3701 * - it's a hard link
3702 * - it's a symbolic link
3703 * - we don't have write permission in the directory
3704 * - we can't set the owner/group of the new file
3705 */
3706 if (st_old.st_nlink > 1
3707 || mch_lstat((char *)fname, &st) < 0
3708 || st.st_dev != st_old.st_dev
Bram Moolenaara5792f52005-11-23 21:25:05 +00003709 || st.st_ino != st_old.st_ino
3710# ifndef HAVE_FCHOWN
3711 || st.st_uid != st_old.st_uid
3712 || st.st_gid != st_old.st_gid
3713# endif
3714 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003715 backup_copy = TRUE;
3716 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003717# else
3718# ifdef WIN32
3719 /* On NTFS file systems hard links are possible. */
3720 if (mch_is_linked(fname))
3721 backup_copy = TRUE;
3722 else
3723# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003724# endif
3725 {
3726 /*
3727 * Check if we can create a file and set the owner/group to
3728 * the ones from the original file.
3729 * First find a file name that doesn't exist yet (use some
3730 * arbitrary numbers).
3731 */
3732 STRCPY(IObuff, fname);
3733 for (i = 4913; ; i += 123)
3734 {
3735 sprintf((char *)gettail(IObuff), "%d", i);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003736 if (mch_lstat((char *)IObuff, &st) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003737 break;
3738 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00003739 fd = mch_open((char *)IObuff,
3740 O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003741 if (fd < 0) /* can't write in directory */
3742 backup_copy = TRUE;
3743 else
3744 {
3745# ifdef UNIX
Bram Moolenaara5792f52005-11-23 21:25:05 +00003746# ifdef HAVE_FCHOWN
Bram Moolenaar42335f52018-09-13 15:33:43 +02003747 vim_ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003748# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003749 if (mch_stat((char *)IObuff, &st) < 0
3750 || st.st_uid != st_old.st_uid
3751 || st.st_gid != st_old.st_gid
Bram Moolenaar78a15312009-05-15 19:33:18 +00003752 || (long)st.st_mode != perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003753 backup_copy = TRUE;
3754# endif
Bram Moolenaar98358622005-11-28 22:58:23 +00003755 /* Close the file before removing it, on MS-Windows we
3756 * can't delete an open file. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003757 close(fd);
Bram Moolenaar98358622005-11-28 22:58:23 +00003758 mch_remove(IObuff);
Bram Moolenaar3479c5d2010-08-08 18:46:06 +02003759# ifdef MSWIN
3760 /* MS-Windows may trigger a virus scanner to open the
3761 * file, we can't delete it then. Keep trying for half a
3762 * second. */
3763 {
3764 int try;
3765
3766 for (try = 0; try < 10; ++try)
3767 {
3768 if (mch_lstat((char *)IObuff, &st) < 0)
3769 break;
3770 ui_delay(50L, TRUE); /* wait 50 msec */
3771 mch_remove(IObuff);
3772 }
3773 }
3774# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003775 }
3776 }
3777 }
3778
Bram Moolenaar071d4272004-06-13 20:20:40 +00003779 /*
3780 * Break symlinks and/or hardlinks if we've been asked to.
3781 */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003782 if ((bkc & BKC_BREAKSYMLINK) || (bkc & BKC_BREAKHARDLINK))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003783 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003784# ifdef UNIX
Bram Moolenaar071d4272004-06-13 20:20:40 +00003785 int lstat_res;
3786
3787 lstat_res = mch_lstat((char *)fname, &st);
3788
3789 /* Symlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003790 if ((bkc & BKC_BREAKSYMLINK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003791 && lstat_res == 0
3792 && st.st_ino != st_old.st_ino)
3793 backup_copy = FALSE;
3794
3795 /* Hardlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003796 if ((bkc & BKC_BREAKHARDLINK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003797 && st_old.st_nlink > 1
3798 && (lstat_res != 0 || st.st_ino == st_old.st_ino))
3799 backup_copy = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003800# else
3801# if defined(WIN32)
3802 /* Symlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003803 if ((bkc & BKC_BREAKSYMLINK) && mch_is_symbolic_link(fname))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003804 backup_copy = FALSE;
3805
3806 /* Hardlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003807 if ((bkc & BKC_BREAKHARDLINK) && mch_is_hard_link(fname))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003808 backup_copy = FALSE;
3809# endif
3810# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003811 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003812
3813#endif
3814
3815 /* make sure we have a valid backup extension to use */
3816 if (*p_bex == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003817 backup_ext = (char_u *)".bak";
Bram Moolenaar071d4272004-06-13 20:20:40 +00003818 else
3819 backup_ext = p_bex;
3820
3821 if (backup_copy
3822 && (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) >= 0)
3823 {
3824 int bfd;
3825 char_u *copybuf, *wp;
3826 int some_error = FALSE;
Bram Moolenaar8767f522016-07-01 17:17:39 +02003827 stat_T st_new;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003828 char_u *dirp;
3829 char_u *rootname;
Bram Moolenaarb782ba42018-08-07 21:39:28 +02003830#if defined(UNIX) || defined(WIN3264)
3831 char_u *p;
3832#endif
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003833#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003834 int did_set_shortname;
Bram Moolenaarcd142e32017-11-16 17:03:45 +01003835 mode_t umask_save;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003836#endif
3837
3838 copybuf = alloc(BUFSIZE + 1);
3839 if (copybuf == NULL)
3840 {
3841 some_error = TRUE; /* out of memory */
3842 goto nobackup;
3843 }
3844
3845 /*
3846 * Try to make the backup in each directory in the 'bdir' option.
3847 *
3848 * Unix semantics has it, that we may have a writable file,
3849 * that cannot be recreated with a simple open(..., O_CREAT, ) e.g:
3850 * - the directory is not writable,
3851 * - the file may be a symbolic link,
3852 * - the file may belong to another user/group, etc.
3853 *
3854 * For these reasons, the existing writable file must be truncated
3855 * and reused. Creation of a backup COPY will be attempted.
3856 */
3857 dirp = p_bdir;
3858 while (*dirp)
3859 {
3860#ifdef UNIX
3861 st_new.st_ino = 0;
3862 st_new.st_dev = 0;
3863 st_new.st_gid = 0;
3864#endif
3865
3866 /*
3867 * Isolate one directory name, using an entry in 'bdir'.
3868 */
3869 (void)copy_option_part(&dirp, copybuf, BUFSIZE, ",");
Bram Moolenaarb782ba42018-08-07 21:39:28 +02003870
3871#if defined(UNIX) || defined(WIN3264)
3872 p = copybuf + STRLEN(copybuf);
3873 if (after_pathsep(copybuf, p) && p[-1] == p[-2])
3874 // Ends with '//', use full path
3875 if ((p = make_percent_swname(copybuf, fname)) != NULL)
3876 {
3877 backup = modname(p, backup_ext, FALSE);
3878 vim_free(p);
3879 }
3880#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003881 rootname = get_file_in_dir(fname, copybuf);
3882 if (rootname == NULL)
3883 {
3884 some_error = TRUE; /* out of memory */
3885 goto nobackup;
3886 }
3887
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003888#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003889 did_set_shortname = FALSE;
3890#endif
3891
3892 /*
3893 * May try twice if 'shortname' not set.
3894 */
3895 for (;;)
3896 {
3897 /*
Bram Moolenaarb782ba42018-08-07 21:39:28 +02003898 * Make the backup file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003899 */
Bram Moolenaarb782ba42018-08-07 21:39:28 +02003900 if (backup == NULL)
3901 backup = buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003902 rootname, backup_ext, FALSE);
3903 if (backup == NULL)
3904 {
3905 vim_free(rootname);
3906 some_error = TRUE; /* out of memory */
3907 goto nobackup;
3908 }
3909
3910 /*
3911 * Check if backup file already exists.
3912 */
3913 if (mch_stat((char *)backup, &st_new) >= 0)
3914 {
3915#ifdef UNIX
3916 /*
3917 * Check if backup file is same as original file.
3918 * May happen when modname() gave the same file back.
3919 * E.g. silly link, or file name-length reached.
3920 * If we don't check here, we either ruin the file
3921 * when copying or erase it after writing. jw.
3922 */
3923 if (st_new.st_dev == st_old.st_dev
3924 && st_new.st_ino == st_old.st_ino)
3925 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01003926 VIM_CLEAR(backup); /* no backup file to delete */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003927 /*
3928 * may try again with 'shortname' set
3929 */
3930 if (!(buf->b_shortname || buf->b_p_sn))
3931 {
3932 buf->b_shortname = TRUE;
3933 did_set_shortname = TRUE;
3934 continue;
3935 }
3936 /* setting shortname didn't help */
3937 if (did_set_shortname)
3938 buf->b_shortname = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003939 break;
3940 }
3941#endif
3942
3943 /*
3944 * If we are not going to keep the backup file, don't
3945 * delete an existing one, try to use another name.
3946 * Change one character, just before the extension.
3947 */
3948 if (!p_bk)
3949 {
3950 wp = backup + STRLEN(backup) - 1
3951 - STRLEN(backup_ext);
3952 if (wp < backup) /* empty file name ??? */
3953 wp = backup;
3954 *wp = 'z';
3955 while (*wp > 'a'
3956 && mch_stat((char *)backup, &st_new) >= 0)
3957 --*wp;
3958 /* They all exist??? Must be something wrong. */
3959 if (*wp == 'a')
Bram Moolenaard23a8232018-02-10 18:45:26 +01003960 VIM_CLEAR(backup);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003961 }
3962 }
3963 break;
3964 }
3965 vim_free(rootname);
3966
3967 /*
3968 * Try to create the backup file
3969 */
3970 if (backup != NULL)
3971 {
3972 /* remove old backup, if present */
3973 mch_remove(backup);
3974 /* Open with O_EXCL to avoid the file being created while
Bram Moolenaarcd142e32017-11-16 17:03:45 +01003975 * we were sleeping (symlink hacker attack?). Reset umask
3976 * if possible to avoid mch_setperm() below. */
3977#ifdef UNIX
3978 umask_save = umask(0);
3979#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003980 bfd = mch_open((char *)backup,
Bram Moolenaara5792f52005-11-23 21:25:05 +00003981 O_WRONLY|O_CREAT|O_EXTRA|O_EXCL|O_NOFOLLOW,
3982 perm & 0777);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01003983#ifdef UNIX
3984 (void)umask(umask_save);
3985#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003986 if (bfd < 0)
Bram Moolenaard23a8232018-02-10 18:45:26 +01003987 VIM_CLEAR(backup);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003988 else
3989 {
Bram Moolenaarcd142e32017-11-16 17:03:45 +01003990 /* Set file protection same as original file, but
3991 * strip s-bit. Only needed if umask() wasn't used
3992 * above. */
3993#ifndef UNIX
Bram Moolenaar071d4272004-06-13 20:20:40 +00003994 (void)mch_setperm(backup, perm & 0777);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01003995#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00003996 /*
3997 * Try to set the group of the backup same as the
3998 * original file. If this fails, set the protection
3999 * bits for the group same as the protection bits for
4000 * others.
4001 */
Bram Moolenaara5792f52005-11-23 21:25:05 +00004002 if (st_new.st_gid != st_old.st_gid
Bram Moolenaar071d4272004-06-13 20:20:40 +00004003# ifdef HAVE_FCHOWN /* sequent-ptx lacks fchown() */
Bram Moolenaara5792f52005-11-23 21:25:05 +00004004 && fchown(bfd, (uid_t)-1, st_old.st_gid) != 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00004005# endif
4006 )
4007 mch_setperm(backup,
4008 (perm & 0707) | ((perm & 07) << 3));
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004009# if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004010 mch_copy_sec(fname, backup);
4011# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004012#endif
4013
4014 /*
4015 * copy the file.
4016 */
4017 write_info.bw_fd = bfd;
4018 write_info.bw_buf = copybuf;
4019#ifdef HAS_BW_FLAGS
4020 write_info.bw_flags = FIO_NOCONVERT;
4021#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004022 while ((write_info.bw_len = read_eintr(fd, copybuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004023 BUFSIZE)) > 0)
4024 {
4025 if (buf_write_bytes(&write_info) == FAIL)
4026 {
4027 errmsg = (char_u *)_("E506: Can't write to backup file (add ! to override)");
4028 break;
4029 }
4030 ui_breakcheck();
4031 if (got_int)
4032 {
4033 errmsg = (char_u *)_(e_interr);
4034 break;
4035 }
4036 }
4037
4038 if (close(bfd) < 0 && errmsg == NULL)
4039 errmsg = (char_u *)_("E507: Close error for backup file (add ! to override)");
4040 if (write_info.bw_len < 0)
4041 errmsg = (char_u *)_("E508: Can't read file for backup (add ! to override)");
4042#ifdef UNIX
4043 set_file_time(backup, st_old.st_atime, st_old.st_mtime);
4044#endif
4045#ifdef HAVE_ACL
4046 mch_set_acl(backup, acl);
4047#endif
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004048#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004049 mch_copy_sec(fname, backup);
4050#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004051 break;
4052 }
4053 }
4054 }
4055 nobackup:
4056 close(fd); /* ignore errors for closing read file */
4057 vim_free(copybuf);
4058
4059 if (backup == NULL && errmsg == NULL)
4060 errmsg = (char_u *)_("E509: Cannot create backup file (add ! to override)");
4061 /* ignore errors when forceit is TRUE */
4062 if ((some_error || errmsg != NULL) && !forceit)
4063 {
4064 retval = FAIL;
4065 goto fail;
4066 }
4067 errmsg = NULL;
4068 }
4069 else
4070 {
4071 char_u *dirp;
4072 char_u *p;
4073 char_u *rootname;
4074
4075 /*
4076 * Make a backup by renaming the original file.
4077 */
4078 /*
4079 * If 'cpoptions' includes the "W" flag, we don't want to
4080 * overwrite a read-only file. But rename may be possible
4081 * anyway, thus we need an extra check here.
4082 */
4083 if (file_readonly && vim_strchr(p_cpo, CPO_FWRITE) != NULL)
4084 {
4085 errnum = (char_u *)"E504: ";
4086 errmsg = (char_u *)_(err_readonly);
4087 goto fail;
4088 }
4089
4090 /*
4091 *
4092 * Form the backup file name - change path/fo.o.h to
4093 * path/fo.o.h.bak Try all directories in 'backupdir', first one
4094 * that works is used.
4095 */
4096 dirp = p_bdir;
4097 while (*dirp)
4098 {
4099 /*
4100 * Isolate one directory name and make the backup file name.
4101 */
4102 (void)copy_option_part(&dirp, IObuff, IOSIZE, ",");
Bram Moolenaarb782ba42018-08-07 21:39:28 +02004103
4104#if defined(UNIX) || defined(WIN3264)
4105 p = IObuff + STRLEN(IObuff);
4106 if (after_pathsep(IObuff, p) && p[-1] == p[-2])
4107 // path ends with '//', use full path
4108 if ((p = make_percent_swname(IObuff, fname)) != NULL)
4109 {
4110 backup = modname(p, backup_ext, FALSE);
4111 vim_free(p);
4112 }
4113#endif
4114 if (backup == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004115 {
Bram Moolenaarb782ba42018-08-07 21:39:28 +02004116 rootname = get_file_in_dir(fname, IObuff);
4117 if (rootname == NULL)
4118 backup = NULL;
4119 else
4120 {
4121 backup = buf_modname(
4122 (buf->b_p_sn || buf->b_shortname),
4123 rootname, backup_ext, FALSE);
4124 vim_free(rootname);
4125 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004126 }
4127
4128 if (backup != NULL)
4129 {
4130 /*
4131 * If we are not going to keep the backup file, don't
4132 * delete an existing one, try to use another name.
4133 * Change one character, just before the extension.
4134 */
4135 if (!p_bk && mch_getperm(backup) >= 0)
4136 {
4137 p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext);
4138 if (p < backup) /* empty file name ??? */
4139 p = backup;
4140 *p = 'z';
4141 while (*p > 'a' && mch_getperm(backup) >= 0)
4142 --*p;
4143 /* They all exist??? Must be something wrong! */
4144 if (*p == 'a')
Bram Moolenaard23a8232018-02-10 18:45:26 +01004145 VIM_CLEAR(backup);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004146 }
4147 }
4148 if (backup != NULL)
4149 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004150 /*
Bram Moolenaarbfd8fc02005-09-20 23:22:24 +00004151 * Delete any existing backup and move the current version
4152 * to the backup. For safety, we don't remove the backup
4153 * until the write has finished successfully. And if the
4154 * 'backup' option is set, leave it around.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004155 */
4156 /*
4157 * If the renaming of the original file to the backup file
4158 * works, quit here.
4159 */
4160 if (vim_rename(fname, backup) == 0)
4161 break;
4162
Bram Moolenaard23a8232018-02-10 18:45:26 +01004163 VIM_CLEAR(backup); /* don't do the rename below */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004164 }
4165 }
4166 if (backup == NULL && !forceit)
4167 {
4168 errmsg = (char_u *)_("E510: Can't make backup file (add ! to override)");
4169 goto fail;
4170 }
4171 }
4172 }
4173
Bram Moolenaar53076832015-12-31 19:53:21 +01004174#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004175 /* When using ":w!" and the file was read-only: make it writable */
4176 if (forceit && perm >= 0 && !(perm & 0200) && st_old.st_uid == getuid()
4177 && vim_strchr(p_cpo, CPO_FWRITE) == NULL)
4178 {
4179 perm |= 0200;
4180 (void)mch_setperm(fname, perm);
4181 made_writable = TRUE;
4182 }
4183#endif
4184
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004185 /* When using ":w!" and writing to the current file, 'readonly' makes no
Bram Moolenaar4399ef42005-02-12 14:29:27 +00004186 * sense, reset it, unless 'Z' appears in 'cpoptions'. */
4187 if (forceit && overwriting && vim_strchr(p_cpo, CPO_KEEPRO) == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004188 {
4189 buf->b_p_ro = FALSE;
4190#ifdef FEAT_TITLE
4191 need_maketitle = TRUE; /* set window title later */
4192#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004193 status_redraw_all(); /* redraw status lines later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004194 }
4195
4196 if (end > buf->b_ml.ml_line_count)
4197 end = buf->b_ml.ml_line_count;
4198 if (buf->b_ml.ml_flags & ML_EMPTY)
4199 start = end + 1;
4200
4201 /*
4202 * If the original file is being overwritten, there is a small chance that
4203 * we crash in the middle of writing. Therefore the file is preserved now.
4204 * This makes all block numbers positive so that recovery does not need
4205 * the original file.
4206 * Don't do this if there is a backup file and we are exiting.
4207 */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004208 if (reset_changed && !newfile && overwriting
Bram Moolenaar071d4272004-06-13 20:20:40 +00004209 && !(exiting && backup != NULL))
4210 {
4211 ml_preserve(buf, FALSE);
4212 if (got_int)
4213 {
4214 errmsg = (char_u *)_(e_interr);
4215 goto restore_backup;
4216 }
4217 }
4218
Bram Moolenaar071d4272004-06-13 20:20:40 +00004219#ifdef VMS
4220 vms_remove_version(fname); /* remove version */
4221#endif
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00004222 /* Default: write the file directly. May write to a temp file for
Bram Moolenaar071d4272004-06-13 20:20:40 +00004223 * multi-byte conversion. */
4224 wfname = fname;
4225
4226#ifdef FEAT_MBYTE
4227 /* Check for forced 'fileencoding' from "++opt=val" argument. */
4228 if (eap != NULL && eap->force_enc != 0)
4229 {
4230 fenc = eap->cmd + eap->force_enc;
4231 fenc = enc_canonize(fenc);
4232 fenc_tofree = fenc;
4233 }
4234 else
4235 fenc = buf->b_p_fenc;
4236
4237 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004238 * Check if the file needs to be converted.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004239 */
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004240 converted = need_conversion(fenc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004241
4242 /*
4243 * Check if UTF-8 to UCS-2/4 or Latin1 conversion needs to be done. Or
4244 * Latin1 to Unicode conversion. This is handled in buf_write_bytes().
4245 * Prepare the flags for it and allocate bw_conv_buf when needed.
4246 */
4247 if (converted && (enc_utf8 || STRCMP(p_enc, "latin1") == 0))
4248 {
4249 wb_flags = get_fio_flags(fenc);
4250 if (wb_flags & (FIO_UCS2 | FIO_UCS4 | FIO_UTF16 | FIO_UTF8))
4251 {
4252 /* Need to allocate a buffer to translate into. */
4253 if (wb_flags & (FIO_UCS2 | FIO_UTF16 | FIO_UTF8))
4254 write_info.bw_conv_buflen = bufsize * 2;
4255 else /* FIO_UCS4 */
4256 write_info.bw_conv_buflen = bufsize * 4;
4257 write_info.bw_conv_buf
4258 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4259 if (write_info.bw_conv_buf == NULL)
4260 end = 0;
4261 }
4262 }
4263
4264# ifdef WIN3264
4265 if (converted && wb_flags == 0 && (wb_flags = get_win_fio_flags(fenc)) != 0)
4266 {
4267 /* Convert UTF-8 -> UCS-2 and UCS-2 -> DBCS. Worst-case * 4: */
4268 write_info.bw_conv_buflen = bufsize * 4;
4269 write_info.bw_conv_buf
4270 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4271 if (write_info.bw_conv_buf == NULL)
4272 end = 0;
4273 }
4274# endif
4275
Bram Moolenaard0573012017-10-28 21:11:06 +02004276# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00004277 if (converted && wb_flags == 0 && (wb_flags = get_mac_fio_flags(fenc)) != 0)
4278 {
4279 write_info.bw_conv_buflen = bufsize * 3;
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 }
4285# endif
4286
4287# if defined(FEAT_EVAL) || defined(USE_ICONV)
4288 if (converted && wb_flags == 0)
4289 {
4290# ifdef USE_ICONV
4291 /*
4292 * Use iconv() conversion when conversion is needed and it's not done
4293 * internally.
4294 */
4295 write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc,
4296 enc_utf8 ? (char_u *)"utf-8" : p_enc);
4297 if (write_info.bw_iconv_fd != (iconv_t)-1)
4298 {
4299 /* We're going to use iconv(), allocate a buffer to convert in. */
4300 write_info.bw_conv_buflen = bufsize * ICONV_MULT;
4301 write_info.bw_conv_buf
4302 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4303 if (write_info.bw_conv_buf == NULL)
4304 end = 0;
4305 write_info.bw_first = TRUE;
4306 }
4307# ifdef FEAT_EVAL
4308 else
4309# endif
4310# endif
4311
4312# ifdef FEAT_EVAL
4313 /*
4314 * When the file needs to be converted with 'charconvert' after
4315 * writing, write to a temp file instead and let the conversion
4316 * overwrite the original file.
4317 */
4318 if (*p_ccv != NUL)
4319 {
Bram Moolenaare5c421c2015-03-31 13:33:08 +02004320 wfname = vim_tempname('w', FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004321 if (wfname == NULL) /* Can't write without a tempfile! */
4322 {
4323 errmsg = (char_u *)_("E214: Can't find temp file for writing");
4324 goto restore_backup;
4325 }
4326 }
4327# endif
4328 }
4329# endif
4330 if (converted && wb_flags == 0
4331# ifdef USE_ICONV
4332 && write_info.bw_iconv_fd == (iconv_t)-1
4333# endif
4334# ifdef FEAT_EVAL
4335 && wfname == fname
4336# endif
4337 )
4338 {
4339 if (!forceit)
4340 {
4341 errmsg = (char_u *)_("E213: Cannot convert (add ! to write without conversion)");
4342 goto restore_backup;
4343 }
4344 notconverted = TRUE;
4345 }
4346#endif
4347
4348 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004349 * If conversion is taking place, we may first pretend to write and check
4350 * for conversion errors. Then loop again to write for real.
4351 * When not doing conversion this writes for real right away.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004352 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004353 for (checking_conversion = TRUE; ; checking_conversion = FALSE)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004354 {
4355 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004356 * There is no need to check conversion when:
4357 * - there is no conversion
4358 * - we make a backup file, that can be restored in case of conversion
4359 * failure.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004360 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004361#ifdef FEAT_MBYTE
4362 if (!converted || dobackup)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004363#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004364 checking_conversion = FALSE;
4365
4366 if (checking_conversion)
4367 {
4368 /* Make sure we don't write anything. */
4369 fd = -1;
4370 write_info.bw_fd = fd;
4371 }
4372 else
4373 {
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004374#ifdef HAVE_FTRUNCATE
4375# define TRUNC_ON_OPEN 0
4376#else
4377# define TRUNC_ON_OPEN O_TRUNC
4378#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004379 /*
4380 * Open the file "wfname" for writing.
4381 * We may try to open the file twice: If we can't write to the file
4382 * and forceit is TRUE we delete the existing file and try to
4383 * create a new one. If this still fails we may have lost the
4384 * original file! (this may happen when the user reached his
4385 * quotum for number of files).
4386 * Appending will fail if the file does not exist and forceit is
4387 * FALSE.
4388 */
4389 while ((fd = mch_open((char *)wfname, O_WRONLY | O_EXTRA | (append
4390 ? (forceit ? (O_APPEND | O_CREAT) : O_APPEND)
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004391 : (O_CREAT | TRUNC_ON_OPEN))
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004392 , perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004393 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004394 /*
4395 * A forced write will try to create a new file if the old one
4396 * is still readonly. This may also happen when the directory
4397 * is read-only. In that case the mch_remove() will fail.
4398 */
4399 if (errmsg == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004400 {
4401#ifdef UNIX
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004402 stat_T st;
4403
4404 /* Don't delete the file when it's a hard or symbolic link.
4405 */
4406 if ((!newfile && st_old.st_nlink > 1)
4407 || (mch_lstat((char *)fname, &st) == 0
4408 && (st.st_dev != st_old.st_dev
4409 || st.st_ino != st_old.st_ino)))
4410 errmsg = (char_u *)_("E166: Can't open linked file for writing");
4411 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004412#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004413 {
4414 errmsg = (char_u *)_("E212: Can't open file for writing");
4415 if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL
4416 && perm >= 0)
4417 {
4418#ifdef UNIX
4419 /* we write to the file, thus it should be marked
4420 writable after all */
4421 if (!(perm & 0200))
4422 made_writable = TRUE;
4423 perm |= 0200;
4424 if (st_old.st_uid != getuid()
4425 || st_old.st_gid != getgid())
4426 perm &= 0777;
4427#endif
4428 if (!append) /* don't remove when appending */
4429 mch_remove(wfname);
4430 continue;
4431 }
4432 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004433 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004434
4435restore_backup:
Bram Moolenaar071d4272004-06-13 20:20:40 +00004436 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004437 stat_T st;
4438
Bram Moolenaar071d4272004-06-13 20:20:40 +00004439 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004440 * If we failed to open the file, we don't need a backup.
4441 * Throw it away. If we moved or removed the original file
4442 * try to put the backup in its place.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004443 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004444 if (backup != NULL && wfname == fname)
4445 {
4446 if (backup_copy)
4447 {
4448 /*
4449 * There is a small chance that we removed the
4450 * original, try to move the copy in its place.
4451 * This may not work if the vim_rename() fails.
4452 * In that case we leave the copy around.
4453 */
4454 /* If file does not exist, put the copy in its
4455 * place */
4456 if (mch_stat((char *)fname, &st) < 0)
4457 vim_rename(backup, fname);
4458 /* if original file does exist throw away the copy
4459 */
4460 if (mch_stat((char *)fname, &st) >= 0)
4461 mch_remove(backup);
4462 }
4463 else
4464 {
4465 /* try to put the original file back */
4466 vim_rename(backup, fname);
4467 }
4468 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004469
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004470 /* if original file no longer exists give an extra warning
4471 */
4472 if (!newfile && mch_stat((char *)fname, &st) < 0)
4473 end = 0;
4474 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004475
4476#ifdef FEAT_MBYTE
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004477 if (wfname != fname)
4478 vim_free(wfname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004479#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004480 goto fail;
4481 }
4482 write_info.bw_fd = fd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004483
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004484#if defined(UNIX)
4485 {
4486 stat_T st;
4487
4488 /* Double check we are writing the intended file before making
4489 * any changes. */
4490 if (overwriting
4491 && (!dobackup || backup_copy)
4492 && fname == wfname
4493 && perm >= 0
4494 && mch_fstat(fd, &st) == 0
4495 && st.st_ino != st_old.st_ino)
4496 {
4497 close(fd);
4498 errmsg = (char_u *)_("E949: File changed while writing");
4499 goto fail;
4500 }
4501 }
4502#endif
4503#ifdef HAVE_FTRUNCATE
4504 if (!append)
Bram Moolenaar42335f52018-09-13 15:33:43 +02004505 vim_ignored = ftruncate(fd, (off_t)0);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004506#endif
4507
Bram Moolenaard0573012017-10-28 21:11:06 +02004508#if defined(WIN3264)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004509 if (backup != NULL && overwriting && !append)
4510 {
4511 if (backup_copy)
4512 (void)mch_copy_file_attribute(wfname, backup);
4513 else
4514 (void)mch_copy_file_attribute(backup, wfname);
4515 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004516
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004517 if (!overwriting && !append)
4518 {
4519 if (buf->b_ffname != NULL)
4520 (void)mch_copy_file_attribute(buf->b_ffname, wfname);
4521 /* Should copy resource fork */
4522 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004523#endif
4524
Bram Moolenaar071d4272004-06-13 20:20:40 +00004525#ifdef FEAT_CRYPT
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004526 if (*buf->b_p_key != NUL && !filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004527 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004528 char_u *header;
4529 int header_len;
4530
4531 buf->b_cryptstate = crypt_create_for_writing(
4532 crypt_get_method_nr(buf),
4533 buf->b_p_key, &header, &header_len);
4534 if (buf->b_cryptstate == NULL || header == NULL)
4535 end = 0;
4536 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004537 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004538 /* Write magic number, so that Vim knows how this file is
4539 * encrypted when reading it back. */
4540 write_info.bw_buf = header;
4541 write_info.bw_len = header_len;
4542 write_info.bw_flags = FIO_NOCONVERT;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004543 if (buf_write_bytes(&write_info) == FAIL)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004544 end = 0;
4545 wb_flags |= FIO_ENCRYPTED;
4546 vim_free(header);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004547 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004548 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004549#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004550 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004551 errmsg = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004552
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004553 write_info.bw_buf = buffer;
4554 nchars = 0;
4555
4556 /* use "++bin", "++nobin" or 'binary' */
4557 if (eap != NULL && eap->force_bin != 0)
4558 write_bin = (eap->force_bin == FORCE_BIN);
4559 else
4560 write_bin = buf->b_p_bin;
4561
4562#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004563 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004564 * The BOM is written just after the encryption magic number.
4565 * Skip it when appending and the file already existed, the BOM only
4566 * makes sense at the start of the file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004567 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004568 if (buf->b_p_bomb && !write_bin && (!append || perm < 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004569 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004570 write_info.bw_len = make_bom(buffer, fenc);
4571 if (write_info.bw_len > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004572 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004573 /* don't convert, do encryption */
4574 write_info.bw_flags = FIO_NOCONVERT | wb_flags;
4575 if (buf_write_bytes(&write_info) == FAIL)
4576 end = 0;
4577 else
4578 nchars += write_info.bw_len;
4579 }
4580 }
4581 write_info.bw_start_lnum = start;
4582#endif
4583
4584#ifdef FEAT_PERSISTENT_UNDO
4585 write_undo_file = (buf->b_p_udf
4586 && overwriting
4587 && !append
4588 && !filtering
4589 && reset_changed
4590 && !checking_conversion);
4591 if (write_undo_file)
4592 /* Prepare for computing the hash value of the text. */
4593 sha256_start(&sha_ctx);
4594#endif
4595
4596 write_info.bw_len = bufsize;
4597#ifdef HAS_BW_FLAGS
4598 write_info.bw_flags = wb_flags;
4599#endif
4600 fileformat = get_fileformat_force(buf, eap);
4601 s = buffer;
4602 len = 0;
4603 for (lnum = start; lnum <= end; ++lnum)
4604 {
4605 /*
4606 * The next while loop is done once for each character written.
4607 * Keep it fast!
4608 */
4609 ptr = ml_get_buf(buf, lnum, FALSE) - 1;
4610#ifdef FEAT_PERSISTENT_UNDO
4611 if (write_undo_file)
4612 sha256_update(&sha_ctx, ptr + 1,
4613 (UINT32_T)(STRLEN(ptr + 1) + 1));
4614#endif
4615 while ((c = *++ptr) != NUL)
4616 {
4617 if (c == NL)
4618 *s = NUL; /* replace newlines with NULs */
4619 else if (c == CAR && fileformat == EOL_MAC)
4620 *s = NL; /* Mac: replace CRs with NLs */
4621 else
4622 *s = c;
4623 ++s;
4624 if (++len != bufsize)
4625 continue;
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004626 if (buf_write_bytes(&write_info) == FAIL)
4627 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004628 end = 0; /* write error: break loop */
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004629 break;
4630 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004631 nchars += bufsize;
4632 s = buffer;
4633 len = 0;
4634#ifdef FEAT_MBYTE
4635 write_info.bw_start_lnum = lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004636#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004637 }
4638 /* write failed or last line has no EOL: stop here */
4639 if (end == 0
4640 || (lnum == end
4641 && (write_bin || !buf->b_p_fixeol)
4642 && (lnum == buf->b_no_eol_lnum
4643 || (lnum == buf->b_ml.ml_line_count
4644 && !buf->b_p_eol))))
4645 {
4646 ++lnum; /* written the line, count it */
4647 no_eol = TRUE;
4648 break;
4649 }
4650 if (fileformat == EOL_UNIX)
4651 *s++ = NL;
4652 else
4653 {
4654 *s++ = CAR; /* EOL_MAC or EOL_DOS: write CR */
4655 if (fileformat == EOL_DOS) /* write CR-NL */
4656 {
4657 if (++len == bufsize)
4658 {
4659 if (buf_write_bytes(&write_info) == FAIL)
4660 {
4661 end = 0; /* write error: break loop */
4662 break;
4663 }
4664 nchars += bufsize;
4665 s = buffer;
4666 len = 0;
4667 }
4668 *s++ = NL;
4669 }
4670 }
4671 if (++len == bufsize && end)
4672 {
4673 if (buf_write_bytes(&write_info) == FAIL)
4674 {
4675 end = 0; /* write error: break loop */
4676 break;
4677 }
4678 nchars += bufsize;
4679 s = buffer;
4680 len = 0;
4681
4682 ui_breakcheck();
4683 if (got_int)
4684 {
4685 end = 0; /* Interrupted, break loop */
4686 break;
4687 }
4688 }
4689#ifdef VMS
4690 /*
4691 * On VMS there is a problem: newlines get added when writing
4692 * blocks at a time. Fix it by writing a line at a time.
4693 * This is much slower!
4694 * Explanation: VAX/DECC RTL insists that records in some RMS
4695 * structures end with a newline (carriage return) character, and
4696 * if they don't it adds one.
4697 * With other RMS structures it works perfect without this fix.
4698 */
4699 if (buf->b_fab_rfm == FAB$C_VFC
4700 || ((buf->b_fab_rat & (FAB$M_FTN | FAB$M_CR)) != 0))
4701 {
4702 int b2write;
4703
4704 buf->b_fab_mrs = (buf->b_fab_mrs == 0
4705 ? MIN(4096, bufsize)
4706 : MIN(buf->b_fab_mrs, bufsize));
4707
4708 b2write = len;
4709 while (b2write > 0)
4710 {
4711 write_info.bw_len = MIN(b2write, buf->b_fab_mrs);
4712 if (buf_write_bytes(&write_info) == FAIL)
4713 {
4714 end = 0;
4715 break;
4716 }
4717 b2write -= MIN(b2write, buf->b_fab_mrs);
4718 }
4719 write_info.bw_len = bufsize;
4720 nchars += len;
4721 s = buffer;
4722 len = 0;
4723 }
4724#endif
4725 }
4726 if (len > 0 && end > 0)
4727 {
4728 write_info.bw_len = len;
4729 if (buf_write_bytes(&write_info) == FAIL)
4730 end = 0; /* write error */
4731 nchars += len;
4732 }
4733
4734 /* Stop when writing done or an error was encountered. */
4735 if (!checking_conversion || end == 0)
4736 break;
4737
4738 /* If no error happened until now, writing should be ok, so loop to
4739 * really write the buffer. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004740 }
4741
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004742 /* If we started writing, finish writing. Also when an error was
4743 * encountered. */
4744 if (!checking_conversion)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004745 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004746#if defined(UNIX) && defined(HAVE_FSYNC)
4747 /*
4748 * On many journalling file systems there is a bug that causes both the
4749 * original and the backup file to be lost when halting the system
4750 * right after writing the file. That's because only the meta-data is
4751 * journalled. Syncing the file slows down the system, but assures it
4752 * has been written to disk and we don't lose it.
4753 * For a device do try the fsync() but don't complain if it does not
4754 * work (could be a pipe).
4755 * If the 'fsync' option is FALSE, don't fsync(). Useful for laptops.
4756 */
4757 if (p_fs && fsync(fd) != 0 && !device)
4758 {
Bram Moolenaar7567d0b2017-11-16 23:04:15 +01004759 errmsg = (char_u *)_(e_fsync);
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004760 end = 0;
4761 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004762#endif
4763
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004764#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004765 /* Probably need to set the security context. */
4766 if (!backup_copy)
4767 mch_copy_sec(backup, wfname);
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004768#endif
4769
Bram Moolenaara5792f52005-11-23 21:25:05 +00004770#ifdef UNIX
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004771 /* When creating a new file, set its owner/group to that of the
4772 * original file. Get the new device and inode number. */
4773 if (backup != NULL && !backup_copy)
Bram Moolenaara5792f52005-11-23 21:25:05 +00004774 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004775# ifdef HAVE_FCHOWN
4776 stat_T st;
4777
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004778 /* Don't change the owner when it's already OK, some systems remove
4779 * permission or ACL stuff. */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004780 if (mch_stat((char *)wfname, &st) < 0
4781 || st.st_uid != st_old.st_uid
4782 || st.st_gid != st_old.st_gid)
4783 {
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004784 /* changing owner might not be possible */
Bram Moolenaar42335f52018-09-13 15:33:43 +02004785 vim_ignored = fchown(fd, st_old.st_uid, -1);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004786 /* if changing group fails clear the group permissions */
4787 if (fchown(fd, -1, st_old.st_gid) == -1 && perm > 0)
4788 perm &= ~070;
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004789 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00004790# endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004791 buf_setino(buf);
4792 }
4793 else if (!buf->b_dev_valid)
4794 /* Set the inode when creating a new file. */
4795 buf_setino(buf);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004796#endif
4797
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004798#ifdef UNIX
4799 if (made_writable)
4800 perm &= ~0200; /* reset 'w' bit for security reasons */
4801#endif
4802#ifdef HAVE_FCHMOD
4803 /* set permission of new file same as old file */
4804 if (perm >= 0)
4805 (void)mch_fsetperm(fd, perm);
4806#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004807 if (close(fd) != 0)
4808 {
4809 errmsg = (char_u *)_("E512: Close failed");
4810 end = 0;
4811 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004812
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004813#ifndef HAVE_FCHMOD
4814 /* set permission of new file same as old file */
4815 if (perm >= 0)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004816 (void)mch_setperm(wfname, perm);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004817#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004818#ifdef HAVE_ACL
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004819 /*
4820 * Probably need to set the ACL before changing the user (can't set the
4821 * ACL on a file the user doesn't own).
4822 * On Solaris, with ZFS and the aclmode property set to "discard" (the
4823 * default), chmod() discards all part of a file's ACL that don't
4824 * represent the mode of the file. It's non-trivial for us to discover
4825 * whether we're in that situation, so we simply always re-set the ACL.
4826 */
Bram Moolenaarda412772016-07-14 20:37:07 +02004827# ifndef HAVE_SOLARIS_ZFS_ACL
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004828 if (!backup_copy)
Bram Moolenaarda412772016-07-14 20:37:07 +02004829# endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004830 mch_set_acl(wfname, acl);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004831#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004832#ifdef FEAT_CRYPT
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004833 if (buf->b_cryptstate != NULL)
4834 {
4835 crypt_free_state(buf->b_cryptstate);
4836 buf->b_cryptstate = NULL;
4837 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004838#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004839
Bram Moolenaar071d4272004-06-13 20:20:40 +00004840#if defined(FEAT_MBYTE) && defined(FEAT_EVAL)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004841 if (wfname != fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004842 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004843 /*
4844 * The file was written to a temp file, now it needs to be
4845 * converted with 'charconvert' to (overwrite) the output file.
4846 */
4847 if (end != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004848 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004849 if (eval_charconvert(enc_utf8 ? (char_u *)"utf-8" : p_enc,
4850 fenc, wfname, fname) == FAIL)
4851 {
4852 write_info.bw_conv_error = TRUE;
4853 end = 0;
4854 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004855 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004856 mch_remove(wfname);
4857 vim_free(wfname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004858 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004859#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004860 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004861
4862 if (end == 0)
4863 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004864 /*
4865 * Error encountered.
4866 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004867 if (errmsg == NULL)
4868 {
4869#ifdef FEAT_MBYTE
4870 if (write_info.bw_conv_error)
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004871 {
4872 if (write_info.bw_conv_error_lnum == 0)
4873 errmsg = (char_u *)_("E513: write error, conversion failed (make 'fenc' empty to override)");
4874 else
4875 {
4876 errmsg_allocated = TRUE;
4877 errmsg = alloc(300);
4878 vim_snprintf((char *)errmsg, 300, _("E513: write error, conversion failed in line %ld (make 'fenc' empty to override)"),
4879 (long)write_info.bw_conv_error_lnum);
4880 }
4881 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004882 else
4883#endif
4884 if (got_int)
4885 errmsg = (char_u *)_(e_interr);
4886 else
4887 errmsg = (char_u *)_("E514: write error (file system full?)");
4888 }
4889
4890 /*
4891 * If we have a backup file, try to put it in place of the new file,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004892 * because the new file is probably corrupt. This avoids losing the
Bram Moolenaar071d4272004-06-13 20:20:40 +00004893 * original file when trying to make a backup when writing the file a
4894 * second time.
4895 * When "backup_copy" is set we need to copy the backup over the new
4896 * file. Otherwise rename the backup file.
4897 * If this is OK, don't give the extra warning message.
4898 */
4899 if (backup != NULL)
4900 {
4901 if (backup_copy)
4902 {
4903 /* This may take a while, if we were interrupted let the user
4904 * know we got the message. */
4905 if (got_int)
4906 {
4907 MSG(_(e_interr));
4908 out_flush();
4909 }
4910 if ((fd = mch_open((char *)backup, O_RDONLY | O_EXTRA, 0)) >= 0)
4911 {
4912 if ((write_info.bw_fd = mch_open((char *)fname,
Bram Moolenaar9be038d2005-03-08 22:34:32 +00004913 O_WRONLY | O_CREAT | O_TRUNC | O_EXTRA,
4914 perm & 0777)) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004915 {
4916 /* copy the file. */
4917 write_info.bw_buf = smallbuf;
4918#ifdef HAS_BW_FLAGS
4919 write_info.bw_flags = FIO_NOCONVERT;
4920#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004921 while ((write_info.bw_len = read_eintr(fd, smallbuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004922 SMBUFSIZE)) > 0)
4923 if (buf_write_bytes(&write_info) == FAIL)
4924 break;
4925
4926 if (close(write_info.bw_fd) >= 0
4927 && write_info.bw_len == 0)
4928 end = 1; /* success */
4929 }
4930 close(fd); /* ignore errors for closing read file */
4931 }
4932 }
4933 else
4934 {
4935 if (vim_rename(backup, fname) == 0)
4936 end = 1;
4937 }
4938 }
4939 goto fail;
4940 }
4941
4942 lnum -= start; /* compute number of written lines */
4943 --no_wait_return; /* may wait for return now */
4944
4945#if !(defined(UNIX) || defined(VMS))
4946 fname = sfname; /* use shortname now, for the messages */
4947#endif
4948 if (!filtering)
4949 {
4950 msg_add_fname(buf, fname); /* put fname in IObuff with quotes */
4951 c = FALSE;
4952#ifdef FEAT_MBYTE
4953 if (write_info.bw_conv_error)
4954 {
4955 STRCAT(IObuff, _(" CONVERSION ERROR"));
4956 c = TRUE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004957 if (write_info.bw_conv_error_lnum != 0)
Bram Moolenaara800b422010-06-27 01:15:55 +02004958 vim_snprintf_add((char *)IObuff, IOSIZE, _(" in line %ld;"),
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004959 (long)write_info.bw_conv_error_lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004960 }
4961 else if (notconverted)
4962 {
4963 STRCAT(IObuff, _("[NOT converted]"));
4964 c = TRUE;
4965 }
4966 else if (converted)
4967 {
4968 STRCAT(IObuff, _("[converted]"));
4969 c = TRUE;
4970 }
4971#endif
4972 if (device)
4973 {
4974 STRCAT(IObuff, _("[Device]"));
4975 c = TRUE;
4976 }
4977 else if (newfile)
4978 {
4979 STRCAT(IObuff, shortmess(SHM_NEW) ? _("[New]") : _("[New File]"));
4980 c = TRUE;
4981 }
4982 if (no_eol)
4983 {
4984 msg_add_eol();
4985 c = TRUE;
4986 }
4987 /* may add [unix/dos/mac] */
4988 if (msg_add_fileformat(fileformat))
4989 c = TRUE;
4990#ifdef FEAT_CRYPT
4991 if (wb_flags & FIO_ENCRYPTED)
4992 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004993 crypt_append_msg(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004994 c = TRUE;
4995 }
4996#endif
4997 msg_add_lines(c, (long)lnum, nchars); /* add line/char count */
4998 if (!shortmess(SHM_WRITE))
4999 {
5000 if (append)
5001 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended"));
5002 else
5003 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written"));
5004 }
5005
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00005006 set_keep_msg(msg_trunc_attr(IObuff, FALSE, 0), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005007 }
5008
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005009 /* When written everything correctly: reset 'modified'. Unless not
5010 * writing to the original file and '+' is not in 'cpoptions'. */
Bram Moolenaar292ad192005-12-11 21:29:51 +00005011 if (reset_changed && whole && !append
Bram Moolenaar071d4272004-06-13 20:20:40 +00005012#ifdef FEAT_MBYTE
5013 && !write_info.bw_conv_error
5014#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005015 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL)
5016 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00005017 {
5018 unchanged(buf, TRUE);
Bram Moolenaar95c526e2017-02-25 14:59:34 +01005019 /* b:changedtick is always incremented in unchanged() but that
Bram Moolenaar086329d2014-10-31 19:51:36 +01005020 * should not trigger a TextChanged event. */
Bram Moolenaar5a093432018-02-10 18:15:19 +01005021 if (buf->b_last_changedtick + 1 == CHANGEDTICK(buf))
5022 buf->b_last_changedtick = CHANGEDTICK(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005023 u_unchanged(buf);
Bram Moolenaar730cde92010-06-27 05:18:54 +02005024 u_update_save_nr(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005025 }
5026
5027 /*
5028 * If written to the current file, update the timestamp of the swap file
5029 * and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
5030 */
5031 if (overwriting)
5032 {
5033 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00005034 if (append)
5035 buf->b_flags &= ~BF_NEW;
5036 else
5037 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005038 }
5039
5040 /*
5041 * If we kept a backup until now, and we are in patch mode, then we make
5042 * the backup file our 'original' file.
5043 */
5044 if (*p_pm && dobackup)
5045 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01005046 char *org = (char *)buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005047 fname, p_pm, FALSE);
5048
5049 if (backup != NULL)
5050 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02005051 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005052
5053 /*
5054 * If the original file does not exist yet
5055 * the current backup file becomes the original file
5056 */
5057 if (org == NULL)
5058 EMSG(_("E205: Patchmode: can't save original file"));
5059 else if (mch_stat(org, &st) < 0)
5060 {
5061 vim_rename(backup, (char_u *)org);
Bram Moolenaard23a8232018-02-10 18:45:26 +01005062 VIM_CLEAR(backup); /* don't delete the file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005063#ifdef UNIX
5064 set_file_time((char_u *)org, st_old.st_atime, st_old.st_mtime);
5065#endif
5066 }
5067 }
5068 /*
5069 * If there is no backup file, remember that a (new) file was
5070 * created.
5071 */
5072 else
5073 {
5074 int empty_fd;
5075
5076 if (org == NULL
Bram Moolenaara5792f52005-11-23 21:25:05 +00005077 || (empty_fd = mch_open(org,
5078 O_CREAT | O_EXTRA | O_EXCL | O_NOFOLLOW,
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00005079 perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005080 EMSG(_("E206: patchmode: can't touch empty original file"));
5081 else
5082 close(empty_fd);
5083 }
5084 if (org != NULL)
5085 {
5086 mch_setperm((char_u *)org, mch_getperm(fname) & 0777);
5087 vim_free(org);
5088 }
5089 }
5090
5091 /*
5092 * Remove the backup unless 'backup' option is set
5093 */
5094 if (!p_bk && backup != NULL && mch_remove(backup) != 0)
5095 EMSG(_("E207: Can't delete backup file"));
5096
5097#ifdef FEAT_SUN_WORKSHOP
5098 if (usingSunWorkShop)
5099 workshop_file_saved((char *) ffname);
5100#endif
5101
5102 goto nofail;
5103
5104 /*
5105 * Finish up. We get here either after failure or success.
5106 */
5107fail:
5108 --no_wait_return; /* may wait for return now */
5109nofail:
5110
5111 /* Done saving, we accept changed buffer warnings again */
5112 buf->b_saving = FALSE;
5113
5114 vim_free(backup);
5115 if (buffer != smallbuf)
5116 vim_free(buffer);
5117#ifdef FEAT_MBYTE
5118 vim_free(fenc_tofree);
5119 vim_free(write_info.bw_conv_buf);
5120# ifdef USE_ICONV
5121 if (write_info.bw_iconv_fd != (iconv_t)-1)
5122 {
5123 iconv_close(write_info.bw_iconv_fd);
5124 write_info.bw_iconv_fd = (iconv_t)-1;
5125 }
5126# endif
5127#endif
5128#ifdef HAVE_ACL
5129 mch_free_acl(acl);
5130#endif
5131
5132 if (errmsg != NULL)
5133 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005134 int numlen = errnum != NULL ? (int)STRLEN(errnum) : 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005135
Bram Moolenaar8820b482017-03-16 17:23:31 +01005136 attr = HL_ATTR(HLF_E); /* set highlight for error messages */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005137 msg_add_fname(buf,
5138#ifndef UNIX
5139 sfname
5140#else
5141 fname
5142#endif
5143 ); /* put file name in IObuff with quotes */
5144 if (STRLEN(IObuff) + STRLEN(errmsg) + numlen >= IOSIZE)
5145 IObuff[IOSIZE - STRLEN(errmsg) - numlen - 1] = NUL;
5146 /* If the error message has the form "is ...", put the error number in
5147 * front of the file name. */
5148 if (errnum != NULL)
5149 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00005150 STRMOVE(IObuff + numlen, IObuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005151 mch_memmove(IObuff, errnum, (size_t)numlen);
5152 }
5153 STRCAT(IObuff, errmsg);
5154 emsg(IObuff);
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005155 if (errmsg_allocated)
5156 vim_free(errmsg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005157
5158 retval = FAIL;
5159 if (end == 0)
5160 {
5161 MSG_PUTS_ATTR(_("\nWARNING: Original file may be lost or damaged\n"),
5162 attr | MSG_HIST);
5163 MSG_PUTS_ATTR(_("don't quit the editor until the file is successfully written!"),
5164 attr | MSG_HIST);
5165
5166 /* Update the timestamp to avoid an "overwrite changed file"
5167 * prompt when writing again. */
5168 if (mch_stat((char *)fname, &st_old) >= 0)
5169 {
5170 buf_store_time(buf, &st_old, fname);
5171 buf->b_mtime_read = buf->b_mtime;
5172 }
5173 }
5174 }
5175 msg_scroll = msg_save;
5176
Bram Moolenaar55debbe2010-05-23 23:34:36 +02005177#ifdef FEAT_PERSISTENT_UNDO
5178 /*
5179 * When writing the whole file and 'undofile' is set, also write the undo
5180 * file.
5181 */
5182 if (retval == OK && write_undo_file)
5183 {
5184 char_u hash[UNDO_HASH_SIZE];
5185
5186 sha256_finish(&sha_ctx, hash);
5187 u_write_undo(NULL, FALSE, buf, hash);
5188 }
5189#endif
5190
Bram Moolenaar071d4272004-06-13 20:20:40 +00005191#ifdef FEAT_EVAL
5192 if (!should_abort(retval))
5193#else
5194 if (!got_int)
5195#endif
5196 {
5197 aco_save_T aco;
5198
Bram Moolenaar68a33fc2012-04-25 16:50:48 +02005199 curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */
5200
Bram Moolenaar071d4272004-06-13 20:20:40 +00005201 /*
5202 * Apply POST autocommands.
5203 * Careful: The autocommands may call buf_write() recursively!
5204 */
5205 aucmd_prepbuf(&aco, buf);
5206
5207 if (append)
5208 apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname,
5209 FALSE, curbuf, eap);
5210 else if (filtering)
5211 apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname,
5212 FALSE, curbuf, eap);
5213 else if (reset_changed && whole)
5214 apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname,
5215 FALSE, curbuf, eap);
5216 else
5217 apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname,
5218 FALSE, curbuf, eap);
5219
5220 /* restore curwin/curbuf and a few other things */
5221 aucmd_restbuf(&aco);
5222
5223#ifdef FEAT_EVAL
5224 if (aborting()) /* autocmds may abort script processing */
5225 retval = FALSE;
5226#endif
5227 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005228
5229 got_int |= prev_got_int;
5230
Bram Moolenaar071d4272004-06-13 20:20:40 +00005231 return retval;
5232}
5233
5234/*
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005235 * Set the name of the current buffer. Use when the buffer doesn't have a
5236 * name and a ":r" or ":w" command with a file name is used.
5237 */
5238 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005239set_rw_fname(char_u *fname, char_u *sfname)
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005240{
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005241 buf_T *buf = curbuf;
5242
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005243 /* It's like the unnamed buffer is deleted.... */
5244 if (curbuf->b_p_bl)
5245 apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
5246 apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf);
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01005247#ifdef FEAT_EVAL
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005248 if (aborting()) /* autocmds may abort script processing */
5249 return FAIL;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01005250#endif
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005251 if (curbuf != buf)
5252 {
5253 /* We are in another buffer now, don't do the renaming. */
5254 EMSG(_(e_auchangedbuf));
5255 return FAIL;
5256 }
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005257
5258 if (setfname(curbuf, fname, sfname, FALSE) == OK)
5259 curbuf->b_flags |= BF_NOTEDITED;
5260
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005261 /* ....and a new named one is created */
5262 apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, curbuf);
5263 if (curbuf->b_p_bl)
5264 apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf);
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01005265#ifdef FEAT_EVAL
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005266 if (aborting()) /* autocmds may abort script processing */
5267 return FAIL;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01005268#endif
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005269
5270 /* Do filetype detection now if 'filetype' is empty. */
5271 if (*curbuf->b_p_ft == NUL)
5272 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005273 if (au_has_group((char_u *)"filetypedetect"))
Bram Moolenaar1610d052016-06-09 22:53:01 +02005274 (void)do_doautocmd((char_u *)"filetypedetect BufRead", FALSE, NULL);
Bram Moolenaara3227e22006-03-08 21:32:40 +00005275 do_modelines(0);
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005276 }
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005277
5278 return OK;
5279}
5280
5281/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00005282 * Put file name into IObuff with quotes.
5283 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005284 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005285msg_add_fname(buf_T *buf, char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005286{
5287 if (fname == NULL)
5288 fname = (char_u *)"-stdin-";
5289 home_replace(buf, fname, IObuff + 1, IOSIZE - 4, TRUE);
5290 IObuff[0] = '"';
5291 STRCAT(IObuff, "\" ");
5292}
5293
5294/*
5295 * Append message for text mode to IObuff.
5296 * Return TRUE if something appended.
5297 */
5298 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005299msg_add_fileformat(int eol_type)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005300{
5301#ifndef USE_CRNL
5302 if (eol_type == EOL_DOS)
5303 {
5304 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[dos]") : _("[dos format]"));
5305 return TRUE;
5306 }
5307#endif
5308#ifndef USE_CR
5309 if (eol_type == EOL_MAC)
5310 {
5311 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[mac]") : _("[mac format]"));
5312 return TRUE;
5313 }
5314#endif
5315#if defined(USE_CRNL) || defined(USE_CR)
5316 if (eol_type == EOL_UNIX)
5317 {
5318 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[unix]") : _("[unix format]"));
5319 return TRUE;
5320 }
5321#endif
5322 return FALSE;
5323}
5324
5325/*
5326 * Append line and character count to IObuff.
5327 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005328 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005329msg_add_lines(
5330 int insert_space,
5331 long lnum,
Bram Moolenaar8767f522016-07-01 17:17:39 +02005332 off_T nchars)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005333{
5334 char_u *p;
5335
5336 p = IObuff + STRLEN(IObuff);
5337
5338 if (insert_space)
5339 *p++ = ' ';
5340 if (shortmess(SHM_LINES))
Bram Moolenaarbde98102016-07-01 20:03:42 +02005341 vim_snprintf((char *)p, IOSIZE - (p - IObuff),
Bram Moolenaarea391762018-04-08 13:07:22 +02005342 "%ldL, %lldC", lnum, (long long)nchars);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005343 else
5344 {
Bram Moolenaarda6e8912018-08-21 15:12:14 +02005345 sprintf((char *)p, NGETTEXT("%ld line, ", "%ld lines, ", lnum), lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005346 p += STRLEN(p);
Bram Moolenaarda6e8912018-08-21 15:12:14 +02005347 vim_snprintf((char *)p, IOSIZE - (p - IObuff),
5348 NGETTEXT("%lld character", "%lld characters", nchars),
5349 (long long)nchars);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005350 }
5351}
5352
5353/*
5354 * Append message for missing line separator to IObuff.
5355 */
5356 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005357msg_add_eol(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005358{
5359 STRCAT(IObuff, shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]"));
5360}
5361
5362/*
5363 * Check modification time of file, before writing to it.
5364 * The size isn't checked, because using a tool like "gzip" takes care of
5365 * using the same timestamp but can't set the size.
5366 */
5367 static int
Bram Moolenaar8767f522016-07-01 17:17:39 +02005368check_mtime(buf_T *buf, stat_T *st)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005369{
5370 if (buf->b_mtime_read != 0
5371 && time_differs((long)st->st_mtime, buf->b_mtime_read))
5372 {
5373 msg_scroll = TRUE; /* don't overwrite messages here */
5374 msg_silent = 0; /* must give this prompt */
5375 /* don't use emsg() here, don't want to flush the buffers */
5376 MSG_ATTR(_("WARNING: The file has been changed since reading it!!!"),
Bram Moolenaar8820b482017-03-16 17:23:31 +01005377 HL_ATTR(HLF_E));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005378 if (ask_yesno((char_u *)_("Do you really want to write to it"),
5379 TRUE) == 'n')
5380 return FAIL;
5381 msg_scroll = FALSE; /* always overwrite the file message now */
5382 }
5383 return OK;
5384}
5385
5386 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005387time_differs(long t1, long t2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005388{
Bram Moolenaar48e330a2016-02-23 14:53:34 +01005389#if defined(__linux__) || defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005390 /* On a FAT filesystem, esp. under Linux, there are only 5 bits to store
5391 * the seconds. Since the roundoff is done when flushing the inode, the
5392 * time may change unexpectedly by one second!!! */
5393 return (t1 - t2 > 1 || t2 - t1 > 1);
5394#else
5395 return (t1 != t2);
5396#endif
5397}
5398
5399/*
5400 * Call write() to write a number of bytes to the file.
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005401 * Handles encryption and 'encoding' conversion.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005402 *
5403 * Return FAIL for failure, OK otherwise.
5404 */
5405 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005406buf_write_bytes(struct bw_info *ip)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005407{
5408 int wlen;
5409 char_u *buf = ip->bw_buf; /* data to write */
5410 int len = ip->bw_len; /* length of data */
5411#ifdef HAS_BW_FLAGS
5412 int flags = ip->bw_flags; /* extra flags */
5413#endif
5414
5415#ifdef FEAT_MBYTE
5416 /*
5417 * Skip conversion when writing the crypt magic number or the BOM.
5418 */
5419 if (!(flags & FIO_NOCONVERT))
5420 {
5421 char_u *p;
5422 unsigned c;
5423 int n;
5424
5425 if (flags & FIO_UTF8)
5426 {
5427 /*
5428 * Convert latin1 in the buffer to UTF-8 in the file.
5429 */
5430 p = ip->bw_conv_buf; /* translate to buffer */
5431 for (wlen = 0; wlen < len; ++wlen)
5432 p += utf_char2bytes(buf[wlen], p);
5433 buf = ip->bw_conv_buf;
5434 len = (int)(p - ip->bw_conv_buf);
5435 }
5436 else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1))
5437 {
5438 /*
5439 * Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
5440 * Latin1 chars in the file.
5441 */
5442 if (flags & FIO_LATIN1)
5443 p = buf; /* translate in-place (can only get shorter) */
5444 else
5445 p = ip->bw_conv_buf; /* translate to buffer */
5446 for (wlen = 0; wlen < len; wlen += n)
5447 {
5448 if (wlen == 0 && ip->bw_restlen != 0)
5449 {
5450 int l;
5451
5452 /* Use remainder of previous call. Append the start of
5453 * buf[] to get a full sequence. Might still be too
5454 * short! */
5455 l = CONV_RESTLEN - ip->bw_restlen;
5456 if (l > len)
5457 l = len;
5458 mch_memmove(ip->bw_rest + ip->bw_restlen, buf, (size_t)l);
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005459 n = utf_ptr2len_len(ip->bw_rest, ip->bw_restlen + l);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005460 if (n > ip->bw_restlen + len)
5461 {
5462 /* We have an incomplete byte sequence at the end to
5463 * be written. We can't convert it without the
5464 * remaining bytes. Keep them for the next call. */
5465 if (ip->bw_restlen + len > CONV_RESTLEN)
5466 return FAIL;
5467 ip->bw_restlen += len;
5468 break;
5469 }
5470 if (n > 1)
5471 c = utf_ptr2char(ip->bw_rest);
5472 else
5473 c = ip->bw_rest[0];
5474 if (n >= ip->bw_restlen)
5475 {
5476 n -= ip->bw_restlen;
5477 ip->bw_restlen = 0;
5478 }
5479 else
5480 {
5481 ip->bw_restlen -= n;
5482 mch_memmove(ip->bw_rest, ip->bw_rest + n,
5483 (size_t)ip->bw_restlen);
5484 n = 0;
5485 }
5486 }
5487 else
5488 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005489 n = utf_ptr2len_len(buf + wlen, len - wlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005490 if (n > len - wlen)
5491 {
5492 /* We have an incomplete byte sequence at the end to
5493 * be written. We can't convert it without the
5494 * remaining bytes. Keep them for the next call. */
5495 if (len - wlen > CONV_RESTLEN)
5496 return FAIL;
5497 ip->bw_restlen = len - wlen;
5498 mch_memmove(ip->bw_rest, buf + wlen,
5499 (size_t)ip->bw_restlen);
5500 break;
5501 }
5502 if (n > 1)
5503 c = utf_ptr2char(buf + wlen);
5504 else
5505 c = buf[wlen];
5506 }
5507
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005508 if (ucs2bytes(c, &p, flags) && !ip->bw_conv_error)
5509 {
5510 ip->bw_conv_error = TRUE;
5511 ip->bw_conv_error_lnum = ip->bw_start_lnum;
5512 }
5513 if (c == NL)
5514 ++ip->bw_start_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005515 }
5516 if (flags & FIO_LATIN1)
5517 len = (int)(p - buf);
5518 else
5519 {
5520 buf = ip->bw_conv_buf;
5521 len = (int)(p - ip->bw_conv_buf);
5522 }
5523 }
5524
5525# ifdef WIN3264
5526 else if (flags & FIO_CODEPAGE)
5527 {
5528 /*
5529 * Convert UTF-8 or codepage to UCS-2 and then to MS-Windows
5530 * codepage.
5531 */
5532 char_u *from;
5533 size_t fromlen;
5534 char_u *to;
5535 int u8c;
5536 BOOL bad = FALSE;
5537 int needed;
5538
5539 if (ip->bw_restlen > 0)
5540 {
5541 /* Need to concatenate the remainder of the previous call and
5542 * the bytes of the current call. Use the end of the
5543 * conversion buffer for this. */
5544 fromlen = len + ip->bw_restlen;
5545 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5546 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5547 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5548 }
5549 else
5550 {
5551 from = buf;
5552 fromlen = len;
5553 }
5554
5555 to = ip->bw_conv_buf;
5556 if (enc_utf8)
5557 {
5558 /* Convert from UTF-8 to UCS-2, to the start of the buffer.
5559 * The buffer has been allocated to be big enough. */
5560 while (fromlen > 0)
5561 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005562 n = (int)utf_ptr2len_len(from, (int)fromlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005563 if (n > (int)fromlen) /* incomplete byte sequence */
5564 break;
5565 u8c = utf_ptr2char(from);
5566 *to++ = (u8c & 0xff);
5567 *to++ = (u8c >> 8);
5568 fromlen -= n;
5569 from += n;
5570 }
5571
5572 /* Copy remainder to ip->bw_rest[] to be used for the next
5573 * call. */
5574 if (fromlen > CONV_RESTLEN)
5575 {
5576 /* weird overlong sequence */
5577 ip->bw_conv_error = TRUE;
5578 return FAIL;
5579 }
5580 mch_memmove(ip->bw_rest, from, fromlen);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005581 ip->bw_restlen = (int)fromlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005582 }
5583 else
5584 {
5585 /* Convert from enc_codepage to UCS-2, to the start of the
5586 * buffer. The buffer has been allocated to be big enough. */
5587 ip->bw_restlen = 0;
5588 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005589 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005590 NULL, 0);
5591 if (needed == 0)
5592 {
5593 /* When conversion fails there may be a trailing byte. */
5594 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005595 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen - 1,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005596 NULL, 0);
5597 if (needed == 0)
5598 {
5599 /* Conversion doesn't work. */
5600 ip->bw_conv_error = TRUE;
5601 return FAIL;
5602 }
5603 /* Save the trailing byte for the next call. */
5604 ip->bw_rest[0] = from[fromlen - 1];
5605 ip->bw_restlen = 1;
5606 }
5607 needed = MultiByteToWideChar(enc_codepage, MB_ERR_INVALID_CHARS,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005608 (LPCSTR)from, (int)(fromlen - ip->bw_restlen),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005609 (LPWSTR)to, needed);
5610 if (needed == 0)
5611 {
5612 /* Safety check: Conversion doesn't work. */
5613 ip->bw_conv_error = TRUE;
5614 return FAIL;
5615 }
5616 to += needed * 2;
5617 }
5618
5619 fromlen = to - ip->bw_conv_buf;
5620 buf = to;
5621# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5622 if (FIO_GET_CP(flags) == CP_UTF8)
5623 {
5624 /* Convert from UCS-2 to UTF-8, using the remainder of the
5625 * conversion buffer. Fails when out of space. */
5626 for (from = ip->bw_conv_buf; fromlen > 1; fromlen -= 2)
5627 {
5628 u8c = *from++;
5629 u8c += (*from++ << 8);
5630 to += utf_char2bytes(u8c, to);
5631 if (to + 6 >= ip->bw_conv_buf + ip->bw_conv_buflen)
5632 {
5633 ip->bw_conv_error = TRUE;
5634 return FAIL;
5635 }
5636 }
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005637 len = (int)(to - buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005638 }
5639 else
5640#endif
5641 {
5642 /* Convert from UCS-2 to the codepage, using the remainder of
5643 * the conversion buffer. If the conversion uses the default
5644 * character "0", the data doesn't fit in this encoding, so
5645 * fail. */
5646 len = WideCharToMultiByte(FIO_GET_CP(flags), 0,
5647 (LPCWSTR)ip->bw_conv_buf, (int)fromlen / sizeof(WCHAR),
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005648 (LPSTR)to, (int)(ip->bw_conv_buflen - fromlen), 0,
5649 &bad);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005650 if (bad)
5651 {
5652 ip->bw_conv_error = TRUE;
5653 return FAIL;
5654 }
5655 }
5656 }
5657# endif
5658
Bram Moolenaar56718732006-03-15 22:53:57 +00005659# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00005660 else if (flags & FIO_MACROMAN)
5661 {
5662 /*
5663 * Convert UTF-8 or latin1 to Apple MacRoman.
5664 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005665 char_u *from;
5666 size_t fromlen;
5667
5668 if (ip->bw_restlen > 0)
5669 {
5670 /* Need to concatenate the remainder of the previous call and
5671 * the bytes of the current call. Use the end of the
5672 * conversion buffer for this. */
5673 fromlen = len + ip->bw_restlen;
5674 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5675 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5676 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5677 }
5678 else
5679 {
5680 from = buf;
5681 fromlen = len;
5682 }
5683
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00005684 if (enc2macroman(from, fromlen,
5685 ip->bw_conv_buf, &len, ip->bw_conv_buflen,
5686 ip->bw_rest, &ip->bw_restlen) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005687 {
5688 ip->bw_conv_error = TRUE;
5689 return FAIL;
5690 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005691 buf = ip->bw_conv_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005692 }
5693# endif
5694
5695# ifdef USE_ICONV
5696 if (ip->bw_iconv_fd != (iconv_t)-1)
5697 {
5698 const char *from;
5699 size_t fromlen;
5700 char *to;
5701 size_t tolen;
5702
5703 /* Convert with iconv(). */
5704 if (ip->bw_restlen > 0)
5705 {
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005706 char *fp;
5707
Bram Moolenaar071d4272004-06-13 20:20:40 +00005708 /* Need to concatenate the remainder of the previous call and
5709 * the bytes of the current call. Use the end of the
5710 * conversion buffer for this. */
5711 fromlen = len + ip->bw_restlen;
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005712 fp = (char *)ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5713 mch_memmove(fp, ip->bw_rest, (size_t)ip->bw_restlen);
5714 mch_memmove(fp + ip->bw_restlen, buf, (size_t)len);
5715 from = fp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005716 tolen = ip->bw_conv_buflen - fromlen;
5717 }
5718 else
5719 {
5720 from = (const char *)buf;
5721 fromlen = len;
5722 tolen = ip->bw_conv_buflen;
5723 }
5724 to = (char *)ip->bw_conv_buf;
5725
5726 if (ip->bw_first)
5727 {
5728 size_t save_len = tolen;
5729
5730 /* output the initial shift state sequence */
5731 (void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen);
5732
5733 /* There is a bug in iconv() on Linux (which appears to be
5734 * wide-spread) which sets "to" to NULL and messes up "tolen".
5735 */
5736 if (to == NULL)
5737 {
5738 to = (char *)ip->bw_conv_buf;
5739 tolen = save_len;
5740 }
5741 ip->bw_first = FALSE;
5742 }
5743
5744 /*
5745 * If iconv() has an error or there is not enough room, fail.
5746 */
5747 if ((iconv(ip->bw_iconv_fd, (void *)&from, &fromlen, &to, &tolen)
5748 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
5749 || fromlen > CONV_RESTLEN)
5750 {
5751 ip->bw_conv_error = TRUE;
5752 return FAIL;
5753 }
5754
5755 /* copy remainder to ip->bw_rest[] to be used for the next call. */
5756 if (fromlen > 0)
5757 mch_memmove(ip->bw_rest, (void *)from, fromlen);
5758 ip->bw_restlen = (int)fromlen;
5759
5760 buf = ip->bw_conv_buf;
5761 len = (int)((char_u *)to - ip->bw_conv_buf);
5762 }
5763# endif
5764 }
5765#endif /* FEAT_MBYTE */
5766
Bram Moolenaare6bf6552017-06-27 22:11:51 +02005767 if (ip->bw_fd < 0)
5768 /* Only checking conversion, which is OK if we get here. */
5769 return OK;
5770
Bram Moolenaar071d4272004-06-13 20:20:40 +00005771#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02005772 if (flags & FIO_ENCRYPTED)
5773 {
5774 /* Encrypt the data. Do it in-place if possible, otherwise use an
5775 * allocated buffer. */
5776 if (crypt_works_inplace(ip->bw_buffer->b_cryptstate))
5777 {
5778 crypt_encode_inplace(ip->bw_buffer->b_cryptstate, buf, len);
5779 }
5780 else
5781 {
5782 char_u *outbuf;
5783
5784 len = crypt_encode_alloc(curbuf->b_cryptstate, buf, len, &outbuf);
5785 if (len == 0)
5786 return OK; /* Crypt layer is buffering, will flush later. */
5787 wlen = write_eintr(ip->bw_fd, outbuf, len);
5788 vim_free(outbuf);
5789 return (wlen < len) ? FAIL : OK;
5790 }
5791 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005792#endif
5793
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005794 wlen = write_eintr(ip->bw_fd, buf, len);
5795 return (wlen < len) ? FAIL : OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005796}
5797
5798#ifdef FEAT_MBYTE
5799/*
5800 * Convert a Unicode character to bytes.
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005801 * Return TRUE for an error, FALSE when it's OK.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005802 */
5803 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005804ucs2bytes(
5805 unsigned c, /* in: character */
5806 char_u **pp, /* in/out: pointer to result */
5807 int flags) /* FIO_ flags */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005808{
5809 char_u *p = *pp;
5810 int error = FALSE;
5811 int cc;
5812
5813
5814 if (flags & FIO_UCS4)
5815 {
5816 if (flags & FIO_ENDIAN_L)
5817 {
5818 *p++ = c;
5819 *p++ = (c >> 8);
5820 *p++ = (c >> 16);
5821 *p++ = (c >> 24);
5822 }
5823 else
5824 {
5825 *p++ = (c >> 24);
5826 *p++ = (c >> 16);
5827 *p++ = (c >> 8);
5828 *p++ = c;
5829 }
5830 }
5831 else if (flags & (FIO_UCS2 | FIO_UTF16))
5832 {
5833 if (c >= 0x10000)
5834 {
5835 if (flags & FIO_UTF16)
5836 {
5837 /* Make two words, ten bits of the character in each. First
5838 * word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff */
5839 c -= 0x10000;
5840 if (c >= 0x100000)
5841 error = TRUE;
5842 cc = ((c >> 10) & 0x3ff) + 0xd800;
5843 if (flags & FIO_ENDIAN_L)
5844 {
5845 *p++ = cc;
5846 *p++ = ((unsigned)cc >> 8);
5847 }
5848 else
5849 {
5850 *p++ = ((unsigned)cc >> 8);
5851 *p++ = cc;
5852 }
5853 c = (c & 0x3ff) + 0xdc00;
5854 }
5855 else
5856 error = TRUE;
5857 }
5858 if (flags & FIO_ENDIAN_L)
5859 {
5860 *p++ = c;
5861 *p++ = (c >> 8);
5862 }
5863 else
5864 {
5865 *p++ = (c >> 8);
5866 *p++ = c;
5867 }
5868 }
5869 else /* Latin1 */
5870 {
5871 if (c >= 0x100)
5872 {
5873 error = TRUE;
5874 *p++ = 0xBF;
5875 }
5876 else
5877 *p++ = c;
5878 }
5879
5880 *pp = p;
5881 return error;
5882}
5883
5884/*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005885 * Return TRUE if file encoding "fenc" requires conversion from or to
5886 * 'encoding'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005887 */
5888 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005889need_conversion(char_u *fenc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005890{
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005891 int same_encoding;
5892 int enc_flags;
5893 int fenc_flags;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005894
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005895 if (*fenc == NUL || STRCMP(p_enc, fenc) == 0)
Bram Moolenaar442b4222010-05-24 21:34:22 +02005896 {
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005897 same_encoding = TRUE;
Bram Moolenaar442b4222010-05-24 21:34:22 +02005898 fenc_flags = 0;
5899 }
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005900 else
5901 {
5902 /* Ignore difference between "ansi" and "latin1", "ucs-4" and
5903 * "ucs-4be", etc. */
5904 enc_flags = get_fio_flags(p_enc);
5905 fenc_flags = get_fio_flags(fenc);
5906 same_encoding = (enc_flags != 0 && fenc_flags == enc_flags);
5907 }
5908 if (same_encoding)
5909 {
5910 /* Specified encoding matches with 'encoding'. This requires
5911 * conversion when 'encoding' is Unicode but not UTF-8. */
5912 return enc_unicode != 0;
5913 }
5914
5915 /* Encodings differ. However, conversion is not needed when 'enc' is any
5916 * Unicode encoding and the file is UTF-8. */
5917 return !(enc_utf8 && fenc_flags == FIO_UTF8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005918}
5919
5920/*
5921 * Check "ptr" for a unicode encoding and return the FIO_ flags needed for the
5922 * internal conversion.
5923 * if "ptr" is an empty string, use 'encoding'.
5924 */
5925 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005926get_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005927{
5928 int prop;
5929
5930 if (*ptr == NUL)
5931 ptr = p_enc;
5932
5933 prop = enc_canon_props(ptr);
5934 if (prop & ENC_UNICODE)
5935 {
5936 if (prop & ENC_2BYTE)
5937 {
5938 if (prop & ENC_ENDIAN_L)
5939 return FIO_UCS2 | FIO_ENDIAN_L;
5940 return FIO_UCS2;
5941 }
5942 if (prop & ENC_4BYTE)
5943 {
5944 if (prop & ENC_ENDIAN_L)
5945 return FIO_UCS4 | FIO_ENDIAN_L;
5946 return FIO_UCS4;
5947 }
5948 if (prop & ENC_2WORD)
5949 {
5950 if (prop & ENC_ENDIAN_L)
5951 return FIO_UTF16 | FIO_ENDIAN_L;
5952 return FIO_UTF16;
5953 }
5954 return FIO_UTF8;
5955 }
5956 if (prop & ENC_LATIN1)
5957 return FIO_LATIN1;
5958 /* must be ENC_DBCS, requires iconv() */
5959 return 0;
5960}
5961
5962#ifdef WIN3264
5963/*
5964 * Check "ptr" for a MS-Windows codepage name and return the FIO_ flags needed
5965 * for the conversion MS-Windows can do for us. Also accept "utf-8".
5966 * Used for conversion between 'encoding' and 'fileencoding'.
5967 */
5968 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005969get_win_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005970{
5971 int cp;
5972
5973 /* Cannot do this when 'encoding' is not utf-8 and not a codepage. */
5974 if (!enc_utf8 && enc_codepage <= 0)
5975 return 0;
5976
5977 cp = encname2codepage(ptr);
5978 if (cp == 0)
5979 {
5980# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5981 if (STRCMP(ptr, "utf-8") == 0)
5982 cp = CP_UTF8;
5983 else
5984# endif
5985 return 0;
5986 }
5987 return FIO_PUT_CP(cp) | FIO_CODEPAGE;
5988}
5989#endif
5990
Bram Moolenaard0573012017-10-28 21:11:06 +02005991#ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00005992/*
5993 * Check "ptr" for a Carbon supported encoding and return the FIO_ flags
5994 * needed for the internal conversion to/from utf-8 or latin1.
5995 */
5996 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005997get_mac_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005998{
5999 if ((enc_utf8 || STRCMP(p_enc, "latin1") == 0)
6000 && (enc_canon_props(ptr) & ENC_MACROMAN))
6001 return FIO_MACROMAN;
6002 return 0;
6003}
6004#endif
6005
6006/*
6007 * Check for a Unicode BOM (Byte Order Mark) at the start of p[size].
6008 * "size" must be at least 2.
6009 * Return the name of the encoding and set "*lenp" to the length.
6010 * Returns NULL when no BOM found.
6011 */
6012 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006013check_for_bom(
6014 char_u *p,
6015 long size,
6016 int *lenp,
6017 int flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006018{
6019 char *name = NULL;
6020 int len = 2;
6021
6022 if (p[0] == 0xef && p[1] == 0xbb && size >= 3 && p[2] == 0xbf
Bram Moolenaaree0f5a62008-07-24 20:09:16 +00006023 && (flags == FIO_ALL || flags == FIO_UTF8 || flags == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006024 {
6025 name = "utf-8"; /* EF BB BF */
6026 len = 3;
6027 }
6028 else if (p[0] == 0xff && p[1] == 0xfe)
6029 {
6030 if (size >= 4 && p[2] == 0 && p[3] == 0
6031 && (flags == FIO_ALL || flags == (FIO_UCS4 | FIO_ENDIAN_L)))
6032 {
6033 name = "ucs-4le"; /* FF FE 00 00 */
6034 len = 4;
6035 }
Bram Moolenaar223a1892008-11-11 20:57:11 +00006036 else if (flags == (FIO_UCS2 | FIO_ENDIAN_L))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006037 name = "ucs-2le"; /* FF FE */
Bram Moolenaar223a1892008-11-11 20:57:11 +00006038 else if (flags == FIO_ALL || flags == (FIO_UTF16 | FIO_ENDIAN_L))
6039 /* utf-16le is preferred, it also works for ucs-2le text */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006040 name = "utf-16le"; /* FF FE */
6041 }
6042 else if (p[0] == 0xfe && p[1] == 0xff
6043 && (flags == FIO_ALL || flags == FIO_UCS2 || flags == FIO_UTF16))
6044 {
Bram Moolenaarffd82c52008-02-20 17:15:26 +00006045 /* Default to utf-16, it works also for ucs-2 text. */
6046 if (flags == FIO_UCS2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006047 name = "ucs-2"; /* FE FF */
Bram Moolenaarffd82c52008-02-20 17:15:26 +00006048 else
6049 name = "utf-16"; /* FE FF */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006050 }
6051 else if (size >= 4 && p[0] == 0 && p[1] == 0 && p[2] == 0xfe
6052 && p[3] == 0xff && (flags == FIO_ALL || flags == FIO_UCS4))
6053 {
6054 name = "ucs-4"; /* 00 00 FE FF */
6055 len = 4;
6056 }
6057
6058 *lenp = len;
6059 return (char_u *)name;
6060}
6061
6062/*
6063 * Generate a BOM in "buf[4]" for encoding "name".
6064 * Return the length of the BOM (zero when no BOM).
6065 */
6066 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006067make_bom(char_u *buf, char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006068{
6069 int flags;
6070 char_u *p;
6071
6072 flags = get_fio_flags(name);
6073
6074 /* Can't put a BOM in a non-Unicode file. */
6075 if (flags == FIO_LATIN1 || flags == 0)
6076 return 0;
6077
6078 if (flags == FIO_UTF8) /* UTF-8 */
6079 {
6080 buf[0] = 0xef;
6081 buf[1] = 0xbb;
6082 buf[2] = 0xbf;
6083 return 3;
6084 }
6085 p = buf;
6086 (void)ucs2bytes(0xfeff, &p, flags);
6087 return (int)(p - buf);
6088}
6089#endif
6090
6091/*
6092 * Try to find a shortname by comparing the fullname with the current
6093 * directory.
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006094 * Returns "full_path" or pointer into "full_path" if shortened.
6095 */
6096 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006097shorten_fname1(char_u *full_path)
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006098{
Bram Moolenaard9462e32011-04-11 21:35:11 +02006099 char_u *dirname;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006100 char_u *p = full_path;
6101
Bram Moolenaard9462e32011-04-11 21:35:11 +02006102 dirname = alloc(MAXPATHL);
6103 if (dirname == NULL)
6104 return full_path;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006105 if (mch_dirname(dirname, MAXPATHL) == OK)
6106 {
6107 p = shorten_fname(full_path, dirname);
6108 if (p == NULL || *p == NUL)
6109 p = full_path;
6110 }
Bram Moolenaard9462e32011-04-11 21:35:11 +02006111 vim_free(dirname);
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006112 return p;
6113}
6114
6115/*
6116 * Try to find a shortname by comparing the fullname with the current
6117 * directory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006118 * Returns NULL if not shorter name possible, pointer into "full_path"
6119 * otherwise.
6120 */
6121 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006122shorten_fname(char_u *full_path, char_u *dir_name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006123{
6124 int len;
6125 char_u *p;
6126
6127 if (full_path == NULL)
6128 return NULL;
6129 len = (int)STRLEN(dir_name);
6130 if (fnamencmp(dir_name, full_path, len) == 0)
6131 {
6132 p = full_path + len;
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006133#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006134 /*
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006135 * MSWIN: when a file is in the root directory, dir_name will end in a
Bram Moolenaar071d4272004-06-13 20:20:40 +00006136 * slash, since C: by itself does not define a specific dir. In this
6137 * case p may already be correct. <negri>
6138 */
6139 if (!((len > 2) && (*(p - 2) == ':')))
6140#endif
6141 {
6142 if (vim_ispathsep(*p))
6143 ++p;
6144#ifndef VMS /* the path separator is always part of the path */
6145 else
6146 p = NULL;
6147#endif
6148 }
6149 }
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006150#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006151 /*
6152 * When using a file in the current drive, remove the drive name:
6153 * "A:\dir\file" -> "\dir\file". This helps when moving a session file on
6154 * a floppy from "A:\dir" to "B:\dir".
6155 */
6156 else if (len > 3
6157 && TOUPPER_LOC(full_path[0]) == TOUPPER_LOC(dir_name[0])
6158 && full_path[1] == ':'
6159 && vim_ispathsep(full_path[2]))
6160 p = full_path + 2;
6161#endif
6162 else
6163 p = NULL;
6164 return p;
6165}
6166
6167/*
Bram Moolenaara796d462018-05-01 14:30:36 +02006168 * Shorten filename of a buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006169 * When "force" is TRUE: Use full path from now on for files currently being
6170 * edited, both for file name and swap file name. Try to shorten the file
6171 * names a bit, if safe to do so.
6172 * When "force" is FALSE: Only try to shorten absolute file names.
6173 * For buffers that have buftype "nofile" or "scratch": never change the file
6174 * name.
6175 */
6176 void
Bram Moolenaara796d462018-05-01 14:30:36 +02006177shorten_buf_fname(buf_T *buf, char_u *dirname, int force)
6178{
6179 char_u *p;
6180
6181 if (buf->b_fname != NULL
6182#ifdef FEAT_QUICKFIX
6183 && !bt_nofile(buf)
6184#endif
6185 && !path_with_url(buf->b_fname)
6186 && (force
6187 || buf->b_sfname == NULL
6188 || mch_isFullName(buf->b_sfname)))
6189 {
Bram Moolenaar3d6014f2018-10-11 19:27:47 +02006190 if (buf->b_sfname != buf->b_ffname)
6191 VIM_CLEAR(buf->b_sfname);
Bram Moolenaara796d462018-05-01 14:30:36 +02006192 p = shorten_fname(buf->b_ffname, dirname);
6193 if (p != NULL)
6194 {
6195 buf->b_sfname = vim_strsave(p);
6196 buf->b_fname = buf->b_sfname;
6197 }
6198 if (p == NULL || buf->b_fname == NULL)
6199 buf->b_fname = buf->b_ffname;
6200 }
6201}
6202
6203/*
6204 * Shorten filenames for all buffers.
6205 */
6206 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006207shorten_fnames(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006208{
6209 char_u dirname[MAXPATHL];
6210 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006211
6212 mch_dirname(dirname, MAXPATHL);
Bram Moolenaar29323592016-07-24 22:04:11 +02006213 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006214 {
Bram Moolenaara796d462018-05-01 14:30:36 +02006215 shorten_buf_fname(buf, dirname, force);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00006216
6217 /* Always make the swap file name a full path, a "nofile" buffer may
6218 * also have a swap file. */
6219 mf_fullname(buf->b_ml.ml_mfp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006220 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006221 status_redraw_all();
Bram Moolenaar49d7bf12006-02-17 21:45:41 +00006222 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006223}
6224
6225#if (defined(FEAT_DND) && defined(FEAT_GUI_GTK)) \
6226 || defined(FEAT_GUI_MSWIN) \
6227 || defined(FEAT_GUI_MAC) \
6228 || defined(PROTO)
6229/*
6230 * Shorten all filenames in "fnames[count]" by current directory.
6231 */
6232 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006233shorten_filenames(char_u **fnames, int count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006234{
6235 int i;
6236 char_u dirname[MAXPATHL];
6237 char_u *p;
6238
6239 if (fnames == NULL || count < 1)
6240 return;
6241 mch_dirname(dirname, sizeof(dirname));
6242 for (i = 0; i < count; ++i)
6243 {
6244 if ((p = shorten_fname(fnames[i], dirname)) != NULL)
6245 {
6246 /* shorten_fname() returns pointer in given "fnames[i]". If free
6247 * "fnames[i]" first, "p" becomes invalid. So we need to copy
6248 * "p" first then free fnames[i]. */
6249 p = vim_strsave(p);
6250 vim_free(fnames[i]);
6251 fnames[i] = p;
6252 }
6253 }
6254}
6255#endif
6256
6257/*
Bram Moolenaarb782ba42018-08-07 21:39:28 +02006258 * Add extension to file name - change path/fo.o.h to path/fo.o.h.ext or
Bram Moolenaar071d4272004-06-13 20:20:40 +00006259 * fo_o_h.ext for MSDOS or when shortname option set.
6260 *
6261 * Assumed that fname is a valid name found in the filesystem we assure that
6262 * the return value is a different name and ends in 'ext'.
6263 * "ext" MUST be at most 4 characters long if it starts with a dot, 3
6264 * characters otherwise.
6265 * Space for the returned name is allocated, must be freed later.
6266 * Returns NULL when out of memory.
6267 */
6268 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006269modname(
6270 char_u *fname,
6271 char_u *ext,
6272 int prepend_dot) /* may prepend a '.' to file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006273{
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006274 return buf_modname((curbuf->b_p_sn || curbuf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00006275 fname, ext, prepend_dot);
6276}
6277
6278 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006279buf_modname(
6280 int shortname, /* use 8.3 file name */
6281 char_u *fname,
6282 char_u *ext,
6283 int prepend_dot) /* may prepend a '.' to file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006284{
6285 char_u *retval;
6286 char_u *s;
6287 char_u *e;
6288 char_u *ptr;
6289 int fnamelen, extlen;
6290
6291 extlen = (int)STRLEN(ext);
6292
6293 /*
6294 * If there is no file name we must get the name of the current directory
6295 * (we need the full path in case :cd is used).
6296 */
6297 if (fname == NULL || *fname == NUL)
6298 {
6299 retval = alloc((unsigned)(MAXPATHL + extlen + 3));
6300 if (retval == NULL)
6301 return NULL;
6302 if (mch_dirname(retval, MAXPATHL) == FAIL ||
6303 (fnamelen = (int)STRLEN(retval)) == 0)
6304 {
6305 vim_free(retval);
6306 return NULL;
6307 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006308 if (!after_pathsep(retval, retval + fnamelen))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006309 {
6310 retval[fnamelen++] = PATHSEP;
6311 retval[fnamelen] = NUL;
6312 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006313 prepend_dot = FALSE; /* nothing to prepend a dot to */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006314 }
6315 else
6316 {
6317 fnamelen = (int)STRLEN(fname);
6318 retval = alloc((unsigned)(fnamelen + extlen + 3));
6319 if (retval == NULL)
6320 return NULL;
6321 STRCPY(retval, fname);
6322#ifdef VMS
6323 vms_remove_version(retval); /* we do not need versions here */
6324#endif
6325 }
6326
6327 /*
6328 * search backwards until we hit a '/', '\' or ':' replacing all '.'
6329 * by '_' for MSDOS or when shortname option set and ext starts with a dot.
6330 * Then truncate what is after the '/', '\' or ':' to 8 characters for
6331 * MSDOS and 26 characters for AMIGA, a lot more for UNIX.
6332 */
Bram Moolenaar91acfff2017-03-12 19:22:36 +01006333 for (ptr = retval + fnamelen; ptr > retval; MB_PTR_BACK(retval, ptr))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006334 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006335 if (*ext == '.'
Bram Moolenaare60acc12011-05-10 16:41:25 +02006336#ifdef USE_LONG_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00006337 && (!USE_LONG_FNAME || shortname)
Bram Moolenaare60acc12011-05-10 16:41:25 +02006338#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006339 && shortname
Bram Moolenaare60acc12011-05-10 16:41:25 +02006340#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006341 )
6342 if (*ptr == '.') /* replace '.' by '_' */
6343 *ptr = '_';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006344 if (vim_ispathsep(*ptr))
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006345 {
6346 ++ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006347 break;
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006348 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006349 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006350
6351 /* the file name has at most BASENAMELEN characters. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006352 if (STRLEN(ptr) > (unsigned)BASENAMELEN)
6353 ptr[BASENAMELEN] = '\0';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006354
6355 s = ptr + STRLEN(ptr);
6356
6357 /*
6358 * For 8.3 file names we may have to reduce the length.
6359 */
6360#ifdef USE_LONG_FNAME
6361 if (!USE_LONG_FNAME || shortname)
6362#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006363 if (shortname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006364#endif
6365 {
6366 /*
6367 * If there is no file name, or the file name ends in '/', and the
6368 * extension starts with '.', put a '_' before the dot, because just
6369 * ".ext" is invalid.
6370 */
6371 if (fname == NULL || *fname == NUL
6372 || vim_ispathsep(fname[STRLEN(fname) - 1]))
6373 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006374 if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006375 *s++ = '_';
6376 }
6377 /*
6378 * If the extension starts with '.', truncate the base name at 8
6379 * characters
6380 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006381 else if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006382 {
Bram Moolenaar78a15312009-05-15 19:33:18 +00006383 if ((size_t)(s - ptr) > (size_t)8)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006384 {
6385 s = ptr + 8;
6386 *s = '\0';
6387 }
6388 }
6389 /*
6390 * If the extension doesn't start with '.', and the file name
6391 * doesn't have an extension yet, append a '.'
6392 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006393 else if ((e = vim_strchr(ptr, '.')) == NULL)
6394 *s++ = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006395 /*
6396 * If the extension doesn't start with '.', and there already is an
Bram Moolenaar7263a772007-05-10 17:35:54 +00006397 * extension, it may need to be truncated
Bram Moolenaar071d4272004-06-13 20:20:40 +00006398 */
6399 else if ((int)STRLEN(e) + extlen > 4)
6400 s = e + 4 - extlen;
6401 }
Bram Moolenaare7fedb62015-12-31 19:07:19 +01006402#if defined(USE_LONG_FNAME) || defined(WIN3264)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006403 /*
6404 * If there is no file name, and the extension starts with '.', put a
6405 * '_' before the dot, because just ".ext" may be invalid if it's on a
6406 * FAT partition, and on HPFS it doesn't matter.
6407 */
6408 else if ((fname == NULL || *fname == NUL) && *ext == '.')
6409 *s++ = '_';
6410#endif
6411
6412 /*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006413 * Append the extension.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006414 * ext can start with '.' and cannot exceed 3 more characters.
6415 */
6416 STRCPY(s, ext);
6417
Bram Moolenaar071d4272004-06-13 20:20:40 +00006418 /*
6419 * Prepend the dot.
6420 */
Bram Moolenaare60acc12011-05-10 16:41:25 +02006421 if (prepend_dot && !shortname && *(e = gettail(retval)) != '.'
Bram Moolenaar071d4272004-06-13 20:20:40 +00006422#ifdef USE_LONG_FNAME
6423 && USE_LONG_FNAME
6424#endif
6425 )
6426 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006427 STRMOVE(e + 1, e);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006428 *e = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006429 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006430
6431 /*
6432 * Check that, after appending the extension, the file name is really
6433 * different.
6434 */
6435 if (fname != NULL && STRCMP(fname, retval) == 0)
6436 {
6437 /* we search for a character that can be replaced by '_' */
6438 while (--s >= ptr)
6439 {
6440 if (*s != '_')
6441 {
6442 *s = '_';
6443 break;
6444 }
6445 }
6446 if (s < ptr) /* fname was "________.<ext>", how tricky! */
6447 *ptr = 'v';
6448 }
6449 return retval;
6450}
6451
6452/*
6453 * Like fgets(), but if the file line is too long, it is truncated and the
6454 * rest of the line is thrown away. Returns TRUE for end-of-file.
Bram Moolenaar7e1652c2017-12-16 18:27:02 +01006455 * If the line is truncated then buf[size - 2] will not be NUL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006456 */
6457 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006458vim_fgets(char_u *buf, int size, FILE *fp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006459{
6460 char *eof;
6461#define FGETS_SIZE 200
6462 char tbuf[FGETS_SIZE];
6463
6464 buf[size - 2] = NUL;
6465#ifdef USE_CR
6466 eof = fgets_cr((char *)buf, size, fp);
6467#else
6468 eof = fgets((char *)buf, size, fp);
6469#endif
6470 if (buf[size - 2] != NUL && buf[size - 2] != '\n')
6471 {
6472 buf[size - 1] = NUL; /* Truncate the line */
6473
6474 /* Now throw away the rest of the line: */
6475 do
6476 {
6477 tbuf[FGETS_SIZE - 2] = NUL;
6478#ifdef USE_CR
Bram Moolenaar42335f52018-09-13 15:33:43 +02006479 vim_ignoredp = fgets_cr((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006480#else
Bram Moolenaar42335f52018-09-13 15:33:43 +02006481 vim_ignoredp = fgets((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006482#endif
6483 } while (tbuf[FGETS_SIZE - 2] != NUL && tbuf[FGETS_SIZE - 2] != '\n');
6484 }
6485 return (eof == NULL);
6486}
6487
6488#if defined(USE_CR) || defined(PROTO)
6489/*
6490 * Like vim_fgets(), but accept any line terminator: CR, CR-LF or LF.
6491 * Returns TRUE for end-of-file.
6492 * Only used for the Mac, because it's much slower than vim_fgets().
6493 */
6494 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006495tag_fgets(char_u *buf, int size, FILE *fp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006496{
6497 int i = 0;
6498 int c;
6499 int eof = FALSE;
6500
6501 for (;;)
6502 {
6503 c = fgetc(fp);
6504 if (c == EOF)
6505 {
6506 eof = TRUE;
6507 break;
6508 }
6509 if (c == '\r')
6510 {
6511 /* Always store a NL for end-of-line. */
6512 if (i < size - 1)
6513 buf[i++] = '\n';
6514 c = fgetc(fp);
6515 if (c != '\n') /* Macintosh format: single CR. */
6516 ungetc(c, fp);
6517 break;
6518 }
6519 if (i < size - 1)
6520 buf[i++] = c;
6521 if (c == '\n')
6522 break;
6523 }
6524 buf[i] = NUL;
6525 return eof;
6526}
6527#endif
6528
6529/*
6530 * rename() only works if both files are on the same file system, this
6531 * function will (attempts to?) copy the file across if rename fails -- webb
6532 * Return -1 for failure, 0 for success.
6533 */
6534 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006535vim_rename(char_u *from, char_u *to)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006536{
6537 int fd_in;
6538 int fd_out;
6539 int n;
6540 char *errmsg = NULL;
6541 char *buffer;
6542#ifdef AMIGA
6543 BPTR flock;
6544#endif
Bram Moolenaar8767f522016-07-01 17:17:39 +02006545 stat_T st;
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006546 long perm;
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006547#ifdef HAVE_ACL
6548 vim_acl_T acl; /* ACL from original file */
6549#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006550 int use_tmp_file = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006551
6552 /*
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006553 * When the names are identical, there is nothing to do. When they refer
6554 * to the same file (ignoring case and slash/backslash differences) but
6555 * the file name differs we need to go through a temp file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006556 */
6557 if (fnamecmp(from, to) == 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006558 {
Bram Moolenaar71afbfe2013-03-19 16:49:16 +01006559 if (p_fic && STRCMP(gettail(from), gettail(to)) != 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006560 use_tmp_file = TRUE;
6561 else
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006562 return 0;
6563 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006564
6565 /*
6566 * Fail if the "from" file doesn't exist. Avoids that "to" is deleted.
6567 */
6568 if (mch_stat((char *)from, &st) < 0)
6569 return -1;
6570
Bram Moolenaar3576da72008-12-30 15:15:57 +00006571#ifdef UNIX
6572 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02006573 stat_T st_to;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006574
6575 /* It's possible for the source and destination to be the same file.
6576 * This happens when "from" and "to" differ in case and are on a FAT32
6577 * filesystem. In that case go through a temp file name. */
6578 if (mch_stat((char *)to, &st_to) >= 0
6579 && st.st_dev == st_to.st_dev
6580 && st.st_ino == st_to.st_ino)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006581 use_tmp_file = TRUE;
6582 }
6583#endif
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02006584#ifdef WIN3264
6585 {
6586 BY_HANDLE_FILE_INFORMATION info1, info2;
6587
6588 /* It's possible for the source and destination to be the same file.
6589 * In that case go through a temp file name. This makes rename("foo",
6590 * "./foo") a no-op (in a complicated way). */
6591 if (win32_fileinfo(from, &info1) == FILEINFO_OK
6592 && win32_fileinfo(to, &info2) == FILEINFO_OK
6593 && info1.dwVolumeSerialNumber == info2.dwVolumeSerialNumber
6594 && info1.nFileIndexHigh == info2.nFileIndexHigh
6595 && info1.nFileIndexLow == info2.nFileIndexLow)
6596 use_tmp_file = TRUE;
6597 }
6598#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006599
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006600 if (use_tmp_file)
6601 {
6602 char tempname[MAXPATHL + 1];
6603
6604 /*
6605 * Find a name that doesn't exist and is in the same directory.
6606 * Rename "from" to "tempname" and then rename "tempname" to "to".
6607 */
6608 if (STRLEN(from) >= MAXPATHL - 5)
6609 return -1;
6610 STRCPY(tempname, from);
6611 for (n = 123; n < 99999; ++n)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006612 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006613 sprintf((char *)gettail((char_u *)tempname), "%d", n);
6614 if (mch_stat(tempname, &st) < 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006615 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006616 if (mch_rename((char *)from, tempname) == 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006617 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006618 if (mch_rename(tempname, (char *)to) == 0)
6619 return 0;
6620 /* Strange, the second step failed. Try moving the
6621 * file back and return failure. */
6622 mch_rename(tempname, (char *)from);
Bram Moolenaar3576da72008-12-30 15:15:57 +00006623 return -1;
6624 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006625 /* If it fails for one temp name it will most likely fail
6626 * for any temp name, give up. */
6627 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006628 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006629 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006630 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006631 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006632
Bram Moolenaar071d4272004-06-13 20:20:40 +00006633 /*
6634 * Delete the "to" file, this is required on some systems to make the
6635 * mch_rename() work, on other systems it makes sure that we don't have
6636 * two files when the mch_rename() fails.
6637 */
6638
6639#ifdef AMIGA
6640 /*
6641 * With MSDOS-compatible filesystems (crossdos, messydos) it is possible
6642 * that the name of the "to" file is the same as the "from" file, even
Bram Moolenaar7263a772007-05-10 17:35:54 +00006643 * though the names are different. To avoid the chance of accidentally
Bram Moolenaar071d4272004-06-13 20:20:40 +00006644 * deleting the "from" file (horror!) we lock it during the remove.
6645 *
6646 * When used for making a backup before writing the file: This should not
6647 * happen with ":w", because startscript() should detect this problem and
6648 * set buf->b_shortname, causing modname() to return a correct ".bak" file
6649 * name. This problem does exist with ":w filename", but then the
6650 * original file will be somewhere else so the backup isn't really
6651 * important. If autoscripting is off the rename may fail.
6652 */
6653 flock = Lock((UBYTE *)from, (long)ACCESS_READ);
6654#endif
6655 mch_remove(to);
6656#ifdef AMIGA
6657 if (flock)
6658 UnLock(flock);
6659#endif
6660
6661 /*
6662 * First try a normal rename, return if it works.
6663 */
6664 if (mch_rename((char *)from, (char *)to) == 0)
6665 return 0;
6666
6667 /*
6668 * Rename() failed, try copying the file.
6669 */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006670 perm = mch_getperm(from);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006671#ifdef HAVE_ACL
6672 /* For systems that support ACL: get the ACL from the original file. */
6673 acl = mch_get_acl(from);
6674#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006675 fd_in = mch_open((char *)from, O_RDONLY|O_EXTRA, 0);
6676 if (fd_in == -1)
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006677 {
6678#ifdef HAVE_ACL
6679 mch_free_acl(acl);
6680#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006681 return -1;
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006682 }
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006683
6684 /* Create the new file with same permissions as the original. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00006685 fd_out = mch_open((char *)to,
6686 O_CREAT|O_EXCL|O_WRONLY|O_EXTRA|O_NOFOLLOW, (int)perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006687 if (fd_out == -1)
6688 {
6689 close(fd_in);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006690#ifdef HAVE_ACL
6691 mch_free_acl(acl);
6692#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006693 return -1;
6694 }
6695
6696 buffer = (char *)alloc(BUFSIZE);
6697 if (buffer == NULL)
6698 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006699 close(fd_out);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006700 close(fd_in);
6701#ifdef HAVE_ACL
6702 mch_free_acl(acl);
6703#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006704 return -1;
6705 }
6706
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01006707 while ((n = read_eintr(fd_in, buffer, BUFSIZE)) > 0)
6708 if (write_eintr(fd_out, buffer, n) != n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006709 {
6710 errmsg = _("E208: Error writing to \"%s\"");
6711 break;
6712 }
6713
6714 vim_free(buffer);
6715 close(fd_in);
6716 if (close(fd_out) < 0)
6717 errmsg = _("E209: Error closing \"%s\"");
6718 if (n < 0)
6719 {
6720 errmsg = _("E210: Error reading \"%s\"");
6721 to = from;
6722 }
Bram Moolenaar7263a772007-05-10 17:35:54 +00006723#ifndef UNIX /* for Unix mch_open() already set the permission */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006724 mch_setperm(to, perm);
Bram Moolenaarc6039d82005-12-02 00:44:04 +00006725#endif
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006726#ifdef HAVE_ACL
6727 mch_set_acl(to, acl);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006728 mch_free_acl(acl);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006729#endif
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02006730#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaare8747442013-11-12 18:09:29 +01006731 mch_copy_sec(from, to);
Bram Moolenaar0671de32013-11-12 05:12:03 +01006732#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006733 if (errmsg != NULL)
6734 {
6735 EMSG2(errmsg, to);
6736 return -1;
6737 }
6738 mch_remove(from);
6739 return 0;
6740}
6741
6742static int already_warned = FALSE;
6743
6744/*
6745 * Check if any not hidden buffer has been changed.
6746 * Postpone the check if there are characters in the stuff buffer, a global
6747 * command is being executed, a mapping is being executed or an autocommand is
6748 * busy.
6749 * Returns TRUE if some message was written (screen should be redrawn and
6750 * cursor positioned).
6751 */
6752 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006753check_timestamps(
6754 int focus) /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006755{
6756 buf_T *buf;
6757 int didit = 0;
6758 int n;
6759
6760 /* Don't check timestamps while system() or another low-level function may
6761 * cause us to lose and gain focus. */
6762 if (no_check_timestamps > 0)
6763 return FALSE;
6764
6765 /* Avoid doing a check twice. The OK/Reload dialog can cause a focus
6766 * event and we would keep on checking if the file is steadily growing.
6767 * Do check again after typing something. */
6768 if (focus && did_check_timestamps)
6769 {
6770 need_check_timestamps = TRUE;
6771 return FALSE;
6772 }
6773
6774 if (!stuff_empty() || global_busy || !typebuf_typed()
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006775 || autocmd_busy || curbuf_lock > 0 || allbuf_lock > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006776 need_check_timestamps = TRUE; /* check later */
6777 else
6778 {
6779 ++no_wait_return;
6780 did_check_timestamps = TRUE;
6781 already_warned = FALSE;
Bram Moolenaar29323592016-07-24 22:04:11 +02006782 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006783 {
6784 /* Only check buffers in a window. */
6785 if (buf->b_nwindows > 0)
6786 {
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006787 bufref_T bufref;
6788
6789 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006790 n = buf_check_timestamp(buf, focus);
6791 if (didit < n)
6792 didit = n;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006793 if (n > 0 && !bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006794 {
6795 /* Autocommands have removed the buffer, start at the
6796 * first one again. */
6797 buf = firstbuf;
6798 continue;
6799 }
6800 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006801 }
6802 --no_wait_return;
6803 need_check_timestamps = FALSE;
6804 if (need_wait_return && didit == 2)
6805 {
6806 /* make sure msg isn't overwritten */
6807 msg_puts((char_u *)"\n");
6808 out_flush();
6809 }
6810 }
6811 return didit;
6812}
6813
6814/*
6815 * Move all the lines from buffer "frombuf" to buffer "tobuf".
6816 * Return OK or FAIL. When FAIL "tobuf" is incomplete and/or "frombuf" is not
6817 * empty.
6818 */
6819 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006820move_lines(buf_T *frombuf, buf_T *tobuf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006821{
6822 buf_T *tbuf = curbuf;
6823 int retval = OK;
6824 linenr_T lnum;
6825 char_u *p;
6826
6827 /* Copy the lines in "frombuf" to "tobuf". */
6828 curbuf = tobuf;
6829 for (lnum = 1; lnum <= frombuf->b_ml.ml_line_count; ++lnum)
6830 {
6831 p = vim_strsave(ml_get_buf(frombuf, lnum, FALSE));
6832 if (p == NULL || ml_append(lnum - 1, p, 0, FALSE) == FAIL)
6833 {
6834 vim_free(p);
6835 retval = FAIL;
6836 break;
6837 }
6838 vim_free(p);
6839 }
6840
6841 /* Delete all the lines in "frombuf". */
6842 if (retval != FAIL)
6843 {
6844 curbuf = frombuf;
Bram Moolenaar9460b9d2007-01-09 14:37:01 +00006845 for (lnum = curbuf->b_ml.ml_line_count; lnum > 0; --lnum)
6846 if (ml_delete(lnum, FALSE) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006847 {
6848 /* Oops! We could try putting back the saved lines, but that
6849 * might fail again... */
6850 retval = FAIL;
6851 break;
6852 }
6853 }
6854
6855 curbuf = tbuf;
6856 return retval;
6857}
6858
6859/*
6860 * Check if buffer "buf" has been changed.
6861 * Also check if the file for a new buffer unexpectedly appeared.
6862 * return 1 if a changed buffer was found.
6863 * return 2 if a message has been displayed.
6864 * return 0 otherwise.
6865 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006866 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006867buf_check_timestamp(
6868 buf_T *buf,
6869 int focus UNUSED) /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006870{
Bram Moolenaar8767f522016-07-01 17:17:39 +02006871 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006872 int stat_res;
6873 int retval = 0;
6874 char_u *path;
6875 char_u *tbuf;
6876 char *mesg = NULL;
Bram Moolenaar44ecf652005-03-07 23:09:59 +00006877 char *mesg2 = "";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006878 int helpmesg = FALSE;
6879 int reload = FALSE;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006880 char *reason;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006881#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6882 int can_reload = FALSE;
6883#endif
Bram Moolenaar8767f522016-07-01 17:17:39 +02006884 off_T orig_size = buf->b_orig_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006885 int orig_mode = buf->b_orig_mode;
6886#ifdef FEAT_GUI
6887 int save_mouse_correct = need_mouse_correct;
6888#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006889 static int busy = FALSE;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006890 int n;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006891#ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006892 char_u *s;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006893#endif
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006894 bufref_T bufref;
6895
6896 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006897
6898 /* If there is no file name, the buffer is not loaded, 'buftype' is
6899 * set, we are in the middle of a save or being called recursively: ignore
6900 * this buffer. */
6901 if (buf->b_ffname == NULL
6902 || buf->b_ml.ml_mfp == NULL
Bram Moolenaar91335e52018-08-01 17:53:12 +02006903 || !bt_normal(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006904 || buf->b_saving
Bram Moolenaar071d4272004-06-13 20:20:40 +00006905 || busy
Bram Moolenaar009b2592004-10-24 19:18:58 +00006906#ifdef FEAT_NETBEANS_INTG
6907 || isNetbeansBuffer(buf)
6908#endif
Bram Moolenaar8cad9302017-08-12 14:32:32 +02006909#ifdef FEAT_TERMINAL
6910 || buf->b_term != NULL
6911#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006912 )
6913 return 0;
6914
6915 if ( !(buf->b_flags & BF_NOTEDITED)
6916 && buf->b_mtime != 0
6917 && ((stat_res = mch_stat((char *)buf->b_ffname, &st)) < 0
6918 || time_differs((long)st.st_mtime, buf->b_mtime)
Bram Moolenaara7611f62014-05-02 15:46:14 +02006919 || st.st_size != buf->b_orig_size
Bram Moolenaar071d4272004-06-13 20:20:40 +00006920#ifdef HAVE_ST_MODE
6921 || (int)st.st_mode != buf->b_orig_mode
6922#else
6923 || mch_getperm(buf->b_ffname) != buf->b_orig_mode
6924#endif
6925 ))
6926 {
6927 retval = 1;
6928
Bram Moolenaar386bc822018-07-07 18:34:12 +02006929 // set b_mtime to stop further warnings (e.g., when executing
6930 // FileChangedShell autocmd)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006931 if (stat_res < 0)
6932 {
Bram Moolenaar386bc822018-07-07 18:34:12 +02006933 // When 'autoread' is set we'll check the file again to see if it
6934 // re-appears.
6935 buf->b_mtime = buf->b_p_ar;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006936 buf->b_orig_size = 0;
6937 buf->b_orig_mode = 0;
6938 }
6939 else
6940 buf_store_time(buf, &st, buf->b_ffname);
6941
6942 /* Don't do anything for a directory. Might contain the file
6943 * explorer. */
6944 if (mch_isdir(buf->b_fname))
6945 ;
6946
6947 /*
6948 * If 'autoread' is set, the buffer has no changes and the file still
6949 * exists, reload the buffer. Use the buffer-local option value if it
6950 * was set, the global option value otherwise.
6951 */
6952 else if ((buf->b_p_ar >= 0 ? buf->b_p_ar : p_ar)
6953 && !bufIsChanged(buf) && stat_res >= 0)
6954 reload = TRUE;
6955 else
6956 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006957 if (stat_res < 0)
6958 reason = "deleted";
6959 else if (bufIsChanged(buf))
6960 reason = "conflict";
6961 else if (orig_size != buf->b_orig_size || buf_contents_changed(buf))
6962 reason = "changed";
6963 else if (orig_mode != buf->b_orig_mode)
6964 reason = "mode";
6965 else
6966 reason = "time";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006967
6968 /*
6969 * Only give the warning if there are no FileChangedShell
6970 * autocommands.
6971 * Avoid being called recursively by setting "busy".
6972 */
6973 busy = TRUE;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006974#ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006975 set_vim_var_string(VV_FCS_REASON, (char_u *)reason, -1);
6976 set_vim_var_string(VV_FCS_CHOICE, (char_u *)"", -1);
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006977#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006978 ++allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006979 n = apply_autocmds(EVENT_FILECHANGEDSHELL,
6980 buf->b_fname, buf->b_fname, FALSE, buf);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006981 --allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006982 busy = FALSE;
6983 if (n)
6984 {
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006985 if (!bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006986 EMSG(_("E246: FileChangedShell autocommand deleted buffer"));
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006987#ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006988 s = get_vim_var_str(VV_FCS_CHOICE);
6989 if (STRCMP(s, "reload") == 0 && *reason != 'd')
6990 reload = TRUE;
6991 else if (STRCMP(s, "ask") == 0)
6992 n = FALSE;
6993 else
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006994#endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006995 return 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006996 }
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006997 if (!n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006998 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006999 if (*reason == 'd')
7000 mesg = _("E211: File \"%s\" no longer available");
Bram Moolenaar071d4272004-06-13 20:20:40 +00007001 else
7002 {
7003 helpmesg = TRUE;
7004#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
7005 can_reload = TRUE;
7006#endif
7007 /*
7008 * Check if the file contents really changed to avoid
7009 * giving a warning when only the timestamp was set (e.g.,
7010 * checked out of CVS). Always warn when the buffer was
7011 * changed.
7012 */
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007013 if (reason[2] == 'n')
7014 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007015 mesg = _("W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007016 mesg2 = _("See \":help W12\" for more info.");
7017 }
7018 else if (reason[1] == 'h')
7019 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007020 mesg = _("W11: Warning: File \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007021 mesg2 = _("See \":help W11\" for more info.");
7022 }
7023 else if (*reason == 'm')
7024 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007025 mesg = _("W16: Warning: Mode of file \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007026 mesg2 = _("See \":help W16\" for more info.");
7027 }
Bram Moolenaar85388b52009-06-24 09:58:32 +00007028 else
7029 /* Only timestamp changed, store it to avoid a warning
7030 * in check_mtime() later. */
7031 buf->b_mtime_read = buf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007032 }
7033 }
7034 }
7035
7036 }
7037 else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W)
7038 && vim_fexists(buf->b_ffname))
7039 {
7040 retval = 1;
7041 mesg = _("W13: Warning: File \"%s\" has been created after editing started");
7042 buf->b_flags |= BF_NEW_W;
7043#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
7044 can_reload = TRUE;
7045#endif
7046 }
7047
7048 if (mesg != NULL)
7049 {
7050 path = home_replace_save(buf, buf->b_fname);
7051 if (path != NULL)
7052 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007053 if (!helpmesg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007054 mesg2 = "";
7055 tbuf = alloc((unsigned)(STRLEN(path) + STRLEN(mesg)
7056 + STRLEN(mesg2) + 2));
7057 sprintf((char *)tbuf, mesg, path);
Bram Moolenaar496c5262009-03-18 14:42:00 +00007058#ifdef FEAT_EVAL
7059 /* Set warningmsg here, before the unimportant and output-specific
7060 * mesg2 has been appended. */
7061 set_vim_var_string(VV_WARNINGMSG, tbuf, -1);
7062#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007063#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
7064 if (can_reload)
7065 {
7066 if (*mesg2 != NUL)
7067 {
7068 STRCAT(tbuf, "\n");
7069 STRCAT(tbuf, mesg2);
7070 }
7071 if (do_dialog(VIM_WARNING, (char_u *)_("Warning"), tbuf,
Bram Moolenaard2c340a2011-01-17 20:08:11 +01007072 (char_u *)_("&OK\n&Load File"), 1, NULL, TRUE) == 2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007073 reload = TRUE;
7074 }
7075 else
7076#endif
7077 if (State > NORMAL_BUSY || (State & CMDLINE) || already_warned)
7078 {
7079 if (*mesg2 != NUL)
7080 {
7081 STRCAT(tbuf, "; ");
7082 STRCAT(tbuf, mesg2);
7083 }
7084 EMSG(tbuf);
7085 retval = 2;
7086 }
7087 else
7088 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007089 if (!autocmd_busy)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007090 {
7091 msg_start();
Bram Moolenaar8820b482017-03-16 17:23:31 +01007092 msg_puts_attr(tbuf, HL_ATTR(HLF_E) + MSG_HIST);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007093 if (*mesg2 != NUL)
7094 msg_puts_attr((char_u *)mesg2,
Bram Moolenaar8820b482017-03-16 17:23:31 +01007095 HL_ATTR(HLF_W) + MSG_HIST);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007096 msg_clr_eos();
7097 (void)msg_end();
7098 if (emsg_silent == 0)
7099 {
7100 out_flush();
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01007101#ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00007102 if (!focus)
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01007103#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007104 /* give the user some time to think about it */
7105 ui_delay(1000L, TRUE);
7106
7107 /* don't redraw and erase the message */
7108 redraw_cmdline = FALSE;
7109 }
7110 }
7111 already_warned = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007112 }
7113
7114 vim_free(path);
7115 vim_free(tbuf);
7116 }
7117 }
7118
7119 if (reload)
Bram Moolenaar465748e2012-08-29 18:50:54 +02007120 {
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007121 /* Reload the buffer. */
Bram Moolenaar316059c2006-01-14 21:18:42 +00007122 buf_reload(buf, orig_mode);
Bram Moolenaar465748e2012-08-29 18:50:54 +02007123#ifdef FEAT_PERSISTENT_UNDO
7124 if (buf->b_p_udf && buf->b_ffname != NULL)
7125 {
7126 char_u hash[UNDO_HASH_SIZE];
7127 buf_T *save_curbuf = curbuf;
7128
7129 /* Any existing undo file is unusable, write it now. */
7130 curbuf = buf;
7131 u_compute_hash(hash);
7132 u_write_undo(NULL, FALSE, buf, hash);
7133 curbuf = save_curbuf;
7134 }
7135#endif
7136 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007137
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00007138 /* Trigger FileChangedShell when the file was changed in any way. */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007139 if (bufref_valid(&bufref) && retval != 0)
Bram Moolenaar56718732006-03-15 22:53:57 +00007140 (void)apply_autocmds(EVENT_FILECHANGEDSHELLPOST,
7141 buf->b_fname, buf->b_fname, FALSE, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007142#ifdef FEAT_GUI
7143 /* restore this in case an autocommand has set it; it would break
7144 * 'mousefocus' */
7145 need_mouse_correct = save_mouse_correct;
7146#endif
7147
7148 return retval;
7149}
7150
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007151/*
7152 * Reload a buffer that is already loaded.
7153 * Used when the file was changed outside of Vim.
Bram Moolenaar316059c2006-01-14 21:18:42 +00007154 * "orig_mode" is buf->b_orig_mode before the need for reloading was detected.
7155 * buf->b_orig_mode may have been reset already.
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007156 */
7157 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007158buf_reload(buf_T *buf, int orig_mode)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007159{
7160 exarg_T ea;
7161 pos_T old_cursor;
7162 linenr_T old_topline;
7163 int old_ro = buf->b_p_ro;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007164 buf_T *savebuf;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007165 bufref_T bufref;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007166 int saved = OK;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007167 aco_save_T aco;
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007168 int flags = READ_NEW;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007169
7170 /* set curwin/curbuf for "buf" and save some things */
7171 aucmd_prepbuf(&aco, buf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007172
7173 /* We only want to read the text from the file, not reset the syntax
7174 * highlighting, clear marks, diff status, etc. Force the fileformat
7175 * and encoding to be the same. */
7176 if (prep_exarg(&ea, buf) == OK)
7177 {
7178 old_cursor = curwin->w_cursor;
7179 old_topline = curwin->w_topline;
7180
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007181 if (p_ur < 0 || curbuf->b_ml.ml_line_count <= p_ur)
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007182 {
7183 /* Save all the text, so that the reload can be undone.
7184 * Sync first so that this is a separate undo-able action. */
7185 u_sync(FALSE);
7186 saved = u_savecommon(0, curbuf->b_ml.ml_line_count + 1, 0, TRUE);
7187 flags |= READ_KEEP_UNDO;
7188 }
7189
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007190 /*
7191 * To behave like when a new file is edited (matters for
7192 * BufReadPost autocommands) we first need to delete the current
7193 * buffer contents. But if reading the file fails we should keep
7194 * the old contents. Can't use memory only, the file might be
7195 * too big. Use a hidden buffer to move the buffer contents to.
7196 */
Bram Moolenaarb5aedf32017-03-12 18:23:53 +01007197 if (BUFEMPTY() || saved == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007198 savebuf = NULL;
7199 else
7200 {
7201 /* Allocate a buffer without putting it in the buffer list. */
7202 savebuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007203 set_bufref(&bufref, savebuf);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007204 if (savebuf != NULL && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007205 {
7206 /* Open the memline. */
7207 curbuf = savebuf;
7208 curwin->w_buffer = savebuf;
Bram Moolenaar4770d092006-01-12 23:22:24 +00007209 saved = ml_open(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007210 curbuf = buf;
7211 curwin->w_buffer = buf;
7212 }
Bram Moolenaar8424a622006-04-19 21:23:36 +00007213 if (savebuf == NULL || saved == FAIL || buf != curbuf
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007214 || move_lines(buf, savebuf) == FAIL)
7215 {
7216 EMSG2(_("E462: Could not prepare for reloading \"%s\""),
7217 buf->b_fname);
7218 saved = FAIL;
7219 }
7220 }
7221
7222 if (saved == OK)
7223 {
7224 curbuf->b_flags |= BF_CHECK_RO; /* check for RO again */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007225 keep_filetype = TRUE; /* don't detect 'filetype' */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007226 if (readfile(buf->b_ffname, buf->b_fname, (linenr_T)0,
7227 (linenr_T)0,
Bram Moolenaare13b9af2017-01-13 22:01:02 +01007228 (linenr_T)MAXLNUM, &ea, flags) != OK)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007229 {
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01007230#if defined(FEAT_EVAL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007231 if (!aborting())
7232#endif
7233 EMSG2(_("E321: Could not reload \"%s\""), buf->b_fname);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007234 if (savebuf != NULL && bufref_valid(&bufref) && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007235 {
7236 /* Put the text back from the save buffer. First
7237 * delete any lines that readfile() added. */
Bram Moolenaarb5aedf32017-03-12 18:23:53 +01007238 while (!BUFEMPTY())
Bram Moolenaar8424a622006-04-19 21:23:36 +00007239 if (ml_delete(buf->b_ml.ml_line_count, FALSE) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007240 break;
7241 (void)move_lines(savebuf, buf);
7242 }
7243 }
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007244 else if (buf == curbuf) /* "buf" still valid */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007245 {
7246 /* Mark the buffer as unmodified and free undo info. */
7247 unchanged(buf, TRUE);
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007248 if ((flags & READ_KEEP_UNDO) == 0)
7249 {
7250 u_blockfree(buf);
7251 u_clearall(buf);
7252 }
7253 else
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007254 {
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007255 /* Mark all undo states as changed. */
7256 u_unchanged(curbuf);
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007257 }
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007258 }
7259 }
7260 vim_free(ea.cmd);
7261
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007262 if (savebuf != NULL && bufref_valid(&bufref))
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007263 wipe_buffer(savebuf, FALSE);
7264
7265#ifdef FEAT_DIFF
7266 /* Invalidate diff info if necessary. */
Bram Moolenaar8424a622006-04-19 21:23:36 +00007267 diff_invalidate(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007268#endif
7269
7270 /* Restore the topline and cursor position and check it (lines may
7271 * have been removed). */
7272 if (old_topline > curbuf->b_ml.ml_line_count)
7273 curwin->w_topline = curbuf->b_ml.ml_line_count;
7274 else
7275 curwin->w_topline = old_topline;
7276 curwin->w_cursor = old_cursor;
7277 check_cursor();
7278 update_topline();
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007279 keep_filetype = FALSE;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007280#ifdef FEAT_FOLDING
7281 {
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007282 win_T *wp;
7283 tabpage_T *tp;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007284
7285 /* Update folds unless they are defined manually. */
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007286 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007287 if (wp->w_buffer == curwin->w_buffer
7288 && !foldmethodIsManual(wp))
7289 foldUpdateAll(wp);
7290 }
7291#endif
7292 /* If the mode didn't change and 'readonly' was set, keep the old
7293 * value; the user probably used the ":view" command. But don't
7294 * reset it, might have had a read error. */
7295 if (orig_mode == curbuf->b_orig_mode)
7296 curbuf->b_p_ro |= old_ro;
Bram Moolenaar52f85b72013-01-30 14:13:56 +01007297
7298 /* Modelines must override settings done by autocommands. */
7299 do_modelines(0);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007300 }
7301
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007302 /* restore curwin/curbuf and a few other things */
7303 aucmd_restbuf(&aco);
7304 /* Careful: autocommands may have made "buf" invalid! */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007305}
7306
Bram Moolenaar071d4272004-06-13 20:20:40 +00007307 void
Bram Moolenaar8767f522016-07-01 17:17:39 +02007308buf_store_time(buf_T *buf, stat_T *st, char_u *fname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007309{
7310 buf->b_mtime = (long)st->st_mtime;
Bram Moolenaar914703b2010-05-31 21:59:46 +02007311 buf->b_orig_size = st->st_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007312#ifdef HAVE_ST_MODE
7313 buf->b_orig_mode = (int)st->st_mode;
7314#else
7315 buf->b_orig_mode = mch_getperm(fname);
7316#endif
7317}
7318
7319/*
7320 * Adjust the line with missing eol, used for the next write.
7321 * Used for do_filter(), when the input lines for the filter are deleted.
7322 */
7323 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007324write_lnum_adjust(linenr_T offset)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007325{
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01007326 if (curbuf->b_no_eol_lnum != 0) /* only if there is a missing eol */
7327 curbuf->b_no_eol_lnum += offset;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007328}
7329
Bram Moolenaarda440d22016-01-16 21:27:23 +01007330#if defined(TEMPDIRNAMES) || defined(FEAT_EVAL) || defined(PROTO)
7331/*
7332 * Delete "name" and everything in it, recursively.
7333 * return 0 for succes, -1 if some file was not deleted.
7334 */
7335 int
7336delete_recursive(char_u *name)
7337{
7338 int result = 0;
7339 char_u **files;
7340 int file_count;
7341 int i;
7342 char_u *exp;
7343
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007344 /* A symbolic link to a directory itself is deleted, not the directory it
7345 * points to. */
7346 if (
Bram Moolenaar203258c2016-01-17 22:15:16 +01007347# if defined(UNIX) || defined(WIN32)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007348 mch_isrealdir(name)
Bram Moolenaar203258c2016-01-17 22:15:16 +01007349# else
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007350 mch_isdir(name)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007351# endif
7352 )
Bram Moolenaarda440d22016-01-16 21:27:23 +01007353 {
7354 vim_snprintf((char *)NameBuff, MAXPATHL, "%s/*", name);
7355 exp = vim_strsave(NameBuff);
7356 if (exp == NULL)
7357 return -1;
7358 if (gen_expand_wildcards(1, &exp, &file_count, &files,
Bram Moolenaar336bd622016-01-17 18:23:58 +01007359 EW_DIR|EW_FILE|EW_SILENT|EW_ALLLINKS|EW_DODOT|EW_EMPTYOK) == OK)
Bram Moolenaarda440d22016-01-16 21:27:23 +01007360 {
7361 for (i = 0; i < file_count; ++i)
7362 if (delete_recursive(files[i]) != 0)
7363 result = -1;
7364 FreeWild(file_count, files);
7365 }
7366 else
7367 result = -1;
7368 vim_free(exp);
7369 (void)mch_rmdir(name);
7370 }
7371 else
7372 result = mch_remove(name) == 0 ? 0 : -1;
7373
7374 return result;
7375}
7376#endif
7377
Bram Moolenaar071d4272004-06-13 20:20:40 +00007378#if defined(TEMPDIRNAMES) || defined(PROTO)
7379static long temp_count = 0; /* Temp filename counter. */
7380
7381/*
7382 * Delete the temp directory and all files it contains.
7383 */
7384 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007385vim_deltempdir(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007386{
Bram Moolenaar071d4272004-06-13 20:20:40 +00007387 if (vim_tempdir != NULL)
7388 {
Bram Moolenaarda440d22016-01-16 21:27:23 +01007389 /* remove the trailing path separator */
7390 gettail(vim_tempdir)[-1] = NUL;
7391 delete_recursive(vim_tempdir);
Bram Moolenaard23a8232018-02-10 18:45:26 +01007392 VIM_CLEAR(vim_tempdir);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007393 }
7394}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007395
7396/*
Bram Moolenaareaf03392009-11-17 11:08:52 +00007397 * Directory "tempdir" was created. Expand this name to a full path and put
7398 * it in "vim_tempdir". This avoids that using ":cd" would confuse us.
7399 * "tempdir" must be no longer than MAXPATHL.
7400 */
7401 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007402vim_settempdir(char_u *tempdir)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007403{
7404 char_u *buf;
7405
7406 buf = alloc((unsigned)MAXPATHL + 2);
7407 if (buf != NULL)
7408 {
7409 if (vim_FullName(tempdir, buf, MAXPATHL, FALSE) == FAIL)
7410 STRCPY(buf, tempdir);
Bram Moolenaara06ecab2016-07-16 14:47:36 +02007411 add_pathsep(buf);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007412 vim_tempdir = vim_strsave(buf);
7413 vim_free(buf);
7414 }
7415}
Bram Moolenaar4592dee2009-11-18 19:11:58 +00007416#endif
Bram Moolenaareaf03392009-11-17 11:08:52 +00007417
7418/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007419 * vim_tempname(): Return a unique name that can be used for a temp file.
7420 *
Bram Moolenaar76ae22f2016-06-13 20:00:29 +02007421 * The temp file is NOT guaranteed to be created. If "keep" is FALSE it is
7422 * guaranteed to NOT be created.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007423 *
7424 * The returned pointer is to allocated memory.
7425 * The returned pointer is NULL if no valid name was found.
7426 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007427 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007428vim_tempname(
7429 int extra_char UNUSED, /* char to use in the name instead of '?' */
7430 int keep UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007431{
7432#ifdef USE_TMPNAM
7433 char_u itmp[L_tmpnam]; /* use tmpnam() */
7434#else
7435 char_u itmp[TEMPNAMELEN];
7436#endif
7437
7438#ifdef TEMPDIRNAMES
7439 static char *(tempdirs[]) = {TEMPDIRNAMES};
7440 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007441# ifndef EEXIST
Bram Moolenaar8767f522016-07-01 17:17:39 +02007442 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007443# endif
7444
7445 /*
7446 * This will create a directory for private use by this instance of Vim.
7447 * This is done once, and the same directory is used for all temp files.
7448 * This method avoids security problems because of symlink attacks et al.
7449 * It's also a bit faster, because we only need to check for an existing
7450 * file when creating the directory and not for each temp file.
7451 */
7452 if (vim_tempdir == NULL)
7453 {
7454 /*
7455 * Try the entries in TEMPDIRNAMES to create the temp directory.
7456 */
Bram Moolenaar78a15312009-05-15 19:33:18 +00007457 for (i = 0; i < (int)(sizeof(tempdirs) / sizeof(char *)); ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007458 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007459# ifndef HAVE_MKDTEMP
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007460 size_t itmplen;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007461 long nr;
7462 long off;
7463# endif
7464
Bram Moolenaare1a61992015-12-03 21:02:27 +01007465 /* Expand $TMP, leave room for "/v1100000/999999999".
7466 * Skip the directory check if the expansion fails. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007467 expand_env((char_u *)tempdirs[i], itmp, TEMPNAMELEN - 20);
Bram Moolenaare1a61992015-12-03 21:02:27 +01007468 if (itmp[0] != '$' && mch_isdir(itmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007469 {
Bram Moolenaare1a61992015-12-03 21:02:27 +01007470 /* directory exists */
Bram Moolenaara06ecab2016-07-16 14:47:36 +02007471 add_pathsep(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007472
Bram Moolenaareaf03392009-11-17 11:08:52 +00007473# ifdef HAVE_MKDTEMP
Bram Moolenaar35d88f42016-06-04 14:52:00 +02007474 {
7475# if defined(UNIX) || defined(VMS)
7476 /* Make sure the umask doesn't remove the executable bit.
7477 * "repl" has been reported to use "177". */
7478 mode_t umask_save = umask(077);
7479# endif
7480 /* Leave room for filename */
7481 STRCAT(itmp, "vXXXXXX");
7482 if (mkdtemp((char *)itmp) != NULL)
7483 vim_settempdir(itmp);
7484# if defined(UNIX) || defined(VMS)
7485 (void)umask(umask_save);
7486# endif
7487 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007488# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007489 /* Get an arbitrary number of up to 6 digits. When it's
7490 * unlikely that it already exists it will be faster,
7491 * otherwise it doesn't matter. The use of mkdir() avoids any
7492 * security problems because of the predictable number. */
7493 nr = (mch_get_pid() + (long)time(NULL)) % 1000000L;
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007494 itmplen = STRLEN(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007495
7496 /* Try up to 10000 different values until we find a name that
7497 * doesn't exist. */
7498 for (off = 0; off < 10000L; ++off)
7499 {
7500 int r;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007501# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007502 mode_t umask_save;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007503# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007504
Bram Moolenaareaf03392009-11-17 11:08:52 +00007505 sprintf((char *)itmp + itmplen, "v%ld", nr + off);
7506# ifndef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007507 /* If mkdir() does not set errno to EEXIST, check for
7508 * existing file here. There is a race condition then,
7509 * although it's fail-safe. */
7510 if (mch_stat((char *)itmp, &st) >= 0)
7511 continue;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007512# endif
7513# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007514 /* Make sure the umask doesn't remove the executable bit.
7515 * "repl" has been reported to use "177". */
7516 umask_save = umask(077);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007517# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007518 r = vim_mkdir(itmp, 0700);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007519# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007520 (void)umask(umask_save);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007521# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007522 if (r == 0)
7523 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007524 vim_settempdir(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007525 break;
7526 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007527# ifdef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007528 /* If the mkdir() didn't fail because the file/dir exists,
7529 * we probably can't create any dir here, try another
7530 * place. */
7531 if (errno != EEXIST)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007532# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007533 break;
7534 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007535# endif /* HAVE_MKDTEMP */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007536 if (vim_tempdir != NULL)
7537 break;
7538 }
7539 }
7540 }
7541
7542 if (vim_tempdir != NULL)
7543 {
7544 /* There is no need to check if the file exists, because we own the
7545 * directory and nobody else creates a file in it. */
7546 sprintf((char *)itmp, "%s%ld", vim_tempdir, temp_count++);
7547 return vim_strsave(itmp);
7548 }
7549
7550 return NULL;
7551
7552#else /* TEMPDIRNAMES */
7553
7554# ifdef WIN3264
7555 char szTempFile[_MAX_PATH + 1];
7556 char buf4[4];
7557 char_u *retval;
7558 char_u *p;
7559
7560 STRCPY(itmp, "");
7561 if (GetTempPath(_MAX_PATH, szTempFile) == 0)
Bram Moolenaarb1891912011-02-09 14:47:03 +01007562 {
7563 szTempFile[0] = '.'; /* GetTempPath() failed, use current dir */
7564 szTempFile[1] = NUL;
7565 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007566 strcpy(buf4, "VIM");
7567 buf4[2] = extra_char; /* make it "VIa", "VIb", etc. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007568 if (GetTempFileName(szTempFile, buf4, 0, (LPSTR)itmp) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007569 return NULL;
Bram Moolenaare5c421c2015-03-31 13:33:08 +02007570 if (!keep)
7571 /* GetTempFileName() will create the file, we don't want that */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007572 (void)DeleteFile((LPSTR)itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007573
7574 /* Backslashes in a temp file name cause problems when filtering with
7575 * "sh". NOTE: This also checks 'shellcmdflag' to help those people who
7576 * didn't set 'shellslash'. */
7577 retval = vim_strsave(itmp);
7578 if (*p_shcf == '-' || p_ssl)
7579 for (p = retval; *p; ++p)
7580 if (*p == '\\')
7581 *p = '/';
7582 return retval;
7583
7584# else /* WIN3264 */
7585
7586# ifdef USE_TMPNAM
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007587 char_u *p;
7588
Bram Moolenaar071d4272004-06-13 20:20:40 +00007589 /* tmpnam() will make its own name */
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007590 p = tmpnam((char *)itmp);
7591 if (p == NULL || *p == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007592 return NULL;
7593# else
7594 char_u *p;
7595
7596# ifdef VMS_TEMPNAM
7597 /* mktemp() is not working on VMS. It seems to be
7598 * a do-nothing function. Therefore we use tempnam().
7599 */
7600 sprintf((char *)itmp, "VIM%c", extra_char);
7601 p = (char_u *)tempnam("tmp:", (char *)itmp);
7602 if (p != NULL)
7603 {
Bram Moolenaar206f0112014-03-12 16:51:55 +01007604 /* VMS will use '.LIS' if we don't explicitly specify an extension,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007605 * and VIM will then be unable to find the file later */
7606 STRCPY(itmp, p);
7607 STRCAT(itmp, ".txt");
7608 free(p);
7609 }
7610 else
7611 return NULL;
7612# else
7613 STRCPY(itmp, TEMPNAME);
7614 if ((p = vim_strchr(itmp, '?')) != NULL)
7615 *p = extra_char;
7616 if (mktemp((char *)itmp) == NULL)
7617 return NULL;
7618# endif
7619# endif
7620
7621 return vim_strsave(itmp);
7622# endif /* WIN3264 */
7623#endif /* TEMPDIRNAMES */
7624}
7625
7626#if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
7627/*
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02007628 * Convert all backslashes in fname to forward slashes in-place, unless when
7629 * it looks like a URL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007630 */
7631 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007632forward_slash(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007633{
7634 char_u *p;
7635
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02007636 if (path_with_url(fname))
7637 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007638 for (p = fname; *p != NUL; ++p)
7639# ifdef FEAT_MBYTE
7640 /* The Big5 encoding can have '\' in the trail byte. */
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00007641 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007642 ++p;
7643 else
7644# endif
7645 if (*p == '\\')
7646 *p = '/';
7647}
7648#endif
7649
7650
7651/*
7652 * Code for automatic commands.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007653 */
7654
Bram Moolenaar071d4272004-06-13 20:20:40 +00007655/*
7656 * The autocommands are stored in a list for each event.
7657 * Autocommands for the same pattern, that are consecutive, are joined
7658 * together, to avoid having to match the pattern too often.
7659 * The result is an array of Autopat lists, which point to AutoCmd lists:
7660 *
Bram Moolenaar462455e2017-11-10 21:53:11 +01007661 * last_autopat[0] -----------------------------+
7662 * V
Bram Moolenaar071d4272004-06-13 20:20:40 +00007663 * first_autopat[0] --> Autopat.next --> Autopat.next --> NULL
7664 * Autopat.cmds Autopat.cmds
7665 * | |
7666 * V V
7667 * AutoCmd.next AutoCmd.next
7668 * | |
7669 * V V
7670 * AutoCmd.next NULL
7671 * |
7672 * V
7673 * NULL
7674 *
Bram Moolenaar462455e2017-11-10 21:53:11 +01007675 * last_autopat[1] --------+
7676 * V
Bram Moolenaar071d4272004-06-13 20:20:40 +00007677 * first_autopat[1] --> Autopat.next --> NULL
7678 * Autopat.cmds
7679 * |
7680 * V
7681 * AutoCmd.next
7682 * |
7683 * V
7684 * NULL
7685 * etc.
7686 *
7687 * The order of AutoCmds is important, this is the order in which they were
7688 * defined and will have to be executed.
7689 */
7690typedef struct AutoCmd
7691{
7692 char_u *cmd; /* The command to be executed (NULL
7693 when command has been removed) */
7694 char nested; /* If autocommands nest here */
7695 char last; /* last command in list */
7696#ifdef FEAT_EVAL
Bram Moolenaarf29c1c62018-09-10 21:05:02 +02007697 sctx_T script_ctx; /* script context where defined */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007698#endif
7699 struct AutoCmd *next; /* Next AutoCmd in list */
7700} AutoCmd;
7701
7702typedef struct AutoPat
7703{
Bram Moolenaar462455e2017-11-10 21:53:11 +01007704 struct AutoPat *next; /* next AutoPat in AutoPat list; MUST
7705 * be the first entry */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007706 char_u *pat; /* pattern as typed (NULL when pattern
7707 has been removed) */
Bram Moolenaar748bf032005-02-02 23:04:36 +00007708 regprog_T *reg_prog; /* compiled regprog for pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007709 AutoCmd *cmds; /* list of commands to do */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007710 int group; /* group ID */
7711 int patlen; /* strlen() of pat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007712 int buflocal_nr; /* !=0 for buffer-local AutoPat */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007713 char allow_dirs; /* Pattern may match whole path */
7714 char last; /* last pattern for apply_autocmds() */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007715} AutoPat;
7716
7717static struct event_name
7718{
7719 char *name; /* event name */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007720 event_T event; /* event number */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007721} event_names[] =
7722{
7723 {"BufAdd", EVENT_BUFADD},
7724 {"BufCreate", EVENT_BUFADD},
7725 {"BufDelete", EVENT_BUFDELETE},
7726 {"BufEnter", EVENT_BUFENTER},
7727 {"BufFilePost", EVENT_BUFFILEPOST},
7728 {"BufFilePre", EVENT_BUFFILEPRE},
7729 {"BufHidden", EVENT_BUFHIDDEN},
7730 {"BufLeave", EVENT_BUFLEAVE},
7731 {"BufNew", EVENT_BUFNEW},
7732 {"BufNewFile", EVENT_BUFNEWFILE},
7733 {"BufRead", EVENT_BUFREADPOST},
7734 {"BufReadCmd", EVENT_BUFREADCMD},
7735 {"BufReadPost", EVENT_BUFREADPOST},
7736 {"BufReadPre", EVENT_BUFREADPRE},
7737 {"BufUnload", EVENT_BUFUNLOAD},
7738 {"BufWinEnter", EVENT_BUFWINENTER},
7739 {"BufWinLeave", EVENT_BUFWINLEAVE},
7740 {"BufWipeout", EVENT_BUFWIPEOUT},
7741 {"BufWrite", EVENT_BUFWRITEPRE},
7742 {"BufWritePost", EVENT_BUFWRITEPOST},
7743 {"BufWritePre", EVENT_BUFWRITEPRE},
7744 {"BufWriteCmd", EVENT_BUFWRITECMD},
Bram Moolenaar153b7042018-01-31 15:48:32 +01007745 {"CmdlineChanged", EVENT_CMDLINECHANGED},
Bram Moolenaarfafcf0d2017-10-19 18:35:51 +02007746 {"CmdlineEnter", EVENT_CMDLINEENTER},
7747 {"CmdlineLeave", EVENT_CMDLINELEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007748 {"CmdwinEnter", EVENT_CMDWINENTER},
7749 {"CmdwinLeave", EVENT_CMDWINLEAVE},
Bram Moolenaard5005162014-08-22 23:05:54 +02007750 {"CmdUndefined", EVENT_CMDUNDEFINED},
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007751 {"ColorScheme", EVENT_COLORSCHEME},
Bram Moolenaar60a68362018-04-30 15:40:48 +02007752 {"ColorSchemePre", EVENT_COLORSCHEMEPRE},
Bram Moolenaarcfa3cae2012-07-10 17:14:56 +02007753 {"CompleteDone", EVENT_COMPLETEDONE},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007754 {"CursorHold", EVENT_CURSORHOLD},
7755 {"CursorHoldI", EVENT_CURSORHOLDI},
7756 {"CursorMoved", EVENT_CURSORMOVED},
7757 {"CursorMovedI", EVENT_CURSORMOVEDI},
Bram Moolenaare8fa05b2018-09-16 15:48:06 +02007758 {"DiffUpdated", EVENT_DIFFUPDATED},
Bram Moolenaarb7407d32018-02-03 17:36:27 +01007759 {"DirChanged", EVENT_DIRCHANGED},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007760 {"EncodingChanged", EVENT_ENCODINGCHANGED},
Bram Moolenaar12a96de2018-03-11 14:44:18 +01007761 {"ExitPre", EVENT_EXITPRE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007762 {"FileEncoding", EVENT_ENCODINGCHANGED},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007763 {"FileAppendPost", EVENT_FILEAPPENDPOST},
7764 {"FileAppendPre", EVENT_FILEAPPENDPRE},
7765 {"FileAppendCmd", EVENT_FILEAPPENDCMD},
7766 {"FileChangedShell",EVENT_FILECHANGEDSHELL},
Bram Moolenaar56718732006-03-15 22:53:57 +00007767 {"FileChangedShellPost",EVENT_FILECHANGEDSHELLPOST},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007768 {"FileChangedRO", EVENT_FILECHANGEDRO},
7769 {"FileReadPost", EVENT_FILEREADPOST},
7770 {"FileReadPre", EVENT_FILEREADPRE},
7771 {"FileReadCmd", EVENT_FILEREADCMD},
7772 {"FileType", EVENT_FILETYPE},
7773 {"FileWritePost", EVENT_FILEWRITEPOST},
7774 {"FileWritePre", EVENT_FILEWRITEPRE},
7775 {"FileWriteCmd", EVENT_FILEWRITECMD},
7776 {"FilterReadPost", EVENT_FILTERREADPOST},
7777 {"FilterReadPre", EVENT_FILTERREADPRE},
7778 {"FilterWritePost", EVENT_FILTERWRITEPOST},
7779 {"FilterWritePre", EVENT_FILTERWRITEPRE},
7780 {"FocusGained", EVENT_FOCUSGAINED},
7781 {"FocusLost", EVENT_FOCUSLOST},
7782 {"FuncUndefined", EVENT_FUNCUNDEFINED},
7783 {"GUIEnter", EVENT_GUIENTER},
Bram Moolenaar265e5072006-08-29 16:13:22 +00007784 {"GUIFailed", EVENT_GUIFAILED},
Bram Moolenaar843ee412004-06-30 16:16:41 +00007785 {"InsertChange", EVENT_INSERTCHANGE},
7786 {"InsertEnter", EVENT_INSERTENTER},
7787 {"InsertLeave", EVENT_INSERTLEAVE},
Bram Moolenaare659c952011-05-19 17:25:41 +02007788 {"InsertCharPre", EVENT_INSERTCHARPRE},
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00007789 {"MenuPopup", EVENT_MENUPOPUP},
Bram Moolenaar53744302015-07-17 17:38:22 +02007790 {"OptionSet", EVENT_OPTIONSET},
Bram Moolenaar7c626922005-02-07 22:01:03 +00007791 {"QuickFixCmdPost", EVENT_QUICKFIXCMDPOST},
7792 {"QuickFixCmdPre", EVENT_QUICKFIXCMDPRE},
Bram Moolenaar3b53dfb2012-06-06 18:03:07 +02007793 {"QuitPre", EVENT_QUITPRE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007794 {"RemoteReply", EVENT_REMOTEREPLY},
Bram Moolenaar9372a112005-12-06 19:59:18 +00007795 {"SessionLoadPost", EVENT_SESSIONLOADPOST},
Bram Moolenaar5c4bab02006-03-10 21:37:46 +00007796 {"ShellCmdPost", EVENT_SHELLCMDPOST},
7797 {"ShellFilterPost", EVENT_SHELLFILTERPOST},
Bram Moolenaara2031822006-03-07 22:29:51 +00007798 {"SourcePre", EVENT_SOURCEPRE},
Bram Moolenaar8dd1aa52007-01-16 20:33:19 +00007799 {"SourceCmd", EVENT_SOURCECMD},
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00007800 {"SpellFileMissing",EVENT_SPELLFILEMISSING},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007801 {"StdinReadPost", EVENT_STDINREADPOST},
7802 {"StdinReadPre", EVENT_STDINREADPRE},
Bram Moolenaarb815dac2005-12-07 20:59:24 +00007803 {"SwapExists", EVENT_SWAPEXISTS},
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00007804 {"Syntax", EVENT_SYNTAX},
Bram Moolenaarc917da42016-07-19 22:31:36 +02007805 {"TabNew", EVENT_TABNEW},
Bram Moolenaar12c11d52016-07-19 23:13:03 +02007806 {"TabClosed", EVENT_TABCLOSED},
Bram Moolenaar70836c82006-02-20 21:28:49 +00007807 {"TabEnter", EVENT_TABENTER},
7808 {"TabLeave", EVENT_TABLEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007809 {"TermChanged", EVENT_TERMCHANGED},
Bram Moolenaarb852c3e2018-03-11 16:55:36 +01007810 {"TerminalOpen", EVENT_TERMINALOPEN},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007811 {"TermResponse", EVENT_TERMRESPONSE},
Bram Moolenaar186628f2013-03-19 13:33:23 +01007812 {"TextChanged", EVENT_TEXTCHANGED},
7813 {"TextChangedI", EVENT_TEXTCHANGEDI},
Bram Moolenaar5a093432018-02-10 18:15:19 +01007814 {"TextChangedP", EVENT_TEXTCHANGEDP},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007815 {"User", EVENT_USER},
7816 {"VimEnter", EVENT_VIMENTER},
7817 {"VimLeave", EVENT_VIMLEAVE},
7818 {"VimLeavePre", EVENT_VIMLEAVEPRE},
Bram Moolenaarc917da42016-07-19 22:31:36 +02007819 {"WinNew", EVENT_WINNEW},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007820 {"WinEnter", EVENT_WINENTER},
7821 {"WinLeave", EVENT_WINLEAVE},
Bram Moolenaar56718732006-03-15 22:53:57 +00007822 {"VimResized", EVENT_VIMRESIZED},
Bram Moolenaar7e1652c2017-12-16 18:27:02 +01007823 {"TextYankPost", EVENT_TEXTYANKPOST},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007824 {NULL, (event_T)0}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007825};
7826
7827static AutoPat *first_autopat[NUM_EVENTS] =
7828{
7829 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7830 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7831 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7832 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00007833 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaar53744302015-07-17 17:38:22 +02007834 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007835};
7836
Bram Moolenaar462455e2017-11-10 21:53:11 +01007837static AutoPat *last_autopat[NUM_EVENTS] =
7838{
7839 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7840 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7841 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7842 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7843 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7844 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
7845};
7846
Bram Moolenaar071d4272004-06-13 20:20:40 +00007847/*
7848 * struct used to keep status while executing autocommands for an event.
7849 */
7850typedef struct AutoPatCmd
7851{
7852 AutoPat *curpat; /* next AutoPat to examine */
7853 AutoCmd *nextcmd; /* next AutoCmd to execute */
7854 int group; /* group being used */
7855 char_u *fname; /* fname to match with */
7856 char_u *sfname; /* sfname to match with */
7857 char_u *tail; /* tail of fname */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007858 event_T event; /* current event */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007859 int arg_bufnr; /* initially equal to <abuf>, set to zero when
7860 buf is deleted */
7861 struct AutoPatCmd *next; /* chain of active apc-s for auto-invalidation*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00007862} AutoPatCmd;
7863
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007864static AutoPatCmd *active_apc_list = NULL; /* stack of active autocommands */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007865
Bram Moolenaar071d4272004-06-13 20:20:40 +00007866/*
7867 * augroups stores a list of autocmd group names.
7868 */
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007869static garray_T augroups = {0, 0, sizeof(char_u *), 10, NULL};
Bram Moolenaar071d4272004-06-13 20:20:40 +00007870#define AUGROUP_NAME(i) (((char_u **)augroups.ga_data)[i])
Bram Moolenaarb62cc362016-09-03 16:43:53 +02007871/* use get_deleted_augroup() to get this */
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02007872static char_u *deleted_augroup = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007873
7874/*
7875 * The ID of the current group. Group 0 is the default one.
7876 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007877static int current_augroup = AUGROUP_DEFAULT;
7878
7879static int au_need_clean = FALSE; /* need to delete marked patterns */
7880
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007881static char_u *event_nr2name(event_T event);
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007882static int au_get_grouparg(char_u **argp);
7883static int do_autocmd_event(event_T event, char_u *pat, int nested, char_u *cmd, int forceit, int group);
7884static int apply_autocmds_group(event_T event, char_u *fname, char_u *fname_io, int force, int group, buf_T *buf, exarg_T *eap);
7885static void auto_next_pat(AutoPatCmd *apc, int stop_at_last);
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007886static 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 +00007887
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007888
Bram Moolenaar754b5602006-02-09 23:53:20 +00007889static event_T last_event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007890static int last_group;
Bram Moolenaar78ab3312007-09-29 12:16:41 +00007891static int autocmd_blocked = 0; /* block all autocmds */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007892
Bram Moolenaarb62cc362016-09-03 16:43:53 +02007893 static char_u *
7894get_deleted_augroup(void)
7895{
7896 if (deleted_augroup == NULL)
7897 deleted_augroup = (char_u *)_("--Deleted--");
7898 return deleted_augroup;
7899}
7900
Bram Moolenaar071d4272004-06-13 20:20:40 +00007901/*
7902 * Show the autocommands for one AutoPat.
7903 */
7904 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007905show_autocmd(AutoPat *ap, event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007906{
7907 AutoCmd *ac;
7908
7909 /* Check for "got_int" (here and at various places below), which is set
7910 * when "q" has been hit for the "--more--" prompt */
7911 if (got_int)
7912 return;
7913 if (ap->pat == NULL) /* pattern has been removed */
7914 return;
7915
7916 msg_putchar('\n');
7917 if (got_int)
7918 return;
7919 if (event != last_event || ap->group != last_group)
7920 {
7921 if (ap->group != AUGROUP_DEFAULT)
7922 {
7923 if (AUGROUP_NAME(ap->group) == NULL)
Bram Moolenaar8820b482017-03-16 17:23:31 +01007924 msg_puts_attr(get_deleted_augroup(), HL_ATTR(HLF_E));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007925 else
Bram Moolenaar8820b482017-03-16 17:23:31 +01007926 msg_puts_attr(AUGROUP_NAME(ap->group), HL_ATTR(HLF_T));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007927 msg_puts((char_u *)" ");
7928 }
Bram Moolenaar8820b482017-03-16 17:23:31 +01007929 msg_puts_attr(event_nr2name(event), HL_ATTR(HLF_T));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007930 last_event = event;
7931 last_group = ap->group;
7932 msg_putchar('\n');
7933 if (got_int)
7934 return;
7935 }
7936 msg_col = 4;
7937 msg_outtrans(ap->pat);
7938
7939 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7940 {
7941 if (ac->cmd != NULL) /* skip removed commands */
7942 {
7943 if (msg_col >= 14)
7944 msg_putchar('\n');
7945 msg_col = 14;
7946 if (got_int)
7947 return;
7948 msg_outtrans(ac->cmd);
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00007949#ifdef FEAT_EVAL
7950 if (p_verbose > 0)
Bram Moolenaarf29c1c62018-09-10 21:05:02 +02007951 last_set_msg(ac->script_ctx);
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00007952#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007953 if (got_int)
7954 return;
7955 if (ac->next != NULL)
7956 {
7957 msg_putchar('\n');
7958 if (got_int)
7959 return;
7960 }
7961 }
7962 }
7963}
7964
7965/*
7966 * Mark an autocommand pattern for deletion.
7967 */
7968 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007969au_remove_pat(AutoPat *ap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007970{
Bram Moolenaard23a8232018-02-10 18:45:26 +01007971 VIM_CLEAR(ap->pat);
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007972 ap->buflocal_nr = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007973 au_need_clean = TRUE;
7974}
7975
7976/*
7977 * Mark all commands for a pattern for deletion.
7978 */
7979 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007980au_remove_cmds(AutoPat *ap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007981{
7982 AutoCmd *ac;
7983
7984 for (ac = ap->cmds; ac != NULL; ac = ac->next)
Bram Moolenaard23a8232018-02-10 18:45:26 +01007985 VIM_CLEAR(ac->cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007986 au_need_clean = TRUE;
7987}
7988
7989/*
7990 * Cleanup autocommands and patterns that have been deleted.
7991 * This is only done when not executing autocommands.
7992 */
7993 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007994au_cleanup(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007995{
7996 AutoPat *ap, **prev_ap;
7997 AutoCmd *ac, **prev_ac;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007998 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007999
8000 if (autocmd_busy || !au_need_clean)
8001 return;
8002
8003 /* loop over all events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008004 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8005 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008006 {
8007 /* loop over all autocommand patterns */
8008 prev_ap = &(first_autopat[(int)event]);
8009 for (ap = *prev_ap; ap != NULL; ap = *prev_ap)
8010 {
8011 /* loop over all commands for this pattern */
8012 prev_ac = &(ap->cmds);
8013 for (ac = *prev_ac; ac != NULL; ac = *prev_ac)
8014 {
8015 /* remove the command if the pattern is to be deleted or when
8016 * the command has been marked for deletion */
8017 if (ap->pat == NULL || ac->cmd == NULL)
8018 {
8019 *prev_ac = ac->next;
8020 vim_free(ac->cmd);
8021 vim_free(ac);
8022 }
8023 else
8024 prev_ac = &(ac->next);
8025 }
8026
8027 /* remove the pattern if it has been marked for deletion */
8028 if (ap->pat == NULL)
8029 {
Bram Moolenaar462455e2017-11-10 21:53:11 +01008030 if (ap->next == NULL)
8031 {
8032 if (prev_ap == &(first_autopat[(int)event]))
8033 last_autopat[(int)event] = NULL;
8034 else
8035 /* this depends on the "next" field being the first in
8036 * the struct */
8037 last_autopat[(int)event] = (AutoPat *)prev_ap;
8038 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008039 *prev_ap = ap->next;
Bram Moolenaar473de612013-06-08 18:19:48 +02008040 vim_regfree(ap->reg_prog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008041 vim_free(ap);
8042 }
8043 else
8044 prev_ap = &(ap->next);
8045 }
8046 }
8047
8048 au_need_clean = FALSE;
8049}
8050
8051/*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008052 * Called when buffer is freed, to remove/invalidate related buffer-local
8053 * autocmds.
8054 */
8055 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008056aubuflocal_remove(buf_T *buf)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008057{
8058 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008059 event_T event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008060 AutoPatCmd *apc;
8061
8062 /* invalidate currently executing autocommands */
8063 for (apc = active_apc_list; apc; apc = apc->next)
8064 if (buf->b_fnum == apc->arg_bufnr)
8065 apc->arg_bufnr = 0;
8066
8067 /* invalidate buflocals looping through events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008068 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8069 event = (event_T)((int)event + 1))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008070 /* loop over all autocommand patterns */
8071 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8072 if (ap->buflocal_nr == buf->b_fnum)
8073 {
8074 au_remove_pat(ap);
8075 if (p_verbose >= 6)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00008076 {
8077 verbose_enter();
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008078 smsg((char_u *)
8079 _("auto-removing autocommand: %s <buffer=%d>"),
8080 event_nr2name(event), buf->b_fnum);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00008081 verbose_leave();
8082 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008083 }
8084 au_cleanup();
8085}
8086
8087/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008088 * Add an autocmd group name.
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01008089 * Return its ID. Returns AUGROUP_ERROR (< 0) for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008090 */
8091 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008092au_new_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008093{
8094 int i;
8095
8096 i = au_find_group(name);
8097 if (i == AUGROUP_ERROR) /* the group doesn't exist yet, add it */
8098 {
8099 /* First try using a free entry. */
8100 for (i = 0; i < augroups.ga_len; ++i)
8101 if (AUGROUP_NAME(i) == NULL)
8102 break;
8103 if (i == augroups.ga_len && ga_grow(&augroups, 1) == FAIL)
8104 return AUGROUP_ERROR;
8105
8106 AUGROUP_NAME(i) = vim_strsave(name);
8107 if (AUGROUP_NAME(i) == NULL)
8108 return AUGROUP_ERROR;
8109 if (i == augroups.ga_len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008110 ++augroups.ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008111 }
8112
8113 return i;
8114}
8115
8116 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008117au_del_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008118{
8119 int i;
8120
8121 i = au_find_group(name);
8122 if (i == AUGROUP_ERROR) /* the group doesn't exist */
8123 EMSG2(_("E367: No such group: \"%s\""), name);
Bram Moolenaarde653f02016-09-03 16:59:06 +02008124 else if (i == current_augroup)
8125 EMSG(_("E936: Cannot delete the current group"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008126 else
8127 {
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008128 event_T event;
8129 AutoPat *ap;
8130 int in_use = FALSE;
8131
8132 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8133 event = (event_T)((int)event + 1))
8134 {
8135 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
Bram Moolenaar5c809082016-09-01 16:21:48 +02008136 if (ap->group == i && ap->pat != NULL)
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008137 {
8138 give_warning((char_u *)_("W19: Deleting augroup that is still in use"), TRUE);
8139 in_use = TRUE;
8140 event = NUM_EVENTS;
8141 break;
8142 }
8143 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008144 vim_free(AUGROUP_NAME(i));
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008145 if (in_use)
8146 {
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008147 AUGROUP_NAME(i) = get_deleted_augroup();
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008148 }
8149 else
8150 AUGROUP_NAME(i) = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008151 }
8152}
8153
8154/*
8155 * Find the ID of an autocmd group name.
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01008156 * Return its ID. Returns AUGROUP_ERROR (< 0) for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008157 */
8158 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008159au_find_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008160{
8161 int i;
8162
8163 for (i = 0; i < augroups.ga_len; ++i)
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008164 if (AUGROUP_NAME(i) != NULL && AUGROUP_NAME(i) != get_deleted_augroup()
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008165 && STRCMP(AUGROUP_NAME(i), name) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008166 return i;
8167 return AUGROUP_ERROR;
8168}
8169
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008170/*
8171 * Return TRUE if augroup "name" exists.
8172 */
8173 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008174au_has_group(char_u *name)
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008175{
8176 return au_find_group(name) != AUGROUP_ERROR;
8177}
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008178
Bram Moolenaar071d4272004-06-13 20:20:40 +00008179/*
8180 * ":augroup {name}".
8181 */
8182 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008183do_augroup(char_u *arg, int del_group)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008184{
8185 int i;
8186
8187 if (del_group)
8188 {
8189 if (*arg == NUL)
8190 EMSG(_(e_argreq));
8191 else
8192 au_del_group(arg);
8193 }
8194 else if (STRICMP(arg, "end") == 0) /* ":aug end": back to group 0 */
8195 current_augroup = AUGROUP_DEFAULT;
8196 else if (*arg) /* ":aug xxx": switch to group xxx */
8197 {
8198 i = au_new_group(arg);
8199 if (i != AUGROUP_ERROR)
8200 current_augroup = i;
8201 }
8202 else /* ":aug": list the group names */
8203 {
8204 msg_start();
8205 for (i = 0; i < augroups.ga_len; ++i)
8206 {
8207 if (AUGROUP_NAME(i) != NULL)
8208 {
8209 msg_puts(AUGROUP_NAME(i));
8210 msg_puts((char_u *)" ");
8211 }
8212 }
8213 msg_clr_eos();
8214 msg_end();
8215 }
8216}
8217
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008218#if defined(EXITFREE) || defined(PROTO)
8219 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008220free_all_autocmds(void)
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008221{
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008222 int i;
8223 char_u *s;
8224
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008225 for (current_augroup = -1; current_augroup < augroups.ga_len;
8226 ++current_augroup)
8227 do_autocmd((char_u *)"", TRUE);
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008228
8229 for (i = 0; i < augroups.ga_len; ++i)
8230 {
8231 s = ((char_u **)(augroups.ga_data))[i];
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008232 if (s != get_deleted_augroup())
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008233 vim_free(s);
8234 }
8235 ga_clear(&augroups);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008236}
8237#endif
8238
Bram Moolenaar071d4272004-06-13 20:20:40 +00008239/*
8240 * Return the event number for event name "start".
8241 * Return NUM_EVENTS if the event name was not found.
8242 * Return a pointer to the next event name in "end".
8243 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008244 static event_T
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008245event_name2nr(char_u *start, char_u **end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008246{
8247 char_u *p;
8248 int i;
8249 int len;
8250
Bram Moolenaare99e8442016-07-26 20:43:40 +02008251 /* the event name ends with end of line, '|', a blank or a comma */
Bram Moolenaar1c465442017-03-12 20:10:05 +01008252 for (p = start; *p && !VIM_ISWHITE(*p) && *p != ',' && *p != '|'; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008253 ;
8254 for (i = 0; event_names[i].name != NULL; ++i)
8255 {
8256 len = (int)STRLEN(event_names[i].name);
8257 if (len == p - start && STRNICMP(event_names[i].name, start, len) == 0)
8258 break;
8259 }
8260 if (*p == ',')
8261 ++p;
8262 *end = p;
8263 if (event_names[i].name == NULL)
8264 return NUM_EVENTS;
8265 return event_names[i].event;
8266}
8267
8268/*
8269 * Return the name for event "event".
8270 */
8271 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008272event_nr2name(event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008273{
8274 int i;
8275
8276 for (i = 0; event_names[i].name != NULL; ++i)
8277 if (event_names[i].event == event)
8278 return (char_u *)event_names[i].name;
8279 return (char_u *)"Unknown";
8280}
8281
8282/*
8283 * Scan over the events. "*" stands for all events.
8284 */
8285 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008286find_end_event(
8287 char_u *arg,
8288 int have_group) /* TRUE when group name was found */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008289{
8290 char_u *pat;
8291 char_u *p;
8292
8293 if (*arg == '*')
8294 {
Bram Moolenaar1c465442017-03-12 20:10:05 +01008295 if (arg[1] && !VIM_ISWHITE(arg[1]))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008296 {
8297 EMSG2(_("E215: Illegal character after *: %s"), arg);
8298 return NULL;
8299 }
8300 pat = arg + 1;
8301 }
8302 else
8303 {
Bram Moolenaar1c465442017-03-12 20:10:05 +01008304 for (pat = arg; *pat && *pat != '|' && !VIM_ISWHITE(*pat); pat = p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008305 {
8306 if ((int)event_name2nr(pat, &p) >= (int)NUM_EVENTS)
8307 {
8308 if (have_group)
8309 EMSG2(_("E216: No such event: %s"), pat);
8310 else
8311 EMSG2(_("E216: No such group or event: %s"), pat);
8312 return NULL;
8313 }
8314 }
8315 }
8316 return pat;
8317}
8318
8319/*
8320 * Return TRUE if "event" is included in 'eventignore'.
8321 */
8322 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008323event_ignored(event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008324{
8325 char_u *p = p_ei;
8326
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008327 while (*p != NUL)
8328 {
8329 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8330 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008331 if (event_name2nr(p, &p) == event)
8332 return TRUE;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008333 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008334
8335 return FALSE;
8336}
8337
8338/*
8339 * Return OK when the contents of p_ei is valid, FAIL otherwise.
8340 */
8341 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008342check_ei(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008343{
8344 char_u *p = p_ei;
8345
Bram Moolenaar071d4272004-06-13 20:20:40 +00008346 while (*p)
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008347 {
8348 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8349 {
8350 p += 3;
8351 if (*p == ',')
8352 ++p;
8353 }
8354 else if (event_name2nr(p, &p) == NUM_EVENTS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008355 return FAIL;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008356 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008357
8358 return OK;
8359}
8360
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008361# if defined(FEAT_SYN_HL) || defined(PROTO)
8362
8363/*
8364 * Add "what" to 'eventignore' to skip loading syntax highlighting for every
8365 * buffer loaded into the window. "what" must start with a comma.
8366 * Returns the old value of 'eventignore' in allocated memory.
8367 */
8368 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008369au_event_disable(char *what)
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008370{
8371 char_u *new_ei;
8372 char_u *save_ei;
8373
8374 save_ei = vim_strsave(p_ei);
8375 if (save_ei != NULL)
8376 {
Bram Moolenaara5792f52005-11-23 21:25:05 +00008377 new_ei = vim_strnsave(p_ei, (int)(STRLEN(p_ei) + STRLEN(what)));
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008378 if (new_ei != NULL)
8379 {
Bram Moolenaar8cac9fd2010-03-02 12:48:05 +01008380 if (*what == ',' && *p_ei == NUL)
8381 STRCPY(new_ei, what + 1);
8382 else
8383 STRCAT(new_ei, what);
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008384 set_string_option_direct((char_u *)"ei", -1, new_ei,
8385 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008386 vim_free(new_ei);
8387 }
8388 }
8389 return save_ei;
8390}
8391
8392 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008393au_event_restore(char_u *old_ei)
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008394{
8395 if (old_ei != NULL)
8396 {
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008397 set_string_option_direct((char_u *)"ei", -1, old_ei,
8398 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008399 vim_free(old_ei);
8400 }
8401}
8402# endif /* FEAT_SYN_HL */
8403
Bram Moolenaar071d4272004-06-13 20:20:40 +00008404/*
8405 * do_autocmd() -- implements the :autocmd command. Can be used in the
8406 * following ways:
8407 *
8408 * :autocmd <event> <pat> <cmd> Add <cmd> to the list of commands that
8409 * will be automatically executed for <event>
8410 * when editing a file matching <pat>, in
8411 * the current group.
Bram Moolenaar8c555332018-06-22 21:30:31 +02008412 * :autocmd <event> <pat> Show the autocommands associated with
Bram Moolenaar071d4272004-06-13 20:20:40 +00008413 * <event> and <pat>.
Bram Moolenaar8c555332018-06-22 21:30:31 +02008414 * :autocmd <event> Show the autocommands associated with
Bram Moolenaar071d4272004-06-13 20:20:40 +00008415 * <event>.
Bram Moolenaar8c555332018-06-22 21:30:31 +02008416 * :autocmd Show all autocommands.
8417 * :autocmd! <event> <pat> <cmd> Remove all autocommands associated with
Bram Moolenaar071d4272004-06-13 20:20:40 +00008418 * <event> and <pat>, and add the command
8419 * <cmd>, for the current group.
Bram Moolenaar8c555332018-06-22 21:30:31 +02008420 * :autocmd! <event> <pat> Remove all autocommands associated with
Bram Moolenaar071d4272004-06-13 20:20:40 +00008421 * <event> and <pat> for the current group.
Bram Moolenaar8c555332018-06-22 21:30:31 +02008422 * :autocmd! <event> Remove all autocommands associated with
Bram Moolenaar071d4272004-06-13 20:20:40 +00008423 * <event> for the current group.
Bram Moolenaar8c555332018-06-22 21:30:31 +02008424 * :autocmd! Remove ALL autocommands for the current
Bram Moolenaar071d4272004-06-13 20:20:40 +00008425 * group.
8426 *
8427 * Multiple events and patterns may be given separated by commas. Here are
8428 * some examples:
8429 * :autocmd bufread,bufenter *.c,*.h set tw=0 smartindent noic
8430 * :autocmd bufleave * set tw=79 nosmartindent ic infercase
8431 *
8432 * :autocmd * *.c show all autocommands for *.c files.
Bram Moolenaard35f9712005-12-18 22:02:33 +00008433 *
8434 * Mostly a {group} argument can optionally appear before <event>.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008435 */
8436 void
Bram Moolenaare99e8442016-07-26 20:43:40 +02008437do_autocmd(char_u *arg_in, int forceit)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008438{
Bram Moolenaare99e8442016-07-26 20:43:40 +02008439 char_u *arg = arg_in;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008440 char_u *pat;
8441 char_u *envpat = NULL;
8442 char_u *cmd;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008443 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008444 int need_free = FALSE;
8445 int nested = FALSE;
8446 int group;
8447
Bram Moolenaare99e8442016-07-26 20:43:40 +02008448 if (*arg == '|')
8449 {
8450 arg = (char_u *)"";
8451 group = AUGROUP_ALL; /* no argument, use all groups */
8452 }
8453 else
8454 {
8455 /*
8456 * Check for a legal group name. If not, use AUGROUP_ALL.
8457 */
8458 group = au_get_grouparg(&arg);
8459 if (arg == NULL) /* out of memory */
8460 return;
8461 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008462
8463 /*
8464 * Scan over the events.
8465 * If we find an illegal name, return here, don't do anything.
8466 */
8467 pat = find_end_event(arg, group != AUGROUP_ALL);
8468 if (pat == NULL)
8469 return;
8470
Bram Moolenaar071d4272004-06-13 20:20:40 +00008471 pat = skipwhite(pat);
Bram Moolenaare99e8442016-07-26 20:43:40 +02008472 if (*pat == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008473 {
Bram Moolenaare99e8442016-07-26 20:43:40 +02008474 pat = (char_u *)"";
8475 cmd = (char_u *)"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00008476 }
Bram Moolenaare99e8442016-07-26 20:43:40 +02008477 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00008478 {
Bram Moolenaare99e8442016-07-26 20:43:40 +02008479 /*
8480 * Scan over the pattern. Put a NUL at the end.
8481 */
8482 cmd = pat;
Bram Moolenaar1c465442017-03-12 20:10:05 +01008483 while (*cmd && (!VIM_ISWHITE(*cmd) || cmd[-1] == '\\'))
Bram Moolenaare99e8442016-07-26 20:43:40 +02008484 cmd++;
8485 if (*cmd)
8486 *cmd++ = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008487
Bram Moolenaare99e8442016-07-26 20:43:40 +02008488 /* Expand environment variables in the pattern. Set 'shellslash', we want
8489 * forward slashes here. */
8490 if (vim_strchr(pat, '$') != NULL || vim_strchr(pat, '~') != NULL)
8491 {
8492#ifdef BACKSLASH_IN_FILENAME
8493 int p_ssl_save = p_ssl;
8494
8495 p_ssl = TRUE;
8496#endif
8497 envpat = expand_env_save(pat);
8498#ifdef BACKSLASH_IN_FILENAME
8499 p_ssl = p_ssl_save;
8500#endif
8501 if (envpat != NULL)
8502 pat = envpat;
8503 }
8504
8505 /*
8506 * Check for "nested" flag.
8507 */
8508 cmd = skipwhite(cmd);
Bram Moolenaar1c465442017-03-12 20:10:05 +01008509 if (*cmd != NUL && STRNCMP(cmd, "nested", 6) == 0 && VIM_ISWHITE(cmd[6]))
Bram Moolenaare99e8442016-07-26 20:43:40 +02008510 {
8511 nested = TRUE;
8512 cmd = skipwhite(cmd + 6);
8513 }
8514
8515 /*
8516 * Find the start of the commands.
8517 * Expand <sfile> in it.
8518 */
8519 if (*cmd != NUL)
8520 {
8521 cmd = expand_sfile(cmd);
8522 if (cmd == NULL) /* some error */
8523 return;
8524 need_free = TRUE;
8525 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008526 }
8527
8528 /*
8529 * Print header when showing autocommands.
8530 */
8531 if (!forceit && *cmd == NUL)
8532 {
8533 /* Highlight title */
Bram Moolenaar8c555332018-06-22 21:30:31 +02008534 MSG_PUTS_TITLE(_("\n--- Autocommands ---"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008535 }
8536
8537 /*
8538 * Loop over the events.
8539 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008540 last_event = (event_T)-1; /* for listing the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008541 last_group = AUGROUP_ERROR; /* for listing the group name */
Bram Moolenaare99e8442016-07-26 20:43:40 +02008542 if (*arg == '*' || *arg == NUL || *arg == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008543 {
Bram Moolenaar754b5602006-02-09 23:53:20 +00008544 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8545 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008546 if (do_autocmd_event(event, pat,
8547 nested, cmd, forceit, group) == FAIL)
8548 break;
8549 }
8550 else
8551 {
Bram Moolenaar1c465442017-03-12 20:10:05 +01008552 while (*arg && *arg != '|' && !VIM_ISWHITE(*arg))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008553 if (do_autocmd_event(event_name2nr(arg, &arg), pat,
8554 nested, cmd, forceit, group) == FAIL)
8555 break;
8556 }
8557
8558 if (need_free)
8559 vim_free(cmd);
8560 vim_free(envpat);
8561}
8562
8563/*
8564 * Find the group ID in a ":autocmd" or ":doautocmd" argument.
8565 * The "argp" argument is advanced to the following argument.
8566 *
8567 * Returns the group ID, AUGROUP_ERROR for error (out of memory).
8568 */
8569 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008570au_get_grouparg(char_u **argp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008571{
8572 char_u *group_name;
8573 char_u *p;
8574 char_u *arg = *argp;
8575 int group = AUGROUP_ALL;
8576
Bram Moolenaar1c465442017-03-12 20:10:05 +01008577 for (p = arg; *p && !VIM_ISWHITE(*p) && *p != '|'; ++p)
Bram Moolenaare99e8442016-07-26 20:43:40 +02008578 ;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008579 if (p > arg)
8580 {
8581 group_name = vim_strnsave(arg, (int)(p - arg));
8582 if (group_name == NULL) /* out of memory */
8583 return AUGROUP_ERROR;
8584 group = au_find_group(group_name);
8585 if (group == AUGROUP_ERROR)
8586 group = AUGROUP_ALL; /* no match, use all groups */
8587 else
8588 *argp = skipwhite(p); /* match, skip over group name */
8589 vim_free(group_name);
8590 }
8591 return group;
8592}
8593
8594/*
8595 * do_autocmd() for one event.
8596 * If *pat == NUL do for all patterns.
8597 * If *cmd == NUL show entries.
8598 * If forceit == TRUE delete entries.
8599 * If group is not AUGROUP_ALL, only use this group.
8600 */
8601 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008602do_autocmd_event(
8603 event_T event,
8604 char_u *pat,
8605 int nested,
8606 char_u *cmd,
8607 int forceit,
8608 int group)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008609{
8610 AutoPat *ap;
8611 AutoPat **prev_ap;
8612 AutoCmd *ac;
8613 AutoCmd **prev_ac;
8614 int brace_level;
8615 char_u *endpat;
8616 int findgroup;
8617 int allgroups;
8618 int patlen;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00008619 int is_buflocal;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008620 int buflocal_nr;
8621 char_u buflocal_pat[25]; /* for "<buffer=X>" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008622
8623 if (group == AUGROUP_ALL)
8624 findgroup = current_augroup;
8625 else
8626 findgroup = group;
8627 allgroups = (group == AUGROUP_ALL && !forceit && *cmd == NUL);
8628
8629 /*
8630 * Show or delete all patterns for an event.
8631 */
8632 if (*pat == NUL)
8633 {
8634 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8635 {
8636 if (forceit) /* delete the AutoPat, if it's in the current group */
8637 {
8638 if (ap->group == findgroup)
8639 au_remove_pat(ap);
8640 }
8641 else if (group == AUGROUP_ALL || ap->group == group)
8642 show_autocmd(ap, event);
8643 }
8644 }
8645
8646 /*
8647 * Loop through all the specified patterns.
8648 */
8649 for ( ; *pat; pat = (*endpat == ',' ? endpat + 1 : endpat))
8650 {
8651 /*
8652 * Find end of the pattern.
8653 * Watch out for a comma in braces, like "*.\{obj,o\}".
8654 */
8655 brace_level = 0;
8656 for (endpat = pat; *endpat && (*endpat != ',' || brace_level
Bram Moolenaar6b9be1b2015-07-28 13:33:45 +02008657 || (endpat > pat && endpat[-1] == '\\')); ++endpat)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008658 {
8659 if (*endpat == '{')
8660 brace_level++;
8661 else if (*endpat == '}')
8662 brace_level--;
8663 }
8664 if (pat == endpat) /* ignore single comma */
8665 continue;
8666 patlen = (int)(endpat - pat);
8667
8668 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008669 * detect special <buflocal[=X]> buffer-local patterns
8670 */
8671 is_buflocal = FALSE;
8672 buflocal_nr = 0;
8673
Bram Moolenaar1e997822015-02-17 16:04:57 +01008674 if (patlen >= 8 && STRNCMP(pat, "<buffer", 7) == 0
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008675 && pat[patlen - 1] == '>')
8676 {
Bram Moolenaar1e997822015-02-17 16:04:57 +01008677 /* "<buffer...>": Error will be printed only for addition.
8678 * printing and removing will proceed silently. */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008679 is_buflocal = TRUE;
8680 if (patlen == 8)
Bram Moolenaar1e997822015-02-17 16:04:57 +01008681 /* "<buffer>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008682 buflocal_nr = curbuf->b_fnum;
8683 else if (patlen > 9 && pat[7] == '=')
8684 {
Bram Moolenaar1e997822015-02-17 16:04:57 +01008685 if (patlen == 13 && STRNICMP(pat, "<buffer=abuf>", 13) == 0)
8686 /* "<buffer=abuf>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008687 buflocal_nr = autocmd_bufnr;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008688 else if (skipdigits(pat + 8) == pat + patlen - 1)
Bram Moolenaar1e997822015-02-17 16:04:57 +01008689 /* "<buffer=123>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008690 buflocal_nr = atoi((char *)pat + 8);
8691 }
8692 }
8693
8694 if (is_buflocal)
8695 {
8696 /* normalize pat into standard "<buffer>#N" form */
8697 sprintf((char *)buflocal_pat, "<buffer=%d>", buflocal_nr);
8698 pat = buflocal_pat; /* can modify pat and patlen */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008699 patlen = (int)STRLEN(buflocal_pat); /* but not endpat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008700 }
8701
8702 /*
Bram Moolenaar462455e2017-11-10 21:53:11 +01008703 * Find AutoPat entries with this pattern. When adding a command it
8704 * always goes at or after the last one, so start at the end.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008705 */
Bram Moolenaar462455e2017-11-10 21:53:11 +01008706 if (!forceit && *cmd != NUL && last_autopat[(int)event] != NULL)
8707 prev_ap = &last_autopat[(int)event];
8708 else
8709 prev_ap = &first_autopat[(int)event];
Bram Moolenaar071d4272004-06-13 20:20:40 +00008710 while ((ap = *prev_ap) != NULL)
8711 {
8712 if (ap->pat != NULL)
8713 {
8714 /* Accept a pattern when:
8715 * - a group was specified and it's that group, or a group was
8716 * not specified and it's the current group, or a group was
8717 * not specified and we are listing
8718 * - the length of the pattern matches
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008719 * - the pattern matches.
8720 * For <buffer[=X]>, this condition works because we normalize
8721 * all buffer-local patterns.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008722 */
8723 if ((allgroups || ap->group == findgroup)
8724 && ap->patlen == patlen
8725 && STRNCMP(pat, ap->pat, patlen) == 0)
8726 {
8727 /*
8728 * Remove existing autocommands.
8729 * If adding any new autocmd's for this AutoPat, don't
8730 * delete the pattern from the autopat list, append to
8731 * this list.
8732 */
8733 if (forceit)
8734 {
8735 if (*cmd != NUL && ap->next == NULL)
8736 {
8737 au_remove_cmds(ap);
8738 break;
8739 }
8740 au_remove_pat(ap);
8741 }
8742
8743 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008744 * Show autocmd's for this autopat, or buflocals <buffer=X>
Bram Moolenaar071d4272004-06-13 20:20:40 +00008745 */
8746 else if (*cmd == NUL)
8747 show_autocmd(ap, event);
8748
8749 /*
8750 * Add autocmd to this autopat, if it's the last one.
8751 */
8752 else if (ap->next == NULL)
8753 break;
8754 }
8755 }
8756 prev_ap = &ap->next;
8757 }
8758
8759 /*
8760 * Add a new command.
8761 */
8762 if (*cmd != NUL)
8763 {
8764 /*
8765 * If the pattern we want to add a command to does appear at the
8766 * end of the list (or not is not in the list at all), add the
8767 * pattern at the end of the list.
8768 */
8769 if (ap == NULL)
8770 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008771 /* refuse to add buffer-local ap if buffer number is invalid */
8772 if (is_buflocal && (buflocal_nr == 0
8773 || buflist_findnr(buflocal_nr) == NULL))
8774 {
8775 EMSGN(_("E680: <buffer=%d>: invalid buffer number "),
8776 buflocal_nr);
8777 return FAIL;
8778 }
8779
Bram Moolenaar071d4272004-06-13 20:20:40 +00008780 ap = (AutoPat *)alloc((unsigned)sizeof(AutoPat));
8781 if (ap == NULL)
8782 return FAIL;
8783 ap->pat = vim_strnsave(pat, patlen);
8784 ap->patlen = patlen;
8785 if (ap->pat == NULL)
8786 {
8787 vim_free(ap);
8788 return FAIL;
8789 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008790
8791 if (is_buflocal)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008792 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008793 ap->buflocal_nr = buflocal_nr;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008794 ap->reg_prog = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008795 }
8796 else
8797 {
Bram Moolenaar748bf032005-02-02 23:04:36 +00008798 char_u *reg_pat;
8799
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008800 ap->buflocal_nr = 0;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008801 reg_pat = file_pat_to_reg_pat(pat, endpat,
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008802 &ap->allow_dirs, TRUE);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008803 if (reg_pat != NULL)
8804 ap->reg_prog = vim_regcomp(reg_pat, RE_MAGIC);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008805 vim_free(reg_pat);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008806 if (reg_pat == NULL || ap->reg_prog == NULL)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008807 {
8808 vim_free(ap->pat);
8809 vim_free(ap);
8810 return FAIL;
8811 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008812 }
8813 ap->cmds = NULL;
8814 *prev_ap = ap;
Bram Moolenaar462455e2017-11-10 21:53:11 +01008815 last_autopat[(int)event] = ap;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008816 ap->next = NULL;
8817 if (group == AUGROUP_ALL)
8818 ap->group = current_augroup;
8819 else
8820 ap->group = group;
8821 }
8822
8823 /*
8824 * Add the autocmd at the end of the AutoCmd list.
8825 */
8826 prev_ac = &(ap->cmds);
8827 while ((ac = *prev_ac) != NULL)
8828 prev_ac = &ac->next;
8829 ac = (AutoCmd *)alloc((unsigned)sizeof(AutoCmd));
8830 if (ac == NULL)
8831 return FAIL;
8832 ac->cmd = vim_strsave(cmd);
8833#ifdef FEAT_EVAL
Bram Moolenaarf29c1c62018-09-10 21:05:02 +02008834 ac->script_ctx = current_sctx;
8835 ac->script_ctx.sc_lnum += sourcing_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008836#endif
8837 if (ac->cmd == NULL)
8838 {
8839 vim_free(ac);
8840 return FAIL;
8841 }
8842 ac->next = NULL;
8843 *prev_ac = ac;
8844 ac->nested = nested;
8845 }
8846 }
8847
8848 au_cleanup(); /* may really delete removed patterns/commands now */
8849 return OK;
8850}
8851
8852/*
8853 * Implementation of ":doautocmd [group] event [fname]".
8854 * Return OK for success, FAIL for failure;
8855 */
8856 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008857do_doautocmd(
8858 char_u *arg,
Bram Moolenaar1610d052016-06-09 22:53:01 +02008859 int do_msg, /* give message for no matching autocmds? */
8860 int *did_something)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008861{
8862 char_u *fname;
8863 int nothing_done = TRUE;
8864 int group;
8865
Bram Moolenaar1610d052016-06-09 22:53:01 +02008866 if (did_something != NULL)
Bram Moolenaar76ae22f2016-06-13 20:00:29 +02008867 *did_something = FALSE;
Bram Moolenaar1610d052016-06-09 22:53:01 +02008868
Bram Moolenaar071d4272004-06-13 20:20:40 +00008869 /*
8870 * Check for a legal group name. If not, use AUGROUP_ALL.
8871 */
8872 group = au_get_grouparg(&arg);
8873 if (arg == NULL) /* out of memory */
8874 return FAIL;
8875
8876 if (*arg == '*')
8877 {
8878 EMSG(_("E217: Can't execute autocommands for ALL events"));
8879 return FAIL;
8880 }
8881
8882 /*
8883 * Scan over the events.
8884 * If we find an illegal name, return here, don't do anything.
8885 */
8886 fname = find_end_event(arg, group != AUGROUP_ALL);
8887 if (fname == NULL)
8888 return FAIL;
8889
8890 fname = skipwhite(fname);
8891
8892 /*
8893 * Loop over the events.
8894 */
Bram Moolenaarfaf29d72017-07-09 11:07:16 +02008895 while (*arg && !ends_excmd(*arg) && !VIM_ISWHITE(*arg))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008896 if (apply_autocmds_group(event_name2nr(arg, &arg),
8897 fname, NULL, TRUE, group, curbuf, NULL))
8898 nothing_done = FALSE;
8899
8900 if (nothing_done && do_msg)
8901 MSG(_("No matching autocommands"));
Bram Moolenaar1610d052016-06-09 22:53:01 +02008902 if (did_something != NULL)
8903 *did_something = !nothing_done;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008904
8905#ifdef FEAT_EVAL
8906 return aborting() ? FAIL : OK;
8907#else
8908 return OK;
8909#endif
8910}
8911
8912/*
8913 * ":doautoall": execute autocommands for each loaded buffer.
8914 */
8915 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008916ex_doautoall(exarg_T *eap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008917{
8918 int retval;
8919 aco_save_T aco;
8920 buf_T *buf;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008921 bufref_T bufref;
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008922 char_u *arg = eap->arg;
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008923 int call_do_modelines = check_nomodeline(&arg);
Bram Moolenaar1610d052016-06-09 22:53:01 +02008924 int did_aucmd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008925
8926 /*
8927 * This is a bit tricky: For some commands curwin->w_buffer needs to be
8928 * equal to curbuf, but for some buffers there may not be a window.
8929 * So we change the buffer for the current window for a moment. This
8930 * gives problems when the autocommands make changes to the list of
8931 * buffers or windows...
8932 */
Bram Moolenaar29323592016-07-24 22:04:11 +02008933 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008934 {
Bram Moolenaar3a847972008-07-08 09:36:58 +00008935 if (buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008936 {
8937 /* find a window for this buffer and save some values */
8938 aucmd_prepbuf(&aco, buf);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008939 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008940
8941 /* execute the autocommands for this buffer */
Bram Moolenaar1610d052016-06-09 22:53:01 +02008942 retval = do_doautocmd(arg, FALSE, &did_aucmd);
Bram Moolenaareeefcc72007-05-01 21:21:21 +00008943
Bram Moolenaar1610d052016-06-09 22:53:01 +02008944 if (call_do_modelines && did_aucmd)
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008945 {
8946 /* Execute the modeline settings, but don't set window-local
8947 * options if we are using the current window for another
8948 * buffer. */
8949 do_modelines(curwin == aucmd_win ? OPT_NOWIN : 0);
8950 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008951
8952 /* restore the current window */
8953 aucmd_restbuf(&aco);
8954
8955 /* stop if there is some error or buffer was deleted */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008956 if (retval == FAIL || !bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008957 break;
8958 }
8959 }
8960
8961 check_cursor(); /* just in case lines got deleted */
8962}
8963
8964/*
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008965 * Check *argp for <nomodeline>. When it is present return FALSE, otherwise
8966 * return TRUE and advance *argp to after it.
8967 * Thus return TRUE when do_modelines() should be called.
8968 */
8969 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008970check_nomodeline(char_u **argp)
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008971{
8972 if (STRNCMP(*argp, "<nomodeline>", 12) == 0)
8973 {
8974 *argp = skipwhite(*argp + 12);
8975 return FALSE;
8976 }
8977 return TRUE;
8978}
8979
8980/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008981 * Prepare for executing autocommands for (hidden) buffer "buf".
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008982 * Search for a visible window containing the current buffer. If there isn't
8983 * one then use "aucmd_win".
Bram Moolenaar071d4272004-06-13 20:20:40 +00008984 * Set "curbuf" and "curwin" to match "buf".
8985 */
8986 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008987aucmd_prepbuf(
8988 aco_save_T *aco, /* structure to save values in */
8989 buf_T *buf) /* new curbuf */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008990{
8991 win_T *win;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008992 int save_ea;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008993#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008994 int save_acd;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008995#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008996
8997 /* Find a window that is for the new buffer */
8998 if (buf == curbuf) /* be quick when buf is curbuf */
8999 win = curwin;
9000 else
Bram Moolenaar29323592016-07-24 22:04:11 +02009001 FOR_ALL_WINDOWS(win)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009002 if (win->w_buffer == buf)
9003 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009004
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009005 /* Allocate "aucmd_win" when needed. If this fails (out of memory) fall
9006 * back to using the current window. */
9007 if (win == NULL && aucmd_win == NULL)
9008 {
9009 win_alloc_aucmd_win();
9010 if (aucmd_win == NULL)
9011 win = curwin;
9012 }
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009013 if (win == NULL && aucmd_win_used)
9014 /* Strange recursive autocommand, fall back to using the current
9015 * window. Expect a few side effects... */
9016 win = curwin;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009017
9018 aco->save_curwin = curwin;
9019 aco->save_curbuf = curbuf;
Bram Moolenaara42df592018-12-24 00:22:39 +01009020 aco->save_prevwin = prevwin;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009021 if (win != NULL)
9022 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009023 /* There is a window for "buf" in the current tab page, make it the
9024 * curwin. This is preferred, it has the least side effects (esp. if
9025 * "buf" is curbuf). */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009026 aco->use_aucmd_win = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009027 curwin = win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009028 }
9029 else
9030 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009031 /* There is no window for "buf", use "aucmd_win". To minimize the side
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02009032 * effects, insert it in the current tab page.
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009033 * Anything related to a window (e.g., setting folds) may have
9034 * unexpected results. */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009035 aco->use_aucmd_win = TRUE;
9036 aucmd_win_used = TRUE;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00009037 aucmd_win->w_buffer = buf;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01009038#if defined(FEAT_SYN_HL) || defined(FEAT_SPELL)
Bram Moolenaarcdddaa42010-06-07 23:07:44 +02009039 aucmd_win->w_s = &buf->b_s;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01009040#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009041 ++buf->b_nwindows;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00009042 win_init_empty(aucmd_win); /* set cursor and topline to safe values */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009043
9044 /* Make sure w_localdir and globaldir are NULL to avoid a chdir() in
9045 * win_enter_ext(). */
Bram Moolenaard23a8232018-02-10 18:45:26 +01009046 VIM_CLEAR(aucmd_win->w_localdir);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009047 aco->globaldir = globaldir;
9048 globaldir = NULL;
9049
Bram Moolenaar071d4272004-06-13 20:20:40 +00009050
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00009051 /* Split the current window, put the aucmd_win in the upper half.
9052 * We don't want the BufEnter or WinEnter autocommands. */
9053 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009054 make_snapshot(SNAP_AUCMD_IDX);
9055 save_ea = p_ea;
9056 p_ea = FALSE;
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009057
Bram Moolenaar4033c552017-09-16 20:54:51 +02009058#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009059 /* Prevent chdir() call in win_enter_ext(), through do_autochdir(). */
9060 save_acd = p_acd;
9061 p_acd = FALSE;
Bram Moolenaar4033c552017-09-16 20:54:51 +02009062#endif
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009063
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009064 (void)win_split_ins(0, WSP_TOP, aucmd_win, 0);
9065 (void)win_comp_pos(); /* recompute window positions */
9066 p_ea = save_ea;
Bram Moolenaar4033c552017-09-16 20:54:51 +02009067#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009068 p_acd = save_acd;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009069#endif
Bram Moolenaar4033c552017-09-16 20:54:51 +02009070 unblock_autocmds();
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00009071 curwin = aucmd_win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009072 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009073 curbuf = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009074 aco->new_curwin = curwin;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009075 set_bufref(&aco->new_curbuf, curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009076}
9077
9078/*
9079 * Cleanup after executing autocommands for a (hidden) buffer.
9080 * Restore the window as it was (if possible).
9081 */
9082 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009083aucmd_restbuf(
9084 aco_save_T *aco) /* structure holding saved values */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009085{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009086 int dummy;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009087
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009088 if (aco->use_aucmd_win)
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009089 {
9090 --curbuf->b_nwindows;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009091 /* Find "aucmd_win", it can't be closed, but it may be in another tab
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00009092 * page. Do not trigger autocommands here. */
9093 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009094 if (curwin != aucmd_win)
9095 {
9096 tabpage_T *tp;
9097 win_T *wp;
9098
9099 FOR_ALL_TAB_WINDOWS(tp, wp)
9100 {
9101 if (wp == aucmd_win)
9102 {
9103 if (tp != curtab)
Bram Moolenaar49e649f2013-05-06 04:50:35 +02009104 goto_tabpage_tp(tp, TRUE, TRUE);
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009105 win_goto(aucmd_win);
Bram Moolenaar28f29082012-02-11 23:45:37 +01009106 goto win_found;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009107 }
9108 }
9109 }
Bram Moolenaar28f29082012-02-11 23:45:37 +01009110win_found:
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009111
9112 /* Remove the window and frame from the tree of frames. */
9113 (void)winframe_remove(curwin, &dummy, NULL);
9114 win_remove(curwin, NULL);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009115 aucmd_win_used = FALSE;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009116 last_status(FALSE); /* may need to remove last status line */
Bram Moolenaar8c752bd2017-03-19 17:09:56 +01009117
9118 if (!valid_tabpage_win(curtab))
9119 /* no valid window in current tabpage */
9120 close_tabpage(curtab);
9121
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009122 restore_snapshot(SNAP_AUCMD_IDX, FALSE);
9123 (void)win_comp_pos(); /* recompute window positions */
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00009124 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009125
9126 if (win_valid(aco->save_curwin))
9127 curwin = aco->save_curwin;
9128 else
9129 /* Hmm, original window disappeared. Just use the first one. */
9130 curwin = firstwin;
Bram Moolenaara42df592018-12-24 00:22:39 +01009131 if (win_valid(aco->save_prevwin))
9132 prevwin = aco->save_prevwin;
Bram Moolenaar4033c552017-09-16 20:54:51 +02009133#ifdef FEAT_EVAL
Bram Moolenaar429fa852013-04-15 12:27:36 +02009134 vars_clear(&aucmd_win->w_vars->dv_hashtab); /* free all w: variables */
9135 hash_init(&aucmd_win->w_vars->dv_hashtab); /* re-use the hashtab */
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009136#endif
9137 curbuf = curwin->w_buffer;
9138
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009139 vim_free(globaldir);
9140 globaldir = aco->globaldir;
9141
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009142 /* the buffer contents may have changed */
9143 check_cursor();
9144 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
9145 {
9146 curwin->w_topline = curbuf->b_ml.ml_line_count;
9147#ifdef FEAT_DIFF
9148 curwin->w_topfill = 0;
9149#endif
9150 }
9151#if defined(FEAT_GUI)
9152 /* Hide the scrollbars from the aucmd_win and update. */
9153 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_LEFT], FALSE);
9154 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_RIGHT], FALSE);
9155 gui_may_update_scrollbars();
9156#endif
9157 }
9158 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00009159 {
9160 /* restore curwin */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009161 if (win_valid(aco->save_curwin))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009162 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009163 /* Restore the buffer which was previously edited by curwin, if
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009164 * it was changed, we are still the same window and the buffer is
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009165 * valid. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009166 if (curwin == aco->new_curwin
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009167 && curbuf != aco->new_curbuf.br_buf
9168 && bufref_valid(&aco->new_curbuf)
9169 && aco->new_curbuf.br_buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009170 {
Bram Moolenaar7da9c372012-04-30 17:04:52 +02009171# if defined(FEAT_SYN_HL) || defined(FEAT_SPELL)
9172 if (curwin->w_s == &curbuf->b_s)
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009173 curwin->w_s = &aco->new_curbuf.br_buf->b_s;
Bram Moolenaar7da9c372012-04-30 17:04:52 +02009174# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009175 --curbuf->b_nwindows;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009176 curbuf = aco->new_curbuf.br_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009177 curwin->w_buffer = curbuf;
9178 ++curbuf->b_nwindows;
9179 }
9180
9181 curwin = aco->save_curwin;
9182 curbuf = curwin->w_buffer;
Bram Moolenaara42df592018-12-24 00:22:39 +01009183 if (win_valid(aco->save_prevwin))
9184 prevwin = aco->save_prevwin;
Bram Moolenaar371932a2014-09-09 16:59:38 +02009185 /* In case the autocommand move the cursor to a position that that
9186 * not exist in curbuf. */
9187 check_cursor();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009188 }
9189 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009190}
9191
9192static int autocmd_nested = FALSE;
9193
9194/*
9195 * Execute autocommands for "event" and file name "fname".
9196 * Return TRUE if some commands were executed.
9197 */
9198 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009199apply_autocmds(
9200 event_T event,
9201 char_u *fname, /* NULL or empty means use actual file name */
9202 char_u *fname_io, /* fname to use for <afile> on cmdline */
9203 int force, /* when TRUE, ignore autocmd_busy */
9204 buf_T *buf) /* buffer for <abuf> */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009205{
9206 return apply_autocmds_group(event, fname, fname_io, force,
9207 AUGROUP_ALL, buf, NULL);
9208}
9209
9210/*
9211 * Like apply_autocmds(), but with extra "eap" argument. This takes care of
9212 * setting v:filearg.
9213 */
9214 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009215apply_autocmds_exarg(
9216 event_T event,
9217 char_u *fname,
9218 char_u *fname_io,
9219 int force,
9220 buf_T *buf,
9221 exarg_T *eap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009222{
9223 return apply_autocmds_group(event, fname, fname_io, force,
9224 AUGROUP_ALL, buf, eap);
9225}
9226
9227/*
9228 * Like apply_autocmds(), but handles the caller's retval. If the script
9229 * processing is being aborted or if retval is FAIL when inside a try
9230 * conditional, no autocommands are executed. If otherwise the autocommands
9231 * cause the script to be aborted, retval is set to FAIL.
9232 */
9233 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009234apply_autocmds_retval(
9235 event_T event,
9236 char_u *fname, /* NULL or empty means use actual file name */
9237 char_u *fname_io, /* fname to use for <afile> on cmdline */
9238 int force, /* when TRUE, ignore autocmd_busy */
9239 buf_T *buf, /* buffer for <abuf> */
9240 int *retval) /* pointer to caller's retval */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009241{
9242 int did_cmd;
9243
Bram Moolenaar1e015462005-09-25 22:16:38 +00009244#ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00009245 if (should_abort(*retval))
9246 return FALSE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00009247#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009248
9249 did_cmd = apply_autocmds_group(event, fname, fname_io, force,
9250 AUGROUP_ALL, buf, NULL);
Bram Moolenaar1e015462005-09-25 22:16:38 +00009251 if (did_cmd
9252#ifdef FEAT_EVAL
9253 && aborting()
9254#endif
9255 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00009256 *retval = FAIL;
9257 return did_cmd;
9258}
9259
Bram Moolenaard35f9712005-12-18 22:02:33 +00009260/*
9261 * Return TRUE when there is a CursorHold autocommand defined.
9262 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009263 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009264has_cursorhold(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009265{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009266 return (first_autopat[(int)(get_real_state() == NORMAL_BUSY
9267 ? EVENT_CURSORHOLD : EVENT_CURSORHOLDI)] != NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009268}
Bram Moolenaard35f9712005-12-18 22:02:33 +00009269
9270/*
9271 * Return TRUE if the CursorHold event can be triggered.
9272 */
9273 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009274trigger_cursorhold(void)
Bram Moolenaard35f9712005-12-18 22:02:33 +00009275{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009276 int state;
9277
Bram Moolenaar05334432011-07-20 18:29:39 +02009278 if (!did_cursorhold
9279 && has_cursorhold()
Bram Moolenaar0b6d9112018-05-22 20:35:17 +02009280 && reg_recording == 0
Bram Moolenaar05334432011-07-20 18:29:39 +02009281 && typebuf.tb_len == 0
Bram Moolenaard29a9ee2006-09-14 09:07:34 +00009282#ifdef FEAT_INS_EXPAND
9283 && !ins_compl_active()
9284#endif
9285 )
Bram Moolenaar754b5602006-02-09 23:53:20 +00009286 {
9287 state = get_real_state();
9288 if (state == NORMAL_BUSY || (state & INSERT) != 0)
9289 return TRUE;
9290 }
9291 return FALSE;
Bram Moolenaard35f9712005-12-18 22:02:33 +00009292}
Bram Moolenaar754b5602006-02-09 23:53:20 +00009293
9294/*
9295 * Return TRUE when there is a CursorMoved autocommand defined.
9296 */
9297 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009298has_cursormoved(void)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009299{
9300 return (first_autopat[(int)EVENT_CURSORMOVED] != NULL);
9301}
9302
9303/*
9304 * Return TRUE when there is a CursorMovedI autocommand defined.
9305 */
9306 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009307has_cursormovedI(void)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009308{
9309 return (first_autopat[(int)EVENT_CURSORMOVEDI] != NULL);
9310}
Bram Moolenaar071d4272004-06-13 20:20:40 +00009311
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009312/*
Bram Moolenaar186628f2013-03-19 13:33:23 +01009313 * Return TRUE when there is a TextChanged autocommand defined.
9314 */
9315 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009316has_textchanged(void)
Bram Moolenaar186628f2013-03-19 13:33:23 +01009317{
9318 return (first_autopat[(int)EVENT_TEXTCHANGED] != NULL);
9319}
9320
9321/*
9322 * Return TRUE when there is a TextChangedI autocommand defined.
9323 */
9324 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009325has_textchangedI(void)
Bram Moolenaar186628f2013-03-19 13:33:23 +01009326{
9327 return (first_autopat[(int)EVENT_TEXTCHANGEDI] != NULL);
9328}
9329
9330/*
Bram Moolenaar5a093432018-02-10 18:15:19 +01009331 * Return TRUE when there is a TextChangedP autocommand defined.
9332 */
9333 int
9334has_textchangedP(void)
9335{
9336 return (first_autopat[(int)EVENT_TEXTCHANGEDP] != NULL);
9337}
9338
9339/*
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009340 * Return TRUE when there is an InsertCharPre autocommand defined.
9341 */
9342 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009343has_insertcharpre(void)
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009344{
9345 return (first_autopat[(int)EVENT_INSERTCHARPRE] != NULL);
9346}
9347
Bram Moolenaard5005162014-08-22 23:05:54 +02009348/*
9349 * Return TRUE when there is an CmdUndefined autocommand defined.
9350 */
9351 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009352has_cmdundefined(void)
Bram Moolenaard5005162014-08-22 23:05:54 +02009353{
9354 return (first_autopat[(int)EVENT_CMDUNDEFINED] != NULL);
9355}
9356
9357/*
9358 * Return TRUE when there is an FuncUndefined autocommand defined.
9359 */
9360 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009361has_funcundefined(void)
Bram Moolenaard5005162014-08-22 23:05:54 +02009362{
9363 return (first_autopat[(int)EVENT_FUNCUNDEFINED] != NULL);
9364}
9365
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009366/*
Bram Moolenaar7e1652c2017-12-16 18:27:02 +01009367 * Return TRUE when there is a TextYankPost autocommand defined.
9368 */
9369 int
9370has_textyankpost(void)
9371{
9372 return (first_autopat[(int)EVENT_TEXTYANKPOST] != NULL);
9373}
9374
9375/*
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009376 * Execute autocommands for "event" and file name "fname".
9377 * Return TRUE if some commands were executed.
9378 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009379 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009380apply_autocmds_group(
9381 event_T event,
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01009382 char_u *fname, /* NULL or empty means use actual file name */
9383 char_u *fname_io, /* fname to use for <afile> on cmdline, NULL means
Bram Moolenaar071d4272004-06-13 20:20:40 +00009384 use fname */
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01009385 int force, /* when TRUE, ignore autocmd_busy */
9386 int group, /* group ID, or AUGROUP_ALL */
9387 buf_T *buf, /* buffer for <abuf> */
9388 exarg_T *eap UNUSED) /* command arguments */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009389{
9390 char_u *sfname = NULL; /* short file name */
9391 char_u *tail;
9392 int save_changed;
9393 buf_T *old_curbuf;
9394 int retval = FALSE;
9395 char_u *save_sourcing_name;
9396 linenr_T save_sourcing_lnum;
9397 char_u *save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009398 int save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009399 int save_autocmd_bufnr;
9400 char_u *save_autocmd_match;
9401 int save_autocmd_busy;
9402 int save_autocmd_nested;
9403 static int nesting = 0;
9404 AutoPatCmd patcmd;
9405 AutoPat *ap;
9406#ifdef FEAT_EVAL
Bram Moolenaarf29c1c62018-09-10 21:05:02 +02009407 sctx_T save_current_sctx;
Bram Moolenaar27e80c82018-10-14 21:41:01 +02009408 funccal_entry_T funccal_entry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009409 char_u *save_cmdarg;
9410 long save_cmdbang;
9411#endif
9412 static int filechangeshell_busy = FALSE;
Bram Moolenaar05159a02005-02-26 23:04:13 +00009413#ifdef FEAT_PROFILE
9414 proftime_T wait_time;
9415#endif
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009416 int did_save_redobuff = FALSE;
Bram Moolenaard4863aa2017-04-07 19:50:12 +02009417 save_redo_T save_redo;
Bram Moolenaarc9e9c712017-11-09 12:29:35 +01009418 int save_KeyTyped = KeyTyped;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009419
9420 /*
9421 * Quickly return if there are no autocommands for this event or
9422 * autocommands are blocked.
9423 */
Bram Moolenaarfaf29d72017-07-09 11:07:16 +02009424 if (event == NUM_EVENTS || first_autopat[(int)event] == NULL
9425 || autocmd_blocked > 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009426 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009427
9428 /*
9429 * When autocommands are busy, new autocommands are only executed when
9430 * explicitly enabled with the "nested" flag.
9431 */
9432 if (autocmd_busy && !(force || autocmd_nested))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009433 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009434
9435#ifdef FEAT_EVAL
9436 /*
Bram Moolenaar7263a772007-05-10 17:35:54 +00009437 * Quickly return when immediately aborting on error, or when an interrupt
Bram Moolenaar071d4272004-06-13 20:20:40 +00009438 * occurred or an exception was thrown but not caught.
9439 */
9440 if (aborting())
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009441 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009442#endif
9443
9444 /*
9445 * FileChangedShell never nests, because it can create an endless loop.
9446 */
Bram Moolenaar56718732006-03-15 22:53:57 +00009447 if (filechangeshell_busy && (event == EVENT_FILECHANGEDSHELL
9448 || event == EVENT_FILECHANGEDSHELLPOST))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009449 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009450
9451 /*
9452 * Ignore events in 'eventignore'.
9453 */
9454 if (event_ignored(event))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009455 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009456
9457 /*
9458 * Allow nesting of autocommands, but restrict the depth, because it's
9459 * possible to create an endless loop.
9460 */
9461 if (nesting == 10)
9462 {
9463 EMSG(_("E218: autocommand nesting too deep"));
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009464 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009465 }
9466
9467 /*
9468 * Check if these autocommands are disabled. Used when doing ":all" or
9469 * ":ball".
9470 */
9471 if ( (autocmd_no_enter
9472 && (event == EVENT_WINENTER || event == EVENT_BUFENTER))
9473 || (autocmd_no_leave
9474 && (event == EVENT_WINLEAVE || event == EVENT_BUFLEAVE)))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009475 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009476
9477 /*
9478 * Save the autocmd_* variables and info about the current buffer.
9479 */
9480 save_autocmd_fname = autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009481 save_autocmd_fname_full = autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009482 save_autocmd_bufnr = autocmd_bufnr;
9483 save_autocmd_match = autocmd_match;
9484 save_autocmd_busy = autocmd_busy;
9485 save_autocmd_nested = autocmd_nested;
9486 save_changed = curbuf->b_changed;
9487 old_curbuf = curbuf;
9488
9489 /*
9490 * Set the file name to be used for <afile>.
Bram Moolenaara0174af2008-01-02 20:08:25 +00009491 * Make a copy to avoid that changing a buffer name or directory makes it
9492 * invalid.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009493 */
9494 if (fname_io == NULL)
9495 {
Bram Moolenaar60a68362018-04-30 15:40:48 +02009496 if (event == EVENT_COLORSCHEME || event == EVENT_COLORSCHEMEPRE
9497 || event == EVENT_OPTIONSET)
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009498 autocmd_fname = NULL;
Bram Moolenaarfaf29d72017-07-09 11:07:16 +02009499 else if (fname != NULL && !ends_excmd(*fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009500 autocmd_fname = fname;
9501 else if (buf != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009502 autocmd_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009503 else
9504 autocmd_fname = NULL;
9505 }
9506 else
9507 autocmd_fname = fname_io;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009508 if (autocmd_fname != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009509 autocmd_fname = vim_strsave(autocmd_fname);
9510 autocmd_fname_full = FALSE; /* call FullName_save() later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009511
9512 /*
9513 * Set the buffer number to be used for <abuf>.
9514 */
9515 if (buf == NULL)
9516 autocmd_bufnr = 0;
9517 else
9518 autocmd_bufnr = buf->b_fnum;
9519
9520 /*
9521 * When the file name is NULL or empty, use the file name of buffer "buf".
9522 * Always use the full path of the file name to match with, in case
9523 * "allow_dirs" is set.
9524 */
9525 if (fname == NULL || *fname == NUL)
9526 {
9527 if (buf == NULL)
9528 fname = NULL;
9529 else
9530 {
9531#ifdef FEAT_SYN_HL
9532 if (event == EVENT_SYNTAX)
9533 fname = buf->b_p_syn;
9534 else
9535#endif
9536 if (event == EVENT_FILETYPE)
9537 fname = buf->b_p_ft;
9538 else
9539 {
9540 if (buf->b_sfname != NULL)
9541 sfname = vim_strsave(buf->b_sfname);
9542 fname = buf->b_ffname;
9543 }
9544 }
9545 if (fname == NULL)
9546 fname = (char_u *)"";
9547 fname = vim_strsave(fname); /* make a copy, so we can change it */
9548 }
9549 else
9550 {
9551 sfname = vim_strsave(fname);
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009552 /* Don't try expanding FileType, Syntax, FuncUndefined, WindowID,
Bram Moolenaarb7407d32018-02-03 17:36:27 +01009553 * ColorScheme, QuickFixCmd* or DirChanged */
Bram Moolenaar7c626922005-02-07 22:01:03 +00009554 if (event == EVENT_FILETYPE
9555 || event == EVENT_SYNTAX
Bram Moolenaara4baf5b2018-04-22 13:27:44 +02009556 || event == EVENT_CMDLINECHANGED
9557 || event == EVENT_CMDLINEENTER
9558 || event == EVENT_CMDLINELEAVE
9559 || event == EVENT_CMDWINENTER
9560 || event == EVENT_CMDWINLEAVE
9561 || event == EVENT_CMDUNDEFINED
Bram Moolenaar5135d462009-04-29 16:03:38 +00009562 || event == EVENT_FUNCUNDEFINED
Bram Moolenaar7c626922005-02-07 22:01:03 +00009563 || event == EVENT_REMOTEREPLY
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00009564 || event == EVENT_SPELLFILEMISSING
Bram Moolenaar7c626922005-02-07 22:01:03 +00009565 || event == EVENT_QUICKFIXCMDPRE
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009566 || event == EVENT_COLORSCHEME
Bram Moolenaar60a68362018-04-30 15:40:48 +02009567 || event == EVENT_COLORSCHEMEPRE
Bram Moolenaar53744302015-07-17 17:38:22 +02009568 || event == EVENT_OPTIONSET
Bram Moolenaarb7407d32018-02-03 17:36:27 +01009569 || event == EVENT_QUICKFIXCMDPOST
9570 || event == EVENT_DIRCHANGED)
Bram Moolenaara4baf5b2018-04-22 13:27:44 +02009571 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00009572 fname = vim_strsave(fname);
Bram Moolenaara4baf5b2018-04-22 13:27:44 +02009573 autocmd_fname_full = TRUE; /* don't expand it later */
9574 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009575 else
9576 fname = FullName_save(fname, FALSE);
9577 }
9578 if (fname == NULL) /* out of memory */
9579 {
9580 vim_free(sfname);
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009581 retval = FALSE;
9582 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009583 }
9584
9585#ifdef BACKSLASH_IN_FILENAME
9586 /*
9587 * Replace all backslashes with forward slashes. This makes the
9588 * autocommand patterns portable between Unix and MS-DOS.
9589 */
9590 if (sfname != NULL)
9591 forward_slash(sfname);
9592 forward_slash(fname);
9593#endif
9594
9595#ifdef VMS
9596 /* remove version for correct match */
9597 if (sfname != NULL)
9598 vms_remove_version(sfname);
9599 vms_remove_version(fname);
9600#endif
9601
9602 /*
9603 * Set the name to be used for <amatch>.
9604 */
9605 autocmd_match = fname;
9606
9607
Bram Moolenaar8c555332018-06-22 21:30:31 +02009608 /* Don't redraw while doing autocommands. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009609 ++RedrawingDisabled;
9610 save_sourcing_name = sourcing_name;
9611 sourcing_name = NULL; /* don't free this one */
9612 save_sourcing_lnum = sourcing_lnum;
9613 sourcing_lnum = 0; /* no line number here */
9614
9615#ifdef FEAT_EVAL
Bram Moolenaarf29c1c62018-09-10 21:05:02 +02009616 save_current_sctx = current_sctx;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009617
Bram Moolenaar05159a02005-02-26 23:04:13 +00009618# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009619 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009620 prof_child_enter(&wait_time); /* doesn't count for the caller itself */
9621# endif
9622
Bram Moolenaar27e80c82018-10-14 21:41:01 +02009623 // Don't use local function variables, if called from a function.
9624 save_funccal(&funccal_entry);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009625#endif
9626
9627 /*
9628 * When starting to execute autocommands, save the search patterns.
9629 */
9630 if (!autocmd_busy)
9631 {
9632 save_search_patterns();
Bram Moolenaar20ad69c2015-12-03 13:52:52 +01009633#ifdef FEAT_INS_EXPAND
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009634 if (!ins_compl_active())
Bram Moolenaar20ad69c2015-12-03 13:52:52 +01009635#endif
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009636 {
Bram Moolenaard4863aa2017-04-07 19:50:12 +02009637 saveRedobuff(&save_redo);
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009638 did_save_redobuff = TRUE;
9639 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009640 did_filetype = keep_filetype;
9641 }
9642
9643 /*
9644 * Note that we are applying autocmds. Some commands need to know.
9645 */
9646 autocmd_busy = TRUE;
9647 filechangeshell_busy = (event == EVENT_FILECHANGEDSHELL);
9648 ++nesting; /* see matching decrement below */
9649
9650 /* Remember that FileType was triggered. Used for did_filetype(). */
9651 if (event == EVENT_FILETYPE)
9652 did_filetype = TRUE;
9653
9654 tail = gettail(fname);
9655
9656 /* Find first autocommand that matches */
9657 patcmd.curpat = first_autopat[(int)event];
9658 patcmd.nextcmd = NULL;
9659 patcmd.group = group;
9660 patcmd.fname = fname;
9661 patcmd.sfname = sfname;
9662 patcmd.tail = tail;
9663 patcmd.event = event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009664 patcmd.arg_bufnr = autocmd_bufnr;
9665 patcmd.next = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009666 auto_next_pat(&patcmd, FALSE);
9667
9668 /* found one, start executing the autocommands */
9669 if (patcmd.curpat != NULL)
9670 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009671 /* add to active_apc_list */
9672 patcmd.next = active_apc_list;
9673 active_apc_list = &patcmd;
9674
Bram Moolenaar071d4272004-06-13 20:20:40 +00009675#ifdef FEAT_EVAL
9676 /* set v:cmdarg (only when there is a matching pattern) */
Bram Moolenaar22fcfad2016-07-01 18:17:26 +02009677 save_cmdbang = (long)get_vim_var_nr(VV_CMDBANG);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009678 if (eap != NULL)
9679 {
9680 save_cmdarg = set_cmdarg(eap, NULL);
9681 set_vim_var_nr(VV_CMDBANG, (long)eap->forceit);
9682 }
9683 else
9684 save_cmdarg = NULL; /* avoid gcc warning */
9685#endif
9686 retval = TRUE;
9687 /* mark the last pattern, to avoid an endless loop when more patterns
9688 * are added when executing autocommands */
9689 for (ap = patcmd.curpat; ap->next != NULL; ap = ap->next)
9690 ap->last = FALSE;
9691 ap->last = TRUE;
9692 check_lnums(TRUE); /* make sure cursor and topline are valid */
9693 do_cmdline(NULL, getnextac, (void *)&patcmd,
9694 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
9695#ifdef FEAT_EVAL
9696 if (eap != NULL)
9697 {
9698 (void)set_cmdarg(NULL, save_cmdarg);
9699 set_vim_var_nr(VV_CMDBANG, save_cmdbang);
9700 }
9701#endif
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009702 /* delete from active_apc_list */
9703 if (active_apc_list == &patcmd) /* just in case */
9704 active_apc_list = patcmd.next;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009705 }
9706
9707 --RedrawingDisabled;
9708 autocmd_busy = save_autocmd_busy;
9709 filechangeshell_busy = FALSE;
9710 autocmd_nested = save_autocmd_nested;
9711 vim_free(sourcing_name);
9712 sourcing_name = save_sourcing_name;
9713 sourcing_lnum = save_sourcing_lnum;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009714 vim_free(autocmd_fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009715 autocmd_fname = save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009716 autocmd_fname_full = save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009717 autocmd_bufnr = save_autocmd_bufnr;
9718 autocmd_match = save_autocmd_match;
9719#ifdef FEAT_EVAL
Bram Moolenaarf29c1c62018-09-10 21:05:02 +02009720 current_sctx = save_current_sctx;
Bram Moolenaar27e80c82018-10-14 21:41:01 +02009721 restore_funccal();
Bram Moolenaar05159a02005-02-26 23:04:13 +00009722# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009723 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009724 prof_child_exit(&wait_time);
9725# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009726#endif
Bram Moolenaarc9e9c712017-11-09 12:29:35 +01009727 KeyTyped = save_KeyTyped;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009728 vim_free(fname);
9729 vim_free(sfname);
9730 --nesting; /* see matching increment above */
9731
9732 /*
9733 * When stopping to execute autocommands, restore the search patterns and
Bram Moolenaar3be85852014-06-12 14:01:31 +02009734 * the redo buffer. Free any buffers in the au_pending_free_buf list and
9735 * free any windows in the au_pending_free_win list.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009736 */
9737 if (!autocmd_busy)
9738 {
9739 restore_search_patterns();
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009740 if (did_save_redobuff)
Bram Moolenaard4863aa2017-04-07 19:50:12 +02009741 restoreRedobuff(&save_redo);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009742 did_filetype = FALSE;
Bram Moolenaar4c7ab1b2014-04-06 20:45:43 +02009743 while (au_pending_free_buf != NULL)
9744 {
9745 buf_T *b = au_pending_free_buf->b_next;
9746 vim_free(au_pending_free_buf);
9747 au_pending_free_buf = b;
9748 }
Bram Moolenaar3be85852014-06-12 14:01:31 +02009749 while (au_pending_free_win != NULL)
9750 {
9751 win_T *w = au_pending_free_win->w_next;
9752 vim_free(au_pending_free_win);
9753 au_pending_free_win = w;
9754 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009755 }
9756
9757 /*
9758 * Some events don't set or reset the Changed flag.
9759 * Check if still in the same buffer!
9760 */
9761 if (curbuf == old_curbuf
9762 && (event == EVENT_BUFREADPOST
9763 || event == EVENT_BUFWRITEPOST
9764 || event == EVENT_FILEAPPENDPOST
9765 || event == EVENT_VIMLEAVE
9766 || event == EVENT_VIMLEAVEPRE))
9767 {
9768#ifdef FEAT_TITLE
9769 if (curbuf->b_changed != save_changed)
9770 need_maketitle = TRUE;
9771#endif
9772 curbuf->b_changed = save_changed;
9773 }
9774
9775 au_cleanup(); /* may really delete removed patterns/commands now */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009776
9777BYPASS_AU:
9778 /* When wiping out a buffer make sure all its buffer-local autocommands
9779 * are deleted. */
9780 if (event == EVENT_BUFWIPEOUT && buf != NULL)
9781 aubuflocal_remove(buf);
9782
Bram Moolenaarc3691332016-04-20 12:49:49 +02009783 if (retval == OK && event == EVENT_FILETYPE)
9784 au_did_filetype = TRUE;
9785
Bram Moolenaar071d4272004-06-13 20:20:40 +00009786 return retval;
9787}
9788
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009789# ifdef FEAT_EVAL
9790static char_u *old_termresponse = NULL;
9791# endif
9792
9793/*
9794 * Block triggering autocommands until unblock_autocmd() is called.
9795 * Can be used recursively, so long as it's symmetric.
9796 */
9797 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009798block_autocmds(void)
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009799{
9800# ifdef FEAT_EVAL
9801 /* Remember the value of v:termresponse. */
9802 if (autocmd_blocked == 0)
9803 old_termresponse = get_vim_var_str(VV_TERMRESPONSE);
9804# endif
9805 ++autocmd_blocked;
9806}
9807
9808 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009809unblock_autocmds(void)
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009810{
9811 --autocmd_blocked;
9812
9813# ifdef FEAT_EVAL
9814 /* When v:termresponse was set while autocommands were blocked, trigger
9815 * the autocommands now. Esp. useful when executing a shell command
9816 * during startup (vimdiff). */
9817 if (autocmd_blocked == 0
9818 && get_vim_var_str(VV_TERMRESPONSE) != old_termresponse)
9819 apply_autocmds(EVENT_TERMRESPONSE, NULL, NULL, FALSE, curbuf);
9820# endif
9821}
9822
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009823 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009824is_autocmd_blocked(void)
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009825{
9826 return autocmd_blocked != 0;
9827}
9828
Bram Moolenaar071d4272004-06-13 20:20:40 +00009829/*
9830 * Find next autocommand pattern that matches.
9831 */
9832 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009833auto_next_pat(
9834 AutoPatCmd *apc,
9835 int stop_at_last) /* stop when 'last' flag is set */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009836{
9837 AutoPat *ap;
9838 AutoCmd *cp;
9839 char_u *name;
9840 char *s;
9841
Bram Moolenaard23a8232018-02-10 18:45:26 +01009842 VIM_CLEAR(sourcing_name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009843
9844 for (ap = apc->curpat; ap != NULL && !got_int; ap = ap->next)
9845 {
9846 apc->curpat = NULL;
9847
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009848 /* Only use a pattern when it has not been removed, has commands and
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009849 * the group matches. For buffer-local autocommands only check the
9850 * buffer number. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009851 if (ap->pat != NULL && ap->cmds != NULL
9852 && (apc->group == AUGROUP_ALL || apc->group == ap->group))
9853 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009854 /* execution-condition */
9855 if (ap->buflocal_nr == 0
Bram Moolenaardffa5b82014-11-19 16:38:07 +01009856 ? (match_file_pat(NULL, &ap->reg_prog, apc->fname,
Bram Moolenaar748bf032005-02-02 23:04:36 +00009857 apc->sfname, apc->tail, ap->allow_dirs))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009858 : ap->buflocal_nr == apc->arg_bufnr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009859 {
9860 name = event_nr2name(apc->event);
Bram Moolenaar8c555332018-06-22 21:30:31 +02009861 s = _("%s Autocommands for \"%s\"");
Bram Moolenaar071d4272004-06-13 20:20:40 +00009862 sourcing_name = alloc((unsigned)(STRLEN(s)
9863 + STRLEN(name) + ap->patlen + 1));
9864 if (sourcing_name != NULL)
9865 {
9866 sprintf((char *)sourcing_name, s,
9867 (char *)name, (char *)ap->pat);
9868 if (p_verbose >= 8)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009869 {
9870 verbose_enter();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009871 smsg((char_u *)_("Executing %s"), sourcing_name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009872 verbose_leave();
9873 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009874 }
9875
9876 apc->curpat = ap;
9877 apc->nextcmd = ap->cmds;
9878 /* mark last command */
9879 for (cp = ap->cmds; cp->next != NULL; cp = cp->next)
9880 cp->last = FALSE;
9881 cp->last = TRUE;
9882 }
9883 line_breakcheck();
9884 if (apc->curpat != NULL) /* found a match */
9885 break;
9886 }
9887 if (stop_at_last && ap->last)
9888 break;
9889 }
9890}
9891
9892/*
9893 * Get next autocommand command.
9894 * Called by do_cmdline() to get the next line for ":if".
9895 * Returns allocated string, or NULL for end of autocommands.
9896 */
Bram Moolenaar21691f82012-12-05 19:13:18 +01009897 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009898getnextac(int c UNUSED, void *cookie, int indent UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009899{
9900 AutoPatCmd *acp = (AutoPatCmd *)cookie;
9901 char_u *retval;
9902 AutoCmd *ac;
9903
9904 /* Can be called again after returning the last line. */
9905 if (acp->curpat == NULL)
9906 return NULL;
9907
9908 /* repeat until we find an autocommand to execute */
9909 for (;;)
9910 {
9911 /* skip removed commands */
9912 while (acp->nextcmd != NULL && acp->nextcmd->cmd == NULL)
9913 if (acp->nextcmd->last)
9914 acp->nextcmd = NULL;
9915 else
9916 acp->nextcmd = acp->nextcmd->next;
9917
9918 if (acp->nextcmd != NULL)
9919 break;
9920
9921 /* at end of commands, find next pattern that matches */
9922 if (acp->curpat->last)
9923 acp->curpat = NULL;
9924 else
9925 acp->curpat = acp->curpat->next;
9926 if (acp->curpat != NULL)
9927 auto_next_pat(acp, TRUE);
9928 if (acp->curpat == NULL)
9929 return NULL;
9930 }
9931
9932 ac = acp->nextcmd;
9933
9934 if (p_verbose >= 9)
9935 {
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009936 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009937 smsg((char_u *)_("autocommand %s"), ac->cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009938 msg_puts((char_u *)"\n"); /* don't overwrite this either */
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009939 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009940 }
9941 retval = vim_strsave(ac->cmd);
9942 autocmd_nested = ac->nested;
9943#ifdef FEAT_EVAL
Bram Moolenaarf29c1c62018-09-10 21:05:02 +02009944 current_sctx = ac->script_ctx;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009945#endif
9946 if (ac->last)
9947 acp->nextcmd = NULL;
9948 else
9949 acp->nextcmd = ac->next;
9950 return retval;
9951}
9952
9953/*
9954 * Return TRUE if there is a matching autocommand for "fname".
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009955 * To account for buffer-local autocommands, function needs to know
9956 * in which buffer the file will be opened.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009957 */
9958 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009959has_autocmd(event_T event, char_u *sfname, buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009960{
9961 AutoPat *ap;
9962 char_u *fname;
9963 char_u *tail = gettail(sfname);
9964 int retval = FALSE;
9965
9966 fname = FullName_save(sfname, FALSE);
9967 if (fname == NULL)
9968 return FALSE;
9969
9970#ifdef BACKSLASH_IN_FILENAME
9971 /*
9972 * Replace all backslashes with forward slashes. This makes the
9973 * autocommand patterns portable between Unix and MS-DOS.
9974 */
9975 sfname = vim_strsave(sfname);
9976 if (sfname != NULL)
9977 forward_slash(sfname);
9978 forward_slash(fname);
9979#endif
9980
9981 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
9982 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009983 && (ap->buflocal_nr == 0
Bram Moolenaardffa5b82014-11-19 16:38:07 +01009984 ? match_file_pat(NULL, &ap->reg_prog,
Bram Moolenaar748bf032005-02-02 23:04:36 +00009985 fname, sfname, tail, ap->allow_dirs)
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009986 : buf != NULL && ap->buflocal_nr == buf->b_fnum
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009987 ))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009988 {
9989 retval = TRUE;
9990 break;
9991 }
9992
9993 vim_free(fname);
9994#ifdef BACKSLASH_IN_FILENAME
9995 vim_free(sfname);
9996#endif
9997
9998 return retval;
9999}
10000
10001#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
10002/*
10003 * Function given to ExpandGeneric() to obtain the list of autocommand group
10004 * names.
10005 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010006 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010007get_augroup_name(expand_T *xp UNUSED, int idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010008{
10009 if (idx == augroups.ga_len) /* add "END" add the end */
10010 return (char_u *)"END";
10011 if (idx >= augroups.ga_len) /* end of list */
10012 return NULL;
Bram Moolenaarb62cc362016-09-03 16:43:53 +020010013 if (AUGROUP_NAME(idx) == NULL || AUGROUP_NAME(idx) == get_deleted_augroup())
Bram Moolenaarf2c4c392016-07-29 20:50:24 +020010014 /* skip deleted entries */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010015 return (char_u *)"";
10016 return AUGROUP_NAME(idx); /* return a name */
10017}
10018
10019static int include_groups = FALSE;
10020
10021 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010022set_context_in_autocmd(
10023 expand_T *xp,
10024 char_u *arg,
10025 int doautocmd) /* TRUE for :doauto*, FALSE for :autocmd */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010026{
10027 char_u *p;
10028 int group;
10029
10030 /* check for a group name, skip it if present */
10031 include_groups = FALSE;
10032 p = arg;
10033 group = au_get_grouparg(&arg);
10034 if (group == AUGROUP_ERROR)
10035 return NULL;
10036 /* If there only is a group name that's what we expand. */
Bram Moolenaar1c465442017-03-12 20:10:05 +010010037 if (*arg == NUL && group != AUGROUP_ALL && !VIM_ISWHITE(arg[-1]))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010038 {
10039 arg = p;
10040 group = AUGROUP_ALL;
10041 }
10042
10043 /* skip over event name */
Bram Moolenaar1c465442017-03-12 20:10:05 +010010044 for (p = arg; *p != NUL && !VIM_ISWHITE(*p); ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010045 if (*p == ',')
10046 arg = p + 1;
10047 if (*p == NUL)
10048 {
10049 if (group == AUGROUP_ALL)
10050 include_groups = TRUE;
10051 xp->xp_context = EXPAND_EVENTS; /* expand event name */
10052 xp->xp_pattern = arg;
10053 return NULL;
10054 }
10055
10056 /* skip over pattern */
10057 arg = skipwhite(p);
Bram Moolenaar1c465442017-03-12 20:10:05 +010010058 while (*arg && (!VIM_ISWHITE(*arg) || arg[-1] == '\\'))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010059 arg++;
10060 if (*arg)
10061 return arg; /* expand (next) command */
10062
10063 if (doautocmd)
10064 xp->xp_context = EXPAND_FILES; /* expand file names */
10065 else
10066 xp->xp_context = EXPAND_NOTHING; /* pattern is not expanded */
10067 return NULL;
10068}
10069
10070/*
10071 * Function given to ExpandGeneric() to obtain the list of event names.
10072 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010073 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010074get_event_name(expand_T *xp UNUSED, int idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010075{
10076 if (idx < augroups.ga_len) /* First list group names, if wanted */
10077 {
Bram Moolenaarf2c4c392016-07-29 20:50:24 +020010078 if (!include_groups || AUGROUP_NAME(idx) == NULL
Bram Moolenaarb62cc362016-09-03 16:43:53 +020010079 || AUGROUP_NAME(idx) == get_deleted_augroup())
Bram Moolenaar071d4272004-06-13 20:20:40 +000010080 return (char_u *)""; /* skip deleted entries */
10081 return AUGROUP_NAME(idx); /* return a name */
10082 }
10083 return (char_u *)event_names[idx - augroups.ga_len].name;
10084}
10085
10086#endif /* FEAT_CMDL_COMPL */
10087
10088/*
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010089 * Return TRUE if autocmd is supported.
10090 */
10091 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010092autocmd_supported(char_u *name)
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010093{
10094 char_u *p;
10095
10096 return (event_name2nr(name, &p) != NUM_EVENTS);
10097}
10098
10099/*
Bram Moolenaar195d6352005-12-19 22:08:24 +000010100 * Return TRUE if an autocommand is defined for a group, event and
10101 * pattern: The group can be omitted to accept any group. "event" and "pattern"
10102 * can be NULL to accept any event and pattern. "pattern" can be NULL to accept
10103 * any pattern. Buffer-local patterns <buffer> or <buffer=N> are accepted.
10104 * Used for:
10105 * exists("#Group") or
10106 * exists("#Group#Event") or
10107 * exists("#Group#Event#pat") or
10108 * exists("#Event") or
10109 * exists("#Event#pat")
Bram Moolenaar071d4272004-06-13 20:20:40 +000010110 */
10111 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010112au_exists(char_u *arg)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010113{
Bram Moolenaar195d6352005-12-19 22:08:24 +000010114 char_u *arg_save;
10115 char_u *pattern = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010116 char_u *event_name;
10117 char_u *p;
Bram Moolenaar754b5602006-02-09 23:53:20 +000010118 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010119 AutoPat *ap;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010120 buf_T *buflocal_buf = NULL;
Bram Moolenaar195d6352005-12-19 22:08:24 +000010121 int group;
10122 int retval = FALSE;
10123
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010124 /* Make a copy so that we can change the '#' chars to a NUL. */
Bram Moolenaar195d6352005-12-19 22:08:24 +000010125 arg_save = vim_strsave(arg);
10126 if (arg_save == NULL)
10127 return FALSE;
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010128 p = vim_strchr(arg_save, '#');
Bram Moolenaar195d6352005-12-19 22:08:24 +000010129 if (p != NULL)
10130 *p++ = NUL;
10131
10132 /* First, look for an autocmd group name */
10133 group = au_find_group(arg_save);
10134 if (group == AUGROUP_ERROR)
10135 {
10136 /* Didn't match a group name, assume the first argument is an event. */
10137 group = AUGROUP_ALL;
10138 event_name = arg_save;
10139 }
10140 else
10141 {
10142 if (p == NULL)
10143 {
10144 /* "Group": group name is present and it's recognized */
10145 retval = TRUE;
10146 goto theend;
10147 }
10148
10149 /* Must be "Group#Event" or "Group#Event#pat". */
10150 event_name = p;
10151 p = vim_strchr(event_name, '#');
10152 if (p != NULL)
10153 *p++ = NUL; /* "Group#Event#pat" */
10154 }
10155
10156 pattern = p; /* "pattern" is NULL when there is no pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010157
10158 /* find the index (enum) for the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010159 event = event_name2nr(event_name, &p);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010160
10161 /* return FALSE if the event name is not recognized */
Bram Moolenaar195d6352005-12-19 22:08:24 +000010162 if (event == NUM_EVENTS)
10163 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010164
10165 /* Find the first autocommand for this event.
10166 * If there isn't any, return FALSE;
10167 * If there is one and no pattern given, return TRUE; */
10168 ap = first_autopat[(int)event];
10169 if (ap == NULL)
Bram Moolenaar195d6352005-12-19 22:08:24 +000010170 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010171
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010172 /* if pattern is "<buffer>", special handling is needed which uses curbuf */
10173 /* for pattern "<buffer=N>, fnamecmp() will work fine */
Bram Moolenaar5b7880d2009-09-11 15:24:31 +000010174 if (pattern != NULL && STRICMP(pattern, "<buffer>") == 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010175 buflocal_buf = curbuf;
10176
Bram Moolenaar071d4272004-06-13 20:20:40 +000010177 /* Check if there is an autocommand with the given pattern. */
10178 for ( ; ap != NULL; ap = ap->next)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010179 /* only use a pattern when it has not been removed and has commands. */
10180 /* For buffer-local autocommands, fnamecmp() works fine. */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010181 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaar195d6352005-12-19 22:08:24 +000010182 && (group == AUGROUP_ALL || ap->group == group)
Bram Moolenaar5b7880d2009-09-11 15:24:31 +000010183 && (pattern == NULL
10184 || (buflocal_buf == NULL
10185 ? fnamecmp(ap->pat, pattern) == 0
10186 : ap->buflocal_nr == buflocal_buf->b_fnum)))
Bram Moolenaar195d6352005-12-19 22:08:24 +000010187 {
10188 retval = TRUE;
10189 break;
10190 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010191
Bram Moolenaar195d6352005-12-19 22:08:24 +000010192theend:
10193 vim_free(arg_save);
10194 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010195}
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010196
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010197
10198/*
Bram Moolenaar748bf032005-02-02 23:04:36 +000010199 * Try matching a filename with a "pattern" ("prog" is NULL), or use the
10200 * precompiled regprog "prog" ("pattern" is NULL). That avoids calling
10201 * vim_regcomp() often.
Bram Moolenaar071d4272004-06-13 20:20:40 +000010202 * Used for autocommands and 'wildignore'.
10203 * Returns TRUE if there is a match, FALSE otherwise.
10204 */
Bram Moolenaardffa5b82014-11-19 16:38:07 +010010205 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010206match_file_pat(
10207 char_u *pattern, /* pattern to match with */
10208 regprog_T **prog, /* pre-compiled regprog or NULL */
10209 char_u *fname, /* full path of file name */
10210 char_u *sfname, /* short file name or NULL */
10211 char_u *tail, /* tail of path */
10212 int allow_dirs) /* allow matching with dir */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010213{
10214 regmatch_T regmatch;
10215 int result = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010216
Bram Moolenaar71afbfe2013-03-19 16:49:16 +010010217 regmatch.rm_ic = p_fic; /* ignore case if 'fileignorecase' is set */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010218 if (prog != NULL)
10219 regmatch.regprog = *prog;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010220 else
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010221 regmatch.regprog = vim_regcomp(pattern, RE_MAGIC);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010222
10223 /*
10224 * Try for a match with the pattern with:
10225 * 1. the full file name, when the pattern has a '/'.
10226 * 2. the short file name, when the pattern has a '/'.
10227 * 3. the tail of the file name, when the pattern has no '/'.
10228 */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010229 if (regmatch.regprog != NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +000010230 && ((allow_dirs
10231 && (vim_regexec(&regmatch, fname, (colnr_T)0)
10232 || (sfname != NULL
10233 && vim_regexec(&regmatch, sfname, (colnr_T)0))))
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010234 || (!allow_dirs && vim_regexec(&regmatch, tail, (colnr_T)0))))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010235 result = TRUE;
10236
Bram Moolenaardffa5b82014-11-19 16:38:07 +010010237 if (prog != NULL)
10238 *prog = regmatch.regprog;
10239 else
Bram Moolenaar473de612013-06-08 18:19:48 +020010240 vim_regfree(regmatch.regprog);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010241 return result;
10242}
Bram Moolenaar071d4272004-06-13 20:20:40 +000010243
10244#if defined(FEAT_WILDIGN) || defined(PROTO)
10245/*
10246 * Return TRUE if a file matches with a pattern in "list".
10247 * "list" is a comma-separated list of patterns, like 'wildignore'.
10248 * "sfname" is the short file name or NULL, "ffname" the long file name.
10249 */
10250 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010251match_file_list(char_u *list, char_u *sfname, char_u *ffname)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010252{
10253 char_u buf[100];
10254 char_u *tail;
10255 char_u *regpat;
10256 char allow_dirs;
10257 int match;
10258 char_u *p;
10259
10260 tail = gettail(sfname);
10261
10262 /* try all patterns in 'wildignore' */
10263 p = list;
10264 while (*p)
10265 {
10266 copy_option_part(&p, buf, 100, ",");
10267 regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, FALSE);
10268 if (regpat == NULL)
10269 break;
Bram Moolenaar748bf032005-02-02 23:04:36 +000010270 match = match_file_pat(regpat, NULL, ffname, sfname,
10271 tail, (int)allow_dirs);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010272 vim_free(regpat);
10273 if (match)
10274 return TRUE;
10275 }
10276 return FALSE;
10277}
10278#endif
10279
10280/*
10281 * Convert the given pattern "pat" which has shell style wildcards in it, into
10282 * a regular expression, and return the result in allocated memory. If there
10283 * is a directory path separator to be matched, then TRUE is put in
10284 * allow_dirs, otherwise FALSE is put there -- webb.
10285 * Handle backslashes before special characters, like "\*" and "\ ".
10286 *
Bram Moolenaar071d4272004-06-13 20:20:40 +000010287 * Returns NULL when out of memory.
10288 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010289 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010290file_pat_to_reg_pat(
10291 char_u *pat,
10292 char_u *pat_end, /* first char after pattern or NULL */
10293 char *allow_dirs, /* Result passed back out in here */
10294 int no_bslash UNUSED) /* Don't use a backward slash as pathsep */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010295{
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010296 int size = 2; /* '^' at start, '$' at end */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010297 char_u *endp;
10298 char_u *reg_pat;
10299 char_u *p;
10300 int i;
10301 int nested = 0;
10302 int add_dollar = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010303
10304 if (allow_dirs != NULL)
10305 *allow_dirs = FALSE;
10306 if (pat_end == NULL)
10307 pat_end = pat + STRLEN(pat);
10308
Bram Moolenaar071d4272004-06-13 20:20:40 +000010309 for (p = pat; p < pat_end; p++)
10310 {
10311 switch (*p)
10312 {
10313 case '*':
10314 case '.':
10315 case ',':
10316 case '{':
10317 case '}':
10318 case '~':
10319 size += 2; /* extra backslash */
10320 break;
10321#ifdef BACKSLASH_IN_FILENAME
10322 case '\\':
10323 case '/':
10324 size += 4; /* could become "[\/]" */
10325 break;
10326#endif
10327 default:
10328 size++;
Bram Moolenaar2288afe2015-08-11 16:20:05 +020010329# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010330 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010331 {
10332 ++p;
10333 ++size;
10334 }
10335# endif
10336 break;
10337 }
10338 }
10339 reg_pat = alloc(size + 1);
10340 if (reg_pat == NULL)
10341 return NULL;
10342
Bram Moolenaar071d4272004-06-13 20:20:40 +000010343 i = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010344
10345 if (pat[0] == '*')
10346 while (pat[0] == '*' && pat < pat_end - 1)
10347 pat++;
10348 else
10349 reg_pat[i++] = '^';
10350 endp = pat_end - 1;
Bram Moolenaar8fee8782015-08-11 18:45:48 +020010351 if (endp >= pat && *endp == '*')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010352 {
10353 while (endp - pat > 0 && *endp == '*')
10354 endp--;
10355 add_dollar = FALSE;
10356 }
10357 for (p = pat; *p && nested >= 0 && p <= endp; p++)
10358 {
10359 switch (*p)
10360 {
10361 case '*':
10362 reg_pat[i++] = '.';
10363 reg_pat[i++] = '*';
Bram Moolenaar02743632005-07-25 20:42:36 +000010364 while (p[1] == '*') /* "**" matches like "*" */
10365 ++p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010366 break;
10367 case '.':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010368 case '~':
10369 reg_pat[i++] = '\\';
10370 reg_pat[i++] = *p;
10371 break;
10372 case '?':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010373 reg_pat[i++] = '.';
10374 break;
10375 case '\\':
10376 if (p[1] == NUL)
10377 break;
10378#ifdef BACKSLASH_IN_FILENAME
10379 if (!no_bslash)
10380 {
10381 /* translate:
10382 * "\x" to "\\x" e.g., "dir\file"
10383 * "\*" to "\\.*" e.g., "dir\*.c"
10384 * "\?" to "\\." e.g., "dir\??.c"
10385 * "\+" to "\+" e.g., "fileX\+.c"
10386 */
10387 if ((vim_isfilec(p[1]) || p[1] == '*' || p[1] == '?')
10388 && p[1] != '+')
10389 {
10390 reg_pat[i++] = '[';
10391 reg_pat[i++] = '\\';
10392 reg_pat[i++] = '/';
10393 reg_pat[i++] = ']';
10394 if (allow_dirs != NULL)
10395 *allow_dirs = TRUE;
10396 break;
10397 }
10398 }
10399#endif
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010400 /* Undo escaping from ExpandEscape():
10401 * foo\?bar -> foo?bar
10402 * foo\%bar -> foo%bar
10403 * foo\,bar -> foo,bar
10404 * foo\ bar -> foo bar
10405 * Don't unescape \, * and others that are also special in a
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010406 * regexp.
10407 * An escaped { must be unescaped since we use magic not
Bram Moolenaara946afe2013-08-02 15:22:39 +020010408 * verymagic. Use "\\\{n,m\}"" to get "\{n,m}".
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010409 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010410 if (*++p == '?'
10411#ifdef BACKSLASH_IN_FILENAME
10412 && no_bslash
10413#endif
10414 )
10415 reg_pat[i++] = '?';
10416 else
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010417 if (*p == ',' || *p == '%' || *p == '#'
Bram Moolenaar2288afe2015-08-11 16:20:05 +020010418 || vim_isspace(*p) || *p == '{' || *p == '}')
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010419 reg_pat[i++] = *p;
Bram Moolenaara946afe2013-08-02 15:22:39 +020010420 else if (*p == '\\' && p[1] == '\\' && p[2] == '{')
10421 {
10422 reg_pat[i++] = '\\';
10423 reg_pat[i++] = '{';
10424 p += 2;
10425 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010426 else
10427 {
10428 if (allow_dirs != NULL && vim_ispathsep(*p)
10429#ifdef BACKSLASH_IN_FILENAME
10430 && (!no_bslash || *p != '\\')
10431#endif
10432 )
10433 *allow_dirs = TRUE;
10434 reg_pat[i++] = '\\';
10435 reg_pat[i++] = *p;
10436 }
10437 break;
10438#ifdef BACKSLASH_IN_FILENAME
10439 case '/':
10440 reg_pat[i++] = '[';
10441 reg_pat[i++] = '\\';
10442 reg_pat[i++] = '/';
10443 reg_pat[i++] = ']';
10444 if (allow_dirs != NULL)
10445 *allow_dirs = TRUE;
10446 break;
10447#endif
10448 case '{':
10449 reg_pat[i++] = '\\';
10450 reg_pat[i++] = '(';
10451 nested++;
10452 break;
10453 case '}':
10454 reg_pat[i++] = '\\';
10455 reg_pat[i++] = ')';
10456 --nested;
10457 break;
10458 case ',':
10459 if (nested)
10460 {
10461 reg_pat[i++] = '\\';
10462 reg_pat[i++] = '|';
10463 }
10464 else
10465 reg_pat[i++] = ',';
10466 break;
10467 default:
10468# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010469 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010470 reg_pat[i++] = *p++;
10471 else
10472# endif
10473 if (allow_dirs != NULL && vim_ispathsep(*p))
10474 *allow_dirs = TRUE;
10475 reg_pat[i++] = *p;
10476 break;
10477 }
10478 }
10479 if (add_dollar)
10480 reg_pat[i++] = '$';
10481 reg_pat[i] = NUL;
10482 if (nested != 0)
10483 {
10484 if (nested < 0)
10485 EMSG(_("E219: Missing {."));
10486 else
10487 EMSG(_("E220: Missing }."));
Bram Moolenaard23a8232018-02-10 18:45:26 +010010488 VIM_CLEAR(reg_pat);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010489 }
10490 return reg_pat;
10491}
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010492
10493#if defined(EINTR) || defined(PROTO)
10494/*
10495 * Version of read() that retries when interrupted by EINTR (possibly
10496 * by a SIGWINCH).
10497 */
10498 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010499read_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010500{
10501 long ret;
10502
10503 for (;;)
10504 {
10505 ret = vim_read(fd, buf, bufsize);
10506 if (ret >= 0 || errno != EINTR)
10507 break;
10508 }
10509 return ret;
10510}
10511
10512/*
10513 * Version of write() that retries when interrupted by EINTR (possibly
10514 * by a SIGWINCH).
10515 */
10516 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010517write_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010518{
10519 long ret = 0;
10520 long wlen;
10521
10522 /* Repeat the write() so long it didn't fail, other than being interrupted
10523 * by a signal. */
10524 while (ret < (long)bufsize)
10525 {
Bram Moolenaar9c263032010-12-17 18:06:06 +010010526 wlen = vim_write(fd, (char *)buf + ret, bufsize - ret);
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010527 if (wlen < 0)
10528 {
10529 if (errno != EINTR)
10530 break;
10531 }
10532 else
10533 ret += wlen;
10534 }
10535 return ret;
10536}
10537#endif