blob: ab216abbf6984438d9b6ce3fac14799a71a828e3 [file] [log] [blame]
Bram Moolenaaredf3f972016-08-29 22:49:24 +02001/* vi:set ts=8 sts=4 sw=4 noet:
Bram Moolenaar071d4272004-06-13 20:20:40 +00002 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
11 * fileio.c: read from and write to a file
12 */
13
Bram Moolenaar071d4272004-06-13 20:20:40 +000014#include "vim.h"
15
Bram Moolenaarf4888d02009-12-02 12:31:27 +000016#if defined(__TANDEM) || defined(__MINT__)
Bram Moolenaar071d4272004-06-13 20:20:40 +000017# include <limits.h> /* for SSIZE_MAX */
18#endif
19
20#if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
21# include <utime.h> /* for struct utimbuf */
22#endif
23
24#define BUFSIZE 8192 /* size of normal write buffer */
25#define SMBUFSIZE 256 /* size of emergency write buffer */
26
Bram Moolenaar071d4272004-06-13 20:20:40 +000027/* Is there any system that doesn't have access()? */
Bram Moolenaar9372a112005-12-06 19:59:18 +000028#define USE_MCH_ACCESS
Bram Moolenaar071d4272004-06-13 20:20:40 +000029
30#ifdef FEAT_MBYTE
Bram Moolenaard25c16e2016-01-29 22:13:30 +010031static char_u *next_fenc(char_u **pp);
Bram Moolenaar071d4272004-06-13 20:20:40 +000032# ifdef FEAT_EVAL
Bram Moolenaard25c16e2016-01-29 22:13:30 +010033static char_u *readfile_charconvert(char_u *fname, char_u *fenc, int *fdp);
Bram Moolenaar071d4272004-06-13 20:20:40 +000034# endif
35#endif
36#ifdef FEAT_VIMINFO
Bram Moolenaard25c16e2016-01-29 22:13:30 +010037static void check_marks_read(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +000038#endif
39#ifdef FEAT_CRYPT
Bram Moolenaar8767f522016-07-01 17:17:39 +020040static char_u *check_for_cryptkey(char_u *cryptkey, char_u *ptr, long *sizep, off_T *filesizep, int newfile, char_u *fname, int *did_ask);
Bram Moolenaar071d4272004-06-13 20:20:40 +000041#endif
42#ifdef UNIX
Bram Moolenaard25c16e2016-01-29 22:13:30 +010043static void set_file_time(char_u *fname, time_t atime, time_t mtime);
Bram Moolenaar071d4272004-06-13 20:20:40 +000044#endif
Bram Moolenaard25c16e2016-01-29 22:13:30 +010045static int set_rw_fname(char_u *fname, char_u *sfname);
46static int msg_add_fileformat(int eol_type);
47static void msg_add_eol(void);
Bram Moolenaar8767f522016-07-01 17:17:39 +020048static int check_mtime(buf_T *buf, stat_T *s);
Bram Moolenaard25c16e2016-01-29 22:13:30 +010049static int time_differs(long t1, long t2);
Bram Moolenaar071d4272004-06-13 20:20:40 +000050#ifdef FEAT_AUTOCMD
Bram Moolenaard25c16e2016-01-29 22:13:30 +010051static int apply_autocmds_exarg(event_T event, char_u *fname, char_u *fname_io, int force, buf_T *buf, exarg_T *eap);
52static int au_find_group(char_u *name);
Bram Moolenaar70836c82006-02-20 21:28:49 +000053
54# define AUGROUP_DEFAULT -1 /* default autocmd group */
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +000055# define AUGROUP_ERROR -2 /* erroneous autocmd group */
Bram Moolenaar70836c82006-02-20 21:28:49 +000056# define AUGROUP_ALL -3 /* all autocmd groups */
Bram Moolenaar071d4272004-06-13 20:20:40 +000057#endif
58
59#if defined(FEAT_CRYPT) || defined(FEAT_MBYTE)
60# define HAS_BW_FLAGS
61# define FIO_LATIN1 0x01 /* convert Latin1 */
62# define FIO_UTF8 0x02 /* convert UTF-8 */
63# define FIO_UCS2 0x04 /* convert UCS-2 */
64# define FIO_UCS4 0x08 /* convert UCS-4 */
65# define FIO_UTF16 0x10 /* convert UTF-16 */
66# ifdef WIN3264
67# define FIO_CODEPAGE 0x20 /* convert MS-Windows codepage */
68# define FIO_PUT_CP(x) (((x) & 0xffff) << 16) /* put codepage in top word */
69# define FIO_GET_CP(x) (((x)>>16) & 0xffff) /* get codepage from top word */
70# endif
Bram Moolenaard0573012017-10-28 21:11:06 +020071# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +000072# define FIO_MACROMAN 0x20 /* convert MacRoman */
73# endif
74# define FIO_ENDIAN_L 0x80 /* little endian */
75# define FIO_ENCRYPTED 0x1000 /* encrypt written bytes */
76# define FIO_NOCONVERT 0x2000 /* skip encoding conversion */
77# define FIO_UCSBOM 0x4000 /* check for BOM at start of file */
78# define FIO_ALL -1 /* allow all formats */
79#endif
80
81/* When converting, a read() or write() may leave some bytes to be converted
82 * for the next call. The value is guessed... */
83#define CONV_RESTLEN 30
84
85/* We have to guess how much a sequence of bytes may expand when converting
86 * with iconv() to be able to allocate a buffer. */
87#define ICONV_MULT 8
88
89/*
90 * Structure to pass arguments from buf_write() to buf_write_bytes().
91 */
92struct bw_info
93{
94 int bw_fd; /* file descriptor */
95 char_u *bw_buf; /* buffer with data to be written */
Bram Moolenaard089d9b2007-09-30 12:02:55 +000096 int bw_len; /* length of data */
Bram Moolenaar071d4272004-06-13 20:20:40 +000097#ifdef HAS_BW_FLAGS
98 int bw_flags; /* FIO_ flags */
99#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +0200100#ifdef FEAT_CRYPT
101 buf_T *bw_buffer; /* buffer being written */
102#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000103#ifdef FEAT_MBYTE
104 char_u bw_rest[CONV_RESTLEN]; /* not converted bytes */
105 int bw_restlen; /* nr of bytes in bw_rest[] */
106 int bw_first; /* first write call */
107 char_u *bw_conv_buf; /* buffer for writing converted chars */
108 int bw_conv_buflen; /* size of bw_conv_buf */
109 int bw_conv_error; /* set for conversion error */
Bram Moolenaar32b485f2009-07-29 16:06:27 +0000110 linenr_T bw_conv_error_lnum; /* first line with error or zero */
111 linenr_T bw_start_lnum; /* line number at start of buffer */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000112# ifdef USE_ICONV
113 iconv_t bw_iconv_fd; /* descriptor for iconv() or -1 */
114# endif
115#endif
116};
117
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100118static int buf_write_bytes(struct bw_info *ip);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000119
120#ifdef FEAT_MBYTE
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100121static linenr_T readfile_linenr(linenr_T linecnt, char_u *p, char_u *endp);
122static int ucs2bytes(unsigned c, char_u **pp, int flags);
123static int need_conversion(char_u *fenc);
124static int get_fio_flags(char_u *ptr);
125static char_u *check_for_bom(char_u *p, long size, int *lenp, int flags);
126static int make_bom(char_u *buf, char_u *name);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000127# ifdef WIN3264
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100128static int get_win_fio_flags(char_u *ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000129# endif
Bram Moolenaard0573012017-10-28 21:11:06 +0200130# ifdef MACOS_CONVERT
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100131static int get_mac_fio_flags(char_u *ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000132# endif
133#endif
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100134static int move_lines(buf_T *frombuf, buf_T *tobuf);
Bram Moolenaar4592dee2009-11-18 19:11:58 +0000135#ifdef TEMPDIRNAMES
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100136static void vim_settempdir(char_u *tempdir);
Bram Moolenaar4592dee2009-11-18 19:11:58 +0000137#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000138#ifdef FEAT_AUTOCMD
139static char *e_auchangedbuf = N_("E812: Autocommands changed buffer or buffer name");
140#endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000141
Bram Moolenaarc3691332016-04-20 12:49:49 +0200142#ifdef FEAT_AUTOCMD
143/*
144 * Set by the apply_autocmds_group function if the given event is equal to
145 * EVENT_FILETYPE. Used by the readfile function in order to determine if
146 * EVENT_BUFREADPOST triggered the EVENT_FILETYPE.
147 *
148 * Relying on this value requires one to reset it prior calling
149 * apply_autocmds_group.
150 */
151static int au_did_filetype INIT(= FALSE);
152#endif
153
Bram Moolenaar071d4272004-06-13 20:20:40 +0000154 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +0100155filemess(
156 buf_T *buf,
157 char_u *name,
158 char_u *s,
159 int attr)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000160{
161 int msg_scroll_save;
162
163 if (msg_silent != 0)
164 return;
165 msg_add_fname(buf, name); /* put file name in IObuff with quotes */
166 /* If it's extremely long, truncate it. */
167 if (STRLEN(IObuff) > IOSIZE - 80)
168 IObuff[IOSIZE - 80] = NUL;
169 STRCAT(IObuff, s);
170 /*
171 * For the first message may have to start a new line.
172 * For further ones overwrite the previous one, reset msg_scroll before
173 * calling filemess().
174 */
175 msg_scroll_save = msg_scroll;
176 if (shortmess(SHM_OVERALL) && !exiting && p_verbose == 0)
177 msg_scroll = FALSE;
178 if (!msg_scroll) /* wait a bit when overwriting an error msg */
179 check_for_delay(FALSE);
180 msg_start();
181 msg_scroll = msg_scroll_save;
182 msg_scrolled_ign = TRUE;
183 /* may truncate the message to avoid a hit-return prompt */
184 msg_outtrans_attr(msg_may_trunc(FALSE, IObuff), attr);
185 msg_clr_eos();
186 out_flush();
187 msg_scrolled_ign = FALSE;
188}
189
190/*
191 * Read lines from file "fname" into the buffer after line "from".
192 *
193 * 1. We allocate blocks with lalloc, as big as possible.
194 * 2. Each block is filled with characters from the file with a single read().
195 * 3. The lines are inserted in the buffer with ml_append().
196 *
197 * (caller must check that fname != NULL, unless READ_STDIN is used)
198 *
199 * "lines_to_skip" is the number of lines that must be skipped
200 * "lines_to_read" is the number of lines that are appended
201 * When not recovering lines_to_skip is 0 and lines_to_read MAXLNUM.
202 *
203 * flags:
204 * READ_NEW starting to edit a new buffer
205 * READ_FILTER reading filter output
206 * READ_STDIN read from stdin instead of a file
207 * READ_BUFFER read from curbuf instead of a file (converting after reading
208 * stdin)
209 * READ_DUMMY read into a dummy buffer (to check if file contents changed)
Bram Moolenaar59f931e2010-07-24 20:27:03 +0200210 * READ_KEEP_UNDO don't clear undo info or read it from a file
Bram Moolenaarf71d7b92016-08-09 22:14:05 +0200211 * READ_FIFO read from fifo/socket instead of a file
Bram Moolenaar071d4272004-06-13 20:20:40 +0000212 *
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100213 * return FAIL for failure, NOTDONE for directory (failure), or OK
Bram Moolenaar071d4272004-06-13 20:20:40 +0000214 */
215 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +0100216readfile(
217 char_u *fname,
218 char_u *sfname,
219 linenr_T from,
220 linenr_T lines_to_skip,
221 linenr_T lines_to_read,
222 exarg_T *eap, /* can be NULL! */
223 int flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000224{
225 int fd = 0;
226 int newfile = (flags & READ_NEW);
227 int check_readonly;
228 int filtering = (flags & READ_FILTER);
229 int read_stdin = (flags & READ_STDIN);
230 int read_buffer = (flags & READ_BUFFER);
Bram Moolenaarf71d7b92016-08-09 22:14:05 +0200231 int read_fifo = (flags & READ_FIFO);
Bram Moolenaar690ffc02008-01-04 15:31:21 +0000232 int set_options = newfile || read_buffer
233 || (eap != NULL && eap->read_edit);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000234 linenr_T read_buf_lnum = 1; /* next line to read from curbuf */
235 colnr_T read_buf_col = 0; /* next char to read from this line */
236 char_u c;
237 linenr_T lnum = from;
238 char_u *ptr = NULL; /* pointer into read buffer */
239 char_u *buffer = NULL; /* read buffer */
240 char_u *new_buffer = NULL; /* init to shut up gcc */
241 char_u *line_start = NULL; /* init to shut up gcc */
242 int wasempty; /* buffer was empty before reading */
243 colnr_T len;
244 long size = 0;
245 char_u *p;
Bram Moolenaar8767f522016-07-01 17:17:39 +0200246 off_T filesize = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000247 int skip_read = FALSE;
248#ifdef FEAT_CRYPT
249 char_u *cryptkey = NULL;
Bram Moolenaarf50a2532010-05-21 15:36:08 +0200250 int did_ask_for_key = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000251#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +0200252#ifdef FEAT_PERSISTENT_UNDO
253 context_sha256_T sha_ctx;
254 int read_undo_file = FALSE;
255#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000256 int split = 0; /* number of split lines */
257#define UNKNOWN 0x0fffffff /* file size is unknown */
258 linenr_T linecnt;
259 int error = FALSE; /* errors encountered */
260 int ff_error = EOL_UNKNOWN; /* file format with errors */
261 long linerest = 0; /* remaining chars in line */
262#ifdef UNIX
263 int perm = 0;
264 int swap_mode = -1; /* protection bits for swap file */
265#else
266 int perm;
267#endif
268 int fileformat = 0; /* end-of-line format */
269 int keep_fileformat = FALSE;
Bram Moolenaar8767f522016-07-01 17:17:39 +0200270 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000271 int file_readonly;
272 linenr_T skip_count = 0;
273 linenr_T read_count = 0;
274 int msg_save = msg_scroll;
275 linenr_T read_no_eol_lnum = 0; /* non-zero lnum when last line of
276 * last read was missing the eol */
Bram Moolenaar7a2699e2017-01-23 21:31:09 +0100277 int try_mac;
278 int try_dos;
279 int try_unix;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000280 int file_rewind = FALSE;
281#ifdef FEAT_MBYTE
282 int can_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000283 linenr_T conv_error = 0; /* line nr with conversion error */
284 linenr_T illegal_byte = 0; /* line nr with illegal byte */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000285 int keep_dest_enc = FALSE; /* don't retry when char doesn't fit
286 in destination encoding */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000287 int bad_char_behavior = BAD_REPLACE;
288 /* BAD_KEEP, BAD_DROP or character to
289 * replace with */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000290 char_u *tmpname = NULL; /* name of 'charconvert' output file */
291 int fio_flags = 0;
292 char_u *fenc; /* fileencoding to use */
293 int fenc_alloced; /* fenc_next is in allocated memory */
294 char_u *fenc_next = NULL; /* next item in 'fencs' or NULL */
295 int advance_fenc = FALSE;
296 long real_size = 0;
297# ifdef USE_ICONV
298 iconv_t iconv_fd = (iconv_t)-1; /* descriptor for iconv() or -1 */
299# ifdef FEAT_EVAL
300 int did_iconv = FALSE; /* TRUE when iconv() failed and trying
301 'charconvert' next */
302# endif
303# endif
304 int converted = FALSE; /* TRUE if conversion done */
305 int notconverted = FALSE; /* TRUE if conversion wanted but it
306 wasn't possible */
307 char_u conv_rest[CONV_RESTLEN];
308 int conv_restlen = 0; /* nr of bytes in conv_rest[] */
309#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000310#ifdef FEAT_AUTOCMD
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200311 buf_T *old_curbuf;
312 char_u *old_b_ffname;
313 char_u *old_b_fname;
314 int using_b_ffname;
315 int using_b_fname;
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000316#endif
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200317
Bram Moolenaarc3691332016-04-20 12:49:49 +0200318#ifdef FEAT_AUTOCMD
319 au_did_filetype = FALSE; /* reset before triggering any autocommands */
320#endif
321
Bram Moolenaarcab35ad2011-02-15 17:39:22 +0100322 curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000323
324 /*
325 * If there is no file name yet, use the one for the read file.
326 * BF_NOTEDITED is set to reflect this.
327 * Don't do this for a read from a filter.
328 * Only do this when 'cpoptions' contains the 'f' flag.
329 */
330 if (curbuf->b_ffname == NULL
331 && !filtering
332 && fname != NULL
333 && vim_strchr(p_cpo, CPO_FNAMER) != NULL
334 && !(flags & READ_DUMMY))
335 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000336 if (set_rw_fname(fname, sfname) == FAIL)
337 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000338 }
339
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200340#ifdef FEAT_AUTOCMD
341 /* Remember the initial values of curbuf, curbuf->b_ffname and
342 * curbuf->b_fname to detect whether they are altered as a result of
343 * executing nasty autocommands. Also check if "fname" and "sfname"
344 * point to one of these values. */
345 old_curbuf = curbuf;
346 old_b_ffname = curbuf->b_ffname;
347 old_b_fname = curbuf->b_fname;
348 using_b_ffname = (fname == curbuf->b_ffname)
349 || (sfname == curbuf->b_ffname);
350 using_b_fname = (fname == curbuf->b_fname) || (sfname == curbuf->b_fname);
351#endif
352
Bram Moolenaardf177f62005-02-22 08:39:57 +0000353 /* After reading a file the cursor line changes but we don't want to
354 * display the line. */
355 ex_no_reprint = TRUE;
356
Bram Moolenaar55b7cf82006-09-09 12:52:42 +0000357 /* don't display the file info for another buffer now */
358 need_fileinfo = FALSE;
359
Bram Moolenaar071d4272004-06-13 20:20:40 +0000360 /*
361 * For Unix: Use the short file name whenever possible.
362 * Avoids problems with networks and when directory names are changed.
363 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
364 * another directory, which we don't detect.
365 */
366 if (sfname == NULL)
367 sfname = fname;
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200368#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000369 fname = sfname;
370#endif
371
372#ifdef FEAT_AUTOCMD
373 /*
374 * The BufReadCmd and FileReadCmd events intercept the reading process by
375 * executing the associated commands instead.
376 */
377 if (!filtering && !read_stdin && !read_buffer)
378 {
379 pos_T pos;
380
381 pos = curbuf->b_op_start;
382
383 /* Set '[ mark to the line above where the lines go (line 1 if zero). */
384 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
385 curbuf->b_op_start.col = 0;
386
387 if (newfile)
388 {
389 if (apply_autocmds_exarg(EVENT_BUFREADCMD, NULL, sfname,
390 FALSE, curbuf, eap))
391#ifdef FEAT_EVAL
392 return aborting() ? FAIL : OK;
393#else
394 return OK;
395#endif
396 }
397 else if (apply_autocmds_exarg(EVENT_FILEREADCMD, sfname, sfname,
398 FALSE, NULL, eap))
399#ifdef FEAT_EVAL
400 return aborting() ? FAIL : OK;
401#else
402 return OK;
403#endif
404
405 curbuf->b_op_start = pos;
406 }
407#endif
408
409 if ((shortmess(SHM_OVER) || curbuf->b_help) && p_verbose == 0)
410 msg_scroll = FALSE; /* overwrite previous file message */
411 else
412 msg_scroll = TRUE; /* don't overwrite previous file message */
413
414 /*
415 * If the name ends in a path separator, we can't open it. Check here,
416 * because reading the file may actually work, but then creating the swap
417 * file may destroy it! Reported on MS-DOS and Win 95.
418 * If the name is too long we might crash further on, quit here.
419 */
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000420 if (fname != NULL && *fname != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000421 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000422 p = fname + STRLEN(fname);
423 if (after_pathsep(fname, p) || STRLEN(fname) >= MAXPATHL)
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000424 {
425 filemess(curbuf, fname, (char_u *)_("Illegal file name"), 0);
426 msg_end();
427 msg_scroll = msg_save;
428 return FAIL;
429 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000430 }
431
Bram Moolenaarf71d7b92016-08-09 22:14:05 +0200432 if (!read_stdin && !read_buffer && !read_fifo)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000433 {
Bram Moolenaar4e4f5292013-08-30 17:07:01 +0200434#ifdef UNIX
435 /*
436 * On Unix it is possible to read a directory, so we have to
437 * check for it before the mch_open().
438 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000439 perm = mch_getperm(fname);
440 if (perm >= 0 && !S_ISREG(perm) /* not a regular file ... */
441# ifdef S_ISFIFO
442 && !S_ISFIFO(perm) /* ... or fifo */
443# endif
444# ifdef S_ISSOCK
445 && !S_ISSOCK(perm) /* ... or socket */
446# endif
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +0000447# ifdef OPEN_CHR_FILES
448 && !(S_ISCHR(perm) && is_dev_fd_file(fname))
449 /* ... or a character special file named /dev/fd/<n> */
450# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000451 )
452 {
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100453 int retval = FAIL;
454
Bram Moolenaar071d4272004-06-13 20:20:40 +0000455 if (S_ISDIR(perm))
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100456 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000457 filemess(curbuf, fname, (char_u *)_("is a directory"), 0);
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100458 retval = NOTDONE;
459 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000460 else
461 filemess(curbuf, fname, (char_u *)_("is not a file"), 0);
462 msg_end();
463 msg_scroll = msg_save;
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100464 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000465 }
Bram Moolenaar4e4f5292013-08-30 17:07:01 +0200466#endif
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100467#if defined(MSWIN)
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000468 /*
469 * MS-Windows allows opening a device, but we will probably get stuck
470 * trying to read it.
471 */
472 if (!p_odev && mch_nodetype(fname) == NODE_WRITABLE)
473 {
Bram Moolenaar5386a122007-06-28 20:02:32 +0000474 filemess(curbuf, fname, (char_u *)_("is a device (disabled with 'opendevice' option)"), 0);
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000475 msg_end();
476 msg_scroll = msg_save;
477 return FAIL;
478 }
Bram Moolenaar043545e2006-10-10 16:44:07 +0000479#endif
Bram Moolenaar4e4f5292013-08-30 17:07:01 +0200480 }
Bram Moolenaar043545e2006-10-10 16:44:07 +0000481
Bram Moolenaarad875fb2013-07-24 15:02:03 +0200482 /* Set default or forced 'fileformat' and 'binary'. */
483 set_file_options(set_options, eap);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000484
485 /*
486 * When opening a new file we take the readonly flag from the file.
487 * Default is r/w, can be set to r/o below.
488 * Don't reset it when in readonly mode
489 * Only set/reset b_p_ro when BF_CHECK_RO is set.
490 */
491 check_readonly = (newfile && (curbuf->b_flags & BF_CHECK_RO));
Bram Moolenaar4399ef42005-02-12 14:29:27 +0000492 if (check_readonly && !readonlymode)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000493 curbuf->b_p_ro = FALSE;
494
Bram Moolenaarf71d7b92016-08-09 22:14:05 +0200495 if (newfile && !read_stdin && !read_buffer && !read_fifo)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000496 {
Bram Moolenaare60acc12011-05-10 16:41:25 +0200497 /* Remember time of file. */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000498 if (mch_stat((char *)fname, &st) >= 0)
499 {
500 buf_store_time(curbuf, &st, fname);
501 curbuf->b_mtime_read = curbuf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000502#ifdef UNIX
503 /*
504 * Use the protection bits of the original file for the swap file.
505 * This makes it possible for others to read the name of the
506 * edited file from the swapfile, but only if they can read the
507 * edited file.
508 * Remove the "write" and "execute" bits for group and others
509 * (they must not write the swapfile).
510 * Add the "read" and "write" bits for the user, otherwise we may
511 * not be able to write to the file ourselves.
512 * Setting the bits is done below, after creating the swap file.
513 */
514 swap_mode = (st.st_mode & 0644) | 0600;
515#endif
516#ifdef FEAT_CW_EDITOR
517 /* Get the FSSpec on MacOS
518 * TODO: Update it properly when the buffer name changes
519 */
520 (void)GetFSSpecFromPath(curbuf->b_ffname, &curbuf->b_FSSpec);
521#endif
522#ifdef VMS
523 curbuf->b_fab_rfm = st.st_fab_rfm;
Bram Moolenaard4755bb2004-09-02 19:12:26 +0000524 curbuf->b_fab_rat = st.st_fab_rat;
525 curbuf->b_fab_mrs = st.st_fab_mrs;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000526#endif
527 }
528 else
529 {
530 curbuf->b_mtime = 0;
531 curbuf->b_mtime_read = 0;
532 curbuf->b_orig_size = 0;
533 curbuf->b_orig_mode = 0;
534 }
535
536 /* Reset the "new file" flag. It will be set again below when the
537 * file doesn't exist. */
538 curbuf->b_flags &= ~(BF_NEW | BF_NEW_W);
539 }
540
541/*
542 * for UNIX: check readonly with perm and mch_access()
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100543 * for Amiga: check readonly by trying to open the file for writing
Bram Moolenaar071d4272004-06-13 20:20:40 +0000544 */
545 file_readonly = FALSE;
546 if (read_stdin)
547 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100548#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000549 /* Force binary I/O on stdin to avoid CR-LF -> LF conversion. */
550 setmode(0, O_BINARY);
551#endif
552 }
553 else if (!read_buffer)
554 {
555#ifdef USE_MCH_ACCESS
556 if (
557# ifdef UNIX
558 !(perm & 0222) ||
559# endif
560 mch_access((char *)fname, W_OK))
561 file_readonly = TRUE;
562 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
563#else
564 if (!newfile
565 || readonlymode
566 || (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0)
567 {
568 file_readonly = TRUE;
569 /* try to open ro */
570 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
571 }
572#endif
573 }
574
575 if (fd < 0) /* cannot open at all */
576 {
577#ifndef UNIX
578 int isdir_f;
579#endif
580 msg_scroll = msg_save;
581#ifndef UNIX
582 /*
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100583 * On Amiga we can't open a directory, check here.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000584 */
585 isdir_f = (mch_isdir(fname));
586 perm = mch_getperm(fname); /* check if the file exists */
587 if (isdir_f)
588 {
589 filemess(curbuf, sfname, (char_u *)_("is a directory"), 0);
590 curbuf->b_p_ro = TRUE; /* must use "w!" now */
591 }
592 else
593#endif
594 if (newfile)
595 {
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200596 if (perm < 0
597#ifdef ENOENT
598 && errno == ENOENT
599#endif
600 )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000601 {
602 /*
603 * Set the 'new-file' flag, so that when the file has
604 * been created by someone else, a ":w" will complain.
605 */
606 curbuf->b_flags |= BF_NEW;
607
608 /* Create a swap file now, so that other Vims are warned
609 * that we are editing this file. Don't do this for a
610 * "nofile" or "nowrite" buffer type. */
611#ifdef FEAT_QUICKFIX
612 if (!bt_dontwrite(curbuf))
613#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000614 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000615 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000616#ifdef FEAT_AUTOCMD
617 /* SwapExists autocommand may mess things up */
618 if (curbuf != old_curbuf
619 || (using_b_ffname
620 && (old_b_ffname != curbuf->b_ffname))
621 || (using_b_fname
622 && (old_b_fname != curbuf->b_fname)))
623 {
624 EMSG(_(e_auchangedbuf));
625 return FAIL;
626 }
627#endif
628 }
Bram Moolenaar5b962cf2005-12-12 21:58:40 +0000629 if (dir_of_file_exists(fname))
630 filemess(curbuf, sfname, (char_u *)_("[New File]"), 0);
631 else
632 filemess(curbuf, sfname,
633 (char_u *)_("[New DIRECTORY]"), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000634#ifdef FEAT_VIMINFO
635 /* Even though this is a new file, it might have been
636 * edited before and deleted. Get the old marks. */
637 check_marks_read();
638#endif
639#ifdef FEAT_MBYTE
Bram Moolenaarad875fb2013-07-24 15:02:03 +0200640 /* Set forced 'fileencoding'. */
641 if (eap != NULL)
642 set_forced_fenc(eap);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000643#endif
644#ifdef FEAT_AUTOCMD
645 apply_autocmds_exarg(EVENT_BUFNEWFILE, sfname, sfname,
646 FALSE, curbuf, eap);
647#endif
648 /* remember the current fileformat */
649 save_file_ff(curbuf);
650
651#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
652 if (aborting()) /* autocmds may abort script processing */
653 return FAIL;
654#endif
655 return OK; /* a new file is not an error */
656 }
657 else
658 {
Bram Moolenaar202795b2005-10-11 20:29:39 +0000659 filemess(curbuf, sfname, (char_u *)(
660# ifdef EFBIG
661 (errno == EFBIG) ? _("[File too big]") :
662# endif
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200663# ifdef EOVERFLOW
664 (errno == EOVERFLOW) ? _("[File too big]") :
665# endif
Bram Moolenaar202795b2005-10-11 20:29:39 +0000666 _("[Permission Denied]")), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000667 curbuf->b_p_ro = TRUE; /* must use "w!" now */
668 }
669 }
670
671 return FAIL;
672 }
673
674 /*
675 * Only set the 'ro' flag for readonly files the first time they are
676 * loaded. Help files always get readonly mode
677 */
678 if ((check_readonly && file_readonly) || curbuf->b_help)
679 curbuf->b_p_ro = TRUE;
680
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000681 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000682 {
Bram Moolenaar690ffc02008-01-04 15:31:21 +0000683 /* Don't change 'eol' if reading from buffer as it will already be
684 * correctly set when reading stdin. */
685 if (!read_buffer)
686 {
687 curbuf->b_p_eol = TRUE;
688 curbuf->b_start_eol = TRUE;
689 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000690#ifdef FEAT_MBYTE
691 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000692 curbuf->b_start_bomb = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000693#endif
694 }
695
696 /* Create a swap file now, so that other Vims are warned that we are
697 * editing this file.
698 * Don't do this for a "nofile" or "nowrite" buffer type. */
699#ifdef FEAT_QUICKFIX
700 if (!bt_dontwrite(curbuf))
701#endif
702 {
703 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000704#ifdef FEAT_AUTOCMD
705 if (!read_stdin && (curbuf != old_curbuf
706 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
707 || (using_b_fname && (old_b_fname != curbuf->b_fname))))
708 {
709 EMSG(_(e_auchangedbuf));
710 if (!read_buffer)
711 close(fd);
712 return FAIL;
713 }
714#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000715#ifdef UNIX
716 /* Set swap file protection bits after creating it. */
Bram Moolenaarf061e0b2009-06-24 15:32:01 +0000717 if (swap_mode > 0 && curbuf->b_ml.ml_mfp != NULL
718 && curbuf->b_ml.ml_mfp->mf_fname != NULL)
Bram Moolenaar5a73e0c2017-11-04 21:35:01 +0100719 {
720 char_u *swap_fname = curbuf->b_ml.ml_mfp->mf_fname;
721
722 /*
723 * If the group-read bit is set but not the world-read bit, then
724 * the group must be equal to the group of the original file. If
725 * we can't make that happen then reset the group-read bit. This
726 * avoids making the swap file readable to more users when the
727 * primary group of the user is too permissive.
728 */
729 if ((swap_mode & 044) == 040)
730 {
731 stat_T swap_st;
732
733 if (mch_stat((char *)swap_fname, &swap_st) >= 0
734 && st.st_gid != swap_st.st_gid
735 && fchown(curbuf->b_ml.ml_mfp->mf_fd, -1, st.st_gid)
736 == -1)
737 swap_mode &= 0600;
738 }
739
740 (void)mch_setperm(swap_fname, (long)swap_mode);
741 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000742#endif
743 }
744
Bram Moolenaarb815dac2005-12-07 20:59:24 +0000745#if defined(HAS_SWAP_EXISTS_ACTION)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000746 /* If "Quit" selected at ATTENTION dialog, don't load the file */
747 if (swap_exists_action == SEA_QUIT)
748 {
749 if (!read_buffer && !read_stdin)
750 close(fd);
751 return FAIL;
752 }
753#endif
754
755 ++no_wait_return; /* don't wait for return yet */
756
757 /*
758 * Set '[ mark to the line above where the lines go (line 1 if zero).
759 */
760 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
761 curbuf->b_op_start.col = 0;
762
Bram Moolenaar7a2699e2017-01-23 21:31:09 +0100763 try_mac = (vim_strchr(p_ffs, 'm') != NULL);
764 try_dos = (vim_strchr(p_ffs, 'd') != NULL);
765 try_unix = (vim_strchr(p_ffs, 'x') != NULL);
766
Bram Moolenaar071d4272004-06-13 20:20:40 +0000767#ifdef FEAT_AUTOCMD
768 if (!read_buffer)
769 {
770 int m = msg_scroll;
771 int n = msg_scrolled;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000772
773 /*
774 * The file must be closed again, the autocommands may want to change
775 * the file before reading it.
776 */
777 if (!read_stdin)
778 close(fd); /* ignore errors */
779
780 /*
781 * The output from the autocommands should not overwrite anything and
782 * should not be overwritten: Set msg_scroll, restore its value if no
783 * output was done.
784 */
785 msg_scroll = TRUE;
786 if (filtering)
787 apply_autocmds_exarg(EVENT_FILTERREADPRE, NULL, sfname,
788 FALSE, curbuf, eap);
789 else if (read_stdin)
790 apply_autocmds_exarg(EVENT_STDINREADPRE, NULL, sfname,
791 FALSE, curbuf, eap);
792 else if (newfile)
793 apply_autocmds_exarg(EVENT_BUFREADPRE, NULL, sfname,
794 FALSE, curbuf, eap);
795 else
796 apply_autocmds_exarg(EVENT_FILEREADPRE, sfname, sfname,
797 FALSE, NULL, eap);
Bram Moolenaar7a2699e2017-01-23 21:31:09 +0100798 /* autocommands may have changed it */
799 try_mac = (vim_strchr(p_ffs, 'm') != NULL);
800 try_dos = (vim_strchr(p_ffs, 'd') != NULL);
801 try_unix = (vim_strchr(p_ffs, 'x') != NULL);
802
Bram Moolenaar071d4272004-06-13 20:20:40 +0000803 if (msg_scrolled == n)
804 msg_scroll = m;
805
806#ifdef FEAT_EVAL
807 if (aborting()) /* autocmds may abort script processing */
808 {
809 --no_wait_return;
810 msg_scroll = msg_save;
811 curbuf->b_p_ro = TRUE; /* must use "w!" now */
812 return FAIL;
813 }
814#endif
815 /*
816 * Don't allow the autocommands to change the current buffer.
817 * Try to re-open the file.
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000818 *
819 * Don't allow the autocommands to change the buffer name either
820 * (cd for example) if it invalidates fname or sfname.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000821 */
822 if (!read_stdin && (curbuf != old_curbuf
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000823 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
824 || (using_b_fname && (old_b_fname != curbuf->b_fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000825 || (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) < 0))
826 {
827 --no_wait_return;
828 msg_scroll = msg_save;
829 if (fd < 0)
830 EMSG(_("E200: *ReadPre autocommands made the file unreadable"));
831 else
832 EMSG(_("E201: *ReadPre autocommands must not change current buffer"));
833 curbuf->b_p_ro = TRUE; /* must use "w!" now */
834 return FAIL;
835 }
836 }
837#endif /* FEAT_AUTOCMD */
838
839 /* Autocommands may add lines to the file, need to check if it is empty */
840 wasempty = (curbuf->b_ml.ml_flags & ML_EMPTY);
841
842 if (!recoverymode && !filtering && !(flags & READ_DUMMY))
843 {
844 /*
845 * Show the user that we are busy reading the input. Sometimes this
846 * may take a while. When reading from stdin another program may
847 * still be running, don't move the cursor to the last line, unless
848 * always using the GUI.
849 */
850 if (read_stdin)
851 {
Bram Moolenaar234d1622017-11-18 14:55:23 +0100852 if (!is_not_a_term())
853 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000854#ifndef ALWAYS_USE_GUI
Bram Moolenaar234d1622017-11-18 14:55:23 +0100855 mch_msg(_("Vim: Reading from stdin...\n"));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000856#endif
857#ifdef FEAT_GUI
Bram Moolenaar234d1622017-11-18 14:55:23 +0100858 /* Also write a message in the GUI window, if there is one. */
859 if (gui.in_use && !gui.dying && !gui.starting)
860 {
861 p = (char_u *)_("Reading from stdin...");
862 gui_write(p, (int)STRLEN(p));
863 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000864#endif
Bram Moolenaar234d1622017-11-18 14:55:23 +0100865 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000866 }
867 else if (!read_buffer)
868 filemess(curbuf, sfname, (char_u *)"", 0);
869 }
870
871 msg_scroll = FALSE; /* overwrite the file message */
872
873 /*
874 * Set linecnt now, before the "retry" caused by a wrong guess for
875 * fileformat, and after the autocommands, which may change them.
876 */
877 linecnt = curbuf->b_ml.ml_line_count;
878
879#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000880 /* "++bad=" argument. */
881 if (eap != NULL && eap->bad_char != 0)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000882 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000883 bad_char_behavior = eap->bad_char;
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000884 if (set_options)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000885 curbuf->b_bad_char = eap->bad_char;
886 }
887 else
888 curbuf->b_bad_char = 0;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000889
Bram Moolenaar071d4272004-06-13 20:20:40 +0000890 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000891 * Decide which 'encoding' to use or use first.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000892 */
893 if (eap != NULL && eap->force_enc != 0)
894 {
895 fenc = enc_canonize(eap->cmd + eap->force_enc);
896 fenc_alloced = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000897 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000898 }
899 else if (curbuf->b_p_bin)
900 {
901 fenc = (char_u *)""; /* binary: don't convert */
902 fenc_alloced = FALSE;
903 }
904 else if (curbuf->b_help)
905 {
906 char_u firstline[80];
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000907 int fc;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000908
909 /* Help files are either utf-8 or latin1. Try utf-8 first, if this
910 * fails it must be latin1.
911 * Always do this when 'encoding' is "utf-8". Otherwise only do
912 * this when needed to avoid [converted] remarks all the time.
913 * It is needed when the first line contains non-ASCII characters.
914 * That is only in *.??x files. */
915 fenc = (char_u *)"latin1";
916 c = enc_utf8;
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000917 if (!c && !read_stdin)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000918 {
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000919 fc = fname[STRLEN(fname) - 1];
920 if (TOLOWER_ASC(fc) == 'x')
921 {
922 /* Read the first line (and a bit more). Immediately rewind to
923 * the start of the file. If the read() fails "len" is -1. */
Bram Moolenaar540fc6f2010-12-17 16:27:16 +0100924 len = read_eintr(fd, firstline, 80);
Bram Moolenaar8767f522016-07-01 17:17:39 +0200925 vim_lseek(fd, (off_T)0L, SEEK_SET);
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000926 for (p = firstline; p < firstline + len; ++p)
927 if (*p >= 0x80)
928 {
929 c = TRUE;
930 break;
931 }
932 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000933 }
934
935 if (c)
936 {
937 fenc_next = fenc;
938 fenc = (char_u *)"utf-8";
939
940 /* When the file is utf-8 but a character doesn't fit in
941 * 'encoding' don't retry. In help text editing utf-8 bytes
942 * doesn't make sense. */
Bram Moolenaarf193fff2006-04-27 00:02:13 +0000943 if (!enc_utf8)
944 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000945 }
946 fenc_alloced = FALSE;
947 }
948 else if (*p_fencs == NUL)
949 {
950 fenc = curbuf->b_p_fenc; /* use format from buffer */
951 fenc_alloced = FALSE;
952 }
953 else
954 {
955 fenc_next = p_fencs; /* try items in 'fileencodings' */
956 fenc = next_fenc(&fenc_next);
957 fenc_alloced = TRUE;
958 }
959#endif
960
961 /*
962 * Jump back here to retry reading the file in different ways.
963 * Reasons to retry:
964 * - encoding conversion failed: try another one from "fenc_next"
965 * - BOM detected and fenc was set, need to setup conversion
966 * - "fileformat" check failed: try another
967 *
968 * Variables set for special retry actions:
969 * "file_rewind" Rewind the file to start reading it again.
970 * "advance_fenc" Advance "fenc" using "fenc_next".
971 * "skip_read" Re-use already read bytes (BOM detected).
972 * "did_iconv" iconv() conversion failed, try 'charconvert'.
973 * "keep_fileformat" Don't reset "fileformat".
974 *
975 * Other status indicators:
976 * "tmpname" When != NULL did conversion with 'charconvert'.
977 * Output file has to be deleted afterwards.
978 * "iconv_fd" When != -1 did conversion with iconv().
979 */
980retry:
981
982 if (file_rewind)
983 {
984 if (read_buffer)
985 {
986 read_buf_lnum = 1;
987 read_buf_col = 0;
988 }
Bram Moolenaar8767f522016-07-01 17:17:39 +0200989 else if (read_stdin || vim_lseek(fd, (off_T)0L, SEEK_SET) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000990 {
991 /* Can't rewind the file, give up. */
992 error = TRUE;
993 goto failed;
994 }
995 /* Delete the previously read lines. */
996 while (lnum > from)
997 ml_delete(lnum--, FALSE);
998 file_rewind = FALSE;
999#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +00001000 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001001 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001002 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001003 curbuf->b_start_bomb = FALSE;
1004 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001005 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001006#endif
1007 }
1008
1009 /*
1010 * When retrying with another "fenc" and the first time "fileformat"
1011 * will be reset.
1012 */
1013 if (keep_fileformat)
1014 keep_fileformat = FALSE;
1015 else
1016 {
1017 if (eap != NULL && eap->force_ff != 0)
Bram Moolenaar1c860362008-11-12 15:05:21 +00001018 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001019 fileformat = get_fileformat_force(curbuf, eap);
Bram Moolenaar1c860362008-11-12 15:05:21 +00001020 try_unix = try_dos = try_mac = FALSE;
1021 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001022 else if (curbuf->b_p_bin)
1023 fileformat = EOL_UNIX; /* binary: use Unix format */
1024 else if (*p_ffs == NUL)
1025 fileformat = get_fileformat(curbuf);/* use format from buffer */
1026 else
1027 fileformat = EOL_UNKNOWN; /* detect from file */
1028 }
1029
1030#ifdef FEAT_MBYTE
1031# ifdef USE_ICONV
1032 if (iconv_fd != (iconv_t)-1)
1033 {
1034 /* aborted conversion with iconv(), close the descriptor */
1035 iconv_close(iconv_fd);
1036 iconv_fd = (iconv_t)-1;
1037 }
1038# endif
1039
1040 if (advance_fenc)
1041 {
1042 /*
1043 * Try the next entry in 'fileencodings'.
1044 */
1045 advance_fenc = FALSE;
1046
1047 if (eap != NULL && eap->force_enc != 0)
1048 {
1049 /* Conversion given with "++cc=" wasn't possible, read
1050 * without conversion. */
1051 notconverted = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001052 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001053 if (fenc_alloced)
1054 vim_free(fenc);
1055 fenc = (char_u *)"";
1056 fenc_alloced = FALSE;
1057 }
1058 else
1059 {
1060 if (fenc_alloced)
1061 vim_free(fenc);
1062 if (fenc_next != NULL)
1063 {
1064 fenc = next_fenc(&fenc_next);
1065 fenc_alloced = (fenc_next != NULL);
1066 }
1067 else
1068 {
1069 fenc = (char_u *)"";
1070 fenc_alloced = FALSE;
1071 }
1072 }
1073 if (tmpname != NULL)
1074 {
1075 mch_remove(tmpname); /* delete converted file */
1076 vim_free(tmpname);
1077 tmpname = NULL;
1078 }
1079 }
1080
1081 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001082 * Conversion may be required when the encoding of the file is different
1083 * from 'encoding' or 'encoding' is UTF-16, UCS-2 or UCS-4.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001084 */
1085 fio_flags = 0;
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001086 converted = need_conversion(fenc);
1087 if (converted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001088 {
1089
1090 /* "ucs-bom" means we need to check the first bytes of the file
1091 * for a BOM. */
1092 if (STRCMP(fenc, ENC_UCSBOM) == 0)
1093 fio_flags = FIO_UCSBOM;
1094
1095 /*
1096 * Check if UCS-2/4 or Latin1 to UTF-8 conversion needs to be
1097 * done. This is handled below after read(). Prepare the
1098 * fio_flags to avoid having to parse the string each time.
1099 * Also check for Unicode to Latin1 conversion, because iconv()
1100 * appears not to handle this correctly. This works just like
1101 * conversion to UTF-8 except how the resulting character is put in
1102 * the buffer.
1103 */
1104 else if (enc_utf8 || STRCMP(p_enc, "latin1") == 0)
1105 fio_flags = get_fio_flags(fenc);
1106
1107# ifdef WIN3264
1108 /*
1109 * Conversion from an MS-Windows codepage to UTF-8 or another codepage
1110 * is handled with MultiByteToWideChar().
1111 */
1112 if (fio_flags == 0)
1113 fio_flags = get_win_fio_flags(fenc);
1114# endif
1115
Bram Moolenaard0573012017-10-28 21:11:06 +02001116# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001117 /* Conversion from Apple MacRoman to latin1 or UTF-8 */
1118 if (fio_flags == 0)
1119 fio_flags = get_mac_fio_flags(fenc);
1120# endif
1121
1122# ifdef USE_ICONV
1123 /*
1124 * Try using iconv() if we can't convert internally.
1125 */
1126 if (fio_flags == 0
1127# ifdef FEAT_EVAL
1128 && !did_iconv
1129# endif
1130 )
1131 iconv_fd = (iconv_t)my_iconv_open(
1132 enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc);
1133# endif
1134
1135# ifdef FEAT_EVAL
1136 /*
1137 * Use the 'charconvert' expression when conversion is required
1138 * and we can't do it internally or with iconv().
1139 */
1140 if (fio_flags == 0 && !read_stdin && !read_buffer && *p_ccv != NUL
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02001141 && !read_fifo
Bram Moolenaar071d4272004-06-13 20:20:40 +00001142# ifdef USE_ICONV
1143 && iconv_fd == (iconv_t)-1
1144# endif
1145 )
1146 {
1147# ifdef USE_ICONV
1148 did_iconv = FALSE;
1149# endif
1150 /* Skip conversion when it's already done (retry for wrong
1151 * "fileformat"). */
1152 if (tmpname == NULL)
1153 {
1154 tmpname = readfile_charconvert(fname, fenc, &fd);
1155 if (tmpname == NULL)
1156 {
1157 /* Conversion failed. Try another one. */
1158 advance_fenc = TRUE;
1159 if (fd < 0)
1160 {
1161 /* Re-opening the original file failed! */
1162 EMSG(_("E202: Conversion made file unreadable!"));
1163 error = TRUE;
1164 goto failed;
1165 }
1166 goto retry;
1167 }
1168 }
1169 }
1170 else
1171# endif
1172 {
1173 if (fio_flags == 0
1174# ifdef USE_ICONV
1175 && iconv_fd == (iconv_t)-1
1176# endif
1177 )
1178 {
1179 /* Conversion wanted but we can't.
1180 * Try the next conversion in 'fileencodings' */
1181 advance_fenc = TRUE;
1182 goto retry;
1183 }
1184 }
1185 }
1186
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001187 /* Set "can_retry" when it's possible to rewind the file and try with
Bram Moolenaar071d4272004-06-13 20:20:40 +00001188 * another "fenc" value. It's FALSE when no other "fenc" to try, reading
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001189 * stdin or fixed at a specific encoding. */
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02001190 can_retry = (*fenc != NUL && !read_stdin && !read_fifo && !keep_dest_enc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001191#endif
1192
1193 if (!skip_read)
1194 {
1195 linerest = 0;
1196 filesize = 0;
1197 skip_count = lines_to_skip;
1198 read_count = lines_to_read;
1199#ifdef FEAT_MBYTE
1200 conv_restlen = 0;
1201#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001202#ifdef FEAT_PERSISTENT_UNDO
Bram Moolenaar59f931e2010-07-24 20:27:03 +02001203 read_undo_file = (newfile && (flags & READ_KEEP_UNDO) == 0
1204 && curbuf->b_ffname != NULL
1205 && curbuf->b_p_udf
1206 && !filtering
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02001207 && !read_fifo
Bram Moolenaar59f931e2010-07-24 20:27:03 +02001208 && !read_stdin
1209 && !read_buffer);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001210 if (read_undo_file)
1211 sha256_start(&sha_ctx);
1212#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001213#ifdef FEAT_CRYPT
1214 if (curbuf->b_cryptstate != NULL)
1215 {
1216 /* Need to free the state, but keep the key, don't want to ask for
1217 * it again. */
1218 crypt_free_state(curbuf->b_cryptstate);
1219 curbuf->b_cryptstate = NULL;
1220 }
1221#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001222 }
1223
1224 while (!error && !got_int)
1225 {
1226 /*
1227 * We allocate as much space for the file as we can get, plus
1228 * space for the old line plus room for one terminating NUL.
1229 * The amount is limited by the fact that read() only can read
1230 * upto max_unsigned characters (and other things).
1231 */
Bram Moolenaara2aa31a2014-02-23 22:52:40 +01001232#if VIM_SIZEOF_INT <= 2
Bram Moolenaar071d4272004-06-13 20:20:40 +00001233 if (linerest >= 0x7ff0)
1234 {
1235 ++split;
1236 *ptr = NL; /* split line by inserting a NL */
1237 size = 1;
1238 }
1239 else
1240#endif
1241 {
1242 if (!skip_read)
1243 {
Bram Moolenaara2aa31a2014-02-23 22:52:40 +01001244#if VIM_SIZEOF_INT > 2
Bram Moolenaar311d9822007-02-27 15:48:28 +00001245# if defined(SSIZE_MAX) && (SSIZE_MAX < 0x10000L)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001246 size = SSIZE_MAX; /* use max I/O size, 52K */
1247# else
1248 size = 0x10000L; /* use buffer >= 64K */
1249# endif
1250#else
1251 size = 0x7ff0L - linerest; /* limit buffer to 32K */
1252#endif
1253
Bram Moolenaarc1e37902006-04-18 21:55:01 +00001254 for ( ; size >= 10; size = (long)((long_u)size >> 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001255 {
1256 if ((new_buffer = lalloc((long_u)(size + linerest + 1),
1257 FALSE)) != NULL)
1258 break;
1259 }
1260 if (new_buffer == NULL)
1261 {
1262 do_outofmem_msg((long_u)(size * 2 + linerest + 1));
1263 error = TRUE;
1264 break;
1265 }
1266 if (linerest) /* copy characters from the previous buffer */
1267 mch_memmove(new_buffer, ptr - linerest, (size_t)linerest);
1268 vim_free(buffer);
1269 buffer = new_buffer;
1270 ptr = buffer + linerest;
1271 line_start = buffer;
1272
1273#ifdef FEAT_MBYTE
1274 /* May need room to translate into.
1275 * For iconv() we don't really know the required space, use a
1276 * factor ICONV_MULT.
1277 * latin1 to utf-8: 1 byte becomes up to 2 bytes
1278 * utf-16 to utf-8: 2 bytes become up to 3 bytes, 4 bytes
1279 * become up to 4 bytes, size must be multiple of 2
1280 * ucs-2 to utf-8: 2 bytes become up to 3 bytes, size must be
1281 * multiple of 2
1282 * ucs-4 to utf-8: 4 bytes become up to 6 bytes, size must be
1283 * multiple of 4 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001284 real_size = (int)size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001285# ifdef USE_ICONV
1286 if (iconv_fd != (iconv_t)-1)
1287 size = size / ICONV_MULT;
1288 else
1289# endif
1290 if (fio_flags & FIO_LATIN1)
1291 size = size / 2;
1292 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1293 size = (size * 2 / 3) & ~1;
1294 else if (fio_flags & FIO_UCS4)
1295 size = (size * 2 / 3) & ~3;
1296 else if (fio_flags == FIO_UCSBOM)
1297 size = size / ICONV_MULT; /* worst case */
1298# ifdef WIN3264
1299 else if (fio_flags & FIO_CODEPAGE)
1300 size = size / ICONV_MULT; /* also worst case */
1301# endif
Bram Moolenaard0573012017-10-28 21:11:06 +02001302# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001303 else if (fio_flags & FIO_MACROMAN)
1304 size = size / ICONV_MULT; /* also worst case */
1305# endif
1306#endif
1307
1308#ifdef FEAT_MBYTE
1309 if (conv_restlen > 0)
1310 {
1311 /* Insert unconverted bytes from previous line. */
1312 mch_memmove(ptr, conv_rest, conv_restlen);
1313 ptr += conv_restlen;
1314 size -= conv_restlen;
1315 }
1316#endif
1317
1318 if (read_buffer)
1319 {
1320 /*
1321 * Read bytes from curbuf. Used for converting text read
1322 * from stdin.
1323 */
1324 if (read_buf_lnum > from)
1325 size = 0;
1326 else
1327 {
1328 int n, ni;
1329 long tlen;
1330
1331 tlen = 0;
1332 for (;;)
1333 {
1334 p = ml_get(read_buf_lnum) + read_buf_col;
1335 n = (int)STRLEN(p);
1336 if ((int)tlen + n + 1 > size)
1337 {
1338 /* Filled up to "size", append partial line.
1339 * Change NL to NUL to reverse the effect done
1340 * below. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001341 n = (int)(size - tlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001342 for (ni = 0; ni < n; ++ni)
1343 {
1344 if (p[ni] == NL)
1345 ptr[tlen++] = NUL;
1346 else
1347 ptr[tlen++] = p[ni];
1348 }
1349 read_buf_col += n;
1350 break;
1351 }
1352 else
1353 {
1354 /* Append whole line and new-line. Change NL
1355 * to NUL to reverse the effect done below. */
1356 for (ni = 0; ni < n; ++ni)
1357 {
1358 if (p[ni] == NL)
1359 ptr[tlen++] = NUL;
1360 else
1361 ptr[tlen++] = p[ni];
1362 }
1363 ptr[tlen++] = NL;
1364 read_buf_col = 0;
1365 if (++read_buf_lnum > from)
1366 {
1367 /* When the last line didn't have an
1368 * end-of-line don't add it now either. */
1369 if (!curbuf->b_p_eol)
1370 --tlen;
1371 size = tlen;
1372 break;
1373 }
1374 }
1375 }
1376 }
1377 }
1378 else
1379 {
1380 /*
1381 * Read bytes from the file.
1382 */
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01001383 size = read_eintr(fd, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001384 }
1385
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001386#ifdef FEAT_CRYPT
1387 /*
1388 * At start of file: Check for magic number of encryption.
1389 */
1390 if (filesize == 0 && size > 0)
1391 cryptkey = check_for_cryptkey(cryptkey, ptr, &size,
1392 &filesize, newfile, sfname,
1393 &did_ask_for_key);
1394 /*
1395 * Decrypt the read bytes. This is done before checking for
1396 * EOF because the crypt layer may be buffering.
1397 */
Bram Moolenaar829aa642017-08-23 22:32:35 +02001398 if (cryptkey != NULL && curbuf->b_cryptstate != NULL
1399 && size > 0)
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001400 {
1401 if (crypt_works_inplace(curbuf->b_cryptstate))
1402 {
1403 crypt_decode_inplace(curbuf->b_cryptstate, ptr, size);
1404 }
1405 else
1406 {
1407 char_u *newptr = NULL;
1408 int decrypted_size;
1409
1410 decrypted_size = crypt_decode_alloc(
1411 curbuf->b_cryptstate, ptr, size, &newptr);
1412
1413 /* If the crypt layer is buffering, not producing
1414 * anything yet, need to read more. */
1415 if (size > 0 && decrypted_size == 0)
1416 continue;
1417
1418 if (linerest == 0)
1419 {
1420 /* Simple case: reuse returned buffer (may be
1421 * NULL, checked later). */
1422 new_buffer = newptr;
1423 }
1424 else
1425 {
1426 long_u new_size;
1427
1428 /* Need new buffer to add bytes carried over. */
1429 new_size = (long_u)(decrypted_size + linerest + 1);
1430 new_buffer = lalloc(new_size, FALSE);
1431 if (new_buffer == NULL)
1432 {
1433 do_outofmem_msg(new_size);
1434 error = TRUE;
1435 break;
1436 }
1437
1438 mch_memmove(new_buffer, buffer, linerest);
1439 if (newptr != NULL)
1440 mch_memmove(new_buffer + linerest, newptr,
1441 decrypted_size);
1442 }
1443
1444 if (new_buffer != NULL)
1445 {
1446 vim_free(buffer);
1447 buffer = new_buffer;
1448 new_buffer = NULL;
1449 line_start = buffer;
1450 ptr = buffer + linerest;
1451 }
1452 size = decrypted_size;
1453 }
1454 }
1455#endif
1456
Bram Moolenaar071d4272004-06-13 20:20:40 +00001457 if (size <= 0)
1458 {
1459 if (size < 0) /* read error */
1460 error = TRUE;
1461#ifdef FEAT_MBYTE
1462 else if (conv_restlen > 0)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001463 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001464 /*
1465 * Reached end-of-file but some trailing bytes could
1466 * not be converted. Truncated file?
1467 */
1468
1469 /* When we did a conversion report an error. */
1470 if (fio_flags != 0
1471# ifdef USE_ICONV
1472 || iconv_fd != (iconv_t)-1
1473# endif
1474 )
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001475 {
Bram Moolenaare8d95302013-04-24 16:34:02 +02001476 if (can_retry)
1477 goto rewind_retry;
Bram Moolenaarf453d352008-06-04 17:37:34 +00001478 if (conv_error == 0)
1479 conv_error = curbuf->b_ml.ml_line_count
1480 - linecnt + 1;
1481 }
1482 /* Remember the first linenr with an illegal byte */
1483 else if (illegal_byte == 0)
1484 illegal_byte = curbuf->b_ml.ml_line_count
1485 - linecnt + 1;
1486 if (bad_char_behavior == BAD_DROP)
1487 {
1488 *(ptr - conv_restlen) = NUL;
1489 conv_restlen = 0;
1490 }
1491 else
1492 {
1493 /* Replace the trailing bytes with the replacement
1494 * character if we were converting; if we weren't,
1495 * leave the UTF8 checking code to do it, as it
1496 * works slightly differently. */
1497 if (bad_char_behavior != BAD_KEEP && (fio_flags != 0
1498# ifdef USE_ICONV
1499 || iconv_fd != (iconv_t)-1
1500# endif
1501 ))
1502 {
1503 while (conv_restlen > 0)
1504 {
1505 *(--ptr) = bad_char_behavior;
1506 --conv_restlen;
1507 }
1508 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001509 fio_flags = 0; /* don't convert this */
Bram Moolenaarb21e5842006-04-16 18:30:08 +00001510# ifdef USE_ICONV
1511 if (iconv_fd != (iconv_t)-1)
1512 {
1513 iconv_close(iconv_fd);
1514 iconv_fd = (iconv_t)-1;
1515 }
1516# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001517 }
1518 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001519#endif
1520 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001521 }
1522 skip_read = FALSE;
1523
1524#ifdef FEAT_MBYTE
1525 /*
1526 * At start of file (or after crypt magic number): Check for BOM.
1527 * Also check for a BOM for other Unicode encodings, but not after
1528 * converting with 'charconvert' or when a BOM has already been
1529 * found.
1530 */
1531 if ((filesize == 0
1532# ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001533 || (cryptkey != NULL
1534 && filesize == crypt_get_header_len(
1535 crypt_get_method_nr(curbuf)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001536# endif
1537 )
1538 && (fio_flags == FIO_UCSBOM
1539 || (!curbuf->b_p_bomb
1540 && tmpname == NULL
1541 && (*fenc == 'u' || (*fenc == NUL && enc_utf8)))))
1542 {
1543 char_u *ccname;
1544 int blen;
1545
1546 /* no BOM detection in a short file or in binary mode */
1547 if (size < 2 || curbuf->b_p_bin)
1548 ccname = NULL;
1549 else
1550 ccname = check_for_bom(ptr, size, &blen,
1551 fio_flags == FIO_UCSBOM ? FIO_ALL : get_fio_flags(fenc));
1552 if (ccname != NULL)
1553 {
1554 /* Remove BOM from the text */
1555 filesize += blen;
1556 size -= blen;
1557 mch_memmove(ptr, ptr + blen, (size_t)size);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00001558 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001559 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001560 curbuf->b_p_bomb = TRUE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001561 curbuf->b_start_bomb = TRUE;
1562 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001563 }
1564
1565 if (fio_flags == FIO_UCSBOM)
1566 {
1567 if (ccname == NULL)
1568 {
1569 /* No BOM detected: retry with next encoding. */
1570 advance_fenc = TRUE;
1571 }
1572 else
1573 {
1574 /* BOM detected: set "fenc" and jump back */
1575 if (fenc_alloced)
1576 vim_free(fenc);
1577 fenc = ccname;
1578 fenc_alloced = FALSE;
1579 }
1580 /* retry reading without getting new bytes or rewinding */
1581 skip_read = TRUE;
1582 goto retry;
1583 }
1584 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001585
1586 /* Include not converted bytes. */
1587 ptr -= conv_restlen;
1588 size += conv_restlen;
1589 conv_restlen = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001590#endif
1591 /*
1592 * Break here for a read error or end-of-file.
1593 */
1594 if (size <= 0)
1595 break;
1596
1597#ifdef FEAT_MBYTE
1598
Bram Moolenaar071d4272004-06-13 20:20:40 +00001599# ifdef USE_ICONV
1600 if (iconv_fd != (iconv_t)-1)
1601 {
1602 /*
1603 * Attempt conversion of the read bytes to 'encoding' using
1604 * iconv().
1605 */
1606 const char *fromp;
1607 char *top;
1608 size_t from_size;
1609 size_t to_size;
1610
1611 fromp = (char *)ptr;
1612 from_size = size;
1613 ptr += size;
1614 top = (char *)ptr;
1615 to_size = real_size - size;
1616
1617 /*
1618 * If there is conversion error or not enough room try using
Bram Moolenaar19a09a12005-03-04 23:39:37 +00001619 * another conversion. Except for when there is no
1620 * alternative (help files).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001621 */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001622 while ((iconv(iconv_fd, (void *)&fromp, &from_size,
1623 &top, &to_size)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001624 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
1625 || from_size > CONV_RESTLEN)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001626 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001627 if (can_retry)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001628 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001629 if (conv_error == 0)
1630 conv_error = readfile_linenr(linecnt,
1631 ptr, (char_u *)top);
Bram Moolenaar42eeac32005-06-29 22:40:58 +00001632
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001633 /* Deal with a bad byte and continue with the next. */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001634 ++fromp;
1635 --from_size;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001636 if (bad_char_behavior == BAD_KEEP)
1637 {
1638 *top++ = *(fromp - 1);
1639 --to_size;
1640 }
1641 else if (bad_char_behavior != BAD_DROP)
1642 {
1643 *top++ = bad_char_behavior;
1644 --to_size;
1645 }
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001646 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001647
1648 if (from_size > 0)
1649 {
1650 /* Some remaining characters, keep them for the next
1651 * round. */
1652 mch_memmove(conv_rest, (char_u *)fromp, from_size);
1653 conv_restlen = (int)from_size;
1654 }
1655
1656 /* move the linerest to before the converted characters */
1657 line_start = ptr - linerest;
1658 mch_memmove(line_start, buffer, (size_t)linerest);
1659 size = (long)((char_u *)top - ptr);
1660 }
1661# endif
1662
1663# ifdef WIN3264
1664 if (fio_flags & FIO_CODEPAGE)
1665 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001666 char_u *src, *dst;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001667 WCHAR ucs2buf[3];
1668 int ucs2len;
1669 int codepage = FIO_GET_CP(fio_flags);
1670 int bytelen;
1671 int found_bad;
1672 char replstr[2];
1673
Bram Moolenaar071d4272004-06-13 20:20:40 +00001674 /*
1675 * Conversion from an MS-Windows codepage or UTF-8 to UTF-8 or
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001676 * a codepage, using standard MS-Windows functions. This
1677 * requires two steps:
1678 * 1. convert from 'fileencoding' to ucs-2
1679 * 2. convert from ucs-2 to 'encoding'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001680 *
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001681 * Because there may be illegal bytes AND an incomplete byte
1682 * sequence at the end, we may have to do the conversion one
1683 * character at a time to get it right.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001684 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001685
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001686 /* Replacement string for WideCharToMultiByte(). */
1687 if (bad_char_behavior > 0)
1688 replstr[0] = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001689 else
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001690 replstr[0] = '?';
1691 replstr[1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001692
1693 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001694 * Move the bytes to the end of the buffer, so that we have
1695 * room to put the result at the start.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001696 */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001697 src = ptr + real_size - size;
1698 mch_memmove(src, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001699
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001700 /*
1701 * Do the conversion.
1702 */
1703 dst = ptr;
1704 size = size;
1705 while (size > 0)
1706 {
1707 found_bad = FALSE;
1708
1709# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
1710 if (codepage == CP_UTF8)
1711 {
1712 /* Handle CP_UTF8 input ourselves to be able to handle
1713 * trailing bytes properly.
1714 * Get one UTF-8 character from src. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001715 bytelen = (int)utf_ptr2len_len(src, size);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001716 if (bytelen > size)
1717 {
1718 /* Only got some bytes of a character. Normally
1719 * it's put in "conv_rest", but if it's too long
1720 * deal with it as if they were illegal bytes. */
1721 if (bytelen <= CONV_RESTLEN)
1722 break;
1723
1724 /* weird overlong byte sequence */
1725 bytelen = size;
1726 found_bad = TRUE;
1727 }
1728 else
1729 {
Bram Moolenaarc01140a2006-03-24 22:21:52 +00001730 int u8c = utf_ptr2char(src);
1731
Bram Moolenaar86e01082005-12-29 22:45:34 +00001732 if (u8c > 0xffff || (*src >= 0x80 && bytelen == 1))
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001733 found_bad = TRUE;
1734 ucs2buf[0] = u8c;
1735 ucs2len = 1;
1736 }
1737 }
1738 else
1739# endif
1740 {
1741 /* We don't know how long the byte sequence is, try
1742 * from one to three bytes. */
1743 for (bytelen = 1; bytelen <= size && bytelen <= 3;
1744 ++bytelen)
1745 {
1746 ucs2len = MultiByteToWideChar(codepage,
1747 MB_ERR_INVALID_CHARS,
1748 (LPCSTR)src, bytelen,
1749 ucs2buf, 3);
1750 if (ucs2len > 0)
1751 break;
1752 }
1753 if (ucs2len == 0)
1754 {
1755 /* If we have only one byte then it's probably an
1756 * incomplete byte sequence. Otherwise discard
1757 * one byte as a bad character. */
1758 if (size == 1)
1759 break;
1760 found_bad = TRUE;
1761 bytelen = 1;
1762 }
1763 }
1764
1765 if (!found_bad)
1766 {
1767 int i;
1768
1769 /* Convert "ucs2buf[ucs2len]" to 'enc' in "dst". */
1770 if (enc_utf8)
1771 {
1772 /* From UCS-2 to UTF-8. Cannot fail. */
1773 for (i = 0; i < ucs2len; ++i)
1774 dst += utf_char2bytes(ucs2buf[i], dst);
1775 }
1776 else
1777 {
1778 BOOL bad = FALSE;
1779 int dstlen;
1780
1781 /* From UCS-2 to "enc_codepage". If the
1782 * conversion uses the default character "?",
1783 * the data doesn't fit in this encoding. */
1784 dstlen = WideCharToMultiByte(enc_codepage, 0,
1785 (LPCWSTR)ucs2buf, ucs2len,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001786 (LPSTR)dst, (int)(src - dst),
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001787 replstr, &bad);
1788 if (bad)
1789 found_bad = TRUE;
1790 else
1791 dst += dstlen;
1792 }
1793 }
1794
1795 if (found_bad)
1796 {
1797 /* Deal with bytes we can't convert. */
1798 if (can_retry)
1799 goto rewind_retry;
1800 if (conv_error == 0)
1801 conv_error = readfile_linenr(linecnt, ptr, dst);
1802 if (bad_char_behavior != BAD_DROP)
1803 {
1804 if (bad_char_behavior == BAD_KEEP)
1805 {
1806 mch_memmove(dst, src, bytelen);
1807 dst += bytelen;
1808 }
1809 else
1810 *dst++ = bad_char_behavior;
1811 }
1812 }
1813
1814 src += bytelen;
1815 size -= bytelen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001816 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001817
1818 if (size > 0)
1819 {
1820 /* An incomplete byte sequence remaining. */
1821 mch_memmove(conv_rest, src, size);
1822 conv_restlen = size;
1823 }
1824
1825 /* The new size is equal to how much "dst" was advanced. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001826 size = (long)(dst - ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001827 }
1828 else
1829# endif
Bram Moolenaar56718732006-03-15 22:53:57 +00001830# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001831 if (fio_flags & FIO_MACROMAN)
1832 {
1833 /*
1834 * Conversion from Apple MacRoman char encoding to UTF-8 or
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001835 * latin1. This is in os_mac_conv.c.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001836 */
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001837 if (macroman2enc(ptr, &size, real_size) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001838 goto rewind_retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001839 }
1840 else
1841# endif
1842 if (fio_flags != 0)
1843 {
1844 int u8c;
1845 char_u *dest;
1846 char_u *tail = NULL;
1847
1848 /*
1849 * "enc_utf8" set: Convert Unicode or Latin1 to UTF-8.
1850 * "enc_utf8" not set: Convert Unicode to Latin1.
1851 * Go from end to start through the buffer, because the number
1852 * of bytes may increase.
1853 * "dest" points to after where the UTF-8 bytes go, "p" points
1854 * to after the next character to convert.
1855 */
1856 dest = ptr + real_size;
1857 if (fio_flags == FIO_LATIN1 || fio_flags == FIO_UTF8)
1858 {
1859 p = ptr + size;
1860 if (fio_flags == FIO_UTF8)
1861 {
1862 /* Check for a trailing incomplete UTF-8 sequence */
1863 tail = ptr + size - 1;
1864 while (tail > ptr && (*tail & 0xc0) == 0x80)
1865 --tail;
1866 if (tail + utf_byte2len(*tail) <= ptr + size)
1867 tail = NULL;
1868 else
1869 p = tail;
1870 }
1871 }
1872 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1873 {
1874 /* Check for a trailing byte */
1875 p = ptr + (size & ~1);
1876 if (size & 1)
1877 tail = p;
1878 if ((fio_flags & FIO_UTF16) && p > ptr)
1879 {
1880 /* Check for a trailing leading word */
1881 if (fio_flags & FIO_ENDIAN_L)
1882 {
1883 u8c = (*--p << 8);
1884 u8c += *--p;
1885 }
1886 else
1887 {
1888 u8c = *--p;
1889 u8c += (*--p << 8);
1890 }
1891 if (u8c >= 0xd800 && u8c <= 0xdbff)
1892 tail = p;
1893 else
1894 p += 2;
1895 }
1896 }
1897 else /* FIO_UCS4 */
1898 {
1899 /* Check for trailing 1, 2 or 3 bytes */
1900 p = ptr + (size & ~3);
1901 if (size & 3)
1902 tail = p;
1903 }
1904
1905 /* If there is a trailing incomplete sequence move it to
1906 * conv_rest[]. */
1907 if (tail != NULL)
1908 {
1909 conv_restlen = (int)((ptr + size) - tail);
1910 mch_memmove(conv_rest, (char_u *)tail, conv_restlen);
1911 size -= conv_restlen;
1912 }
1913
1914
1915 while (p > ptr)
1916 {
1917 if (fio_flags & FIO_LATIN1)
1918 u8c = *--p;
1919 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1920 {
1921 if (fio_flags & FIO_ENDIAN_L)
1922 {
1923 u8c = (*--p << 8);
1924 u8c += *--p;
1925 }
1926 else
1927 {
1928 u8c = *--p;
1929 u8c += (*--p << 8);
1930 }
1931 if ((fio_flags & FIO_UTF16)
1932 && u8c >= 0xdc00 && u8c <= 0xdfff)
1933 {
1934 int u16c;
1935
1936 if (p == ptr)
1937 {
1938 /* Missing leading word. */
1939 if (can_retry)
1940 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001941 if (conv_error == 0)
1942 conv_error = readfile_linenr(linecnt,
1943 ptr, p);
1944 if (bad_char_behavior == BAD_DROP)
1945 continue;
1946 if (bad_char_behavior != BAD_KEEP)
1947 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001948 }
1949
1950 /* found second word of double-word, get the first
1951 * word and compute the resulting character */
1952 if (fio_flags & FIO_ENDIAN_L)
1953 {
1954 u16c = (*--p << 8);
1955 u16c += *--p;
1956 }
1957 else
1958 {
1959 u16c = *--p;
1960 u16c += (*--p << 8);
1961 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001962 u8c = 0x10000 + ((u16c & 0x3ff) << 10)
1963 + (u8c & 0x3ff);
1964
Bram Moolenaar071d4272004-06-13 20:20:40 +00001965 /* Check if the word is indeed a leading word. */
1966 if (u16c < 0xd800 || u16c > 0xdbff)
1967 {
1968 if (can_retry)
1969 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001970 if (conv_error == 0)
1971 conv_error = readfile_linenr(linecnt,
1972 ptr, p);
1973 if (bad_char_behavior == BAD_DROP)
1974 continue;
1975 if (bad_char_behavior != BAD_KEEP)
1976 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001977 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001978 }
1979 }
1980 else if (fio_flags & FIO_UCS4)
1981 {
1982 if (fio_flags & FIO_ENDIAN_L)
1983 {
Bram Moolenaardc1c9812017-10-27 22:15:24 +02001984 u8c = (unsigned)*--p << 24;
1985 u8c += (unsigned)*--p << 16;
1986 u8c += (unsigned)*--p << 8;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001987 u8c += *--p;
1988 }
1989 else /* big endian */
1990 {
1991 u8c = *--p;
Bram Moolenaardc1c9812017-10-27 22:15:24 +02001992 u8c += (unsigned)*--p << 8;
1993 u8c += (unsigned)*--p << 16;
1994 u8c += (unsigned)*--p << 24;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001995 }
1996 }
1997 else /* UTF-8 */
1998 {
1999 if (*--p < 0x80)
2000 u8c = *p;
2001 else
2002 {
2003 len = utf_head_off(ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002004 p -= len;
2005 u8c = utf_ptr2char(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002006 if (len == 0)
2007 {
2008 /* Not a valid UTF-8 character, retry with
2009 * another fenc when possible, otherwise just
2010 * report the error. */
2011 if (can_retry)
2012 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002013 if (conv_error == 0)
2014 conv_error = readfile_linenr(linecnt,
2015 ptr, p);
2016 if (bad_char_behavior == BAD_DROP)
2017 continue;
2018 if (bad_char_behavior != BAD_KEEP)
2019 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002020 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002021 }
2022 }
2023 if (enc_utf8) /* produce UTF-8 */
2024 {
2025 dest -= utf_char2len(u8c);
2026 (void)utf_char2bytes(u8c, dest);
2027 }
2028 else /* produce Latin1 */
2029 {
2030 --dest;
2031 if (u8c >= 0x100)
2032 {
2033 /* character doesn't fit in latin1, retry with
2034 * another fenc when possible, otherwise just
2035 * report the error. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002036 if (can_retry)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002037 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002038 if (conv_error == 0)
2039 conv_error = readfile_linenr(linecnt, ptr, p);
2040 if (bad_char_behavior == BAD_DROP)
2041 ++dest;
2042 else if (bad_char_behavior == BAD_KEEP)
2043 *dest = u8c;
2044 else if (eap != NULL && eap->bad_char != 0)
2045 *dest = bad_char_behavior;
2046 else
2047 *dest = 0xBF;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002048 }
2049 else
2050 *dest = u8c;
2051 }
2052 }
2053
2054 /* move the linerest to before the converted characters */
2055 line_start = dest - linerest;
2056 mch_memmove(line_start, buffer, (size_t)linerest);
2057 size = (long)((ptr + real_size) - dest);
2058 ptr = dest;
2059 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002060 else if (enc_utf8 && !curbuf->b_p_bin)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002061 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002062 int incomplete_tail = FALSE;
2063
2064 /* Reading UTF-8: Check if the bytes are valid UTF-8. */
2065 for (p = ptr; ; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002066 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002067 int todo = (int)((ptr + size) - p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002068 int l;
2069
2070 if (todo <= 0)
2071 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002072 if (*p >= 0x80)
2073 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002074 /* A length of 1 means it's an illegal byte. Accept
2075 * an incomplete character at the end though, the next
2076 * read() will get the next bytes, we'll check it
2077 * then. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002078 l = utf_ptr2len_len(p, todo);
Bram Moolenaarf453d352008-06-04 17:37:34 +00002079 if (l > todo && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002080 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002081 /* Avoid retrying with a different encoding when
2082 * a truncated file is more likely, or attempting
2083 * to read the rest of an incomplete sequence when
2084 * we have already done so. */
2085 if (p > ptr || filesize > 0)
2086 incomplete_tail = TRUE;
2087 /* Incomplete byte sequence, move it to conv_rest[]
2088 * and try to read the rest of it, unless we've
2089 * already done so. */
2090 if (p > ptr)
2091 {
2092 conv_restlen = todo;
2093 mch_memmove(conv_rest, p, conv_restlen);
2094 size -= conv_restlen;
2095 break;
2096 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002097 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002098 if (l == 1 || l > todo)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002099 {
2100 /* Illegal byte. If we can try another encoding
Bram Moolenaarf453d352008-06-04 17:37:34 +00002101 * do that, unless at EOF where a truncated
2102 * file is more likely than a conversion error. */
2103 if (can_retry && !incomplete_tail)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002104 break;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002105# ifdef USE_ICONV
2106 /* When we did a conversion report an error. */
2107 if (iconv_fd != (iconv_t)-1 && conv_error == 0)
2108 conv_error = readfile_linenr(linecnt, ptr, p);
2109# endif
Bram Moolenaarf453d352008-06-04 17:37:34 +00002110 /* Remember the first linenr with an illegal byte */
2111 if (conv_error == 0 && illegal_byte == 0)
2112 illegal_byte = readfile_linenr(linecnt, ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002113
2114 /* Drop, keep or replace the bad byte. */
2115 if (bad_char_behavior == BAD_DROP)
2116 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002117 mch_memmove(p, p + 1, todo - 1);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002118 --p;
2119 --size;
2120 }
2121 else if (bad_char_behavior != BAD_KEEP)
2122 *p = bad_char_behavior;
2123 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002124 else
2125 p += l - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002126 }
2127 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002128 if (p < ptr + size && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002129 {
2130 /* Detected a UTF-8 error. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002131rewind_retry:
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002132 /* Retry reading with another conversion. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002133# if defined(FEAT_EVAL) && defined(USE_ICONV)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002134 if (*p_ccv != NUL && iconv_fd != (iconv_t)-1)
2135 /* iconv() failed, try 'charconvert' */
2136 did_iconv = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002137 else
2138# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002139 /* use next item from 'fileencodings' */
2140 advance_fenc = TRUE;
2141 file_rewind = TRUE;
2142 goto retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002143 }
2144 }
2145#endif
2146
2147 /* count the number of characters (after conversion!) */
2148 filesize += size;
2149
2150 /*
2151 * when reading the first part of a file: guess EOL type
2152 */
2153 if (fileformat == EOL_UNKNOWN)
2154 {
2155 /* First try finding a NL, for Dos and Unix */
2156 if (try_dos || try_unix)
2157 {
Bram Moolenaarc6b72172015-02-27 17:48:09 +01002158 /* Reset the carriage return counter. */
2159 if (try_mac)
2160 try_mac = 1;
2161
Bram Moolenaar071d4272004-06-13 20:20:40 +00002162 for (p = ptr; p < ptr + size; ++p)
2163 {
2164 if (*p == NL)
2165 {
2166 if (!try_unix
2167 || (try_dos && p > ptr && p[-1] == CAR))
2168 fileformat = EOL_DOS;
2169 else
2170 fileformat = EOL_UNIX;
2171 break;
2172 }
Bram Moolenaar05eb6122015-02-17 14:15:19 +01002173 else if (*p == CAR && try_mac)
2174 try_mac++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002175 }
2176
2177 /* Don't give in to EOL_UNIX if EOL_MAC is more likely */
2178 if (fileformat == EOL_UNIX && try_mac)
2179 {
2180 /* Need to reset the counters when retrying fenc. */
2181 try_mac = 1;
2182 try_unix = 1;
2183 for (; p >= ptr && *p != CAR; p--)
2184 ;
2185 if (p >= ptr)
2186 {
2187 for (p = ptr; p < ptr + size; ++p)
2188 {
2189 if (*p == NL)
2190 try_unix++;
2191 else if (*p == CAR)
2192 try_mac++;
2193 }
2194 if (try_mac > try_unix)
2195 fileformat = EOL_MAC;
2196 }
2197 }
Bram Moolenaar05eb6122015-02-17 14:15:19 +01002198 else if (fileformat == EOL_UNKNOWN && try_mac == 1)
2199 /* Looking for CR but found no end-of-line markers at
2200 * all: use the default format. */
2201 fileformat = default_fileformat();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002202 }
2203
2204 /* No NL found: may use Mac format */
2205 if (fileformat == EOL_UNKNOWN && try_mac)
2206 fileformat = EOL_MAC;
2207
2208 /* Still nothing found? Use first format in 'ffs' */
2209 if (fileformat == EOL_UNKNOWN)
2210 fileformat = default_fileformat();
2211
2212 /* if editing a new file: may set p_tx and p_ff */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002213 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002214 set_fileformat(fileformat, OPT_LOCAL);
2215 }
2216 }
2217
2218 /*
2219 * This loop is executed once for every character read.
2220 * Keep it fast!
2221 */
2222 if (fileformat == EOL_MAC)
2223 {
2224 --ptr;
2225 while (++ptr, --size >= 0)
2226 {
2227 /* catch most common case first */
2228 if ((c = *ptr) != NUL && c != CAR && c != NL)
2229 continue;
2230 if (c == NUL)
2231 *ptr = NL; /* NULs are replaced by newlines! */
2232 else if (c == NL)
2233 *ptr = CAR; /* NLs are replaced by CRs! */
2234 else
2235 {
2236 if (skip_count == 0)
2237 {
2238 *ptr = NUL; /* end of line */
2239 len = (colnr_T) (ptr - line_start + 1);
2240 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2241 {
2242 error = TRUE;
2243 break;
2244 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002245#ifdef FEAT_PERSISTENT_UNDO
2246 if (read_undo_file)
2247 sha256_update(&sha_ctx, line_start, len);
2248#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002249 ++lnum;
2250 if (--read_count == 0)
2251 {
2252 error = TRUE; /* break loop */
2253 line_start = ptr; /* nothing left to write */
2254 break;
2255 }
2256 }
2257 else
2258 --skip_count;
2259 line_start = ptr + 1;
2260 }
2261 }
2262 }
2263 else
2264 {
2265 --ptr;
2266 while (++ptr, --size >= 0)
2267 {
2268 if ((c = *ptr) != NUL && c != NL) /* catch most common case */
2269 continue;
2270 if (c == NUL)
2271 *ptr = NL; /* NULs are replaced by newlines! */
2272 else
2273 {
2274 if (skip_count == 0)
2275 {
2276 *ptr = NUL; /* end of line */
2277 len = (colnr_T)(ptr - line_start + 1);
2278 if (fileformat == EOL_DOS)
2279 {
Bram Moolenaar2aa5f692017-01-24 15:46:48 +01002280 if (ptr > line_start && ptr[-1] == CAR)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002281 {
Bram Moolenaar2aa5f692017-01-24 15:46:48 +01002282 /* remove CR before NL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002283 ptr[-1] = NUL;
2284 --len;
2285 }
2286 /*
2287 * Reading in Dos format, but no CR-LF found!
2288 * When 'fileformats' includes "unix", delete all
2289 * the lines read so far and start all over again.
2290 * Otherwise give an error message later.
2291 */
2292 else if (ff_error != EOL_DOS)
2293 {
2294 if ( try_unix
2295 && !read_stdin
2296 && (read_buffer
Bram Moolenaar8767f522016-07-01 17:17:39 +02002297 || vim_lseek(fd, (off_T)0L, SEEK_SET)
2298 == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002299 {
2300 fileformat = EOL_UNIX;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002301 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002302 set_fileformat(EOL_UNIX, OPT_LOCAL);
2303 file_rewind = TRUE;
2304 keep_fileformat = TRUE;
2305 goto retry;
2306 }
2307 ff_error = EOL_DOS;
2308 }
2309 }
2310 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2311 {
2312 error = TRUE;
2313 break;
2314 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002315#ifdef FEAT_PERSISTENT_UNDO
2316 if (read_undo_file)
2317 sha256_update(&sha_ctx, line_start, len);
2318#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002319 ++lnum;
2320 if (--read_count == 0)
2321 {
2322 error = TRUE; /* break loop */
2323 line_start = ptr; /* nothing left to write */
2324 break;
2325 }
2326 }
2327 else
2328 --skip_count;
2329 line_start = ptr + 1;
2330 }
2331 }
2332 }
2333 linerest = (long)(ptr - line_start);
2334 ui_breakcheck();
2335 }
2336
2337failed:
2338 /* not an error, max. number of lines reached */
2339 if (error && read_count == 0)
2340 error = FALSE;
2341
2342 /*
2343 * If we get EOF in the middle of a line, note the fact and
2344 * complete the line ourselves.
2345 * In Dos format ignore a trailing CTRL-Z, unless 'binary' set.
2346 */
2347 if (!error
2348 && !got_int
2349 && linerest != 0
2350 && !(!curbuf->b_p_bin
2351 && fileformat == EOL_DOS
2352 && *line_start == Ctrl_Z
2353 && ptr == line_start + 1))
2354 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002355 /* remember for when writing */
2356 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002357 curbuf->b_p_eol = FALSE;
2358 *ptr = NUL;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002359 len = (colnr_T)(ptr - line_start + 1);
2360 if (ml_append(lnum, line_start, len, newfile) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002361 error = TRUE;
2362 else
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002363 {
2364#ifdef FEAT_PERSISTENT_UNDO
2365 if (read_undo_file)
2366 sha256_update(&sha_ctx, line_start, len);
2367#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002368 read_no_eol_lnum = ++lnum;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002369 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002370 }
2371
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002372 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002373 save_file_ff(curbuf); /* remember the current file format */
2374
2375#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002376 if (curbuf->b_cryptstate != NULL)
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002377 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002378 crypt_free_state(curbuf->b_cryptstate);
2379 curbuf->b_cryptstate = NULL;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002380 }
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002381 if (cryptkey != NULL && cryptkey != curbuf->b_p_key)
2382 crypt_free_key(cryptkey);
2383 /* Don't set cryptkey to NULL, it's used below as a flag that
2384 * encryption was used. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002385#endif
2386
2387#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002388 /* If editing a new file: set 'fenc' for the current buffer.
2389 * Also for ":read ++edit file". */
2390 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002391 set_string_option_direct((char_u *)"fenc", -1, fenc,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00002392 OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002393 if (fenc_alloced)
2394 vim_free(fenc);
2395# ifdef USE_ICONV
2396 if (iconv_fd != (iconv_t)-1)
2397 {
2398 iconv_close(iconv_fd);
2399 iconv_fd = (iconv_t)-1;
2400 }
2401# endif
2402#endif
2403
2404 if (!read_buffer && !read_stdin)
2405 close(fd); /* errors are ignored */
Bram Moolenaarf05da212009-11-17 16:13:15 +00002406#ifdef HAVE_FD_CLOEXEC
2407 else
2408 {
2409 int fdflags = fcntl(fd, F_GETFD);
2410 if (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0)
Bram Moolenaarfbc4b4d2016-02-07 15:14:01 +01002411 (void)fcntl(fd, F_SETFD, fdflags | FD_CLOEXEC);
Bram Moolenaarf05da212009-11-17 16:13:15 +00002412 }
2413#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002414 vim_free(buffer);
2415
2416#ifdef HAVE_DUP
2417 if (read_stdin)
2418 {
2419 /* Use stderr for stdin, makes shell commands work. */
2420 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00002421 ignored = dup(2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002422 }
2423#endif
2424
2425#ifdef FEAT_MBYTE
2426 if (tmpname != NULL)
2427 {
2428 mch_remove(tmpname); /* delete converted file */
2429 vim_free(tmpname);
2430 }
2431#endif
2432 --no_wait_return; /* may wait for return now */
2433
2434 /*
2435 * In recovery mode everything but autocommands is skipped.
2436 */
2437 if (!recoverymode)
2438 {
2439 /* need to delete the last line, which comes from the empty buffer */
2440 if (newfile && wasempty && !(curbuf->b_ml.ml_flags & ML_EMPTY))
2441 {
2442#ifdef FEAT_NETBEANS_INTG
2443 netbeansFireChanges = 0;
2444#endif
2445 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
2446#ifdef FEAT_NETBEANS_INTG
2447 netbeansFireChanges = 1;
2448#endif
2449 --linecnt;
2450 }
2451 linecnt = curbuf->b_ml.ml_line_count - linecnt;
2452 if (filesize == 0)
2453 linecnt = 0;
2454 if (newfile || read_buffer)
Bram Moolenaar7263a772007-05-10 17:35:54 +00002455 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002456 redraw_curbuf_later(NOT_VALID);
Bram Moolenaar7263a772007-05-10 17:35:54 +00002457#ifdef FEAT_DIFF
2458 /* After reading the text into the buffer the diff info needs to
2459 * be updated. */
2460 diff_invalidate(curbuf);
2461#endif
2462#ifdef FEAT_FOLDING
2463 /* All folds in the window are invalid now. Mark them for update
2464 * before triggering autocommands. */
2465 foldUpdateAll(curwin);
2466#endif
2467 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002468 else if (linecnt) /* appended at least one line */
2469 appended_lines_mark(from, linecnt);
2470
Bram Moolenaar071d4272004-06-13 20:20:40 +00002471#ifndef ALWAYS_USE_GUI
2472 /*
2473 * If we were reading from the same terminal as where messages go,
2474 * the screen will have been messed up.
2475 * Switch on raw mode now and clear the screen.
2476 */
2477 if (read_stdin)
2478 {
2479 settmode(TMODE_RAW); /* set to raw mode */
2480 starttermcap();
2481 screenclear();
2482 }
2483#endif
2484
2485 if (got_int)
2486 {
2487 if (!(flags & READ_DUMMY))
2488 {
2489 filemess(curbuf, sfname, (char_u *)_(e_interr), 0);
2490 if (newfile)
2491 curbuf->b_p_ro = TRUE; /* must use "w!" now */
2492 }
2493 msg_scroll = msg_save;
2494#ifdef FEAT_VIMINFO
2495 check_marks_read();
2496#endif
2497 return OK; /* an interrupt isn't really an error */
2498 }
2499
2500 if (!filtering && !(flags & READ_DUMMY))
2501 {
2502 msg_add_fname(curbuf, sfname); /* fname in IObuff with quotes */
2503 c = FALSE;
2504
2505#ifdef UNIX
2506# ifdef S_ISFIFO
2507 if (S_ISFIFO(perm)) /* fifo or socket */
2508 {
2509 STRCAT(IObuff, _("[fifo/socket]"));
2510 c = TRUE;
2511 }
2512# else
2513# ifdef S_IFIFO
2514 if ((perm & S_IFMT) == S_IFIFO) /* fifo */
2515 {
2516 STRCAT(IObuff, _("[fifo]"));
2517 c = TRUE;
2518 }
2519# endif
2520# ifdef S_IFSOCK
2521 if ((perm & S_IFMT) == S_IFSOCK) /* or socket */
2522 {
2523 STRCAT(IObuff, _("[socket]"));
2524 c = TRUE;
2525 }
2526# endif
2527# endif
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002528# ifdef OPEN_CHR_FILES
2529 if (S_ISCHR(perm)) /* or character special */
2530 {
2531 STRCAT(IObuff, _("[character special]"));
2532 c = TRUE;
2533 }
2534# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002535#endif
2536 if (curbuf->b_p_ro)
2537 {
2538 STRCAT(IObuff, shortmess(SHM_RO) ? _("[RO]") : _("[readonly]"));
2539 c = TRUE;
2540 }
2541 if (read_no_eol_lnum)
2542 {
2543 msg_add_eol();
2544 c = TRUE;
2545 }
2546 if (ff_error == EOL_DOS)
2547 {
2548 STRCAT(IObuff, _("[CR missing]"));
2549 c = TRUE;
2550 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002551 if (split)
2552 {
2553 STRCAT(IObuff, _("[long lines split]"));
2554 c = TRUE;
2555 }
2556#ifdef FEAT_MBYTE
2557 if (notconverted)
2558 {
2559 STRCAT(IObuff, _("[NOT converted]"));
2560 c = TRUE;
2561 }
2562 else if (converted)
2563 {
2564 STRCAT(IObuff, _("[converted]"));
2565 c = TRUE;
2566 }
2567#endif
2568#ifdef FEAT_CRYPT
2569 if (cryptkey != NULL)
2570 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002571 crypt_append_msg(curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002572 c = TRUE;
2573 }
2574#endif
2575#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002576 if (conv_error != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002577 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002578 sprintf((char *)IObuff + STRLEN(IObuff),
2579 _("[CONVERSION ERROR in line %ld]"), (long)conv_error);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002580 c = TRUE;
2581 }
2582 else if (illegal_byte > 0)
2583 {
2584 sprintf((char *)IObuff + STRLEN(IObuff),
2585 _("[ILLEGAL BYTE in line %ld]"), (long)illegal_byte);
2586 c = TRUE;
2587 }
2588 else
2589#endif
2590 if (error)
2591 {
2592 STRCAT(IObuff, _("[READ ERRORS]"));
2593 c = TRUE;
2594 }
2595 if (msg_add_fileformat(fileformat))
2596 c = TRUE;
2597#ifdef FEAT_CRYPT
2598 if (cryptkey != NULL)
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002599 msg_add_lines(c, (long)linecnt, filesize
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002600 - crypt_get_header_len(crypt_get_method_nr(curbuf)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002601 else
2602#endif
2603 msg_add_lines(c, (long)linecnt, filesize);
2604
2605 vim_free(keep_msg);
2606 keep_msg = NULL;
2607 msg_scrolled_ign = TRUE;
2608#ifdef ALWAYS_USE_GUI
2609 /* Don't show the message when reading stdin, it would end up in a
2610 * message box (which might be shown when exiting!) */
2611 if (read_stdin || read_buffer)
2612 p = msg_may_trunc(FALSE, IObuff);
2613 else
2614#endif
2615 p = msg_trunc_attr(IObuff, FALSE, 0);
2616 if (read_stdin || read_buffer || restart_edit != 0
Bram Moolenaar1c7715d2005-10-03 22:02:18 +00002617 || (msg_scrolled != 0 && !need_wait_return))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002618 /* Need to repeat the message after redrawing when:
2619 * - When reading from stdin (the screen will be cleared next).
2620 * - When restart_edit is set (otherwise there will be a delay
2621 * before redrawing).
2622 * - When the screen was scrolled but there is no wait-return
2623 * prompt. */
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002624 set_keep_msg(p, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002625 msg_scrolled_ign = FALSE;
2626 }
2627
2628 /* with errors writing the file requires ":w!" */
2629 if (newfile && (error
2630#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002631 || conv_error != 0
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002632 || (illegal_byte > 0 && bad_char_behavior != BAD_KEEP)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002633#endif
2634 ))
2635 curbuf->b_p_ro = TRUE;
2636
2637 u_clearline(); /* cannot use "U" command after adding lines */
2638
2639 /*
2640 * In Ex mode: cursor at last new line.
2641 * Otherwise: cursor at first new line.
2642 */
2643 if (exmode_active)
2644 curwin->w_cursor.lnum = from + linecnt;
2645 else
2646 curwin->w_cursor.lnum = from + 1;
2647 check_cursor_lnum();
2648 beginline(BL_WHITE | BL_FIX); /* on first non-blank */
2649
2650 /*
2651 * Set '[ and '] marks to the newly read lines.
2652 */
2653 curbuf->b_op_start.lnum = from + 1;
2654 curbuf->b_op_start.col = 0;
2655 curbuf->b_op_end.lnum = from + linecnt;
2656 curbuf->b_op_end.col = 0;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002657
2658#ifdef WIN32
2659 /*
2660 * Work around a weird problem: When a file has two links (only
2661 * possible on NTFS) and we write through one link, then stat() it
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00002662 * through the other link, the timestamp information may be wrong.
Bram Moolenaar03f48552006-02-28 23:52:23 +00002663 * It's correct again after reading the file, thus reset the timestamp
2664 * here.
2665 */
2666 if (newfile && !read_stdin && !read_buffer
2667 && mch_stat((char *)fname, &st) >= 0)
2668 {
2669 buf_store_time(curbuf, &st, fname);
2670 curbuf->b_mtime_read = curbuf->b_mtime;
2671 }
2672#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002673 }
2674 msg_scroll = msg_save;
2675
2676#ifdef FEAT_VIMINFO
2677 /*
2678 * Get the marks before executing autocommands, so they can be used there.
2679 */
2680 check_marks_read();
2681#endif
2682
Bram Moolenaar071d4272004-06-13 20:20:40 +00002683 /*
Bram Moolenaar34d72d42015-07-17 14:18:08 +02002684 * We remember if the last line of the read didn't have
2685 * an eol even when 'binary' is off, to support turning 'fixeol' off,
2686 * or writing the read again with 'binary' on. The latter is required
2687 * for ":autocmd FileReadPost *.gz set bin|'[,']!gunzip" to work.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002688 */
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002689 curbuf->b_no_eol_lnum = read_no_eol_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002690
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02002691 /* When reloading a buffer put the cursor at the first line that is
2692 * different. */
2693 if (flags & READ_KEEP_UNDO)
2694 u_find_first_changed();
2695
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002696#ifdef FEAT_PERSISTENT_UNDO
2697 /*
2698 * When opening a new file locate undo info and read it.
2699 */
2700 if (read_undo_file)
2701 {
2702 char_u hash[UNDO_HASH_SIZE];
2703
2704 sha256_finish(&sha_ctx, hash);
Bram Moolenaar6ed8ed82010-05-30 20:40:11 +02002705 u_read_undo(NULL, hash, fname);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002706 }
2707#endif
2708
Bram Moolenaardf177f62005-02-22 08:39:57 +00002709#ifdef FEAT_AUTOCMD
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02002710 if (!read_stdin && !read_fifo && (!read_buffer || sfname != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002711 {
2712 int m = msg_scroll;
2713 int n = msg_scrolled;
2714
2715 /* Save the fileformat now, otherwise the buffer will be considered
2716 * modified if the format/encoding was automatically detected. */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002717 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002718 save_file_ff(curbuf);
2719
2720 /*
2721 * The output from the autocommands should not overwrite anything and
2722 * should not be overwritten: Set msg_scroll, restore its value if no
2723 * output was done.
2724 */
2725 msg_scroll = TRUE;
2726 if (filtering)
2727 apply_autocmds_exarg(EVENT_FILTERREADPOST, NULL, sfname,
2728 FALSE, curbuf, eap);
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02002729 else if (newfile || (read_buffer && sfname != NULL))
Bram Moolenaarc3691332016-04-20 12:49:49 +02002730 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002731 apply_autocmds_exarg(EVENT_BUFREADPOST, NULL, sfname,
2732 FALSE, curbuf, eap);
Bram Moolenaarc3691332016-04-20 12:49:49 +02002733 if (!au_did_filetype && *curbuf->b_p_ft != NUL)
2734 /*
2735 * EVENT_FILETYPE was not triggered but the buffer already has a
2736 * filetype. Trigger EVENT_FILETYPE using the existing filetype.
2737 */
2738 apply_autocmds(EVENT_FILETYPE, curbuf->b_p_ft, curbuf->b_fname,
2739 TRUE, curbuf);
2740 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002741 else
2742 apply_autocmds_exarg(EVENT_FILEREADPOST, sfname, sfname,
2743 FALSE, NULL, eap);
2744 if (msg_scrolled == n)
2745 msg_scroll = m;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002746# ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002747 if (aborting()) /* autocmds may abort script processing */
2748 return FAIL;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002749# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002750 }
2751#endif
2752
2753 if (recoverymode && error)
2754 return FAIL;
2755 return OK;
2756}
2757
Bram Moolenaarf04507d2016-08-20 15:05:39 +02002758#if defined(OPEN_CHR_FILES) || defined(PROTO)
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002759/*
2760 * Returns TRUE if the file name argument is of the form "/dev/fd/\d\+",
2761 * which is the name of files used for process substitution output by
2762 * some shells on some operating systems, e.g., bash on SunOS.
2763 * Do not accept "/dev/fd/[012]", opening these may hang Vim.
2764 */
Bram Moolenaarf04507d2016-08-20 15:05:39 +02002765 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002766is_dev_fd_file(char_u *fname)
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002767{
2768 return (STRNCMP(fname, "/dev/fd/", 8) == 0
2769 && VIM_ISDIGIT(fname[8])
2770 && *skipdigits(fname + 9) == NUL
2771 && (fname[9] != NUL
2772 || (fname[8] != '0' && fname[8] != '1' && fname[8] != '2')));
2773}
2774#endif
2775
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002776#ifdef FEAT_MBYTE
2777
2778/*
2779 * From the current line count and characters read after that, estimate the
2780 * line number where we are now.
2781 * Used for error messages that include a line number.
2782 */
2783 static linenr_T
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002784readfile_linenr(
2785 linenr_T linecnt, /* line count before reading more bytes */
2786 char_u *p, /* start of more bytes read */
2787 char_u *endp) /* end of more bytes read */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002788{
2789 char_u *s;
2790 linenr_T lnum;
2791
2792 lnum = curbuf->b_ml.ml_line_count - linecnt + 1;
2793 for (s = p; s < endp; ++s)
2794 if (*s == '\n')
2795 ++lnum;
2796 return lnum;
2797}
2798#endif
2799
Bram Moolenaar071d4272004-06-13 20:20:40 +00002800/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00002801 * Fill "*eap" to force the 'fileencoding', 'fileformat' and 'binary to be
2802 * equal to the buffer "buf". Used for calling readfile().
Bram Moolenaar071d4272004-06-13 20:20:40 +00002803 * Returns OK or FAIL.
2804 */
2805 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002806prep_exarg(exarg_T *eap, buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002807{
2808 eap->cmd = alloc((unsigned)(STRLEN(buf->b_p_ff)
2809#ifdef FEAT_MBYTE
2810 + STRLEN(buf->b_p_fenc)
2811#endif
2812 + 15));
2813 if (eap->cmd == NULL)
2814 return FAIL;
2815
2816#ifdef FEAT_MBYTE
2817 sprintf((char *)eap->cmd, "e ++ff=%s ++enc=%s", buf->b_p_ff, buf->b_p_fenc);
2818 eap->force_enc = 14 + (int)STRLEN(buf->b_p_ff);
Bram Moolenaar195d6352005-12-19 22:08:24 +00002819 eap->bad_char = buf->b_bad_char;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002820#else
2821 sprintf((char *)eap->cmd, "e ++ff=%s", buf->b_p_ff);
2822#endif
2823 eap->force_ff = 7;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002824
2825 eap->force_bin = buf->b_p_bin ? FORCE_BIN : FORCE_NOBIN;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002826 eap->read_edit = FALSE;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002827 eap->forceit = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002828 return OK;
2829}
2830
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002831/*
2832 * Set default or forced 'fileformat' and 'binary'.
2833 */
2834 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002835set_file_options(int set_options, exarg_T *eap)
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002836{
2837 /* set default 'fileformat' */
2838 if (set_options)
2839 {
2840 if (eap != NULL && eap->force_ff != 0)
2841 set_fileformat(get_fileformat_force(curbuf, eap), OPT_LOCAL);
2842 else if (*p_ffs != NUL)
2843 set_fileformat(default_fileformat(), OPT_LOCAL);
2844 }
2845
2846 /* set or reset 'binary' */
2847 if (eap != NULL && eap->force_bin != 0)
2848 {
2849 int oldval = curbuf->b_p_bin;
2850
2851 curbuf->b_p_bin = (eap->force_bin == FORCE_BIN);
2852 set_options_bin(oldval, curbuf->b_p_bin, OPT_LOCAL);
2853 }
2854}
2855
2856#if defined(FEAT_MBYTE) || defined(PROTO)
2857/*
2858 * Set forced 'fileencoding'.
2859 */
2860 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002861set_forced_fenc(exarg_T *eap)
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002862{
2863 if (eap->force_enc != 0)
2864 {
2865 char_u *fenc = enc_canonize(eap->cmd + eap->force_enc);
2866
2867 if (fenc != NULL)
2868 set_string_option_direct((char_u *)"fenc", -1,
2869 fenc, OPT_FREE|OPT_LOCAL, 0);
2870 vim_free(fenc);
2871 }
2872}
2873
Bram Moolenaar071d4272004-06-13 20:20:40 +00002874/*
2875 * Find next fileencoding to use from 'fileencodings'.
2876 * "pp" points to fenc_next. It's advanced to the next item.
2877 * When there are no more items, an empty string is returned and *pp is set to
2878 * NULL.
2879 * When *pp is not set to NULL, the result is in allocated memory.
2880 */
2881 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002882next_fenc(char_u **pp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002883{
2884 char_u *p;
2885 char_u *r;
2886
2887 if (**pp == NUL)
2888 {
2889 *pp = NULL;
2890 return (char_u *)"";
2891 }
2892 p = vim_strchr(*pp, ',');
2893 if (p == NULL)
2894 {
2895 r = enc_canonize(*pp);
2896 *pp += STRLEN(*pp);
2897 }
2898 else
2899 {
2900 r = vim_strnsave(*pp, (int)(p - *pp));
2901 *pp = p + 1;
2902 if (r != NULL)
2903 {
2904 p = enc_canonize(r);
2905 vim_free(r);
2906 r = p;
2907 }
2908 }
2909 if (r == NULL) /* out of memory */
2910 {
2911 r = (char_u *)"";
2912 *pp = NULL;
2913 }
2914 return r;
2915}
2916
2917# ifdef FEAT_EVAL
2918/*
2919 * Convert a file with the 'charconvert' expression.
2920 * This closes the file which is to be read, converts it and opens the
2921 * resulting file for reading.
2922 * Returns name of the resulting converted file (the caller should delete it
2923 * after reading it).
2924 * Returns NULL if the conversion failed ("*fdp" is not set) .
2925 */
2926 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002927readfile_charconvert(
2928 char_u *fname, /* name of input file */
2929 char_u *fenc, /* converted from */
2930 int *fdp) /* in/out: file descriptor of file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002931{
2932 char_u *tmpname;
2933 char_u *errmsg = NULL;
2934
Bram Moolenaare5c421c2015-03-31 13:33:08 +02002935 tmpname = vim_tempname('r', FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002936 if (tmpname == NULL)
2937 errmsg = (char_u *)_("Can't find temp file for conversion");
2938 else
2939 {
2940 close(*fdp); /* close the input file, ignore errors */
2941 *fdp = -1;
2942 if (eval_charconvert(fenc, enc_utf8 ? (char_u *)"utf-8" : p_enc,
2943 fname, tmpname) == FAIL)
2944 errmsg = (char_u *)_("Conversion with 'charconvert' failed");
2945 if (errmsg == NULL && (*fdp = mch_open((char *)tmpname,
2946 O_RDONLY | O_EXTRA, 0)) < 0)
2947 errmsg = (char_u *)_("can't read output of 'charconvert'");
2948 }
2949
2950 if (errmsg != NULL)
2951 {
2952 /* Don't use emsg(), it breaks mappings, the retry with
2953 * another type of conversion might still work. */
2954 MSG(errmsg);
2955 if (tmpname != NULL)
2956 {
2957 mch_remove(tmpname); /* delete converted file */
2958 vim_free(tmpname);
2959 tmpname = NULL;
2960 }
2961 }
2962
2963 /* If the input file is closed, open it (caller should check for error). */
2964 if (*fdp < 0)
2965 *fdp = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
2966
2967 return tmpname;
2968}
2969# endif
2970
2971#endif
2972
2973#ifdef FEAT_VIMINFO
2974/*
2975 * Read marks for the current buffer from the viminfo file, when we support
2976 * buffer marks and the buffer has a name.
2977 */
2978 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002979check_marks_read(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002980{
2981 if (!curbuf->b_marks_read && get_viminfo_parameter('\'') > 0
2982 && curbuf->b_ffname != NULL)
Bram Moolenaard812df62008-11-09 12:46:09 +00002983 read_viminfo(NULL, VIF_WANT_MARKS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002984
2985 /* Always set b_marks_read; needed when 'viminfo' is changed to include
2986 * the ' parameter after opening a buffer. */
2987 curbuf->b_marks_read = TRUE;
2988}
2989#endif
2990
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002991#if defined(FEAT_CRYPT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002992/*
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002993 * Check for magic number used for encryption. Applies to the current buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002994 * If found, the magic number is removed from ptr[*sizep] and *sizep and
2995 * *filesizep are updated.
2996 * Return the (new) encryption key, NULL for no encryption.
2997 */
2998 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002999check_for_cryptkey(
3000 char_u *cryptkey, /* previous encryption key or NULL */
3001 char_u *ptr, /* pointer to read bytes */
3002 long *sizep, /* length of read bytes */
Bram Moolenaar8767f522016-07-01 17:17:39 +02003003 off_T *filesizep, /* nr of bytes used from file */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003004 int newfile, /* editing a new buffer */
3005 char_u *fname, /* file name to display */
3006 int *did_ask) /* flag: whether already asked for key */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003007{
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003008 int method = crypt_method_nr_from_magic((char *)ptr, *sizep);
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02003009 int b_p_ro = curbuf->b_p_ro;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003010
3011 if (method >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003012 {
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02003013 /* Mark the buffer as read-only until the decryption has taken place.
3014 * Avoids accidentally overwriting the file with garbage. */
3015 curbuf->b_p_ro = TRUE;
3016
Bram Moolenaar2be79502014-08-13 21:58:28 +02003017 /* Set the cryptmethod local to the buffer. */
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003018 crypt_set_cm_option(curbuf, method);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02003019 if (cryptkey == NULL && !*did_ask)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003020 {
3021 if (*curbuf->b_p_key)
3022 cryptkey = curbuf->b_p_key;
3023 else
3024 {
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003025 /* When newfile is TRUE, store the typed key in the 'key'
3026 * option and don't free it. bf needs hash of the key saved.
Bram Moolenaarf50a2532010-05-21 15:36:08 +02003027 * Don't ask for the key again when first time Enter was hit.
3028 * Happens when retrying to detect encoding. */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003029 smsg((char_u *)_(need_key_msg), fname);
3030 msg_scroll = TRUE;
Bram Moolenaar3a0c9082014-11-12 15:15:42 +01003031 crypt_check_method(method);
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003032 cryptkey = crypt_get_key(newfile, FALSE);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02003033 *did_ask = TRUE;
3034
Bram Moolenaar071d4272004-06-13 20:20:40 +00003035 /* check if empty key entered */
3036 if (cryptkey != NULL && *cryptkey == NUL)
3037 {
3038 if (cryptkey != curbuf->b_p_key)
3039 vim_free(cryptkey);
3040 cryptkey = NULL;
3041 }
3042 }
3043 }
3044
3045 if (cryptkey != NULL)
3046 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003047 int header_len;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003048
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003049 curbuf->b_cryptstate = crypt_create_from_header(
3050 method, cryptkey, ptr);
3051 crypt_set_cm_option(curbuf, method);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003052
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003053 /* Remove cryptmethod specific header from the text. */
3054 header_len = crypt_get_header_len(method);
Bram Moolenaar680e0152016-09-25 20:54:11 +02003055 if (*sizep <= header_len)
3056 /* invalid header, buffer can't be encrypted */
3057 return NULL;
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003058 *filesizep += header_len;
3059 *sizep -= header_len;
3060 mch_memmove(ptr, ptr + header_len, (size_t)*sizep);
3061
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02003062 /* Restore the read-only flag. */
3063 curbuf->b_p_ro = b_p_ro;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003064 }
3065 }
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003066 /* When starting to edit a new file which does not have encryption, clear
3067 * the 'key' option, except when starting up (called with -x argument) */
Bram Moolenaarfa0ff9a2010-07-25 16:05:19 +02003068 else if (newfile && *curbuf->b_p_key != NUL && !starting)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003069 set_option_value((char_u *)"key", 0L, (char_u *)"", OPT_LOCAL);
3070
3071 return cryptkey;
3072}
Bram Moolenaar80794b12010-06-13 05:20:42 +02003073#endif /* FEAT_CRYPT */
3074
Bram Moolenaar071d4272004-06-13 20:20:40 +00003075#ifdef UNIX
3076 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003077set_file_time(
3078 char_u *fname,
3079 time_t atime, /* access time */
3080 time_t mtime) /* modification time */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003081{
3082# if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
3083 struct utimbuf buf;
3084
3085 buf.actime = atime;
3086 buf.modtime = mtime;
3087 (void)utime((char *)fname, &buf);
3088# else
3089# if defined(HAVE_UTIMES)
3090 struct timeval tvp[2];
3091
3092 tvp[0].tv_sec = atime;
3093 tvp[0].tv_usec = 0;
3094 tvp[1].tv_sec = mtime;
3095 tvp[1].tv_usec = 0;
3096# ifdef NeXT
3097 (void)utimes((char *)fname, tvp);
3098# else
3099 (void)utimes((char *)fname, (const struct timeval *)&tvp);
3100# endif
3101# endif
3102# endif
3103}
3104#endif /* UNIX */
3105
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003106#if defined(VMS) && !defined(MIN)
3107/* Older DECC compiler for VAX doesn't define MIN() */
3108# define MIN(a, b) ((a) < (b) ? (a) : (b))
3109#endif
3110
Bram Moolenaar071d4272004-06-13 20:20:40 +00003111/*
Bram Moolenaar5386a122007-06-28 20:02:32 +00003112 * Return TRUE if a file appears to be read-only from the file permissions.
3113 */
3114 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003115check_file_readonly(
3116 char_u *fname, /* full path to file */
3117 int perm) /* known permissions on file */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003118{
3119#ifndef USE_MCH_ACCESS
3120 int fd = 0;
3121#endif
3122
3123 return (
3124#ifdef USE_MCH_ACCESS
3125# ifdef UNIX
3126 (perm & 0222) == 0 ||
3127# endif
3128 mch_access((char *)fname, W_OK)
3129#else
3130 (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0
3131 ? TRUE : (close(fd), FALSE)
3132#endif
3133 );
3134}
3135
3136
3137/*
Bram Moolenaar292ad192005-12-11 21:29:51 +00003138 * buf_write() - write to file "fname" lines "start" through "end"
Bram Moolenaar071d4272004-06-13 20:20:40 +00003139 *
3140 * We do our own buffering here because fwrite() is so slow.
3141 *
Bram Moolenaar292ad192005-12-11 21:29:51 +00003142 * If "forceit" is true, we don't care for errors when attempting backups.
3143 * In case of an error everything possible is done to restore the original
Bram Moolenaare37d50a2008-08-06 17:06:04 +00003144 * file. But when "forceit" is TRUE, we risk losing it.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003145 *
3146 * When "reset_changed" is TRUE and "append" == FALSE and "start" == 1 and
3147 * "end" == curbuf->b_ml.ml_line_count, reset curbuf->b_changed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003148 *
3149 * This function must NOT use NameBuff (because it's called by autowrite()).
3150 *
3151 * return FAIL for failure, OK otherwise
3152 */
3153 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003154buf_write(
3155 buf_T *buf,
3156 char_u *fname,
3157 char_u *sfname,
3158 linenr_T start,
3159 linenr_T end,
3160 exarg_T *eap, /* for forced 'ff' and 'fenc', can be
Bram Moolenaar071d4272004-06-13 20:20:40 +00003161 NULL! */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003162 int append, /* append to the file */
3163 int forceit,
3164 int reset_changed,
3165 int filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003166{
3167 int fd;
3168 char_u *backup = NULL;
3169 int backup_copy = FALSE; /* copy the original file? */
3170 int dobackup;
3171 char_u *ffname;
3172 char_u *wfname = NULL; /* name of file to write to */
3173 char_u *s;
3174 char_u *ptr;
3175 char_u c;
3176 int len;
3177 linenr_T lnum;
3178 long nchars;
3179 char_u *errmsg = NULL;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003180 int errmsg_allocated = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003181 char_u *errnum = NULL;
3182 char_u *buffer;
3183 char_u smallbuf[SMBUFSIZE];
3184 char_u *backup_ext;
3185 int bufsize;
3186 long perm; /* file permissions */
3187 int retval = OK;
3188 int newfile = FALSE; /* TRUE if file doesn't exist yet */
3189 int msg_save = msg_scroll;
3190 int overwriting; /* TRUE if writing over original */
3191 int no_eol = FALSE; /* no end-of-line written */
3192 int device = FALSE; /* writing to a device */
Bram Moolenaar8767f522016-07-01 17:17:39 +02003193 stat_T st_old;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003194 int prev_got_int = got_int;
Bram Moolenaare6bf6552017-06-27 22:11:51 +02003195 int checking_conversion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003196 int file_readonly = FALSE; /* overwritten file is read-only */
3197 static char *err_readonly = "is read-only (cannot override: \"W\" in 'cpoptions')";
Bram Moolenaara06ecab2016-07-16 14:47:36 +02003198#if defined(UNIX) /*XXX fix me sometime? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003199 int made_writable = FALSE; /* 'w' bit has been set */
3200#endif
3201 /* writing everything */
3202 int whole = (start == 1 && end == buf->b_ml.ml_line_count);
3203#ifdef FEAT_AUTOCMD
3204 linenr_T old_line_count = buf->b_ml.ml_line_count;
3205#endif
3206 int attr;
3207 int fileformat;
3208 int write_bin;
3209 struct bw_info write_info; /* info for buf_write_bytes() */
3210#ifdef FEAT_MBYTE
3211 int converted = FALSE;
3212 int notconverted = FALSE;
3213 char_u *fenc; /* effective 'fileencoding' */
3214 char_u *fenc_tofree = NULL; /* allocated "fenc" */
3215#endif
3216#ifdef HAS_BW_FLAGS
3217 int wb_flags = 0;
3218#endif
3219#ifdef HAVE_ACL
3220 vim_acl_T acl = NULL; /* ACL copied from original file to
3221 backup or new file */
3222#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003223#ifdef FEAT_PERSISTENT_UNDO
3224 int write_undo_file = FALSE;
3225 context_sha256_T sha_ctx;
3226#endif
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003227 unsigned int bkc = get_bkc_value(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003228
3229 if (fname == NULL || *fname == NUL) /* safety check */
3230 return FAIL;
Bram Moolenaar70d60e92009-12-31 13:53:33 +00003231 if (buf->b_ml.ml_mfp == NULL)
3232 {
3233 /* This can happen during startup when there is a stray "w" in the
3234 * vimrc file. */
3235 EMSG(_(e_emptybuf));
3236 return FAIL;
3237 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003238
3239 /*
3240 * Disallow writing from .exrc and .vimrc in current directory for
3241 * security reasons.
3242 */
3243 if (check_secure())
3244 return FAIL;
3245
3246 /* Avoid a crash for a long name. */
3247 if (STRLEN(fname) >= MAXPATHL)
3248 {
3249 EMSG(_(e_longname));
3250 return FAIL;
3251 }
3252
3253#ifdef FEAT_MBYTE
3254 /* must init bw_conv_buf and bw_iconv_fd before jumping to "fail" */
3255 write_info.bw_conv_buf = NULL;
3256 write_info.bw_conv_error = FALSE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003257 write_info.bw_conv_error_lnum = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003258 write_info.bw_restlen = 0;
3259# ifdef USE_ICONV
3260 write_info.bw_iconv_fd = (iconv_t)-1;
3261# endif
3262#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003263#ifdef FEAT_CRYPT
3264 write_info.bw_buffer = buf;
3265#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003266
Bram Moolenaardf177f62005-02-22 08:39:57 +00003267 /* After writing a file changedtick changes but we don't want to display
3268 * the line. */
3269 ex_no_reprint = TRUE;
3270
Bram Moolenaar071d4272004-06-13 20:20:40 +00003271 /*
3272 * If there is no file name yet, use the one for the written file.
3273 * BF_NOTEDITED is set to reflect this (in case the write fails).
3274 * Don't do this when the write is for a filter command.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003275 * Don't do this when appending.
3276 * Only do this when 'cpoptions' contains the 'F' flag.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003277 */
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003278 if (buf->b_ffname == NULL
3279 && reset_changed
Bram Moolenaar071d4272004-06-13 20:20:40 +00003280 && whole
3281 && buf == curbuf
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00003282#ifdef FEAT_QUICKFIX
3283 && !bt_nofile(buf)
3284#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003285 && !filtering
Bram Moolenaar292ad192005-12-11 21:29:51 +00003286 && (!append || vim_strchr(p_cpo, CPO_FNAMEAPP) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003287 && vim_strchr(p_cpo, CPO_FNAMEW) != NULL)
3288 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003289 if (set_rw_fname(fname, sfname) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003290 return FAIL;
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003291 buf = curbuf; /* just in case autocmds made "buf" invalid */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003292 }
3293
3294 if (sfname == NULL)
3295 sfname = fname;
3296 /*
3297 * For Unix: Use the short file name whenever possible.
3298 * Avoids problems with networks and when directory names are changed.
3299 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
3300 * another directory, which we don't detect
3301 */
3302 ffname = fname; /* remember full fname */
3303#ifdef UNIX
3304 fname = sfname;
3305#endif
3306
3307 if (buf->b_ffname != NULL && fnamecmp(ffname, buf->b_ffname) == 0)
3308 overwriting = TRUE;
3309 else
3310 overwriting = FALSE;
3311
3312 if (exiting)
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003313 settmode(TMODE_COOK); /* when exiting allow typeahead now */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003314
3315 ++no_wait_return; /* don't wait for return yet */
3316
3317 /*
3318 * Set '[ and '] marks to the lines to be written.
3319 */
3320 buf->b_op_start.lnum = start;
3321 buf->b_op_start.col = 0;
3322 buf->b_op_end.lnum = end;
3323 buf->b_op_end.col = 0;
3324
3325#ifdef FEAT_AUTOCMD
3326 {
3327 aco_save_T aco;
3328 int buf_ffname = FALSE;
3329 int buf_sfname = FALSE;
3330 int buf_fname_f = FALSE;
3331 int buf_fname_s = FALSE;
3332 int did_cmd = FALSE;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003333 int nofile_err = FALSE;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003334 int empty_memline = (buf->b_ml.ml_mfp == NULL);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003335 bufref_T bufref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003336
3337 /*
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003338 * Apply PRE autocommands.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003339 * Set curbuf to the buffer to be written.
3340 * Careful: The autocommands may call buf_write() recursively!
3341 */
3342 if (ffname == buf->b_ffname)
3343 buf_ffname = TRUE;
3344 if (sfname == buf->b_sfname)
3345 buf_sfname = TRUE;
3346 if (fname == buf->b_ffname)
3347 buf_fname_f = TRUE;
3348 if (fname == buf->b_sfname)
3349 buf_fname_s = TRUE;
3350
3351 /* set curwin/curbuf to buf and save a few things */
3352 aucmd_prepbuf(&aco, buf);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003353 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003354
3355 if (append)
3356 {
3357 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD,
3358 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003359 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003360#ifdef FEAT_QUICKFIX
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00003361 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003362 nofile_err = TRUE;
3363 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003364#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003365 apply_autocmds_exarg(EVENT_FILEAPPENDPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003366 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003367 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003368 }
3369 else if (filtering)
3370 {
3371 apply_autocmds_exarg(EVENT_FILTERWRITEPRE,
3372 NULL, sfname, FALSE, curbuf, eap);
3373 }
3374 else if (reset_changed && whole)
3375 {
Bram Moolenaar39fc42e2011-09-02 11:56:20 +02003376 int was_changed = curbufIsChanged();
3377
3378 did_cmd = apply_autocmds_exarg(EVENT_BUFWRITECMD,
3379 sfname, sfname, FALSE, curbuf, eap);
3380 if (did_cmd)
3381 {
3382 if (was_changed && !curbufIsChanged())
3383 {
3384 /* Written everything correctly and BufWriteCmd has reset
3385 * 'modified': Correct the undo information so that an
3386 * undo now sets 'modified'. */
3387 u_unchanged(curbuf);
3388 u_update_save_nr(curbuf);
3389 }
3390 }
3391 else
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003392 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003393#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003394 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003395 nofile_err = TRUE;
3396 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003397#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003398 apply_autocmds_exarg(EVENT_BUFWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003399 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003400 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003401 }
3402 else
3403 {
3404 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD,
3405 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003406 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003407#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003408 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003409 nofile_err = TRUE;
3410 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003411#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003412 apply_autocmds_exarg(EVENT_FILEWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003413 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003414 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003415 }
3416
3417 /* restore curwin/curbuf and a few other things */
3418 aucmd_restbuf(&aco);
3419
3420 /*
3421 * In three situations we return here and don't write the file:
3422 * 1. the autocommands deleted or unloaded the buffer.
3423 * 2. The autocommands abort script processing.
3424 * 3. If one of the "Cmd" autocommands was executed.
3425 */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003426 if (!bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003427 buf = NULL;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003428 if (buf == NULL || (buf->b_ml.ml_mfp == NULL && !empty_memline)
Bram Moolenaar1e015462005-09-25 22:16:38 +00003429 || did_cmd || nofile_err
3430#ifdef FEAT_EVAL
3431 || aborting()
3432#endif
3433 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003434 {
3435 --no_wait_return;
3436 msg_scroll = msg_save;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003437 if (nofile_err)
3438 EMSG(_("E676: No matching autocommands for acwrite buffer"));
3439
Bram Moolenaar1e015462005-09-25 22:16:38 +00003440 if (nofile_err
3441#ifdef FEAT_EVAL
3442 || aborting()
3443#endif
3444 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003445 /* An aborting error, interrupt or exception in the
3446 * autocommands. */
3447 return FAIL;
3448 if (did_cmd)
3449 {
3450 if (buf == NULL)
3451 /* The buffer was deleted. We assume it was written
3452 * (can't retry anyway). */
3453 return OK;
3454 if (overwriting)
3455 {
3456 /* Assume the buffer was written, update the timestamp. */
3457 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00003458 if (append)
3459 buf->b_flags &= ~BF_NEW;
3460 else
3461 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003462 }
Bram Moolenaar292ad192005-12-11 21:29:51 +00003463 if (reset_changed && buf->b_changed && !append
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003464 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003465 /* Buffer still changed, the autocommands didn't work
3466 * properly. */
3467 return FAIL;
3468 return OK;
3469 }
3470#ifdef FEAT_EVAL
3471 if (!aborting())
3472#endif
3473 EMSG(_("E203: Autocommands deleted or unloaded buffer to be written"));
3474 return FAIL;
3475 }
3476
3477 /*
3478 * The autocommands may have changed the number of lines in the file.
3479 * When writing the whole file, adjust the end.
3480 * When writing part of the file, assume that the autocommands only
3481 * changed the number of lines that are to be written (tricky!).
3482 */
3483 if (buf->b_ml.ml_line_count != old_line_count)
3484 {
3485 if (whole) /* write all */
3486 end = buf->b_ml.ml_line_count;
3487 else if (buf->b_ml.ml_line_count > old_line_count) /* more lines */
3488 end += buf->b_ml.ml_line_count - old_line_count;
3489 else /* less lines */
3490 {
3491 end -= old_line_count - buf->b_ml.ml_line_count;
3492 if (end < start)
3493 {
3494 --no_wait_return;
3495 msg_scroll = msg_save;
3496 EMSG(_("E204: Autocommand changed number of lines in unexpected way"));
3497 return FAIL;
3498 }
3499 }
3500 }
3501
3502 /*
3503 * The autocommands may have changed the name of the buffer, which may
3504 * be kept in fname, ffname and sfname.
3505 */
3506 if (buf_ffname)
3507 ffname = buf->b_ffname;
3508 if (buf_sfname)
3509 sfname = buf->b_sfname;
3510 if (buf_fname_f)
3511 fname = buf->b_ffname;
3512 if (buf_fname_s)
3513 fname = buf->b_sfname;
3514 }
3515#endif
3516
3517#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003518 if (netbeans_active() && isNetbeansBuffer(buf))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003519 {
3520 if (whole)
3521 {
3522 /*
3523 * b_changed can be 0 after an undo, but we still need to write
3524 * the buffer to NetBeans.
3525 */
3526 if (buf->b_changed || isNetbeansModified(buf))
3527 {
Bram Moolenaar009b2592004-10-24 19:18:58 +00003528 --no_wait_return; /* may wait for return now */
3529 msg_scroll = msg_save;
3530 netbeans_save_buffer(buf); /* no error checking... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003531 return retval;
3532 }
3533 else
3534 {
3535 errnum = (char_u *)"E656: ";
Bram Moolenaared0e7452008-06-27 19:17:34 +00003536 errmsg = (char_u *)_("NetBeans disallows writes of unmodified buffers");
Bram Moolenaar071d4272004-06-13 20:20:40 +00003537 buffer = NULL;
3538 goto fail;
3539 }
3540 }
3541 else
3542 {
3543 errnum = (char_u *)"E657: ";
3544 errmsg = (char_u *)_("Partial writes disallowed for NetBeans buffers");
3545 buffer = NULL;
3546 goto fail;
3547 }
3548 }
3549#endif
3550
3551 if (shortmess(SHM_OVER) && !exiting)
3552 msg_scroll = FALSE; /* overwrite previous file message */
3553 else
3554 msg_scroll = TRUE; /* don't overwrite previous file message */
3555 if (!filtering)
3556 filemess(buf,
3557#ifndef UNIX
3558 sfname,
3559#else
3560 fname,
3561#endif
3562 (char_u *)"", 0); /* show that we are busy */
3563 msg_scroll = FALSE; /* always overwrite the file message now */
3564
3565 buffer = alloc(BUFSIZE);
3566 if (buffer == NULL) /* can't allocate big buffer, use small
3567 * one (to be able to write when out of
3568 * memory) */
3569 {
3570 buffer = smallbuf;
3571 bufsize = SMBUFSIZE;
3572 }
3573 else
3574 bufsize = BUFSIZE;
3575
3576 /*
3577 * Get information about original file (if there is one).
3578 */
Bram Moolenaar53076832015-12-31 19:53:21 +01003579#if defined(UNIX)
Bram Moolenaar6f192452007-11-08 19:49:02 +00003580 st_old.st_dev = 0;
3581 st_old.st_ino = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003582 perm = -1;
3583 if (mch_stat((char *)fname, &st_old) < 0)
3584 newfile = TRUE;
3585 else
3586 {
3587 perm = st_old.st_mode;
3588 if (!S_ISREG(st_old.st_mode)) /* not a file */
3589 {
3590 if (S_ISDIR(st_old.st_mode))
3591 {
3592 errnum = (char_u *)"E502: ";
3593 errmsg = (char_u *)_("is a directory");
3594 goto fail;
3595 }
3596 if (mch_nodetype(fname) != NODE_WRITABLE)
3597 {
3598 errnum = (char_u *)"E503: ";
3599 errmsg = (char_u *)_("is not a file or writable device");
3600 goto fail;
3601 }
3602 /* It's a device of some kind (or a fifo) which we can write to
3603 * but for which we can't make a backup. */
3604 device = TRUE;
3605 newfile = TRUE;
3606 perm = -1;
3607 }
3608 }
3609#else /* !UNIX */
3610 /*
3611 * Check for a writable device name.
3612 */
3613 c = mch_nodetype(fname);
3614 if (c == NODE_OTHER)
3615 {
3616 errnum = (char_u *)"E503: ";
3617 errmsg = (char_u *)_("is not a file or writable device");
3618 goto fail;
3619 }
3620 if (c == NODE_WRITABLE)
3621 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003622# if defined(MSWIN)
Bram Moolenaar043545e2006-10-10 16:44:07 +00003623 /* MS-Windows allows opening a device, but we will probably get stuck
3624 * trying to write to it. */
3625 if (!p_odev)
3626 {
3627 errnum = (char_u *)"E796: ";
3628 errmsg = (char_u *)_("writing to device disabled with 'opendevice' option");
3629 goto fail;
3630 }
3631# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003632 device = TRUE;
3633 newfile = TRUE;
3634 perm = -1;
3635 }
3636 else
3637 {
3638 perm = mch_getperm(fname);
3639 if (perm < 0)
3640 newfile = TRUE;
3641 else if (mch_isdir(fname))
3642 {
3643 errnum = (char_u *)"E502: ";
3644 errmsg = (char_u *)_("is a directory");
3645 goto fail;
3646 }
3647 if (overwriting)
3648 (void)mch_stat((char *)fname, &st_old);
3649 }
3650#endif /* !UNIX */
3651
3652 if (!device && !newfile)
3653 {
3654 /*
3655 * Check if the file is really writable (when renaming the file to
3656 * make a backup we won't discover it later).
3657 */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003658 file_readonly = check_file_readonly(fname, (int)perm);
3659
Bram Moolenaar071d4272004-06-13 20:20:40 +00003660 if (!forceit && file_readonly)
3661 {
3662 if (vim_strchr(p_cpo, CPO_FWRITE) != NULL)
3663 {
3664 errnum = (char_u *)"E504: ";
3665 errmsg = (char_u *)_(err_readonly);
3666 }
3667 else
3668 {
3669 errnum = (char_u *)"E505: ";
3670 errmsg = (char_u *)_("is read-only (add ! to override)");
3671 }
3672 goto fail;
3673 }
3674
3675 /*
3676 * Check if the timestamp hasn't changed since reading the file.
3677 */
3678 if (overwriting)
3679 {
3680 retval = check_mtime(buf, &st_old);
3681 if (retval == FAIL)
3682 goto fail;
3683 }
3684 }
3685
3686#ifdef HAVE_ACL
3687 /*
3688 * For systems that support ACL: get the ACL from the original file.
3689 */
3690 if (!newfile)
3691 acl = mch_get_acl(fname);
3692#endif
3693
3694 /*
3695 * If 'backupskip' is not empty, don't make a backup for some files.
3696 */
3697 dobackup = (p_wb || p_bk || *p_pm != NUL);
3698#ifdef FEAT_WILDIGN
3699 if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname))
3700 dobackup = FALSE;
3701#endif
3702
3703 /*
3704 * Save the value of got_int and reset it. We don't want a previous
3705 * interruption cancel writing, only hitting CTRL-C while writing should
3706 * abort it.
3707 */
3708 prev_got_int = got_int;
3709 got_int = FALSE;
3710
3711 /* Mark the buffer as 'being saved' to prevent changed buffer warnings */
3712 buf->b_saving = TRUE;
3713
3714 /*
3715 * If we are not appending or filtering, the file exists, and the
3716 * 'writebackup', 'backup' or 'patchmode' option is set, need a backup.
3717 * When 'patchmode' is set also make a backup when appending.
3718 *
3719 * Do not make any backup, if 'writebackup' and 'backup' are both switched
3720 * off. This helps when editing large files on almost-full disks.
3721 */
3722 if (!(append && *p_pm == NUL) && !filtering && perm >= 0 && dobackup)
3723 {
3724#if defined(UNIX) || defined(WIN32)
Bram Moolenaar8767f522016-07-01 17:17:39 +02003725 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003726#endif
3727
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003728 if ((bkc & BKC_YES) || append) /* "yes" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003729 backup_copy = TRUE;
3730#if defined(UNIX) || defined(WIN32)
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003731 else if ((bkc & BKC_AUTO)) /* "auto" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003732 {
3733 int i;
3734
3735# ifdef UNIX
3736 /*
3737 * Don't rename the file when:
3738 * - it's a hard link
3739 * - it's a symbolic link
3740 * - we don't have write permission in the directory
3741 * - we can't set the owner/group of the new file
3742 */
3743 if (st_old.st_nlink > 1
3744 || mch_lstat((char *)fname, &st) < 0
3745 || st.st_dev != st_old.st_dev
Bram Moolenaara5792f52005-11-23 21:25:05 +00003746 || st.st_ino != st_old.st_ino
3747# ifndef HAVE_FCHOWN
3748 || st.st_uid != st_old.st_uid
3749 || st.st_gid != st_old.st_gid
3750# endif
3751 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003752 backup_copy = TRUE;
3753 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003754# else
3755# ifdef WIN32
3756 /* On NTFS file systems hard links are possible. */
3757 if (mch_is_linked(fname))
3758 backup_copy = TRUE;
3759 else
3760# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003761# endif
3762 {
3763 /*
3764 * Check if we can create a file and set the owner/group to
3765 * the ones from the original file.
3766 * First find a file name that doesn't exist yet (use some
3767 * arbitrary numbers).
3768 */
3769 STRCPY(IObuff, fname);
3770 for (i = 4913; ; i += 123)
3771 {
3772 sprintf((char *)gettail(IObuff), "%d", i);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003773 if (mch_lstat((char *)IObuff, &st) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003774 break;
3775 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00003776 fd = mch_open((char *)IObuff,
3777 O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003778 if (fd < 0) /* can't write in directory */
3779 backup_copy = TRUE;
3780 else
3781 {
3782# ifdef UNIX
Bram Moolenaara5792f52005-11-23 21:25:05 +00003783# ifdef HAVE_FCHOWN
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00003784 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003785# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003786 if (mch_stat((char *)IObuff, &st) < 0
3787 || st.st_uid != st_old.st_uid
3788 || st.st_gid != st_old.st_gid
Bram Moolenaar78a15312009-05-15 19:33:18 +00003789 || (long)st.st_mode != perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003790 backup_copy = TRUE;
3791# endif
Bram Moolenaar98358622005-11-28 22:58:23 +00003792 /* Close the file before removing it, on MS-Windows we
3793 * can't delete an open file. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003794 close(fd);
Bram Moolenaar98358622005-11-28 22:58:23 +00003795 mch_remove(IObuff);
Bram Moolenaar3479c5d2010-08-08 18:46:06 +02003796# ifdef MSWIN
3797 /* MS-Windows may trigger a virus scanner to open the
3798 * file, we can't delete it then. Keep trying for half a
3799 * second. */
3800 {
3801 int try;
3802
3803 for (try = 0; try < 10; ++try)
3804 {
3805 if (mch_lstat((char *)IObuff, &st) < 0)
3806 break;
3807 ui_delay(50L, TRUE); /* wait 50 msec */
3808 mch_remove(IObuff);
3809 }
3810 }
3811# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003812 }
3813 }
3814 }
3815
Bram Moolenaar071d4272004-06-13 20:20:40 +00003816 /*
3817 * Break symlinks and/or hardlinks if we've been asked to.
3818 */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003819 if ((bkc & BKC_BREAKSYMLINK) || (bkc & BKC_BREAKHARDLINK))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003820 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003821# ifdef UNIX
Bram Moolenaar071d4272004-06-13 20:20:40 +00003822 int lstat_res;
3823
3824 lstat_res = mch_lstat((char *)fname, &st);
3825
3826 /* Symlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003827 if ((bkc & BKC_BREAKSYMLINK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003828 && lstat_res == 0
3829 && st.st_ino != st_old.st_ino)
3830 backup_copy = FALSE;
3831
3832 /* Hardlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003833 if ((bkc & BKC_BREAKHARDLINK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003834 && st_old.st_nlink > 1
3835 && (lstat_res != 0 || st.st_ino == st_old.st_ino))
3836 backup_copy = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003837# else
3838# if defined(WIN32)
3839 /* Symlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003840 if ((bkc & BKC_BREAKSYMLINK) && mch_is_symbolic_link(fname))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003841 backup_copy = FALSE;
3842
3843 /* Hardlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003844 if ((bkc & BKC_BREAKHARDLINK) && mch_is_hard_link(fname))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003845 backup_copy = FALSE;
3846# endif
3847# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003848 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003849
3850#endif
3851
3852 /* make sure we have a valid backup extension to use */
3853 if (*p_bex == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003854 backup_ext = (char_u *)".bak";
Bram Moolenaar071d4272004-06-13 20:20:40 +00003855 else
3856 backup_ext = p_bex;
3857
3858 if (backup_copy
3859 && (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) >= 0)
3860 {
3861 int bfd;
3862 char_u *copybuf, *wp;
3863 int some_error = FALSE;
Bram Moolenaar8767f522016-07-01 17:17:39 +02003864 stat_T st_new;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003865 char_u *dirp;
3866 char_u *rootname;
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003867#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003868 int did_set_shortname;
Bram Moolenaarcd142e32017-11-16 17:03:45 +01003869 mode_t umask_save;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003870#endif
3871
3872 copybuf = alloc(BUFSIZE + 1);
3873 if (copybuf == NULL)
3874 {
3875 some_error = TRUE; /* out of memory */
3876 goto nobackup;
3877 }
3878
3879 /*
3880 * Try to make the backup in each directory in the 'bdir' option.
3881 *
3882 * Unix semantics has it, that we may have a writable file,
3883 * that cannot be recreated with a simple open(..., O_CREAT, ) e.g:
3884 * - the directory is not writable,
3885 * - the file may be a symbolic link,
3886 * - the file may belong to another user/group, etc.
3887 *
3888 * For these reasons, the existing writable file must be truncated
3889 * and reused. Creation of a backup COPY will be attempted.
3890 */
3891 dirp = p_bdir;
3892 while (*dirp)
3893 {
3894#ifdef UNIX
3895 st_new.st_ino = 0;
3896 st_new.st_dev = 0;
3897 st_new.st_gid = 0;
3898#endif
3899
3900 /*
3901 * Isolate one directory name, using an entry in 'bdir'.
3902 */
3903 (void)copy_option_part(&dirp, copybuf, BUFSIZE, ",");
3904 rootname = get_file_in_dir(fname, copybuf);
3905 if (rootname == NULL)
3906 {
3907 some_error = TRUE; /* out of memory */
3908 goto nobackup;
3909 }
3910
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003911#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003912 did_set_shortname = FALSE;
3913#endif
3914
3915 /*
3916 * May try twice if 'shortname' not set.
3917 */
3918 for (;;)
3919 {
3920 /*
3921 * Make backup file name.
3922 */
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003923 backup = buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003924 rootname, backup_ext, FALSE);
3925 if (backup == NULL)
3926 {
3927 vim_free(rootname);
3928 some_error = TRUE; /* out of memory */
3929 goto nobackup;
3930 }
3931
3932 /*
3933 * Check if backup file already exists.
3934 */
3935 if (mch_stat((char *)backup, &st_new) >= 0)
3936 {
3937#ifdef UNIX
3938 /*
3939 * Check if backup file is same as original file.
3940 * May happen when modname() gave the same file back.
3941 * E.g. silly link, or file name-length reached.
3942 * If we don't check here, we either ruin the file
3943 * when copying or erase it after writing. jw.
3944 */
3945 if (st_new.st_dev == st_old.st_dev
3946 && st_new.st_ino == st_old.st_ino)
3947 {
3948 vim_free(backup);
3949 backup = NULL; /* no backup file to delete */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003950 /*
3951 * may try again with 'shortname' set
3952 */
3953 if (!(buf->b_shortname || buf->b_p_sn))
3954 {
3955 buf->b_shortname = TRUE;
3956 did_set_shortname = TRUE;
3957 continue;
3958 }
3959 /* setting shortname didn't help */
3960 if (did_set_shortname)
3961 buf->b_shortname = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003962 break;
3963 }
3964#endif
3965
3966 /*
3967 * If we are not going to keep the backup file, don't
3968 * delete an existing one, try to use another name.
3969 * Change one character, just before the extension.
3970 */
3971 if (!p_bk)
3972 {
3973 wp = backup + STRLEN(backup) - 1
3974 - STRLEN(backup_ext);
3975 if (wp < backup) /* empty file name ??? */
3976 wp = backup;
3977 *wp = 'z';
3978 while (*wp > 'a'
3979 && mch_stat((char *)backup, &st_new) >= 0)
3980 --*wp;
3981 /* They all exist??? Must be something wrong. */
3982 if (*wp == 'a')
3983 {
3984 vim_free(backup);
3985 backup = NULL;
3986 }
3987 }
3988 }
3989 break;
3990 }
3991 vim_free(rootname);
3992
3993 /*
3994 * Try to create the backup file
3995 */
3996 if (backup != NULL)
3997 {
3998 /* remove old backup, if present */
3999 mch_remove(backup);
4000 /* Open with O_EXCL to avoid the file being created while
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004001 * we were sleeping (symlink hacker attack?). Reset umask
4002 * if possible to avoid mch_setperm() below. */
4003#ifdef UNIX
4004 umask_save = umask(0);
4005#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004006 bfd = mch_open((char *)backup,
Bram Moolenaara5792f52005-11-23 21:25:05 +00004007 O_WRONLY|O_CREAT|O_EXTRA|O_EXCL|O_NOFOLLOW,
4008 perm & 0777);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004009#ifdef UNIX
4010 (void)umask(umask_save);
4011#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004012 if (bfd < 0)
4013 {
4014 vim_free(backup);
4015 backup = NULL;
4016 }
4017 else
4018 {
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004019 /* Set file protection same as original file, but
4020 * strip s-bit. Only needed if umask() wasn't used
4021 * above. */
4022#ifndef UNIX
Bram Moolenaar071d4272004-06-13 20:20:40 +00004023 (void)mch_setperm(backup, perm & 0777);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004024#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004025 /*
4026 * Try to set the group of the backup same as the
4027 * original file. If this fails, set the protection
4028 * bits for the group same as the protection bits for
4029 * others.
4030 */
Bram Moolenaara5792f52005-11-23 21:25:05 +00004031 if (st_new.st_gid != st_old.st_gid
Bram Moolenaar071d4272004-06-13 20:20:40 +00004032# ifdef HAVE_FCHOWN /* sequent-ptx lacks fchown() */
Bram Moolenaara5792f52005-11-23 21:25:05 +00004033 && fchown(bfd, (uid_t)-1, st_old.st_gid) != 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00004034# endif
4035 )
4036 mch_setperm(backup,
4037 (perm & 0707) | ((perm & 07) << 3));
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004038# if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004039 mch_copy_sec(fname, backup);
4040# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004041#endif
4042
4043 /*
4044 * copy the file.
4045 */
4046 write_info.bw_fd = bfd;
4047 write_info.bw_buf = copybuf;
4048#ifdef HAS_BW_FLAGS
4049 write_info.bw_flags = FIO_NOCONVERT;
4050#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004051 while ((write_info.bw_len = read_eintr(fd, copybuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004052 BUFSIZE)) > 0)
4053 {
4054 if (buf_write_bytes(&write_info) == FAIL)
4055 {
4056 errmsg = (char_u *)_("E506: Can't write to backup file (add ! to override)");
4057 break;
4058 }
4059 ui_breakcheck();
4060 if (got_int)
4061 {
4062 errmsg = (char_u *)_(e_interr);
4063 break;
4064 }
4065 }
4066
4067 if (close(bfd) < 0 && errmsg == NULL)
4068 errmsg = (char_u *)_("E507: Close error for backup file (add ! to override)");
4069 if (write_info.bw_len < 0)
4070 errmsg = (char_u *)_("E508: Can't read file for backup (add ! to override)");
4071#ifdef UNIX
4072 set_file_time(backup, st_old.st_atime, st_old.st_mtime);
4073#endif
4074#ifdef HAVE_ACL
4075 mch_set_acl(backup, acl);
4076#endif
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004077#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004078 mch_copy_sec(fname, backup);
4079#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004080 break;
4081 }
4082 }
4083 }
4084 nobackup:
4085 close(fd); /* ignore errors for closing read file */
4086 vim_free(copybuf);
4087
4088 if (backup == NULL && errmsg == NULL)
4089 errmsg = (char_u *)_("E509: Cannot create backup file (add ! to override)");
4090 /* ignore errors when forceit is TRUE */
4091 if ((some_error || errmsg != NULL) && !forceit)
4092 {
4093 retval = FAIL;
4094 goto fail;
4095 }
4096 errmsg = NULL;
4097 }
4098 else
4099 {
4100 char_u *dirp;
4101 char_u *p;
4102 char_u *rootname;
4103
4104 /*
4105 * Make a backup by renaming the original file.
4106 */
4107 /*
4108 * If 'cpoptions' includes the "W" flag, we don't want to
4109 * overwrite a read-only file. But rename may be possible
4110 * anyway, thus we need an extra check here.
4111 */
4112 if (file_readonly && vim_strchr(p_cpo, CPO_FWRITE) != NULL)
4113 {
4114 errnum = (char_u *)"E504: ";
4115 errmsg = (char_u *)_(err_readonly);
4116 goto fail;
4117 }
4118
4119 /*
4120 *
4121 * Form the backup file name - change path/fo.o.h to
4122 * path/fo.o.h.bak Try all directories in 'backupdir', first one
4123 * that works is used.
4124 */
4125 dirp = p_bdir;
4126 while (*dirp)
4127 {
4128 /*
4129 * Isolate one directory name and make the backup file name.
4130 */
4131 (void)copy_option_part(&dirp, IObuff, IOSIZE, ",");
4132 rootname = get_file_in_dir(fname, IObuff);
4133 if (rootname == NULL)
4134 backup = NULL;
4135 else
4136 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01004137 backup = buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00004138 rootname, backup_ext, FALSE);
4139 vim_free(rootname);
4140 }
4141
4142 if (backup != NULL)
4143 {
4144 /*
4145 * If we are not going to keep the backup file, don't
4146 * delete an existing one, try to use another name.
4147 * Change one character, just before the extension.
4148 */
4149 if (!p_bk && mch_getperm(backup) >= 0)
4150 {
4151 p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext);
4152 if (p < backup) /* empty file name ??? */
4153 p = backup;
4154 *p = 'z';
4155 while (*p > 'a' && mch_getperm(backup) >= 0)
4156 --*p;
4157 /* They all exist??? Must be something wrong! */
4158 if (*p == 'a')
4159 {
4160 vim_free(backup);
4161 backup = NULL;
4162 }
4163 }
4164 }
4165 if (backup != NULL)
4166 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004167 /*
Bram Moolenaarbfd8fc02005-09-20 23:22:24 +00004168 * Delete any existing backup and move the current version
4169 * to the backup. For safety, we don't remove the backup
4170 * until the write has finished successfully. And if the
4171 * 'backup' option is set, leave it around.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004172 */
4173 /*
4174 * If the renaming of the original file to the backup file
4175 * works, quit here.
4176 */
4177 if (vim_rename(fname, backup) == 0)
4178 break;
4179
4180 vim_free(backup); /* don't do the rename below */
4181 backup = NULL;
4182 }
4183 }
4184 if (backup == NULL && !forceit)
4185 {
4186 errmsg = (char_u *)_("E510: Can't make backup file (add ! to override)");
4187 goto fail;
4188 }
4189 }
4190 }
4191
Bram Moolenaar53076832015-12-31 19:53:21 +01004192#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004193 /* When using ":w!" and the file was read-only: make it writable */
4194 if (forceit && perm >= 0 && !(perm & 0200) && st_old.st_uid == getuid()
4195 && vim_strchr(p_cpo, CPO_FWRITE) == NULL)
4196 {
4197 perm |= 0200;
4198 (void)mch_setperm(fname, perm);
4199 made_writable = TRUE;
4200 }
4201#endif
4202
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004203 /* When using ":w!" and writing to the current file, 'readonly' makes no
Bram Moolenaar4399ef42005-02-12 14:29:27 +00004204 * sense, reset it, unless 'Z' appears in 'cpoptions'. */
4205 if (forceit && overwriting && vim_strchr(p_cpo, CPO_KEEPRO) == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004206 {
4207 buf->b_p_ro = FALSE;
4208#ifdef FEAT_TITLE
4209 need_maketitle = TRUE; /* set window title later */
4210#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004211 status_redraw_all(); /* redraw status lines later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004212 }
4213
4214 if (end > buf->b_ml.ml_line_count)
4215 end = buf->b_ml.ml_line_count;
4216 if (buf->b_ml.ml_flags & ML_EMPTY)
4217 start = end + 1;
4218
4219 /*
4220 * If the original file is being overwritten, there is a small chance that
4221 * we crash in the middle of writing. Therefore the file is preserved now.
4222 * This makes all block numbers positive so that recovery does not need
4223 * the original file.
4224 * Don't do this if there is a backup file and we are exiting.
4225 */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004226 if (reset_changed && !newfile && overwriting
Bram Moolenaar071d4272004-06-13 20:20:40 +00004227 && !(exiting && backup != NULL))
4228 {
4229 ml_preserve(buf, FALSE);
4230 if (got_int)
4231 {
4232 errmsg = (char_u *)_(e_interr);
4233 goto restore_backup;
4234 }
4235 }
4236
Bram Moolenaar071d4272004-06-13 20:20:40 +00004237#ifdef VMS
4238 vms_remove_version(fname); /* remove version */
4239#endif
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00004240 /* Default: write the file directly. May write to a temp file for
Bram Moolenaar071d4272004-06-13 20:20:40 +00004241 * multi-byte conversion. */
4242 wfname = fname;
4243
4244#ifdef FEAT_MBYTE
4245 /* Check for forced 'fileencoding' from "++opt=val" argument. */
4246 if (eap != NULL && eap->force_enc != 0)
4247 {
4248 fenc = eap->cmd + eap->force_enc;
4249 fenc = enc_canonize(fenc);
4250 fenc_tofree = fenc;
4251 }
4252 else
4253 fenc = buf->b_p_fenc;
4254
4255 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004256 * Check if the file needs to be converted.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004257 */
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004258 converted = need_conversion(fenc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004259
4260 /*
4261 * Check if UTF-8 to UCS-2/4 or Latin1 conversion needs to be done. Or
4262 * Latin1 to Unicode conversion. This is handled in buf_write_bytes().
4263 * Prepare the flags for it and allocate bw_conv_buf when needed.
4264 */
4265 if (converted && (enc_utf8 || STRCMP(p_enc, "latin1") == 0))
4266 {
4267 wb_flags = get_fio_flags(fenc);
4268 if (wb_flags & (FIO_UCS2 | FIO_UCS4 | FIO_UTF16 | FIO_UTF8))
4269 {
4270 /* Need to allocate a buffer to translate into. */
4271 if (wb_flags & (FIO_UCS2 | FIO_UTF16 | FIO_UTF8))
4272 write_info.bw_conv_buflen = bufsize * 2;
4273 else /* FIO_UCS4 */
4274 write_info.bw_conv_buflen = bufsize * 4;
4275 write_info.bw_conv_buf
4276 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4277 if (write_info.bw_conv_buf == NULL)
4278 end = 0;
4279 }
4280 }
4281
4282# ifdef WIN3264
4283 if (converted && wb_flags == 0 && (wb_flags = get_win_fio_flags(fenc)) != 0)
4284 {
4285 /* Convert UTF-8 -> UCS-2 and UCS-2 -> DBCS. Worst-case * 4: */
4286 write_info.bw_conv_buflen = bufsize * 4;
4287 write_info.bw_conv_buf
4288 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4289 if (write_info.bw_conv_buf == NULL)
4290 end = 0;
4291 }
4292# endif
4293
Bram Moolenaard0573012017-10-28 21:11:06 +02004294# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00004295 if (converted && wb_flags == 0 && (wb_flags = get_mac_fio_flags(fenc)) != 0)
4296 {
4297 write_info.bw_conv_buflen = bufsize * 3;
4298 write_info.bw_conv_buf
4299 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4300 if (write_info.bw_conv_buf == NULL)
4301 end = 0;
4302 }
4303# endif
4304
4305# if defined(FEAT_EVAL) || defined(USE_ICONV)
4306 if (converted && wb_flags == 0)
4307 {
4308# ifdef USE_ICONV
4309 /*
4310 * Use iconv() conversion when conversion is needed and it's not done
4311 * internally.
4312 */
4313 write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc,
4314 enc_utf8 ? (char_u *)"utf-8" : p_enc);
4315 if (write_info.bw_iconv_fd != (iconv_t)-1)
4316 {
4317 /* We're going to use iconv(), allocate a buffer to convert in. */
4318 write_info.bw_conv_buflen = bufsize * ICONV_MULT;
4319 write_info.bw_conv_buf
4320 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4321 if (write_info.bw_conv_buf == NULL)
4322 end = 0;
4323 write_info.bw_first = TRUE;
4324 }
4325# ifdef FEAT_EVAL
4326 else
4327# endif
4328# endif
4329
4330# ifdef FEAT_EVAL
4331 /*
4332 * When the file needs to be converted with 'charconvert' after
4333 * writing, write to a temp file instead and let the conversion
4334 * overwrite the original file.
4335 */
4336 if (*p_ccv != NUL)
4337 {
Bram Moolenaare5c421c2015-03-31 13:33:08 +02004338 wfname = vim_tempname('w', FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004339 if (wfname == NULL) /* Can't write without a tempfile! */
4340 {
4341 errmsg = (char_u *)_("E214: Can't find temp file for writing");
4342 goto restore_backup;
4343 }
4344 }
4345# endif
4346 }
4347# endif
4348 if (converted && wb_flags == 0
4349# ifdef USE_ICONV
4350 && write_info.bw_iconv_fd == (iconv_t)-1
4351# endif
4352# ifdef FEAT_EVAL
4353 && wfname == fname
4354# endif
4355 )
4356 {
4357 if (!forceit)
4358 {
4359 errmsg = (char_u *)_("E213: Cannot convert (add ! to write without conversion)");
4360 goto restore_backup;
4361 }
4362 notconverted = TRUE;
4363 }
4364#endif
4365
4366 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004367 * If conversion is taking place, we may first pretend to write and check
4368 * for conversion errors. Then loop again to write for real.
4369 * When not doing conversion this writes for real right away.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004370 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004371 for (checking_conversion = TRUE; ; checking_conversion = FALSE)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004372 {
4373 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004374 * There is no need to check conversion when:
4375 * - there is no conversion
4376 * - we make a backup file, that can be restored in case of conversion
4377 * failure.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004378 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004379#ifdef FEAT_MBYTE
4380 if (!converted || dobackup)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004381#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004382 checking_conversion = FALSE;
4383
4384 if (checking_conversion)
4385 {
4386 /* Make sure we don't write anything. */
4387 fd = -1;
4388 write_info.bw_fd = fd;
4389 }
4390 else
4391 {
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004392#ifdef HAVE_FTRUNCATE
4393# define TRUNC_ON_OPEN 0
4394#else
4395# define TRUNC_ON_OPEN O_TRUNC
4396#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004397 /*
4398 * Open the file "wfname" for writing.
4399 * We may try to open the file twice: If we can't write to the file
4400 * and forceit is TRUE we delete the existing file and try to
4401 * create a new one. If this still fails we may have lost the
4402 * original file! (this may happen when the user reached his
4403 * quotum for number of files).
4404 * Appending will fail if the file does not exist and forceit is
4405 * FALSE.
4406 */
4407 while ((fd = mch_open((char *)wfname, O_WRONLY | O_EXTRA | (append
4408 ? (forceit ? (O_APPEND | O_CREAT) : O_APPEND)
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004409 : (O_CREAT | TRUNC_ON_OPEN))
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004410 , perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004411 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004412 /*
4413 * A forced write will try to create a new file if the old one
4414 * is still readonly. This may also happen when the directory
4415 * is read-only. In that case the mch_remove() will fail.
4416 */
4417 if (errmsg == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004418 {
4419#ifdef UNIX
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004420 stat_T st;
4421
4422 /* Don't delete the file when it's a hard or symbolic link.
4423 */
4424 if ((!newfile && st_old.st_nlink > 1)
4425 || (mch_lstat((char *)fname, &st) == 0
4426 && (st.st_dev != st_old.st_dev
4427 || st.st_ino != st_old.st_ino)))
4428 errmsg = (char_u *)_("E166: Can't open linked file for writing");
4429 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004430#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004431 {
4432 errmsg = (char_u *)_("E212: Can't open file for writing");
4433 if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL
4434 && perm >= 0)
4435 {
4436#ifdef UNIX
4437 /* we write to the file, thus it should be marked
4438 writable after all */
4439 if (!(perm & 0200))
4440 made_writable = TRUE;
4441 perm |= 0200;
4442 if (st_old.st_uid != getuid()
4443 || st_old.st_gid != getgid())
4444 perm &= 0777;
4445#endif
4446 if (!append) /* don't remove when appending */
4447 mch_remove(wfname);
4448 continue;
4449 }
4450 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004451 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004452
4453restore_backup:
Bram Moolenaar071d4272004-06-13 20:20:40 +00004454 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004455 stat_T st;
4456
Bram Moolenaar071d4272004-06-13 20:20:40 +00004457 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004458 * If we failed to open the file, we don't need a backup.
4459 * Throw it away. If we moved or removed the original file
4460 * try to put the backup in its place.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004461 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004462 if (backup != NULL && wfname == fname)
4463 {
4464 if (backup_copy)
4465 {
4466 /*
4467 * There is a small chance that we removed the
4468 * original, try to move the copy in its place.
4469 * This may not work if the vim_rename() fails.
4470 * In that case we leave the copy around.
4471 */
4472 /* If file does not exist, put the copy in its
4473 * place */
4474 if (mch_stat((char *)fname, &st) < 0)
4475 vim_rename(backup, fname);
4476 /* if original file does exist throw away the copy
4477 */
4478 if (mch_stat((char *)fname, &st) >= 0)
4479 mch_remove(backup);
4480 }
4481 else
4482 {
4483 /* try to put the original file back */
4484 vim_rename(backup, fname);
4485 }
4486 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004487
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004488 /* if original file no longer exists give an extra warning
4489 */
4490 if (!newfile && mch_stat((char *)fname, &st) < 0)
4491 end = 0;
4492 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004493
4494#ifdef FEAT_MBYTE
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004495 if (wfname != fname)
4496 vim_free(wfname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004497#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004498 goto fail;
4499 }
4500 write_info.bw_fd = fd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004501
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004502#if defined(UNIX)
4503 {
4504 stat_T st;
4505
4506 /* Double check we are writing the intended file before making
4507 * any changes. */
4508 if (overwriting
4509 && (!dobackup || backup_copy)
4510 && fname == wfname
4511 && perm >= 0
4512 && mch_fstat(fd, &st) == 0
4513 && st.st_ino != st_old.st_ino)
4514 {
4515 close(fd);
4516 errmsg = (char_u *)_("E949: File changed while writing");
4517 goto fail;
4518 }
4519 }
4520#endif
4521#ifdef HAVE_FTRUNCATE
4522 if (!append)
Bram Moolenaarae1e1082017-11-17 21:35:24 +01004523 ignored = ftruncate(fd, (off_t)0);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004524#endif
4525
Bram Moolenaard0573012017-10-28 21:11:06 +02004526#if defined(WIN3264)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004527 if (backup != NULL && overwriting && !append)
4528 {
4529 if (backup_copy)
4530 (void)mch_copy_file_attribute(wfname, backup);
4531 else
4532 (void)mch_copy_file_attribute(backup, wfname);
4533 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004534
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004535 if (!overwriting && !append)
4536 {
4537 if (buf->b_ffname != NULL)
4538 (void)mch_copy_file_attribute(buf->b_ffname, wfname);
4539 /* Should copy resource fork */
4540 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004541#endif
4542
Bram Moolenaar071d4272004-06-13 20:20:40 +00004543#ifdef FEAT_CRYPT
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004544 if (*buf->b_p_key != NUL && !filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004545 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004546 char_u *header;
4547 int header_len;
4548
4549 buf->b_cryptstate = crypt_create_for_writing(
4550 crypt_get_method_nr(buf),
4551 buf->b_p_key, &header, &header_len);
4552 if (buf->b_cryptstate == NULL || header == NULL)
4553 end = 0;
4554 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004555 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004556 /* Write magic number, so that Vim knows how this file is
4557 * encrypted when reading it back. */
4558 write_info.bw_buf = header;
4559 write_info.bw_len = header_len;
4560 write_info.bw_flags = FIO_NOCONVERT;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004561 if (buf_write_bytes(&write_info) == FAIL)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004562 end = 0;
4563 wb_flags |= FIO_ENCRYPTED;
4564 vim_free(header);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004565 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004566 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004567#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004568 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004569 errmsg = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004570
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004571 write_info.bw_buf = buffer;
4572 nchars = 0;
4573
4574 /* use "++bin", "++nobin" or 'binary' */
4575 if (eap != NULL && eap->force_bin != 0)
4576 write_bin = (eap->force_bin == FORCE_BIN);
4577 else
4578 write_bin = buf->b_p_bin;
4579
4580#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004581 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004582 * The BOM is written just after the encryption magic number.
4583 * Skip it when appending and the file already existed, the BOM only
4584 * makes sense at the start of the file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004585 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004586 if (buf->b_p_bomb && !write_bin && (!append || perm < 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004587 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004588 write_info.bw_len = make_bom(buffer, fenc);
4589 if (write_info.bw_len > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004590 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004591 /* don't convert, do encryption */
4592 write_info.bw_flags = FIO_NOCONVERT | wb_flags;
4593 if (buf_write_bytes(&write_info) == FAIL)
4594 end = 0;
4595 else
4596 nchars += write_info.bw_len;
4597 }
4598 }
4599 write_info.bw_start_lnum = start;
4600#endif
4601
4602#ifdef FEAT_PERSISTENT_UNDO
4603 write_undo_file = (buf->b_p_udf
4604 && overwriting
4605 && !append
4606 && !filtering
4607 && reset_changed
4608 && !checking_conversion);
4609 if (write_undo_file)
4610 /* Prepare for computing the hash value of the text. */
4611 sha256_start(&sha_ctx);
4612#endif
4613
4614 write_info.bw_len = bufsize;
4615#ifdef HAS_BW_FLAGS
4616 write_info.bw_flags = wb_flags;
4617#endif
4618 fileformat = get_fileformat_force(buf, eap);
4619 s = buffer;
4620 len = 0;
4621 for (lnum = start; lnum <= end; ++lnum)
4622 {
4623 /*
4624 * The next while loop is done once for each character written.
4625 * Keep it fast!
4626 */
4627 ptr = ml_get_buf(buf, lnum, FALSE) - 1;
4628#ifdef FEAT_PERSISTENT_UNDO
4629 if (write_undo_file)
4630 sha256_update(&sha_ctx, ptr + 1,
4631 (UINT32_T)(STRLEN(ptr + 1) + 1));
4632#endif
4633 while ((c = *++ptr) != NUL)
4634 {
4635 if (c == NL)
4636 *s = NUL; /* replace newlines with NULs */
4637 else if (c == CAR && fileformat == EOL_MAC)
4638 *s = NL; /* Mac: replace CRs with NLs */
4639 else
4640 *s = c;
4641 ++s;
4642 if (++len != bufsize)
4643 continue;
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004644 if (buf_write_bytes(&write_info) == FAIL)
4645 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004646 end = 0; /* write error: break loop */
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004647 break;
4648 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004649 nchars += bufsize;
4650 s = buffer;
4651 len = 0;
4652#ifdef FEAT_MBYTE
4653 write_info.bw_start_lnum = lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004654#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004655 }
4656 /* write failed or last line has no EOL: stop here */
4657 if (end == 0
4658 || (lnum == end
4659 && (write_bin || !buf->b_p_fixeol)
4660 && (lnum == buf->b_no_eol_lnum
4661 || (lnum == buf->b_ml.ml_line_count
4662 && !buf->b_p_eol))))
4663 {
4664 ++lnum; /* written the line, count it */
4665 no_eol = TRUE;
4666 break;
4667 }
4668 if (fileformat == EOL_UNIX)
4669 *s++ = NL;
4670 else
4671 {
4672 *s++ = CAR; /* EOL_MAC or EOL_DOS: write CR */
4673 if (fileformat == EOL_DOS) /* write CR-NL */
4674 {
4675 if (++len == bufsize)
4676 {
4677 if (buf_write_bytes(&write_info) == FAIL)
4678 {
4679 end = 0; /* write error: break loop */
4680 break;
4681 }
4682 nchars += bufsize;
4683 s = buffer;
4684 len = 0;
4685 }
4686 *s++ = NL;
4687 }
4688 }
4689 if (++len == bufsize && end)
4690 {
4691 if (buf_write_bytes(&write_info) == FAIL)
4692 {
4693 end = 0; /* write error: break loop */
4694 break;
4695 }
4696 nchars += bufsize;
4697 s = buffer;
4698 len = 0;
4699
4700 ui_breakcheck();
4701 if (got_int)
4702 {
4703 end = 0; /* Interrupted, break loop */
4704 break;
4705 }
4706 }
4707#ifdef VMS
4708 /*
4709 * On VMS there is a problem: newlines get added when writing
4710 * blocks at a time. Fix it by writing a line at a time.
4711 * This is much slower!
4712 * Explanation: VAX/DECC RTL insists that records in some RMS
4713 * structures end with a newline (carriage return) character, and
4714 * if they don't it adds one.
4715 * With other RMS structures it works perfect without this fix.
4716 */
4717 if (buf->b_fab_rfm == FAB$C_VFC
4718 || ((buf->b_fab_rat & (FAB$M_FTN | FAB$M_CR)) != 0))
4719 {
4720 int b2write;
4721
4722 buf->b_fab_mrs = (buf->b_fab_mrs == 0
4723 ? MIN(4096, bufsize)
4724 : MIN(buf->b_fab_mrs, bufsize));
4725
4726 b2write = len;
4727 while (b2write > 0)
4728 {
4729 write_info.bw_len = MIN(b2write, buf->b_fab_mrs);
4730 if (buf_write_bytes(&write_info) == FAIL)
4731 {
4732 end = 0;
4733 break;
4734 }
4735 b2write -= MIN(b2write, buf->b_fab_mrs);
4736 }
4737 write_info.bw_len = bufsize;
4738 nchars += len;
4739 s = buffer;
4740 len = 0;
4741 }
4742#endif
4743 }
4744 if (len > 0 && end > 0)
4745 {
4746 write_info.bw_len = len;
4747 if (buf_write_bytes(&write_info) == FAIL)
4748 end = 0; /* write error */
4749 nchars += len;
4750 }
4751
4752 /* Stop when writing done or an error was encountered. */
4753 if (!checking_conversion || end == 0)
4754 break;
4755
4756 /* If no error happened until now, writing should be ok, so loop to
4757 * really write the buffer. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004758 }
4759
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004760 /* If we started writing, finish writing. Also when an error was
4761 * encountered. */
4762 if (!checking_conversion)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004763 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004764#if defined(UNIX) && defined(HAVE_FSYNC)
4765 /*
4766 * On many journalling file systems there is a bug that causes both the
4767 * original and the backup file to be lost when halting the system
4768 * right after writing the file. That's because only the meta-data is
4769 * journalled. Syncing the file slows down the system, but assures it
4770 * has been written to disk and we don't lose it.
4771 * For a device do try the fsync() but don't complain if it does not
4772 * work (could be a pipe).
4773 * If the 'fsync' option is FALSE, don't fsync(). Useful for laptops.
4774 */
4775 if (p_fs && fsync(fd) != 0 && !device)
4776 {
Bram Moolenaar7567d0b2017-11-16 23:04:15 +01004777 errmsg = (char_u *)_(e_fsync);
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004778 end = 0;
4779 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004780#endif
4781
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004782#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004783 /* Probably need to set the security context. */
4784 if (!backup_copy)
4785 mch_copy_sec(backup, wfname);
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004786#endif
4787
Bram Moolenaara5792f52005-11-23 21:25:05 +00004788#ifdef UNIX
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004789 /* When creating a new file, set its owner/group to that of the
4790 * original file. Get the new device and inode number. */
4791 if (backup != NULL && !backup_copy)
Bram Moolenaara5792f52005-11-23 21:25:05 +00004792 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004793# ifdef HAVE_FCHOWN
4794 stat_T st;
4795
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004796 /* Don't change the owner when it's already OK, some systems remove
4797 * permission or ACL stuff. */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004798 if (mch_stat((char *)wfname, &st) < 0
4799 || st.st_uid != st_old.st_uid
4800 || st.st_gid != st_old.st_gid)
4801 {
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004802 /* changing owner might not be possible */
4803 ignored = fchown(fd, st_old.st_uid, -1);
4804 /* if changing group fails clear the group permissions */
4805 if (fchown(fd, -1, st_old.st_gid) == -1 && perm > 0)
4806 perm &= ~070;
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004807 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00004808# endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004809 buf_setino(buf);
4810 }
4811 else if (!buf->b_dev_valid)
4812 /* Set the inode when creating a new file. */
4813 buf_setino(buf);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004814#endif
4815
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004816#ifdef UNIX
4817 if (made_writable)
4818 perm &= ~0200; /* reset 'w' bit for security reasons */
4819#endif
4820#ifdef HAVE_FCHMOD
4821 /* set permission of new file same as old file */
4822 if (perm >= 0)
4823 (void)mch_fsetperm(fd, perm);
4824#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004825 if (close(fd) != 0)
4826 {
4827 errmsg = (char_u *)_("E512: Close failed");
4828 end = 0;
4829 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004830
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004831#ifndef HAVE_FCHMOD
4832 /* set permission of new file same as old file */
4833 if (perm >= 0)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004834 (void)mch_setperm(wfname, perm);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004835#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004836#ifdef HAVE_ACL
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004837 /*
4838 * Probably need to set the ACL before changing the user (can't set the
4839 * ACL on a file the user doesn't own).
4840 * On Solaris, with ZFS and the aclmode property set to "discard" (the
4841 * default), chmod() discards all part of a file's ACL that don't
4842 * represent the mode of the file. It's non-trivial for us to discover
4843 * whether we're in that situation, so we simply always re-set the ACL.
4844 */
Bram Moolenaarda412772016-07-14 20:37:07 +02004845# ifndef HAVE_SOLARIS_ZFS_ACL
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004846 if (!backup_copy)
Bram Moolenaarda412772016-07-14 20:37:07 +02004847# endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004848 mch_set_acl(wfname, acl);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004849#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004850#ifdef FEAT_CRYPT
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004851 if (buf->b_cryptstate != NULL)
4852 {
4853 crypt_free_state(buf->b_cryptstate);
4854 buf->b_cryptstate = NULL;
4855 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004856#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004857
Bram Moolenaar071d4272004-06-13 20:20:40 +00004858#if defined(FEAT_MBYTE) && defined(FEAT_EVAL)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004859 if (wfname != fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004860 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004861 /*
4862 * The file was written to a temp file, now it needs to be
4863 * converted with 'charconvert' to (overwrite) the output file.
4864 */
4865 if (end != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004866 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004867 if (eval_charconvert(enc_utf8 ? (char_u *)"utf-8" : p_enc,
4868 fenc, wfname, fname) == FAIL)
4869 {
4870 write_info.bw_conv_error = TRUE;
4871 end = 0;
4872 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004873 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004874 mch_remove(wfname);
4875 vim_free(wfname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004876 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004877#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004878 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004879
4880 if (end == 0)
4881 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004882 /*
4883 * Error encountered.
4884 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004885 if (errmsg == NULL)
4886 {
4887#ifdef FEAT_MBYTE
4888 if (write_info.bw_conv_error)
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004889 {
4890 if (write_info.bw_conv_error_lnum == 0)
4891 errmsg = (char_u *)_("E513: write error, conversion failed (make 'fenc' empty to override)");
4892 else
4893 {
4894 errmsg_allocated = TRUE;
4895 errmsg = alloc(300);
4896 vim_snprintf((char *)errmsg, 300, _("E513: write error, conversion failed in line %ld (make 'fenc' empty to override)"),
4897 (long)write_info.bw_conv_error_lnum);
4898 }
4899 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004900 else
4901#endif
4902 if (got_int)
4903 errmsg = (char_u *)_(e_interr);
4904 else
4905 errmsg = (char_u *)_("E514: write error (file system full?)");
4906 }
4907
4908 /*
4909 * If we have a backup file, try to put it in place of the new file,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004910 * because the new file is probably corrupt. This avoids losing the
Bram Moolenaar071d4272004-06-13 20:20:40 +00004911 * original file when trying to make a backup when writing the file a
4912 * second time.
4913 * When "backup_copy" is set we need to copy the backup over the new
4914 * file. Otherwise rename the backup file.
4915 * If this is OK, don't give the extra warning message.
4916 */
4917 if (backup != NULL)
4918 {
4919 if (backup_copy)
4920 {
4921 /* This may take a while, if we were interrupted let the user
4922 * know we got the message. */
4923 if (got_int)
4924 {
4925 MSG(_(e_interr));
4926 out_flush();
4927 }
4928 if ((fd = mch_open((char *)backup, O_RDONLY | O_EXTRA, 0)) >= 0)
4929 {
4930 if ((write_info.bw_fd = mch_open((char *)fname,
Bram Moolenaar9be038d2005-03-08 22:34:32 +00004931 O_WRONLY | O_CREAT | O_TRUNC | O_EXTRA,
4932 perm & 0777)) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004933 {
4934 /* copy the file. */
4935 write_info.bw_buf = smallbuf;
4936#ifdef HAS_BW_FLAGS
4937 write_info.bw_flags = FIO_NOCONVERT;
4938#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004939 while ((write_info.bw_len = read_eintr(fd, smallbuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004940 SMBUFSIZE)) > 0)
4941 if (buf_write_bytes(&write_info) == FAIL)
4942 break;
4943
4944 if (close(write_info.bw_fd) >= 0
4945 && write_info.bw_len == 0)
4946 end = 1; /* success */
4947 }
4948 close(fd); /* ignore errors for closing read file */
4949 }
4950 }
4951 else
4952 {
4953 if (vim_rename(backup, fname) == 0)
4954 end = 1;
4955 }
4956 }
4957 goto fail;
4958 }
4959
4960 lnum -= start; /* compute number of written lines */
4961 --no_wait_return; /* may wait for return now */
4962
4963#if !(defined(UNIX) || defined(VMS))
4964 fname = sfname; /* use shortname now, for the messages */
4965#endif
4966 if (!filtering)
4967 {
4968 msg_add_fname(buf, fname); /* put fname in IObuff with quotes */
4969 c = FALSE;
4970#ifdef FEAT_MBYTE
4971 if (write_info.bw_conv_error)
4972 {
4973 STRCAT(IObuff, _(" CONVERSION ERROR"));
4974 c = TRUE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004975 if (write_info.bw_conv_error_lnum != 0)
Bram Moolenaara800b422010-06-27 01:15:55 +02004976 vim_snprintf_add((char *)IObuff, IOSIZE, _(" in line %ld;"),
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004977 (long)write_info.bw_conv_error_lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004978 }
4979 else if (notconverted)
4980 {
4981 STRCAT(IObuff, _("[NOT converted]"));
4982 c = TRUE;
4983 }
4984 else if (converted)
4985 {
4986 STRCAT(IObuff, _("[converted]"));
4987 c = TRUE;
4988 }
4989#endif
4990 if (device)
4991 {
4992 STRCAT(IObuff, _("[Device]"));
4993 c = TRUE;
4994 }
4995 else if (newfile)
4996 {
4997 STRCAT(IObuff, shortmess(SHM_NEW) ? _("[New]") : _("[New File]"));
4998 c = TRUE;
4999 }
5000 if (no_eol)
5001 {
5002 msg_add_eol();
5003 c = TRUE;
5004 }
5005 /* may add [unix/dos/mac] */
5006 if (msg_add_fileformat(fileformat))
5007 c = TRUE;
5008#ifdef FEAT_CRYPT
5009 if (wb_flags & FIO_ENCRYPTED)
5010 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02005011 crypt_append_msg(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005012 c = TRUE;
5013 }
5014#endif
5015 msg_add_lines(c, (long)lnum, nchars); /* add line/char count */
5016 if (!shortmess(SHM_WRITE))
5017 {
5018 if (append)
5019 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended"));
5020 else
5021 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written"));
5022 }
5023
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00005024 set_keep_msg(msg_trunc_attr(IObuff, FALSE, 0), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005025 }
5026
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005027 /* When written everything correctly: reset 'modified'. Unless not
5028 * writing to the original file and '+' is not in 'cpoptions'. */
Bram Moolenaar292ad192005-12-11 21:29:51 +00005029 if (reset_changed && whole && !append
Bram Moolenaar071d4272004-06-13 20:20:40 +00005030#ifdef FEAT_MBYTE
5031 && !write_info.bw_conv_error
5032#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005033 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL)
5034 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00005035 {
5036 unchanged(buf, TRUE);
Bram Moolenaar086329d2014-10-31 19:51:36 +01005037#ifdef FEAT_AUTOCMD
Bram Moolenaar95c526e2017-02-25 14:59:34 +01005038 /* b:changedtick is always incremented in unchanged() but that
Bram Moolenaar086329d2014-10-31 19:51:36 +01005039 * should not trigger a TextChanged event. */
Bram Moolenaar95c526e2017-02-25 14:59:34 +01005040 if (last_changedtick + 1 == CHANGEDTICK(buf)
Bram Moolenaar086329d2014-10-31 19:51:36 +01005041 && last_changedtick_buf == buf)
Bram Moolenaar95c526e2017-02-25 14:59:34 +01005042 last_changedtick = CHANGEDTICK(buf);
Bram Moolenaar086329d2014-10-31 19:51:36 +01005043#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005044 u_unchanged(buf);
Bram Moolenaar730cde92010-06-27 05:18:54 +02005045 u_update_save_nr(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005046 }
5047
5048 /*
5049 * If written to the current file, update the timestamp of the swap file
5050 * and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
5051 */
5052 if (overwriting)
5053 {
5054 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00005055 if (append)
5056 buf->b_flags &= ~BF_NEW;
5057 else
5058 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005059 }
5060
5061 /*
5062 * If we kept a backup until now, and we are in patch mode, then we make
5063 * the backup file our 'original' file.
5064 */
5065 if (*p_pm && dobackup)
5066 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01005067 char *org = (char *)buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005068 fname, p_pm, FALSE);
5069
5070 if (backup != NULL)
5071 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02005072 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005073
5074 /*
5075 * If the original file does not exist yet
5076 * the current backup file becomes the original file
5077 */
5078 if (org == NULL)
5079 EMSG(_("E205: Patchmode: can't save original file"));
5080 else if (mch_stat(org, &st) < 0)
5081 {
5082 vim_rename(backup, (char_u *)org);
5083 vim_free(backup); /* don't delete the file */
5084 backup = NULL;
5085#ifdef UNIX
5086 set_file_time((char_u *)org, st_old.st_atime, st_old.st_mtime);
5087#endif
5088 }
5089 }
5090 /*
5091 * If there is no backup file, remember that a (new) file was
5092 * created.
5093 */
5094 else
5095 {
5096 int empty_fd;
5097
5098 if (org == NULL
Bram Moolenaara5792f52005-11-23 21:25:05 +00005099 || (empty_fd = mch_open(org,
5100 O_CREAT | O_EXTRA | O_EXCL | O_NOFOLLOW,
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00005101 perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005102 EMSG(_("E206: patchmode: can't touch empty original file"));
5103 else
5104 close(empty_fd);
5105 }
5106 if (org != NULL)
5107 {
5108 mch_setperm((char_u *)org, mch_getperm(fname) & 0777);
5109 vim_free(org);
5110 }
5111 }
5112
5113 /*
5114 * Remove the backup unless 'backup' option is set
5115 */
5116 if (!p_bk && backup != NULL && mch_remove(backup) != 0)
5117 EMSG(_("E207: Can't delete backup file"));
5118
5119#ifdef FEAT_SUN_WORKSHOP
5120 if (usingSunWorkShop)
5121 workshop_file_saved((char *) ffname);
5122#endif
5123
5124 goto nofail;
5125
5126 /*
5127 * Finish up. We get here either after failure or success.
5128 */
5129fail:
5130 --no_wait_return; /* may wait for return now */
5131nofail:
5132
5133 /* Done saving, we accept changed buffer warnings again */
5134 buf->b_saving = FALSE;
5135
5136 vim_free(backup);
5137 if (buffer != smallbuf)
5138 vim_free(buffer);
5139#ifdef FEAT_MBYTE
5140 vim_free(fenc_tofree);
5141 vim_free(write_info.bw_conv_buf);
5142# ifdef USE_ICONV
5143 if (write_info.bw_iconv_fd != (iconv_t)-1)
5144 {
5145 iconv_close(write_info.bw_iconv_fd);
5146 write_info.bw_iconv_fd = (iconv_t)-1;
5147 }
5148# endif
5149#endif
5150#ifdef HAVE_ACL
5151 mch_free_acl(acl);
5152#endif
5153
5154 if (errmsg != NULL)
5155 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005156 int numlen = errnum != NULL ? (int)STRLEN(errnum) : 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005157
Bram Moolenaar8820b482017-03-16 17:23:31 +01005158 attr = HL_ATTR(HLF_E); /* set highlight for error messages */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005159 msg_add_fname(buf,
5160#ifndef UNIX
5161 sfname
5162#else
5163 fname
5164#endif
5165 ); /* put file name in IObuff with quotes */
5166 if (STRLEN(IObuff) + STRLEN(errmsg) + numlen >= IOSIZE)
5167 IObuff[IOSIZE - STRLEN(errmsg) - numlen - 1] = NUL;
5168 /* If the error message has the form "is ...", put the error number in
5169 * front of the file name. */
5170 if (errnum != NULL)
5171 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00005172 STRMOVE(IObuff + numlen, IObuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005173 mch_memmove(IObuff, errnum, (size_t)numlen);
5174 }
5175 STRCAT(IObuff, errmsg);
5176 emsg(IObuff);
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005177 if (errmsg_allocated)
5178 vim_free(errmsg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005179
5180 retval = FAIL;
5181 if (end == 0)
5182 {
5183 MSG_PUTS_ATTR(_("\nWARNING: Original file may be lost or damaged\n"),
5184 attr | MSG_HIST);
5185 MSG_PUTS_ATTR(_("don't quit the editor until the file is successfully written!"),
5186 attr | MSG_HIST);
5187
5188 /* Update the timestamp to avoid an "overwrite changed file"
5189 * prompt when writing again. */
5190 if (mch_stat((char *)fname, &st_old) >= 0)
5191 {
5192 buf_store_time(buf, &st_old, fname);
5193 buf->b_mtime_read = buf->b_mtime;
5194 }
5195 }
5196 }
5197 msg_scroll = msg_save;
5198
Bram Moolenaar55debbe2010-05-23 23:34:36 +02005199#ifdef FEAT_PERSISTENT_UNDO
5200 /*
5201 * When writing the whole file and 'undofile' is set, also write the undo
5202 * file.
5203 */
5204 if (retval == OK && write_undo_file)
5205 {
5206 char_u hash[UNDO_HASH_SIZE];
5207
5208 sha256_finish(&sha_ctx, hash);
5209 u_write_undo(NULL, FALSE, buf, hash);
5210 }
5211#endif
5212
Bram Moolenaar071d4272004-06-13 20:20:40 +00005213#ifdef FEAT_AUTOCMD
5214#ifdef FEAT_EVAL
5215 if (!should_abort(retval))
5216#else
5217 if (!got_int)
5218#endif
5219 {
5220 aco_save_T aco;
5221
Bram Moolenaar68a33fc2012-04-25 16:50:48 +02005222 curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */
5223
Bram Moolenaar071d4272004-06-13 20:20:40 +00005224 /*
5225 * Apply POST autocommands.
5226 * Careful: The autocommands may call buf_write() recursively!
5227 */
5228 aucmd_prepbuf(&aco, buf);
5229
5230 if (append)
5231 apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname,
5232 FALSE, curbuf, eap);
5233 else if (filtering)
5234 apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname,
5235 FALSE, curbuf, eap);
5236 else if (reset_changed && whole)
5237 apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname,
5238 FALSE, curbuf, eap);
5239 else
5240 apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname,
5241 FALSE, curbuf, eap);
5242
5243 /* restore curwin/curbuf and a few other things */
5244 aucmd_restbuf(&aco);
5245
5246#ifdef FEAT_EVAL
5247 if (aborting()) /* autocmds may abort script processing */
5248 retval = FALSE;
5249#endif
5250 }
5251#endif
5252
5253 got_int |= prev_got_int;
5254
Bram Moolenaar071d4272004-06-13 20:20:40 +00005255 return retval;
5256}
5257
5258/*
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005259 * Set the name of the current buffer. Use when the buffer doesn't have a
5260 * name and a ":r" or ":w" command with a file name is used.
5261 */
5262 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005263set_rw_fname(char_u *fname, char_u *sfname)
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005264{
5265#ifdef FEAT_AUTOCMD
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005266 buf_T *buf = curbuf;
5267
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005268 /* It's like the unnamed buffer is deleted.... */
5269 if (curbuf->b_p_bl)
5270 apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
5271 apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf);
5272# ifdef FEAT_EVAL
5273 if (aborting()) /* autocmds may abort script processing */
5274 return FAIL;
5275# endif
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005276 if (curbuf != buf)
5277 {
5278 /* We are in another buffer now, don't do the renaming. */
5279 EMSG(_(e_auchangedbuf));
5280 return FAIL;
5281 }
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005282#endif
5283
5284 if (setfname(curbuf, fname, sfname, FALSE) == OK)
5285 curbuf->b_flags |= BF_NOTEDITED;
5286
5287#ifdef FEAT_AUTOCMD
5288 /* ....and a new named one is created */
5289 apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, curbuf);
5290 if (curbuf->b_p_bl)
5291 apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf);
5292# ifdef FEAT_EVAL
5293 if (aborting()) /* autocmds may abort script processing */
5294 return FAIL;
5295# endif
5296
5297 /* Do filetype detection now if 'filetype' is empty. */
5298 if (*curbuf->b_p_ft == NUL)
5299 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005300 if (au_has_group((char_u *)"filetypedetect"))
Bram Moolenaar1610d052016-06-09 22:53:01 +02005301 (void)do_doautocmd((char_u *)"filetypedetect BufRead", FALSE, NULL);
Bram Moolenaara3227e22006-03-08 21:32:40 +00005302 do_modelines(0);
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005303 }
5304#endif
5305
5306 return OK;
5307}
5308
5309/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00005310 * Put file name into IObuff with quotes.
5311 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005312 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005313msg_add_fname(buf_T *buf, char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005314{
5315 if (fname == NULL)
5316 fname = (char_u *)"-stdin-";
5317 home_replace(buf, fname, IObuff + 1, IOSIZE - 4, TRUE);
5318 IObuff[0] = '"';
5319 STRCAT(IObuff, "\" ");
5320}
5321
5322/*
5323 * Append message for text mode to IObuff.
5324 * Return TRUE if something appended.
5325 */
5326 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005327msg_add_fileformat(int eol_type)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005328{
5329#ifndef USE_CRNL
5330 if (eol_type == EOL_DOS)
5331 {
5332 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[dos]") : _("[dos format]"));
5333 return TRUE;
5334 }
5335#endif
5336#ifndef USE_CR
5337 if (eol_type == EOL_MAC)
5338 {
5339 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[mac]") : _("[mac format]"));
5340 return TRUE;
5341 }
5342#endif
5343#if defined(USE_CRNL) || defined(USE_CR)
5344 if (eol_type == EOL_UNIX)
5345 {
5346 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[unix]") : _("[unix format]"));
5347 return TRUE;
5348 }
5349#endif
5350 return FALSE;
5351}
5352
5353/*
5354 * Append line and character count to IObuff.
5355 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005356 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005357msg_add_lines(
5358 int insert_space,
5359 long lnum,
Bram Moolenaar8767f522016-07-01 17:17:39 +02005360 off_T nchars)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005361{
5362 char_u *p;
5363
5364 p = IObuff + STRLEN(IObuff);
5365
5366 if (insert_space)
5367 *p++ = ' ';
5368 if (shortmess(SHM_LINES))
Bram Moolenaarbde98102016-07-01 20:03:42 +02005369 vim_snprintf((char *)p, IOSIZE - (p - IObuff),
5370 "%ldL, %lldC", lnum, (varnumber_T)nchars);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005371 else
5372 {
5373 if (lnum == 1)
5374 STRCPY(p, _("1 line, "));
5375 else
5376 sprintf((char *)p, _("%ld lines, "), lnum);
5377 p += STRLEN(p);
5378 if (nchars == 1)
5379 STRCPY(p, _("1 character"));
5380 else
Bram Moolenaarbde98102016-07-01 20:03:42 +02005381 vim_snprintf((char *)p, IOSIZE - (p - IObuff),
5382 _("%lld characters"), (varnumber_T)nchars);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005383 }
5384}
5385
5386/*
5387 * Append message for missing line separator to IObuff.
5388 */
5389 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005390msg_add_eol(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005391{
5392 STRCAT(IObuff, shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]"));
5393}
5394
5395/*
5396 * Check modification time of file, before writing to it.
5397 * The size isn't checked, because using a tool like "gzip" takes care of
5398 * using the same timestamp but can't set the size.
5399 */
5400 static int
Bram Moolenaar8767f522016-07-01 17:17:39 +02005401check_mtime(buf_T *buf, stat_T *st)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005402{
5403 if (buf->b_mtime_read != 0
5404 && time_differs((long)st->st_mtime, buf->b_mtime_read))
5405 {
5406 msg_scroll = TRUE; /* don't overwrite messages here */
5407 msg_silent = 0; /* must give this prompt */
5408 /* don't use emsg() here, don't want to flush the buffers */
5409 MSG_ATTR(_("WARNING: The file has been changed since reading it!!!"),
Bram Moolenaar8820b482017-03-16 17:23:31 +01005410 HL_ATTR(HLF_E));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005411 if (ask_yesno((char_u *)_("Do you really want to write to it"),
5412 TRUE) == 'n')
5413 return FAIL;
5414 msg_scroll = FALSE; /* always overwrite the file message now */
5415 }
5416 return OK;
5417}
5418
5419 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005420time_differs(long t1, long t2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005421{
Bram Moolenaar48e330a2016-02-23 14:53:34 +01005422#if defined(__linux__) || defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005423 /* On a FAT filesystem, esp. under Linux, there are only 5 bits to store
5424 * the seconds. Since the roundoff is done when flushing the inode, the
5425 * time may change unexpectedly by one second!!! */
5426 return (t1 - t2 > 1 || t2 - t1 > 1);
5427#else
5428 return (t1 != t2);
5429#endif
5430}
5431
5432/*
5433 * Call write() to write a number of bytes to the file.
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005434 * Handles encryption and 'encoding' conversion.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005435 *
5436 * Return FAIL for failure, OK otherwise.
5437 */
5438 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005439buf_write_bytes(struct bw_info *ip)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005440{
5441 int wlen;
5442 char_u *buf = ip->bw_buf; /* data to write */
5443 int len = ip->bw_len; /* length of data */
5444#ifdef HAS_BW_FLAGS
5445 int flags = ip->bw_flags; /* extra flags */
5446#endif
5447
5448#ifdef FEAT_MBYTE
5449 /*
5450 * Skip conversion when writing the crypt magic number or the BOM.
5451 */
5452 if (!(flags & FIO_NOCONVERT))
5453 {
5454 char_u *p;
5455 unsigned c;
5456 int n;
5457
5458 if (flags & FIO_UTF8)
5459 {
5460 /*
5461 * Convert latin1 in the buffer to UTF-8 in the file.
5462 */
5463 p = ip->bw_conv_buf; /* translate to buffer */
5464 for (wlen = 0; wlen < len; ++wlen)
5465 p += utf_char2bytes(buf[wlen], p);
5466 buf = ip->bw_conv_buf;
5467 len = (int)(p - ip->bw_conv_buf);
5468 }
5469 else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1))
5470 {
5471 /*
5472 * Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
5473 * Latin1 chars in the file.
5474 */
5475 if (flags & FIO_LATIN1)
5476 p = buf; /* translate in-place (can only get shorter) */
5477 else
5478 p = ip->bw_conv_buf; /* translate to buffer */
5479 for (wlen = 0; wlen < len; wlen += n)
5480 {
5481 if (wlen == 0 && ip->bw_restlen != 0)
5482 {
5483 int l;
5484
5485 /* Use remainder of previous call. Append the start of
5486 * buf[] to get a full sequence. Might still be too
5487 * short! */
5488 l = CONV_RESTLEN - ip->bw_restlen;
5489 if (l > len)
5490 l = len;
5491 mch_memmove(ip->bw_rest + ip->bw_restlen, buf, (size_t)l);
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005492 n = utf_ptr2len_len(ip->bw_rest, ip->bw_restlen + l);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005493 if (n > ip->bw_restlen + len)
5494 {
5495 /* We have an incomplete byte sequence at the end to
5496 * be written. We can't convert it without the
5497 * remaining bytes. Keep them for the next call. */
5498 if (ip->bw_restlen + len > CONV_RESTLEN)
5499 return FAIL;
5500 ip->bw_restlen += len;
5501 break;
5502 }
5503 if (n > 1)
5504 c = utf_ptr2char(ip->bw_rest);
5505 else
5506 c = ip->bw_rest[0];
5507 if (n >= ip->bw_restlen)
5508 {
5509 n -= ip->bw_restlen;
5510 ip->bw_restlen = 0;
5511 }
5512 else
5513 {
5514 ip->bw_restlen -= n;
5515 mch_memmove(ip->bw_rest, ip->bw_rest + n,
5516 (size_t)ip->bw_restlen);
5517 n = 0;
5518 }
5519 }
5520 else
5521 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005522 n = utf_ptr2len_len(buf + wlen, len - wlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005523 if (n > len - wlen)
5524 {
5525 /* We have an incomplete byte sequence at the end to
5526 * be written. We can't convert it without the
5527 * remaining bytes. Keep them for the next call. */
5528 if (len - wlen > CONV_RESTLEN)
5529 return FAIL;
5530 ip->bw_restlen = len - wlen;
5531 mch_memmove(ip->bw_rest, buf + wlen,
5532 (size_t)ip->bw_restlen);
5533 break;
5534 }
5535 if (n > 1)
5536 c = utf_ptr2char(buf + wlen);
5537 else
5538 c = buf[wlen];
5539 }
5540
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005541 if (ucs2bytes(c, &p, flags) && !ip->bw_conv_error)
5542 {
5543 ip->bw_conv_error = TRUE;
5544 ip->bw_conv_error_lnum = ip->bw_start_lnum;
5545 }
5546 if (c == NL)
5547 ++ip->bw_start_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005548 }
5549 if (flags & FIO_LATIN1)
5550 len = (int)(p - buf);
5551 else
5552 {
5553 buf = ip->bw_conv_buf;
5554 len = (int)(p - ip->bw_conv_buf);
5555 }
5556 }
5557
5558# ifdef WIN3264
5559 else if (flags & FIO_CODEPAGE)
5560 {
5561 /*
5562 * Convert UTF-8 or codepage to UCS-2 and then to MS-Windows
5563 * codepage.
5564 */
5565 char_u *from;
5566 size_t fromlen;
5567 char_u *to;
5568 int u8c;
5569 BOOL bad = FALSE;
5570 int needed;
5571
5572 if (ip->bw_restlen > 0)
5573 {
5574 /* Need to concatenate the remainder of the previous call and
5575 * the bytes of the current call. Use the end of the
5576 * conversion buffer for this. */
5577 fromlen = len + ip->bw_restlen;
5578 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5579 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5580 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5581 }
5582 else
5583 {
5584 from = buf;
5585 fromlen = len;
5586 }
5587
5588 to = ip->bw_conv_buf;
5589 if (enc_utf8)
5590 {
5591 /* Convert from UTF-8 to UCS-2, to the start of the buffer.
5592 * The buffer has been allocated to be big enough. */
5593 while (fromlen > 0)
5594 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005595 n = (int)utf_ptr2len_len(from, (int)fromlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005596 if (n > (int)fromlen) /* incomplete byte sequence */
5597 break;
5598 u8c = utf_ptr2char(from);
5599 *to++ = (u8c & 0xff);
5600 *to++ = (u8c >> 8);
5601 fromlen -= n;
5602 from += n;
5603 }
5604
5605 /* Copy remainder to ip->bw_rest[] to be used for the next
5606 * call. */
5607 if (fromlen > CONV_RESTLEN)
5608 {
5609 /* weird overlong sequence */
5610 ip->bw_conv_error = TRUE;
5611 return FAIL;
5612 }
5613 mch_memmove(ip->bw_rest, from, fromlen);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005614 ip->bw_restlen = (int)fromlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005615 }
5616 else
5617 {
5618 /* Convert from enc_codepage to UCS-2, to the start of the
5619 * buffer. The buffer has been allocated to be big enough. */
5620 ip->bw_restlen = 0;
5621 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005622 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005623 NULL, 0);
5624 if (needed == 0)
5625 {
5626 /* When conversion fails there may be a trailing byte. */
5627 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005628 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen - 1,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005629 NULL, 0);
5630 if (needed == 0)
5631 {
5632 /* Conversion doesn't work. */
5633 ip->bw_conv_error = TRUE;
5634 return FAIL;
5635 }
5636 /* Save the trailing byte for the next call. */
5637 ip->bw_rest[0] = from[fromlen - 1];
5638 ip->bw_restlen = 1;
5639 }
5640 needed = MultiByteToWideChar(enc_codepage, MB_ERR_INVALID_CHARS,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005641 (LPCSTR)from, (int)(fromlen - ip->bw_restlen),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005642 (LPWSTR)to, needed);
5643 if (needed == 0)
5644 {
5645 /* Safety check: Conversion doesn't work. */
5646 ip->bw_conv_error = TRUE;
5647 return FAIL;
5648 }
5649 to += needed * 2;
5650 }
5651
5652 fromlen = to - ip->bw_conv_buf;
5653 buf = to;
5654# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5655 if (FIO_GET_CP(flags) == CP_UTF8)
5656 {
5657 /* Convert from UCS-2 to UTF-8, using the remainder of the
5658 * conversion buffer. Fails when out of space. */
5659 for (from = ip->bw_conv_buf; fromlen > 1; fromlen -= 2)
5660 {
5661 u8c = *from++;
5662 u8c += (*from++ << 8);
5663 to += utf_char2bytes(u8c, to);
5664 if (to + 6 >= ip->bw_conv_buf + ip->bw_conv_buflen)
5665 {
5666 ip->bw_conv_error = TRUE;
5667 return FAIL;
5668 }
5669 }
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005670 len = (int)(to - buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005671 }
5672 else
5673#endif
5674 {
5675 /* Convert from UCS-2 to the codepage, using the remainder of
5676 * the conversion buffer. If the conversion uses the default
5677 * character "0", the data doesn't fit in this encoding, so
5678 * fail. */
5679 len = WideCharToMultiByte(FIO_GET_CP(flags), 0,
5680 (LPCWSTR)ip->bw_conv_buf, (int)fromlen / sizeof(WCHAR),
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005681 (LPSTR)to, (int)(ip->bw_conv_buflen - fromlen), 0,
5682 &bad);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005683 if (bad)
5684 {
5685 ip->bw_conv_error = TRUE;
5686 return FAIL;
5687 }
5688 }
5689 }
5690# endif
5691
Bram Moolenaar56718732006-03-15 22:53:57 +00005692# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00005693 else if (flags & FIO_MACROMAN)
5694 {
5695 /*
5696 * Convert UTF-8 or latin1 to Apple MacRoman.
5697 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005698 char_u *from;
5699 size_t fromlen;
5700
5701 if (ip->bw_restlen > 0)
5702 {
5703 /* Need to concatenate the remainder of the previous call and
5704 * the bytes of the current call. Use the end of the
5705 * conversion buffer for this. */
5706 fromlen = len + ip->bw_restlen;
5707 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5708 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5709 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5710 }
5711 else
5712 {
5713 from = buf;
5714 fromlen = len;
5715 }
5716
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00005717 if (enc2macroman(from, fromlen,
5718 ip->bw_conv_buf, &len, ip->bw_conv_buflen,
5719 ip->bw_rest, &ip->bw_restlen) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005720 {
5721 ip->bw_conv_error = TRUE;
5722 return FAIL;
5723 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005724 buf = ip->bw_conv_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005725 }
5726# endif
5727
5728# ifdef USE_ICONV
5729 if (ip->bw_iconv_fd != (iconv_t)-1)
5730 {
5731 const char *from;
5732 size_t fromlen;
5733 char *to;
5734 size_t tolen;
5735
5736 /* Convert with iconv(). */
5737 if (ip->bw_restlen > 0)
5738 {
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005739 char *fp;
5740
Bram Moolenaar071d4272004-06-13 20:20:40 +00005741 /* Need to concatenate the remainder of the previous call and
5742 * the bytes of the current call. Use the end of the
5743 * conversion buffer for this. */
5744 fromlen = len + ip->bw_restlen;
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005745 fp = (char *)ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5746 mch_memmove(fp, ip->bw_rest, (size_t)ip->bw_restlen);
5747 mch_memmove(fp + ip->bw_restlen, buf, (size_t)len);
5748 from = fp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005749 tolen = ip->bw_conv_buflen - fromlen;
5750 }
5751 else
5752 {
5753 from = (const char *)buf;
5754 fromlen = len;
5755 tolen = ip->bw_conv_buflen;
5756 }
5757 to = (char *)ip->bw_conv_buf;
5758
5759 if (ip->bw_first)
5760 {
5761 size_t save_len = tolen;
5762
5763 /* output the initial shift state sequence */
5764 (void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen);
5765
5766 /* There is a bug in iconv() on Linux (which appears to be
5767 * wide-spread) which sets "to" to NULL and messes up "tolen".
5768 */
5769 if (to == NULL)
5770 {
5771 to = (char *)ip->bw_conv_buf;
5772 tolen = save_len;
5773 }
5774 ip->bw_first = FALSE;
5775 }
5776
5777 /*
5778 * If iconv() has an error or there is not enough room, fail.
5779 */
5780 if ((iconv(ip->bw_iconv_fd, (void *)&from, &fromlen, &to, &tolen)
5781 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
5782 || fromlen > CONV_RESTLEN)
5783 {
5784 ip->bw_conv_error = TRUE;
5785 return FAIL;
5786 }
5787
5788 /* copy remainder to ip->bw_rest[] to be used for the next call. */
5789 if (fromlen > 0)
5790 mch_memmove(ip->bw_rest, (void *)from, fromlen);
5791 ip->bw_restlen = (int)fromlen;
5792
5793 buf = ip->bw_conv_buf;
5794 len = (int)((char_u *)to - ip->bw_conv_buf);
5795 }
5796# endif
5797 }
5798#endif /* FEAT_MBYTE */
5799
Bram Moolenaare6bf6552017-06-27 22:11:51 +02005800 if (ip->bw_fd < 0)
5801 /* Only checking conversion, which is OK if we get here. */
5802 return OK;
5803
Bram Moolenaar071d4272004-06-13 20:20:40 +00005804#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02005805 if (flags & FIO_ENCRYPTED)
5806 {
5807 /* Encrypt the data. Do it in-place if possible, otherwise use an
5808 * allocated buffer. */
5809 if (crypt_works_inplace(ip->bw_buffer->b_cryptstate))
5810 {
5811 crypt_encode_inplace(ip->bw_buffer->b_cryptstate, buf, len);
5812 }
5813 else
5814 {
5815 char_u *outbuf;
5816
5817 len = crypt_encode_alloc(curbuf->b_cryptstate, buf, len, &outbuf);
5818 if (len == 0)
5819 return OK; /* Crypt layer is buffering, will flush later. */
5820 wlen = write_eintr(ip->bw_fd, outbuf, len);
5821 vim_free(outbuf);
5822 return (wlen < len) ? FAIL : OK;
5823 }
5824 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005825#endif
5826
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005827 wlen = write_eintr(ip->bw_fd, buf, len);
5828 return (wlen < len) ? FAIL : OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005829}
5830
5831#ifdef FEAT_MBYTE
5832/*
5833 * Convert a Unicode character to bytes.
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005834 * Return TRUE for an error, FALSE when it's OK.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005835 */
5836 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005837ucs2bytes(
5838 unsigned c, /* in: character */
5839 char_u **pp, /* in/out: pointer to result */
5840 int flags) /* FIO_ flags */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005841{
5842 char_u *p = *pp;
5843 int error = FALSE;
5844 int cc;
5845
5846
5847 if (flags & FIO_UCS4)
5848 {
5849 if (flags & FIO_ENDIAN_L)
5850 {
5851 *p++ = c;
5852 *p++ = (c >> 8);
5853 *p++ = (c >> 16);
5854 *p++ = (c >> 24);
5855 }
5856 else
5857 {
5858 *p++ = (c >> 24);
5859 *p++ = (c >> 16);
5860 *p++ = (c >> 8);
5861 *p++ = c;
5862 }
5863 }
5864 else if (flags & (FIO_UCS2 | FIO_UTF16))
5865 {
5866 if (c >= 0x10000)
5867 {
5868 if (flags & FIO_UTF16)
5869 {
5870 /* Make two words, ten bits of the character in each. First
5871 * word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff */
5872 c -= 0x10000;
5873 if (c >= 0x100000)
5874 error = TRUE;
5875 cc = ((c >> 10) & 0x3ff) + 0xd800;
5876 if (flags & FIO_ENDIAN_L)
5877 {
5878 *p++ = cc;
5879 *p++ = ((unsigned)cc >> 8);
5880 }
5881 else
5882 {
5883 *p++ = ((unsigned)cc >> 8);
5884 *p++ = cc;
5885 }
5886 c = (c & 0x3ff) + 0xdc00;
5887 }
5888 else
5889 error = TRUE;
5890 }
5891 if (flags & FIO_ENDIAN_L)
5892 {
5893 *p++ = c;
5894 *p++ = (c >> 8);
5895 }
5896 else
5897 {
5898 *p++ = (c >> 8);
5899 *p++ = c;
5900 }
5901 }
5902 else /* Latin1 */
5903 {
5904 if (c >= 0x100)
5905 {
5906 error = TRUE;
5907 *p++ = 0xBF;
5908 }
5909 else
5910 *p++ = c;
5911 }
5912
5913 *pp = p;
5914 return error;
5915}
5916
5917/*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005918 * Return TRUE if file encoding "fenc" requires conversion from or to
5919 * 'encoding'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005920 */
5921 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005922need_conversion(char_u *fenc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005923{
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005924 int same_encoding;
5925 int enc_flags;
5926 int fenc_flags;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005927
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005928 if (*fenc == NUL || STRCMP(p_enc, fenc) == 0)
Bram Moolenaar442b4222010-05-24 21:34:22 +02005929 {
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005930 same_encoding = TRUE;
Bram Moolenaar442b4222010-05-24 21:34:22 +02005931 fenc_flags = 0;
5932 }
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005933 else
5934 {
5935 /* Ignore difference between "ansi" and "latin1", "ucs-4" and
5936 * "ucs-4be", etc. */
5937 enc_flags = get_fio_flags(p_enc);
5938 fenc_flags = get_fio_flags(fenc);
5939 same_encoding = (enc_flags != 0 && fenc_flags == enc_flags);
5940 }
5941 if (same_encoding)
5942 {
5943 /* Specified encoding matches with 'encoding'. This requires
5944 * conversion when 'encoding' is Unicode but not UTF-8. */
5945 return enc_unicode != 0;
5946 }
5947
5948 /* Encodings differ. However, conversion is not needed when 'enc' is any
5949 * Unicode encoding and the file is UTF-8. */
5950 return !(enc_utf8 && fenc_flags == FIO_UTF8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005951}
5952
5953/*
5954 * Check "ptr" for a unicode encoding and return the FIO_ flags needed for the
5955 * internal conversion.
5956 * if "ptr" is an empty string, use 'encoding'.
5957 */
5958 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005959get_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005960{
5961 int prop;
5962
5963 if (*ptr == NUL)
5964 ptr = p_enc;
5965
5966 prop = enc_canon_props(ptr);
5967 if (prop & ENC_UNICODE)
5968 {
5969 if (prop & ENC_2BYTE)
5970 {
5971 if (prop & ENC_ENDIAN_L)
5972 return FIO_UCS2 | FIO_ENDIAN_L;
5973 return FIO_UCS2;
5974 }
5975 if (prop & ENC_4BYTE)
5976 {
5977 if (prop & ENC_ENDIAN_L)
5978 return FIO_UCS4 | FIO_ENDIAN_L;
5979 return FIO_UCS4;
5980 }
5981 if (prop & ENC_2WORD)
5982 {
5983 if (prop & ENC_ENDIAN_L)
5984 return FIO_UTF16 | FIO_ENDIAN_L;
5985 return FIO_UTF16;
5986 }
5987 return FIO_UTF8;
5988 }
5989 if (prop & ENC_LATIN1)
5990 return FIO_LATIN1;
5991 /* must be ENC_DBCS, requires iconv() */
5992 return 0;
5993}
5994
5995#ifdef WIN3264
5996/*
5997 * Check "ptr" for a MS-Windows codepage name and return the FIO_ flags needed
5998 * for the conversion MS-Windows can do for us. Also accept "utf-8".
5999 * Used for conversion between 'encoding' and 'fileencoding'.
6000 */
6001 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006002get_win_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006003{
6004 int cp;
6005
6006 /* Cannot do this when 'encoding' is not utf-8 and not a codepage. */
6007 if (!enc_utf8 && enc_codepage <= 0)
6008 return 0;
6009
6010 cp = encname2codepage(ptr);
6011 if (cp == 0)
6012 {
6013# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
6014 if (STRCMP(ptr, "utf-8") == 0)
6015 cp = CP_UTF8;
6016 else
6017# endif
6018 return 0;
6019 }
6020 return FIO_PUT_CP(cp) | FIO_CODEPAGE;
6021}
6022#endif
6023
Bram Moolenaard0573012017-10-28 21:11:06 +02006024#ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00006025/*
6026 * Check "ptr" for a Carbon supported encoding and return the FIO_ flags
6027 * needed for the internal conversion to/from utf-8 or latin1.
6028 */
6029 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006030get_mac_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006031{
6032 if ((enc_utf8 || STRCMP(p_enc, "latin1") == 0)
6033 && (enc_canon_props(ptr) & ENC_MACROMAN))
6034 return FIO_MACROMAN;
6035 return 0;
6036}
6037#endif
6038
6039/*
6040 * Check for a Unicode BOM (Byte Order Mark) at the start of p[size].
6041 * "size" must be at least 2.
6042 * Return the name of the encoding and set "*lenp" to the length.
6043 * Returns NULL when no BOM found.
6044 */
6045 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006046check_for_bom(
6047 char_u *p,
6048 long size,
6049 int *lenp,
6050 int flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006051{
6052 char *name = NULL;
6053 int len = 2;
6054
6055 if (p[0] == 0xef && p[1] == 0xbb && size >= 3 && p[2] == 0xbf
Bram Moolenaaree0f5a62008-07-24 20:09:16 +00006056 && (flags == FIO_ALL || flags == FIO_UTF8 || flags == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006057 {
6058 name = "utf-8"; /* EF BB BF */
6059 len = 3;
6060 }
6061 else if (p[0] == 0xff && p[1] == 0xfe)
6062 {
6063 if (size >= 4 && p[2] == 0 && p[3] == 0
6064 && (flags == FIO_ALL || flags == (FIO_UCS4 | FIO_ENDIAN_L)))
6065 {
6066 name = "ucs-4le"; /* FF FE 00 00 */
6067 len = 4;
6068 }
Bram Moolenaar223a1892008-11-11 20:57:11 +00006069 else if (flags == (FIO_UCS2 | FIO_ENDIAN_L))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006070 name = "ucs-2le"; /* FF FE */
Bram Moolenaar223a1892008-11-11 20:57:11 +00006071 else if (flags == FIO_ALL || flags == (FIO_UTF16 | FIO_ENDIAN_L))
6072 /* utf-16le is preferred, it also works for ucs-2le text */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006073 name = "utf-16le"; /* FF FE */
6074 }
6075 else if (p[0] == 0xfe && p[1] == 0xff
6076 && (flags == FIO_ALL || flags == FIO_UCS2 || flags == FIO_UTF16))
6077 {
Bram Moolenaarffd82c52008-02-20 17:15:26 +00006078 /* Default to utf-16, it works also for ucs-2 text. */
6079 if (flags == FIO_UCS2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006080 name = "ucs-2"; /* FE FF */
Bram Moolenaarffd82c52008-02-20 17:15:26 +00006081 else
6082 name = "utf-16"; /* FE FF */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006083 }
6084 else if (size >= 4 && p[0] == 0 && p[1] == 0 && p[2] == 0xfe
6085 && p[3] == 0xff && (flags == FIO_ALL || flags == FIO_UCS4))
6086 {
6087 name = "ucs-4"; /* 00 00 FE FF */
6088 len = 4;
6089 }
6090
6091 *lenp = len;
6092 return (char_u *)name;
6093}
6094
6095/*
6096 * Generate a BOM in "buf[4]" for encoding "name".
6097 * Return the length of the BOM (zero when no BOM).
6098 */
6099 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006100make_bom(char_u *buf, char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006101{
6102 int flags;
6103 char_u *p;
6104
6105 flags = get_fio_flags(name);
6106
6107 /* Can't put a BOM in a non-Unicode file. */
6108 if (flags == FIO_LATIN1 || flags == 0)
6109 return 0;
6110
6111 if (flags == FIO_UTF8) /* UTF-8 */
6112 {
6113 buf[0] = 0xef;
6114 buf[1] = 0xbb;
6115 buf[2] = 0xbf;
6116 return 3;
6117 }
6118 p = buf;
6119 (void)ucs2bytes(0xfeff, &p, flags);
6120 return (int)(p - buf);
6121}
6122#endif
6123
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00006124#if defined(FEAT_VIMINFO) || defined(FEAT_BROWSE) || \
Bram Moolenaara0174af2008-01-02 20:08:25 +00006125 defined(FEAT_QUICKFIX) || defined(FEAT_AUTOCMD) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006126/*
6127 * Try to find a shortname by comparing the fullname with the current
6128 * directory.
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006129 * Returns "full_path" or pointer into "full_path" if shortened.
6130 */
6131 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006132shorten_fname1(char_u *full_path)
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006133{
Bram Moolenaard9462e32011-04-11 21:35:11 +02006134 char_u *dirname;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006135 char_u *p = full_path;
6136
Bram Moolenaard9462e32011-04-11 21:35:11 +02006137 dirname = alloc(MAXPATHL);
6138 if (dirname == NULL)
6139 return full_path;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006140 if (mch_dirname(dirname, MAXPATHL) == OK)
6141 {
6142 p = shorten_fname(full_path, dirname);
6143 if (p == NULL || *p == NUL)
6144 p = full_path;
6145 }
Bram Moolenaard9462e32011-04-11 21:35:11 +02006146 vim_free(dirname);
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006147 return p;
6148}
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00006149#endif
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006150
6151/*
6152 * Try to find a shortname by comparing the fullname with the current
6153 * directory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006154 * Returns NULL if not shorter name possible, pointer into "full_path"
6155 * otherwise.
6156 */
6157 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006158shorten_fname(char_u *full_path, char_u *dir_name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006159{
6160 int len;
6161 char_u *p;
6162
6163 if (full_path == NULL)
6164 return NULL;
6165 len = (int)STRLEN(dir_name);
6166 if (fnamencmp(dir_name, full_path, len) == 0)
6167 {
6168 p = full_path + len;
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006169#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006170 /*
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006171 * MSWIN: when a file is in the root directory, dir_name will end in a
Bram Moolenaar071d4272004-06-13 20:20:40 +00006172 * slash, since C: by itself does not define a specific dir. In this
6173 * case p may already be correct. <negri>
6174 */
6175 if (!((len > 2) && (*(p - 2) == ':')))
6176#endif
6177 {
6178 if (vim_ispathsep(*p))
6179 ++p;
6180#ifndef VMS /* the path separator is always part of the path */
6181 else
6182 p = NULL;
6183#endif
6184 }
6185 }
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006186#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006187 /*
6188 * When using a file in the current drive, remove the drive name:
6189 * "A:\dir\file" -> "\dir\file". This helps when moving a session file on
6190 * a floppy from "A:\dir" to "B:\dir".
6191 */
6192 else if (len > 3
6193 && TOUPPER_LOC(full_path[0]) == TOUPPER_LOC(dir_name[0])
6194 && full_path[1] == ':'
6195 && vim_ispathsep(full_path[2]))
6196 p = full_path + 2;
6197#endif
6198 else
6199 p = NULL;
6200 return p;
6201}
6202
6203/*
6204 * Shorten filenames for all buffers.
6205 * When "force" is TRUE: Use full path from now on for files currently being
6206 * edited, both for file name and swap file name. Try to shorten the file
6207 * names a bit, if safe to do so.
6208 * When "force" is FALSE: Only try to shorten absolute file names.
6209 * For buffers that have buftype "nofile" or "scratch": never change the file
6210 * name.
6211 */
6212 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006213shorten_fnames(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006214{
6215 char_u dirname[MAXPATHL];
6216 buf_T *buf;
6217 char_u *p;
6218
6219 mch_dirname(dirname, MAXPATHL);
Bram Moolenaar29323592016-07-24 22:04:11 +02006220 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006221 {
6222 if (buf->b_fname != NULL
6223#ifdef FEAT_QUICKFIX
6224 && !bt_nofile(buf)
6225#endif
6226 && !path_with_url(buf->b_fname)
6227 && (force
6228 || buf->b_sfname == NULL
6229 || mch_isFullName(buf->b_sfname)))
6230 {
6231 vim_free(buf->b_sfname);
6232 buf->b_sfname = NULL;
6233 p = shorten_fname(buf->b_ffname, dirname);
6234 if (p != NULL)
6235 {
6236 buf->b_sfname = vim_strsave(p);
6237 buf->b_fname = buf->b_sfname;
6238 }
6239 if (p == NULL || buf->b_fname == NULL)
6240 buf->b_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006241 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00006242
6243 /* Always make the swap file name a full path, a "nofile" buffer may
6244 * also have a swap file. */
6245 mf_fullname(buf->b_ml.ml_mfp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006246 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006247 status_redraw_all();
Bram Moolenaar49d7bf12006-02-17 21:45:41 +00006248 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006249}
6250
6251#if (defined(FEAT_DND) && defined(FEAT_GUI_GTK)) \
6252 || defined(FEAT_GUI_MSWIN) \
6253 || defined(FEAT_GUI_MAC) \
6254 || defined(PROTO)
6255/*
6256 * Shorten all filenames in "fnames[count]" by current directory.
6257 */
6258 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006259shorten_filenames(char_u **fnames, int count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006260{
6261 int i;
6262 char_u dirname[MAXPATHL];
6263 char_u *p;
6264
6265 if (fnames == NULL || count < 1)
6266 return;
6267 mch_dirname(dirname, sizeof(dirname));
6268 for (i = 0; i < count; ++i)
6269 {
6270 if ((p = shorten_fname(fnames[i], dirname)) != NULL)
6271 {
6272 /* shorten_fname() returns pointer in given "fnames[i]". If free
6273 * "fnames[i]" first, "p" becomes invalid. So we need to copy
6274 * "p" first then free fnames[i]. */
6275 p = vim_strsave(p);
6276 vim_free(fnames[i]);
6277 fnames[i] = p;
6278 }
6279 }
6280}
6281#endif
6282
6283/*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006284 * add extension to file name - change path/fo.o.h to path/fo.o.h.ext or
Bram Moolenaar071d4272004-06-13 20:20:40 +00006285 * fo_o_h.ext for MSDOS or when shortname option set.
6286 *
6287 * Assumed that fname is a valid name found in the filesystem we assure that
6288 * the return value is a different name and ends in 'ext'.
6289 * "ext" MUST be at most 4 characters long if it starts with a dot, 3
6290 * characters otherwise.
6291 * Space for the returned name is allocated, must be freed later.
6292 * Returns NULL when out of memory.
6293 */
6294 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006295modname(
6296 char_u *fname,
6297 char_u *ext,
6298 int prepend_dot) /* may prepend a '.' to file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006299{
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006300 return buf_modname((curbuf->b_p_sn || curbuf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00006301 fname, ext, prepend_dot);
6302}
6303
6304 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006305buf_modname(
6306 int shortname, /* use 8.3 file name */
6307 char_u *fname,
6308 char_u *ext,
6309 int prepend_dot) /* may prepend a '.' to file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006310{
6311 char_u *retval;
6312 char_u *s;
6313 char_u *e;
6314 char_u *ptr;
6315 int fnamelen, extlen;
6316
6317 extlen = (int)STRLEN(ext);
6318
6319 /*
6320 * If there is no file name we must get the name of the current directory
6321 * (we need the full path in case :cd is used).
6322 */
6323 if (fname == NULL || *fname == NUL)
6324 {
6325 retval = alloc((unsigned)(MAXPATHL + extlen + 3));
6326 if (retval == NULL)
6327 return NULL;
6328 if (mch_dirname(retval, MAXPATHL) == FAIL ||
6329 (fnamelen = (int)STRLEN(retval)) == 0)
6330 {
6331 vim_free(retval);
6332 return NULL;
6333 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006334 if (!after_pathsep(retval, retval + fnamelen))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006335 {
6336 retval[fnamelen++] = PATHSEP;
6337 retval[fnamelen] = NUL;
6338 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006339 prepend_dot = FALSE; /* nothing to prepend a dot to */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006340 }
6341 else
6342 {
6343 fnamelen = (int)STRLEN(fname);
6344 retval = alloc((unsigned)(fnamelen + extlen + 3));
6345 if (retval == NULL)
6346 return NULL;
6347 STRCPY(retval, fname);
6348#ifdef VMS
6349 vms_remove_version(retval); /* we do not need versions here */
6350#endif
6351 }
6352
6353 /*
6354 * search backwards until we hit a '/', '\' or ':' replacing all '.'
6355 * by '_' for MSDOS or when shortname option set and ext starts with a dot.
6356 * Then truncate what is after the '/', '\' or ':' to 8 characters for
6357 * MSDOS and 26 characters for AMIGA, a lot more for UNIX.
6358 */
Bram Moolenaar91acfff2017-03-12 19:22:36 +01006359 for (ptr = retval + fnamelen; ptr > retval; MB_PTR_BACK(retval, ptr))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006360 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006361 if (*ext == '.'
Bram Moolenaare60acc12011-05-10 16:41:25 +02006362#ifdef USE_LONG_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00006363 && (!USE_LONG_FNAME || shortname)
Bram Moolenaare60acc12011-05-10 16:41:25 +02006364#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006365 && shortname
Bram Moolenaare60acc12011-05-10 16:41:25 +02006366#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006367 )
6368 if (*ptr == '.') /* replace '.' by '_' */
6369 *ptr = '_';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006370 if (vim_ispathsep(*ptr))
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006371 {
6372 ++ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006373 break;
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006374 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006375 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006376
6377 /* the file name has at most BASENAMELEN characters. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006378 if (STRLEN(ptr) > (unsigned)BASENAMELEN)
6379 ptr[BASENAMELEN] = '\0';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006380
6381 s = ptr + STRLEN(ptr);
6382
6383 /*
6384 * For 8.3 file names we may have to reduce the length.
6385 */
6386#ifdef USE_LONG_FNAME
6387 if (!USE_LONG_FNAME || shortname)
6388#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006389 if (shortname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006390#endif
6391 {
6392 /*
6393 * If there is no file name, or the file name ends in '/', and the
6394 * extension starts with '.', put a '_' before the dot, because just
6395 * ".ext" is invalid.
6396 */
6397 if (fname == NULL || *fname == NUL
6398 || vim_ispathsep(fname[STRLEN(fname) - 1]))
6399 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006400 if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006401 *s++ = '_';
6402 }
6403 /*
6404 * If the extension starts with '.', truncate the base name at 8
6405 * characters
6406 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006407 else if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006408 {
Bram Moolenaar78a15312009-05-15 19:33:18 +00006409 if ((size_t)(s - ptr) > (size_t)8)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006410 {
6411 s = ptr + 8;
6412 *s = '\0';
6413 }
6414 }
6415 /*
6416 * If the extension doesn't start with '.', and the file name
6417 * doesn't have an extension yet, append a '.'
6418 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006419 else if ((e = vim_strchr(ptr, '.')) == NULL)
6420 *s++ = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006421 /*
6422 * If the extension doesn't start with '.', and there already is an
Bram Moolenaar7263a772007-05-10 17:35:54 +00006423 * extension, it may need to be truncated
Bram Moolenaar071d4272004-06-13 20:20:40 +00006424 */
6425 else if ((int)STRLEN(e) + extlen > 4)
6426 s = e + 4 - extlen;
6427 }
Bram Moolenaare7fedb62015-12-31 19:07:19 +01006428#if defined(USE_LONG_FNAME) || defined(WIN3264)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006429 /*
6430 * If there is no file name, and the extension starts with '.', put a
6431 * '_' before the dot, because just ".ext" may be invalid if it's on a
6432 * FAT partition, and on HPFS it doesn't matter.
6433 */
6434 else if ((fname == NULL || *fname == NUL) && *ext == '.')
6435 *s++ = '_';
6436#endif
6437
6438 /*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006439 * Append the extension.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006440 * ext can start with '.' and cannot exceed 3 more characters.
6441 */
6442 STRCPY(s, ext);
6443
Bram Moolenaar071d4272004-06-13 20:20:40 +00006444 /*
6445 * Prepend the dot.
6446 */
Bram Moolenaare60acc12011-05-10 16:41:25 +02006447 if (prepend_dot && !shortname && *(e = gettail(retval)) != '.'
Bram Moolenaar071d4272004-06-13 20:20:40 +00006448#ifdef USE_LONG_FNAME
6449 && USE_LONG_FNAME
6450#endif
6451 )
6452 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006453 STRMOVE(e + 1, e);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006454 *e = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006455 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006456
6457 /*
6458 * Check that, after appending the extension, the file name is really
6459 * different.
6460 */
6461 if (fname != NULL && STRCMP(fname, retval) == 0)
6462 {
6463 /* we search for a character that can be replaced by '_' */
6464 while (--s >= ptr)
6465 {
6466 if (*s != '_')
6467 {
6468 *s = '_';
6469 break;
6470 }
6471 }
6472 if (s < ptr) /* fname was "________.<ext>", how tricky! */
6473 *ptr = 'v';
6474 }
6475 return retval;
6476}
6477
6478/*
6479 * Like fgets(), but if the file line is too long, it is truncated and the
6480 * rest of the line is thrown away. Returns TRUE for end-of-file.
Bram Moolenaar7e1652c2017-12-16 18:27:02 +01006481 * If the line is truncated then buf[size - 2] will not be NUL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006482 */
6483 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006484vim_fgets(char_u *buf, int size, FILE *fp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006485{
6486 char *eof;
6487#define FGETS_SIZE 200
6488 char tbuf[FGETS_SIZE];
6489
6490 buf[size - 2] = NUL;
6491#ifdef USE_CR
6492 eof = fgets_cr((char *)buf, size, fp);
6493#else
6494 eof = fgets((char *)buf, size, fp);
6495#endif
6496 if (buf[size - 2] != NUL && buf[size - 2] != '\n')
6497 {
6498 buf[size - 1] = NUL; /* Truncate the line */
6499
6500 /* Now throw away the rest of the line: */
6501 do
6502 {
6503 tbuf[FGETS_SIZE - 2] = NUL;
6504#ifdef USE_CR
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006505 ignoredp = fgets_cr((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006506#else
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006507 ignoredp = fgets((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006508#endif
6509 } while (tbuf[FGETS_SIZE - 2] != NUL && tbuf[FGETS_SIZE - 2] != '\n');
6510 }
6511 return (eof == NULL);
6512}
6513
6514#if defined(USE_CR) || defined(PROTO)
6515/*
6516 * Like vim_fgets(), but accept any line terminator: CR, CR-LF or LF.
6517 * Returns TRUE for end-of-file.
6518 * Only used for the Mac, because it's much slower than vim_fgets().
6519 */
6520 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006521tag_fgets(char_u *buf, int size, FILE *fp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006522{
6523 int i = 0;
6524 int c;
6525 int eof = FALSE;
6526
6527 for (;;)
6528 {
6529 c = fgetc(fp);
6530 if (c == EOF)
6531 {
6532 eof = TRUE;
6533 break;
6534 }
6535 if (c == '\r')
6536 {
6537 /* Always store a NL for end-of-line. */
6538 if (i < size - 1)
6539 buf[i++] = '\n';
6540 c = fgetc(fp);
6541 if (c != '\n') /* Macintosh format: single CR. */
6542 ungetc(c, fp);
6543 break;
6544 }
6545 if (i < size - 1)
6546 buf[i++] = c;
6547 if (c == '\n')
6548 break;
6549 }
6550 buf[i] = NUL;
6551 return eof;
6552}
6553#endif
6554
6555/*
6556 * rename() only works if both files are on the same file system, this
6557 * function will (attempts to?) copy the file across if rename fails -- webb
6558 * Return -1 for failure, 0 for success.
6559 */
6560 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006561vim_rename(char_u *from, char_u *to)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006562{
6563 int fd_in;
6564 int fd_out;
6565 int n;
6566 char *errmsg = NULL;
6567 char *buffer;
6568#ifdef AMIGA
6569 BPTR flock;
6570#endif
Bram Moolenaar8767f522016-07-01 17:17:39 +02006571 stat_T st;
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006572 long perm;
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006573#ifdef HAVE_ACL
6574 vim_acl_T acl; /* ACL from original file */
6575#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006576 int use_tmp_file = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006577
6578 /*
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006579 * When the names are identical, there is nothing to do. When they refer
6580 * to the same file (ignoring case and slash/backslash differences) but
6581 * the file name differs we need to go through a temp file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006582 */
6583 if (fnamecmp(from, to) == 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006584 {
Bram Moolenaar71afbfe2013-03-19 16:49:16 +01006585 if (p_fic && STRCMP(gettail(from), gettail(to)) != 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006586 use_tmp_file = TRUE;
6587 else
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006588 return 0;
6589 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006590
6591 /*
6592 * Fail if the "from" file doesn't exist. Avoids that "to" is deleted.
6593 */
6594 if (mch_stat((char *)from, &st) < 0)
6595 return -1;
6596
Bram Moolenaar3576da72008-12-30 15:15:57 +00006597#ifdef UNIX
6598 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02006599 stat_T st_to;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006600
6601 /* It's possible for the source and destination to be the same file.
6602 * This happens when "from" and "to" differ in case and are on a FAT32
6603 * filesystem. In that case go through a temp file name. */
6604 if (mch_stat((char *)to, &st_to) >= 0
6605 && st.st_dev == st_to.st_dev
6606 && st.st_ino == st_to.st_ino)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006607 use_tmp_file = TRUE;
6608 }
6609#endif
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02006610#ifdef WIN3264
6611 {
6612 BY_HANDLE_FILE_INFORMATION info1, info2;
6613
6614 /* It's possible for the source and destination to be the same file.
6615 * In that case go through a temp file name. This makes rename("foo",
6616 * "./foo") a no-op (in a complicated way). */
6617 if (win32_fileinfo(from, &info1) == FILEINFO_OK
6618 && win32_fileinfo(to, &info2) == FILEINFO_OK
6619 && info1.dwVolumeSerialNumber == info2.dwVolumeSerialNumber
6620 && info1.nFileIndexHigh == info2.nFileIndexHigh
6621 && info1.nFileIndexLow == info2.nFileIndexLow)
6622 use_tmp_file = TRUE;
6623 }
6624#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006625
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006626 if (use_tmp_file)
6627 {
6628 char tempname[MAXPATHL + 1];
6629
6630 /*
6631 * Find a name that doesn't exist and is in the same directory.
6632 * Rename "from" to "tempname" and then rename "tempname" to "to".
6633 */
6634 if (STRLEN(from) >= MAXPATHL - 5)
6635 return -1;
6636 STRCPY(tempname, from);
6637 for (n = 123; n < 99999; ++n)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006638 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006639 sprintf((char *)gettail((char_u *)tempname), "%d", n);
6640 if (mch_stat(tempname, &st) < 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006641 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006642 if (mch_rename((char *)from, tempname) == 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006643 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006644 if (mch_rename(tempname, (char *)to) == 0)
6645 return 0;
6646 /* Strange, the second step failed. Try moving the
6647 * file back and return failure. */
6648 mch_rename(tempname, (char *)from);
Bram Moolenaar3576da72008-12-30 15:15:57 +00006649 return -1;
6650 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006651 /* If it fails for one temp name it will most likely fail
6652 * for any temp name, give up. */
6653 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006654 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006655 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006656 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006657 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006658
Bram Moolenaar071d4272004-06-13 20:20:40 +00006659 /*
6660 * Delete the "to" file, this is required on some systems to make the
6661 * mch_rename() work, on other systems it makes sure that we don't have
6662 * two files when the mch_rename() fails.
6663 */
6664
6665#ifdef AMIGA
6666 /*
6667 * With MSDOS-compatible filesystems (crossdos, messydos) it is possible
6668 * that the name of the "to" file is the same as the "from" file, even
Bram Moolenaar7263a772007-05-10 17:35:54 +00006669 * though the names are different. To avoid the chance of accidentally
Bram Moolenaar071d4272004-06-13 20:20:40 +00006670 * deleting the "from" file (horror!) we lock it during the remove.
6671 *
6672 * When used for making a backup before writing the file: This should not
6673 * happen with ":w", because startscript() should detect this problem and
6674 * set buf->b_shortname, causing modname() to return a correct ".bak" file
6675 * name. This problem does exist with ":w filename", but then the
6676 * original file will be somewhere else so the backup isn't really
6677 * important. If autoscripting is off the rename may fail.
6678 */
6679 flock = Lock((UBYTE *)from, (long)ACCESS_READ);
6680#endif
6681 mch_remove(to);
6682#ifdef AMIGA
6683 if (flock)
6684 UnLock(flock);
6685#endif
6686
6687 /*
6688 * First try a normal rename, return if it works.
6689 */
6690 if (mch_rename((char *)from, (char *)to) == 0)
6691 return 0;
6692
6693 /*
6694 * Rename() failed, try copying the file.
6695 */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006696 perm = mch_getperm(from);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006697#ifdef HAVE_ACL
6698 /* For systems that support ACL: get the ACL from the original file. */
6699 acl = mch_get_acl(from);
6700#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006701 fd_in = mch_open((char *)from, O_RDONLY|O_EXTRA, 0);
6702 if (fd_in == -1)
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006703 {
6704#ifdef HAVE_ACL
6705 mch_free_acl(acl);
6706#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006707 return -1;
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006708 }
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006709
6710 /* Create the new file with same permissions as the original. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00006711 fd_out = mch_open((char *)to,
6712 O_CREAT|O_EXCL|O_WRONLY|O_EXTRA|O_NOFOLLOW, (int)perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006713 if (fd_out == -1)
6714 {
6715 close(fd_in);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006716#ifdef HAVE_ACL
6717 mch_free_acl(acl);
6718#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006719 return -1;
6720 }
6721
6722 buffer = (char *)alloc(BUFSIZE);
6723 if (buffer == NULL)
6724 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006725 close(fd_out);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006726 close(fd_in);
6727#ifdef HAVE_ACL
6728 mch_free_acl(acl);
6729#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006730 return -1;
6731 }
6732
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01006733 while ((n = read_eintr(fd_in, buffer, BUFSIZE)) > 0)
6734 if (write_eintr(fd_out, buffer, n) != n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006735 {
6736 errmsg = _("E208: Error writing to \"%s\"");
6737 break;
6738 }
6739
6740 vim_free(buffer);
6741 close(fd_in);
6742 if (close(fd_out) < 0)
6743 errmsg = _("E209: Error closing \"%s\"");
6744 if (n < 0)
6745 {
6746 errmsg = _("E210: Error reading \"%s\"");
6747 to = from;
6748 }
Bram Moolenaar7263a772007-05-10 17:35:54 +00006749#ifndef UNIX /* for Unix mch_open() already set the permission */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006750 mch_setperm(to, perm);
Bram Moolenaarc6039d82005-12-02 00:44:04 +00006751#endif
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006752#ifdef HAVE_ACL
6753 mch_set_acl(to, acl);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006754 mch_free_acl(acl);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006755#endif
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02006756#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaare8747442013-11-12 18:09:29 +01006757 mch_copy_sec(from, to);
Bram Moolenaar0671de32013-11-12 05:12:03 +01006758#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006759 if (errmsg != NULL)
6760 {
6761 EMSG2(errmsg, to);
6762 return -1;
6763 }
6764 mch_remove(from);
6765 return 0;
6766}
6767
6768static int already_warned = FALSE;
6769
6770/*
6771 * Check if any not hidden buffer has been changed.
6772 * Postpone the check if there are characters in the stuff buffer, a global
6773 * command is being executed, a mapping is being executed or an autocommand is
6774 * busy.
6775 * Returns TRUE if some message was written (screen should be redrawn and
6776 * cursor positioned).
6777 */
6778 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006779check_timestamps(
6780 int focus) /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006781{
6782 buf_T *buf;
6783 int didit = 0;
6784 int n;
6785
6786 /* Don't check timestamps while system() or another low-level function may
6787 * cause us to lose and gain focus. */
6788 if (no_check_timestamps > 0)
6789 return FALSE;
6790
6791 /* Avoid doing a check twice. The OK/Reload dialog can cause a focus
6792 * event and we would keep on checking if the file is steadily growing.
6793 * Do check again after typing something. */
6794 if (focus && did_check_timestamps)
6795 {
6796 need_check_timestamps = TRUE;
6797 return FALSE;
6798 }
6799
6800 if (!stuff_empty() || global_busy || !typebuf_typed()
6801#ifdef FEAT_AUTOCMD
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006802 || autocmd_busy || curbuf_lock > 0 || allbuf_lock > 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00006803#endif
6804 )
6805 need_check_timestamps = TRUE; /* check later */
6806 else
6807 {
6808 ++no_wait_return;
6809 did_check_timestamps = TRUE;
6810 already_warned = FALSE;
Bram Moolenaar29323592016-07-24 22:04:11 +02006811 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006812 {
6813 /* Only check buffers in a window. */
6814 if (buf->b_nwindows > 0)
6815 {
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006816 bufref_T bufref;
6817
6818 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006819 n = buf_check_timestamp(buf, focus);
6820 if (didit < n)
6821 didit = n;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006822 if (n > 0 && !bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006823 {
6824 /* Autocommands have removed the buffer, start at the
6825 * first one again. */
6826 buf = firstbuf;
6827 continue;
6828 }
6829 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006830 }
6831 --no_wait_return;
6832 need_check_timestamps = FALSE;
6833 if (need_wait_return && didit == 2)
6834 {
6835 /* make sure msg isn't overwritten */
6836 msg_puts((char_u *)"\n");
6837 out_flush();
6838 }
6839 }
6840 return didit;
6841}
6842
6843/*
6844 * Move all the lines from buffer "frombuf" to buffer "tobuf".
6845 * Return OK or FAIL. When FAIL "tobuf" is incomplete and/or "frombuf" is not
6846 * empty.
6847 */
6848 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006849move_lines(buf_T *frombuf, buf_T *tobuf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006850{
6851 buf_T *tbuf = curbuf;
6852 int retval = OK;
6853 linenr_T lnum;
6854 char_u *p;
6855
6856 /* Copy the lines in "frombuf" to "tobuf". */
6857 curbuf = tobuf;
6858 for (lnum = 1; lnum <= frombuf->b_ml.ml_line_count; ++lnum)
6859 {
6860 p = vim_strsave(ml_get_buf(frombuf, lnum, FALSE));
6861 if (p == NULL || ml_append(lnum - 1, p, 0, FALSE) == FAIL)
6862 {
6863 vim_free(p);
6864 retval = FAIL;
6865 break;
6866 }
6867 vim_free(p);
6868 }
6869
6870 /* Delete all the lines in "frombuf". */
6871 if (retval != FAIL)
6872 {
6873 curbuf = frombuf;
Bram Moolenaar9460b9d2007-01-09 14:37:01 +00006874 for (lnum = curbuf->b_ml.ml_line_count; lnum > 0; --lnum)
6875 if (ml_delete(lnum, FALSE) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006876 {
6877 /* Oops! We could try putting back the saved lines, but that
6878 * might fail again... */
6879 retval = FAIL;
6880 break;
6881 }
6882 }
6883
6884 curbuf = tbuf;
6885 return retval;
6886}
6887
6888/*
6889 * Check if buffer "buf" has been changed.
6890 * Also check if the file for a new buffer unexpectedly appeared.
6891 * return 1 if a changed buffer was found.
6892 * return 2 if a message has been displayed.
6893 * return 0 otherwise.
6894 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006895 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006896buf_check_timestamp(
6897 buf_T *buf,
6898 int focus UNUSED) /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006899{
Bram Moolenaar8767f522016-07-01 17:17:39 +02006900 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006901 int stat_res;
6902 int retval = 0;
6903 char_u *path;
6904 char_u *tbuf;
6905 char *mesg = NULL;
Bram Moolenaar44ecf652005-03-07 23:09:59 +00006906 char *mesg2 = "";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006907 int helpmesg = FALSE;
6908 int reload = FALSE;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006909 char *reason;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006910#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6911 int can_reload = FALSE;
6912#endif
Bram Moolenaar8767f522016-07-01 17:17:39 +02006913 off_T orig_size = buf->b_orig_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006914 int orig_mode = buf->b_orig_mode;
6915#ifdef FEAT_GUI
6916 int save_mouse_correct = need_mouse_correct;
6917#endif
6918#ifdef FEAT_AUTOCMD
6919 static int busy = FALSE;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006920 int n;
6921 char_u *s;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006922 bufref_T bufref;
6923
6924 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006925#endif
6926
6927 /* If there is no file name, the buffer is not loaded, 'buftype' is
6928 * set, we are in the middle of a save or being called recursively: ignore
6929 * this buffer. */
6930 if (buf->b_ffname == NULL
6931 || buf->b_ml.ml_mfp == NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00006932 || *buf->b_p_bt != NUL
Bram Moolenaar071d4272004-06-13 20:20:40 +00006933 || buf->b_saving
6934#ifdef FEAT_AUTOCMD
6935 || busy
6936#endif
Bram Moolenaar009b2592004-10-24 19:18:58 +00006937#ifdef FEAT_NETBEANS_INTG
6938 || isNetbeansBuffer(buf)
6939#endif
Bram Moolenaar8cad9302017-08-12 14:32:32 +02006940#ifdef FEAT_TERMINAL
6941 || buf->b_term != NULL
6942#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006943 )
6944 return 0;
6945
6946 if ( !(buf->b_flags & BF_NOTEDITED)
6947 && buf->b_mtime != 0
6948 && ((stat_res = mch_stat((char *)buf->b_ffname, &st)) < 0
6949 || time_differs((long)st.st_mtime, buf->b_mtime)
Bram Moolenaara7611f62014-05-02 15:46:14 +02006950 || st.st_size != buf->b_orig_size
Bram Moolenaar071d4272004-06-13 20:20:40 +00006951#ifdef HAVE_ST_MODE
6952 || (int)st.st_mode != buf->b_orig_mode
6953#else
6954 || mch_getperm(buf->b_ffname) != buf->b_orig_mode
6955#endif
6956 ))
6957 {
6958 retval = 1;
6959
Bram Moolenaar316059c2006-01-14 21:18:42 +00006960 /* set b_mtime to stop further warnings (e.g., when executing
6961 * FileChangedShell autocmd) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006962 if (stat_res < 0)
6963 {
6964 buf->b_mtime = 0;
6965 buf->b_orig_size = 0;
6966 buf->b_orig_mode = 0;
6967 }
6968 else
6969 buf_store_time(buf, &st, buf->b_ffname);
6970
6971 /* Don't do anything for a directory. Might contain the file
6972 * explorer. */
6973 if (mch_isdir(buf->b_fname))
6974 ;
6975
6976 /*
6977 * If 'autoread' is set, the buffer has no changes and the file still
6978 * exists, reload the buffer. Use the buffer-local option value if it
6979 * was set, the global option value otherwise.
6980 */
6981 else if ((buf->b_p_ar >= 0 ? buf->b_p_ar : p_ar)
6982 && !bufIsChanged(buf) && stat_res >= 0)
6983 reload = TRUE;
6984 else
6985 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006986 if (stat_res < 0)
6987 reason = "deleted";
6988 else if (bufIsChanged(buf))
6989 reason = "conflict";
6990 else if (orig_size != buf->b_orig_size || buf_contents_changed(buf))
6991 reason = "changed";
6992 else if (orig_mode != buf->b_orig_mode)
6993 reason = "mode";
6994 else
6995 reason = "time";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006996
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006997#ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006998 /*
6999 * Only give the warning if there are no FileChangedShell
7000 * autocommands.
7001 * Avoid being called recursively by setting "busy".
7002 */
7003 busy = TRUE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00007004# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007005 set_vim_var_string(VV_FCS_REASON, (char_u *)reason, -1);
7006 set_vim_var_string(VV_FCS_CHOICE, (char_u *)"", -1);
Bram Moolenaar1e015462005-09-25 22:16:38 +00007007# endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00007008 ++allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007009 n = apply_autocmds(EVENT_FILECHANGEDSHELL,
7010 buf->b_fname, buf->b_fname, FALSE, buf);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00007011 --allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007012 busy = FALSE;
7013 if (n)
7014 {
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007015 if (!bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007016 EMSG(_("E246: FileChangedShell autocommand deleted buffer"));
Bram Moolenaar1e015462005-09-25 22:16:38 +00007017# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007018 s = get_vim_var_str(VV_FCS_CHOICE);
7019 if (STRCMP(s, "reload") == 0 && *reason != 'd')
7020 reload = TRUE;
7021 else if (STRCMP(s, "ask") == 0)
7022 n = FALSE;
7023 else
Bram Moolenaar1e015462005-09-25 22:16:38 +00007024# endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007025 return 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007026 }
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007027 if (!n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007028#endif
7029 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007030 if (*reason == 'd')
7031 mesg = _("E211: File \"%s\" no longer available");
Bram Moolenaar071d4272004-06-13 20:20:40 +00007032 else
7033 {
7034 helpmesg = TRUE;
7035#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
7036 can_reload = TRUE;
7037#endif
7038 /*
7039 * Check if the file contents really changed to avoid
7040 * giving a warning when only the timestamp was set (e.g.,
7041 * checked out of CVS). Always warn when the buffer was
7042 * changed.
7043 */
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007044 if (reason[2] == 'n')
7045 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007046 mesg = _("W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007047 mesg2 = _("See \":help W12\" for more info.");
7048 }
7049 else if (reason[1] == 'h')
7050 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007051 mesg = _("W11: Warning: File \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007052 mesg2 = _("See \":help W11\" for more info.");
7053 }
7054 else if (*reason == 'm')
7055 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007056 mesg = _("W16: Warning: Mode of file \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007057 mesg2 = _("See \":help W16\" for more info.");
7058 }
Bram Moolenaar85388b52009-06-24 09:58:32 +00007059 else
7060 /* Only timestamp changed, store it to avoid a warning
7061 * in check_mtime() later. */
7062 buf->b_mtime_read = buf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007063 }
7064 }
7065 }
7066
7067 }
7068 else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W)
7069 && vim_fexists(buf->b_ffname))
7070 {
7071 retval = 1;
7072 mesg = _("W13: Warning: File \"%s\" has been created after editing started");
7073 buf->b_flags |= BF_NEW_W;
7074#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
7075 can_reload = TRUE;
7076#endif
7077 }
7078
7079 if (mesg != NULL)
7080 {
7081 path = home_replace_save(buf, buf->b_fname);
7082 if (path != NULL)
7083 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007084 if (!helpmesg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007085 mesg2 = "";
7086 tbuf = alloc((unsigned)(STRLEN(path) + STRLEN(mesg)
7087 + STRLEN(mesg2) + 2));
7088 sprintf((char *)tbuf, mesg, path);
Bram Moolenaar496c5262009-03-18 14:42:00 +00007089#ifdef FEAT_EVAL
7090 /* Set warningmsg here, before the unimportant and output-specific
7091 * mesg2 has been appended. */
7092 set_vim_var_string(VV_WARNINGMSG, tbuf, -1);
7093#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007094#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
7095 if (can_reload)
7096 {
7097 if (*mesg2 != NUL)
7098 {
7099 STRCAT(tbuf, "\n");
7100 STRCAT(tbuf, mesg2);
7101 }
7102 if (do_dialog(VIM_WARNING, (char_u *)_("Warning"), tbuf,
Bram Moolenaard2c340a2011-01-17 20:08:11 +01007103 (char_u *)_("&OK\n&Load File"), 1, NULL, TRUE) == 2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007104 reload = TRUE;
7105 }
7106 else
7107#endif
7108 if (State > NORMAL_BUSY || (State & CMDLINE) || already_warned)
7109 {
7110 if (*mesg2 != NUL)
7111 {
7112 STRCAT(tbuf, "; ");
7113 STRCAT(tbuf, mesg2);
7114 }
7115 EMSG(tbuf);
7116 retval = 2;
7117 }
7118 else
7119 {
Bram Moolenaared203462004-06-16 11:19:22 +00007120# ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00007121 if (!autocmd_busy)
Bram Moolenaared203462004-06-16 11:19:22 +00007122# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007123 {
7124 msg_start();
Bram Moolenaar8820b482017-03-16 17:23:31 +01007125 msg_puts_attr(tbuf, HL_ATTR(HLF_E) + MSG_HIST);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007126 if (*mesg2 != NUL)
7127 msg_puts_attr((char_u *)mesg2,
Bram Moolenaar8820b482017-03-16 17:23:31 +01007128 HL_ATTR(HLF_W) + MSG_HIST);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007129 msg_clr_eos();
7130 (void)msg_end();
7131 if (emsg_silent == 0)
7132 {
7133 out_flush();
Bram Moolenaared203462004-06-16 11:19:22 +00007134# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00007135 if (!focus)
Bram Moolenaared203462004-06-16 11:19:22 +00007136# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007137 /* give the user some time to think about it */
7138 ui_delay(1000L, TRUE);
7139
7140 /* don't redraw and erase the message */
7141 redraw_cmdline = FALSE;
7142 }
7143 }
7144 already_warned = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007145 }
7146
7147 vim_free(path);
7148 vim_free(tbuf);
7149 }
7150 }
7151
7152 if (reload)
Bram Moolenaar465748e2012-08-29 18:50:54 +02007153 {
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007154 /* Reload the buffer. */
Bram Moolenaar316059c2006-01-14 21:18:42 +00007155 buf_reload(buf, orig_mode);
Bram Moolenaar465748e2012-08-29 18:50:54 +02007156#ifdef FEAT_PERSISTENT_UNDO
7157 if (buf->b_p_udf && buf->b_ffname != NULL)
7158 {
7159 char_u hash[UNDO_HASH_SIZE];
7160 buf_T *save_curbuf = curbuf;
7161
7162 /* Any existing undo file is unusable, write it now. */
7163 curbuf = buf;
7164 u_compute_hash(hash);
7165 u_write_undo(NULL, FALSE, buf, hash);
7166 curbuf = save_curbuf;
7167 }
7168#endif
7169 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007170
Bram Moolenaar56718732006-03-15 22:53:57 +00007171#ifdef FEAT_AUTOCMD
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00007172 /* Trigger FileChangedShell when the file was changed in any way. */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007173 if (bufref_valid(&bufref) && retval != 0)
Bram Moolenaar56718732006-03-15 22:53:57 +00007174 (void)apply_autocmds(EVENT_FILECHANGEDSHELLPOST,
7175 buf->b_fname, buf->b_fname, FALSE, buf);
7176#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007177#ifdef FEAT_GUI
7178 /* restore this in case an autocommand has set it; it would break
7179 * 'mousefocus' */
7180 need_mouse_correct = save_mouse_correct;
7181#endif
7182
7183 return retval;
7184}
7185
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007186/*
7187 * Reload a buffer that is already loaded.
7188 * Used when the file was changed outside of Vim.
Bram Moolenaar316059c2006-01-14 21:18:42 +00007189 * "orig_mode" is buf->b_orig_mode before the need for reloading was detected.
7190 * buf->b_orig_mode may have been reset already.
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007191 */
7192 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007193buf_reload(buf_T *buf, int orig_mode)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007194{
7195 exarg_T ea;
7196 pos_T old_cursor;
7197 linenr_T old_topline;
7198 int old_ro = buf->b_p_ro;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007199 buf_T *savebuf;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007200 bufref_T bufref;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007201 int saved = OK;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007202 aco_save_T aco;
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007203 int flags = READ_NEW;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007204
7205 /* set curwin/curbuf for "buf" and save some things */
7206 aucmd_prepbuf(&aco, buf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007207
7208 /* We only want to read the text from the file, not reset the syntax
7209 * highlighting, clear marks, diff status, etc. Force the fileformat
7210 * and encoding to be the same. */
7211 if (prep_exarg(&ea, buf) == OK)
7212 {
7213 old_cursor = curwin->w_cursor;
7214 old_topline = curwin->w_topline;
7215
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007216 if (p_ur < 0 || curbuf->b_ml.ml_line_count <= p_ur)
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007217 {
7218 /* Save all the text, so that the reload can be undone.
7219 * Sync first so that this is a separate undo-able action. */
7220 u_sync(FALSE);
7221 saved = u_savecommon(0, curbuf->b_ml.ml_line_count + 1, 0, TRUE);
7222 flags |= READ_KEEP_UNDO;
7223 }
7224
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007225 /*
7226 * To behave like when a new file is edited (matters for
7227 * BufReadPost autocommands) we first need to delete the current
7228 * buffer contents. But if reading the file fails we should keep
7229 * the old contents. Can't use memory only, the file might be
7230 * too big. Use a hidden buffer to move the buffer contents to.
7231 */
Bram Moolenaarb5aedf32017-03-12 18:23:53 +01007232 if (BUFEMPTY() || saved == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007233 savebuf = NULL;
7234 else
7235 {
7236 /* Allocate a buffer without putting it in the buffer list. */
7237 savebuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007238 set_bufref(&bufref, savebuf);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007239 if (savebuf != NULL && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007240 {
7241 /* Open the memline. */
7242 curbuf = savebuf;
7243 curwin->w_buffer = savebuf;
Bram Moolenaar4770d092006-01-12 23:22:24 +00007244 saved = ml_open(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007245 curbuf = buf;
7246 curwin->w_buffer = buf;
7247 }
Bram Moolenaar8424a622006-04-19 21:23:36 +00007248 if (savebuf == NULL || saved == FAIL || buf != curbuf
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007249 || move_lines(buf, savebuf) == FAIL)
7250 {
7251 EMSG2(_("E462: Could not prepare for reloading \"%s\""),
7252 buf->b_fname);
7253 saved = FAIL;
7254 }
7255 }
7256
7257 if (saved == OK)
7258 {
7259 curbuf->b_flags |= BF_CHECK_RO; /* check for RO again */
7260#ifdef FEAT_AUTOCMD
7261 keep_filetype = TRUE; /* don't detect 'filetype' */
7262#endif
7263 if (readfile(buf->b_ffname, buf->b_fname, (linenr_T)0,
7264 (linenr_T)0,
Bram Moolenaare13b9af2017-01-13 22:01:02 +01007265 (linenr_T)MAXLNUM, &ea, flags) != OK)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007266 {
7267#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
7268 if (!aborting())
7269#endif
7270 EMSG2(_("E321: Could not reload \"%s\""), buf->b_fname);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007271 if (savebuf != NULL && bufref_valid(&bufref) && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007272 {
7273 /* Put the text back from the save buffer. First
7274 * delete any lines that readfile() added. */
Bram Moolenaarb5aedf32017-03-12 18:23:53 +01007275 while (!BUFEMPTY())
Bram Moolenaar8424a622006-04-19 21:23:36 +00007276 if (ml_delete(buf->b_ml.ml_line_count, FALSE) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007277 break;
7278 (void)move_lines(savebuf, buf);
7279 }
7280 }
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007281 else if (buf == curbuf) /* "buf" still valid */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007282 {
7283 /* Mark the buffer as unmodified and free undo info. */
7284 unchanged(buf, TRUE);
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007285 if ((flags & READ_KEEP_UNDO) == 0)
7286 {
7287 u_blockfree(buf);
7288 u_clearall(buf);
7289 }
7290 else
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007291 {
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007292 /* Mark all undo states as changed. */
7293 u_unchanged(curbuf);
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007294 }
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007295 }
7296 }
7297 vim_free(ea.cmd);
7298
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007299 if (savebuf != NULL && bufref_valid(&bufref))
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007300 wipe_buffer(savebuf, FALSE);
7301
7302#ifdef FEAT_DIFF
7303 /* Invalidate diff info if necessary. */
Bram Moolenaar8424a622006-04-19 21:23:36 +00007304 diff_invalidate(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007305#endif
7306
7307 /* Restore the topline and cursor position and check it (lines may
7308 * have been removed). */
7309 if (old_topline > curbuf->b_ml.ml_line_count)
7310 curwin->w_topline = curbuf->b_ml.ml_line_count;
7311 else
7312 curwin->w_topline = old_topline;
7313 curwin->w_cursor = old_cursor;
7314 check_cursor();
7315 update_topline();
7316#ifdef FEAT_AUTOCMD
7317 keep_filetype = FALSE;
7318#endif
7319#ifdef FEAT_FOLDING
7320 {
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007321 win_T *wp;
7322 tabpage_T *tp;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007323
7324 /* Update folds unless they are defined manually. */
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007325 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007326 if (wp->w_buffer == curwin->w_buffer
7327 && !foldmethodIsManual(wp))
7328 foldUpdateAll(wp);
7329 }
7330#endif
7331 /* If the mode didn't change and 'readonly' was set, keep the old
7332 * value; the user probably used the ":view" command. But don't
7333 * reset it, might have had a read error. */
7334 if (orig_mode == curbuf->b_orig_mode)
7335 curbuf->b_p_ro |= old_ro;
Bram Moolenaar52f85b72013-01-30 14:13:56 +01007336
7337 /* Modelines must override settings done by autocommands. */
7338 do_modelines(0);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007339 }
7340
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007341 /* restore curwin/curbuf and a few other things */
7342 aucmd_restbuf(&aco);
7343 /* Careful: autocommands may have made "buf" invalid! */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007344}
7345
Bram Moolenaar071d4272004-06-13 20:20:40 +00007346 void
Bram Moolenaar8767f522016-07-01 17:17:39 +02007347buf_store_time(buf_T *buf, stat_T *st, char_u *fname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007348{
7349 buf->b_mtime = (long)st->st_mtime;
Bram Moolenaar914703b2010-05-31 21:59:46 +02007350 buf->b_orig_size = st->st_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007351#ifdef HAVE_ST_MODE
7352 buf->b_orig_mode = (int)st->st_mode;
7353#else
7354 buf->b_orig_mode = mch_getperm(fname);
7355#endif
7356}
7357
7358/*
7359 * Adjust the line with missing eol, used for the next write.
7360 * Used for do_filter(), when the input lines for the filter are deleted.
7361 */
7362 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007363write_lnum_adjust(linenr_T offset)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007364{
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01007365 if (curbuf->b_no_eol_lnum != 0) /* only if there is a missing eol */
7366 curbuf->b_no_eol_lnum += offset;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007367}
7368
Bram Moolenaarda440d22016-01-16 21:27:23 +01007369#if defined(TEMPDIRNAMES) || defined(FEAT_EVAL) || defined(PROTO)
7370/*
7371 * Delete "name" and everything in it, recursively.
7372 * return 0 for succes, -1 if some file was not deleted.
7373 */
7374 int
7375delete_recursive(char_u *name)
7376{
7377 int result = 0;
7378 char_u **files;
7379 int file_count;
7380 int i;
7381 char_u *exp;
7382
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007383 /* A symbolic link to a directory itself is deleted, not the directory it
7384 * points to. */
7385 if (
Bram Moolenaar203258c2016-01-17 22:15:16 +01007386# if defined(UNIX) || defined(WIN32)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007387 mch_isrealdir(name)
Bram Moolenaar203258c2016-01-17 22:15:16 +01007388# else
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007389 mch_isdir(name)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007390# endif
7391 )
Bram Moolenaarda440d22016-01-16 21:27:23 +01007392 {
7393 vim_snprintf((char *)NameBuff, MAXPATHL, "%s/*", name);
7394 exp = vim_strsave(NameBuff);
7395 if (exp == NULL)
7396 return -1;
7397 if (gen_expand_wildcards(1, &exp, &file_count, &files,
Bram Moolenaar336bd622016-01-17 18:23:58 +01007398 EW_DIR|EW_FILE|EW_SILENT|EW_ALLLINKS|EW_DODOT|EW_EMPTYOK) == OK)
Bram Moolenaarda440d22016-01-16 21:27:23 +01007399 {
7400 for (i = 0; i < file_count; ++i)
7401 if (delete_recursive(files[i]) != 0)
7402 result = -1;
7403 FreeWild(file_count, files);
7404 }
7405 else
7406 result = -1;
7407 vim_free(exp);
7408 (void)mch_rmdir(name);
7409 }
7410 else
7411 result = mch_remove(name) == 0 ? 0 : -1;
7412
7413 return result;
7414}
7415#endif
7416
Bram Moolenaar071d4272004-06-13 20:20:40 +00007417#if defined(TEMPDIRNAMES) || defined(PROTO)
7418static long temp_count = 0; /* Temp filename counter. */
7419
7420/*
7421 * Delete the temp directory and all files it contains.
7422 */
7423 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007424vim_deltempdir(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007425{
Bram Moolenaar071d4272004-06-13 20:20:40 +00007426 if (vim_tempdir != NULL)
7427 {
Bram Moolenaarda440d22016-01-16 21:27:23 +01007428 /* remove the trailing path separator */
7429 gettail(vim_tempdir)[-1] = NUL;
7430 delete_recursive(vim_tempdir);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007431 vim_free(vim_tempdir);
7432 vim_tempdir = NULL;
7433 }
7434}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007435
7436/*
Bram Moolenaareaf03392009-11-17 11:08:52 +00007437 * Directory "tempdir" was created. Expand this name to a full path and put
7438 * it in "vim_tempdir". This avoids that using ":cd" would confuse us.
7439 * "tempdir" must be no longer than MAXPATHL.
7440 */
7441 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007442vim_settempdir(char_u *tempdir)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007443{
7444 char_u *buf;
7445
7446 buf = alloc((unsigned)MAXPATHL + 2);
7447 if (buf != NULL)
7448 {
7449 if (vim_FullName(tempdir, buf, MAXPATHL, FALSE) == FAIL)
7450 STRCPY(buf, tempdir);
Bram Moolenaara06ecab2016-07-16 14:47:36 +02007451 add_pathsep(buf);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007452 vim_tempdir = vim_strsave(buf);
7453 vim_free(buf);
7454 }
7455}
Bram Moolenaar4592dee2009-11-18 19:11:58 +00007456#endif
Bram Moolenaareaf03392009-11-17 11:08:52 +00007457
7458/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007459 * vim_tempname(): Return a unique name that can be used for a temp file.
7460 *
Bram Moolenaar76ae22f2016-06-13 20:00:29 +02007461 * The temp file is NOT guaranteed to be created. If "keep" is FALSE it is
7462 * guaranteed to NOT be created.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007463 *
7464 * The returned pointer is to allocated memory.
7465 * The returned pointer is NULL if no valid name was found.
7466 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007467 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007468vim_tempname(
7469 int extra_char UNUSED, /* char to use in the name instead of '?' */
7470 int keep UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007471{
7472#ifdef USE_TMPNAM
7473 char_u itmp[L_tmpnam]; /* use tmpnam() */
7474#else
7475 char_u itmp[TEMPNAMELEN];
7476#endif
7477
7478#ifdef TEMPDIRNAMES
7479 static char *(tempdirs[]) = {TEMPDIRNAMES};
7480 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007481# ifndef EEXIST
Bram Moolenaar8767f522016-07-01 17:17:39 +02007482 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007483# endif
7484
7485 /*
7486 * This will create a directory for private use by this instance of Vim.
7487 * This is done once, and the same directory is used for all temp files.
7488 * This method avoids security problems because of symlink attacks et al.
7489 * It's also a bit faster, because we only need to check for an existing
7490 * file when creating the directory and not for each temp file.
7491 */
7492 if (vim_tempdir == NULL)
7493 {
7494 /*
7495 * Try the entries in TEMPDIRNAMES to create the temp directory.
7496 */
Bram Moolenaar78a15312009-05-15 19:33:18 +00007497 for (i = 0; i < (int)(sizeof(tempdirs) / sizeof(char *)); ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007498 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007499# ifndef HAVE_MKDTEMP
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007500 size_t itmplen;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007501 long nr;
7502 long off;
7503# endif
7504
Bram Moolenaare1a61992015-12-03 21:02:27 +01007505 /* Expand $TMP, leave room for "/v1100000/999999999".
7506 * Skip the directory check if the expansion fails. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007507 expand_env((char_u *)tempdirs[i], itmp, TEMPNAMELEN - 20);
Bram Moolenaare1a61992015-12-03 21:02:27 +01007508 if (itmp[0] != '$' && mch_isdir(itmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007509 {
Bram Moolenaare1a61992015-12-03 21:02:27 +01007510 /* directory exists */
Bram Moolenaara06ecab2016-07-16 14:47:36 +02007511 add_pathsep(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007512
Bram Moolenaareaf03392009-11-17 11:08:52 +00007513# ifdef HAVE_MKDTEMP
Bram Moolenaar35d88f42016-06-04 14:52:00 +02007514 {
7515# if defined(UNIX) || defined(VMS)
7516 /* Make sure the umask doesn't remove the executable bit.
7517 * "repl" has been reported to use "177". */
7518 mode_t umask_save = umask(077);
7519# endif
7520 /* Leave room for filename */
7521 STRCAT(itmp, "vXXXXXX");
7522 if (mkdtemp((char *)itmp) != NULL)
7523 vim_settempdir(itmp);
7524# if defined(UNIX) || defined(VMS)
7525 (void)umask(umask_save);
7526# endif
7527 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007528# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007529 /* Get an arbitrary number of up to 6 digits. When it's
7530 * unlikely that it already exists it will be faster,
7531 * otherwise it doesn't matter. The use of mkdir() avoids any
7532 * security problems because of the predictable number. */
7533 nr = (mch_get_pid() + (long)time(NULL)) % 1000000L;
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007534 itmplen = STRLEN(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007535
7536 /* Try up to 10000 different values until we find a name that
7537 * doesn't exist. */
7538 for (off = 0; off < 10000L; ++off)
7539 {
7540 int r;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007541# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007542 mode_t umask_save;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007543# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007544
Bram Moolenaareaf03392009-11-17 11:08:52 +00007545 sprintf((char *)itmp + itmplen, "v%ld", nr + off);
7546# ifndef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007547 /* If mkdir() does not set errno to EEXIST, check for
7548 * existing file here. There is a race condition then,
7549 * although it's fail-safe. */
7550 if (mch_stat((char *)itmp, &st) >= 0)
7551 continue;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007552# endif
7553# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007554 /* Make sure the umask doesn't remove the executable bit.
7555 * "repl" has been reported to use "177". */
7556 umask_save = umask(077);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007557# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007558 r = vim_mkdir(itmp, 0700);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007559# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007560 (void)umask(umask_save);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007561# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007562 if (r == 0)
7563 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007564 vim_settempdir(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007565 break;
7566 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007567# ifdef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007568 /* If the mkdir() didn't fail because the file/dir exists,
7569 * we probably can't create any dir here, try another
7570 * place. */
7571 if (errno != EEXIST)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007572# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007573 break;
7574 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007575# endif /* HAVE_MKDTEMP */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007576 if (vim_tempdir != NULL)
7577 break;
7578 }
7579 }
7580 }
7581
7582 if (vim_tempdir != NULL)
7583 {
7584 /* There is no need to check if the file exists, because we own the
7585 * directory and nobody else creates a file in it. */
7586 sprintf((char *)itmp, "%s%ld", vim_tempdir, temp_count++);
7587 return vim_strsave(itmp);
7588 }
7589
7590 return NULL;
7591
7592#else /* TEMPDIRNAMES */
7593
7594# ifdef WIN3264
7595 char szTempFile[_MAX_PATH + 1];
7596 char buf4[4];
7597 char_u *retval;
7598 char_u *p;
7599
7600 STRCPY(itmp, "");
7601 if (GetTempPath(_MAX_PATH, szTempFile) == 0)
Bram Moolenaarb1891912011-02-09 14:47:03 +01007602 {
7603 szTempFile[0] = '.'; /* GetTempPath() failed, use current dir */
7604 szTempFile[1] = NUL;
7605 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007606 strcpy(buf4, "VIM");
7607 buf4[2] = extra_char; /* make it "VIa", "VIb", etc. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007608 if (GetTempFileName(szTempFile, buf4, 0, (LPSTR)itmp) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007609 return NULL;
Bram Moolenaare5c421c2015-03-31 13:33:08 +02007610 if (!keep)
7611 /* GetTempFileName() will create the file, we don't want that */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007612 (void)DeleteFile((LPSTR)itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007613
7614 /* Backslashes in a temp file name cause problems when filtering with
7615 * "sh". NOTE: This also checks 'shellcmdflag' to help those people who
7616 * didn't set 'shellslash'. */
7617 retval = vim_strsave(itmp);
7618 if (*p_shcf == '-' || p_ssl)
7619 for (p = retval; *p; ++p)
7620 if (*p == '\\')
7621 *p = '/';
7622 return retval;
7623
7624# else /* WIN3264 */
7625
7626# ifdef USE_TMPNAM
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007627 char_u *p;
7628
Bram Moolenaar071d4272004-06-13 20:20:40 +00007629 /* tmpnam() will make its own name */
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007630 p = tmpnam((char *)itmp);
7631 if (p == NULL || *p == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007632 return NULL;
7633# else
7634 char_u *p;
7635
7636# ifdef VMS_TEMPNAM
7637 /* mktemp() is not working on VMS. It seems to be
7638 * a do-nothing function. Therefore we use tempnam().
7639 */
7640 sprintf((char *)itmp, "VIM%c", extra_char);
7641 p = (char_u *)tempnam("tmp:", (char *)itmp);
7642 if (p != NULL)
7643 {
Bram Moolenaar206f0112014-03-12 16:51:55 +01007644 /* VMS will use '.LIS' if we don't explicitly specify an extension,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007645 * and VIM will then be unable to find the file later */
7646 STRCPY(itmp, p);
7647 STRCAT(itmp, ".txt");
7648 free(p);
7649 }
7650 else
7651 return NULL;
7652# else
7653 STRCPY(itmp, TEMPNAME);
7654 if ((p = vim_strchr(itmp, '?')) != NULL)
7655 *p = extra_char;
7656 if (mktemp((char *)itmp) == NULL)
7657 return NULL;
7658# endif
7659# endif
7660
7661 return vim_strsave(itmp);
7662# endif /* WIN3264 */
7663#endif /* TEMPDIRNAMES */
7664}
7665
7666#if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
7667/*
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02007668 * Convert all backslashes in fname to forward slashes in-place, unless when
7669 * it looks like a URL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007670 */
7671 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007672forward_slash(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007673{
7674 char_u *p;
7675
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02007676 if (path_with_url(fname))
7677 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007678 for (p = fname; *p != NUL; ++p)
7679# ifdef FEAT_MBYTE
7680 /* The Big5 encoding can have '\' in the trail byte. */
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00007681 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007682 ++p;
7683 else
7684# endif
7685 if (*p == '\\')
7686 *p = '/';
7687}
7688#endif
7689
7690
7691/*
7692 * Code for automatic commands.
7693 *
7694 * Only included when "FEAT_AUTOCMD" has been defined.
7695 */
7696
7697#if defined(FEAT_AUTOCMD) || defined(PROTO)
7698
7699/*
7700 * The autocommands are stored in a list for each event.
7701 * Autocommands for the same pattern, that are consecutive, are joined
7702 * together, to avoid having to match the pattern too often.
7703 * The result is an array of Autopat lists, which point to AutoCmd lists:
7704 *
Bram Moolenaar462455e2017-11-10 21:53:11 +01007705 * last_autopat[0] -----------------------------+
7706 * V
Bram Moolenaar071d4272004-06-13 20:20:40 +00007707 * first_autopat[0] --> Autopat.next --> Autopat.next --> NULL
7708 * Autopat.cmds Autopat.cmds
7709 * | |
7710 * V V
7711 * AutoCmd.next AutoCmd.next
7712 * | |
7713 * V V
7714 * AutoCmd.next NULL
7715 * |
7716 * V
7717 * NULL
7718 *
Bram Moolenaar462455e2017-11-10 21:53:11 +01007719 * last_autopat[1] --------+
7720 * V
Bram Moolenaar071d4272004-06-13 20:20:40 +00007721 * first_autopat[1] --> Autopat.next --> NULL
7722 * Autopat.cmds
7723 * |
7724 * V
7725 * AutoCmd.next
7726 * |
7727 * V
7728 * NULL
7729 * etc.
7730 *
7731 * The order of AutoCmds is important, this is the order in which they were
7732 * defined and will have to be executed.
7733 */
7734typedef struct AutoCmd
7735{
7736 char_u *cmd; /* The command to be executed (NULL
7737 when command has been removed) */
7738 char nested; /* If autocommands nest here */
7739 char last; /* last command in list */
7740#ifdef FEAT_EVAL
7741 scid_T scriptID; /* script ID where defined */
7742#endif
7743 struct AutoCmd *next; /* Next AutoCmd in list */
7744} AutoCmd;
7745
7746typedef struct AutoPat
7747{
Bram Moolenaar462455e2017-11-10 21:53:11 +01007748 struct AutoPat *next; /* next AutoPat in AutoPat list; MUST
7749 * be the first entry */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007750 char_u *pat; /* pattern as typed (NULL when pattern
7751 has been removed) */
Bram Moolenaar748bf032005-02-02 23:04:36 +00007752 regprog_T *reg_prog; /* compiled regprog for pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007753 AutoCmd *cmds; /* list of commands to do */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007754 int group; /* group ID */
7755 int patlen; /* strlen() of pat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007756 int buflocal_nr; /* !=0 for buffer-local AutoPat */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007757 char allow_dirs; /* Pattern may match whole path */
7758 char last; /* last pattern for apply_autocmds() */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007759} AutoPat;
7760
7761static struct event_name
7762{
7763 char *name; /* event name */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007764 event_T event; /* event number */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007765} event_names[] =
7766{
7767 {"BufAdd", EVENT_BUFADD},
7768 {"BufCreate", EVENT_BUFADD},
7769 {"BufDelete", EVENT_BUFDELETE},
7770 {"BufEnter", EVENT_BUFENTER},
7771 {"BufFilePost", EVENT_BUFFILEPOST},
7772 {"BufFilePre", EVENT_BUFFILEPRE},
7773 {"BufHidden", EVENT_BUFHIDDEN},
7774 {"BufLeave", EVENT_BUFLEAVE},
7775 {"BufNew", EVENT_BUFNEW},
7776 {"BufNewFile", EVENT_BUFNEWFILE},
7777 {"BufRead", EVENT_BUFREADPOST},
7778 {"BufReadCmd", EVENT_BUFREADCMD},
7779 {"BufReadPost", EVENT_BUFREADPOST},
7780 {"BufReadPre", EVENT_BUFREADPRE},
7781 {"BufUnload", EVENT_BUFUNLOAD},
7782 {"BufWinEnter", EVENT_BUFWINENTER},
7783 {"BufWinLeave", EVENT_BUFWINLEAVE},
7784 {"BufWipeout", EVENT_BUFWIPEOUT},
7785 {"BufWrite", EVENT_BUFWRITEPRE},
7786 {"BufWritePost", EVENT_BUFWRITEPOST},
7787 {"BufWritePre", EVENT_BUFWRITEPRE},
7788 {"BufWriteCmd", EVENT_BUFWRITECMD},
Bram Moolenaar153b7042018-01-31 15:48:32 +01007789 {"CmdlineChanged", EVENT_CMDLINECHANGED},
Bram Moolenaarfafcf0d2017-10-19 18:35:51 +02007790 {"CmdlineEnter", EVENT_CMDLINEENTER},
7791 {"CmdlineLeave", EVENT_CMDLINELEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007792 {"CmdwinEnter", EVENT_CMDWINENTER},
7793 {"CmdwinLeave", EVENT_CMDWINLEAVE},
Bram Moolenaard5005162014-08-22 23:05:54 +02007794 {"CmdUndefined", EVENT_CMDUNDEFINED},
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007795 {"ColorScheme", EVENT_COLORSCHEME},
Bram Moolenaarcfa3cae2012-07-10 17:14:56 +02007796 {"CompleteDone", EVENT_COMPLETEDONE},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007797 {"CursorHold", EVENT_CURSORHOLD},
7798 {"CursorHoldI", EVENT_CURSORHOLDI},
7799 {"CursorMoved", EVENT_CURSORMOVED},
7800 {"CursorMovedI", EVENT_CURSORMOVEDI},
Bram Moolenaarb7407d32018-02-03 17:36:27 +01007801 {"DirChanged", EVENT_DIRCHANGED},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007802 {"EncodingChanged", EVENT_ENCODINGCHANGED},
7803 {"FileEncoding", EVENT_ENCODINGCHANGED},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007804 {"FileAppendPost", EVENT_FILEAPPENDPOST},
7805 {"FileAppendPre", EVENT_FILEAPPENDPRE},
7806 {"FileAppendCmd", EVENT_FILEAPPENDCMD},
7807 {"FileChangedShell",EVENT_FILECHANGEDSHELL},
Bram Moolenaar56718732006-03-15 22:53:57 +00007808 {"FileChangedShellPost",EVENT_FILECHANGEDSHELLPOST},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007809 {"FileChangedRO", EVENT_FILECHANGEDRO},
7810 {"FileReadPost", EVENT_FILEREADPOST},
7811 {"FileReadPre", EVENT_FILEREADPRE},
7812 {"FileReadCmd", EVENT_FILEREADCMD},
7813 {"FileType", EVENT_FILETYPE},
7814 {"FileWritePost", EVENT_FILEWRITEPOST},
7815 {"FileWritePre", EVENT_FILEWRITEPRE},
7816 {"FileWriteCmd", EVENT_FILEWRITECMD},
7817 {"FilterReadPost", EVENT_FILTERREADPOST},
7818 {"FilterReadPre", EVENT_FILTERREADPRE},
7819 {"FilterWritePost", EVENT_FILTERWRITEPOST},
7820 {"FilterWritePre", EVENT_FILTERWRITEPRE},
7821 {"FocusGained", EVENT_FOCUSGAINED},
7822 {"FocusLost", EVENT_FOCUSLOST},
7823 {"FuncUndefined", EVENT_FUNCUNDEFINED},
7824 {"GUIEnter", EVENT_GUIENTER},
Bram Moolenaar265e5072006-08-29 16:13:22 +00007825 {"GUIFailed", EVENT_GUIFAILED},
Bram Moolenaar843ee412004-06-30 16:16:41 +00007826 {"InsertChange", EVENT_INSERTCHANGE},
7827 {"InsertEnter", EVENT_INSERTENTER},
7828 {"InsertLeave", EVENT_INSERTLEAVE},
Bram Moolenaare659c952011-05-19 17:25:41 +02007829 {"InsertCharPre", EVENT_INSERTCHARPRE},
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00007830 {"MenuPopup", EVENT_MENUPOPUP},
Bram Moolenaar53744302015-07-17 17:38:22 +02007831 {"OptionSet", EVENT_OPTIONSET},
Bram Moolenaar7c626922005-02-07 22:01:03 +00007832 {"QuickFixCmdPost", EVENT_QUICKFIXCMDPOST},
7833 {"QuickFixCmdPre", EVENT_QUICKFIXCMDPRE},
Bram Moolenaar3b53dfb2012-06-06 18:03:07 +02007834 {"QuitPre", EVENT_QUITPRE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007835 {"RemoteReply", EVENT_REMOTEREPLY},
Bram Moolenaar9372a112005-12-06 19:59:18 +00007836 {"SessionLoadPost", EVENT_SESSIONLOADPOST},
Bram Moolenaar5c4bab02006-03-10 21:37:46 +00007837 {"ShellCmdPost", EVENT_SHELLCMDPOST},
7838 {"ShellFilterPost", EVENT_SHELLFILTERPOST},
Bram Moolenaara2031822006-03-07 22:29:51 +00007839 {"SourcePre", EVENT_SOURCEPRE},
Bram Moolenaar8dd1aa52007-01-16 20:33:19 +00007840 {"SourceCmd", EVENT_SOURCECMD},
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00007841 {"SpellFileMissing",EVENT_SPELLFILEMISSING},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007842 {"StdinReadPost", EVENT_STDINREADPOST},
7843 {"StdinReadPre", EVENT_STDINREADPRE},
Bram Moolenaarb815dac2005-12-07 20:59:24 +00007844 {"SwapExists", EVENT_SWAPEXISTS},
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00007845 {"Syntax", EVENT_SYNTAX},
Bram Moolenaarc917da42016-07-19 22:31:36 +02007846 {"TabNew", EVENT_TABNEW},
Bram Moolenaar12c11d52016-07-19 23:13:03 +02007847 {"TabClosed", EVENT_TABCLOSED},
Bram Moolenaar70836c82006-02-20 21:28:49 +00007848 {"TabEnter", EVENT_TABENTER},
7849 {"TabLeave", EVENT_TABLEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007850 {"TermChanged", EVENT_TERMCHANGED},
7851 {"TermResponse", EVENT_TERMRESPONSE},
Bram Moolenaar186628f2013-03-19 13:33:23 +01007852 {"TextChanged", EVENT_TEXTCHANGED},
7853 {"TextChangedI", EVENT_TEXTCHANGEDI},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007854 {"User", EVENT_USER},
7855 {"VimEnter", EVENT_VIMENTER},
7856 {"VimLeave", EVENT_VIMLEAVE},
7857 {"VimLeavePre", EVENT_VIMLEAVEPRE},
Bram Moolenaarc917da42016-07-19 22:31:36 +02007858 {"WinNew", EVENT_WINNEW},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007859 {"WinEnter", EVENT_WINENTER},
7860 {"WinLeave", EVENT_WINLEAVE},
Bram Moolenaar56718732006-03-15 22:53:57 +00007861 {"VimResized", EVENT_VIMRESIZED},
Bram Moolenaar7e1652c2017-12-16 18:27:02 +01007862 {"TextYankPost", EVENT_TEXTYANKPOST},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007863 {NULL, (event_T)0}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007864};
7865
7866static AutoPat *first_autopat[NUM_EVENTS] =
7867{
7868 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7869 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7870 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7871 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00007872 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaar53744302015-07-17 17:38:22 +02007873 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007874};
7875
Bram Moolenaar462455e2017-11-10 21:53:11 +01007876static AutoPat *last_autopat[NUM_EVENTS] =
7877{
7878 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7879 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7880 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7881 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7882 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7883 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
7884};
7885
Bram Moolenaar071d4272004-06-13 20:20:40 +00007886/*
7887 * struct used to keep status while executing autocommands for an event.
7888 */
7889typedef struct AutoPatCmd
7890{
7891 AutoPat *curpat; /* next AutoPat to examine */
7892 AutoCmd *nextcmd; /* next AutoCmd to execute */
7893 int group; /* group being used */
7894 char_u *fname; /* fname to match with */
7895 char_u *sfname; /* sfname to match with */
7896 char_u *tail; /* tail of fname */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007897 event_T event; /* current event */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007898 int arg_bufnr; /* initially equal to <abuf>, set to zero when
7899 buf is deleted */
7900 struct AutoPatCmd *next; /* chain of active apc-s for auto-invalidation*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00007901} AutoPatCmd;
7902
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007903static AutoPatCmd *active_apc_list = NULL; /* stack of active autocommands */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007904
Bram Moolenaar071d4272004-06-13 20:20:40 +00007905/*
7906 * augroups stores a list of autocmd group names.
7907 */
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007908static garray_T augroups = {0, 0, sizeof(char_u *), 10, NULL};
Bram Moolenaar071d4272004-06-13 20:20:40 +00007909#define AUGROUP_NAME(i) (((char_u **)augroups.ga_data)[i])
Bram Moolenaarb62cc362016-09-03 16:43:53 +02007910/* use get_deleted_augroup() to get this */
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02007911static char_u *deleted_augroup = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007912
7913/*
7914 * The ID of the current group. Group 0 is the default one.
7915 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007916static int current_augroup = AUGROUP_DEFAULT;
7917
7918static int au_need_clean = FALSE; /* need to delete marked patterns */
7919
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007920static void show_autocmd(AutoPat *ap, event_T event);
7921static void au_remove_pat(AutoPat *ap);
7922static void au_remove_cmds(AutoPat *ap);
7923static void au_cleanup(void);
7924static int au_new_group(char_u *name);
7925static void au_del_group(char_u *name);
7926static event_T event_name2nr(char_u *start, char_u **end);
7927static char_u *event_nr2name(event_T event);
7928static char_u *find_end_event(char_u *arg, int have_group);
7929static int event_ignored(event_T event);
7930static int au_get_grouparg(char_u **argp);
7931static int do_autocmd_event(event_T event, char_u *pat, int nested, char_u *cmd, int forceit, int group);
7932static int apply_autocmds_group(event_T event, char_u *fname, char_u *fname_io, int force, int group, buf_T *buf, exarg_T *eap);
7933static void auto_next_pat(AutoPatCmd *apc, int stop_at_last);
Bram Moolenaardffa5b82014-11-19 16:38:07 +01007934#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN)
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007935static int match_file_pat(char_u *pattern, regprog_T **prog, char_u *fname, char_u *sfname, char_u *tail, int allow_dirs);
Bram Moolenaardffa5b82014-11-19 16:38:07 +01007936#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007937
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007938
Bram Moolenaar754b5602006-02-09 23:53:20 +00007939static event_T last_event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007940static int last_group;
Bram Moolenaar78ab3312007-09-29 12:16:41 +00007941static int autocmd_blocked = 0; /* block all autocmds */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007942
Bram Moolenaarb62cc362016-09-03 16:43:53 +02007943 static char_u *
7944get_deleted_augroup(void)
7945{
7946 if (deleted_augroup == NULL)
7947 deleted_augroup = (char_u *)_("--Deleted--");
7948 return deleted_augroup;
7949}
7950
Bram Moolenaar071d4272004-06-13 20:20:40 +00007951/*
7952 * Show the autocommands for one AutoPat.
7953 */
7954 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007955show_autocmd(AutoPat *ap, event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007956{
7957 AutoCmd *ac;
7958
7959 /* Check for "got_int" (here and at various places below), which is set
7960 * when "q" has been hit for the "--more--" prompt */
7961 if (got_int)
7962 return;
7963 if (ap->pat == NULL) /* pattern has been removed */
7964 return;
7965
7966 msg_putchar('\n');
7967 if (got_int)
7968 return;
7969 if (event != last_event || ap->group != last_group)
7970 {
7971 if (ap->group != AUGROUP_DEFAULT)
7972 {
7973 if (AUGROUP_NAME(ap->group) == NULL)
Bram Moolenaar8820b482017-03-16 17:23:31 +01007974 msg_puts_attr(get_deleted_augroup(), HL_ATTR(HLF_E));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007975 else
Bram Moolenaar8820b482017-03-16 17:23:31 +01007976 msg_puts_attr(AUGROUP_NAME(ap->group), HL_ATTR(HLF_T));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007977 msg_puts((char_u *)" ");
7978 }
Bram Moolenaar8820b482017-03-16 17:23:31 +01007979 msg_puts_attr(event_nr2name(event), HL_ATTR(HLF_T));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007980 last_event = event;
7981 last_group = ap->group;
7982 msg_putchar('\n');
7983 if (got_int)
7984 return;
7985 }
7986 msg_col = 4;
7987 msg_outtrans(ap->pat);
7988
7989 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7990 {
7991 if (ac->cmd != NULL) /* skip removed commands */
7992 {
7993 if (msg_col >= 14)
7994 msg_putchar('\n');
7995 msg_col = 14;
7996 if (got_int)
7997 return;
7998 msg_outtrans(ac->cmd);
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00007999#ifdef FEAT_EVAL
8000 if (p_verbose > 0)
8001 last_set_msg(ac->scriptID);
8002#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008003 if (got_int)
8004 return;
8005 if (ac->next != NULL)
8006 {
8007 msg_putchar('\n');
8008 if (got_int)
8009 return;
8010 }
8011 }
8012 }
8013}
8014
8015/*
8016 * Mark an autocommand pattern for deletion.
8017 */
8018 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008019au_remove_pat(AutoPat *ap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008020{
8021 vim_free(ap->pat);
8022 ap->pat = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008023 ap->buflocal_nr = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008024 au_need_clean = TRUE;
8025}
8026
8027/*
8028 * Mark all commands for a pattern for deletion.
8029 */
8030 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008031au_remove_cmds(AutoPat *ap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008032{
8033 AutoCmd *ac;
8034
8035 for (ac = ap->cmds; ac != NULL; ac = ac->next)
8036 {
8037 vim_free(ac->cmd);
8038 ac->cmd = NULL;
8039 }
8040 au_need_clean = TRUE;
8041}
8042
8043/*
8044 * Cleanup autocommands and patterns that have been deleted.
8045 * This is only done when not executing autocommands.
8046 */
8047 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008048au_cleanup(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008049{
8050 AutoPat *ap, **prev_ap;
8051 AutoCmd *ac, **prev_ac;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008052 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008053
8054 if (autocmd_busy || !au_need_clean)
8055 return;
8056
8057 /* loop over all events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008058 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8059 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008060 {
8061 /* loop over all autocommand patterns */
8062 prev_ap = &(first_autopat[(int)event]);
8063 for (ap = *prev_ap; ap != NULL; ap = *prev_ap)
8064 {
8065 /* loop over all commands for this pattern */
8066 prev_ac = &(ap->cmds);
8067 for (ac = *prev_ac; ac != NULL; ac = *prev_ac)
8068 {
8069 /* remove the command if the pattern is to be deleted or when
8070 * the command has been marked for deletion */
8071 if (ap->pat == NULL || ac->cmd == NULL)
8072 {
8073 *prev_ac = ac->next;
8074 vim_free(ac->cmd);
8075 vim_free(ac);
8076 }
8077 else
8078 prev_ac = &(ac->next);
8079 }
8080
8081 /* remove the pattern if it has been marked for deletion */
8082 if (ap->pat == NULL)
8083 {
Bram Moolenaar462455e2017-11-10 21:53:11 +01008084 if (ap->next == NULL)
8085 {
8086 if (prev_ap == &(first_autopat[(int)event]))
8087 last_autopat[(int)event] = NULL;
8088 else
8089 /* this depends on the "next" field being the first in
8090 * the struct */
8091 last_autopat[(int)event] = (AutoPat *)prev_ap;
8092 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008093 *prev_ap = ap->next;
Bram Moolenaar473de612013-06-08 18:19:48 +02008094 vim_regfree(ap->reg_prog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008095 vim_free(ap);
8096 }
8097 else
8098 prev_ap = &(ap->next);
8099 }
8100 }
8101
8102 au_need_clean = FALSE;
8103}
8104
8105/*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008106 * Called when buffer is freed, to remove/invalidate related buffer-local
8107 * autocmds.
8108 */
8109 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008110aubuflocal_remove(buf_T *buf)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008111{
8112 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008113 event_T event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008114 AutoPatCmd *apc;
8115
8116 /* invalidate currently executing autocommands */
8117 for (apc = active_apc_list; apc; apc = apc->next)
8118 if (buf->b_fnum == apc->arg_bufnr)
8119 apc->arg_bufnr = 0;
8120
8121 /* invalidate buflocals looping through events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008122 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8123 event = (event_T)((int)event + 1))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008124 /* loop over all autocommand patterns */
8125 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8126 if (ap->buflocal_nr == buf->b_fnum)
8127 {
8128 au_remove_pat(ap);
8129 if (p_verbose >= 6)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00008130 {
8131 verbose_enter();
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008132 smsg((char_u *)
8133 _("auto-removing autocommand: %s <buffer=%d>"),
8134 event_nr2name(event), buf->b_fnum);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00008135 verbose_leave();
8136 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008137 }
8138 au_cleanup();
8139}
8140
8141/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008142 * Add an autocmd group name.
8143 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
8144 */
8145 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008146au_new_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008147{
8148 int i;
8149
8150 i = au_find_group(name);
8151 if (i == AUGROUP_ERROR) /* the group doesn't exist yet, add it */
8152 {
8153 /* First try using a free entry. */
8154 for (i = 0; i < augroups.ga_len; ++i)
8155 if (AUGROUP_NAME(i) == NULL)
8156 break;
8157 if (i == augroups.ga_len && ga_grow(&augroups, 1) == FAIL)
8158 return AUGROUP_ERROR;
8159
8160 AUGROUP_NAME(i) = vim_strsave(name);
8161 if (AUGROUP_NAME(i) == NULL)
8162 return AUGROUP_ERROR;
8163 if (i == augroups.ga_len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008164 ++augroups.ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008165 }
8166
8167 return i;
8168}
8169
8170 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008171au_del_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008172{
8173 int i;
8174
8175 i = au_find_group(name);
8176 if (i == AUGROUP_ERROR) /* the group doesn't exist */
8177 EMSG2(_("E367: No such group: \"%s\""), name);
Bram Moolenaarde653f02016-09-03 16:59:06 +02008178 else if (i == current_augroup)
8179 EMSG(_("E936: Cannot delete the current group"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008180 else
8181 {
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008182 event_T event;
8183 AutoPat *ap;
8184 int in_use = FALSE;
8185
8186 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8187 event = (event_T)((int)event + 1))
8188 {
8189 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
Bram Moolenaar5c809082016-09-01 16:21:48 +02008190 if (ap->group == i && ap->pat != NULL)
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008191 {
8192 give_warning((char_u *)_("W19: Deleting augroup that is still in use"), TRUE);
8193 in_use = TRUE;
8194 event = NUM_EVENTS;
8195 break;
8196 }
8197 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008198 vim_free(AUGROUP_NAME(i));
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008199 if (in_use)
8200 {
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008201 AUGROUP_NAME(i) = get_deleted_augroup();
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008202 }
8203 else
8204 AUGROUP_NAME(i) = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008205 }
8206}
8207
8208/*
8209 * Find the ID of an autocmd group name.
8210 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
8211 */
8212 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008213au_find_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008214{
8215 int i;
8216
8217 for (i = 0; i < augroups.ga_len; ++i)
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008218 if (AUGROUP_NAME(i) != NULL && AUGROUP_NAME(i) != get_deleted_augroup()
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008219 && STRCMP(AUGROUP_NAME(i), name) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008220 return i;
8221 return AUGROUP_ERROR;
8222}
8223
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008224/*
8225 * Return TRUE if augroup "name" exists.
8226 */
8227 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008228au_has_group(char_u *name)
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008229{
8230 return au_find_group(name) != AUGROUP_ERROR;
8231}
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008232
Bram Moolenaar071d4272004-06-13 20:20:40 +00008233/*
8234 * ":augroup {name}".
8235 */
8236 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008237do_augroup(char_u *arg, int del_group)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008238{
8239 int i;
8240
8241 if (del_group)
8242 {
8243 if (*arg == NUL)
8244 EMSG(_(e_argreq));
8245 else
8246 au_del_group(arg);
8247 }
8248 else if (STRICMP(arg, "end") == 0) /* ":aug end": back to group 0 */
8249 current_augroup = AUGROUP_DEFAULT;
8250 else if (*arg) /* ":aug xxx": switch to group xxx */
8251 {
8252 i = au_new_group(arg);
8253 if (i != AUGROUP_ERROR)
8254 current_augroup = i;
8255 }
8256 else /* ":aug": list the group names */
8257 {
8258 msg_start();
8259 for (i = 0; i < augroups.ga_len; ++i)
8260 {
8261 if (AUGROUP_NAME(i) != NULL)
8262 {
8263 msg_puts(AUGROUP_NAME(i));
8264 msg_puts((char_u *)" ");
8265 }
8266 }
8267 msg_clr_eos();
8268 msg_end();
8269 }
8270}
8271
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008272#if defined(EXITFREE) || defined(PROTO)
8273 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008274free_all_autocmds(void)
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008275{
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008276 int i;
8277 char_u *s;
8278
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008279 for (current_augroup = -1; current_augroup < augroups.ga_len;
8280 ++current_augroup)
8281 do_autocmd((char_u *)"", TRUE);
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008282
8283 for (i = 0; i < augroups.ga_len; ++i)
8284 {
8285 s = ((char_u **)(augroups.ga_data))[i];
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008286 if (s != get_deleted_augroup())
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008287 vim_free(s);
8288 }
8289 ga_clear(&augroups);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008290}
8291#endif
8292
Bram Moolenaar071d4272004-06-13 20:20:40 +00008293/*
8294 * Return the event number for event name "start".
8295 * Return NUM_EVENTS if the event name was not found.
8296 * Return a pointer to the next event name in "end".
8297 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008298 static event_T
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008299event_name2nr(char_u *start, char_u **end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008300{
8301 char_u *p;
8302 int i;
8303 int len;
8304
Bram Moolenaare99e8442016-07-26 20:43:40 +02008305 /* the event name ends with end of line, '|', a blank or a comma */
Bram Moolenaar1c465442017-03-12 20:10:05 +01008306 for (p = start; *p && !VIM_ISWHITE(*p) && *p != ',' && *p != '|'; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008307 ;
8308 for (i = 0; event_names[i].name != NULL; ++i)
8309 {
8310 len = (int)STRLEN(event_names[i].name);
8311 if (len == p - start && STRNICMP(event_names[i].name, start, len) == 0)
8312 break;
8313 }
8314 if (*p == ',')
8315 ++p;
8316 *end = p;
8317 if (event_names[i].name == NULL)
8318 return NUM_EVENTS;
8319 return event_names[i].event;
8320}
8321
8322/*
8323 * Return the name for event "event".
8324 */
8325 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008326event_nr2name(event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008327{
8328 int i;
8329
8330 for (i = 0; event_names[i].name != NULL; ++i)
8331 if (event_names[i].event == event)
8332 return (char_u *)event_names[i].name;
8333 return (char_u *)"Unknown";
8334}
8335
8336/*
8337 * Scan over the events. "*" stands for all events.
8338 */
8339 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008340find_end_event(
8341 char_u *arg,
8342 int have_group) /* TRUE when group name was found */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008343{
8344 char_u *pat;
8345 char_u *p;
8346
8347 if (*arg == '*')
8348 {
Bram Moolenaar1c465442017-03-12 20:10:05 +01008349 if (arg[1] && !VIM_ISWHITE(arg[1]))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008350 {
8351 EMSG2(_("E215: Illegal character after *: %s"), arg);
8352 return NULL;
8353 }
8354 pat = arg + 1;
8355 }
8356 else
8357 {
Bram Moolenaar1c465442017-03-12 20:10:05 +01008358 for (pat = arg; *pat && *pat != '|' && !VIM_ISWHITE(*pat); pat = p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008359 {
8360 if ((int)event_name2nr(pat, &p) >= (int)NUM_EVENTS)
8361 {
8362 if (have_group)
8363 EMSG2(_("E216: No such event: %s"), pat);
8364 else
8365 EMSG2(_("E216: No such group or event: %s"), pat);
8366 return NULL;
8367 }
8368 }
8369 }
8370 return pat;
8371}
8372
8373/*
8374 * Return TRUE if "event" is included in 'eventignore'.
8375 */
8376 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008377event_ignored(event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008378{
8379 char_u *p = p_ei;
8380
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008381 while (*p != NUL)
8382 {
8383 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8384 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008385 if (event_name2nr(p, &p) == event)
8386 return TRUE;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008387 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008388
8389 return FALSE;
8390}
8391
8392/*
8393 * Return OK when the contents of p_ei is valid, FAIL otherwise.
8394 */
8395 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008396check_ei(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008397{
8398 char_u *p = p_ei;
8399
Bram Moolenaar071d4272004-06-13 20:20:40 +00008400 while (*p)
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008401 {
8402 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8403 {
8404 p += 3;
8405 if (*p == ',')
8406 ++p;
8407 }
8408 else if (event_name2nr(p, &p) == NUM_EVENTS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008409 return FAIL;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008410 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008411
8412 return OK;
8413}
8414
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008415# if defined(FEAT_SYN_HL) || defined(PROTO)
8416
8417/*
8418 * Add "what" to 'eventignore' to skip loading syntax highlighting for every
8419 * buffer loaded into the window. "what" must start with a comma.
8420 * Returns the old value of 'eventignore' in allocated memory.
8421 */
8422 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008423au_event_disable(char *what)
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008424{
8425 char_u *new_ei;
8426 char_u *save_ei;
8427
8428 save_ei = vim_strsave(p_ei);
8429 if (save_ei != NULL)
8430 {
Bram Moolenaara5792f52005-11-23 21:25:05 +00008431 new_ei = vim_strnsave(p_ei, (int)(STRLEN(p_ei) + STRLEN(what)));
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008432 if (new_ei != NULL)
8433 {
Bram Moolenaar8cac9fd2010-03-02 12:48:05 +01008434 if (*what == ',' && *p_ei == NUL)
8435 STRCPY(new_ei, what + 1);
8436 else
8437 STRCAT(new_ei, what);
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008438 set_string_option_direct((char_u *)"ei", -1, new_ei,
8439 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008440 vim_free(new_ei);
8441 }
8442 }
8443 return save_ei;
8444}
8445
8446 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008447au_event_restore(char_u *old_ei)
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008448{
8449 if (old_ei != NULL)
8450 {
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008451 set_string_option_direct((char_u *)"ei", -1, old_ei,
8452 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008453 vim_free(old_ei);
8454 }
8455}
8456# endif /* FEAT_SYN_HL */
8457
Bram Moolenaar071d4272004-06-13 20:20:40 +00008458/*
8459 * do_autocmd() -- implements the :autocmd command. Can be used in the
8460 * following ways:
8461 *
8462 * :autocmd <event> <pat> <cmd> Add <cmd> to the list of commands that
8463 * will be automatically executed for <event>
8464 * when editing a file matching <pat>, in
8465 * the current group.
8466 * :autocmd <event> <pat> Show the auto-commands associated with
8467 * <event> and <pat>.
8468 * :autocmd <event> Show the auto-commands associated with
8469 * <event>.
8470 * :autocmd Show all auto-commands.
8471 * :autocmd! <event> <pat> <cmd> Remove all auto-commands associated with
8472 * <event> and <pat>, and add the command
8473 * <cmd>, for the current group.
8474 * :autocmd! <event> <pat> Remove all auto-commands associated with
8475 * <event> and <pat> for the current group.
8476 * :autocmd! <event> Remove all auto-commands associated with
8477 * <event> for the current group.
8478 * :autocmd! Remove ALL auto-commands for the current
8479 * group.
8480 *
8481 * Multiple events and patterns may be given separated by commas. Here are
8482 * some examples:
8483 * :autocmd bufread,bufenter *.c,*.h set tw=0 smartindent noic
8484 * :autocmd bufleave * set tw=79 nosmartindent ic infercase
8485 *
8486 * :autocmd * *.c show all autocommands for *.c files.
Bram Moolenaard35f9712005-12-18 22:02:33 +00008487 *
8488 * Mostly a {group} argument can optionally appear before <event>.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008489 */
8490 void
Bram Moolenaare99e8442016-07-26 20:43:40 +02008491do_autocmd(char_u *arg_in, int forceit)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008492{
Bram Moolenaare99e8442016-07-26 20:43:40 +02008493 char_u *arg = arg_in;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008494 char_u *pat;
8495 char_u *envpat = NULL;
8496 char_u *cmd;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008497 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008498 int need_free = FALSE;
8499 int nested = FALSE;
8500 int group;
8501
Bram Moolenaare99e8442016-07-26 20:43:40 +02008502 if (*arg == '|')
8503 {
8504 arg = (char_u *)"";
8505 group = AUGROUP_ALL; /* no argument, use all groups */
8506 }
8507 else
8508 {
8509 /*
8510 * Check for a legal group name. If not, use AUGROUP_ALL.
8511 */
8512 group = au_get_grouparg(&arg);
8513 if (arg == NULL) /* out of memory */
8514 return;
8515 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008516
8517 /*
8518 * Scan over the events.
8519 * If we find an illegal name, return here, don't do anything.
8520 */
8521 pat = find_end_event(arg, group != AUGROUP_ALL);
8522 if (pat == NULL)
8523 return;
8524
Bram Moolenaar071d4272004-06-13 20:20:40 +00008525 pat = skipwhite(pat);
Bram Moolenaare99e8442016-07-26 20:43:40 +02008526 if (*pat == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008527 {
Bram Moolenaare99e8442016-07-26 20:43:40 +02008528 pat = (char_u *)"";
8529 cmd = (char_u *)"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00008530 }
Bram Moolenaare99e8442016-07-26 20:43:40 +02008531 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00008532 {
Bram Moolenaare99e8442016-07-26 20:43:40 +02008533 /*
8534 * Scan over the pattern. Put a NUL at the end.
8535 */
8536 cmd = pat;
Bram Moolenaar1c465442017-03-12 20:10:05 +01008537 while (*cmd && (!VIM_ISWHITE(*cmd) || cmd[-1] == '\\'))
Bram Moolenaare99e8442016-07-26 20:43:40 +02008538 cmd++;
8539 if (*cmd)
8540 *cmd++ = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008541
Bram Moolenaare99e8442016-07-26 20:43:40 +02008542 /* Expand environment variables in the pattern. Set 'shellslash', we want
8543 * forward slashes here. */
8544 if (vim_strchr(pat, '$') != NULL || vim_strchr(pat, '~') != NULL)
8545 {
8546#ifdef BACKSLASH_IN_FILENAME
8547 int p_ssl_save = p_ssl;
8548
8549 p_ssl = TRUE;
8550#endif
8551 envpat = expand_env_save(pat);
8552#ifdef BACKSLASH_IN_FILENAME
8553 p_ssl = p_ssl_save;
8554#endif
8555 if (envpat != NULL)
8556 pat = envpat;
8557 }
8558
8559 /*
8560 * Check for "nested" flag.
8561 */
8562 cmd = skipwhite(cmd);
Bram Moolenaar1c465442017-03-12 20:10:05 +01008563 if (*cmd != NUL && STRNCMP(cmd, "nested", 6) == 0 && VIM_ISWHITE(cmd[6]))
Bram Moolenaare99e8442016-07-26 20:43:40 +02008564 {
8565 nested = TRUE;
8566 cmd = skipwhite(cmd + 6);
8567 }
8568
8569 /*
8570 * Find the start of the commands.
8571 * Expand <sfile> in it.
8572 */
8573 if (*cmd != NUL)
8574 {
8575 cmd = expand_sfile(cmd);
8576 if (cmd == NULL) /* some error */
8577 return;
8578 need_free = TRUE;
8579 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008580 }
8581
8582 /*
8583 * Print header when showing autocommands.
8584 */
8585 if (!forceit && *cmd == NUL)
8586 {
8587 /* Highlight title */
8588 MSG_PUTS_TITLE(_("\n--- Auto-Commands ---"));
8589 }
8590
8591 /*
8592 * Loop over the events.
8593 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008594 last_event = (event_T)-1; /* for listing the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008595 last_group = AUGROUP_ERROR; /* for listing the group name */
Bram Moolenaare99e8442016-07-26 20:43:40 +02008596 if (*arg == '*' || *arg == NUL || *arg == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008597 {
Bram Moolenaar754b5602006-02-09 23:53:20 +00008598 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8599 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008600 if (do_autocmd_event(event, pat,
8601 nested, cmd, forceit, group) == FAIL)
8602 break;
8603 }
8604 else
8605 {
Bram Moolenaar1c465442017-03-12 20:10:05 +01008606 while (*arg && *arg != '|' && !VIM_ISWHITE(*arg))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008607 if (do_autocmd_event(event_name2nr(arg, &arg), pat,
8608 nested, cmd, forceit, group) == FAIL)
8609 break;
8610 }
8611
8612 if (need_free)
8613 vim_free(cmd);
8614 vim_free(envpat);
8615}
8616
8617/*
8618 * Find the group ID in a ":autocmd" or ":doautocmd" argument.
8619 * The "argp" argument is advanced to the following argument.
8620 *
8621 * Returns the group ID, AUGROUP_ERROR for error (out of memory).
8622 */
8623 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008624au_get_grouparg(char_u **argp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008625{
8626 char_u *group_name;
8627 char_u *p;
8628 char_u *arg = *argp;
8629 int group = AUGROUP_ALL;
8630
Bram Moolenaar1c465442017-03-12 20:10:05 +01008631 for (p = arg; *p && !VIM_ISWHITE(*p) && *p != '|'; ++p)
Bram Moolenaare99e8442016-07-26 20:43:40 +02008632 ;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008633 if (p > arg)
8634 {
8635 group_name = vim_strnsave(arg, (int)(p - arg));
8636 if (group_name == NULL) /* out of memory */
8637 return AUGROUP_ERROR;
8638 group = au_find_group(group_name);
8639 if (group == AUGROUP_ERROR)
8640 group = AUGROUP_ALL; /* no match, use all groups */
8641 else
8642 *argp = skipwhite(p); /* match, skip over group name */
8643 vim_free(group_name);
8644 }
8645 return group;
8646}
8647
8648/*
8649 * do_autocmd() for one event.
8650 * If *pat == NUL do for all patterns.
8651 * If *cmd == NUL show entries.
8652 * If forceit == TRUE delete entries.
8653 * If group is not AUGROUP_ALL, only use this group.
8654 */
8655 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008656do_autocmd_event(
8657 event_T event,
8658 char_u *pat,
8659 int nested,
8660 char_u *cmd,
8661 int forceit,
8662 int group)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008663{
8664 AutoPat *ap;
8665 AutoPat **prev_ap;
8666 AutoCmd *ac;
8667 AutoCmd **prev_ac;
8668 int brace_level;
8669 char_u *endpat;
8670 int findgroup;
8671 int allgroups;
8672 int patlen;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00008673 int is_buflocal;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008674 int buflocal_nr;
8675 char_u buflocal_pat[25]; /* for "<buffer=X>" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008676
8677 if (group == AUGROUP_ALL)
8678 findgroup = current_augroup;
8679 else
8680 findgroup = group;
8681 allgroups = (group == AUGROUP_ALL && !forceit && *cmd == NUL);
8682
8683 /*
8684 * Show or delete all patterns for an event.
8685 */
8686 if (*pat == NUL)
8687 {
8688 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8689 {
8690 if (forceit) /* delete the AutoPat, if it's in the current group */
8691 {
8692 if (ap->group == findgroup)
8693 au_remove_pat(ap);
8694 }
8695 else if (group == AUGROUP_ALL || ap->group == group)
8696 show_autocmd(ap, event);
8697 }
8698 }
8699
8700 /*
8701 * Loop through all the specified patterns.
8702 */
8703 for ( ; *pat; pat = (*endpat == ',' ? endpat + 1 : endpat))
8704 {
8705 /*
8706 * Find end of the pattern.
8707 * Watch out for a comma in braces, like "*.\{obj,o\}".
8708 */
8709 brace_level = 0;
8710 for (endpat = pat; *endpat && (*endpat != ',' || brace_level
Bram Moolenaar6b9be1b2015-07-28 13:33:45 +02008711 || (endpat > pat && endpat[-1] == '\\')); ++endpat)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008712 {
8713 if (*endpat == '{')
8714 brace_level++;
8715 else if (*endpat == '}')
8716 brace_level--;
8717 }
8718 if (pat == endpat) /* ignore single comma */
8719 continue;
8720 patlen = (int)(endpat - pat);
8721
8722 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008723 * detect special <buflocal[=X]> buffer-local patterns
8724 */
8725 is_buflocal = FALSE;
8726 buflocal_nr = 0;
8727
Bram Moolenaar1e997822015-02-17 16:04:57 +01008728 if (patlen >= 8 && STRNCMP(pat, "<buffer", 7) == 0
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008729 && pat[patlen - 1] == '>')
8730 {
Bram Moolenaar1e997822015-02-17 16:04:57 +01008731 /* "<buffer...>": Error will be printed only for addition.
8732 * printing and removing will proceed silently. */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008733 is_buflocal = TRUE;
8734 if (patlen == 8)
Bram Moolenaar1e997822015-02-17 16:04:57 +01008735 /* "<buffer>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008736 buflocal_nr = curbuf->b_fnum;
8737 else if (patlen > 9 && pat[7] == '=')
8738 {
Bram Moolenaar1e997822015-02-17 16:04:57 +01008739 if (patlen == 13 && STRNICMP(pat, "<buffer=abuf>", 13) == 0)
8740 /* "<buffer=abuf>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008741 buflocal_nr = autocmd_bufnr;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008742 else if (skipdigits(pat + 8) == pat + patlen - 1)
Bram Moolenaar1e997822015-02-17 16:04:57 +01008743 /* "<buffer=123>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008744 buflocal_nr = atoi((char *)pat + 8);
8745 }
8746 }
8747
8748 if (is_buflocal)
8749 {
8750 /* normalize pat into standard "<buffer>#N" form */
8751 sprintf((char *)buflocal_pat, "<buffer=%d>", buflocal_nr);
8752 pat = buflocal_pat; /* can modify pat and patlen */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008753 patlen = (int)STRLEN(buflocal_pat); /* but not endpat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008754 }
8755
8756 /*
Bram Moolenaar462455e2017-11-10 21:53:11 +01008757 * Find AutoPat entries with this pattern. When adding a command it
8758 * always goes at or after the last one, so start at the end.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008759 */
Bram Moolenaar462455e2017-11-10 21:53:11 +01008760 if (!forceit && *cmd != NUL && last_autopat[(int)event] != NULL)
8761 prev_ap = &last_autopat[(int)event];
8762 else
8763 prev_ap = &first_autopat[(int)event];
Bram Moolenaar071d4272004-06-13 20:20:40 +00008764 while ((ap = *prev_ap) != NULL)
8765 {
8766 if (ap->pat != NULL)
8767 {
8768 /* Accept a pattern when:
8769 * - a group was specified and it's that group, or a group was
8770 * not specified and it's the current group, or a group was
8771 * not specified and we are listing
8772 * - the length of the pattern matches
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008773 * - the pattern matches.
8774 * For <buffer[=X]>, this condition works because we normalize
8775 * all buffer-local patterns.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008776 */
8777 if ((allgroups || ap->group == findgroup)
8778 && ap->patlen == patlen
8779 && STRNCMP(pat, ap->pat, patlen) == 0)
8780 {
8781 /*
8782 * Remove existing autocommands.
8783 * If adding any new autocmd's for this AutoPat, don't
8784 * delete the pattern from the autopat list, append to
8785 * this list.
8786 */
8787 if (forceit)
8788 {
8789 if (*cmd != NUL && ap->next == NULL)
8790 {
8791 au_remove_cmds(ap);
8792 break;
8793 }
8794 au_remove_pat(ap);
8795 }
8796
8797 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008798 * Show autocmd's for this autopat, or buflocals <buffer=X>
Bram Moolenaar071d4272004-06-13 20:20:40 +00008799 */
8800 else if (*cmd == NUL)
8801 show_autocmd(ap, event);
8802
8803 /*
8804 * Add autocmd to this autopat, if it's the last one.
8805 */
8806 else if (ap->next == NULL)
8807 break;
8808 }
8809 }
8810 prev_ap = &ap->next;
8811 }
8812
8813 /*
8814 * Add a new command.
8815 */
8816 if (*cmd != NUL)
8817 {
8818 /*
8819 * If the pattern we want to add a command to does appear at the
8820 * end of the list (or not is not in the list at all), add the
8821 * pattern at the end of the list.
8822 */
8823 if (ap == NULL)
8824 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008825 /* refuse to add buffer-local ap if buffer number is invalid */
8826 if (is_buflocal && (buflocal_nr == 0
8827 || buflist_findnr(buflocal_nr) == NULL))
8828 {
8829 EMSGN(_("E680: <buffer=%d>: invalid buffer number "),
8830 buflocal_nr);
8831 return FAIL;
8832 }
8833
Bram Moolenaar071d4272004-06-13 20:20:40 +00008834 ap = (AutoPat *)alloc((unsigned)sizeof(AutoPat));
8835 if (ap == NULL)
8836 return FAIL;
8837 ap->pat = vim_strnsave(pat, patlen);
8838 ap->patlen = patlen;
8839 if (ap->pat == NULL)
8840 {
8841 vim_free(ap);
8842 return FAIL;
8843 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008844
8845 if (is_buflocal)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008846 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008847 ap->buflocal_nr = buflocal_nr;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008848 ap->reg_prog = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008849 }
8850 else
8851 {
Bram Moolenaar748bf032005-02-02 23:04:36 +00008852 char_u *reg_pat;
8853
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008854 ap->buflocal_nr = 0;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008855 reg_pat = file_pat_to_reg_pat(pat, endpat,
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008856 &ap->allow_dirs, TRUE);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008857 if (reg_pat != NULL)
8858 ap->reg_prog = vim_regcomp(reg_pat, RE_MAGIC);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008859 vim_free(reg_pat);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008860 if (reg_pat == NULL || ap->reg_prog == NULL)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008861 {
8862 vim_free(ap->pat);
8863 vim_free(ap);
8864 return FAIL;
8865 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008866 }
8867 ap->cmds = NULL;
8868 *prev_ap = ap;
Bram Moolenaar462455e2017-11-10 21:53:11 +01008869 last_autopat[(int)event] = ap;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008870 ap->next = NULL;
8871 if (group == AUGROUP_ALL)
8872 ap->group = current_augroup;
8873 else
8874 ap->group = group;
8875 }
8876
8877 /*
8878 * Add the autocmd at the end of the AutoCmd list.
8879 */
8880 prev_ac = &(ap->cmds);
8881 while ((ac = *prev_ac) != NULL)
8882 prev_ac = &ac->next;
8883 ac = (AutoCmd *)alloc((unsigned)sizeof(AutoCmd));
8884 if (ac == NULL)
8885 return FAIL;
8886 ac->cmd = vim_strsave(cmd);
8887#ifdef FEAT_EVAL
8888 ac->scriptID = current_SID;
8889#endif
8890 if (ac->cmd == NULL)
8891 {
8892 vim_free(ac);
8893 return FAIL;
8894 }
8895 ac->next = NULL;
8896 *prev_ac = ac;
8897 ac->nested = nested;
8898 }
8899 }
8900
8901 au_cleanup(); /* may really delete removed patterns/commands now */
8902 return OK;
8903}
8904
8905/*
8906 * Implementation of ":doautocmd [group] event [fname]".
8907 * Return OK for success, FAIL for failure;
8908 */
8909 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008910do_doautocmd(
8911 char_u *arg,
Bram Moolenaar1610d052016-06-09 22:53:01 +02008912 int do_msg, /* give message for no matching autocmds? */
8913 int *did_something)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008914{
8915 char_u *fname;
8916 int nothing_done = TRUE;
8917 int group;
8918
Bram Moolenaar1610d052016-06-09 22:53:01 +02008919 if (did_something != NULL)
Bram Moolenaar76ae22f2016-06-13 20:00:29 +02008920 *did_something = FALSE;
Bram Moolenaar1610d052016-06-09 22:53:01 +02008921
Bram Moolenaar071d4272004-06-13 20:20:40 +00008922 /*
8923 * Check for a legal group name. If not, use AUGROUP_ALL.
8924 */
8925 group = au_get_grouparg(&arg);
8926 if (arg == NULL) /* out of memory */
8927 return FAIL;
8928
8929 if (*arg == '*')
8930 {
8931 EMSG(_("E217: Can't execute autocommands for ALL events"));
8932 return FAIL;
8933 }
8934
8935 /*
8936 * Scan over the events.
8937 * If we find an illegal name, return here, don't do anything.
8938 */
8939 fname = find_end_event(arg, group != AUGROUP_ALL);
8940 if (fname == NULL)
8941 return FAIL;
8942
8943 fname = skipwhite(fname);
8944
8945 /*
8946 * Loop over the events.
8947 */
Bram Moolenaarfaf29d72017-07-09 11:07:16 +02008948 while (*arg && !ends_excmd(*arg) && !VIM_ISWHITE(*arg))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008949 if (apply_autocmds_group(event_name2nr(arg, &arg),
8950 fname, NULL, TRUE, group, curbuf, NULL))
8951 nothing_done = FALSE;
8952
8953 if (nothing_done && do_msg)
8954 MSG(_("No matching autocommands"));
Bram Moolenaar1610d052016-06-09 22:53:01 +02008955 if (did_something != NULL)
8956 *did_something = !nothing_done;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008957
8958#ifdef FEAT_EVAL
8959 return aborting() ? FAIL : OK;
8960#else
8961 return OK;
8962#endif
8963}
8964
8965/*
8966 * ":doautoall": execute autocommands for each loaded buffer.
8967 */
8968 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008969ex_doautoall(exarg_T *eap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008970{
8971 int retval;
8972 aco_save_T aco;
8973 buf_T *buf;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008974 bufref_T bufref;
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008975 char_u *arg = eap->arg;
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008976 int call_do_modelines = check_nomodeline(&arg);
Bram Moolenaar1610d052016-06-09 22:53:01 +02008977 int did_aucmd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008978
8979 /*
8980 * This is a bit tricky: For some commands curwin->w_buffer needs to be
8981 * equal to curbuf, but for some buffers there may not be a window.
8982 * So we change the buffer for the current window for a moment. This
8983 * gives problems when the autocommands make changes to the list of
8984 * buffers or windows...
8985 */
Bram Moolenaar29323592016-07-24 22:04:11 +02008986 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008987 {
Bram Moolenaar3a847972008-07-08 09:36:58 +00008988 if (buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008989 {
8990 /* find a window for this buffer and save some values */
8991 aucmd_prepbuf(&aco, buf);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008992 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008993
8994 /* execute the autocommands for this buffer */
Bram Moolenaar1610d052016-06-09 22:53:01 +02008995 retval = do_doautocmd(arg, FALSE, &did_aucmd);
Bram Moolenaareeefcc72007-05-01 21:21:21 +00008996
Bram Moolenaar1610d052016-06-09 22:53:01 +02008997 if (call_do_modelines && did_aucmd)
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008998 {
8999 /* Execute the modeline settings, but don't set window-local
9000 * options if we are using the current window for another
9001 * buffer. */
9002 do_modelines(curwin == aucmd_win ? OPT_NOWIN : 0);
9003 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009004
9005 /* restore the current window */
9006 aucmd_restbuf(&aco);
9007
9008 /* stop if there is some error or buffer was deleted */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009009 if (retval == FAIL || !bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009010 break;
9011 }
9012 }
9013
9014 check_cursor(); /* just in case lines got deleted */
9015}
9016
9017/*
Bram Moolenaar60542ac2012-02-12 20:14:01 +01009018 * Check *argp for <nomodeline>. When it is present return FALSE, otherwise
9019 * return TRUE and advance *argp to after it.
9020 * Thus return TRUE when do_modelines() should be called.
9021 */
9022 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009023check_nomodeline(char_u **argp)
Bram Moolenaar60542ac2012-02-12 20:14:01 +01009024{
9025 if (STRNCMP(*argp, "<nomodeline>", 12) == 0)
9026 {
9027 *argp = skipwhite(*argp + 12);
9028 return FALSE;
9029 }
9030 return TRUE;
9031}
9032
9033/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00009034 * Prepare for executing autocommands for (hidden) buffer "buf".
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009035 * Search for a visible window containing the current buffer. If there isn't
9036 * one then use "aucmd_win".
Bram Moolenaar071d4272004-06-13 20:20:40 +00009037 * Set "curbuf" and "curwin" to match "buf".
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009038 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009039 */
9040 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009041aucmd_prepbuf(
9042 aco_save_T *aco, /* structure to save values in */
9043 buf_T *buf) /* new curbuf */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009044{
9045 win_T *win;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009046 int save_ea;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02009047#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009048 int save_acd;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02009049#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009050
9051 /* Find a window that is for the new buffer */
9052 if (buf == curbuf) /* be quick when buf is curbuf */
9053 win = curwin;
9054 else
Bram Moolenaar29323592016-07-24 22:04:11 +02009055 FOR_ALL_WINDOWS(win)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009056 if (win->w_buffer == buf)
9057 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009058
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009059 /* Allocate "aucmd_win" when needed. If this fails (out of memory) fall
9060 * back to using the current window. */
9061 if (win == NULL && aucmd_win == NULL)
9062 {
9063 win_alloc_aucmd_win();
9064 if (aucmd_win == NULL)
9065 win = curwin;
9066 }
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009067 if (win == NULL && aucmd_win_used)
9068 /* Strange recursive autocommand, fall back to using the current
9069 * window. Expect a few side effects... */
9070 win = curwin;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009071
9072 aco->save_curwin = curwin;
9073 aco->save_curbuf = curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009074 if (win != NULL)
9075 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009076 /* There is a window for "buf" in the current tab page, make it the
9077 * curwin. This is preferred, it has the least side effects (esp. if
9078 * "buf" is curbuf). */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009079 aco->use_aucmd_win = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009080 curwin = win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009081 }
9082 else
9083 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009084 /* There is no window for "buf", use "aucmd_win". To minimize the side
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02009085 * effects, insert it in the current tab page.
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009086 * Anything related to a window (e.g., setting folds) may have
9087 * unexpected results. */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009088 aco->use_aucmd_win = TRUE;
9089 aucmd_win_used = TRUE;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00009090 aucmd_win->w_buffer = buf;
Bram Moolenaarcdddaa42010-06-07 23:07:44 +02009091 aucmd_win->w_s = &buf->b_s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009092 ++buf->b_nwindows;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00009093 win_init_empty(aucmd_win); /* set cursor and topline to safe values */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009094
9095 /* Make sure w_localdir and globaldir are NULL to avoid a chdir() in
9096 * win_enter_ext(). */
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009097 vim_free(aucmd_win->w_localdir);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009098 aucmd_win->w_localdir = NULL;
9099 aco->globaldir = globaldir;
9100 globaldir = NULL;
9101
Bram Moolenaar071d4272004-06-13 20:20:40 +00009102
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00009103 /* Split the current window, put the aucmd_win in the upper half.
9104 * We don't want the BufEnter or WinEnter autocommands. */
9105 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009106 make_snapshot(SNAP_AUCMD_IDX);
9107 save_ea = p_ea;
9108 p_ea = FALSE;
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009109
Bram Moolenaar4033c552017-09-16 20:54:51 +02009110#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009111 /* Prevent chdir() call in win_enter_ext(), through do_autochdir(). */
9112 save_acd = p_acd;
9113 p_acd = FALSE;
Bram Moolenaar4033c552017-09-16 20:54:51 +02009114#endif
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009115
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009116 (void)win_split_ins(0, WSP_TOP, aucmd_win, 0);
9117 (void)win_comp_pos(); /* recompute window positions */
9118 p_ea = save_ea;
Bram Moolenaar4033c552017-09-16 20:54:51 +02009119#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009120 p_acd = save_acd;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009121#endif
Bram Moolenaar4033c552017-09-16 20:54:51 +02009122 unblock_autocmds();
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00009123 curwin = aucmd_win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009124 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009125 curbuf = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009126 aco->new_curwin = curwin;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009127 set_bufref(&aco->new_curbuf, curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009128}
9129
9130/*
9131 * Cleanup after executing autocommands for a (hidden) buffer.
9132 * Restore the window as it was (if possible).
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009133 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009134 */
9135 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009136aucmd_restbuf(
9137 aco_save_T *aco) /* structure holding saved values */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009138{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009139 int dummy;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009140
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009141 if (aco->use_aucmd_win)
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009142 {
9143 --curbuf->b_nwindows;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009144 /* Find "aucmd_win", it can't be closed, but it may be in another tab
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00009145 * page. Do not trigger autocommands here. */
9146 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009147 if (curwin != aucmd_win)
9148 {
9149 tabpage_T *tp;
9150 win_T *wp;
9151
9152 FOR_ALL_TAB_WINDOWS(tp, wp)
9153 {
9154 if (wp == aucmd_win)
9155 {
9156 if (tp != curtab)
Bram Moolenaar49e649f2013-05-06 04:50:35 +02009157 goto_tabpage_tp(tp, TRUE, TRUE);
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009158 win_goto(aucmd_win);
Bram Moolenaar28f29082012-02-11 23:45:37 +01009159 goto win_found;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009160 }
9161 }
9162 }
Bram Moolenaar28f29082012-02-11 23:45:37 +01009163win_found:
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009164
9165 /* Remove the window and frame from the tree of frames. */
9166 (void)winframe_remove(curwin, &dummy, NULL);
9167 win_remove(curwin, NULL);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009168 aucmd_win_used = FALSE;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009169 last_status(FALSE); /* may need to remove last status line */
Bram Moolenaar8c752bd2017-03-19 17:09:56 +01009170
9171 if (!valid_tabpage_win(curtab))
9172 /* no valid window in current tabpage */
9173 close_tabpage(curtab);
9174
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009175 restore_snapshot(SNAP_AUCMD_IDX, FALSE);
9176 (void)win_comp_pos(); /* recompute window positions */
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00009177 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009178
9179 if (win_valid(aco->save_curwin))
9180 curwin = aco->save_curwin;
9181 else
9182 /* Hmm, original window disappeared. Just use the first one. */
9183 curwin = firstwin;
Bram Moolenaar4033c552017-09-16 20:54:51 +02009184#ifdef FEAT_EVAL
Bram Moolenaar429fa852013-04-15 12:27:36 +02009185 vars_clear(&aucmd_win->w_vars->dv_hashtab); /* free all w: variables */
9186 hash_init(&aucmd_win->w_vars->dv_hashtab); /* re-use the hashtab */
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009187#endif
9188 curbuf = curwin->w_buffer;
9189
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009190 vim_free(globaldir);
9191 globaldir = aco->globaldir;
9192
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009193 /* the buffer contents may have changed */
9194 check_cursor();
9195 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
9196 {
9197 curwin->w_topline = curbuf->b_ml.ml_line_count;
9198#ifdef FEAT_DIFF
9199 curwin->w_topfill = 0;
9200#endif
9201 }
9202#if defined(FEAT_GUI)
9203 /* Hide the scrollbars from the aucmd_win and update. */
9204 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_LEFT], FALSE);
9205 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_RIGHT], FALSE);
9206 gui_may_update_scrollbars();
9207#endif
9208 }
9209 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00009210 {
9211 /* restore curwin */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009212 if (win_valid(aco->save_curwin))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009213 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009214 /* Restore the buffer which was previously edited by curwin, if
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009215 * it was changed, we are still the same window and the buffer is
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009216 * valid. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009217 if (curwin == aco->new_curwin
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009218 && curbuf != aco->new_curbuf.br_buf
9219 && bufref_valid(&aco->new_curbuf)
9220 && aco->new_curbuf.br_buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009221 {
Bram Moolenaar7da9c372012-04-30 17:04:52 +02009222# if defined(FEAT_SYN_HL) || defined(FEAT_SPELL)
9223 if (curwin->w_s == &curbuf->b_s)
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009224 curwin->w_s = &aco->new_curbuf.br_buf->b_s;
Bram Moolenaar7da9c372012-04-30 17:04:52 +02009225# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009226 --curbuf->b_nwindows;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009227 curbuf = aco->new_curbuf.br_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009228 curwin->w_buffer = curbuf;
9229 ++curbuf->b_nwindows;
9230 }
9231
9232 curwin = aco->save_curwin;
9233 curbuf = curwin->w_buffer;
Bram Moolenaar371932a2014-09-09 16:59:38 +02009234 /* In case the autocommand move the cursor to a position that that
9235 * not exist in curbuf. */
9236 check_cursor();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009237 }
9238 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009239}
9240
9241static int autocmd_nested = FALSE;
9242
9243/*
9244 * Execute autocommands for "event" and file name "fname".
9245 * Return TRUE if some commands were executed.
9246 */
9247 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009248apply_autocmds(
9249 event_T event,
9250 char_u *fname, /* NULL or empty means use actual file name */
9251 char_u *fname_io, /* fname to use for <afile> on cmdline */
9252 int force, /* when TRUE, ignore autocmd_busy */
9253 buf_T *buf) /* buffer for <abuf> */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009254{
9255 return apply_autocmds_group(event, fname, fname_io, force,
9256 AUGROUP_ALL, buf, NULL);
9257}
9258
9259/*
9260 * Like apply_autocmds(), but with extra "eap" argument. This takes care of
9261 * setting v:filearg.
9262 */
9263 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009264apply_autocmds_exarg(
9265 event_T event,
9266 char_u *fname,
9267 char_u *fname_io,
9268 int force,
9269 buf_T *buf,
9270 exarg_T *eap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009271{
9272 return apply_autocmds_group(event, fname, fname_io, force,
9273 AUGROUP_ALL, buf, eap);
9274}
9275
9276/*
9277 * Like apply_autocmds(), but handles the caller's retval. If the script
9278 * processing is being aborted or if retval is FAIL when inside a try
9279 * conditional, no autocommands are executed. If otherwise the autocommands
9280 * cause the script to be aborted, retval is set to FAIL.
9281 */
9282 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009283apply_autocmds_retval(
9284 event_T event,
9285 char_u *fname, /* NULL or empty means use actual file name */
9286 char_u *fname_io, /* fname to use for <afile> on cmdline */
9287 int force, /* when TRUE, ignore autocmd_busy */
9288 buf_T *buf, /* buffer for <abuf> */
9289 int *retval) /* pointer to caller's retval */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009290{
9291 int did_cmd;
9292
Bram Moolenaar1e015462005-09-25 22:16:38 +00009293#ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00009294 if (should_abort(*retval))
9295 return FALSE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00009296#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009297
9298 did_cmd = apply_autocmds_group(event, fname, fname_io, force,
9299 AUGROUP_ALL, buf, NULL);
Bram Moolenaar1e015462005-09-25 22:16:38 +00009300 if (did_cmd
9301#ifdef FEAT_EVAL
9302 && aborting()
9303#endif
9304 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00009305 *retval = FAIL;
9306 return did_cmd;
9307}
9308
Bram Moolenaard35f9712005-12-18 22:02:33 +00009309/*
9310 * Return TRUE when there is a CursorHold autocommand defined.
9311 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009312 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009313has_cursorhold(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009314{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009315 return (first_autopat[(int)(get_real_state() == NORMAL_BUSY
9316 ? EVENT_CURSORHOLD : EVENT_CURSORHOLDI)] != NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009317}
Bram Moolenaard35f9712005-12-18 22:02:33 +00009318
9319/*
9320 * Return TRUE if the CursorHold event can be triggered.
9321 */
9322 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009323trigger_cursorhold(void)
Bram Moolenaard35f9712005-12-18 22:02:33 +00009324{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009325 int state;
9326
Bram Moolenaar05334432011-07-20 18:29:39 +02009327 if (!did_cursorhold
9328 && has_cursorhold()
9329 && !Recording
9330 && typebuf.tb_len == 0
Bram Moolenaard29a9ee2006-09-14 09:07:34 +00009331#ifdef FEAT_INS_EXPAND
9332 && !ins_compl_active()
9333#endif
9334 )
Bram Moolenaar754b5602006-02-09 23:53:20 +00009335 {
9336 state = get_real_state();
9337 if (state == NORMAL_BUSY || (state & INSERT) != 0)
9338 return TRUE;
9339 }
9340 return FALSE;
Bram Moolenaard35f9712005-12-18 22:02:33 +00009341}
Bram Moolenaar754b5602006-02-09 23:53:20 +00009342
9343/*
9344 * Return TRUE when there is a CursorMoved autocommand defined.
9345 */
9346 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009347has_cursormoved(void)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009348{
9349 return (first_autopat[(int)EVENT_CURSORMOVED] != NULL);
9350}
9351
9352/*
9353 * Return TRUE when there is a CursorMovedI autocommand defined.
9354 */
9355 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009356has_cursormovedI(void)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009357{
9358 return (first_autopat[(int)EVENT_CURSORMOVEDI] != NULL);
9359}
Bram Moolenaar071d4272004-06-13 20:20:40 +00009360
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009361/*
Bram Moolenaar186628f2013-03-19 13:33:23 +01009362 * Return TRUE when there is a TextChanged autocommand defined.
9363 */
9364 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009365has_textchanged(void)
Bram Moolenaar186628f2013-03-19 13:33:23 +01009366{
9367 return (first_autopat[(int)EVENT_TEXTCHANGED] != NULL);
9368}
9369
9370/*
9371 * Return TRUE when there is a TextChangedI autocommand defined.
9372 */
9373 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009374has_textchangedI(void)
Bram Moolenaar186628f2013-03-19 13:33:23 +01009375{
9376 return (first_autopat[(int)EVENT_TEXTCHANGEDI] != NULL);
9377}
9378
9379/*
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009380 * Return TRUE when there is an InsertCharPre autocommand defined.
9381 */
9382 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009383has_insertcharpre(void)
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009384{
9385 return (first_autopat[(int)EVENT_INSERTCHARPRE] != NULL);
9386}
9387
Bram Moolenaard5005162014-08-22 23:05:54 +02009388/*
9389 * Return TRUE when there is an CmdUndefined autocommand defined.
9390 */
9391 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009392has_cmdundefined(void)
Bram Moolenaard5005162014-08-22 23:05:54 +02009393{
9394 return (first_autopat[(int)EVENT_CMDUNDEFINED] != NULL);
9395}
9396
9397/*
9398 * Return TRUE when there is an FuncUndefined autocommand defined.
9399 */
9400 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009401has_funcundefined(void)
Bram Moolenaard5005162014-08-22 23:05:54 +02009402{
9403 return (first_autopat[(int)EVENT_FUNCUNDEFINED] != NULL);
9404}
9405
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009406/*
Bram Moolenaar7e1652c2017-12-16 18:27:02 +01009407 * Return TRUE when there is a TextYankPost autocommand defined.
9408 */
9409 int
9410has_textyankpost(void)
9411{
9412 return (first_autopat[(int)EVENT_TEXTYANKPOST] != NULL);
9413}
9414
9415/*
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009416 * Execute autocommands for "event" and file name "fname".
9417 * Return TRUE if some commands were executed.
9418 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009419 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009420apply_autocmds_group(
9421 event_T event,
9422 char_u *fname, /* NULL or empty means use actual file name */
9423 char_u *fname_io, /* fname to use for <afile> on cmdline, NULL means
Bram Moolenaar071d4272004-06-13 20:20:40 +00009424 use fname */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009425 int force, /* when TRUE, ignore autocmd_busy */
9426 int group, /* group ID, or AUGROUP_ALL */
9427 buf_T *buf, /* buffer for <abuf> */
9428 exarg_T *eap) /* command arguments */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009429{
9430 char_u *sfname = NULL; /* short file name */
9431 char_u *tail;
9432 int save_changed;
9433 buf_T *old_curbuf;
9434 int retval = FALSE;
9435 char_u *save_sourcing_name;
9436 linenr_T save_sourcing_lnum;
9437 char_u *save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009438 int save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009439 int save_autocmd_bufnr;
9440 char_u *save_autocmd_match;
9441 int save_autocmd_busy;
9442 int save_autocmd_nested;
9443 static int nesting = 0;
9444 AutoPatCmd patcmd;
9445 AutoPat *ap;
9446#ifdef FEAT_EVAL
9447 scid_T save_current_SID;
9448 void *save_funccalp;
9449 char_u *save_cmdarg;
9450 long save_cmdbang;
9451#endif
9452 static int filechangeshell_busy = FALSE;
Bram Moolenaar05159a02005-02-26 23:04:13 +00009453#ifdef FEAT_PROFILE
9454 proftime_T wait_time;
9455#endif
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009456 int did_save_redobuff = FALSE;
Bram Moolenaard4863aa2017-04-07 19:50:12 +02009457 save_redo_T save_redo;
Bram Moolenaarc9e9c712017-11-09 12:29:35 +01009458 int save_KeyTyped = KeyTyped;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009459
9460 /*
9461 * Quickly return if there are no autocommands for this event or
9462 * autocommands are blocked.
9463 */
Bram Moolenaarfaf29d72017-07-09 11:07:16 +02009464 if (event == NUM_EVENTS || first_autopat[(int)event] == NULL
9465 || autocmd_blocked > 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009466 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009467
9468 /*
9469 * When autocommands are busy, new autocommands are only executed when
9470 * explicitly enabled with the "nested" flag.
9471 */
9472 if (autocmd_busy && !(force || autocmd_nested))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009473 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009474
9475#ifdef FEAT_EVAL
9476 /*
Bram Moolenaar7263a772007-05-10 17:35:54 +00009477 * Quickly return when immediately aborting on error, or when an interrupt
Bram Moolenaar071d4272004-06-13 20:20:40 +00009478 * occurred or an exception was thrown but not caught.
9479 */
9480 if (aborting())
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009481 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009482#endif
9483
9484 /*
9485 * FileChangedShell never nests, because it can create an endless loop.
9486 */
Bram Moolenaar56718732006-03-15 22:53:57 +00009487 if (filechangeshell_busy && (event == EVENT_FILECHANGEDSHELL
9488 || event == EVENT_FILECHANGEDSHELLPOST))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009489 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009490
9491 /*
9492 * Ignore events in 'eventignore'.
9493 */
9494 if (event_ignored(event))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009495 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009496
9497 /*
9498 * Allow nesting of autocommands, but restrict the depth, because it's
9499 * possible to create an endless loop.
9500 */
9501 if (nesting == 10)
9502 {
9503 EMSG(_("E218: autocommand nesting too deep"));
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009504 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009505 }
9506
9507 /*
9508 * Check if these autocommands are disabled. Used when doing ":all" or
9509 * ":ball".
9510 */
9511 if ( (autocmd_no_enter
9512 && (event == EVENT_WINENTER || event == EVENT_BUFENTER))
9513 || (autocmd_no_leave
9514 && (event == EVENT_WINLEAVE || event == EVENT_BUFLEAVE)))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009515 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009516
9517 /*
9518 * Save the autocmd_* variables and info about the current buffer.
9519 */
9520 save_autocmd_fname = autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009521 save_autocmd_fname_full = autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009522 save_autocmd_bufnr = autocmd_bufnr;
9523 save_autocmd_match = autocmd_match;
9524 save_autocmd_busy = autocmd_busy;
9525 save_autocmd_nested = autocmd_nested;
9526 save_changed = curbuf->b_changed;
9527 old_curbuf = curbuf;
9528
9529 /*
9530 * Set the file name to be used for <afile>.
Bram Moolenaara0174af2008-01-02 20:08:25 +00009531 * Make a copy to avoid that changing a buffer name or directory makes it
9532 * invalid.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009533 */
9534 if (fname_io == NULL)
9535 {
Bram Moolenaar53744302015-07-17 17:38:22 +02009536 if (event == EVENT_COLORSCHEME || event == EVENT_OPTIONSET)
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009537 autocmd_fname = NULL;
Bram Moolenaarfaf29d72017-07-09 11:07:16 +02009538 else if (fname != NULL && !ends_excmd(*fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009539 autocmd_fname = fname;
9540 else if (buf != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009541 autocmd_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009542 else
9543 autocmd_fname = NULL;
9544 }
9545 else
9546 autocmd_fname = fname_io;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009547 if (autocmd_fname != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009548 autocmd_fname = vim_strsave(autocmd_fname);
9549 autocmd_fname_full = FALSE; /* call FullName_save() later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009550
9551 /*
9552 * Set the buffer number to be used for <abuf>.
9553 */
9554 if (buf == NULL)
9555 autocmd_bufnr = 0;
9556 else
9557 autocmd_bufnr = buf->b_fnum;
9558
9559 /*
9560 * When the file name is NULL or empty, use the file name of buffer "buf".
9561 * Always use the full path of the file name to match with, in case
9562 * "allow_dirs" is set.
9563 */
9564 if (fname == NULL || *fname == NUL)
9565 {
9566 if (buf == NULL)
9567 fname = NULL;
9568 else
9569 {
9570#ifdef FEAT_SYN_HL
9571 if (event == EVENT_SYNTAX)
9572 fname = buf->b_p_syn;
9573 else
9574#endif
9575 if (event == EVENT_FILETYPE)
9576 fname = buf->b_p_ft;
9577 else
9578 {
9579 if (buf->b_sfname != NULL)
9580 sfname = vim_strsave(buf->b_sfname);
9581 fname = buf->b_ffname;
9582 }
9583 }
9584 if (fname == NULL)
9585 fname = (char_u *)"";
9586 fname = vim_strsave(fname); /* make a copy, so we can change it */
9587 }
9588 else
9589 {
9590 sfname = vim_strsave(fname);
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009591 /* Don't try expanding FileType, Syntax, FuncUndefined, WindowID,
Bram Moolenaarb7407d32018-02-03 17:36:27 +01009592 * ColorScheme, QuickFixCmd* or DirChanged */
Bram Moolenaar7c626922005-02-07 22:01:03 +00009593 if (event == EVENT_FILETYPE
9594 || event == EVENT_SYNTAX
Bram Moolenaar5135d462009-04-29 16:03:38 +00009595 || event == EVENT_FUNCUNDEFINED
Bram Moolenaar7c626922005-02-07 22:01:03 +00009596 || event == EVENT_REMOTEREPLY
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00009597 || event == EVENT_SPELLFILEMISSING
Bram Moolenaar7c626922005-02-07 22:01:03 +00009598 || event == EVENT_QUICKFIXCMDPRE
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009599 || event == EVENT_COLORSCHEME
Bram Moolenaar53744302015-07-17 17:38:22 +02009600 || event == EVENT_OPTIONSET
Bram Moolenaarb7407d32018-02-03 17:36:27 +01009601 || event == EVENT_QUICKFIXCMDPOST
9602 || event == EVENT_DIRCHANGED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009603 fname = vim_strsave(fname);
9604 else
9605 fname = FullName_save(fname, FALSE);
9606 }
9607 if (fname == NULL) /* out of memory */
9608 {
9609 vim_free(sfname);
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009610 retval = FALSE;
9611 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009612 }
9613
9614#ifdef BACKSLASH_IN_FILENAME
9615 /*
9616 * Replace all backslashes with forward slashes. This makes the
9617 * autocommand patterns portable between Unix and MS-DOS.
9618 */
9619 if (sfname != NULL)
9620 forward_slash(sfname);
9621 forward_slash(fname);
9622#endif
9623
9624#ifdef VMS
9625 /* remove version for correct match */
9626 if (sfname != NULL)
9627 vms_remove_version(sfname);
9628 vms_remove_version(fname);
9629#endif
9630
9631 /*
9632 * Set the name to be used for <amatch>.
9633 */
9634 autocmd_match = fname;
9635
9636
9637 /* Don't redraw while doing auto commands. */
9638 ++RedrawingDisabled;
9639 save_sourcing_name = sourcing_name;
9640 sourcing_name = NULL; /* don't free this one */
9641 save_sourcing_lnum = sourcing_lnum;
9642 sourcing_lnum = 0; /* no line number here */
9643
9644#ifdef FEAT_EVAL
9645 save_current_SID = current_SID;
9646
Bram Moolenaar05159a02005-02-26 23:04:13 +00009647# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009648 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009649 prof_child_enter(&wait_time); /* doesn't count for the caller itself */
9650# endif
9651
Bram Moolenaar071d4272004-06-13 20:20:40 +00009652 /* Don't use local function variables, if called from a function */
9653 save_funccalp = save_funccal();
9654#endif
9655
9656 /*
9657 * When starting to execute autocommands, save the search patterns.
9658 */
9659 if (!autocmd_busy)
9660 {
9661 save_search_patterns();
Bram Moolenaar20ad69c2015-12-03 13:52:52 +01009662#ifdef FEAT_INS_EXPAND
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009663 if (!ins_compl_active())
Bram Moolenaar20ad69c2015-12-03 13:52:52 +01009664#endif
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009665 {
Bram Moolenaard4863aa2017-04-07 19:50:12 +02009666 saveRedobuff(&save_redo);
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009667 did_save_redobuff = TRUE;
9668 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009669 did_filetype = keep_filetype;
9670 }
9671
9672 /*
9673 * Note that we are applying autocmds. Some commands need to know.
9674 */
9675 autocmd_busy = TRUE;
9676 filechangeshell_busy = (event == EVENT_FILECHANGEDSHELL);
9677 ++nesting; /* see matching decrement below */
9678
9679 /* Remember that FileType was triggered. Used for did_filetype(). */
9680 if (event == EVENT_FILETYPE)
9681 did_filetype = TRUE;
9682
9683 tail = gettail(fname);
9684
9685 /* Find first autocommand that matches */
9686 patcmd.curpat = first_autopat[(int)event];
9687 patcmd.nextcmd = NULL;
9688 patcmd.group = group;
9689 patcmd.fname = fname;
9690 patcmd.sfname = sfname;
9691 patcmd.tail = tail;
9692 patcmd.event = event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009693 patcmd.arg_bufnr = autocmd_bufnr;
9694 patcmd.next = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009695 auto_next_pat(&patcmd, FALSE);
9696
9697 /* found one, start executing the autocommands */
9698 if (patcmd.curpat != NULL)
9699 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009700 /* add to active_apc_list */
9701 patcmd.next = active_apc_list;
9702 active_apc_list = &patcmd;
9703
Bram Moolenaar071d4272004-06-13 20:20:40 +00009704#ifdef FEAT_EVAL
9705 /* set v:cmdarg (only when there is a matching pattern) */
Bram Moolenaar22fcfad2016-07-01 18:17:26 +02009706 save_cmdbang = (long)get_vim_var_nr(VV_CMDBANG);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009707 if (eap != NULL)
9708 {
9709 save_cmdarg = set_cmdarg(eap, NULL);
9710 set_vim_var_nr(VV_CMDBANG, (long)eap->forceit);
9711 }
9712 else
9713 save_cmdarg = NULL; /* avoid gcc warning */
9714#endif
9715 retval = TRUE;
9716 /* mark the last pattern, to avoid an endless loop when more patterns
9717 * are added when executing autocommands */
9718 for (ap = patcmd.curpat; ap->next != NULL; ap = ap->next)
9719 ap->last = FALSE;
9720 ap->last = TRUE;
9721 check_lnums(TRUE); /* make sure cursor and topline are valid */
9722 do_cmdline(NULL, getnextac, (void *)&patcmd,
9723 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
9724#ifdef FEAT_EVAL
9725 if (eap != NULL)
9726 {
9727 (void)set_cmdarg(NULL, save_cmdarg);
9728 set_vim_var_nr(VV_CMDBANG, save_cmdbang);
9729 }
9730#endif
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009731 /* delete from active_apc_list */
9732 if (active_apc_list == &patcmd) /* just in case */
9733 active_apc_list = patcmd.next;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009734 }
9735
9736 --RedrawingDisabled;
9737 autocmd_busy = save_autocmd_busy;
9738 filechangeshell_busy = FALSE;
9739 autocmd_nested = save_autocmd_nested;
9740 vim_free(sourcing_name);
9741 sourcing_name = save_sourcing_name;
9742 sourcing_lnum = save_sourcing_lnum;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009743 vim_free(autocmd_fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009744 autocmd_fname = save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009745 autocmd_fname_full = save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009746 autocmd_bufnr = save_autocmd_bufnr;
9747 autocmd_match = save_autocmd_match;
9748#ifdef FEAT_EVAL
9749 current_SID = save_current_SID;
9750 restore_funccal(save_funccalp);
Bram Moolenaar05159a02005-02-26 23:04:13 +00009751# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009752 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009753 prof_child_exit(&wait_time);
9754# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009755#endif
Bram Moolenaarc9e9c712017-11-09 12:29:35 +01009756 KeyTyped = save_KeyTyped;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009757 vim_free(fname);
9758 vim_free(sfname);
9759 --nesting; /* see matching increment above */
9760
9761 /*
9762 * When stopping to execute autocommands, restore the search patterns and
Bram Moolenaar3be85852014-06-12 14:01:31 +02009763 * the redo buffer. Free any buffers in the au_pending_free_buf list and
9764 * free any windows in the au_pending_free_win list.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009765 */
9766 if (!autocmd_busy)
9767 {
9768 restore_search_patterns();
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009769 if (did_save_redobuff)
Bram Moolenaard4863aa2017-04-07 19:50:12 +02009770 restoreRedobuff(&save_redo);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009771 did_filetype = FALSE;
Bram Moolenaar4c7ab1b2014-04-06 20:45:43 +02009772 while (au_pending_free_buf != NULL)
9773 {
9774 buf_T *b = au_pending_free_buf->b_next;
9775 vim_free(au_pending_free_buf);
9776 au_pending_free_buf = b;
9777 }
Bram Moolenaar3be85852014-06-12 14:01:31 +02009778 while (au_pending_free_win != NULL)
9779 {
9780 win_T *w = au_pending_free_win->w_next;
9781 vim_free(au_pending_free_win);
9782 au_pending_free_win = w;
9783 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009784 }
9785
9786 /*
9787 * Some events don't set or reset the Changed flag.
9788 * Check if still in the same buffer!
9789 */
9790 if (curbuf == old_curbuf
9791 && (event == EVENT_BUFREADPOST
9792 || event == EVENT_BUFWRITEPOST
9793 || event == EVENT_FILEAPPENDPOST
9794 || event == EVENT_VIMLEAVE
9795 || event == EVENT_VIMLEAVEPRE))
9796 {
9797#ifdef FEAT_TITLE
9798 if (curbuf->b_changed != save_changed)
9799 need_maketitle = TRUE;
9800#endif
9801 curbuf->b_changed = save_changed;
9802 }
9803
9804 au_cleanup(); /* may really delete removed patterns/commands now */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009805
9806BYPASS_AU:
9807 /* When wiping out a buffer make sure all its buffer-local autocommands
9808 * are deleted. */
9809 if (event == EVENT_BUFWIPEOUT && buf != NULL)
9810 aubuflocal_remove(buf);
9811
Bram Moolenaarc3691332016-04-20 12:49:49 +02009812 if (retval == OK && event == EVENT_FILETYPE)
9813 au_did_filetype = TRUE;
9814
Bram Moolenaar071d4272004-06-13 20:20:40 +00009815 return retval;
9816}
9817
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009818# ifdef FEAT_EVAL
9819static char_u *old_termresponse = NULL;
9820# endif
9821
9822/*
9823 * Block triggering autocommands until unblock_autocmd() is called.
9824 * Can be used recursively, so long as it's symmetric.
9825 */
9826 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009827block_autocmds(void)
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009828{
9829# ifdef FEAT_EVAL
9830 /* Remember the value of v:termresponse. */
9831 if (autocmd_blocked == 0)
9832 old_termresponse = get_vim_var_str(VV_TERMRESPONSE);
9833# endif
9834 ++autocmd_blocked;
9835}
9836
9837 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009838unblock_autocmds(void)
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009839{
9840 --autocmd_blocked;
9841
9842# ifdef FEAT_EVAL
9843 /* When v:termresponse was set while autocommands were blocked, trigger
9844 * the autocommands now. Esp. useful when executing a shell command
9845 * during startup (vimdiff). */
9846 if (autocmd_blocked == 0
9847 && get_vim_var_str(VV_TERMRESPONSE) != old_termresponse)
9848 apply_autocmds(EVENT_TERMRESPONSE, NULL, NULL, FALSE, curbuf);
9849# endif
9850}
9851
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009852 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009853is_autocmd_blocked(void)
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009854{
9855 return autocmd_blocked != 0;
9856}
9857
Bram Moolenaar071d4272004-06-13 20:20:40 +00009858/*
9859 * Find next autocommand pattern that matches.
9860 */
9861 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009862auto_next_pat(
9863 AutoPatCmd *apc,
9864 int stop_at_last) /* stop when 'last' flag is set */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009865{
9866 AutoPat *ap;
9867 AutoCmd *cp;
9868 char_u *name;
9869 char *s;
9870
9871 vim_free(sourcing_name);
9872 sourcing_name = NULL;
9873
9874 for (ap = apc->curpat; ap != NULL && !got_int; ap = ap->next)
9875 {
9876 apc->curpat = NULL;
9877
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009878 /* Only use a pattern when it has not been removed, has commands and
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009879 * the group matches. For buffer-local autocommands only check the
9880 * buffer number. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009881 if (ap->pat != NULL && ap->cmds != NULL
9882 && (apc->group == AUGROUP_ALL || apc->group == ap->group))
9883 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009884 /* execution-condition */
9885 if (ap->buflocal_nr == 0
Bram Moolenaardffa5b82014-11-19 16:38:07 +01009886 ? (match_file_pat(NULL, &ap->reg_prog, apc->fname,
Bram Moolenaar748bf032005-02-02 23:04:36 +00009887 apc->sfname, apc->tail, ap->allow_dirs))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009888 : ap->buflocal_nr == apc->arg_bufnr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009889 {
9890 name = event_nr2name(apc->event);
9891 s = _("%s Auto commands for \"%s\"");
9892 sourcing_name = alloc((unsigned)(STRLEN(s)
9893 + STRLEN(name) + ap->patlen + 1));
9894 if (sourcing_name != NULL)
9895 {
9896 sprintf((char *)sourcing_name, s,
9897 (char *)name, (char *)ap->pat);
9898 if (p_verbose >= 8)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009899 {
9900 verbose_enter();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009901 smsg((char_u *)_("Executing %s"), sourcing_name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009902 verbose_leave();
9903 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009904 }
9905
9906 apc->curpat = ap;
9907 apc->nextcmd = ap->cmds;
9908 /* mark last command */
9909 for (cp = ap->cmds; cp->next != NULL; cp = cp->next)
9910 cp->last = FALSE;
9911 cp->last = TRUE;
9912 }
9913 line_breakcheck();
9914 if (apc->curpat != NULL) /* found a match */
9915 break;
9916 }
9917 if (stop_at_last && ap->last)
9918 break;
9919 }
9920}
9921
9922/*
9923 * Get next autocommand command.
9924 * Called by do_cmdline() to get the next line for ":if".
9925 * Returns allocated string, or NULL for end of autocommands.
9926 */
Bram Moolenaar21691f82012-12-05 19:13:18 +01009927 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009928getnextac(int c UNUSED, void *cookie, int indent UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009929{
9930 AutoPatCmd *acp = (AutoPatCmd *)cookie;
9931 char_u *retval;
9932 AutoCmd *ac;
9933
9934 /* Can be called again after returning the last line. */
9935 if (acp->curpat == NULL)
9936 return NULL;
9937
9938 /* repeat until we find an autocommand to execute */
9939 for (;;)
9940 {
9941 /* skip removed commands */
9942 while (acp->nextcmd != NULL && acp->nextcmd->cmd == NULL)
9943 if (acp->nextcmd->last)
9944 acp->nextcmd = NULL;
9945 else
9946 acp->nextcmd = acp->nextcmd->next;
9947
9948 if (acp->nextcmd != NULL)
9949 break;
9950
9951 /* at end of commands, find next pattern that matches */
9952 if (acp->curpat->last)
9953 acp->curpat = NULL;
9954 else
9955 acp->curpat = acp->curpat->next;
9956 if (acp->curpat != NULL)
9957 auto_next_pat(acp, TRUE);
9958 if (acp->curpat == NULL)
9959 return NULL;
9960 }
9961
9962 ac = acp->nextcmd;
9963
9964 if (p_verbose >= 9)
9965 {
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009966 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009967 smsg((char_u *)_("autocommand %s"), ac->cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009968 msg_puts((char_u *)"\n"); /* don't overwrite this either */
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009969 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009970 }
9971 retval = vim_strsave(ac->cmd);
9972 autocmd_nested = ac->nested;
9973#ifdef FEAT_EVAL
9974 current_SID = ac->scriptID;
9975#endif
9976 if (ac->last)
9977 acp->nextcmd = NULL;
9978 else
9979 acp->nextcmd = ac->next;
9980 return retval;
9981}
9982
9983/*
9984 * Return TRUE if there is a matching autocommand for "fname".
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009985 * To account for buffer-local autocommands, function needs to know
9986 * in which buffer the file will be opened.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009987 */
9988 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009989has_autocmd(event_T event, char_u *sfname, buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009990{
9991 AutoPat *ap;
9992 char_u *fname;
9993 char_u *tail = gettail(sfname);
9994 int retval = FALSE;
9995
9996 fname = FullName_save(sfname, FALSE);
9997 if (fname == NULL)
9998 return FALSE;
9999
10000#ifdef BACKSLASH_IN_FILENAME
10001 /*
10002 * Replace all backslashes with forward slashes. This makes the
10003 * autocommand patterns portable between Unix and MS-DOS.
10004 */
10005 sfname = vim_strsave(sfname);
10006 if (sfname != NULL)
10007 forward_slash(sfname);
10008 forward_slash(fname);
10009#endif
10010
10011 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
10012 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaarc9b4b052006-04-30 18:54:39 +000010013 && (ap->buflocal_nr == 0
Bram Moolenaardffa5b82014-11-19 16:38:07 +010010014 ? match_file_pat(NULL, &ap->reg_prog,
Bram Moolenaar748bf032005-02-02 23:04:36 +000010015 fname, sfname, tail, ap->allow_dirs)
Bram Moolenaarc9b4b052006-04-30 18:54:39 +000010016 : buf != NULL && ap->buflocal_nr == buf->b_fnum
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010017 ))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010018 {
10019 retval = TRUE;
10020 break;
10021 }
10022
10023 vim_free(fname);
10024#ifdef BACKSLASH_IN_FILENAME
10025 vim_free(sfname);
10026#endif
10027
10028 return retval;
10029}
10030
10031#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
10032/*
10033 * Function given to ExpandGeneric() to obtain the list of autocommand group
10034 * names.
10035 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010036 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010037get_augroup_name(expand_T *xp UNUSED, int idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010038{
10039 if (idx == augroups.ga_len) /* add "END" add the end */
10040 return (char_u *)"END";
10041 if (idx >= augroups.ga_len) /* end of list */
10042 return NULL;
Bram Moolenaarb62cc362016-09-03 16:43:53 +020010043 if (AUGROUP_NAME(idx) == NULL || AUGROUP_NAME(idx) == get_deleted_augroup())
Bram Moolenaarf2c4c392016-07-29 20:50:24 +020010044 /* skip deleted entries */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010045 return (char_u *)"";
10046 return AUGROUP_NAME(idx); /* return a name */
10047}
10048
10049static int include_groups = FALSE;
10050
10051 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010052set_context_in_autocmd(
10053 expand_T *xp,
10054 char_u *arg,
10055 int doautocmd) /* TRUE for :doauto*, FALSE for :autocmd */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010056{
10057 char_u *p;
10058 int group;
10059
10060 /* check for a group name, skip it if present */
10061 include_groups = FALSE;
10062 p = arg;
10063 group = au_get_grouparg(&arg);
10064 if (group == AUGROUP_ERROR)
10065 return NULL;
10066 /* If there only is a group name that's what we expand. */
Bram Moolenaar1c465442017-03-12 20:10:05 +010010067 if (*arg == NUL && group != AUGROUP_ALL && !VIM_ISWHITE(arg[-1]))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010068 {
10069 arg = p;
10070 group = AUGROUP_ALL;
10071 }
10072
10073 /* skip over event name */
Bram Moolenaar1c465442017-03-12 20:10:05 +010010074 for (p = arg; *p != NUL && !VIM_ISWHITE(*p); ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010075 if (*p == ',')
10076 arg = p + 1;
10077 if (*p == NUL)
10078 {
10079 if (group == AUGROUP_ALL)
10080 include_groups = TRUE;
10081 xp->xp_context = EXPAND_EVENTS; /* expand event name */
10082 xp->xp_pattern = arg;
10083 return NULL;
10084 }
10085
10086 /* skip over pattern */
10087 arg = skipwhite(p);
Bram Moolenaar1c465442017-03-12 20:10:05 +010010088 while (*arg && (!VIM_ISWHITE(*arg) || arg[-1] == '\\'))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010089 arg++;
10090 if (*arg)
10091 return arg; /* expand (next) command */
10092
10093 if (doautocmd)
10094 xp->xp_context = EXPAND_FILES; /* expand file names */
10095 else
10096 xp->xp_context = EXPAND_NOTHING; /* pattern is not expanded */
10097 return NULL;
10098}
10099
10100/*
10101 * Function given to ExpandGeneric() to obtain the list of event names.
10102 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010103 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010104get_event_name(expand_T *xp UNUSED, int idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010105{
10106 if (idx < augroups.ga_len) /* First list group names, if wanted */
10107 {
Bram Moolenaarf2c4c392016-07-29 20:50:24 +020010108 if (!include_groups || AUGROUP_NAME(idx) == NULL
Bram Moolenaarb62cc362016-09-03 16:43:53 +020010109 || AUGROUP_NAME(idx) == get_deleted_augroup())
Bram Moolenaar071d4272004-06-13 20:20:40 +000010110 return (char_u *)""; /* skip deleted entries */
10111 return AUGROUP_NAME(idx); /* return a name */
10112 }
10113 return (char_u *)event_names[idx - augroups.ga_len].name;
10114}
10115
10116#endif /* FEAT_CMDL_COMPL */
10117
10118/*
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010119 * Return TRUE if autocmd is supported.
10120 */
10121 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010122autocmd_supported(char_u *name)
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010123{
10124 char_u *p;
10125
10126 return (event_name2nr(name, &p) != NUM_EVENTS);
10127}
10128
10129/*
Bram Moolenaar195d6352005-12-19 22:08:24 +000010130 * Return TRUE if an autocommand is defined for a group, event and
10131 * pattern: The group can be omitted to accept any group. "event" and "pattern"
10132 * can be NULL to accept any event and pattern. "pattern" can be NULL to accept
10133 * any pattern. Buffer-local patterns <buffer> or <buffer=N> are accepted.
10134 * Used for:
10135 * exists("#Group") or
10136 * exists("#Group#Event") or
10137 * exists("#Group#Event#pat") or
10138 * exists("#Event") or
10139 * exists("#Event#pat")
Bram Moolenaar071d4272004-06-13 20:20:40 +000010140 */
10141 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010142au_exists(char_u *arg)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010143{
Bram Moolenaar195d6352005-12-19 22:08:24 +000010144 char_u *arg_save;
10145 char_u *pattern = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010146 char_u *event_name;
10147 char_u *p;
Bram Moolenaar754b5602006-02-09 23:53:20 +000010148 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010149 AutoPat *ap;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010150 buf_T *buflocal_buf = NULL;
Bram Moolenaar195d6352005-12-19 22:08:24 +000010151 int group;
10152 int retval = FALSE;
10153
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010154 /* Make a copy so that we can change the '#' chars to a NUL. */
Bram Moolenaar195d6352005-12-19 22:08:24 +000010155 arg_save = vim_strsave(arg);
10156 if (arg_save == NULL)
10157 return FALSE;
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010158 p = vim_strchr(arg_save, '#');
Bram Moolenaar195d6352005-12-19 22:08:24 +000010159 if (p != NULL)
10160 *p++ = NUL;
10161
10162 /* First, look for an autocmd group name */
10163 group = au_find_group(arg_save);
10164 if (group == AUGROUP_ERROR)
10165 {
10166 /* Didn't match a group name, assume the first argument is an event. */
10167 group = AUGROUP_ALL;
10168 event_name = arg_save;
10169 }
10170 else
10171 {
10172 if (p == NULL)
10173 {
10174 /* "Group": group name is present and it's recognized */
10175 retval = TRUE;
10176 goto theend;
10177 }
10178
10179 /* Must be "Group#Event" or "Group#Event#pat". */
10180 event_name = p;
10181 p = vim_strchr(event_name, '#');
10182 if (p != NULL)
10183 *p++ = NUL; /* "Group#Event#pat" */
10184 }
10185
10186 pattern = p; /* "pattern" is NULL when there is no pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010187
10188 /* find the index (enum) for the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010189 event = event_name2nr(event_name, &p);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010190
10191 /* return FALSE if the event name is not recognized */
Bram Moolenaar195d6352005-12-19 22:08:24 +000010192 if (event == NUM_EVENTS)
10193 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010194
10195 /* Find the first autocommand for this event.
10196 * If there isn't any, return FALSE;
10197 * If there is one and no pattern given, return TRUE; */
10198 ap = first_autopat[(int)event];
10199 if (ap == NULL)
Bram Moolenaar195d6352005-12-19 22:08:24 +000010200 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010201
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010202 /* if pattern is "<buffer>", special handling is needed which uses curbuf */
10203 /* for pattern "<buffer=N>, fnamecmp() will work fine */
Bram Moolenaar5b7880d2009-09-11 15:24:31 +000010204 if (pattern != NULL && STRICMP(pattern, "<buffer>") == 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010205 buflocal_buf = curbuf;
10206
Bram Moolenaar071d4272004-06-13 20:20:40 +000010207 /* Check if there is an autocommand with the given pattern. */
10208 for ( ; ap != NULL; ap = ap->next)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010209 /* only use a pattern when it has not been removed and has commands. */
10210 /* For buffer-local autocommands, fnamecmp() works fine. */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010211 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaar195d6352005-12-19 22:08:24 +000010212 && (group == AUGROUP_ALL || ap->group == group)
Bram Moolenaar5b7880d2009-09-11 15:24:31 +000010213 && (pattern == NULL
10214 || (buflocal_buf == NULL
10215 ? fnamecmp(ap->pat, pattern) == 0
10216 : ap->buflocal_nr == buflocal_buf->b_fnum)))
Bram Moolenaar195d6352005-12-19 22:08:24 +000010217 {
10218 retval = TRUE;
10219 break;
10220 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010221
Bram Moolenaar195d6352005-12-19 22:08:24 +000010222theend:
10223 vim_free(arg_save);
10224 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010225}
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010226
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010227#else /* FEAT_AUTOCMD */
10228
10229/*
10230 * Prepare for executing commands for (hidden) buffer "buf".
10231 * This is the non-autocommand version, it simply saves "curbuf" and sets
10232 * "curbuf" and "curwin" to match "buf".
10233 */
10234 void
Bram Moolenaard14e00e2016-01-31 17:30:51 +010010235aucmd_prepbuf(
10236 aco_save_T *aco, /* structure to save values in */
10237 buf_T *buf) /* new curbuf */
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010238{
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010239 aco->save_curbuf = curbuf;
10240 --curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010241 curbuf = buf;
10242 curwin->w_buffer = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010243 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010244}
10245
10246/*
10247 * Restore after executing commands for a (hidden) buffer.
10248 * This is the non-autocommand version.
10249 */
10250 void
Bram Moolenaard14e00e2016-01-31 17:30:51 +010010251aucmd_restbuf(
10252 aco_save_T *aco) /* structure holding saved values */
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010253{
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010254 --curbuf->b_nwindows;
10255 curbuf = aco->save_curbuf;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010256 curwin->w_buffer = curbuf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010257 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010258}
10259
Bram Moolenaar071d4272004-06-13 20:20:40 +000010260#endif /* FEAT_AUTOCMD */
10261
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010262
Bram Moolenaar071d4272004-06-13 20:20:40 +000010263#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN) || defined(PROTO)
10264/*
Bram Moolenaar748bf032005-02-02 23:04:36 +000010265 * Try matching a filename with a "pattern" ("prog" is NULL), or use the
10266 * precompiled regprog "prog" ("pattern" is NULL). That avoids calling
10267 * vim_regcomp() often.
Bram Moolenaar071d4272004-06-13 20:20:40 +000010268 * Used for autocommands and 'wildignore'.
10269 * Returns TRUE if there is a match, FALSE otherwise.
10270 */
Bram Moolenaardffa5b82014-11-19 16:38:07 +010010271 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010272match_file_pat(
10273 char_u *pattern, /* pattern to match with */
10274 regprog_T **prog, /* pre-compiled regprog or NULL */
10275 char_u *fname, /* full path of file name */
10276 char_u *sfname, /* short file name or NULL */
10277 char_u *tail, /* tail of path */
10278 int allow_dirs) /* allow matching with dir */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010279{
10280 regmatch_T regmatch;
10281 int result = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010282
Bram Moolenaar71afbfe2013-03-19 16:49:16 +010010283 regmatch.rm_ic = p_fic; /* ignore case if 'fileignorecase' is set */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010284 if (prog != NULL)
10285 regmatch.regprog = *prog;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010286 else
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010287 regmatch.regprog = vim_regcomp(pattern, RE_MAGIC);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010288
10289 /*
10290 * Try for a match with the pattern with:
10291 * 1. the full file name, when the pattern has a '/'.
10292 * 2. the short file name, when the pattern has a '/'.
10293 * 3. the tail of the file name, when the pattern has no '/'.
10294 */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010295 if (regmatch.regprog != NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +000010296 && ((allow_dirs
10297 && (vim_regexec(&regmatch, fname, (colnr_T)0)
10298 || (sfname != NULL
10299 && vim_regexec(&regmatch, sfname, (colnr_T)0))))
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010300 || (!allow_dirs && vim_regexec(&regmatch, tail, (colnr_T)0))))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010301 result = TRUE;
10302
Bram Moolenaardffa5b82014-11-19 16:38:07 +010010303 if (prog != NULL)
10304 *prog = regmatch.regprog;
10305 else
Bram Moolenaar473de612013-06-08 18:19:48 +020010306 vim_regfree(regmatch.regprog);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010307 return result;
10308}
10309#endif
10310
10311#if defined(FEAT_WILDIGN) || defined(PROTO)
10312/*
10313 * Return TRUE if a file matches with a pattern in "list".
10314 * "list" is a comma-separated list of patterns, like 'wildignore'.
10315 * "sfname" is the short file name or NULL, "ffname" the long file name.
10316 */
10317 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010318match_file_list(char_u *list, char_u *sfname, char_u *ffname)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010319{
10320 char_u buf[100];
10321 char_u *tail;
10322 char_u *regpat;
10323 char allow_dirs;
10324 int match;
10325 char_u *p;
10326
10327 tail = gettail(sfname);
10328
10329 /* try all patterns in 'wildignore' */
10330 p = list;
10331 while (*p)
10332 {
10333 copy_option_part(&p, buf, 100, ",");
10334 regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, FALSE);
10335 if (regpat == NULL)
10336 break;
Bram Moolenaar748bf032005-02-02 23:04:36 +000010337 match = match_file_pat(regpat, NULL, ffname, sfname,
10338 tail, (int)allow_dirs);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010339 vim_free(regpat);
10340 if (match)
10341 return TRUE;
10342 }
10343 return FALSE;
10344}
10345#endif
10346
10347/*
10348 * Convert the given pattern "pat" which has shell style wildcards in it, into
10349 * a regular expression, and return the result in allocated memory. If there
10350 * is a directory path separator to be matched, then TRUE is put in
10351 * allow_dirs, otherwise FALSE is put there -- webb.
10352 * Handle backslashes before special characters, like "\*" and "\ ".
10353 *
Bram Moolenaar071d4272004-06-13 20:20:40 +000010354 * Returns NULL when out of memory.
10355 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010356 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010357file_pat_to_reg_pat(
10358 char_u *pat,
10359 char_u *pat_end, /* first char after pattern or NULL */
10360 char *allow_dirs, /* Result passed back out in here */
10361 int no_bslash UNUSED) /* Don't use a backward slash as pathsep */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010362{
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010363 int size = 2; /* '^' at start, '$' at end */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010364 char_u *endp;
10365 char_u *reg_pat;
10366 char_u *p;
10367 int i;
10368 int nested = 0;
10369 int add_dollar = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010370
10371 if (allow_dirs != NULL)
10372 *allow_dirs = FALSE;
10373 if (pat_end == NULL)
10374 pat_end = pat + STRLEN(pat);
10375
Bram Moolenaar071d4272004-06-13 20:20:40 +000010376 for (p = pat; p < pat_end; p++)
10377 {
10378 switch (*p)
10379 {
10380 case '*':
10381 case '.':
10382 case ',':
10383 case '{':
10384 case '}':
10385 case '~':
10386 size += 2; /* extra backslash */
10387 break;
10388#ifdef BACKSLASH_IN_FILENAME
10389 case '\\':
10390 case '/':
10391 size += 4; /* could become "[\/]" */
10392 break;
10393#endif
10394 default:
10395 size++;
Bram Moolenaar2288afe2015-08-11 16:20:05 +020010396# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010397 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010398 {
10399 ++p;
10400 ++size;
10401 }
10402# endif
10403 break;
10404 }
10405 }
10406 reg_pat = alloc(size + 1);
10407 if (reg_pat == NULL)
10408 return NULL;
10409
Bram Moolenaar071d4272004-06-13 20:20:40 +000010410 i = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010411
10412 if (pat[0] == '*')
10413 while (pat[0] == '*' && pat < pat_end - 1)
10414 pat++;
10415 else
10416 reg_pat[i++] = '^';
10417 endp = pat_end - 1;
Bram Moolenaar8fee8782015-08-11 18:45:48 +020010418 if (endp >= pat && *endp == '*')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010419 {
10420 while (endp - pat > 0 && *endp == '*')
10421 endp--;
10422 add_dollar = FALSE;
10423 }
10424 for (p = pat; *p && nested >= 0 && p <= endp; p++)
10425 {
10426 switch (*p)
10427 {
10428 case '*':
10429 reg_pat[i++] = '.';
10430 reg_pat[i++] = '*';
Bram Moolenaar02743632005-07-25 20:42:36 +000010431 while (p[1] == '*') /* "**" matches like "*" */
10432 ++p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010433 break;
10434 case '.':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010435 case '~':
10436 reg_pat[i++] = '\\';
10437 reg_pat[i++] = *p;
10438 break;
10439 case '?':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010440 reg_pat[i++] = '.';
10441 break;
10442 case '\\':
10443 if (p[1] == NUL)
10444 break;
10445#ifdef BACKSLASH_IN_FILENAME
10446 if (!no_bslash)
10447 {
10448 /* translate:
10449 * "\x" to "\\x" e.g., "dir\file"
10450 * "\*" to "\\.*" e.g., "dir\*.c"
10451 * "\?" to "\\." e.g., "dir\??.c"
10452 * "\+" to "\+" e.g., "fileX\+.c"
10453 */
10454 if ((vim_isfilec(p[1]) || p[1] == '*' || p[1] == '?')
10455 && p[1] != '+')
10456 {
10457 reg_pat[i++] = '[';
10458 reg_pat[i++] = '\\';
10459 reg_pat[i++] = '/';
10460 reg_pat[i++] = ']';
10461 if (allow_dirs != NULL)
10462 *allow_dirs = TRUE;
10463 break;
10464 }
10465 }
10466#endif
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010467 /* Undo escaping from ExpandEscape():
10468 * foo\?bar -> foo?bar
10469 * foo\%bar -> foo%bar
10470 * foo\,bar -> foo,bar
10471 * foo\ bar -> foo bar
10472 * Don't unescape \, * and others that are also special in a
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010473 * regexp.
10474 * An escaped { must be unescaped since we use magic not
Bram Moolenaara946afe2013-08-02 15:22:39 +020010475 * verymagic. Use "\\\{n,m\}"" to get "\{n,m}".
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010476 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010477 if (*++p == '?'
10478#ifdef BACKSLASH_IN_FILENAME
10479 && no_bslash
10480#endif
10481 )
10482 reg_pat[i++] = '?';
10483 else
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010484 if (*p == ',' || *p == '%' || *p == '#'
Bram Moolenaar2288afe2015-08-11 16:20:05 +020010485 || vim_isspace(*p) || *p == '{' || *p == '}')
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010486 reg_pat[i++] = *p;
Bram Moolenaara946afe2013-08-02 15:22:39 +020010487 else if (*p == '\\' && p[1] == '\\' && p[2] == '{')
10488 {
10489 reg_pat[i++] = '\\';
10490 reg_pat[i++] = '{';
10491 p += 2;
10492 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010493 else
10494 {
10495 if (allow_dirs != NULL && vim_ispathsep(*p)
10496#ifdef BACKSLASH_IN_FILENAME
10497 && (!no_bslash || *p != '\\')
10498#endif
10499 )
10500 *allow_dirs = TRUE;
10501 reg_pat[i++] = '\\';
10502 reg_pat[i++] = *p;
10503 }
10504 break;
10505#ifdef BACKSLASH_IN_FILENAME
10506 case '/':
10507 reg_pat[i++] = '[';
10508 reg_pat[i++] = '\\';
10509 reg_pat[i++] = '/';
10510 reg_pat[i++] = ']';
10511 if (allow_dirs != NULL)
10512 *allow_dirs = TRUE;
10513 break;
10514#endif
10515 case '{':
10516 reg_pat[i++] = '\\';
10517 reg_pat[i++] = '(';
10518 nested++;
10519 break;
10520 case '}':
10521 reg_pat[i++] = '\\';
10522 reg_pat[i++] = ')';
10523 --nested;
10524 break;
10525 case ',':
10526 if (nested)
10527 {
10528 reg_pat[i++] = '\\';
10529 reg_pat[i++] = '|';
10530 }
10531 else
10532 reg_pat[i++] = ',';
10533 break;
10534 default:
10535# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010536 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010537 reg_pat[i++] = *p++;
10538 else
10539# endif
10540 if (allow_dirs != NULL && vim_ispathsep(*p))
10541 *allow_dirs = TRUE;
10542 reg_pat[i++] = *p;
10543 break;
10544 }
10545 }
10546 if (add_dollar)
10547 reg_pat[i++] = '$';
10548 reg_pat[i] = NUL;
10549 if (nested != 0)
10550 {
10551 if (nested < 0)
10552 EMSG(_("E219: Missing {."));
10553 else
10554 EMSG(_("E220: Missing }."));
10555 vim_free(reg_pat);
10556 reg_pat = NULL;
10557 }
10558 return reg_pat;
10559}
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010560
10561#if defined(EINTR) || defined(PROTO)
10562/*
10563 * Version of read() that retries when interrupted by EINTR (possibly
10564 * by a SIGWINCH).
10565 */
10566 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010567read_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010568{
10569 long ret;
10570
10571 for (;;)
10572 {
10573 ret = vim_read(fd, buf, bufsize);
10574 if (ret >= 0 || errno != EINTR)
10575 break;
10576 }
10577 return ret;
10578}
10579
10580/*
10581 * Version of write() that retries when interrupted by EINTR (possibly
10582 * by a SIGWINCH).
10583 */
10584 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010585write_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010586{
10587 long ret = 0;
10588 long wlen;
10589
10590 /* Repeat the write() so long it didn't fail, other than being interrupted
10591 * by a signal. */
10592 while (ret < (long)bufsize)
10593 {
Bram Moolenaar9c263032010-12-17 18:06:06 +010010594 wlen = vim_write(fd, (char *)buf + ret, bufsize - ret);
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010595 if (wlen < 0)
10596 {
10597 if (errno != EINTR)
10598 break;
10599 }
10600 else
10601 ret += wlen;
10602 }
10603 return ret;
10604}
10605#endif