blob: e76e3d19aaf7420a27ff86e403fe355d8db037a0 [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 {
852#ifndef ALWAYS_USE_GUI
853 mch_msg(_("Vim: Reading from stdin...\n"));
854#endif
855#ifdef FEAT_GUI
856 /* Also write a message in the GUI window, if there is one. */
857 if (gui.in_use && !gui.dying && !gui.starting)
858 {
859 p = (char_u *)_("Reading from stdin...");
860 gui_write(p, (int)STRLEN(p));
861 }
862#endif
863 }
864 else if (!read_buffer)
865 filemess(curbuf, sfname, (char_u *)"", 0);
866 }
867
868 msg_scroll = FALSE; /* overwrite the file message */
869
870 /*
871 * Set linecnt now, before the "retry" caused by a wrong guess for
872 * fileformat, and after the autocommands, which may change them.
873 */
874 linecnt = curbuf->b_ml.ml_line_count;
875
876#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000877 /* "++bad=" argument. */
878 if (eap != NULL && eap->bad_char != 0)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000879 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000880 bad_char_behavior = eap->bad_char;
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000881 if (set_options)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000882 curbuf->b_bad_char = eap->bad_char;
883 }
884 else
885 curbuf->b_bad_char = 0;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000886
Bram Moolenaar071d4272004-06-13 20:20:40 +0000887 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000888 * Decide which 'encoding' to use or use first.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000889 */
890 if (eap != NULL && eap->force_enc != 0)
891 {
892 fenc = enc_canonize(eap->cmd + eap->force_enc);
893 fenc_alloced = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000894 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000895 }
896 else if (curbuf->b_p_bin)
897 {
898 fenc = (char_u *)""; /* binary: don't convert */
899 fenc_alloced = FALSE;
900 }
901 else if (curbuf->b_help)
902 {
903 char_u firstline[80];
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000904 int fc;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000905
906 /* Help files are either utf-8 or latin1. Try utf-8 first, if this
907 * fails it must be latin1.
908 * Always do this when 'encoding' is "utf-8". Otherwise only do
909 * this when needed to avoid [converted] remarks all the time.
910 * It is needed when the first line contains non-ASCII characters.
911 * That is only in *.??x files. */
912 fenc = (char_u *)"latin1";
913 c = enc_utf8;
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000914 if (!c && !read_stdin)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000915 {
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000916 fc = fname[STRLEN(fname) - 1];
917 if (TOLOWER_ASC(fc) == 'x')
918 {
919 /* Read the first line (and a bit more). Immediately rewind to
920 * the start of the file. If the read() fails "len" is -1. */
Bram Moolenaar540fc6f2010-12-17 16:27:16 +0100921 len = read_eintr(fd, firstline, 80);
Bram Moolenaar8767f522016-07-01 17:17:39 +0200922 vim_lseek(fd, (off_T)0L, SEEK_SET);
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000923 for (p = firstline; p < firstline + len; ++p)
924 if (*p >= 0x80)
925 {
926 c = TRUE;
927 break;
928 }
929 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000930 }
931
932 if (c)
933 {
934 fenc_next = fenc;
935 fenc = (char_u *)"utf-8";
936
937 /* When the file is utf-8 but a character doesn't fit in
938 * 'encoding' don't retry. In help text editing utf-8 bytes
939 * doesn't make sense. */
Bram Moolenaarf193fff2006-04-27 00:02:13 +0000940 if (!enc_utf8)
941 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000942 }
943 fenc_alloced = FALSE;
944 }
945 else if (*p_fencs == NUL)
946 {
947 fenc = curbuf->b_p_fenc; /* use format from buffer */
948 fenc_alloced = FALSE;
949 }
950 else
951 {
952 fenc_next = p_fencs; /* try items in 'fileencodings' */
953 fenc = next_fenc(&fenc_next);
954 fenc_alloced = TRUE;
955 }
956#endif
957
958 /*
959 * Jump back here to retry reading the file in different ways.
960 * Reasons to retry:
961 * - encoding conversion failed: try another one from "fenc_next"
962 * - BOM detected and fenc was set, need to setup conversion
963 * - "fileformat" check failed: try another
964 *
965 * Variables set for special retry actions:
966 * "file_rewind" Rewind the file to start reading it again.
967 * "advance_fenc" Advance "fenc" using "fenc_next".
968 * "skip_read" Re-use already read bytes (BOM detected).
969 * "did_iconv" iconv() conversion failed, try 'charconvert'.
970 * "keep_fileformat" Don't reset "fileformat".
971 *
972 * Other status indicators:
973 * "tmpname" When != NULL did conversion with 'charconvert'.
974 * Output file has to be deleted afterwards.
975 * "iconv_fd" When != -1 did conversion with iconv().
976 */
977retry:
978
979 if (file_rewind)
980 {
981 if (read_buffer)
982 {
983 read_buf_lnum = 1;
984 read_buf_col = 0;
985 }
Bram Moolenaar8767f522016-07-01 17:17:39 +0200986 else if (read_stdin || vim_lseek(fd, (off_T)0L, SEEK_SET) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000987 {
988 /* Can't rewind the file, give up. */
989 error = TRUE;
990 goto failed;
991 }
992 /* Delete the previously read lines. */
993 while (lnum > from)
994 ml_delete(lnum--, FALSE);
995 file_rewind = FALSE;
996#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000997 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000998 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000999 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001000 curbuf->b_start_bomb = FALSE;
1001 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001002 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001003#endif
1004 }
1005
1006 /*
1007 * When retrying with another "fenc" and the first time "fileformat"
1008 * will be reset.
1009 */
1010 if (keep_fileformat)
1011 keep_fileformat = FALSE;
1012 else
1013 {
1014 if (eap != NULL && eap->force_ff != 0)
Bram Moolenaar1c860362008-11-12 15:05:21 +00001015 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001016 fileformat = get_fileformat_force(curbuf, eap);
Bram Moolenaar1c860362008-11-12 15:05:21 +00001017 try_unix = try_dos = try_mac = FALSE;
1018 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001019 else if (curbuf->b_p_bin)
1020 fileformat = EOL_UNIX; /* binary: use Unix format */
1021 else if (*p_ffs == NUL)
1022 fileformat = get_fileformat(curbuf);/* use format from buffer */
1023 else
1024 fileformat = EOL_UNKNOWN; /* detect from file */
1025 }
1026
1027#ifdef FEAT_MBYTE
1028# ifdef USE_ICONV
1029 if (iconv_fd != (iconv_t)-1)
1030 {
1031 /* aborted conversion with iconv(), close the descriptor */
1032 iconv_close(iconv_fd);
1033 iconv_fd = (iconv_t)-1;
1034 }
1035# endif
1036
1037 if (advance_fenc)
1038 {
1039 /*
1040 * Try the next entry in 'fileencodings'.
1041 */
1042 advance_fenc = FALSE;
1043
1044 if (eap != NULL && eap->force_enc != 0)
1045 {
1046 /* Conversion given with "++cc=" wasn't possible, read
1047 * without conversion. */
1048 notconverted = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001049 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001050 if (fenc_alloced)
1051 vim_free(fenc);
1052 fenc = (char_u *)"";
1053 fenc_alloced = FALSE;
1054 }
1055 else
1056 {
1057 if (fenc_alloced)
1058 vim_free(fenc);
1059 if (fenc_next != NULL)
1060 {
1061 fenc = next_fenc(&fenc_next);
1062 fenc_alloced = (fenc_next != NULL);
1063 }
1064 else
1065 {
1066 fenc = (char_u *)"";
1067 fenc_alloced = FALSE;
1068 }
1069 }
1070 if (tmpname != NULL)
1071 {
1072 mch_remove(tmpname); /* delete converted file */
1073 vim_free(tmpname);
1074 tmpname = NULL;
1075 }
1076 }
1077
1078 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001079 * Conversion may be required when the encoding of the file is different
1080 * from 'encoding' or 'encoding' is UTF-16, UCS-2 or UCS-4.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001081 */
1082 fio_flags = 0;
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001083 converted = need_conversion(fenc);
1084 if (converted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001085 {
1086
1087 /* "ucs-bom" means we need to check the first bytes of the file
1088 * for a BOM. */
1089 if (STRCMP(fenc, ENC_UCSBOM) == 0)
1090 fio_flags = FIO_UCSBOM;
1091
1092 /*
1093 * Check if UCS-2/4 or Latin1 to UTF-8 conversion needs to be
1094 * done. This is handled below after read(). Prepare the
1095 * fio_flags to avoid having to parse the string each time.
1096 * Also check for Unicode to Latin1 conversion, because iconv()
1097 * appears not to handle this correctly. This works just like
1098 * conversion to UTF-8 except how the resulting character is put in
1099 * the buffer.
1100 */
1101 else if (enc_utf8 || STRCMP(p_enc, "latin1") == 0)
1102 fio_flags = get_fio_flags(fenc);
1103
1104# ifdef WIN3264
1105 /*
1106 * Conversion from an MS-Windows codepage to UTF-8 or another codepage
1107 * is handled with MultiByteToWideChar().
1108 */
1109 if (fio_flags == 0)
1110 fio_flags = get_win_fio_flags(fenc);
1111# endif
1112
Bram Moolenaard0573012017-10-28 21:11:06 +02001113# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001114 /* Conversion from Apple MacRoman to latin1 or UTF-8 */
1115 if (fio_flags == 0)
1116 fio_flags = get_mac_fio_flags(fenc);
1117# endif
1118
1119# ifdef USE_ICONV
1120 /*
1121 * Try using iconv() if we can't convert internally.
1122 */
1123 if (fio_flags == 0
1124# ifdef FEAT_EVAL
1125 && !did_iconv
1126# endif
1127 )
1128 iconv_fd = (iconv_t)my_iconv_open(
1129 enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc);
1130# endif
1131
1132# ifdef FEAT_EVAL
1133 /*
1134 * Use the 'charconvert' expression when conversion is required
1135 * and we can't do it internally or with iconv().
1136 */
1137 if (fio_flags == 0 && !read_stdin && !read_buffer && *p_ccv != NUL
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02001138 && !read_fifo
Bram Moolenaar071d4272004-06-13 20:20:40 +00001139# ifdef USE_ICONV
1140 && iconv_fd == (iconv_t)-1
1141# endif
1142 )
1143 {
1144# ifdef USE_ICONV
1145 did_iconv = FALSE;
1146# endif
1147 /* Skip conversion when it's already done (retry for wrong
1148 * "fileformat"). */
1149 if (tmpname == NULL)
1150 {
1151 tmpname = readfile_charconvert(fname, fenc, &fd);
1152 if (tmpname == NULL)
1153 {
1154 /* Conversion failed. Try another one. */
1155 advance_fenc = TRUE;
1156 if (fd < 0)
1157 {
1158 /* Re-opening the original file failed! */
1159 EMSG(_("E202: Conversion made file unreadable!"));
1160 error = TRUE;
1161 goto failed;
1162 }
1163 goto retry;
1164 }
1165 }
1166 }
1167 else
1168# endif
1169 {
1170 if (fio_flags == 0
1171# ifdef USE_ICONV
1172 && iconv_fd == (iconv_t)-1
1173# endif
1174 )
1175 {
1176 /* Conversion wanted but we can't.
1177 * Try the next conversion in 'fileencodings' */
1178 advance_fenc = TRUE;
1179 goto retry;
1180 }
1181 }
1182 }
1183
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001184 /* Set "can_retry" when it's possible to rewind the file and try with
Bram Moolenaar071d4272004-06-13 20:20:40 +00001185 * another "fenc" value. It's FALSE when no other "fenc" to try, reading
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001186 * stdin or fixed at a specific encoding. */
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02001187 can_retry = (*fenc != NUL && !read_stdin && !read_fifo && !keep_dest_enc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001188#endif
1189
1190 if (!skip_read)
1191 {
1192 linerest = 0;
1193 filesize = 0;
1194 skip_count = lines_to_skip;
1195 read_count = lines_to_read;
1196#ifdef FEAT_MBYTE
1197 conv_restlen = 0;
1198#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001199#ifdef FEAT_PERSISTENT_UNDO
Bram Moolenaar59f931e2010-07-24 20:27:03 +02001200 read_undo_file = (newfile && (flags & READ_KEEP_UNDO) == 0
1201 && curbuf->b_ffname != NULL
1202 && curbuf->b_p_udf
1203 && !filtering
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02001204 && !read_fifo
Bram Moolenaar59f931e2010-07-24 20:27:03 +02001205 && !read_stdin
1206 && !read_buffer);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001207 if (read_undo_file)
1208 sha256_start(&sha_ctx);
1209#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001210#ifdef FEAT_CRYPT
1211 if (curbuf->b_cryptstate != NULL)
1212 {
1213 /* Need to free the state, but keep the key, don't want to ask for
1214 * it again. */
1215 crypt_free_state(curbuf->b_cryptstate);
1216 curbuf->b_cryptstate = NULL;
1217 }
1218#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001219 }
1220
1221 while (!error && !got_int)
1222 {
1223 /*
1224 * We allocate as much space for the file as we can get, plus
1225 * space for the old line plus room for one terminating NUL.
1226 * The amount is limited by the fact that read() only can read
1227 * upto max_unsigned characters (and other things).
1228 */
Bram Moolenaara2aa31a2014-02-23 22:52:40 +01001229#if VIM_SIZEOF_INT <= 2
Bram Moolenaar071d4272004-06-13 20:20:40 +00001230 if (linerest >= 0x7ff0)
1231 {
1232 ++split;
1233 *ptr = NL; /* split line by inserting a NL */
1234 size = 1;
1235 }
1236 else
1237#endif
1238 {
1239 if (!skip_read)
1240 {
Bram Moolenaara2aa31a2014-02-23 22:52:40 +01001241#if VIM_SIZEOF_INT > 2
Bram Moolenaar311d9822007-02-27 15:48:28 +00001242# if defined(SSIZE_MAX) && (SSIZE_MAX < 0x10000L)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001243 size = SSIZE_MAX; /* use max I/O size, 52K */
1244# else
1245 size = 0x10000L; /* use buffer >= 64K */
1246# endif
1247#else
1248 size = 0x7ff0L - linerest; /* limit buffer to 32K */
1249#endif
1250
Bram Moolenaarc1e37902006-04-18 21:55:01 +00001251 for ( ; size >= 10; size = (long)((long_u)size >> 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001252 {
1253 if ((new_buffer = lalloc((long_u)(size + linerest + 1),
1254 FALSE)) != NULL)
1255 break;
1256 }
1257 if (new_buffer == NULL)
1258 {
1259 do_outofmem_msg((long_u)(size * 2 + linerest + 1));
1260 error = TRUE;
1261 break;
1262 }
1263 if (linerest) /* copy characters from the previous buffer */
1264 mch_memmove(new_buffer, ptr - linerest, (size_t)linerest);
1265 vim_free(buffer);
1266 buffer = new_buffer;
1267 ptr = buffer + linerest;
1268 line_start = buffer;
1269
1270#ifdef FEAT_MBYTE
1271 /* May need room to translate into.
1272 * For iconv() we don't really know the required space, use a
1273 * factor ICONV_MULT.
1274 * latin1 to utf-8: 1 byte becomes up to 2 bytes
1275 * utf-16 to utf-8: 2 bytes become up to 3 bytes, 4 bytes
1276 * become up to 4 bytes, size must be multiple of 2
1277 * ucs-2 to utf-8: 2 bytes become up to 3 bytes, size must be
1278 * multiple of 2
1279 * ucs-4 to utf-8: 4 bytes become up to 6 bytes, size must be
1280 * multiple of 4 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001281 real_size = (int)size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001282# ifdef USE_ICONV
1283 if (iconv_fd != (iconv_t)-1)
1284 size = size / ICONV_MULT;
1285 else
1286# endif
1287 if (fio_flags & FIO_LATIN1)
1288 size = size / 2;
1289 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1290 size = (size * 2 / 3) & ~1;
1291 else if (fio_flags & FIO_UCS4)
1292 size = (size * 2 / 3) & ~3;
1293 else if (fio_flags == FIO_UCSBOM)
1294 size = size / ICONV_MULT; /* worst case */
1295# ifdef WIN3264
1296 else if (fio_flags & FIO_CODEPAGE)
1297 size = size / ICONV_MULT; /* also worst case */
1298# endif
Bram Moolenaard0573012017-10-28 21:11:06 +02001299# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001300 else if (fio_flags & FIO_MACROMAN)
1301 size = size / ICONV_MULT; /* also worst case */
1302# endif
1303#endif
1304
1305#ifdef FEAT_MBYTE
1306 if (conv_restlen > 0)
1307 {
1308 /* Insert unconverted bytes from previous line. */
1309 mch_memmove(ptr, conv_rest, conv_restlen);
1310 ptr += conv_restlen;
1311 size -= conv_restlen;
1312 }
1313#endif
1314
1315 if (read_buffer)
1316 {
1317 /*
1318 * Read bytes from curbuf. Used for converting text read
1319 * from stdin.
1320 */
1321 if (read_buf_lnum > from)
1322 size = 0;
1323 else
1324 {
1325 int n, ni;
1326 long tlen;
1327
1328 tlen = 0;
1329 for (;;)
1330 {
1331 p = ml_get(read_buf_lnum) + read_buf_col;
1332 n = (int)STRLEN(p);
1333 if ((int)tlen + n + 1 > size)
1334 {
1335 /* Filled up to "size", append partial line.
1336 * Change NL to NUL to reverse the effect done
1337 * below. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001338 n = (int)(size - tlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001339 for (ni = 0; ni < n; ++ni)
1340 {
1341 if (p[ni] == NL)
1342 ptr[tlen++] = NUL;
1343 else
1344 ptr[tlen++] = p[ni];
1345 }
1346 read_buf_col += n;
1347 break;
1348 }
1349 else
1350 {
1351 /* Append whole line and new-line. Change NL
1352 * to NUL to reverse the effect done below. */
1353 for (ni = 0; ni < n; ++ni)
1354 {
1355 if (p[ni] == NL)
1356 ptr[tlen++] = NUL;
1357 else
1358 ptr[tlen++] = p[ni];
1359 }
1360 ptr[tlen++] = NL;
1361 read_buf_col = 0;
1362 if (++read_buf_lnum > from)
1363 {
1364 /* When the last line didn't have an
1365 * end-of-line don't add it now either. */
1366 if (!curbuf->b_p_eol)
1367 --tlen;
1368 size = tlen;
1369 break;
1370 }
1371 }
1372 }
1373 }
1374 }
1375 else
1376 {
1377 /*
1378 * Read bytes from the file.
1379 */
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01001380 size = read_eintr(fd, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001381 }
1382
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001383#ifdef FEAT_CRYPT
1384 /*
1385 * At start of file: Check for magic number of encryption.
1386 */
1387 if (filesize == 0 && size > 0)
1388 cryptkey = check_for_cryptkey(cryptkey, ptr, &size,
1389 &filesize, newfile, sfname,
1390 &did_ask_for_key);
1391 /*
1392 * Decrypt the read bytes. This is done before checking for
1393 * EOF because the crypt layer may be buffering.
1394 */
Bram Moolenaar829aa642017-08-23 22:32:35 +02001395 if (cryptkey != NULL && curbuf->b_cryptstate != NULL
1396 && size > 0)
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001397 {
1398 if (crypt_works_inplace(curbuf->b_cryptstate))
1399 {
1400 crypt_decode_inplace(curbuf->b_cryptstate, ptr, size);
1401 }
1402 else
1403 {
1404 char_u *newptr = NULL;
1405 int decrypted_size;
1406
1407 decrypted_size = crypt_decode_alloc(
1408 curbuf->b_cryptstate, ptr, size, &newptr);
1409
1410 /* If the crypt layer is buffering, not producing
1411 * anything yet, need to read more. */
1412 if (size > 0 && decrypted_size == 0)
1413 continue;
1414
1415 if (linerest == 0)
1416 {
1417 /* Simple case: reuse returned buffer (may be
1418 * NULL, checked later). */
1419 new_buffer = newptr;
1420 }
1421 else
1422 {
1423 long_u new_size;
1424
1425 /* Need new buffer to add bytes carried over. */
1426 new_size = (long_u)(decrypted_size + linerest + 1);
1427 new_buffer = lalloc(new_size, FALSE);
1428 if (new_buffer == NULL)
1429 {
1430 do_outofmem_msg(new_size);
1431 error = TRUE;
1432 break;
1433 }
1434
1435 mch_memmove(new_buffer, buffer, linerest);
1436 if (newptr != NULL)
1437 mch_memmove(new_buffer + linerest, newptr,
1438 decrypted_size);
1439 }
1440
1441 if (new_buffer != NULL)
1442 {
1443 vim_free(buffer);
1444 buffer = new_buffer;
1445 new_buffer = NULL;
1446 line_start = buffer;
1447 ptr = buffer + linerest;
1448 }
1449 size = decrypted_size;
1450 }
1451 }
1452#endif
1453
Bram Moolenaar071d4272004-06-13 20:20:40 +00001454 if (size <= 0)
1455 {
1456 if (size < 0) /* read error */
1457 error = TRUE;
1458#ifdef FEAT_MBYTE
1459 else if (conv_restlen > 0)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001460 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001461 /*
1462 * Reached end-of-file but some trailing bytes could
1463 * not be converted. Truncated file?
1464 */
1465
1466 /* When we did a conversion report an error. */
1467 if (fio_flags != 0
1468# ifdef USE_ICONV
1469 || iconv_fd != (iconv_t)-1
1470# endif
1471 )
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001472 {
Bram Moolenaare8d95302013-04-24 16:34:02 +02001473 if (can_retry)
1474 goto rewind_retry;
Bram Moolenaarf453d352008-06-04 17:37:34 +00001475 if (conv_error == 0)
1476 conv_error = curbuf->b_ml.ml_line_count
1477 - linecnt + 1;
1478 }
1479 /* Remember the first linenr with an illegal byte */
1480 else if (illegal_byte == 0)
1481 illegal_byte = curbuf->b_ml.ml_line_count
1482 - linecnt + 1;
1483 if (bad_char_behavior == BAD_DROP)
1484 {
1485 *(ptr - conv_restlen) = NUL;
1486 conv_restlen = 0;
1487 }
1488 else
1489 {
1490 /* Replace the trailing bytes with the replacement
1491 * character if we were converting; if we weren't,
1492 * leave the UTF8 checking code to do it, as it
1493 * works slightly differently. */
1494 if (bad_char_behavior != BAD_KEEP && (fio_flags != 0
1495# ifdef USE_ICONV
1496 || iconv_fd != (iconv_t)-1
1497# endif
1498 ))
1499 {
1500 while (conv_restlen > 0)
1501 {
1502 *(--ptr) = bad_char_behavior;
1503 --conv_restlen;
1504 }
1505 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001506 fio_flags = 0; /* don't convert this */
Bram Moolenaarb21e5842006-04-16 18:30:08 +00001507# ifdef USE_ICONV
1508 if (iconv_fd != (iconv_t)-1)
1509 {
1510 iconv_close(iconv_fd);
1511 iconv_fd = (iconv_t)-1;
1512 }
1513# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001514 }
1515 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001516#endif
1517 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001518 }
1519 skip_read = FALSE;
1520
1521#ifdef FEAT_MBYTE
1522 /*
1523 * At start of file (or after crypt magic number): Check for BOM.
1524 * Also check for a BOM for other Unicode encodings, but not after
1525 * converting with 'charconvert' or when a BOM has already been
1526 * found.
1527 */
1528 if ((filesize == 0
1529# ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001530 || (cryptkey != NULL
1531 && filesize == crypt_get_header_len(
1532 crypt_get_method_nr(curbuf)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001533# endif
1534 )
1535 && (fio_flags == FIO_UCSBOM
1536 || (!curbuf->b_p_bomb
1537 && tmpname == NULL
1538 && (*fenc == 'u' || (*fenc == NUL && enc_utf8)))))
1539 {
1540 char_u *ccname;
1541 int blen;
1542
1543 /* no BOM detection in a short file or in binary mode */
1544 if (size < 2 || curbuf->b_p_bin)
1545 ccname = NULL;
1546 else
1547 ccname = check_for_bom(ptr, size, &blen,
1548 fio_flags == FIO_UCSBOM ? FIO_ALL : get_fio_flags(fenc));
1549 if (ccname != NULL)
1550 {
1551 /* Remove BOM from the text */
1552 filesize += blen;
1553 size -= blen;
1554 mch_memmove(ptr, ptr + blen, (size_t)size);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00001555 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001556 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001557 curbuf->b_p_bomb = TRUE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001558 curbuf->b_start_bomb = TRUE;
1559 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001560 }
1561
1562 if (fio_flags == FIO_UCSBOM)
1563 {
1564 if (ccname == NULL)
1565 {
1566 /* No BOM detected: retry with next encoding. */
1567 advance_fenc = TRUE;
1568 }
1569 else
1570 {
1571 /* BOM detected: set "fenc" and jump back */
1572 if (fenc_alloced)
1573 vim_free(fenc);
1574 fenc = ccname;
1575 fenc_alloced = FALSE;
1576 }
1577 /* retry reading without getting new bytes or rewinding */
1578 skip_read = TRUE;
1579 goto retry;
1580 }
1581 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001582
1583 /* Include not converted bytes. */
1584 ptr -= conv_restlen;
1585 size += conv_restlen;
1586 conv_restlen = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001587#endif
1588 /*
1589 * Break here for a read error or end-of-file.
1590 */
1591 if (size <= 0)
1592 break;
1593
1594#ifdef FEAT_MBYTE
1595
Bram Moolenaar071d4272004-06-13 20:20:40 +00001596# ifdef USE_ICONV
1597 if (iconv_fd != (iconv_t)-1)
1598 {
1599 /*
1600 * Attempt conversion of the read bytes to 'encoding' using
1601 * iconv().
1602 */
1603 const char *fromp;
1604 char *top;
1605 size_t from_size;
1606 size_t to_size;
1607
1608 fromp = (char *)ptr;
1609 from_size = size;
1610 ptr += size;
1611 top = (char *)ptr;
1612 to_size = real_size - size;
1613
1614 /*
1615 * If there is conversion error or not enough room try using
Bram Moolenaar19a09a12005-03-04 23:39:37 +00001616 * another conversion. Except for when there is no
1617 * alternative (help files).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001618 */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001619 while ((iconv(iconv_fd, (void *)&fromp, &from_size,
1620 &top, &to_size)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001621 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
1622 || from_size > CONV_RESTLEN)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001623 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001624 if (can_retry)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001625 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001626 if (conv_error == 0)
1627 conv_error = readfile_linenr(linecnt,
1628 ptr, (char_u *)top);
Bram Moolenaar42eeac32005-06-29 22:40:58 +00001629
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001630 /* Deal with a bad byte and continue with the next. */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001631 ++fromp;
1632 --from_size;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001633 if (bad_char_behavior == BAD_KEEP)
1634 {
1635 *top++ = *(fromp - 1);
1636 --to_size;
1637 }
1638 else if (bad_char_behavior != BAD_DROP)
1639 {
1640 *top++ = bad_char_behavior;
1641 --to_size;
1642 }
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001643 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001644
1645 if (from_size > 0)
1646 {
1647 /* Some remaining characters, keep them for the next
1648 * round. */
1649 mch_memmove(conv_rest, (char_u *)fromp, from_size);
1650 conv_restlen = (int)from_size;
1651 }
1652
1653 /* move the linerest to before the converted characters */
1654 line_start = ptr - linerest;
1655 mch_memmove(line_start, buffer, (size_t)linerest);
1656 size = (long)((char_u *)top - ptr);
1657 }
1658# endif
1659
1660# ifdef WIN3264
1661 if (fio_flags & FIO_CODEPAGE)
1662 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001663 char_u *src, *dst;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001664 WCHAR ucs2buf[3];
1665 int ucs2len;
1666 int codepage = FIO_GET_CP(fio_flags);
1667 int bytelen;
1668 int found_bad;
1669 char replstr[2];
1670
Bram Moolenaar071d4272004-06-13 20:20:40 +00001671 /*
1672 * Conversion from an MS-Windows codepage or UTF-8 to UTF-8 or
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001673 * a codepage, using standard MS-Windows functions. This
1674 * requires two steps:
1675 * 1. convert from 'fileencoding' to ucs-2
1676 * 2. convert from ucs-2 to 'encoding'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001677 *
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001678 * Because there may be illegal bytes AND an incomplete byte
1679 * sequence at the end, we may have to do the conversion one
1680 * character at a time to get it right.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001681 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001682
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001683 /* Replacement string for WideCharToMultiByte(). */
1684 if (bad_char_behavior > 0)
1685 replstr[0] = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001686 else
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001687 replstr[0] = '?';
1688 replstr[1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001689
1690 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001691 * Move the bytes to the end of the buffer, so that we have
1692 * room to put the result at the start.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001693 */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001694 src = ptr + real_size - size;
1695 mch_memmove(src, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001696
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001697 /*
1698 * Do the conversion.
1699 */
1700 dst = ptr;
1701 size = size;
1702 while (size > 0)
1703 {
1704 found_bad = FALSE;
1705
1706# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
1707 if (codepage == CP_UTF8)
1708 {
1709 /* Handle CP_UTF8 input ourselves to be able to handle
1710 * trailing bytes properly.
1711 * Get one UTF-8 character from src. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001712 bytelen = (int)utf_ptr2len_len(src, size);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001713 if (bytelen > size)
1714 {
1715 /* Only got some bytes of a character. Normally
1716 * it's put in "conv_rest", but if it's too long
1717 * deal with it as if they were illegal bytes. */
1718 if (bytelen <= CONV_RESTLEN)
1719 break;
1720
1721 /* weird overlong byte sequence */
1722 bytelen = size;
1723 found_bad = TRUE;
1724 }
1725 else
1726 {
Bram Moolenaarc01140a2006-03-24 22:21:52 +00001727 int u8c = utf_ptr2char(src);
1728
Bram Moolenaar86e01082005-12-29 22:45:34 +00001729 if (u8c > 0xffff || (*src >= 0x80 && bytelen == 1))
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001730 found_bad = TRUE;
1731 ucs2buf[0] = u8c;
1732 ucs2len = 1;
1733 }
1734 }
1735 else
1736# endif
1737 {
1738 /* We don't know how long the byte sequence is, try
1739 * from one to three bytes. */
1740 for (bytelen = 1; bytelen <= size && bytelen <= 3;
1741 ++bytelen)
1742 {
1743 ucs2len = MultiByteToWideChar(codepage,
1744 MB_ERR_INVALID_CHARS,
1745 (LPCSTR)src, bytelen,
1746 ucs2buf, 3);
1747 if (ucs2len > 0)
1748 break;
1749 }
1750 if (ucs2len == 0)
1751 {
1752 /* If we have only one byte then it's probably an
1753 * incomplete byte sequence. Otherwise discard
1754 * one byte as a bad character. */
1755 if (size == 1)
1756 break;
1757 found_bad = TRUE;
1758 bytelen = 1;
1759 }
1760 }
1761
1762 if (!found_bad)
1763 {
1764 int i;
1765
1766 /* Convert "ucs2buf[ucs2len]" to 'enc' in "dst". */
1767 if (enc_utf8)
1768 {
1769 /* From UCS-2 to UTF-8. Cannot fail. */
1770 for (i = 0; i < ucs2len; ++i)
1771 dst += utf_char2bytes(ucs2buf[i], dst);
1772 }
1773 else
1774 {
1775 BOOL bad = FALSE;
1776 int dstlen;
1777
1778 /* From UCS-2 to "enc_codepage". If the
1779 * conversion uses the default character "?",
1780 * the data doesn't fit in this encoding. */
1781 dstlen = WideCharToMultiByte(enc_codepage, 0,
1782 (LPCWSTR)ucs2buf, ucs2len,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001783 (LPSTR)dst, (int)(src - dst),
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001784 replstr, &bad);
1785 if (bad)
1786 found_bad = TRUE;
1787 else
1788 dst += dstlen;
1789 }
1790 }
1791
1792 if (found_bad)
1793 {
1794 /* Deal with bytes we can't convert. */
1795 if (can_retry)
1796 goto rewind_retry;
1797 if (conv_error == 0)
1798 conv_error = readfile_linenr(linecnt, ptr, dst);
1799 if (bad_char_behavior != BAD_DROP)
1800 {
1801 if (bad_char_behavior == BAD_KEEP)
1802 {
1803 mch_memmove(dst, src, bytelen);
1804 dst += bytelen;
1805 }
1806 else
1807 *dst++ = bad_char_behavior;
1808 }
1809 }
1810
1811 src += bytelen;
1812 size -= bytelen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001813 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001814
1815 if (size > 0)
1816 {
1817 /* An incomplete byte sequence remaining. */
1818 mch_memmove(conv_rest, src, size);
1819 conv_restlen = size;
1820 }
1821
1822 /* The new size is equal to how much "dst" was advanced. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001823 size = (long)(dst - ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001824 }
1825 else
1826# endif
Bram Moolenaar56718732006-03-15 22:53:57 +00001827# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001828 if (fio_flags & FIO_MACROMAN)
1829 {
1830 /*
1831 * Conversion from Apple MacRoman char encoding to UTF-8 or
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001832 * latin1. This is in os_mac_conv.c.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001833 */
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001834 if (macroman2enc(ptr, &size, real_size) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001835 goto rewind_retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001836 }
1837 else
1838# endif
1839 if (fio_flags != 0)
1840 {
1841 int u8c;
1842 char_u *dest;
1843 char_u *tail = NULL;
1844
1845 /*
1846 * "enc_utf8" set: Convert Unicode or Latin1 to UTF-8.
1847 * "enc_utf8" not set: Convert Unicode to Latin1.
1848 * Go from end to start through the buffer, because the number
1849 * of bytes may increase.
1850 * "dest" points to after where the UTF-8 bytes go, "p" points
1851 * to after the next character to convert.
1852 */
1853 dest = ptr + real_size;
1854 if (fio_flags == FIO_LATIN1 || fio_flags == FIO_UTF8)
1855 {
1856 p = ptr + size;
1857 if (fio_flags == FIO_UTF8)
1858 {
1859 /* Check for a trailing incomplete UTF-8 sequence */
1860 tail = ptr + size - 1;
1861 while (tail > ptr && (*tail & 0xc0) == 0x80)
1862 --tail;
1863 if (tail + utf_byte2len(*tail) <= ptr + size)
1864 tail = NULL;
1865 else
1866 p = tail;
1867 }
1868 }
1869 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1870 {
1871 /* Check for a trailing byte */
1872 p = ptr + (size & ~1);
1873 if (size & 1)
1874 tail = p;
1875 if ((fio_flags & FIO_UTF16) && p > ptr)
1876 {
1877 /* Check for a trailing leading word */
1878 if (fio_flags & FIO_ENDIAN_L)
1879 {
1880 u8c = (*--p << 8);
1881 u8c += *--p;
1882 }
1883 else
1884 {
1885 u8c = *--p;
1886 u8c += (*--p << 8);
1887 }
1888 if (u8c >= 0xd800 && u8c <= 0xdbff)
1889 tail = p;
1890 else
1891 p += 2;
1892 }
1893 }
1894 else /* FIO_UCS4 */
1895 {
1896 /* Check for trailing 1, 2 or 3 bytes */
1897 p = ptr + (size & ~3);
1898 if (size & 3)
1899 tail = p;
1900 }
1901
1902 /* If there is a trailing incomplete sequence move it to
1903 * conv_rest[]. */
1904 if (tail != NULL)
1905 {
1906 conv_restlen = (int)((ptr + size) - tail);
1907 mch_memmove(conv_rest, (char_u *)tail, conv_restlen);
1908 size -= conv_restlen;
1909 }
1910
1911
1912 while (p > ptr)
1913 {
1914 if (fio_flags & FIO_LATIN1)
1915 u8c = *--p;
1916 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1917 {
1918 if (fio_flags & FIO_ENDIAN_L)
1919 {
1920 u8c = (*--p << 8);
1921 u8c += *--p;
1922 }
1923 else
1924 {
1925 u8c = *--p;
1926 u8c += (*--p << 8);
1927 }
1928 if ((fio_flags & FIO_UTF16)
1929 && u8c >= 0xdc00 && u8c <= 0xdfff)
1930 {
1931 int u16c;
1932
1933 if (p == ptr)
1934 {
1935 /* Missing leading word. */
1936 if (can_retry)
1937 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001938 if (conv_error == 0)
1939 conv_error = readfile_linenr(linecnt,
1940 ptr, p);
1941 if (bad_char_behavior == BAD_DROP)
1942 continue;
1943 if (bad_char_behavior != BAD_KEEP)
1944 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001945 }
1946
1947 /* found second word of double-word, get the first
1948 * word and compute the resulting character */
1949 if (fio_flags & FIO_ENDIAN_L)
1950 {
1951 u16c = (*--p << 8);
1952 u16c += *--p;
1953 }
1954 else
1955 {
1956 u16c = *--p;
1957 u16c += (*--p << 8);
1958 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001959 u8c = 0x10000 + ((u16c & 0x3ff) << 10)
1960 + (u8c & 0x3ff);
1961
Bram Moolenaar071d4272004-06-13 20:20:40 +00001962 /* Check if the word is indeed a leading word. */
1963 if (u16c < 0xd800 || u16c > 0xdbff)
1964 {
1965 if (can_retry)
1966 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001967 if (conv_error == 0)
1968 conv_error = readfile_linenr(linecnt,
1969 ptr, p);
1970 if (bad_char_behavior == BAD_DROP)
1971 continue;
1972 if (bad_char_behavior != BAD_KEEP)
1973 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001974 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001975 }
1976 }
1977 else if (fio_flags & FIO_UCS4)
1978 {
1979 if (fio_flags & FIO_ENDIAN_L)
1980 {
Bram Moolenaardc1c9812017-10-27 22:15:24 +02001981 u8c = (unsigned)*--p << 24;
1982 u8c += (unsigned)*--p << 16;
1983 u8c += (unsigned)*--p << 8;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001984 u8c += *--p;
1985 }
1986 else /* big endian */
1987 {
1988 u8c = *--p;
Bram Moolenaardc1c9812017-10-27 22:15:24 +02001989 u8c += (unsigned)*--p << 8;
1990 u8c += (unsigned)*--p << 16;
1991 u8c += (unsigned)*--p << 24;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001992 }
1993 }
1994 else /* UTF-8 */
1995 {
1996 if (*--p < 0x80)
1997 u8c = *p;
1998 else
1999 {
2000 len = utf_head_off(ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002001 p -= len;
2002 u8c = utf_ptr2char(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002003 if (len == 0)
2004 {
2005 /* Not a valid UTF-8 character, retry with
2006 * another fenc when possible, otherwise just
2007 * report the error. */
2008 if (can_retry)
2009 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002010 if (conv_error == 0)
2011 conv_error = readfile_linenr(linecnt,
2012 ptr, p);
2013 if (bad_char_behavior == BAD_DROP)
2014 continue;
2015 if (bad_char_behavior != BAD_KEEP)
2016 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002017 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002018 }
2019 }
2020 if (enc_utf8) /* produce UTF-8 */
2021 {
2022 dest -= utf_char2len(u8c);
2023 (void)utf_char2bytes(u8c, dest);
2024 }
2025 else /* produce Latin1 */
2026 {
2027 --dest;
2028 if (u8c >= 0x100)
2029 {
2030 /* character doesn't fit in latin1, retry with
2031 * another fenc when possible, otherwise just
2032 * report the error. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002033 if (can_retry)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002034 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002035 if (conv_error == 0)
2036 conv_error = readfile_linenr(linecnt, ptr, p);
2037 if (bad_char_behavior == BAD_DROP)
2038 ++dest;
2039 else if (bad_char_behavior == BAD_KEEP)
2040 *dest = u8c;
2041 else if (eap != NULL && eap->bad_char != 0)
2042 *dest = bad_char_behavior;
2043 else
2044 *dest = 0xBF;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002045 }
2046 else
2047 *dest = u8c;
2048 }
2049 }
2050
2051 /* move the linerest to before the converted characters */
2052 line_start = dest - linerest;
2053 mch_memmove(line_start, buffer, (size_t)linerest);
2054 size = (long)((ptr + real_size) - dest);
2055 ptr = dest;
2056 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002057 else if (enc_utf8 && !curbuf->b_p_bin)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002058 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002059 int incomplete_tail = FALSE;
2060
2061 /* Reading UTF-8: Check if the bytes are valid UTF-8. */
2062 for (p = ptr; ; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002063 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002064 int todo = (int)((ptr + size) - p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002065 int l;
2066
2067 if (todo <= 0)
2068 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002069 if (*p >= 0x80)
2070 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002071 /* A length of 1 means it's an illegal byte. Accept
2072 * an incomplete character at the end though, the next
2073 * read() will get the next bytes, we'll check it
2074 * then. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002075 l = utf_ptr2len_len(p, todo);
Bram Moolenaarf453d352008-06-04 17:37:34 +00002076 if (l > todo && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002077 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002078 /* Avoid retrying with a different encoding when
2079 * a truncated file is more likely, or attempting
2080 * to read the rest of an incomplete sequence when
2081 * we have already done so. */
2082 if (p > ptr || filesize > 0)
2083 incomplete_tail = TRUE;
2084 /* Incomplete byte sequence, move it to conv_rest[]
2085 * and try to read the rest of it, unless we've
2086 * already done so. */
2087 if (p > ptr)
2088 {
2089 conv_restlen = todo;
2090 mch_memmove(conv_rest, p, conv_restlen);
2091 size -= conv_restlen;
2092 break;
2093 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002094 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002095 if (l == 1 || l > todo)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002096 {
2097 /* Illegal byte. If we can try another encoding
Bram Moolenaarf453d352008-06-04 17:37:34 +00002098 * do that, unless at EOF where a truncated
2099 * file is more likely than a conversion error. */
2100 if (can_retry && !incomplete_tail)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002101 break;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002102# ifdef USE_ICONV
2103 /* When we did a conversion report an error. */
2104 if (iconv_fd != (iconv_t)-1 && conv_error == 0)
2105 conv_error = readfile_linenr(linecnt, ptr, p);
2106# endif
Bram Moolenaarf453d352008-06-04 17:37:34 +00002107 /* Remember the first linenr with an illegal byte */
2108 if (conv_error == 0 && illegal_byte == 0)
2109 illegal_byte = readfile_linenr(linecnt, ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002110
2111 /* Drop, keep or replace the bad byte. */
2112 if (bad_char_behavior == BAD_DROP)
2113 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002114 mch_memmove(p, p + 1, todo - 1);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002115 --p;
2116 --size;
2117 }
2118 else if (bad_char_behavior != BAD_KEEP)
2119 *p = bad_char_behavior;
2120 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002121 else
2122 p += l - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002123 }
2124 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002125 if (p < ptr + size && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002126 {
2127 /* Detected a UTF-8 error. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002128rewind_retry:
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002129 /* Retry reading with another conversion. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002130# if defined(FEAT_EVAL) && defined(USE_ICONV)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002131 if (*p_ccv != NUL && iconv_fd != (iconv_t)-1)
2132 /* iconv() failed, try 'charconvert' */
2133 did_iconv = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002134 else
2135# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002136 /* use next item from 'fileencodings' */
2137 advance_fenc = TRUE;
2138 file_rewind = TRUE;
2139 goto retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002140 }
2141 }
2142#endif
2143
2144 /* count the number of characters (after conversion!) */
2145 filesize += size;
2146
2147 /*
2148 * when reading the first part of a file: guess EOL type
2149 */
2150 if (fileformat == EOL_UNKNOWN)
2151 {
2152 /* First try finding a NL, for Dos and Unix */
2153 if (try_dos || try_unix)
2154 {
Bram Moolenaarc6b72172015-02-27 17:48:09 +01002155 /* Reset the carriage return counter. */
2156 if (try_mac)
2157 try_mac = 1;
2158
Bram Moolenaar071d4272004-06-13 20:20:40 +00002159 for (p = ptr; p < ptr + size; ++p)
2160 {
2161 if (*p == NL)
2162 {
2163 if (!try_unix
2164 || (try_dos && p > ptr && p[-1] == CAR))
2165 fileformat = EOL_DOS;
2166 else
2167 fileformat = EOL_UNIX;
2168 break;
2169 }
Bram Moolenaar05eb6122015-02-17 14:15:19 +01002170 else if (*p == CAR && try_mac)
2171 try_mac++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002172 }
2173
2174 /* Don't give in to EOL_UNIX if EOL_MAC is more likely */
2175 if (fileformat == EOL_UNIX && try_mac)
2176 {
2177 /* Need to reset the counters when retrying fenc. */
2178 try_mac = 1;
2179 try_unix = 1;
2180 for (; p >= ptr && *p != CAR; p--)
2181 ;
2182 if (p >= ptr)
2183 {
2184 for (p = ptr; p < ptr + size; ++p)
2185 {
2186 if (*p == NL)
2187 try_unix++;
2188 else if (*p == CAR)
2189 try_mac++;
2190 }
2191 if (try_mac > try_unix)
2192 fileformat = EOL_MAC;
2193 }
2194 }
Bram Moolenaar05eb6122015-02-17 14:15:19 +01002195 else if (fileformat == EOL_UNKNOWN && try_mac == 1)
2196 /* Looking for CR but found no end-of-line markers at
2197 * all: use the default format. */
2198 fileformat = default_fileformat();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002199 }
2200
2201 /* No NL found: may use Mac format */
2202 if (fileformat == EOL_UNKNOWN && try_mac)
2203 fileformat = EOL_MAC;
2204
2205 /* Still nothing found? Use first format in 'ffs' */
2206 if (fileformat == EOL_UNKNOWN)
2207 fileformat = default_fileformat();
2208
2209 /* if editing a new file: may set p_tx and p_ff */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002210 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002211 set_fileformat(fileformat, OPT_LOCAL);
2212 }
2213 }
2214
2215 /*
2216 * This loop is executed once for every character read.
2217 * Keep it fast!
2218 */
2219 if (fileformat == EOL_MAC)
2220 {
2221 --ptr;
2222 while (++ptr, --size >= 0)
2223 {
2224 /* catch most common case first */
2225 if ((c = *ptr) != NUL && c != CAR && c != NL)
2226 continue;
2227 if (c == NUL)
2228 *ptr = NL; /* NULs are replaced by newlines! */
2229 else if (c == NL)
2230 *ptr = CAR; /* NLs are replaced by CRs! */
2231 else
2232 {
2233 if (skip_count == 0)
2234 {
2235 *ptr = NUL; /* end of line */
2236 len = (colnr_T) (ptr - line_start + 1);
2237 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2238 {
2239 error = TRUE;
2240 break;
2241 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002242#ifdef FEAT_PERSISTENT_UNDO
2243 if (read_undo_file)
2244 sha256_update(&sha_ctx, line_start, len);
2245#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002246 ++lnum;
2247 if (--read_count == 0)
2248 {
2249 error = TRUE; /* break loop */
2250 line_start = ptr; /* nothing left to write */
2251 break;
2252 }
2253 }
2254 else
2255 --skip_count;
2256 line_start = ptr + 1;
2257 }
2258 }
2259 }
2260 else
2261 {
2262 --ptr;
2263 while (++ptr, --size >= 0)
2264 {
2265 if ((c = *ptr) != NUL && c != NL) /* catch most common case */
2266 continue;
2267 if (c == NUL)
2268 *ptr = NL; /* NULs are replaced by newlines! */
2269 else
2270 {
2271 if (skip_count == 0)
2272 {
2273 *ptr = NUL; /* end of line */
2274 len = (colnr_T)(ptr - line_start + 1);
2275 if (fileformat == EOL_DOS)
2276 {
Bram Moolenaar2aa5f692017-01-24 15:46:48 +01002277 if (ptr > line_start && ptr[-1] == CAR)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002278 {
Bram Moolenaar2aa5f692017-01-24 15:46:48 +01002279 /* remove CR before NL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002280 ptr[-1] = NUL;
2281 --len;
2282 }
2283 /*
2284 * Reading in Dos format, but no CR-LF found!
2285 * When 'fileformats' includes "unix", delete all
2286 * the lines read so far and start all over again.
2287 * Otherwise give an error message later.
2288 */
2289 else if (ff_error != EOL_DOS)
2290 {
2291 if ( try_unix
2292 && !read_stdin
2293 && (read_buffer
Bram Moolenaar8767f522016-07-01 17:17:39 +02002294 || vim_lseek(fd, (off_T)0L, SEEK_SET)
2295 == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002296 {
2297 fileformat = EOL_UNIX;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002298 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002299 set_fileformat(EOL_UNIX, OPT_LOCAL);
2300 file_rewind = TRUE;
2301 keep_fileformat = TRUE;
2302 goto retry;
2303 }
2304 ff_error = EOL_DOS;
2305 }
2306 }
2307 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2308 {
2309 error = TRUE;
2310 break;
2311 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002312#ifdef FEAT_PERSISTENT_UNDO
2313 if (read_undo_file)
2314 sha256_update(&sha_ctx, line_start, len);
2315#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002316 ++lnum;
2317 if (--read_count == 0)
2318 {
2319 error = TRUE; /* break loop */
2320 line_start = ptr; /* nothing left to write */
2321 break;
2322 }
2323 }
2324 else
2325 --skip_count;
2326 line_start = ptr + 1;
2327 }
2328 }
2329 }
2330 linerest = (long)(ptr - line_start);
2331 ui_breakcheck();
2332 }
2333
2334failed:
2335 /* not an error, max. number of lines reached */
2336 if (error && read_count == 0)
2337 error = FALSE;
2338
2339 /*
2340 * If we get EOF in the middle of a line, note the fact and
2341 * complete the line ourselves.
2342 * In Dos format ignore a trailing CTRL-Z, unless 'binary' set.
2343 */
2344 if (!error
2345 && !got_int
2346 && linerest != 0
2347 && !(!curbuf->b_p_bin
2348 && fileformat == EOL_DOS
2349 && *line_start == Ctrl_Z
2350 && ptr == line_start + 1))
2351 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002352 /* remember for when writing */
2353 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002354 curbuf->b_p_eol = FALSE;
2355 *ptr = NUL;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002356 len = (colnr_T)(ptr - line_start + 1);
2357 if (ml_append(lnum, line_start, len, newfile) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002358 error = TRUE;
2359 else
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002360 {
2361#ifdef FEAT_PERSISTENT_UNDO
2362 if (read_undo_file)
2363 sha256_update(&sha_ctx, line_start, len);
2364#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002365 read_no_eol_lnum = ++lnum;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002366 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002367 }
2368
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002369 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002370 save_file_ff(curbuf); /* remember the current file format */
2371
2372#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002373 if (curbuf->b_cryptstate != NULL)
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002374 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002375 crypt_free_state(curbuf->b_cryptstate);
2376 curbuf->b_cryptstate = NULL;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002377 }
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002378 if (cryptkey != NULL && cryptkey != curbuf->b_p_key)
2379 crypt_free_key(cryptkey);
2380 /* Don't set cryptkey to NULL, it's used below as a flag that
2381 * encryption was used. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002382#endif
2383
2384#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002385 /* If editing a new file: set 'fenc' for the current buffer.
2386 * Also for ":read ++edit file". */
2387 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002388 set_string_option_direct((char_u *)"fenc", -1, fenc,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00002389 OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002390 if (fenc_alloced)
2391 vim_free(fenc);
2392# ifdef USE_ICONV
2393 if (iconv_fd != (iconv_t)-1)
2394 {
2395 iconv_close(iconv_fd);
2396 iconv_fd = (iconv_t)-1;
2397 }
2398# endif
2399#endif
2400
2401 if (!read_buffer && !read_stdin)
2402 close(fd); /* errors are ignored */
Bram Moolenaarf05da212009-11-17 16:13:15 +00002403#ifdef HAVE_FD_CLOEXEC
2404 else
2405 {
2406 int fdflags = fcntl(fd, F_GETFD);
2407 if (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0)
Bram Moolenaarfbc4b4d2016-02-07 15:14:01 +01002408 (void)fcntl(fd, F_SETFD, fdflags | FD_CLOEXEC);
Bram Moolenaarf05da212009-11-17 16:13:15 +00002409 }
2410#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002411 vim_free(buffer);
2412
2413#ifdef HAVE_DUP
2414 if (read_stdin)
2415 {
2416 /* Use stderr for stdin, makes shell commands work. */
2417 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00002418 ignored = dup(2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002419 }
2420#endif
2421
2422#ifdef FEAT_MBYTE
2423 if (tmpname != NULL)
2424 {
2425 mch_remove(tmpname); /* delete converted file */
2426 vim_free(tmpname);
2427 }
2428#endif
2429 --no_wait_return; /* may wait for return now */
2430
2431 /*
2432 * In recovery mode everything but autocommands is skipped.
2433 */
2434 if (!recoverymode)
2435 {
2436 /* need to delete the last line, which comes from the empty buffer */
2437 if (newfile && wasempty && !(curbuf->b_ml.ml_flags & ML_EMPTY))
2438 {
2439#ifdef FEAT_NETBEANS_INTG
2440 netbeansFireChanges = 0;
2441#endif
2442 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
2443#ifdef FEAT_NETBEANS_INTG
2444 netbeansFireChanges = 1;
2445#endif
2446 --linecnt;
2447 }
2448 linecnt = curbuf->b_ml.ml_line_count - linecnt;
2449 if (filesize == 0)
2450 linecnt = 0;
2451 if (newfile || read_buffer)
Bram Moolenaar7263a772007-05-10 17:35:54 +00002452 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002453 redraw_curbuf_later(NOT_VALID);
Bram Moolenaar7263a772007-05-10 17:35:54 +00002454#ifdef FEAT_DIFF
2455 /* After reading the text into the buffer the diff info needs to
2456 * be updated. */
2457 diff_invalidate(curbuf);
2458#endif
2459#ifdef FEAT_FOLDING
2460 /* All folds in the window are invalid now. Mark them for update
2461 * before triggering autocommands. */
2462 foldUpdateAll(curwin);
2463#endif
2464 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002465 else if (linecnt) /* appended at least one line */
2466 appended_lines_mark(from, linecnt);
2467
Bram Moolenaar071d4272004-06-13 20:20:40 +00002468#ifndef ALWAYS_USE_GUI
2469 /*
2470 * If we were reading from the same terminal as where messages go,
2471 * the screen will have been messed up.
2472 * Switch on raw mode now and clear the screen.
2473 */
2474 if (read_stdin)
2475 {
2476 settmode(TMODE_RAW); /* set to raw mode */
2477 starttermcap();
2478 screenclear();
2479 }
2480#endif
2481
2482 if (got_int)
2483 {
2484 if (!(flags & READ_DUMMY))
2485 {
2486 filemess(curbuf, sfname, (char_u *)_(e_interr), 0);
2487 if (newfile)
2488 curbuf->b_p_ro = TRUE; /* must use "w!" now */
2489 }
2490 msg_scroll = msg_save;
2491#ifdef FEAT_VIMINFO
2492 check_marks_read();
2493#endif
2494 return OK; /* an interrupt isn't really an error */
2495 }
2496
2497 if (!filtering && !(flags & READ_DUMMY))
2498 {
2499 msg_add_fname(curbuf, sfname); /* fname in IObuff with quotes */
2500 c = FALSE;
2501
2502#ifdef UNIX
2503# ifdef S_ISFIFO
2504 if (S_ISFIFO(perm)) /* fifo or socket */
2505 {
2506 STRCAT(IObuff, _("[fifo/socket]"));
2507 c = TRUE;
2508 }
2509# else
2510# ifdef S_IFIFO
2511 if ((perm & S_IFMT) == S_IFIFO) /* fifo */
2512 {
2513 STRCAT(IObuff, _("[fifo]"));
2514 c = TRUE;
2515 }
2516# endif
2517# ifdef S_IFSOCK
2518 if ((perm & S_IFMT) == S_IFSOCK) /* or socket */
2519 {
2520 STRCAT(IObuff, _("[socket]"));
2521 c = TRUE;
2522 }
2523# endif
2524# endif
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002525# ifdef OPEN_CHR_FILES
2526 if (S_ISCHR(perm)) /* or character special */
2527 {
2528 STRCAT(IObuff, _("[character special]"));
2529 c = TRUE;
2530 }
2531# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002532#endif
2533 if (curbuf->b_p_ro)
2534 {
2535 STRCAT(IObuff, shortmess(SHM_RO) ? _("[RO]") : _("[readonly]"));
2536 c = TRUE;
2537 }
2538 if (read_no_eol_lnum)
2539 {
2540 msg_add_eol();
2541 c = TRUE;
2542 }
2543 if (ff_error == EOL_DOS)
2544 {
2545 STRCAT(IObuff, _("[CR missing]"));
2546 c = TRUE;
2547 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002548 if (split)
2549 {
2550 STRCAT(IObuff, _("[long lines split]"));
2551 c = TRUE;
2552 }
2553#ifdef FEAT_MBYTE
2554 if (notconverted)
2555 {
2556 STRCAT(IObuff, _("[NOT converted]"));
2557 c = TRUE;
2558 }
2559 else if (converted)
2560 {
2561 STRCAT(IObuff, _("[converted]"));
2562 c = TRUE;
2563 }
2564#endif
2565#ifdef FEAT_CRYPT
2566 if (cryptkey != NULL)
2567 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002568 crypt_append_msg(curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002569 c = TRUE;
2570 }
2571#endif
2572#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002573 if (conv_error != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002574 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002575 sprintf((char *)IObuff + STRLEN(IObuff),
2576 _("[CONVERSION ERROR in line %ld]"), (long)conv_error);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002577 c = TRUE;
2578 }
2579 else if (illegal_byte > 0)
2580 {
2581 sprintf((char *)IObuff + STRLEN(IObuff),
2582 _("[ILLEGAL BYTE in line %ld]"), (long)illegal_byte);
2583 c = TRUE;
2584 }
2585 else
2586#endif
2587 if (error)
2588 {
2589 STRCAT(IObuff, _("[READ ERRORS]"));
2590 c = TRUE;
2591 }
2592 if (msg_add_fileformat(fileformat))
2593 c = TRUE;
2594#ifdef FEAT_CRYPT
2595 if (cryptkey != NULL)
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002596 msg_add_lines(c, (long)linecnt, filesize
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002597 - crypt_get_header_len(crypt_get_method_nr(curbuf)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002598 else
2599#endif
2600 msg_add_lines(c, (long)linecnt, filesize);
2601
2602 vim_free(keep_msg);
2603 keep_msg = NULL;
2604 msg_scrolled_ign = TRUE;
2605#ifdef ALWAYS_USE_GUI
2606 /* Don't show the message when reading stdin, it would end up in a
2607 * message box (which might be shown when exiting!) */
2608 if (read_stdin || read_buffer)
2609 p = msg_may_trunc(FALSE, IObuff);
2610 else
2611#endif
2612 p = msg_trunc_attr(IObuff, FALSE, 0);
2613 if (read_stdin || read_buffer || restart_edit != 0
Bram Moolenaar1c7715d2005-10-03 22:02:18 +00002614 || (msg_scrolled != 0 && !need_wait_return))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002615 /* Need to repeat the message after redrawing when:
2616 * - When reading from stdin (the screen will be cleared next).
2617 * - When restart_edit is set (otherwise there will be a delay
2618 * before redrawing).
2619 * - When the screen was scrolled but there is no wait-return
2620 * prompt. */
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002621 set_keep_msg(p, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002622 msg_scrolled_ign = FALSE;
2623 }
2624
2625 /* with errors writing the file requires ":w!" */
2626 if (newfile && (error
2627#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002628 || conv_error != 0
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002629 || (illegal_byte > 0 && bad_char_behavior != BAD_KEEP)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002630#endif
2631 ))
2632 curbuf->b_p_ro = TRUE;
2633
2634 u_clearline(); /* cannot use "U" command after adding lines */
2635
2636 /*
2637 * In Ex mode: cursor at last new line.
2638 * Otherwise: cursor at first new line.
2639 */
2640 if (exmode_active)
2641 curwin->w_cursor.lnum = from + linecnt;
2642 else
2643 curwin->w_cursor.lnum = from + 1;
2644 check_cursor_lnum();
2645 beginline(BL_WHITE | BL_FIX); /* on first non-blank */
2646
2647 /*
2648 * Set '[ and '] marks to the newly read lines.
2649 */
2650 curbuf->b_op_start.lnum = from + 1;
2651 curbuf->b_op_start.col = 0;
2652 curbuf->b_op_end.lnum = from + linecnt;
2653 curbuf->b_op_end.col = 0;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002654
2655#ifdef WIN32
2656 /*
2657 * Work around a weird problem: When a file has two links (only
2658 * possible on NTFS) and we write through one link, then stat() it
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00002659 * through the other link, the timestamp information may be wrong.
Bram Moolenaar03f48552006-02-28 23:52:23 +00002660 * It's correct again after reading the file, thus reset the timestamp
2661 * here.
2662 */
2663 if (newfile && !read_stdin && !read_buffer
2664 && mch_stat((char *)fname, &st) >= 0)
2665 {
2666 buf_store_time(curbuf, &st, fname);
2667 curbuf->b_mtime_read = curbuf->b_mtime;
2668 }
2669#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002670 }
2671 msg_scroll = msg_save;
2672
2673#ifdef FEAT_VIMINFO
2674 /*
2675 * Get the marks before executing autocommands, so they can be used there.
2676 */
2677 check_marks_read();
2678#endif
2679
Bram Moolenaar071d4272004-06-13 20:20:40 +00002680 /*
Bram Moolenaar34d72d42015-07-17 14:18:08 +02002681 * We remember if the last line of the read didn't have
2682 * an eol even when 'binary' is off, to support turning 'fixeol' off,
2683 * or writing the read again with 'binary' on. The latter is required
2684 * for ":autocmd FileReadPost *.gz set bin|'[,']!gunzip" to work.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002685 */
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002686 curbuf->b_no_eol_lnum = read_no_eol_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002687
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02002688 /* When reloading a buffer put the cursor at the first line that is
2689 * different. */
2690 if (flags & READ_KEEP_UNDO)
2691 u_find_first_changed();
2692
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002693#ifdef FEAT_PERSISTENT_UNDO
2694 /*
2695 * When opening a new file locate undo info and read it.
2696 */
2697 if (read_undo_file)
2698 {
2699 char_u hash[UNDO_HASH_SIZE];
2700
2701 sha256_finish(&sha_ctx, hash);
Bram Moolenaar6ed8ed82010-05-30 20:40:11 +02002702 u_read_undo(NULL, hash, fname);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002703 }
2704#endif
2705
Bram Moolenaardf177f62005-02-22 08:39:57 +00002706#ifdef FEAT_AUTOCMD
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02002707 if (!read_stdin && !read_fifo && (!read_buffer || sfname != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002708 {
2709 int m = msg_scroll;
2710 int n = msg_scrolled;
2711
2712 /* Save the fileformat now, otherwise the buffer will be considered
2713 * modified if the format/encoding was automatically detected. */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002714 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002715 save_file_ff(curbuf);
2716
2717 /*
2718 * The output from the autocommands should not overwrite anything and
2719 * should not be overwritten: Set msg_scroll, restore its value if no
2720 * output was done.
2721 */
2722 msg_scroll = TRUE;
2723 if (filtering)
2724 apply_autocmds_exarg(EVENT_FILTERREADPOST, NULL, sfname,
2725 FALSE, curbuf, eap);
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02002726 else if (newfile || (read_buffer && sfname != NULL))
Bram Moolenaarc3691332016-04-20 12:49:49 +02002727 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002728 apply_autocmds_exarg(EVENT_BUFREADPOST, NULL, sfname,
2729 FALSE, curbuf, eap);
Bram Moolenaarc3691332016-04-20 12:49:49 +02002730 if (!au_did_filetype && *curbuf->b_p_ft != NUL)
2731 /*
2732 * EVENT_FILETYPE was not triggered but the buffer already has a
2733 * filetype. Trigger EVENT_FILETYPE using the existing filetype.
2734 */
2735 apply_autocmds(EVENT_FILETYPE, curbuf->b_p_ft, curbuf->b_fname,
2736 TRUE, curbuf);
2737 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002738 else
2739 apply_autocmds_exarg(EVENT_FILEREADPOST, sfname, sfname,
2740 FALSE, NULL, eap);
2741 if (msg_scrolled == n)
2742 msg_scroll = m;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002743# ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002744 if (aborting()) /* autocmds may abort script processing */
2745 return FAIL;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002746# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002747 }
2748#endif
2749
2750 if (recoverymode && error)
2751 return FAIL;
2752 return OK;
2753}
2754
Bram Moolenaarf04507d2016-08-20 15:05:39 +02002755#if defined(OPEN_CHR_FILES) || defined(PROTO)
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002756/*
2757 * Returns TRUE if the file name argument is of the form "/dev/fd/\d\+",
2758 * which is the name of files used for process substitution output by
2759 * some shells on some operating systems, e.g., bash on SunOS.
2760 * Do not accept "/dev/fd/[012]", opening these may hang Vim.
2761 */
Bram Moolenaarf04507d2016-08-20 15:05:39 +02002762 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002763is_dev_fd_file(char_u *fname)
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002764{
2765 return (STRNCMP(fname, "/dev/fd/", 8) == 0
2766 && VIM_ISDIGIT(fname[8])
2767 && *skipdigits(fname + 9) == NUL
2768 && (fname[9] != NUL
2769 || (fname[8] != '0' && fname[8] != '1' && fname[8] != '2')));
2770}
2771#endif
2772
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002773#ifdef FEAT_MBYTE
2774
2775/*
2776 * From the current line count and characters read after that, estimate the
2777 * line number where we are now.
2778 * Used for error messages that include a line number.
2779 */
2780 static linenr_T
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002781readfile_linenr(
2782 linenr_T linecnt, /* line count before reading more bytes */
2783 char_u *p, /* start of more bytes read */
2784 char_u *endp) /* end of more bytes read */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002785{
2786 char_u *s;
2787 linenr_T lnum;
2788
2789 lnum = curbuf->b_ml.ml_line_count - linecnt + 1;
2790 for (s = p; s < endp; ++s)
2791 if (*s == '\n')
2792 ++lnum;
2793 return lnum;
2794}
2795#endif
2796
Bram Moolenaar071d4272004-06-13 20:20:40 +00002797/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00002798 * Fill "*eap" to force the 'fileencoding', 'fileformat' and 'binary to be
2799 * equal to the buffer "buf". Used for calling readfile().
Bram Moolenaar071d4272004-06-13 20:20:40 +00002800 * Returns OK or FAIL.
2801 */
2802 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002803prep_exarg(exarg_T *eap, buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002804{
2805 eap->cmd = alloc((unsigned)(STRLEN(buf->b_p_ff)
2806#ifdef FEAT_MBYTE
2807 + STRLEN(buf->b_p_fenc)
2808#endif
2809 + 15));
2810 if (eap->cmd == NULL)
2811 return FAIL;
2812
2813#ifdef FEAT_MBYTE
2814 sprintf((char *)eap->cmd, "e ++ff=%s ++enc=%s", buf->b_p_ff, buf->b_p_fenc);
2815 eap->force_enc = 14 + (int)STRLEN(buf->b_p_ff);
Bram Moolenaar195d6352005-12-19 22:08:24 +00002816 eap->bad_char = buf->b_bad_char;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002817#else
2818 sprintf((char *)eap->cmd, "e ++ff=%s", buf->b_p_ff);
2819#endif
2820 eap->force_ff = 7;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002821
2822 eap->force_bin = buf->b_p_bin ? FORCE_BIN : FORCE_NOBIN;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002823 eap->read_edit = FALSE;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002824 eap->forceit = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002825 return OK;
2826}
2827
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002828/*
2829 * Set default or forced 'fileformat' and 'binary'.
2830 */
2831 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002832set_file_options(int set_options, exarg_T *eap)
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002833{
2834 /* set default 'fileformat' */
2835 if (set_options)
2836 {
2837 if (eap != NULL && eap->force_ff != 0)
2838 set_fileformat(get_fileformat_force(curbuf, eap), OPT_LOCAL);
2839 else if (*p_ffs != NUL)
2840 set_fileformat(default_fileformat(), OPT_LOCAL);
2841 }
2842
2843 /* set or reset 'binary' */
2844 if (eap != NULL && eap->force_bin != 0)
2845 {
2846 int oldval = curbuf->b_p_bin;
2847
2848 curbuf->b_p_bin = (eap->force_bin == FORCE_BIN);
2849 set_options_bin(oldval, curbuf->b_p_bin, OPT_LOCAL);
2850 }
2851}
2852
2853#if defined(FEAT_MBYTE) || defined(PROTO)
2854/*
2855 * Set forced 'fileencoding'.
2856 */
2857 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002858set_forced_fenc(exarg_T *eap)
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002859{
2860 if (eap->force_enc != 0)
2861 {
2862 char_u *fenc = enc_canonize(eap->cmd + eap->force_enc);
2863
2864 if (fenc != NULL)
2865 set_string_option_direct((char_u *)"fenc", -1,
2866 fenc, OPT_FREE|OPT_LOCAL, 0);
2867 vim_free(fenc);
2868 }
2869}
2870
Bram Moolenaar071d4272004-06-13 20:20:40 +00002871/*
2872 * Find next fileencoding to use from 'fileencodings'.
2873 * "pp" points to fenc_next. It's advanced to the next item.
2874 * When there are no more items, an empty string is returned and *pp is set to
2875 * NULL.
2876 * When *pp is not set to NULL, the result is in allocated memory.
2877 */
2878 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002879next_fenc(char_u **pp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002880{
2881 char_u *p;
2882 char_u *r;
2883
2884 if (**pp == NUL)
2885 {
2886 *pp = NULL;
2887 return (char_u *)"";
2888 }
2889 p = vim_strchr(*pp, ',');
2890 if (p == NULL)
2891 {
2892 r = enc_canonize(*pp);
2893 *pp += STRLEN(*pp);
2894 }
2895 else
2896 {
2897 r = vim_strnsave(*pp, (int)(p - *pp));
2898 *pp = p + 1;
2899 if (r != NULL)
2900 {
2901 p = enc_canonize(r);
2902 vim_free(r);
2903 r = p;
2904 }
2905 }
2906 if (r == NULL) /* out of memory */
2907 {
2908 r = (char_u *)"";
2909 *pp = NULL;
2910 }
2911 return r;
2912}
2913
2914# ifdef FEAT_EVAL
2915/*
2916 * Convert a file with the 'charconvert' expression.
2917 * This closes the file which is to be read, converts it and opens the
2918 * resulting file for reading.
2919 * Returns name of the resulting converted file (the caller should delete it
2920 * after reading it).
2921 * Returns NULL if the conversion failed ("*fdp" is not set) .
2922 */
2923 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002924readfile_charconvert(
2925 char_u *fname, /* name of input file */
2926 char_u *fenc, /* converted from */
2927 int *fdp) /* in/out: file descriptor of file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002928{
2929 char_u *tmpname;
2930 char_u *errmsg = NULL;
2931
Bram Moolenaare5c421c2015-03-31 13:33:08 +02002932 tmpname = vim_tempname('r', FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002933 if (tmpname == NULL)
2934 errmsg = (char_u *)_("Can't find temp file for conversion");
2935 else
2936 {
2937 close(*fdp); /* close the input file, ignore errors */
2938 *fdp = -1;
2939 if (eval_charconvert(fenc, enc_utf8 ? (char_u *)"utf-8" : p_enc,
2940 fname, tmpname) == FAIL)
2941 errmsg = (char_u *)_("Conversion with 'charconvert' failed");
2942 if (errmsg == NULL && (*fdp = mch_open((char *)tmpname,
2943 O_RDONLY | O_EXTRA, 0)) < 0)
2944 errmsg = (char_u *)_("can't read output of 'charconvert'");
2945 }
2946
2947 if (errmsg != NULL)
2948 {
2949 /* Don't use emsg(), it breaks mappings, the retry with
2950 * another type of conversion might still work. */
2951 MSG(errmsg);
2952 if (tmpname != NULL)
2953 {
2954 mch_remove(tmpname); /* delete converted file */
2955 vim_free(tmpname);
2956 tmpname = NULL;
2957 }
2958 }
2959
2960 /* If the input file is closed, open it (caller should check for error). */
2961 if (*fdp < 0)
2962 *fdp = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
2963
2964 return tmpname;
2965}
2966# endif
2967
2968#endif
2969
2970#ifdef FEAT_VIMINFO
2971/*
2972 * Read marks for the current buffer from the viminfo file, when we support
2973 * buffer marks and the buffer has a name.
2974 */
2975 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002976check_marks_read(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002977{
2978 if (!curbuf->b_marks_read && get_viminfo_parameter('\'') > 0
2979 && curbuf->b_ffname != NULL)
Bram Moolenaard812df62008-11-09 12:46:09 +00002980 read_viminfo(NULL, VIF_WANT_MARKS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002981
2982 /* Always set b_marks_read; needed when 'viminfo' is changed to include
2983 * the ' parameter after opening a buffer. */
2984 curbuf->b_marks_read = TRUE;
2985}
2986#endif
2987
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002988#if defined(FEAT_CRYPT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002989/*
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002990 * Check for magic number used for encryption. Applies to the current buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002991 * If found, the magic number is removed from ptr[*sizep] and *sizep and
2992 * *filesizep are updated.
2993 * Return the (new) encryption key, NULL for no encryption.
2994 */
2995 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002996check_for_cryptkey(
2997 char_u *cryptkey, /* previous encryption key or NULL */
2998 char_u *ptr, /* pointer to read bytes */
2999 long *sizep, /* length of read bytes */
Bram Moolenaar8767f522016-07-01 17:17:39 +02003000 off_T *filesizep, /* nr of bytes used from file */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003001 int newfile, /* editing a new buffer */
3002 char_u *fname, /* file name to display */
3003 int *did_ask) /* flag: whether already asked for key */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003004{
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003005 int method = crypt_method_nr_from_magic((char *)ptr, *sizep);
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02003006 int b_p_ro = curbuf->b_p_ro;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003007
3008 if (method >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003009 {
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02003010 /* Mark the buffer as read-only until the decryption has taken place.
3011 * Avoids accidentally overwriting the file with garbage. */
3012 curbuf->b_p_ro = TRUE;
3013
Bram Moolenaar2be79502014-08-13 21:58:28 +02003014 /* Set the cryptmethod local to the buffer. */
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003015 crypt_set_cm_option(curbuf, method);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02003016 if (cryptkey == NULL && !*did_ask)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003017 {
3018 if (*curbuf->b_p_key)
3019 cryptkey = curbuf->b_p_key;
3020 else
3021 {
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003022 /* When newfile is TRUE, store the typed key in the 'key'
3023 * option and don't free it. bf needs hash of the key saved.
Bram Moolenaarf50a2532010-05-21 15:36:08 +02003024 * Don't ask for the key again when first time Enter was hit.
3025 * Happens when retrying to detect encoding. */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003026 smsg((char_u *)_(need_key_msg), fname);
3027 msg_scroll = TRUE;
Bram Moolenaar3a0c9082014-11-12 15:15:42 +01003028 crypt_check_method(method);
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003029 cryptkey = crypt_get_key(newfile, FALSE);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02003030 *did_ask = TRUE;
3031
Bram Moolenaar071d4272004-06-13 20:20:40 +00003032 /* check if empty key entered */
3033 if (cryptkey != NULL && *cryptkey == NUL)
3034 {
3035 if (cryptkey != curbuf->b_p_key)
3036 vim_free(cryptkey);
3037 cryptkey = NULL;
3038 }
3039 }
3040 }
3041
3042 if (cryptkey != NULL)
3043 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003044 int header_len;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003045
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003046 curbuf->b_cryptstate = crypt_create_from_header(
3047 method, cryptkey, ptr);
3048 crypt_set_cm_option(curbuf, method);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003049
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003050 /* Remove cryptmethod specific header from the text. */
3051 header_len = crypt_get_header_len(method);
Bram Moolenaar680e0152016-09-25 20:54:11 +02003052 if (*sizep <= header_len)
3053 /* invalid header, buffer can't be encrypted */
3054 return NULL;
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003055 *filesizep += header_len;
3056 *sizep -= header_len;
3057 mch_memmove(ptr, ptr + header_len, (size_t)*sizep);
3058
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02003059 /* Restore the read-only flag. */
3060 curbuf->b_p_ro = b_p_ro;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003061 }
3062 }
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003063 /* When starting to edit a new file which does not have encryption, clear
3064 * the 'key' option, except when starting up (called with -x argument) */
Bram Moolenaarfa0ff9a2010-07-25 16:05:19 +02003065 else if (newfile && *curbuf->b_p_key != NUL && !starting)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003066 set_option_value((char_u *)"key", 0L, (char_u *)"", OPT_LOCAL);
3067
3068 return cryptkey;
3069}
Bram Moolenaar80794b12010-06-13 05:20:42 +02003070#endif /* FEAT_CRYPT */
3071
Bram Moolenaar071d4272004-06-13 20:20:40 +00003072#ifdef UNIX
3073 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003074set_file_time(
3075 char_u *fname,
3076 time_t atime, /* access time */
3077 time_t mtime) /* modification time */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003078{
3079# if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
3080 struct utimbuf buf;
3081
3082 buf.actime = atime;
3083 buf.modtime = mtime;
3084 (void)utime((char *)fname, &buf);
3085# else
3086# if defined(HAVE_UTIMES)
3087 struct timeval tvp[2];
3088
3089 tvp[0].tv_sec = atime;
3090 tvp[0].tv_usec = 0;
3091 tvp[1].tv_sec = mtime;
3092 tvp[1].tv_usec = 0;
3093# ifdef NeXT
3094 (void)utimes((char *)fname, tvp);
3095# else
3096 (void)utimes((char *)fname, (const struct timeval *)&tvp);
3097# endif
3098# endif
3099# endif
3100}
3101#endif /* UNIX */
3102
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003103#if defined(VMS) && !defined(MIN)
3104/* Older DECC compiler for VAX doesn't define MIN() */
3105# define MIN(a, b) ((a) < (b) ? (a) : (b))
3106#endif
3107
Bram Moolenaar071d4272004-06-13 20:20:40 +00003108/*
Bram Moolenaar5386a122007-06-28 20:02:32 +00003109 * Return TRUE if a file appears to be read-only from the file permissions.
3110 */
3111 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003112check_file_readonly(
3113 char_u *fname, /* full path to file */
3114 int perm) /* known permissions on file */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003115{
3116#ifndef USE_MCH_ACCESS
3117 int fd = 0;
3118#endif
3119
3120 return (
3121#ifdef USE_MCH_ACCESS
3122# ifdef UNIX
3123 (perm & 0222) == 0 ||
3124# endif
3125 mch_access((char *)fname, W_OK)
3126#else
3127 (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0
3128 ? TRUE : (close(fd), FALSE)
3129#endif
3130 );
3131}
3132
3133
3134/*
Bram Moolenaar292ad192005-12-11 21:29:51 +00003135 * buf_write() - write to file "fname" lines "start" through "end"
Bram Moolenaar071d4272004-06-13 20:20:40 +00003136 *
3137 * We do our own buffering here because fwrite() is so slow.
3138 *
Bram Moolenaar292ad192005-12-11 21:29:51 +00003139 * If "forceit" is true, we don't care for errors when attempting backups.
3140 * In case of an error everything possible is done to restore the original
Bram Moolenaare37d50a2008-08-06 17:06:04 +00003141 * file. But when "forceit" is TRUE, we risk losing it.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003142 *
3143 * When "reset_changed" is TRUE and "append" == FALSE and "start" == 1 and
3144 * "end" == curbuf->b_ml.ml_line_count, reset curbuf->b_changed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003145 *
3146 * This function must NOT use NameBuff (because it's called by autowrite()).
3147 *
3148 * return FAIL for failure, OK otherwise
3149 */
3150 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003151buf_write(
3152 buf_T *buf,
3153 char_u *fname,
3154 char_u *sfname,
3155 linenr_T start,
3156 linenr_T end,
3157 exarg_T *eap, /* for forced 'ff' and 'fenc', can be
Bram Moolenaar071d4272004-06-13 20:20:40 +00003158 NULL! */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003159 int append, /* append to the file */
3160 int forceit,
3161 int reset_changed,
3162 int filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003163{
3164 int fd;
3165 char_u *backup = NULL;
3166 int backup_copy = FALSE; /* copy the original file? */
3167 int dobackup;
3168 char_u *ffname;
3169 char_u *wfname = NULL; /* name of file to write to */
3170 char_u *s;
3171 char_u *ptr;
3172 char_u c;
3173 int len;
3174 linenr_T lnum;
3175 long nchars;
3176 char_u *errmsg = NULL;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003177 int errmsg_allocated = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003178 char_u *errnum = NULL;
3179 char_u *buffer;
3180 char_u smallbuf[SMBUFSIZE];
3181 char_u *backup_ext;
3182 int bufsize;
3183 long perm; /* file permissions */
3184 int retval = OK;
3185 int newfile = FALSE; /* TRUE if file doesn't exist yet */
3186 int msg_save = msg_scroll;
3187 int overwriting; /* TRUE if writing over original */
3188 int no_eol = FALSE; /* no end-of-line written */
3189 int device = FALSE; /* writing to a device */
Bram Moolenaar8767f522016-07-01 17:17:39 +02003190 stat_T st_old;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003191 int prev_got_int = got_int;
Bram Moolenaare6bf6552017-06-27 22:11:51 +02003192 int checking_conversion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003193 int file_readonly = FALSE; /* overwritten file is read-only */
3194 static char *err_readonly = "is read-only (cannot override: \"W\" in 'cpoptions')";
Bram Moolenaara06ecab2016-07-16 14:47:36 +02003195#if defined(UNIX) /*XXX fix me sometime? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003196 int made_writable = FALSE; /* 'w' bit has been set */
3197#endif
3198 /* writing everything */
3199 int whole = (start == 1 && end == buf->b_ml.ml_line_count);
3200#ifdef FEAT_AUTOCMD
3201 linenr_T old_line_count = buf->b_ml.ml_line_count;
3202#endif
3203 int attr;
3204 int fileformat;
3205 int write_bin;
3206 struct bw_info write_info; /* info for buf_write_bytes() */
3207#ifdef FEAT_MBYTE
3208 int converted = FALSE;
3209 int notconverted = FALSE;
3210 char_u *fenc; /* effective 'fileencoding' */
3211 char_u *fenc_tofree = NULL; /* allocated "fenc" */
3212#endif
3213#ifdef HAS_BW_FLAGS
3214 int wb_flags = 0;
3215#endif
3216#ifdef HAVE_ACL
3217 vim_acl_T acl = NULL; /* ACL copied from original file to
3218 backup or new file */
3219#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003220#ifdef FEAT_PERSISTENT_UNDO
3221 int write_undo_file = FALSE;
3222 context_sha256_T sha_ctx;
3223#endif
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003224 unsigned int bkc = get_bkc_value(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003225
3226 if (fname == NULL || *fname == NUL) /* safety check */
3227 return FAIL;
Bram Moolenaar70d60e92009-12-31 13:53:33 +00003228 if (buf->b_ml.ml_mfp == NULL)
3229 {
3230 /* This can happen during startup when there is a stray "w" in the
3231 * vimrc file. */
3232 EMSG(_(e_emptybuf));
3233 return FAIL;
3234 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003235
3236 /*
3237 * Disallow writing from .exrc and .vimrc in current directory for
3238 * security reasons.
3239 */
3240 if (check_secure())
3241 return FAIL;
3242
3243 /* Avoid a crash for a long name. */
3244 if (STRLEN(fname) >= MAXPATHL)
3245 {
3246 EMSG(_(e_longname));
3247 return FAIL;
3248 }
3249
3250#ifdef FEAT_MBYTE
3251 /* must init bw_conv_buf and bw_iconv_fd before jumping to "fail" */
3252 write_info.bw_conv_buf = NULL;
3253 write_info.bw_conv_error = FALSE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003254 write_info.bw_conv_error_lnum = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003255 write_info.bw_restlen = 0;
3256# ifdef USE_ICONV
3257 write_info.bw_iconv_fd = (iconv_t)-1;
3258# endif
3259#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003260#ifdef FEAT_CRYPT
3261 write_info.bw_buffer = buf;
3262#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003263
Bram Moolenaardf177f62005-02-22 08:39:57 +00003264 /* After writing a file changedtick changes but we don't want to display
3265 * the line. */
3266 ex_no_reprint = TRUE;
3267
Bram Moolenaar071d4272004-06-13 20:20:40 +00003268 /*
3269 * If there is no file name yet, use the one for the written file.
3270 * BF_NOTEDITED is set to reflect this (in case the write fails).
3271 * Don't do this when the write is for a filter command.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003272 * Don't do this when appending.
3273 * Only do this when 'cpoptions' contains the 'F' flag.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003274 */
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003275 if (buf->b_ffname == NULL
3276 && reset_changed
Bram Moolenaar071d4272004-06-13 20:20:40 +00003277 && whole
3278 && buf == curbuf
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00003279#ifdef FEAT_QUICKFIX
3280 && !bt_nofile(buf)
3281#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003282 && !filtering
Bram Moolenaar292ad192005-12-11 21:29:51 +00003283 && (!append || vim_strchr(p_cpo, CPO_FNAMEAPP) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003284 && vim_strchr(p_cpo, CPO_FNAMEW) != NULL)
3285 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003286 if (set_rw_fname(fname, sfname) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003287 return FAIL;
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003288 buf = curbuf; /* just in case autocmds made "buf" invalid */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003289 }
3290
3291 if (sfname == NULL)
3292 sfname = fname;
3293 /*
3294 * For Unix: Use the short file name whenever possible.
3295 * Avoids problems with networks and when directory names are changed.
3296 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
3297 * another directory, which we don't detect
3298 */
3299 ffname = fname; /* remember full fname */
3300#ifdef UNIX
3301 fname = sfname;
3302#endif
3303
3304 if (buf->b_ffname != NULL && fnamecmp(ffname, buf->b_ffname) == 0)
3305 overwriting = TRUE;
3306 else
3307 overwriting = FALSE;
3308
3309 if (exiting)
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003310 settmode(TMODE_COOK); /* when exiting allow typeahead now */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003311
3312 ++no_wait_return; /* don't wait for return yet */
3313
3314 /*
3315 * Set '[ and '] marks to the lines to be written.
3316 */
3317 buf->b_op_start.lnum = start;
3318 buf->b_op_start.col = 0;
3319 buf->b_op_end.lnum = end;
3320 buf->b_op_end.col = 0;
3321
3322#ifdef FEAT_AUTOCMD
3323 {
3324 aco_save_T aco;
3325 int buf_ffname = FALSE;
3326 int buf_sfname = FALSE;
3327 int buf_fname_f = FALSE;
3328 int buf_fname_s = FALSE;
3329 int did_cmd = FALSE;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003330 int nofile_err = FALSE;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003331 int empty_memline = (buf->b_ml.ml_mfp == NULL);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003332 bufref_T bufref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003333
3334 /*
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003335 * Apply PRE autocommands.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003336 * Set curbuf to the buffer to be written.
3337 * Careful: The autocommands may call buf_write() recursively!
3338 */
3339 if (ffname == buf->b_ffname)
3340 buf_ffname = TRUE;
3341 if (sfname == buf->b_sfname)
3342 buf_sfname = TRUE;
3343 if (fname == buf->b_ffname)
3344 buf_fname_f = TRUE;
3345 if (fname == buf->b_sfname)
3346 buf_fname_s = TRUE;
3347
3348 /* set curwin/curbuf to buf and save a few things */
3349 aucmd_prepbuf(&aco, buf);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003350 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003351
3352 if (append)
3353 {
3354 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD,
3355 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003356 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003357#ifdef FEAT_QUICKFIX
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00003358 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003359 nofile_err = TRUE;
3360 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003361#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003362 apply_autocmds_exarg(EVENT_FILEAPPENDPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003363 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003364 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003365 }
3366 else if (filtering)
3367 {
3368 apply_autocmds_exarg(EVENT_FILTERWRITEPRE,
3369 NULL, sfname, FALSE, curbuf, eap);
3370 }
3371 else if (reset_changed && whole)
3372 {
Bram Moolenaar39fc42e2011-09-02 11:56:20 +02003373 int was_changed = curbufIsChanged();
3374
3375 did_cmd = apply_autocmds_exarg(EVENT_BUFWRITECMD,
3376 sfname, sfname, FALSE, curbuf, eap);
3377 if (did_cmd)
3378 {
3379 if (was_changed && !curbufIsChanged())
3380 {
3381 /* Written everything correctly and BufWriteCmd has reset
3382 * 'modified': Correct the undo information so that an
3383 * undo now sets 'modified'. */
3384 u_unchanged(curbuf);
3385 u_update_save_nr(curbuf);
3386 }
3387 }
3388 else
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003389 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003390#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003391 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003392 nofile_err = TRUE;
3393 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003394#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003395 apply_autocmds_exarg(EVENT_BUFWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003396 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003397 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003398 }
3399 else
3400 {
3401 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD,
3402 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003403 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003404#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003405 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003406 nofile_err = TRUE;
3407 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003408#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003409 apply_autocmds_exarg(EVENT_FILEWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003410 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003411 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003412 }
3413
3414 /* restore curwin/curbuf and a few other things */
3415 aucmd_restbuf(&aco);
3416
3417 /*
3418 * In three situations we return here and don't write the file:
3419 * 1. the autocommands deleted or unloaded the buffer.
3420 * 2. The autocommands abort script processing.
3421 * 3. If one of the "Cmd" autocommands was executed.
3422 */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003423 if (!bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003424 buf = NULL;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003425 if (buf == NULL || (buf->b_ml.ml_mfp == NULL && !empty_memline)
Bram Moolenaar1e015462005-09-25 22:16:38 +00003426 || did_cmd || nofile_err
3427#ifdef FEAT_EVAL
3428 || aborting()
3429#endif
3430 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003431 {
3432 --no_wait_return;
3433 msg_scroll = msg_save;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003434 if (nofile_err)
3435 EMSG(_("E676: No matching autocommands for acwrite buffer"));
3436
Bram Moolenaar1e015462005-09-25 22:16:38 +00003437 if (nofile_err
3438#ifdef FEAT_EVAL
3439 || aborting()
3440#endif
3441 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003442 /* An aborting error, interrupt or exception in the
3443 * autocommands. */
3444 return FAIL;
3445 if (did_cmd)
3446 {
3447 if (buf == NULL)
3448 /* The buffer was deleted. We assume it was written
3449 * (can't retry anyway). */
3450 return OK;
3451 if (overwriting)
3452 {
3453 /* Assume the buffer was written, update the timestamp. */
3454 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00003455 if (append)
3456 buf->b_flags &= ~BF_NEW;
3457 else
3458 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003459 }
Bram Moolenaar292ad192005-12-11 21:29:51 +00003460 if (reset_changed && buf->b_changed && !append
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003461 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003462 /* Buffer still changed, the autocommands didn't work
3463 * properly. */
3464 return FAIL;
3465 return OK;
3466 }
3467#ifdef FEAT_EVAL
3468 if (!aborting())
3469#endif
3470 EMSG(_("E203: Autocommands deleted or unloaded buffer to be written"));
3471 return FAIL;
3472 }
3473
3474 /*
3475 * The autocommands may have changed the number of lines in the file.
3476 * When writing the whole file, adjust the end.
3477 * When writing part of the file, assume that the autocommands only
3478 * changed the number of lines that are to be written (tricky!).
3479 */
3480 if (buf->b_ml.ml_line_count != old_line_count)
3481 {
3482 if (whole) /* write all */
3483 end = buf->b_ml.ml_line_count;
3484 else if (buf->b_ml.ml_line_count > old_line_count) /* more lines */
3485 end += buf->b_ml.ml_line_count - old_line_count;
3486 else /* less lines */
3487 {
3488 end -= old_line_count - buf->b_ml.ml_line_count;
3489 if (end < start)
3490 {
3491 --no_wait_return;
3492 msg_scroll = msg_save;
3493 EMSG(_("E204: Autocommand changed number of lines in unexpected way"));
3494 return FAIL;
3495 }
3496 }
3497 }
3498
3499 /*
3500 * The autocommands may have changed the name of the buffer, which may
3501 * be kept in fname, ffname and sfname.
3502 */
3503 if (buf_ffname)
3504 ffname = buf->b_ffname;
3505 if (buf_sfname)
3506 sfname = buf->b_sfname;
3507 if (buf_fname_f)
3508 fname = buf->b_ffname;
3509 if (buf_fname_s)
3510 fname = buf->b_sfname;
3511 }
3512#endif
3513
3514#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003515 if (netbeans_active() && isNetbeansBuffer(buf))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003516 {
3517 if (whole)
3518 {
3519 /*
3520 * b_changed can be 0 after an undo, but we still need to write
3521 * the buffer to NetBeans.
3522 */
3523 if (buf->b_changed || isNetbeansModified(buf))
3524 {
Bram Moolenaar009b2592004-10-24 19:18:58 +00003525 --no_wait_return; /* may wait for return now */
3526 msg_scroll = msg_save;
3527 netbeans_save_buffer(buf); /* no error checking... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003528 return retval;
3529 }
3530 else
3531 {
3532 errnum = (char_u *)"E656: ";
Bram Moolenaared0e7452008-06-27 19:17:34 +00003533 errmsg = (char_u *)_("NetBeans disallows writes of unmodified buffers");
Bram Moolenaar071d4272004-06-13 20:20:40 +00003534 buffer = NULL;
3535 goto fail;
3536 }
3537 }
3538 else
3539 {
3540 errnum = (char_u *)"E657: ";
3541 errmsg = (char_u *)_("Partial writes disallowed for NetBeans buffers");
3542 buffer = NULL;
3543 goto fail;
3544 }
3545 }
3546#endif
3547
3548 if (shortmess(SHM_OVER) && !exiting)
3549 msg_scroll = FALSE; /* overwrite previous file message */
3550 else
3551 msg_scroll = TRUE; /* don't overwrite previous file message */
3552 if (!filtering)
3553 filemess(buf,
3554#ifndef UNIX
3555 sfname,
3556#else
3557 fname,
3558#endif
3559 (char_u *)"", 0); /* show that we are busy */
3560 msg_scroll = FALSE; /* always overwrite the file message now */
3561
3562 buffer = alloc(BUFSIZE);
3563 if (buffer == NULL) /* can't allocate big buffer, use small
3564 * one (to be able to write when out of
3565 * memory) */
3566 {
3567 buffer = smallbuf;
3568 bufsize = SMBUFSIZE;
3569 }
3570 else
3571 bufsize = BUFSIZE;
3572
3573 /*
3574 * Get information about original file (if there is one).
3575 */
Bram Moolenaar53076832015-12-31 19:53:21 +01003576#if defined(UNIX)
Bram Moolenaar6f192452007-11-08 19:49:02 +00003577 st_old.st_dev = 0;
3578 st_old.st_ino = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003579 perm = -1;
3580 if (mch_stat((char *)fname, &st_old) < 0)
3581 newfile = TRUE;
3582 else
3583 {
3584 perm = st_old.st_mode;
3585 if (!S_ISREG(st_old.st_mode)) /* not a file */
3586 {
3587 if (S_ISDIR(st_old.st_mode))
3588 {
3589 errnum = (char_u *)"E502: ";
3590 errmsg = (char_u *)_("is a directory");
3591 goto fail;
3592 }
3593 if (mch_nodetype(fname) != NODE_WRITABLE)
3594 {
3595 errnum = (char_u *)"E503: ";
3596 errmsg = (char_u *)_("is not a file or writable device");
3597 goto fail;
3598 }
3599 /* It's a device of some kind (or a fifo) which we can write to
3600 * but for which we can't make a backup. */
3601 device = TRUE;
3602 newfile = TRUE;
3603 perm = -1;
3604 }
3605 }
3606#else /* !UNIX */
3607 /*
3608 * Check for a writable device name.
3609 */
3610 c = mch_nodetype(fname);
3611 if (c == NODE_OTHER)
3612 {
3613 errnum = (char_u *)"E503: ";
3614 errmsg = (char_u *)_("is not a file or writable device");
3615 goto fail;
3616 }
3617 if (c == NODE_WRITABLE)
3618 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003619# if defined(MSWIN)
Bram Moolenaar043545e2006-10-10 16:44:07 +00003620 /* MS-Windows allows opening a device, but we will probably get stuck
3621 * trying to write to it. */
3622 if (!p_odev)
3623 {
3624 errnum = (char_u *)"E796: ";
3625 errmsg = (char_u *)_("writing to device disabled with 'opendevice' option");
3626 goto fail;
3627 }
3628# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003629 device = TRUE;
3630 newfile = TRUE;
3631 perm = -1;
3632 }
3633 else
3634 {
3635 perm = mch_getperm(fname);
3636 if (perm < 0)
3637 newfile = TRUE;
3638 else if (mch_isdir(fname))
3639 {
3640 errnum = (char_u *)"E502: ";
3641 errmsg = (char_u *)_("is a directory");
3642 goto fail;
3643 }
3644 if (overwriting)
3645 (void)mch_stat((char *)fname, &st_old);
3646 }
3647#endif /* !UNIX */
3648
3649 if (!device && !newfile)
3650 {
3651 /*
3652 * Check if the file is really writable (when renaming the file to
3653 * make a backup we won't discover it later).
3654 */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003655 file_readonly = check_file_readonly(fname, (int)perm);
3656
Bram Moolenaar071d4272004-06-13 20:20:40 +00003657 if (!forceit && file_readonly)
3658 {
3659 if (vim_strchr(p_cpo, CPO_FWRITE) != NULL)
3660 {
3661 errnum = (char_u *)"E504: ";
3662 errmsg = (char_u *)_(err_readonly);
3663 }
3664 else
3665 {
3666 errnum = (char_u *)"E505: ";
3667 errmsg = (char_u *)_("is read-only (add ! to override)");
3668 }
3669 goto fail;
3670 }
3671
3672 /*
3673 * Check if the timestamp hasn't changed since reading the file.
3674 */
3675 if (overwriting)
3676 {
3677 retval = check_mtime(buf, &st_old);
3678 if (retval == FAIL)
3679 goto fail;
3680 }
3681 }
3682
3683#ifdef HAVE_ACL
3684 /*
3685 * For systems that support ACL: get the ACL from the original file.
3686 */
3687 if (!newfile)
3688 acl = mch_get_acl(fname);
3689#endif
3690
3691 /*
3692 * If 'backupskip' is not empty, don't make a backup for some files.
3693 */
3694 dobackup = (p_wb || p_bk || *p_pm != NUL);
3695#ifdef FEAT_WILDIGN
3696 if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname))
3697 dobackup = FALSE;
3698#endif
3699
3700 /*
3701 * Save the value of got_int and reset it. We don't want a previous
3702 * interruption cancel writing, only hitting CTRL-C while writing should
3703 * abort it.
3704 */
3705 prev_got_int = got_int;
3706 got_int = FALSE;
3707
3708 /* Mark the buffer as 'being saved' to prevent changed buffer warnings */
3709 buf->b_saving = TRUE;
3710
3711 /*
3712 * If we are not appending or filtering, the file exists, and the
3713 * 'writebackup', 'backup' or 'patchmode' option is set, need a backup.
3714 * When 'patchmode' is set also make a backup when appending.
3715 *
3716 * Do not make any backup, if 'writebackup' and 'backup' are both switched
3717 * off. This helps when editing large files on almost-full disks.
3718 */
3719 if (!(append && *p_pm == NUL) && !filtering && perm >= 0 && dobackup)
3720 {
3721#if defined(UNIX) || defined(WIN32)
Bram Moolenaar8767f522016-07-01 17:17:39 +02003722 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003723#endif
3724
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003725 if ((bkc & BKC_YES) || append) /* "yes" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003726 backup_copy = TRUE;
3727#if defined(UNIX) || defined(WIN32)
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003728 else if ((bkc & BKC_AUTO)) /* "auto" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003729 {
3730 int i;
3731
3732# ifdef UNIX
3733 /*
3734 * Don't rename the file when:
3735 * - it's a hard link
3736 * - it's a symbolic link
3737 * - we don't have write permission in the directory
3738 * - we can't set the owner/group of the new file
3739 */
3740 if (st_old.st_nlink > 1
3741 || mch_lstat((char *)fname, &st) < 0
3742 || st.st_dev != st_old.st_dev
Bram Moolenaara5792f52005-11-23 21:25:05 +00003743 || st.st_ino != st_old.st_ino
3744# ifndef HAVE_FCHOWN
3745 || st.st_uid != st_old.st_uid
3746 || st.st_gid != st_old.st_gid
3747# endif
3748 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003749 backup_copy = TRUE;
3750 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003751# else
3752# ifdef WIN32
3753 /* On NTFS file systems hard links are possible. */
3754 if (mch_is_linked(fname))
3755 backup_copy = TRUE;
3756 else
3757# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003758# endif
3759 {
3760 /*
3761 * Check if we can create a file and set the owner/group to
3762 * the ones from the original file.
3763 * First find a file name that doesn't exist yet (use some
3764 * arbitrary numbers).
3765 */
3766 STRCPY(IObuff, fname);
3767 for (i = 4913; ; i += 123)
3768 {
3769 sprintf((char *)gettail(IObuff), "%d", i);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003770 if (mch_lstat((char *)IObuff, &st) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003771 break;
3772 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00003773 fd = mch_open((char *)IObuff,
3774 O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003775 if (fd < 0) /* can't write in directory */
3776 backup_copy = TRUE;
3777 else
3778 {
3779# ifdef UNIX
Bram Moolenaara5792f52005-11-23 21:25:05 +00003780# ifdef HAVE_FCHOWN
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00003781 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003782# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003783 if (mch_stat((char *)IObuff, &st) < 0
3784 || st.st_uid != st_old.st_uid
3785 || st.st_gid != st_old.st_gid
Bram Moolenaar78a15312009-05-15 19:33:18 +00003786 || (long)st.st_mode != perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003787 backup_copy = TRUE;
3788# endif
Bram Moolenaar98358622005-11-28 22:58:23 +00003789 /* Close the file before removing it, on MS-Windows we
3790 * can't delete an open file. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003791 close(fd);
Bram Moolenaar98358622005-11-28 22:58:23 +00003792 mch_remove(IObuff);
Bram Moolenaar3479c5d2010-08-08 18:46:06 +02003793# ifdef MSWIN
3794 /* MS-Windows may trigger a virus scanner to open the
3795 * file, we can't delete it then. Keep trying for half a
3796 * second. */
3797 {
3798 int try;
3799
3800 for (try = 0; try < 10; ++try)
3801 {
3802 if (mch_lstat((char *)IObuff, &st) < 0)
3803 break;
3804 ui_delay(50L, TRUE); /* wait 50 msec */
3805 mch_remove(IObuff);
3806 }
3807 }
3808# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003809 }
3810 }
3811 }
3812
Bram Moolenaar071d4272004-06-13 20:20:40 +00003813 /*
3814 * Break symlinks and/or hardlinks if we've been asked to.
3815 */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003816 if ((bkc & BKC_BREAKSYMLINK) || (bkc & BKC_BREAKHARDLINK))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003817 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003818# ifdef UNIX
Bram Moolenaar071d4272004-06-13 20:20:40 +00003819 int lstat_res;
3820
3821 lstat_res = mch_lstat((char *)fname, &st);
3822
3823 /* Symlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003824 if ((bkc & BKC_BREAKSYMLINK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003825 && lstat_res == 0
3826 && st.st_ino != st_old.st_ino)
3827 backup_copy = FALSE;
3828
3829 /* Hardlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003830 if ((bkc & BKC_BREAKHARDLINK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003831 && st_old.st_nlink > 1
3832 && (lstat_res != 0 || st.st_ino == st_old.st_ino))
3833 backup_copy = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003834# else
3835# if defined(WIN32)
3836 /* Symlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003837 if ((bkc & BKC_BREAKSYMLINK) && mch_is_symbolic_link(fname))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003838 backup_copy = FALSE;
3839
3840 /* Hardlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003841 if ((bkc & BKC_BREAKHARDLINK) && mch_is_hard_link(fname))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003842 backup_copy = FALSE;
3843# endif
3844# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003845 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003846
3847#endif
3848
3849 /* make sure we have a valid backup extension to use */
3850 if (*p_bex == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003851 backup_ext = (char_u *)".bak";
Bram Moolenaar071d4272004-06-13 20:20:40 +00003852 else
3853 backup_ext = p_bex;
3854
3855 if (backup_copy
3856 && (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) >= 0)
3857 {
3858 int bfd;
3859 char_u *copybuf, *wp;
3860 int some_error = FALSE;
Bram Moolenaar8767f522016-07-01 17:17:39 +02003861 stat_T st_new;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003862 char_u *dirp;
3863 char_u *rootname;
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003864#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003865 int did_set_shortname;
Bram Moolenaarcd142e32017-11-16 17:03:45 +01003866 mode_t umask_save;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003867#endif
3868
3869 copybuf = alloc(BUFSIZE + 1);
3870 if (copybuf == NULL)
3871 {
3872 some_error = TRUE; /* out of memory */
3873 goto nobackup;
3874 }
3875
3876 /*
3877 * Try to make the backup in each directory in the 'bdir' option.
3878 *
3879 * Unix semantics has it, that we may have a writable file,
3880 * that cannot be recreated with a simple open(..., O_CREAT, ) e.g:
3881 * - the directory is not writable,
3882 * - the file may be a symbolic link,
3883 * - the file may belong to another user/group, etc.
3884 *
3885 * For these reasons, the existing writable file must be truncated
3886 * and reused. Creation of a backup COPY will be attempted.
3887 */
3888 dirp = p_bdir;
3889 while (*dirp)
3890 {
3891#ifdef UNIX
3892 st_new.st_ino = 0;
3893 st_new.st_dev = 0;
3894 st_new.st_gid = 0;
3895#endif
3896
3897 /*
3898 * Isolate one directory name, using an entry in 'bdir'.
3899 */
3900 (void)copy_option_part(&dirp, copybuf, BUFSIZE, ",");
3901 rootname = get_file_in_dir(fname, copybuf);
3902 if (rootname == NULL)
3903 {
3904 some_error = TRUE; /* out of memory */
3905 goto nobackup;
3906 }
3907
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003908#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003909 did_set_shortname = FALSE;
3910#endif
3911
3912 /*
3913 * May try twice if 'shortname' not set.
3914 */
3915 for (;;)
3916 {
3917 /*
3918 * Make backup file name.
3919 */
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003920 backup = buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003921 rootname, backup_ext, FALSE);
3922 if (backup == NULL)
3923 {
3924 vim_free(rootname);
3925 some_error = TRUE; /* out of memory */
3926 goto nobackup;
3927 }
3928
3929 /*
3930 * Check if backup file already exists.
3931 */
3932 if (mch_stat((char *)backup, &st_new) >= 0)
3933 {
3934#ifdef UNIX
3935 /*
3936 * Check if backup file is same as original file.
3937 * May happen when modname() gave the same file back.
3938 * E.g. silly link, or file name-length reached.
3939 * If we don't check here, we either ruin the file
3940 * when copying or erase it after writing. jw.
3941 */
3942 if (st_new.st_dev == st_old.st_dev
3943 && st_new.st_ino == st_old.st_ino)
3944 {
3945 vim_free(backup);
3946 backup = NULL; /* no backup file to delete */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003947 /*
3948 * may try again with 'shortname' set
3949 */
3950 if (!(buf->b_shortname || buf->b_p_sn))
3951 {
3952 buf->b_shortname = TRUE;
3953 did_set_shortname = TRUE;
3954 continue;
3955 }
3956 /* setting shortname didn't help */
3957 if (did_set_shortname)
3958 buf->b_shortname = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003959 break;
3960 }
3961#endif
3962
3963 /*
3964 * If we are not going to keep the backup file, don't
3965 * delete an existing one, try to use another name.
3966 * Change one character, just before the extension.
3967 */
3968 if (!p_bk)
3969 {
3970 wp = backup + STRLEN(backup) - 1
3971 - STRLEN(backup_ext);
3972 if (wp < backup) /* empty file name ??? */
3973 wp = backup;
3974 *wp = 'z';
3975 while (*wp > 'a'
3976 && mch_stat((char *)backup, &st_new) >= 0)
3977 --*wp;
3978 /* They all exist??? Must be something wrong. */
3979 if (*wp == 'a')
3980 {
3981 vim_free(backup);
3982 backup = NULL;
3983 }
3984 }
3985 }
3986 break;
3987 }
3988 vim_free(rootname);
3989
3990 /*
3991 * Try to create the backup file
3992 */
3993 if (backup != NULL)
3994 {
3995 /* remove old backup, if present */
3996 mch_remove(backup);
3997 /* Open with O_EXCL to avoid the file being created while
Bram Moolenaarcd142e32017-11-16 17:03:45 +01003998 * we were sleeping (symlink hacker attack?). Reset umask
3999 * if possible to avoid mch_setperm() below. */
4000#ifdef UNIX
4001 umask_save = umask(0);
4002#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004003 bfd = mch_open((char *)backup,
Bram Moolenaara5792f52005-11-23 21:25:05 +00004004 O_WRONLY|O_CREAT|O_EXTRA|O_EXCL|O_NOFOLLOW,
4005 perm & 0777);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004006#ifdef UNIX
4007 (void)umask(umask_save);
4008#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004009 if (bfd < 0)
4010 {
4011 vim_free(backup);
4012 backup = NULL;
4013 }
4014 else
4015 {
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004016 /* Set file protection same as original file, but
4017 * strip s-bit. Only needed if umask() wasn't used
4018 * above. */
4019#ifndef UNIX
Bram Moolenaar071d4272004-06-13 20:20:40 +00004020 (void)mch_setperm(backup, perm & 0777);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004021#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004022 /*
4023 * Try to set the group of the backup same as the
4024 * original file. If this fails, set the protection
4025 * bits for the group same as the protection bits for
4026 * others.
4027 */
Bram Moolenaara5792f52005-11-23 21:25:05 +00004028 if (st_new.st_gid != st_old.st_gid
Bram Moolenaar071d4272004-06-13 20:20:40 +00004029# ifdef HAVE_FCHOWN /* sequent-ptx lacks fchown() */
Bram Moolenaara5792f52005-11-23 21:25:05 +00004030 && fchown(bfd, (uid_t)-1, st_old.st_gid) != 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00004031# endif
4032 )
4033 mch_setperm(backup,
4034 (perm & 0707) | ((perm & 07) << 3));
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004035# if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004036 mch_copy_sec(fname, backup);
4037# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004038#endif
4039
4040 /*
4041 * copy the file.
4042 */
4043 write_info.bw_fd = bfd;
4044 write_info.bw_buf = copybuf;
4045#ifdef HAS_BW_FLAGS
4046 write_info.bw_flags = FIO_NOCONVERT;
4047#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004048 while ((write_info.bw_len = read_eintr(fd, copybuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004049 BUFSIZE)) > 0)
4050 {
4051 if (buf_write_bytes(&write_info) == FAIL)
4052 {
4053 errmsg = (char_u *)_("E506: Can't write to backup file (add ! to override)");
4054 break;
4055 }
4056 ui_breakcheck();
4057 if (got_int)
4058 {
4059 errmsg = (char_u *)_(e_interr);
4060 break;
4061 }
4062 }
4063
4064 if (close(bfd) < 0 && errmsg == NULL)
4065 errmsg = (char_u *)_("E507: Close error for backup file (add ! to override)");
4066 if (write_info.bw_len < 0)
4067 errmsg = (char_u *)_("E508: Can't read file for backup (add ! to override)");
4068#ifdef UNIX
4069 set_file_time(backup, st_old.st_atime, st_old.st_mtime);
4070#endif
4071#ifdef HAVE_ACL
4072 mch_set_acl(backup, acl);
4073#endif
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004074#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004075 mch_copy_sec(fname, backup);
4076#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004077 break;
4078 }
4079 }
4080 }
4081 nobackup:
4082 close(fd); /* ignore errors for closing read file */
4083 vim_free(copybuf);
4084
4085 if (backup == NULL && errmsg == NULL)
4086 errmsg = (char_u *)_("E509: Cannot create backup file (add ! to override)");
4087 /* ignore errors when forceit is TRUE */
4088 if ((some_error || errmsg != NULL) && !forceit)
4089 {
4090 retval = FAIL;
4091 goto fail;
4092 }
4093 errmsg = NULL;
4094 }
4095 else
4096 {
4097 char_u *dirp;
4098 char_u *p;
4099 char_u *rootname;
4100
4101 /*
4102 * Make a backup by renaming the original file.
4103 */
4104 /*
4105 * If 'cpoptions' includes the "W" flag, we don't want to
4106 * overwrite a read-only file. But rename may be possible
4107 * anyway, thus we need an extra check here.
4108 */
4109 if (file_readonly && vim_strchr(p_cpo, CPO_FWRITE) != NULL)
4110 {
4111 errnum = (char_u *)"E504: ";
4112 errmsg = (char_u *)_(err_readonly);
4113 goto fail;
4114 }
4115
4116 /*
4117 *
4118 * Form the backup file name - change path/fo.o.h to
4119 * path/fo.o.h.bak Try all directories in 'backupdir', first one
4120 * that works is used.
4121 */
4122 dirp = p_bdir;
4123 while (*dirp)
4124 {
4125 /*
4126 * Isolate one directory name and make the backup file name.
4127 */
4128 (void)copy_option_part(&dirp, IObuff, IOSIZE, ",");
4129 rootname = get_file_in_dir(fname, IObuff);
4130 if (rootname == NULL)
4131 backup = NULL;
4132 else
4133 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01004134 backup = buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00004135 rootname, backup_ext, FALSE);
4136 vim_free(rootname);
4137 }
4138
4139 if (backup != NULL)
4140 {
4141 /*
4142 * If we are not going to keep the backup file, don't
4143 * delete an existing one, try to use another name.
4144 * Change one character, just before the extension.
4145 */
4146 if (!p_bk && mch_getperm(backup) >= 0)
4147 {
4148 p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext);
4149 if (p < backup) /* empty file name ??? */
4150 p = backup;
4151 *p = 'z';
4152 while (*p > 'a' && mch_getperm(backup) >= 0)
4153 --*p;
4154 /* They all exist??? Must be something wrong! */
4155 if (*p == 'a')
4156 {
4157 vim_free(backup);
4158 backup = NULL;
4159 }
4160 }
4161 }
4162 if (backup != NULL)
4163 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004164 /*
Bram Moolenaarbfd8fc02005-09-20 23:22:24 +00004165 * Delete any existing backup and move the current version
4166 * to the backup. For safety, we don't remove the backup
4167 * until the write has finished successfully. And if the
4168 * 'backup' option is set, leave it around.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004169 */
4170 /*
4171 * If the renaming of the original file to the backup file
4172 * works, quit here.
4173 */
4174 if (vim_rename(fname, backup) == 0)
4175 break;
4176
4177 vim_free(backup); /* don't do the rename below */
4178 backup = NULL;
4179 }
4180 }
4181 if (backup == NULL && !forceit)
4182 {
4183 errmsg = (char_u *)_("E510: Can't make backup file (add ! to override)");
4184 goto fail;
4185 }
4186 }
4187 }
4188
Bram Moolenaar53076832015-12-31 19:53:21 +01004189#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004190 /* When using ":w!" and the file was read-only: make it writable */
4191 if (forceit && perm >= 0 && !(perm & 0200) && st_old.st_uid == getuid()
4192 && vim_strchr(p_cpo, CPO_FWRITE) == NULL)
4193 {
4194 perm |= 0200;
4195 (void)mch_setperm(fname, perm);
4196 made_writable = TRUE;
4197 }
4198#endif
4199
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004200 /* When using ":w!" and writing to the current file, 'readonly' makes no
Bram Moolenaar4399ef42005-02-12 14:29:27 +00004201 * sense, reset it, unless 'Z' appears in 'cpoptions'. */
4202 if (forceit && overwriting && vim_strchr(p_cpo, CPO_KEEPRO) == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004203 {
4204 buf->b_p_ro = FALSE;
4205#ifdef FEAT_TITLE
4206 need_maketitle = TRUE; /* set window title later */
4207#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004208 status_redraw_all(); /* redraw status lines later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004209 }
4210
4211 if (end > buf->b_ml.ml_line_count)
4212 end = buf->b_ml.ml_line_count;
4213 if (buf->b_ml.ml_flags & ML_EMPTY)
4214 start = end + 1;
4215
4216 /*
4217 * If the original file is being overwritten, there is a small chance that
4218 * we crash in the middle of writing. Therefore the file is preserved now.
4219 * This makes all block numbers positive so that recovery does not need
4220 * the original file.
4221 * Don't do this if there is a backup file and we are exiting.
4222 */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004223 if (reset_changed && !newfile && overwriting
Bram Moolenaar071d4272004-06-13 20:20:40 +00004224 && !(exiting && backup != NULL))
4225 {
4226 ml_preserve(buf, FALSE);
4227 if (got_int)
4228 {
4229 errmsg = (char_u *)_(e_interr);
4230 goto restore_backup;
4231 }
4232 }
4233
Bram Moolenaar071d4272004-06-13 20:20:40 +00004234#ifdef VMS
4235 vms_remove_version(fname); /* remove version */
4236#endif
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00004237 /* Default: write the file directly. May write to a temp file for
Bram Moolenaar071d4272004-06-13 20:20:40 +00004238 * multi-byte conversion. */
4239 wfname = fname;
4240
4241#ifdef FEAT_MBYTE
4242 /* Check for forced 'fileencoding' from "++opt=val" argument. */
4243 if (eap != NULL && eap->force_enc != 0)
4244 {
4245 fenc = eap->cmd + eap->force_enc;
4246 fenc = enc_canonize(fenc);
4247 fenc_tofree = fenc;
4248 }
4249 else
4250 fenc = buf->b_p_fenc;
4251
4252 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004253 * Check if the file needs to be converted.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004254 */
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004255 converted = need_conversion(fenc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004256
4257 /*
4258 * Check if UTF-8 to UCS-2/4 or Latin1 conversion needs to be done. Or
4259 * Latin1 to Unicode conversion. This is handled in buf_write_bytes().
4260 * Prepare the flags for it and allocate bw_conv_buf when needed.
4261 */
4262 if (converted && (enc_utf8 || STRCMP(p_enc, "latin1") == 0))
4263 {
4264 wb_flags = get_fio_flags(fenc);
4265 if (wb_flags & (FIO_UCS2 | FIO_UCS4 | FIO_UTF16 | FIO_UTF8))
4266 {
4267 /* Need to allocate a buffer to translate into. */
4268 if (wb_flags & (FIO_UCS2 | FIO_UTF16 | FIO_UTF8))
4269 write_info.bw_conv_buflen = bufsize * 2;
4270 else /* FIO_UCS4 */
4271 write_info.bw_conv_buflen = bufsize * 4;
4272 write_info.bw_conv_buf
4273 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4274 if (write_info.bw_conv_buf == NULL)
4275 end = 0;
4276 }
4277 }
4278
4279# ifdef WIN3264
4280 if (converted && wb_flags == 0 && (wb_flags = get_win_fio_flags(fenc)) != 0)
4281 {
4282 /* Convert UTF-8 -> UCS-2 and UCS-2 -> DBCS. Worst-case * 4: */
4283 write_info.bw_conv_buflen = bufsize * 4;
4284 write_info.bw_conv_buf
4285 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4286 if (write_info.bw_conv_buf == NULL)
4287 end = 0;
4288 }
4289# endif
4290
Bram Moolenaard0573012017-10-28 21:11:06 +02004291# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00004292 if (converted && wb_flags == 0 && (wb_flags = get_mac_fio_flags(fenc)) != 0)
4293 {
4294 write_info.bw_conv_buflen = bufsize * 3;
4295 write_info.bw_conv_buf
4296 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4297 if (write_info.bw_conv_buf == NULL)
4298 end = 0;
4299 }
4300# endif
4301
4302# if defined(FEAT_EVAL) || defined(USE_ICONV)
4303 if (converted && wb_flags == 0)
4304 {
4305# ifdef USE_ICONV
4306 /*
4307 * Use iconv() conversion when conversion is needed and it's not done
4308 * internally.
4309 */
4310 write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc,
4311 enc_utf8 ? (char_u *)"utf-8" : p_enc);
4312 if (write_info.bw_iconv_fd != (iconv_t)-1)
4313 {
4314 /* We're going to use iconv(), allocate a buffer to convert in. */
4315 write_info.bw_conv_buflen = bufsize * ICONV_MULT;
4316 write_info.bw_conv_buf
4317 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4318 if (write_info.bw_conv_buf == NULL)
4319 end = 0;
4320 write_info.bw_first = TRUE;
4321 }
4322# ifdef FEAT_EVAL
4323 else
4324# endif
4325# endif
4326
4327# ifdef FEAT_EVAL
4328 /*
4329 * When the file needs to be converted with 'charconvert' after
4330 * writing, write to a temp file instead and let the conversion
4331 * overwrite the original file.
4332 */
4333 if (*p_ccv != NUL)
4334 {
Bram Moolenaare5c421c2015-03-31 13:33:08 +02004335 wfname = vim_tempname('w', FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004336 if (wfname == NULL) /* Can't write without a tempfile! */
4337 {
4338 errmsg = (char_u *)_("E214: Can't find temp file for writing");
4339 goto restore_backup;
4340 }
4341 }
4342# endif
4343 }
4344# endif
4345 if (converted && wb_flags == 0
4346# ifdef USE_ICONV
4347 && write_info.bw_iconv_fd == (iconv_t)-1
4348# endif
4349# ifdef FEAT_EVAL
4350 && wfname == fname
4351# endif
4352 )
4353 {
4354 if (!forceit)
4355 {
4356 errmsg = (char_u *)_("E213: Cannot convert (add ! to write without conversion)");
4357 goto restore_backup;
4358 }
4359 notconverted = TRUE;
4360 }
4361#endif
4362
4363 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004364 * If conversion is taking place, we may first pretend to write and check
4365 * for conversion errors. Then loop again to write for real.
4366 * When not doing conversion this writes for real right away.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004367 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004368 for (checking_conversion = TRUE; ; checking_conversion = FALSE)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004369 {
4370 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004371 * There is no need to check conversion when:
4372 * - there is no conversion
4373 * - we make a backup file, that can be restored in case of conversion
4374 * failure.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004375 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004376#ifdef FEAT_MBYTE
4377 if (!converted || dobackup)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004378#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004379 checking_conversion = FALSE;
4380
4381 if (checking_conversion)
4382 {
4383 /* Make sure we don't write anything. */
4384 fd = -1;
4385 write_info.bw_fd = fd;
4386 }
4387 else
4388 {
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004389#ifdef HAVE_FTRUNCATE
4390# define TRUNC_ON_OPEN 0
4391#else
4392# define TRUNC_ON_OPEN O_TRUNC
4393#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004394 /*
4395 * Open the file "wfname" for writing.
4396 * We may try to open the file twice: If we can't write to the file
4397 * and forceit is TRUE we delete the existing file and try to
4398 * create a new one. If this still fails we may have lost the
4399 * original file! (this may happen when the user reached his
4400 * quotum for number of files).
4401 * Appending will fail if the file does not exist and forceit is
4402 * FALSE.
4403 */
4404 while ((fd = mch_open((char *)wfname, O_WRONLY | O_EXTRA | (append
4405 ? (forceit ? (O_APPEND | O_CREAT) : O_APPEND)
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004406 : (O_CREAT | TRUNC_ON_OPEN))
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004407 , perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004408 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004409 /*
4410 * A forced write will try to create a new file if the old one
4411 * is still readonly. This may also happen when the directory
4412 * is read-only. In that case the mch_remove() will fail.
4413 */
4414 if (errmsg == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004415 {
4416#ifdef UNIX
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004417 stat_T st;
4418
4419 /* Don't delete the file when it's a hard or symbolic link.
4420 */
4421 if ((!newfile && st_old.st_nlink > 1)
4422 || (mch_lstat((char *)fname, &st) == 0
4423 && (st.st_dev != st_old.st_dev
4424 || st.st_ino != st_old.st_ino)))
4425 errmsg = (char_u *)_("E166: Can't open linked file for writing");
4426 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004427#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004428 {
4429 errmsg = (char_u *)_("E212: Can't open file for writing");
4430 if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL
4431 && perm >= 0)
4432 {
4433#ifdef UNIX
4434 /* we write to the file, thus it should be marked
4435 writable after all */
4436 if (!(perm & 0200))
4437 made_writable = TRUE;
4438 perm |= 0200;
4439 if (st_old.st_uid != getuid()
4440 || st_old.st_gid != getgid())
4441 perm &= 0777;
4442#endif
4443 if (!append) /* don't remove when appending */
4444 mch_remove(wfname);
4445 continue;
4446 }
4447 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004448 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004449
4450restore_backup:
Bram Moolenaar071d4272004-06-13 20:20:40 +00004451 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004452 stat_T st;
4453
Bram Moolenaar071d4272004-06-13 20:20:40 +00004454 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004455 * If we failed to open the file, we don't need a backup.
4456 * Throw it away. If we moved or removed the original file
4457 * try to put the backup in its place.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004458 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004459 if (backup != NULL && wfname == fname)
4460 {
4461 if (backup_copy)
4462 {
4463 /*
4464 * There is a small chance that we removed the
4465 * original, try to move the copy in its place.
4466 * This may not work if the vim_rename() fails.
4467 * In that case we leave the copy around.
4468 */
4469 /* If file does not exist, put the copy in its
4470 * place */
4471 if (mch_stat((char *)fname, &st) < 0)
4472 vim_rename(backup, fname);
4473 /* if original file does exist throw away the copy
4474 */
4475 if (mch_stat((char *)fname, &st) >= 0)
4476 mch_remove(backup);
4477 }
4478 else
4479 {
4480 /* try to put the original file back */
4481 vim_rename(backup, fname);
4482 }
4483 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004484
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004485 /* if original file no longer exists give an extra warning
4486 */
4487 if (!newfile && mch_stat((char *)fname, &st) < 0)
4488 end = 0;
4489 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004490
4491#ifdef FEAT_MBYTE
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004492 if (wfname != fname)
4493 vim_free(wfname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004494#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004495 goto fail;
4496 }
4497 write_info.bw_fd = fd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004498
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004499#if defined(UNIX)
4500 {
4501 stat_T st;
4502
4503 /* Double check we are writing the intended file before making
4504 * any changes. */
4505 if (overwriting
4506 && (!dobackup || backup_copy)
4507 && fname == wfname
4508 && perm >= 0
4509 && mch_fstat(fd, &st) == 0
4510 && st.st_ino != st_old.st_ino)
4511 {
4512 close(fd);
4513 errmsg = (char_u *)_("E949: File changed while writing");
4514 goto fail;
4515 }
4516 }
4517#endif
4518#ifdef HAVE_FTRUNCATE
4519 if (!append)
4520 ftruncate(fd, (off_t)0);
4521#endif
4522
Bram Moolenaard0573012017-10-28 21:11:06 +02004523#if defined(WIN3264)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004524 if (backup != NULL && overwriting && !append)
4525 {
4526 if (backup_copy)
4527 (void)mch_copy_file_attribute(wfname, backup);
4528 else
4529 (void)mch_copy_file_attribute(backup, wfname);
4530 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004531
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004532 if (!overwriting && !append)
4533 {
4534 if (buf->b_ffname != NULL)
4535 (void)mch_copy_file_attribute(buf->b_ffname, wfname);
4536 /* Should copy resource fork */
4537 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004538#endif
4539
Bram Moolenaar071d4272004-06-13 20:20:40 +00004540#ifdef FEAT_CRYPT
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004541 if (*buf->b_p_key != NUL && !filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004542 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004543 char_u *header;
4544 int header_len;
4545
4546 buf->b_cryptstate = crypt_create_for_writing(
4547 crypt_get_method_nr(buf),
4548 buf->b_p_key, &header, &header_len);
4549 if (buf->b_cryptstate == NULL || header == NULL)
4550 end = 0;
4551 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004552 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004553 /* Write magic number, so that Vim knows how this file is
4554 * encrypted when reading it back. */
4555 write_info.bw_buf = header;
4556 write_info.bw_len = header_len;
4557 write_info.bw_flags = FIO_NOCONVERT;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004558 if (buf_write_bytes(&write_info) == FAIL)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004559 end = 0;
4560 wb_flags |= FIO_ENCRYPTED;
4561 vim_free(header);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004562 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004563 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004564#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004565 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004566 errmsg = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004567
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004568 write_info.bw_buf = buffer;
4569 nchars = 0;
4570
4571 /* use "++bin", "++nobin" or 'binary' */
4572 if (eap != NULL && eap->force_bin != 0)
4573 write_bin = (eap->force_bin == FORCE_BIN);
4574 else
4575 write_bin = buf->b_p_bin;
4576
4577#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004578 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004579 * The BOM is written just after the encryption magic number.
4580 * Skip it when appending and the file already existed, the BOM only
4581 * makes sense at the start of the file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004582 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004583 if (buf->b_p_bomb && !write_bin && (!append || perm < 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004584 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004585 write_info.bw_len = make_bom(buffer, fenc);
4586 if (write_info.bw_len > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004587 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004588 /* don't convert, do encryption */
4589 write_info.bw_flags = FIO_NOCONVERT | wb_flags;
4590 if (buf_write_bytes(&write_info) == FAIL)
4591 end = 0;
4592 else
4593 nchars += write_info.bw_len;
4594 }
4595 }
4596 write_info.bw_start_lnum = start;
4597#endif
4598
4599#ifdef FEAT_PERSISTENT_UNDO
4600 write_undo_file = (buf->b_p_udf
4601 && overwriting
4602 && !append
4603 && !filtering
4604 && reset_changed
4605 && !checking_conversion);
4606 if (write_undo_file)
4607 /* Prepare for computing the hash value of the text. */
4608 sha256_start(&sha_ctx);
4609#endif
4610
4611 write_info.bw_len = bufsize;
4612#ifdef HAS_BW_FLAGS
4613 write_info.bw_flags = wb_flags;
4614#endif
4615 fileformat = get_fileformat_force(buf, eap);
4616 s = buffer;
4617 len = 0;
4618 for (lnum = start; lnum <= end; ++lnum)
4619 {
4620 /*
4621 * The next while loop is done once for each character written.
4622 * Keep it fast!
4623 */
4624 ptr = ml_get_buf(buf, lnum, FALSE) - 1;
4625#ifdef FEAT_PERSISTENT_UNDO
4626 if (write_undo_file)
4627 sha256_update(&sha_ctx, ptr + 1,
4628 (UINT32_T)(STRLEN(ptr + 1) + 1));
4629#endif
4630 while ((c = *++ptr) != NUL)
4631 {
4632 if (c == NL)
4633 *s = NUL; /* replace newlines with NULs */
4634 else if (c == CAR && fileformat == EOL_MAC)
4635 *s = NL; /* Mac: replace CRs with NLs */
4636 else
4637 *s = c;
4638 ++s;
4639 if (++len != bufsize)
4640 continue;
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004641 if (buf_write_bytes(&write_info) == FAIL)
4642 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004643 end = 0; /* write error: break loop */
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004644 break;
4645 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004646 nchars += bufsize;
4647 s = buffer;
4648 len = 0;
4649#ifdef FEAT_MBYTE
4650 write_info.bw_start_lnum = lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004651#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004652 }
4653 /* write failed or last line has no EOL: stop here */
4654 if (end == 0
4655 || (lnum == end
4656 && (write_bin || !buf->b_p_fixeol)
4657 && (lnum == buf->b_no_eol_lnum
4658 || (lnum == buf->b_ml.ml_line_count
4659 && !buf->b_p_eol))))
4660 {
4661 ++lnum; /* written the line, count it */
4662 no_eol = TRUE;
4663 break;
4664 }
4665 if (fileformat == EOL_UNIX)
4666 *s++ = NL;
4667 else
4668 {
4669 *s++ = CAR; /* EOL_MAC or EOL_DOS: write CR */
4670 if (fileformat == EOL_DOS) /* write CR-NL */
4671 {
4672 if (++len == bufsize)
4673 {
4674 if (buf_write_bytes(&write_info) == FAIL)
4675 {
4676 end = 0; /* write error: break loop */
4677 break;
4678 }
4679 nchars += bufsize;
4680 s = buffer;
4681 len = 0;
4682 }
4683 *s++ = NL;
4684 }
4685 }
4686 if (++len == bufsize && end)
4687 {
4688 if (buf_write_bytes(&write_info) == FAIL)
4689 {
4690 end = 0; /* write error: break loop */
4691 break;
4692 }
4693 nchars += bufsize;
4694 s = buffer;
4695 len = 0;
4696
4697 ui_breakcheck();
4698 if (got_int)
4699 {
4700 end = 0; /* Interrupted, break loop */
4701 break;
4702 }
4703 }
4704#ifdef VMS
4705 /*
4706 * On VMS there is a problem: newlines get added when writing
4707 * blocks at a time. Fix it by writing a line at a time.
4708 * This is much slower!
4709 * Explanation: VAX/DECC RTL insists that records in some RMS
4710 * structures end with a newline (carriage return) character, and
4711 * if they don't it adds one.
4712 * With other RMS structures it works perfect without this fix.
4713 */
4714 if (buf->b_fab_rfm == FAB$C_VFC
4715 || ((buf->b_fab_rat & (FAB$M_FTN | FAB$M_CR)) != 0))
4716 {
4717 int b2write;
4718
4719 buf->b_fab_mrs = (buf->b_fab_mrs == 0
4720 ? MIN(4096, bufsize)
4721 : MIN(buf->b_fab_mrs, bufsize));
4722
4723 b2write = len;
4724 while (b2write > 0)
4725 {
4726 write_info.bw_len = MIN(b2write, buf->b_fab_mrs);
4727 if (buf_write_bytes(&write_info) == FAIL)
4728 {
4729 end = 0;
4730 break;
4731 }
4732 b2write -= MIN(b2write, buf->b_fab_mrs);
4733 }
4734 write_info.bw_len = bufsize;
4735 nchars += len;
4736 s = buffer;
4737 len = 0;
4738 }
4739#endif
4740 }
4741 if (len > 0 && end > 0)
4742 {
4743 write_info.bw_len = len;
4744 if (buf_write_bytes(&write_info) == FAIL)
4745 end = 0; /* write error */
4746 nchars += len;
4747 }
4748
4749 /* Stop when writing done or an error was encountered. */
4750 if (!checking_conversion || end == 0)
4751 break;
4752
4753 /* If no error happened until now, writing should be ok, so loop to
4754 * really write the buffer. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004755 }
4756
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004757 /* If we started writing, finish writing. Also when an error was
4758 * encountered. */
4759 if (!checking_conversion)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004760 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004761#if defined(UNIX) && defined(HAVE_FSYNC)
4762 /*
4763 * On many journalling file systems there is a bug that causes both the
4764 * original and the backup file to be lost when halting the system
4765 * right after writing the file. That's because only the meta-data is
4766 * journalled. Syncing the file slows down the system, but assures it
4767 * has been written to disk and we don't lose it.
4768 * For a device do try the fsync() but don't complain if it does not
4769 * work (could be a pipe).
4770 * If the 'fsync' option is FALSE, don't fsync(). Useful for laptops.
4771 */
4772 if (p_fs && fsync(fd) != 0 && !device)
4773 {
Bram Moolenaar7567d0b2017-11-16 23:04:15 +01004774 errmsg = (char_u *)_(e_fsync);
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004775 end = 0;
4776 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004777#endif
4778
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004779#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004780 /* Probably need to set the security context. */
4781 if (!backup_copy)
4782 mch_copy_sec(backup, wfname);
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004783#endif
4784
Bram Moolenaara5792f52005-11-23 21:25:05 +00004785#ifdef UNIX
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004786 /* When creating a new file, set its owner/group to that of the
4787 * original file. Get the new device and inode number. */
4788 if (backup != NULL && !backup_copy)
Bram Moolenaara5792f52005-11-23 21:25:05 +00004789 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004790# ifdef HAVE_FCHOWN
4791 stat_T st;
4792
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004793 /* Don't change the owner when it's already OK, some systems remove
4794 * permission or ACL stuff. */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004795 if (mch_stat((char *)wfname, &st) < 0
4796 || st.st_uid != st_old.st_uid
4797 || st.st_gid != st_old.st_gid)
4798 {
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004799 /* changing owner might not be possible */
4800 ignored = fchown(fd, st_old.st_uid, -1);
4801 /* if changing group fails clear the group permissions */
4802 if (fchown(fd, -1, st_old.st_gid) == -1 && perm > 0)
4803 perm &= ~070;
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004804 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00004805# endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004806 buf_setino(buf);
4807 }
4808 else if (!buf->b_dev_valid)
4809 /* Set the inode when creating a new file. */
4810 buf_setino(buf);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004811#endif
4812
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004813#ifdef UNIX
4814 if (made_writable)
4815 perm &= ~0200; /* reset 'w' bit for security reasons */
4816#endif
4817#ifdef HAVE_FCHMOD
4818 /* set permission of new file same as old file */
4819 if (perm >= 0)
4820 (void)mch_fsetperm(fd, perm);
4821#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004822 if (close(fd) != 0)
4823 {
4824 errmsg = (char_u *)_("E512: Close failed");
4825 end = 0;
4826 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004827
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004828#ifndef HAVE_FCHMOD
4829 /* set permission of new file same as old file */
4830 if (perm >= 0)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004831 (void)mch_setperm(wfname, perm);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004832#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004833#ifdef HAVE_ACL
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004834 /*
4835 * Probably need to set the ACL before changing the user (can't set the
4836 * ACL on a file the user doesn't own).
4837 * On Solaris, with ZFS and the aclmode property set to "discard" (the
4838 * default), chmod() discards all part of a file's ACL that don't
4839 * represent the mode of the file. It's non-trivial for us to discover
4840 * whether we're in that situation, so we simply always re-set the ACL.
4841 */
Bram Moolenaarda412772016-07-14 20:37:07 +02004842# ifndef HAVE_SOLARIS_ZFS_ACL
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004843 if (!backup_copy)
Bram Moolenaarda412772016-07-14 20:37:07 +02004844# endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004845 mch_set_acl(wfname, acl);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004846#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004847#ifdef FEAT_CRYPT
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004848 if (buf->b_cryptstate != NULL)
4849 {
4850 crypt_free_state(buf->b_cryptstate);
4851 buf->b_cryptstate = NULL;
4852 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004853#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004854
Bram Moolenaar071d4272004-06-13 20:20:40 +00004855#if defined(FEAT_MBYTE) && defined(FEAT_EVAL)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004856 if (wfname != fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004857 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004858 /*
4859 * The file was written to a temp file, now it needs to be
4860 * converted with 'charconvert' to (overwrite) the output file.
4861 */
4862 if (end != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004863 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004864 if (eval_charconvert(enc_utf8 ? (char_u *)"utf-8" : p_enc,
4865 fenc, wfname, fname) == FAIL)
4866 {
4867 write_info.bw_conv_error = TRUE;
4868 end = 0;
4869 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004870 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004871 mch_remove(wfname);
4872 vim_free(wfname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004873 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004874#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004875 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004876
4877 if (end == 0)
4878 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004879 /*
4880 * Error encountered.
4881 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004882 if (errmsg == NULL)
4883 {
4884#ifdef FEAT_MBYTE
4885 if (write_info.bw_conv_error)
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004886 {
4887 if (write_info.bw_conv_error_lnum == 0)
4888 errmsg = (char_u *)_("E513: write error, conversion failed (make 'fenc' empty to override)");
4889 else
4890 {
4891 errmsg_allocated = TRUE;
4892 errmsg = alloc(300);
4893 vim_snprintf((char *)errmsg, 300, _("E513: write error, conversion failed in line %ld (make 'fenc' empty to override)"),
4894 (long)write_info.bw_conv_error_lnum);
4895 }
4896 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004897 else
4898#endif
4899 if (got_int)
4900 errmsg = (char_u *)_(e_interr);
4901 else
4902 errmsg = (char_u *)_("E514: write error (file system full?)");
4903 }
4904
4905 /*
4906 * If we have a backup file, try to put it in place of the new file,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004907 * because the new file is probably corrupt. This avoids losing the
Bram Moolenaar071d4272004-06-13 20:20:40 +00004908 * original file when trying to make a backup when writing the file a
4909 * second time.
4910 * When "backup_copy" is set we need to copy the backup over the new
4911 * file. Otherwise rename the backup file.
4912 * If this is OK, don't give the extra warning message.
4913 */
4914 if (backup != NULL)
4915 {
4916 if (backup_copy)
4917 {
4918 /* This may take a while, if we were interrupted let the user
4919 * know we got the message. */
4920 if (got_int)
4921 {
4922 MSG(_(e_interr));
4923 out_flush();
4924 }
4925 if ((fd = mch_open((char *)backup, O_RDONLY | O_EXTRA, 0)) >= 0)
4926 {
4927 if ((write_info.bw_fd = mch_open((char *)fname,
Bram Moolenaar9be038d2005-03-08 22:34:32 +00004928 O_WRONLY | O_CREAT | O_TRUNC | O_EXTRA,
4929 perm & 0777)) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004930 {
4931 /* copy the file. */
4932 write_info.bw_buf = smallbuf;
4933#ifdef HAS_BW_FLAGS
4934 write_info.bw_flags = FIO_NOCONVERT;
4935#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004936 while ((write_info.bw_len = read_eintr(fd, smallbuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004937 SMBUFSIZE)) > 0)
4938 if (buf_write_bytes(&write_info) == FAIL)
4939 break;
4940
4941 if (close(write_info.bw_fd) >= 0
4942 && write_info.bw_len == 0)
4943 end = 1; /* success */
4944 }
4945 close(fd); /* ignore errors for closing read file */
4946 }
4947 }
4948 else
4949 {
4950 if (vim_rename(backup, fname) == 0)
4951 end = 1;
4952 }
4953 }
4954 goto fail;
4955 }
4956
4957 lnum -= start; /* compute number of written lines */
4958 --no_wait_return; /* may wait for return now */
4959
4960#if !(defined(UNIX) || defined(VMS))
4961 fname = sfname; /* use shortname now, for the messages */
4962#endif
4963 if (!filtering)
4964 {
4965 msg_add_fname(buf, fname); /* put fname in IObuff with quotes */
4966 c = FALSE;
4967#ifdef FEAT_MBYTE
4968 if (write_info.bw_conv_error)
4969 {
4970 STRCAT(IObuff, _(" CONVERSION ERROR"));
4971 c = TRUE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004972 if (write_info.bw_conv_error_lnum != 0)
Bram Moolenaara800b422010-06-27 01:15:55 +02004973 vim_snprintf_add((char *)IObuff, IOSIZE, _(" in line %ld;"),
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004974 (long)write_info.bw_conv_error_lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004975 }
4976 else if (notconverted)
4977 {
4978 STRCAT(IObuff, _("[NOT converted]"));
4979 c = TRUE;
4980 }
4981 else if (converted)
4982 {
4983 STRCAT(IObuff, _("[converted]"));
4984 c = TRUE;
4985 }
4986#endif
4987 if (device)
4988 {
4989 STRCAT(IObuff, _("[Device]"));
4990 c = TRUE;
4991 }
4992 else if (newfile)
4993 {
4994 STRCAT(IObuff, shortmess(SHM_NEW) ? _("[New]") : _("[New File]"));
4995 c = TRUE;
4996 }
4997 if (no_eol)
4998 {
4999 msg_add_eol();
5000 c = TRUE;
5001 }
5002 /* may add [unix/dos/mac] */
5003 if (msg_add_fileformat(fileformat))
5004 c = TRUE;
5005#ifdef FEAT_CRYPT
5006 if (wb_flags & FIO_ENCRYPTED)
5007 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02005008 crypt_append_msg(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005009 c = TRUE;
5010 }
5011#endif
5012 msg_add_lines(c, (long)lnum, nchars); /* add line/char count */
5013 if (!shortmess(SHM_WRITE))
5014 {
5015 if (append)
5016 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended"));
5017 else
5018 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written"));
5019 }
5020
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00005021 set_keep_msg(msg_trunc_attr(IObuff, FALSE, 0), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005022 }
5023
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005024 /* When written everything correctly: reset 'modified'. Unless not
5025 * writing to the original file and '+' is not in 'cpoptions'. */
Bram Moolenaar292ad192005-12-11 21:29:51 +00005026 if (reset_changed && whole && !append
Bram Moolenaar071d4272004-06-13 20:20:40 +00005027#ifdef FEAT_MBYTE
5028 && !write_info.bw_conv_error
5029#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005030 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL)
5031 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00005032 {
5033 unchanged(buf, TRUE);
Bram Moolenaar086329d2014-10-31 19:51:36 +01005034#ifdef FEAT_AUTOCMD
Bram Moolenaar95c526e2017-02-25 14:59:34 +01005035 /* b:changedtick is always incremented in unchanged() but that
Bram Moolenaar086329d2014-10-31 19:51:36 +01005036 * should not trigger a TextChanged event. */
Bram Moolenaar95c526e2017-02-25 14:59:34 +01005037 if (last_changedtick + 1 == CHANGEDTICK(buf)
Bram Moolenaar086329d2014-10-31 19:51:36 +01005038 && last_changedtick_buf == buf)
Bram Moolenaar95c526e2017-02-25 14:59:34 +01005039 last_changedtick = CHANGEDTICK(buf);
Bram Moolenaar086329d2014-10-31 19:51:36 +01005040#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005041 u_unchanged(buf);
Bram Moolenaar730cde92010-06-27 05:18:54 +02005042 u_update_save_nr(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005043 }
5044
5045 /*
5046 * If written to the current file, update the timestamp of the swap file
5047 * and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
5048 */
5049 if (overwriting)
5050 {
5051 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00005052 if (append)
5053 buf->b_flags &= ~BF_NEW;
5054 else
5055 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005056 }
5057
5058 /*
5059 * If we kept a backup until now, and we are in patch mode, then we make
5060 * the backup file our 'original' file.
5061 */
5062 if (*p_pm && dobackup)
5063 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01005064 char *org = (char *)buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005065 fname, p_pm, FALSE);
5066
5067 if (backup != NULL)
5068 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02005069 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005070
5071 /*
5072 * If the original file does not exist yet
5073 * the current backup file becomes the original file
5074 */
5075 if (org == NULL)
5076 EMSG(_("E205: Patchmode: can't save original file"));
5077 else if (mch_stat(org, &st) < 0)
5078 {
5079 vim_rename(backup, (char_u *)org);
5080 vim_free(backup); /* don't delete the file */
5081 backup = NULL;
5082#ifdef UNIX
5083 set_file_time((char_u *)org, st_old.st_atime, st_old.st_mtime);
5084#endif
5085 }
5086 }
5087 /*
5088 * If there is no backup file, remember that a (new) file was
5089 * created.
5090 */
5091 else
5092 {
5093 int empty_fd;
5094
5095 if (org == NULL
Bram Moolenaara5792f52005-11-23 21:25:05 +00005096 || (empty_fd = mch_open(org,
5097 O_CREAT | O_EXTRA | O_EXCL | O_NOFOLLOW,
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00005098 perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005099 EMSG(_("E206: patchmode: can't touch empty original file"));
5100 else
5101 close(empty_fd);
5102 }
5103 if (org != NULL)
5104 {
5105 mch_setperm((char_u *)org, mch_getperm(fname) & 0777);
5106 vim_free(org);
5107 }
5108 }
5109
5110 /*
5111 * Remove the backup unless 'backup' option is set
5112 */
5113 if (!p_bk && backup != NULL && mch_remove(backup) != 0)
5114 EMSG(_("E207: Can't delete backup file"));
5115
5116#ifdef FEAT_SUN_WORKSHOP
5117 if (usingSunWorkShop)
5118 workshop_file_saved((char *) ffname);
5119#endif
5120
5121 goto nofail;
5122
5123 /*
5124 * Finish up. We get here either after failure or success.
5125 */
5126fail:
5127 --no_wait_return; /* may wait for return now */
5128nofail:
5129
5130 /* Done saving, we accept changed buffer warnings again */
5131 buf->b_saving = FALSE;
5132
5133 vim_free(backup);
5134 if (buffer != smallbuf)
5135 vim_free(buffer);
5136#ifdef FEAT_MBYTE
5137 vim_free(fenc_tofree);
5138 vim_free(write_info.bw_conv_buf);
5139# ifdef USE_ICONV
5140 if (write_info.bw_iconv_fd != (iconv_t)-1)
5141 {
5142 iconv_close(write_info.bw_iconv_fd);
5143 write_info.bw_iconv_fd = (iconv_t)-1;
5144 }
5145# endif
5146#endif
5147#ifdef HAVE_ACL
5148 mch_free_acl(acl);
5149#endif
5150
5151 if (errmsg != NULL)
5152 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005153 int numlen = errnum != NULL ? (int)STRLEN(errnum) : 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005154
Bram Moolenaar8820b482017-03-16 17:23:31 +01005155 attr = HL_ATTR(HLF_E); /* set highlight for error messages */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005156 msg_add_fname(buf,
5157#ifndef UNIX
5158 sfname
5159#else
5160 fname
5161#endif
5162 ); /* put file name in IObuff with quotes */
5163 if (STRLEN(IObuff) + STRLEN(errmsg) + numlen >= IOSIZE)
5164 IObuff[IOSIZE - STRLEN(errmsg) - numlen - 1] = NUL;
5165 /* If the error message has the form "is ...", put the error number in
5166 * front of the file name. */
5167 if (errnum != NULL)
5168 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00005169 STRMOVE(IObuff + numlen, IObuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005170 mch_memmove(IObuff, errnum, (size_t)numlen);
5171 }
5172 STRCAT(IObuff, errmsg);
5173 emsg(IObuff);
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005174 if (errmsg_allocated)
5175 vim_free(errmsg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005176
5177 retval = FAIL;
5178 if (end == 0)
5179 {
5180 MSG_PUTS_ATTR(_("\nWARNING: Original file may be lost or damaged\n"),
5181 attr | MSG_HIST);
5182 MSG_PUTS_ATTR(_("don't quit the editor until the file is successfully written!"),
5183 attr | MSG_HIST);
5184
5185 /* Update the timestamp to avoid an "overwrite changed file"
5186 * prompt when writing again. */
5187 if (mch_stat((char *)fname, &st_old) >= 0)
5188 {
5189 buf_store_time(buf, &st_old, fname);
5190 buf->b_mtime_read = buf->b_mtime;
5191 }
5192 }
5193 }
5194 msg_scroll = msg_save;
5195
Bram Moolenaar55debbe2010-05-23 23:34:36 +02005196#ifdef FEAT_PERSISTENT_UNDO
5197 /*
5198 * When writing the whole file and 'undofile' is set, also write the undo
5199 * file.
5200 */
5201 if (retval == OK && write_undo_file)
5202 {
5203 char_u hash[UNDO_HASH_SIZE];
5204
5205 sha256_finish(&sha_ctx, hash);
5206 u_write_undo(NULL, FALSE, buf, hash);
5207 }
5208#endif
5209
Bram Moolenaar071d4272004-06-13 20:20:40 +00005210#ifdef FEAT_AUTOCMD
5211#ifdef FEAT_EVAL
5212 if (!should_abort(retval))
5213#else
5214 if (!got_int)
5215#endif
5216 {
5217 aco_save_T aco;
5218
Bram Moolenaar68a33fc2012-04-25 16:50:48 +02005219 curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */
5220
Bram Moolenaar071d4272004-06-13 20:20:40 +00005221 /*
5222 * Apply POST autocommands.
5223 * Careful: The autocommands may call buf_write() recursively!
5224 */
5225 aucmd_prepbuf(&aco, buf);
5226
5227 if (append)
5228 apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname,
5229 FALSE, curbuf, eap);
5230 else if (filtering)
5231 apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname,
5232 FALSE, curbuf, eap);
5233 else if (reset_changed && whole)
5234 apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname,
5235 FALSE, curbuf, eap);
5236 else
5237 apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname,
5238 FALSE, curbuf, eap);
5239
5240 /* restore curwin/curbuf and a few other things */
5241 aucmd_restbuf(&aco);
5242
5243#ifdef FEAT_EVAL
5244 if (aborting()) /* autocmds may abort script processing */
5245 retval = FALSE;
5246#endif
5247 }
5248#endif
5249
5250 got_int |= prev_got_int;
5251
Bram Moolenaar071d4272004-06-13 20:20:40 +00005252 return retval;
5253}
5254
5255/*
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005256 * Set the name of the current buffer. Use when the buffer doesn't have a
5257 * name and a ":r" or ":w" command with a file name is used.
5258 */
5259 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005260set_rw_fname(char_u *fname, char_u *sfname)
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005261{
5262#ifdef FEAT_AUTOCMD
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005263 buf_T *buf = curbuf;
5264
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005265 /* It's like the unnamed buffer is deleted.... */
5266 if (curbuf->b_p_bl)
5267 apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
5268 apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf);
5269# ifdef FEAT_EVAL
5270 if (aborting()) /* autocmds may abort script processing */
5271 return FAIL;
5272# endif
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005273 if (curbuf != buf)
5274 {
5275 /* We are in another buffer now, don't do the renaming. */
5276 EMSG(_(e_auchangedbuf));
5277 return FAIL;
5278 }
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005279#endif
5280
5281 if (setfname(curbuf, fname, sfname, FALSE) == OK)
5282 curbuf->b_flags |= BF_NOTEDITED;
5283
5284#ifdef FEAT_AUTOCMD
5285 /* ....and a new named one is created */
5286 apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, curbuf);
5287 if (curbuf->b_p_bl)
5288 apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf);
5289# ifdef FEAT_EVAL
5290 if (aborting()) /* autocmds may abort script processing */
5291 return FAIL;
5292# endif
5293
5294 /* Do filetype detection now if 'filetype' is empty. */
5295 if (*curbuf->b_p_ft == NUL)
5296 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005297 if (au_has_group((char_u *)"filetypedetect"))
Bram Moolenaar1610d052016-06-09 22:53:01 +02005298 (void)do_doautocmd((char_u *)"filetypedetect BufRead", FALSE, NULL);
Bram Moolenaara3227e22006-03-08 21:32:40 +00005299 do_modelines(0);
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005300 }
5301#endif
5302
5303 return OK;
5304}
5305
5306/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00005307 * Put file name into IObuff with quotes.
5308 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005309 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005310msg_add_fname(buf_T *buf, char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005311{
5312 if (fname == NULL)
5313 fname = (char_u *)"-stdin-";
5314 home_replace(buf, fname, IObuff + 1, IOSIZE - 4, TRUE);
5315 IObuff[0] = '"';
5316 STRCAT(IObuff, "\" ");
5317}
5318
5319/*
5320 * Append message for text mode to IObuff.
5321 * Return TRUE if something appended.
5322 */
5323 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005324msg_add_fileformat(int eol_type)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005325{
5326#ifndef USE_CRNL
5327 if (eol_type == EOL_DOS)
5328 {
5329 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[dos]") : _("[dos format]"));
5330 return TRUE;
5331 }
5332#endif
5333#ifndef USE_CR
5334 if (eol_type == EOL_MAC)
5335 {
5336 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[mac]") : _("[mac format]"));
5337 return TRUE;
5338 }
5339#endif
5340#if defined(USE_CRNL) || defined(USE_CR)
5341 if (eol_type == EOL_UNIX)
5342 {
5343 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[unix]") : _("[unix format]"));
5344 return TRUE;
5345 }
5346#endif
5347 return FALSE;
5348}
5349
5350/*
5351 * Append line and character count to IObuff.
5352 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005353 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005354msg_add_lines(
5355 int insert_space,
5356 long lnum,
Bram Moolenaar8767f522016-07-01 17:17:39 +02005357 off_T nchars)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005358{
5359 char_u *p;
5360
5361 p = IObuff + STRLEN(IObuff);
5362
5363 if (insert_space)
5364 *p++ = ' ';
5365 if (shortmess(SHM_LINES))
Bram Moolenaarbde98102016-07-01 20:03:42 +02005366 vim_snprintf((char *)p, IOSIZE - (p - IObuff),
5367 "%ldL, %lldC", lnum, (varnumber_T)nchars);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005368 else
5369 {
5370 if (lnum == 1)
5371 STRCPY(p, _("1 line, "));
5372 else
5373 sprintf((char *)p, _("%ld lines, "), lnum);
5374 p += STRLEN(p);
5375 if (nchars == 1)
5376 STRCPY(p, _("1 character"));
5377 else
Bram Moolenaarbde98102016-07-01 20:03:42 +02005378 vim_snprintf((char *)p, IOSIZE - (p - IObuff),
5379 _("%lld characters"), (varnumber_T)nchars);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005380 }
5381}
5382
5383/*
5384 * Append message for missing line separator to IObuff.
5385 */
5386 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005387msg_add_eol(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005388{
5389 STRCAT(IObuff, shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]"));
5390}
5391
5392/*
5393 * Check modification time of file, before writing to it.
5394 * The size isn't checked, because using a tool like "gzip" takes care of
5395 * using the same timestamp but can't set the size.
5396 */
5397 static int
Bram Moolenaar8767f522016-07-01 17:17:39 +02005398check_mtime(buf_T *buf, stat_T *st)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005399{
5400 if (buf->b_mtime_read != 0
5401 && time_differs((long)st->st_mtime, buf->b_mtime_read))
5402 {
5403 msg_scroll = TRUE; /* don't overwrite messages here */
5404 msg_silent = 0; /* must give this prompt */
5405 /* don't use emsg() here, don't want to flush the buffers */
5406 MSG_ATTR(_("WARNING: The file has been changed since reading it!!!"),
Bram Moolenaar8820b482017-03-16 17:23:31 +01005407 HL_ATTR(HLF_E));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005408 if (ask_yesno((char_u *)_("Do you really want to write to it"),
5409 TRUE) == 'n')
5410 return FAIL;
5411 msg_scroll = FALSE; /* always overwrite the file message now */
5412 }
5413 return OK;
5414}
5415
5416 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005417time_differs(long t1, long t2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005418{
Bram Moolenaar48e330a2016-02-23 14:53:34 +01005419#if defined(__linux__) || defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005420 /* On a FAT filesystem, esp. under Linux, there are only 5 bits to store
5421 * the seconds. Since the roundoff is done when flushing the inode, the
5422 * time may change unexpectedly by one second!!! */
5423 return (t1 - t2 > 1 || t2 - t1 > 1);
5424#else
5425 return (t1 != t2);
5426#endif
5427}
5428
5429/*
5430 * Call write() to write a number of bytes to the file.
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005431 * Handles encryption and 'encoding' conversion.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005432 *
5433 * Return FAIL for failure, OK otherwise.
5434 */
5435 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005436buf_write_bytes(struct bw_info *ip)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005437{
5438 int wlen;
5439 char_u *buf = ip->bw_buf; /* data to write */
5440 int len = ip->bw_len; /* length of data */
5441#ifdef HAS_BW_FLAGS
5442 int flags = ip->bw_flags; /* extra flags */
5443#endif
5444
5445#ifdef FEAT_MBYTE
5446 /*
5447 * Skip conversion when writing the crypt magic number or the BOM.
5448 */
5449 if (!(flags & FIO_NOCONVERT))
5450 {
5451 char_u *p;
5452 unsigned c;
5453 int n;
5454
5455 if (flags & FIO_UTF8)
5456 {
5457 /*
5458 * Convert latin1 in the buffer to UTF-8 in the file.
5459 */
5460 p = ip->bw_conv_buf; /* translate to buffer */
5461 for (wlen = 0; wlen < len; ++wlen)
5462 p += utf_char2bytes(buf[wlen], p);
5463 buf = ip->bw_conv_buf;
5464 len = (int)(p - ip->bw_conv_buf);
5465 }
5466 else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1))
5467 {
5468 /*
5469 * Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
5470 * Latin1 chars in the file.
5471 */
5472 if (flags & FIO_LATIN1)
5473 p = buf; /* translate in-place (can only get shorter) */
5474 else
5475 p = ip->bw_conv_buf; /* translate to buffer */
5476 for (wlen = 0; wlen < len; wlen += n)
5477 {
5478 if (wlen == 0 && ip->bw_restlen != 0)
5479 {
5480 int l;
5481
5482 /* Use remainder of previous call. Append the start of
5483 * buf[] to get a full sequence. Might still be too
5484 * short! */
5485 l = CONV_RESTLEN - ip->bw_restlen;
5486 if (l > len)
5487 l = len;
5488 mch_memmove(ip->bw_rest + ip->bw_restlen, buf, (size_t)l);
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005489 n = utf_ptr2len_len(ip->bw_rest, ip->bw_restlen + l);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005490 if (n > ip->bw_restlen + len)
5491 {
5492 /* We have an incomplete byte sequence at the end to
5493 * be written. We can't convert it without the
5494 * remaining bytes. Keep them for the next call. */
5495 if (ip->bw_restlen + len > CONV_RESTLEN)
5496 return FAIL;
5497 ip->bw_restlen += len;
5498 break;
5499 }
5500 if (n > 1)
5501 c = utf_ptr2char(ip->bw_rest);
5502 else
5503 c = ip->bw_rest[0];
5504 if (n >= ip->bw_restlen)
5505 {
5506 n -= ip->bw_restlen;
5507 ip->bw_restlen = 0;
5508 }
5509 else
5510 {
5511 ip->bw_restlen -= n;
5512 mch_memmove(ip->bw_rest, ip->bw_rest + n,
5513 (size_t)ip->bw_restlen);
5514 n = 0;
5515 }
5516 }
5517 else
5518 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005519 n = utf_ptr2len_len(buf + wlen, len - wlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005520 if (n > len - wlen)
5521 {
5522 /* We have an incomplete byte sequence at the end to
5523 * be written. We can't convert it without the
5524 * remaining bytes. Keep them for the next call. */
5525 if (len - wlen > CONV_RESTLEN)
5526 return FAIL;
5527 ip->bw_restlen = len - wlen;
5528 mch_memmove(ip->bw_rest, buf + wlen,
5529 (size_t)ip->bw_restlen);
5530 break;
5531 }
5532 if (n > 1)
5533 c = utf_ptr2char(buf + wlen);
5534 else
5535 c = buf[wlen];
5536 }
5537
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005538 if (ucs2bytes(c, &p, flags) && !ip->bw_conv_error)
5539 {
5540 ip->bw_conv_error = TRUE;
5541 ip->bw_conv_error_lnum = ip->bw_start_lnum;
5542 }
5543 if (c == NL)
5544 ++ip->bw_start_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005545 }
5546 if (flags & FIO_LATIN1)
5547 len = (int)(p - buf);
5548 else
5549 {
5550 buf = ip->bw_conv_buf;
5551 len = (int)(p - ip->bw_conv_buf);
5552 }
5553 }
5554
5555# ifdef WIN3264
5556 else if (flags & FIO_CODEPAGE)
5557 {
5558 /*
5559 * Convert UTF-8 or codepage to UCS-2 and then to MS-Windows
5560 * codepage.
5561 */
5562 char_u *from;
5563 size_t fromlen;
5564 char_u *to;
5565 int u8c;
5566 BOOL bad = FALSE;
5567 int needed;
5568
5569 if (ip->bw_restlen > 0)
5570 {
5571 /* Need to concatenate the remainder of the previous call and
5572 * the bytes of the current call. Use the end of the
5573 * conversion buffer for this. */
5574 fromlen = len + ip->bw_restlen;
5575 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5576 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5577 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5578 }
5579 else
5580 {
5581 from = buf;
5582 fromlen = len;
5583 }
5584
5585 to = ip->bw_conv_buf;
5586 if (enc_utf8)
5587 {
5588 /* Convert from UTF-8 to UCS-2, to the start of the buffer.
5589 * The buffer has been allocated to be big enough. */
5590 while (fromlen > 0)
5591 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005592 n = (int)utf_ptr2len_len(from, (int)fromlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005593 if (n > (int)fromlen) /* incomplete byte sequence */
5594 break;
5595 u8c = utf_ptr2char(from);
5596 *to++ = (u8c & 0xff);
5597 *to++ = (u8c >> 8);
5598 fromlen -= n;
5599 from += n;
5600 }
5601
5602 /* Copy remainder to ip->bw_rest[] to be used for the next
5603 * call. */
5604 if (fromlen > CONV_RESTLEN)
5605 {
5606 /* weird overlong sequence */
5607 ip->bw_conv_error = TRUE;
5608 return FAIL;
5609 }
5610 mch_memmove(ip->bw_rest, from, fromlen);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005611 ip->bw_restlen = (int)fromlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005612 }
5613 else
5614 {
5615 /* Convert from enc_codepage to UCS-2, to the start of the
5616 * buffer. The buffer has been allocated to be big enough. */
5617 ip->bw_restlen = 0;
5618 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005619 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005620 NULL, 0);
5621 if (needed == 0)
5622 {
5623 /* When conversion fails there may be a trailing byte. */
5624 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005625 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen - 1,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005626 NULL, 0);
5627 if (needed == 0)
5628 {
5629 /* Conversion doesn't work. */
5630 ip->bw_conv_error = TRUE;
5631 return FAIL;
5632 }
5633 /* Save the trailing byte for the next call. */
5634 ip->bw_rest[0] = from[fromlen - 1];
5635 ip->bw_restlen = 1;
5636 }
5637 needed = MultiByteToWideChar(enc_codepage, MB_ERR_INVALID_CHARS,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005638 (LPCSTR)from, (int)(fromlen - ip->bw_restlen),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005639 (LPWSTR)to, needed);
5640 if (needed == 0)
5641 {
5642 /* Safety check: Conversion doesn't work. */
5643 ip->bw_conv_error = TRUE;
5644 return FAIL;
5645 }
5646 to += needed * 2;
5647 }
5648
5649 fromlen = to - ip->bw_conv_buf;
5650 buf = to;
5651# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5652 if (FIO_GET_CP(flags) == CP_UTF8)
5653 {
5654 /* Convert from UCS-2 to UTF-8, using the remainder of the
5655 * conversion buffer. Fails when out of space. */
5656 for (from = ip->bw_conv_buf; fromlen > 1; fromlen -= 2)
5657 {
5658 u8c = *from++;
5659 u8c += (*from++ << 8);
5660 to += utf_char2bytes(u8c, to);
5661 if (to + 6 >= ip->bw_conv_buf + ip->bw_conv_buflen)
5662 {
5663 ip->bw_conv_error = TRUE;
5664 return FAIL;
5665 }
5666 }
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005667 len = (int)(to - buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005668 }
5669 else
5670#endif
5671 {
5672 /* Convert from UCS-2 to the codepage, using the remainder of
5673 * the conversion buffer. If the conversion uses the default
5674 * character "0", the data doesn't fit in this encoding, so
5675 * fail. */
5676 len = WideCharToMultiByte(FIO_GET_CP(flags), 0,
5677 (LPCWSTR)ip->bw_conv_buf, (int)fromlen / sizeof(WCHAR),
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005678 (LPSTR)to, (int)(ip->bw_conv_buflen - fromlen), 0,
5679 &bad);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005680 if (bad)
5681 {
5682 ip->bw_conv_error = TRUE;
5683 return FAIL;
5684 }
5685 }
5686 }
5687# endif
5688
Bram Moolenaar56718732006-03-15 22:53:57 +00005689# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00005690 else if (flags & FIO_MACROMAN)
5691 {
5692 /*
5693 * Convert UTF-8 or latin1 to Apple MacRoman.
5694 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005695 char_u *from;
5696 size_t fromlen;
5697
5698 if (ip->bw_restlen > 0)
5699 {
5700 /* Need to concatenate the remainder of the previous call and
5701 * the bytes of the current call. Use the end of the
5702 * conversion buffer for this. */
5703 fromlen = len + ip->bw_restlen;
5704 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5705 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5706 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5707 }
5708 else
5709 {
5710 from = buf;
5711 fromlen = len;
5712 }
5713
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00005714 if (enc2macroman(from, fromlen,
5715 ip->bw_conv_buf, &len, ip->bw_conv_buflen,
5716 ip->bw_rest, &ip->bw_restlen) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005717 {
5718 ip->bw_conv_error = TRUE;
5719 return FAIL;
5720 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005721 buf = ip->bw_conv_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005722 }
5723# endif
5724
5725# ifdef USE_ICONV
5726 if (ip->bw_iconv_fd != (iconv_t)-1)
5727 {
5728 const char *from;
5729 size_t fromlen;
5730 char *to;
5731 size_t tolen;
5732
5733 /* Convert with iconv(). */
5734 if (ip->bw_restlen > 0)
5735 {
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005736 char *fp;
5737
Bram Moolenaar071d4272004-06-13 20:20:40 +00005738 /* Need to concatenate the remainder of the previous call and
5739 * the bytes of the current call. Use the end of the
5740 * conversion buffer for this. */
5741 fromlen = len + ip->bw_restlen;
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005742 fp = (char *)ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5743 mch_memmove(fp, ip->bw_rest, (size_t)ip->bw_restlen);
5744 mch_memmove(fp + ip->bw_restlen, buf, (size_t)len);
5745 from = fp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005746 tolen = ip->bw_conv_buflen - fromlen;
5747 }
5748 else
5749 {
5750 from = (const char *)buf;
5751 fromlen = len;
5752 tolen = ip->bw_conv_buflen;
5753 }
5754 to = (char *)ip->bw_conv_buf;
5755
5756 if (ip->bw_first)
5757 {
5758 size_t save_len = tolen;
5759
5760 /* output the initial shift state sequence */
5761 (void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen);
5762
5763 /* There is a bug in iconv() on Linux (which appears to be
5764 * wide-spread) which sets "to" to NULL and messes up "tolen".
5765 */
5766 if (to == NULL)
5767 {
5768 to = (char *)ip->bw_conv_buf;
5769 tolen = save_len;
5770 }
5771 ip->bw_first = FALSE;
5772 }
5773
5774 /*
5775 * If iconv() has an error or there is not enough room, fail.
5776 */
5777 if ((iconv(ip->bw_iconv_fd, (void *)&from, &fromlen, &to, &tolen)
5778 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
5779 || fromlen > CONV_RESTLEN)
5780 {
5781 ip->bw_conv_error = TRUE;
5782 return FAIL;
5783 }
5784
5785 /* copy remainder to ip->bw_rest[] to be used for the next call. */
5786 if (fromlen > 0)
5787 mch_memmove(ip->bw_rest, (void *)from, fromlen);
5788 ip->bw_restlen = (int)fromlen;
5789
5790 buf = ip->bw_conv_buf;
5791 len = (int)((char_u *)to - ip->bw_conv_buf);
5792 }
5793# endif
5794 }
5795#endif /* FEAT_MBYTE */
5796
Bram Moolenaare6bf6552017-06-27 22:11:51 +02005797 if (ip->bw_fd < 0)
5798 /* Only checking conversion, which is OK if we get here. */
5799 return OK;
5800
Bram Moolenaar071d4272004-06-13 20:20:40 +00005801#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02005802 if (flags & FIO_ENCRYPTED)
5803 {
5804 /* Encrypt the data. Do it in-place if possible, otherwise use an
5805 * allocated buffer. */
5806 if (crypt_works_inplace(ip->bw_buffer->b_cryptstate))
5807 {
5808 crypt_encode_inplace(ip->bw_buffer->b_cryptstate, buf, len);
5809 }
5810 else
5811 {
5812 char_u *outbuf;
5813
5814 len = crypt_encode_alloc(curbuf->b_cryptstate, buf, len, &outbuf);
5815 if (len == 0)
5816 return OK; /* Crypt layer is buffering, will flush later. */
5817 wlen = write_eintr(ip->bw_fd, outbuf, len);
5818 vim_free(outbuf);
5819 return (wlen < len) ? FAIL : OK;
5820 }
5821 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005822#endif
5823
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005824 wlen = write_eintr(ip->bw_fd, buf, len);
5825 return (wlen < len) ? FAIL : OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005826}
5827
5828#ifdef FEAT_MBYTE
5829/*
5830 * Convert a Unicode character to bytes.
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005831 * Return TRUE for an error, FALSE when it's OK.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005832 */
5833 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005834ucs2bytes(
5835 unsigned c, /* in: character */
5836 char_u **pp, /* in/out: pointer to result */
5837 int flags) /* FIO_ flags */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005838{
5839 char_u *p = *pp;
5840 int error = FALSE;
5841 int cc;
5842
5843
5844 if (flags & FIO_UCS4)
5845 {
5846 if (flags & FIO_ENDIAN_L)
5847 {
5848 *p++ = c;
5849 *p++ = (c >> 8);
5850 *p++ = (c >> 16);
5851 *p++ = (c >> 24);
5852 }
5853 else
5854 {
5855 *p++ = (c >> 24);
5856 *p++ = (c >> 16);
5857 *p++ = (c >> 8);
5858 *p++ = c;
5859 }
5860 }
5861 else if (flags & (FIO_UCS2 | FIO_UTF16))
5862 {
5863 if (c >= 0x10000)
5864 {
5865 if (flags & FIO_UTF16)
5866 {
5867 /* Make two words, ten bits of the character in each. First
5868 * word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff */
5869 c -= 0x10000;
5870 if (c >= 0x100000)
5871 error = TRUE;
5872 cc = ((c >> 10) & 0x3ff) + 0xd800;
5873 if (flags & FIO_ENDIAN_L)
5874 {
5875 *p++ = cc;
5876 *p++ = ((unsigned)cc >> 8);
5877 }
5878 else
5879 {
5880 *p++ = ((unsigned)cc >> 8);
5881 *p++ = cc;
5882 }
5883 c = (c & 0x3ff) + 0xdc00;
5884 }
5885 else
5886 error = TRUE;
5887 }
5888 if (flags & FIO_ENDIAN_L)
5889 {
5890 *p++ = c;
5891 *p++ = (c >> 8);
5892 }
5893 else
5894 {
5895 *p++ = (c >> 8);
5896 *p++ = c;
5897 }
5898 }
5899 else /* Latin1 */
5900 {
5901 if (c >= 0x100)
5902 {
5903 error = TRUE;
5904 *p++ = 0xBF;
5905 }
5906 else
5907 *p++ = c;
5908 }
5909
5910 *pp = p;
5911 return error;
5912}
5913
5914/*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005915 * Return TRUE if file encoding "fenc" requires conversion from or to
5916 * 'encoding'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005917 */
5918 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005919need_conversion(char_u *fenc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005920{
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005921 int same_encoding;
5922 int enc_flags;
5923 int fenc_flags;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005924
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005925 if (*fenc == NUL || STRCMP(p_enc, fenc) == 0)
Bram Moolenaar442b4222010-05-24 21:34:22 +02005926 {
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005927 same_encoding = TRUE;
Bram Moolenaar442b4222010-05-24 21:34:22 +02005928 fenc_flags = 0;
5929 }
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005930 else
5931 {
5932 /* Ignore difference between "ansi" and "latin1", "ucs-4" and
5933 * "ucs-4be", etc. */
5934 enc_flags = get_fio_flags(p_enc);
5935 fenc_flags = get_fio_flags(fenc);
5936 same_encoding = (enc_flags != 0 && fenc_flags == enc_flags);
5937 }
5938 if (same_encoding)
5939 {
5940 /* Specified encoding matches with 'encoding'. This requires
5941 * conversion when 'encoding' is Unicode but not UTF-8. */
5942 return enc_unicode != 0;
5943 }
5944
5945 /* Encodings differ. However, conversion is not needed when 'enc' is any
5946 * Unicode encoding and the file is UTF-8. */
5947 return !(enc_utf8 && fenc_flags == FIO_UTF8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005948}
5949
5950/*
5951 * Check "ptr" for a unicode encoding and return the FIO_ flags needed for the
5952 * internal conversion.
5953 * if "ptr" is an empty string, use 'encoding'.
5954 */
5955 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005956get_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005957{
5958 int prop;
5959
5960 if (*ptr == NUL)
5961 ptr = p_enc;
5962
5963 prop = enc_canon_props(ptr);
5964 if (prop & ENC_UNICODE)
5965 {
5966 if (prop & ENC_2BYTE)
5967 {
5968 if (prop & ENC_ENDIAN_L)
5969 return FIO_UCS2 | FIO_ENDIAN_L;
5970 return FIO_UCS2;
5971 }
5972 if (prop & ENC_4BYTE)
5973 {
5974 if (prop & ENC_ENDIAN_L)
5975 return FIO_UCS4 | FIO_ENDIAN_L;
5976 return FIO_UCS4;
5977 }
5978 if (prop & ENC_2WORD)
5979 {
5980 if (prop & ENC_ENDIAN_L)
5981 return FIO_UTF16 | FIO_ENDIAN_L;
5982 return FIO_UTF16;
5983 }
5984 return FIO_UTF8;
5985 }
5986 if (prop & ENC_LATIN1)
5987 return FIO_LATIN1;
5988 /* must be ENC_DBCS, requires iconv() */
5989 return 0;
5990}
5991
5992#ifdef WIN3264
5993/*
5994 * Check "ptr" for a MS-Windows codepage name and return the FIO_ flags needed
5995 * for the conversion MS-Windows can do for us. Also accept "utf-8".
5996 * Used for conversion between 'encoding' and 'fileencoding'.
5997 */
5998 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005999get_win_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006000{
6001 int cp;
6002
6003 /* Cannot do this when 'encoding' is not utf-8 and not a codepage. */
6004 if (!enc_utf8 && enc_codepage <= 0)
6005 return 0;
6006
6007 cp = encname2codepage(ptr);
6008 if (cp == 0)
6009 {
6010# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
6011 if (STRCMP(ptr, "utf-8") == 0)
6012 cp = CP_UTF8;
6013 else
6014# endif
6015 return 0;
6016 }
6017 return FIO_PUT_CP(cp) | FIO_CODEPAGE;
6018}
6019#endif
6020
Bram Moolenaard0573012017-10-28 21:11:06 +02006021#ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00006022/*
6023 * Check "ptr" for a Carbon supported encoding and return the FIO_ flags
6024 * needed for the internal conversion to/from utf-8 or latin1.
6025 */
6026 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006027get_mac_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006028{
6029 if ((enc_utf8 || STRCMP(p_enc, "latin1") == 0)
6030 && (enc_canon_props(ptr) & ENC_MACROMAN))
6031 return FIO_MACROMAN;
6032 return 0;
6033}
6034#endif
6035
6036/*
6037 * Check for a Unicode BOM (Byte Order Mark) at the start of p[size].
6038 * "size" must be at least 2.
6039 * Return the name of the encoding and set "*lenp" to the length.
6040 * Returns NULL when no BOM found.
6041 */
6042 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006043check_for_bom(
6044 char_u *p,
6045 long size,
6046 int *lenp,
6047 int flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006048{
6049 char *name = NULL;
6050 int len = 2;
6051
6052 if (p[0] == 0xef && p[1] == 0xbb && size >= 3 && p[2] == 0xbf
Bram Moolenaaree0f5a62008-07-24 20:09:16 +00006053 && (flags == FIO_ALL || flags == FIO_UTF8 || flags == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006054 {
6055 name = "utf-8"; /* EF BB BF */
6056 len = 3;
6057 }
6058 else if (p[0] == 0xff && p[1] == 0xfe)
6059 {
6060 if (size >= 4 && p[2] == 0 && p[3] == 0
6061 && (flags == FIO_ALL || flags == (FIO_UCS4 | FIO_ENDIAN_L)))
6062 {
6063 name = "ucs-4le"; /* FF FE 00 00 */
6064 len = 4;
6065 }
Bram Moolenaar223a1892008-11-11 20:57:11 +00006066 else if (flags == (FIO_UCS2 | FIO_ENDIAN_L))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006067 name = "ucs-2le"; /* FF FE */
Bram Moolenaar223a1892008-11-11 20:57:11 +00006068 else if (flags == FIO_ALL || flags == (FIO_UTF16 | FIO_ENDIAN_L))
6069 /* utf-16le is preferred, it also works for ucs-2le text */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006070 name = "utf-16le"; /* FF FE */
6071 }
6072 else if (p[0] == 0xfe && p[1] == 0xff
6073 && (flags == FIO_ALL || flags == FIO_UCS2 || flags == FIO_UTF16))
6074 {
Bram Moolenaarffd82c52008-02-20 17:15:26 +00006075 /* Default to utf-16, it works also for ucs-2 text. */
6076 if (flags == FIO_UCS2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006077 name = "ucs-2"; /* FE FF */
Bram Moolenaarffd82c52008-02-20 17:15:26 +00006078 else
6079 name = "utf-16"; /* FE FF */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006080 }
6081 else if (size >= 4 && p[0] == 0 && p[1] == 0 && p[2] == 0xfe
6082 && p[3] == 0xff && (flags == FIO_ALL || flags == FIO_UCS4))
6083 {
6084 name = "ucs-4"; /* 00 00 FE FF */
6085 len = 4;
6086 }
6087
6088 *lenp = len;
6089 return (char_u *)name;
6090}
6091
6092/*
6093 * Generate a BOM in "buf[4]" for encoding "name".
6094 * Return the length of the BOM (zero when no BOM).
6095 */
6096 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006097make_bom(char_u *buf, char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006098{
6099 int flags;
6100 char_u *p;
6101
6102 flags = get_fio_flags(name);
6103
6104 /* Can't put a BOM in a non-Unicode file. */
6105 if (flags == FIO_LATIN1 || flags == 0)
6106 return 0;
6107
6108 if (flags == FIO_UTF8) /* UTF-8 */
6109 {
6110 buf[0] = 0xef;
6111 buf[1] = 0xbb;
6112 buf[2] = 0xbf;
6113 return 3;
6114 }
6115 p = buf;
6116 (void)ucs2bytes(0xfeff, &p, flags);
6117 return (int)(p - buf);
6118}
6119#endif
6120
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00006121#if defined(FEAT_VIMINFO) || defined(FEAT_BROWSE) || \
Bram Moolenaara0174af2008-01-02 20:08:25 +00006122 defined(FEAT_QUICKFIX) || defined(FEAT_AUTOCMD) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006123/*
6124 * Try to find a shortname by comparing the fullname with the current
6125 * directory.
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006126 * Returns "full_path" or pointer into "full_path" if shortened.
6127 */
6128 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006129shorten_fname1(char_u *full_path)
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006130{
Bram Moolenaard9462e32011-04-11 21:35:11 +02006131 char_u *dirname;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006132 char_u *p = full_path;
6133
Bram Moolenaard9462e32011-04-11 21:35:11 +02006134 dirname = alloc(MAXPATHL);
6135 if (dirname == NULL)
6136 return full_path;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006137 if (mch_dirname(dirname, MAXPATHL) == OK)
6138 {
6139 p = shorten_fname(full_path, dirname);
6140 if (p == NULL || *p == NUL)
6141 p = full_path;
6142 }
Bram Moolenaard9462e32011-04-11 21:35:11 +02006143 vim_free(dirname);
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006144 return p;
6145}
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00006146#endif
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006147
6148/*
6149 * Try to find a shortname by comparing the fullname with the current
6150 * directory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006151 * Returns NULL if not shorter name possible, pointer into "full_path"
6152 * otherwise.
6153 */
6154 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006155shorten_fname(char_u *full_path, char_u *dir_name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006156{
6157 int len;
6158 char_u *p;
6159
6160 if (full_path == NULL)
6161 return NULL;
6162 len = (int)STRLEN(dir_name);
6163 if (fnamencmp(dir_name, full_path, len) == 0)
6164 {
6165 p = full_path + len;
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006166#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006167 /*
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006168 * MSWIN: when a file is in the root directory, dir_name will end in a
Bram Moolenaar071d4272004-06-13 20:20:40 +00006169 * slash, since C: by itself does not define a specific dir. In this
6170 * case p may already be correct. <negri>
6171 */
6172 if (!((len > 2) && (*(p - 2) == ':')))
6173#endif
6174 {
6175 if (vim_ispathsep(*p))
6176 ++p;
6177#ifndef VMS /* the path separator is always part of the path */
6178 else
6179 p = NULL;
6180#endif
6181 }
6182 }
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006183#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006184 /*
6185 * When using a file in the current drive, remove the drive name:
6186 * "A:\dir\file" -> "\dir\file". This helps when moving a session file on
6187 * a floppy from "A:\dir" to "B:\dir".
6188 */
6189 else if (len > 3
6190 && TOUPPER_LOC(full_path[0]) == TOUPPER_LOC(dir_name[0])
6191 && full_path[1] == ':'
6192 && vim_ispathsep(full_path[2]))
6193 p = full_path + 2;
6194#endif
6195 else
6196 p = NULL;
6197 return p;
6198}
6199
6200/*
6201 * Shorten filenames for all buffers.
6202 * When "force" is TRUE: Use full path from now on for files currently being
6203 * edited, both for file name and swap file name. Try to shorten the file
6204 * names a bit, if safe to do so.
6205 * When "force" is FALSE: Only try to shorten absolute file names.
6206 * For buffers that have buftype "nofile" or "scratch": never change the file
6207 * name.
6208 */
6209 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006210shorten_fnames(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006211{
6212 char_u dirname[MAXPATHL];
6213 buf_T *buf;
6214 char_u *p;
6215
6216 mch_dirname(dirname, MAXPATHL);
Bram Moolenaar29323592016-07-24 22:04:11 +02006217 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006218 {
6219 if (buf->b_fname != NULL
6220#ifdef FEAT_QUICKFIX
6221 && !bt_nofile(buf)
6222#endif
6223 && !path_with_url(buf->b_fname)
6224 && (force
6225 || buf->b_sfname == NULL
6226 || mch_isFullName(buf->b_sfname)))
6227 {
6228 vim_free(buf->b_sfname);
6229 buf->b_sfname = NULL;
6230 p = shorten_fname(buf->b_ffname, dirname);
6231 if (p != NULL)
6232 {
6233 buf->b_sfname = vim_strsave(p);
6234 buf->b_fname = buf->b_sfname;
6235 }
6236 if (p == NULL || buf->b_fname == NULL)
6237 buf->b_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006238 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00006239
6240 /* Always make the swap file name a full path, a "nofile" buffer may
6241 * also have a swap file. */
6242 mf_fullname(buf->b_ml.ml_mfp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006243 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006244 status_redraw_all();
Bram Moolenaar49d7bf12006-02-17 21:45:41 +00006245 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006246}
6247
6248#if (defined(FEAT_DND) && defined(FEAT_GUI_GTK)) \
6249 || defined(FEAT_GUI_MSWIN) \
6250 || defined(FEAT_GUI_MAC) \
6251 || defined(PROTO)
6252/*
6253 * Shorten all filenames in "fnames[count]" by current directory.
6254 */
6255 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006256shorten_filenames(char_u **fnames, int count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006257{
6258 int i;
6259 char_u dirname[MAXPATHL];
6260 char_u *p;
6261
6262 if (fnames == NULL || count < 1)
6263 return;
6264 mch_dirname(dirname, sizeof(dirname));
6265 for (i = 0; i < count; ++i)
6266 {
6267 if ((p = shorten_fname(fnames[i], dirname)) != NULL)
6268 {
6269 /* shorten_fname() returns pointer in given "fnames[i]". If free
6270 * "fnames[i]" first, "p" becomes invalid. So we need to copy
6271 * "p" first then free fnames[i]. */
6272 p = vim_strsave(p);
6273 vim_free(fnames[i]);
6274 fnames[i] = p;
6275 }
6276 }
6277}
6278#endif
6279
6280/*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006281 * add extension to file name - change path/fo.o.h to path/fo.o.h.ext or
Bram Moolenaar071d4272004-06-13 20:20:40 +00006282 * fo_o_h.ext for MSDOS or when shortname option set.
6283 *
6284 * Assumed that fname is a valid name found in the filesystem we assure that
6285 * the return value is a different name and ends in 'ext'.
6286 * "ext" MUST be at most 4 characters long if it starts with a dot, 3
6287 * characters otherwise.
6288 * Space for the returned name is allocated, must be freed later.
6289 * Returns NULL when out of memory.
6290 */
6291 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006292modname(
6293 char_u *fname,
6294 char_u *ext,
6295 int prepend_dot) /* may prepend a '.' to file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006296{
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006297 return buf_modname((curbuf->b_p_sn || curbuf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00006298 fname, ext, prepend_dot);
6299}
6300
6301 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006302buf_modname(
6303 int shortname, /* use 8.3 file name */
6304 char_u *fname,
6305 char_u *ext,
6306 int prepend_dot) /* may prepend a '.' to file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006307{
6308 char_u *retval;
6309 char_u *s;
6310 char_u *e;
6311 char_u *ptr;
6312 int fnamelen, extlen;
6313
6314 extlen = (int)STRLEN(ext);
6315
6316 /*
6317 * If there is no file name we must get the name of the current directory
6318 * (we need the full path in case :cd is used).
6319 */
6320 if (fname == NULL || *fname == NUL)
6321 {
6322 retval = alloc((unsigned)(MAXPATHL + extlen + 3));
6323 if (retval == NULL)
6324 return NULL;
6325 if (mch_dirname(retval, MAXPATHL) == FAIL ||
6326 (fnamelen = (int)STRLEN(retval)) == 0)
6327 {
6328 vim_free(retval);
6329 return NULL;
6330 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006331 if (!after_pathsep(retval, retval + fnamelen))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006332 {
6333 retval[fnamelen++] = PATHSEP;
6334 retval[fnamelen] = NUL;
6335 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006336 prepend_dot = FALSE; /* nothing to prepend a dot to */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006337 }
6338 else
6339 {
6340 fnamelen = (int)STRLEN(fname);
6341 retval = alloc((unsigned)(fnamelen + extlen + 3));
6342 if (retval == NULL)
6343 return NULL;
6344 STRCPY(retval, fname);
6345#ifdef VMS
6346 vms_remove_version(retval); /* we do not need versions here */
6347#endif
6348 }
6349
6350 /*
6351 * search backwards until we hit a '/', '\' or ':' replacing all '.'
6352 * by '_' for MSDOS or when shortname option set and ext starts with a dot.
6353 * Then truncate what is after the '/', '\' or ':' to 8 characters for
6354 * MSDOS and 26 characters for AMIGA, a lot more for UNIX.
6355 */
Bram Moolenaar91acfff2017-03-12 19:22:36 +01006356 for (ptr = retval + fnamelen; ptr > retval; MB_PTR_BACK(retval, ptr))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006357 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006358 if (*ext == '.'
Bram Moolenaare60acc12011-05-10 16:41:25 +02006359#ifdef USE_LONG_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00006360 && (!USE_LONG_FNAME || shortname)
Bram Moolenaare60acc12011-05-10 16:41:25 +02006361#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006362 && shortname
Bram Moolenaare60acc12011-05-10 16:41:25 +02006363#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006364 )
6365 if (*ptr == '.') /* replace '.' by '_' */
6366 *ptr = '_';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006367 if (vim_ispathsep(*ptr))
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006368 {
6369 ++ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006370 break;
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006371 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006372 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006373
6374 /* the file name has at most BASENAMELEN characters. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006375 if (STRLEN(ptr) > (unsigned)BASENAMELEN)
6376 ptr[BASENAMELEN] = '\0';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006377
6378 s = ptr + STRLEN(ptr);
6379
6380 /*
6381 * For 8.3 file names we may have to reduce the length.
6382 */
6383#ifdef USE_LONG_FNAME
6384 if (!USE_LONG_FNAME || shortname)
6385#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006386 if (shortname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006387#endif
6388 {
6389 /*
6390 * If there is no file name, or the file name ends in '/', and the
6391 * extension starts with '.', put a '_' before the dot, because just
6392 * ".ext" is invalid.
6393 */
6394 if (fname == NULL || *fname == NUL
6395 || vim_ispathsep(fname[STRLEN(fname) - 1]))
6396 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006397 if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006398 *s++ = '_';
6399 }
6400 /*
6401 * If the extension starts with '.', truncate the base name at 8
6402 * characters
6403 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006404 else if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006405 {
Bram Moolenaar78a15312009-05-15 19:33:18 +00006406 if ((size_t)(s - ptr) > (size_t)8)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006407 {
6408 s = ptr + 8;
6409 *s = '\0';
6410 }
6411 }
6412 /*
6413 * If the extension doesn't start with '.', and the file name
6414 * doesn't have an extension yet, append a '.'
6415 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006416 else if ((e = vim_strchr(ptr, '.')) == NULL)
6417 *s++ = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006418 /*
6419 * If the extension doesn't start with '.', and there already is an
Bram Moolenaar7263a772007-05-10 17:35:54 +00006420 * extension, it may need to be truncated
Bram Moolenaar071d4272004-06-13 20:20:40 +00006421 */
6422 else if ((int)STRLEN(e) + extlen > 4)
6423 s = e + 4 - extlen;
6424 }
Bram Moolenaare7fedb62015-12-31 19:07:19 +01006425#if defined(USE_LONG_FNAME) || defined(WIN3264)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006426 /*
6427 * If there is no file name, and the extension starts with '.', put a
6428 * '_' before the dot, because just ".ext" may be invalid if it's on a
6429 * FAT partition, and on HPFS it doesn't matter.
6430 */
6431 else if ((fname == NULL || *fname == NUL) && *ext == '.')
6432 *s++ = '_';
6433#endif
6434
6435 /*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006436 * Append the extension.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006437 * ext can start with '.' and cannot exceed 3 more characters.
6438 */
6439 STRCPY(s, ext);
6440
Bram Moolenaar071d4272004-06-13 20:20:40 +00006441 /*
6442 * Prepend the dot.
6443 */
Bram Moolenaare60acc12011-05-10 16:41:25 +02006444 if (prepend_dot && !shortname && *(e = gettail(retval)) != '.'
Bram Moolenaar071d4272004-06-13 20:20:40 +00006445#ifdef USE_LONG_FNAME
6446 && USE_LONG_FNAME
6447#endif
6448 )
6449 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006450 STRMOVE(e + 1, e);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006451 *e = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006452 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006453
6454 /*
6455 * Check that, after appending the extension, the file name is really
6456 * different.
6457 */
6458 if (fname != NULL && STRCMP(fname, retval) == 0)
6459 {
6460 /* we search for a character that can be replaced by '_' */
6461 while (--s >= ptr)
6462 {
6463 if (*s != '_')
6464 {
6465 *s = '_';
6466 break;
6467 }
6468 }
6469 if (s < ptr) /* fname was "________.<ext>", how tricky! */
6470 *ptr = 'v';
6471 }
6472 return retval;
6473}
6474
6475/*
6476 * Like fgets(), but if the file line is too long, it is truncated and the
6477 * rest of the line is thrown away. Returns TRUE for end-of-file.
6478 */
6479 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006480vim_fgets(char_u *buf, int size, FILE *fp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006481{
6482 char *eof;
6483#define FGETS_SIZE 200
6484 char tbuf[FGETS_SIZE];
6485
6486 buf[size - 2] = NUL;
6487#ifdef USE_CR
6488 eof = fgets_cr((char *)buf, size, fp);
6489#else
6490 eof = fgets((char *)buf, size, fp);
6491#endif
6492 if (buf[size - 2] != NUL && buf[size - 2] != '\n')
6493 {
6494 buf[size - 1] = NUL; /* Truncate the line */
6495
6496 /* Now throw away the rest of the line: */
6497 do
6498 {
6499 tbuf[FGETS_SIZE - 2] = NUL;
6500#ifdef USE_CR
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006501 ignoredp = fgets_cr((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006502#else
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006503 ignoredp = fgets((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006504#endif
6505 } while (tbuf[FGETS_SIZE - 2] != NUL && tbuf[FGETS_SIZE - 2] != '\n');
6506 }
6507 return (eof == NULL);
6508}
6509
6510#if defined(USE_CR) || defined(PROTO)
6511/*
6512 * Like vim_fgets(), but accept any line terminator: CR, CR-LF or LF.
6513 * Returns TRUE for end-of-file.
6514 * Only used for the Mac, because it's much slower than vim_fgets().
6515 */
6516 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006517tag_fgets(char_u *buf, int size, FILE *fp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006518{
6519 int i = 0;
6520 int c;
6521 int eof = FALSE;
6522
6523 for (;;)
6524 {
6525 c = fgetc(fp);
6526 if (c == EOF)
6527 {
6528 eof = TRUE;
6529 break;
6530 }
6531 if (c == '\r')
6532 {
6533 /* Always store a NL for end-of-line. */
6534 if (i < size - 1)
6535 buf[i++] = '\n';
6536 c = fgetc(fp);
6537 if (c != '\n') /* Macintosh format: single CR. */
6538 ungetc(c, fp);
6539 break;
6540 }
6541 if (i < size - 1)
6542 buf[i++] = c;
6543 if (c == '\n')
6544 break;
6545 }
6546 buf[i] = NUL;
6547 return eof;
6548}
6549#endif
6550
6551/*
6552 * rename() only works if both files are on the same file system, this
6553 * function will (attempts to?) copy the file across if rename fails -- webb
6554 * Return -1 for failure, 0 for success.
6555 */
6556 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006557vim_rename(char_u *from, char_u *to)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006558{
6559 int fd_in;
6560 int fd_out;
6561 int n;
6562 char *errmsg = NULL;
6563 char *buffer;
6564#ifdef AMIGA
6565 BPTR flock;
6566#endif
Bram Moolenaar8767f522016-07-01 17:17:39 +02006567 stat_T st;
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006568 long perm;
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006569#ifdef HAVE_ACL
6570 vim_acl_T acl; /* ACL from original file */
6571#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006572 int use_tmp_file = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006573
6574 /*
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006575 * When the names are identical, there is nothing to do. When they refer
6576 * to the same file (ignoring case and slash/backslash differences) but
6577 * the file name differs we need to go through a temp file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006578 */
6579 if (fnamecmp(from, to) == 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006580 {
Bram Moolenaar71afbfe2013-03-19 16:49:16 +01006581 if (p_fic && STRCMP(gettail(from), gettail(to)) != 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006582 use_tmp_file = TRUE;
6583 else
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006584 return 0;
6585 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006586
6587 /*
6588 * Fail if the "from" file doesn't exist. Avoids that "to" is deleted.
6589 */
6590 if (mch_stat((char *)from, &st) < 0)
6591 return -1;
6592
Bram Moolenaar3576da72008-12-30 15:15:57 +00006593#ifdef UNIX
6594 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02006595 stat_T st_to;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006596
6597 /* It's possible for the source and destination to be the same file.
6598 * This happens when "from" and "to" differ in case and are on a FAT32
6599 * filesystem. In that case go through a temp file name. */
6600 if (mch_stat((char *)to, &st_to) >= 0
6601 && st.st_dev == st_to.st_dev
6602 && st.st_ino == st_to.st_ino)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006603 use_tmp_file = TRUE;
6604 }
6605#endif
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02006606#ifdef WIN3264
6607 {
6608 BY_HANDLE_FILE_INFORMATION info1, info2;
6609
6610 /* It's possible for the source and destination to be the same file.
6611 * In that case go through a temp file name. This makes rename("foo",
6612 * "./foo") a no-op (in a complicated way). */
6613 if (win32_fileinfo(from, &info1) == FILEINFO_OK
6614 && win32_fileinfo(to, &info2) == FILEINFO_OK
6615 && info1.dwVolumeSerialNumber == info2.dwVolumeSerialNumber
6616 && info1.nFileIndexHigh == info2.nFileIndexHigh
6617 && info1.nFileIndexLow == info2.nFileIndexLow)
6618 use_tmp_file = TRUE;
6619 }
6620#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006621
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006622 if (use_tmp_file)
6623 {
6624 char tempname[MAXPATHL + 1];
6625
6626 /*
6627 * Find a name that doesn't exist and is in the same directory.
6628 * Rename "from" to "tempname" and then rename "tempname" to "to".
6629 */
6630 if (STRLEN(from) >= MAXPATHL - 5)
6631 return -1;
6632 STRCPY(tempname, from);
6633 for (n = 123; n < 99999; ++n)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006634 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006635 sprintf((char *)gettail((char_u *)tempname), "%d", n);
6636 if (mch_stat(tempname, &st) < 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006637 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006638 if (mch_rename((char *)from, tempname) == 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006639 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006640 if (mch_rename(tempname, (char *)to) == 0)
6641 return 0;
6642 /* Strange, the second step failed. Try moving the
6643 * file back and return failure. */
6644 mch_rename(tempname, (char *)from);
Bram Moolenaar3576da72008-12-30 15:15:57 +00006645 return -1;
6646 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006647 /* If it fails for one temp name it will most likely fail
6648 * for any temp name, give up. */
6649 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006650 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006651 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006652 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006653 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006654
Bram Moolenaar071d4272004-06-13 20:20:40 +00006655 /*
6656 * Delete the "to" file, this is required on some systems to make the
6657 * mch_rename() work, on other systems it makes sure that we don't have
6658 * two files when the mch_rename() fails.
6659 */
6660
6661#ifdef AMIGA
6662 /*
6663 * With MSDOS-compatible filesystems (crossdos, messydos) it is possible
6664 * that the name of the "to" file is the same as the "from" file, even
Bram Moolenaar7263a772007-05-10 17:35:54 +00006665 * though the names are different. To avoid the chance of accidentally
Bram Moolenaar071d4272004-06-13 20:20:40 +00006666 * deleting the "from" file (horror!) we lock it during the remove.
6667 *
6668 * When used for making a backup before writing the file: This should not
6669 * happen with ":w", because startscript() should detect this problem and
6670 * set buf->b_shortname, causing modname() to return a correct ".bak" file
6671 * name. This problem does exist with ":w filename", but then the
6672 * original file will be somewhere else so the backup isn't really
6673 * important. If autoscripting is off the rename may fail.
6674 */
6675 flock = Lock((UBYTE *)from, (long)ACCESS_READ);
6676#endif
6677 mch_remove(to);
6678#ifdef AMIGA
6679 if (flock)
6680 UnLock(flock);
6681#endif
6682
6683 /*
6684 * First try a normal rename, return if it works.
6685 */
6686 if (mch_rename((char *)from, (char *)to) == 0)
6687 return 0;
6688
6689 /*
6690 * Rename() failed, try copying the file.
6691 */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006692 perm = mch_getperm(from);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006693#ifdef HAVE_ACL
6694 /* For systems that support ACL: get the ACL from the original file. */
6695 acl = mch_get_acl(from);
6696#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006697 fd_in = mch_open((char *)from, O_RDONLY|O_EXTRA, 0);
6698 if (fd_in == -1)
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006699 {
6700#ifdef HAVE_ACL
6701 mch_free_acl(acl);
6702#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006703 return -1;
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006704 }
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006705
6706 /* Create the new file with same permissions as the original. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00006707 fd_out = mch_open((char *)to,
6708 O_CREAT|O_EXCL|O_WRONLY|O_EXTRA|O_NOFOLLOW, (int)perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006709 if (fd_out == -1)
6710 {
6711 close(fd_in);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006712#ifdef HAVE_ACL
6713 mch_free_acl(acl);
6714#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006715 return -1;
6716 }
6717
6718 buffer = (char *)alloc(BUFSIZE);
6719 if (buffer == NULL)
6720 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006721 close(fd_out);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006722 close(fd_in);
6723#ifdef HAVE_ACL
6724 mch_free_acl(acl);
6725#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006726 return -1;
6727 }
6728
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01006729 while ((n = read_eintr(fd_in, buffer, BUFSIZE)) > 0)
6730 if (write_eintr(fd_out, buffer, n) != n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006731 {
6732 errmsg = _("E208: Error writing to \"%s\"");
6733 break;
6734 }
6735
6736 vim_free(buffer);
6737 close(fd_in);
6738 if (close(fd_out) < 0)
6739 errmsg = _("E209: Error closing \"%s\"");
6740 if (n < 0)
6741 {
6742 errmsg = _("E210: Error reading \"%s\"");
6743 to = from;
6744 }
Bram Moolenaar7263a772007-05-10 17:35:54 +00006745#ifndef UNIX /* for Unix mch_open() already set the permission */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006746 mch_setperm(to, perm);
Bram Moolenaarc6039d82005-12-02 00:44:04 +00006747#endif
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006748#ifdef HAVE_ACL
6749 mch_set_acl(to, acl);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006750 mch_free_acl(acl);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006751#endif
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02006752#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaare8747442013-11-12 18:09:29 +01006753 mch_copy_sec(from, to);
Bram Moolenaar0671de32013-11-12 05:12:03 +01006754#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006755 if (errmsg != NULL)
6756 {
6757 EMSG2(errmsg, to);
6758 return -1;
6759 }
6760 mch_remove(from);
6761 return 0;
6762}
6763
6764static int already_warned = FALSE;
6765
6766/*
6767 * Check if any not hidden buffer has been changed.
6768 * Postpone the check if there are characters in the stuff buffer, a global
6769 * command is being executed, a mapping is being executed or an autocommand is
6770 * busy.
6771 * Returns TRUE if some message was written (screen should be redrawn and
6772 * cursor positioned).
6773 */
6774 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006775check_timestamps(
6776 int focus) /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006777{
6778 buf_T *buf;
6779 int didit = 0;
6780 int n;
6781
6782 /* Don't check timestamps while system() or another low-level function may
6783 * cause us to lose and gain focus. */
6784 if (no_check_timestamps > 0)
6785 return FALSE;
6786
6787 /* Avoid doing a check twice. The OK/Reload dialog can cause a focus
6788 * event and we would keep on checking if the file is steadily growing.
6789 * Do check again after typing something. */
6790 if (focus && did_check_timestamps)
6791 {
6792 need_check_timestamps = TRUE;
6793 return FALSE;
6794 }
6795
6796 if (!stuff_empty() || global_busy || !typebuf_typed()
6797#ifdef FEAT_AUTOCMD
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006798 || autocmd_busy || curbuf_lock > 0 || allbuf_lock > 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00006799#endif
6800 )
6801 need_check_timestamps = TRUE; /* check later */
6802 else
6803 {
6804 ++no_wait_return;
6805 did_check_timestamps = TRUE;
6806 already_warned = FALSE;
Bram Moolenaar29323592016-07-24 22:04:11 +02006807 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006808 {
6809 /* Only check buffers in a window. */
6810 if (buf->b_nwindows > 0)
6811 {
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006812 bufref_T bufref;
6813
6814 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006815 n = buf_check_timestamp(buf, focus);
6816 if (didit < n)
6817 didit = n;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006818 if (n > 0 && !bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006819 {
6820 /* Autocommands have removed the buffer, start at the
6821 * first one again. */
6822 buf = firstbuf;
6823 continue;
6824 }
6825 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006826 }
6827 --no_wait_return;
6828 need_check_timestamps = FALSE;
6829 if (need_wait_return && didit == 2)
6830 {
6831 /* make sure msg isn't overwritten */
6832 msg_puts((char_u *)"\n");
6833 out_flush();
6834 }
6835 }
6836 return didit;
6837}
6838
6839/*
6840 * Move all the lines from buffer "frombuf" to buffer "tobuf".
6841 * Return OK or FAIL. When FAIL "tobuf" is incomplete and/or "frombuf" is not
6842 * empty.
6843 */
6844 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006845move_lines(buf_T *frombuf, buf_T *tobuf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006846{
6847 buf_T *tbuf = curbuf;
6848 int retval = OK;
6849 linenr_T lnum;
6850 char_u *p;
6851
6852 /* Copy the lines in "frombuf" to "tobuf". */
6853 curbuf = tobuf;
6854 for (lnum = 1; lnum <= frombuf->b_ml.ml_line_count; ++lnum)
6855 {
6856 p = vim_strsave(ml_get_buf(frombuf, lnum, FALSE));
6857 if (p == NULL || ml_append(lnum - 1, p, 0, FALSE) == FAIL)
6858 {
6859 vim_free(p);
6860 retval = FAIL;
6861 break;
6862 }
6863 vim_free(p);
6864 }
6865
6866 /* Delete all the lines in "frombuf". */
6867 if (retval != FAIL)
6868 {
6869 curbuf = frombuf;
Bram Moolenaar9460b9d2007-01-09 14:37:01 +00006870 for (lnum = curbuf->b_ml.ml_line_count; lnum > 0; --lnum)
6871 if (ml_delete(lnum, FALSE) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006872 {
6873 /* Oops! We could try putting back the saved lines, but that
6874 * might fail again... */
6875 retval = FAIL;
6876 break;
6877 }
6878 }
6879
6880 curbuf = tbuf;
6881 return retval;
6882}
6883
6884/*
6885 * Check if buffer "buf" has been changed.
6886 * Also check if the file for a new buffer unexpectedly appeared.
6887 * return 1 if a changed buffer was found.
6888 * return 2 if a message has been displayed.
6889 * return 0 otherwise.
6890 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006891 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006892buf_check_timestamp(
6893 buf_T *buf,
6894 int focus UNUSED) /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006895{
Bram Moolenaar8767f522016-07-01 17:17:39 +02006896 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006897 int stat_res;
6898 int retval = 0;
6899 char_u *path;
6900 char_u *tbuf;
6901 char *mesg = NULL;
Bram Moolenaar44ecf652005-03-07 23:09:59 +00006902 char *mesg2 = "";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006903 int helpmesg = FALSE;
6904 int reload = FALSE;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006905 char *reason;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006906#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6907 int can_reload = FALSE;
6908#endif
Bram Moolenaar8767f522016-07-01 17:17:39 +02006909 off_T orig_size = buf->b_orig_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006910 int orig_mode = buf->b_orig_mode;
6911#ifdef FEAT_GUI
6912 int save_mouse_correct = need_mouse_correct;
6913#endif
6914#ifdef FEAT_AUTOCMD
6915 static int busy = FALSE;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006916 int n;
6917 char_u *s;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006918 bufref_T bufref;
6919
6920 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006921#endif
6922
6923 /* If there is no file name, the buffer is not loaded, 'buftype' is
6924 * set, we are in the middle of a save or being called recursively: ignore
6925 * this buffer. */
6926 if (buf->b_ffname == NULL
6927 || buf->b_ml.ml_mfp == NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00006928 || *buf->b_p_bt != NUL
Bram Moolenaar071d4272004-06-13 20:20:40 +00006929 || buf->b_saving
6930#ifdef FEAT_AUTOCMD
6931 || busy
6932#endif
Bram Moolenaar009b2592004-10-24 19:18:58 +00006933#ifdef FEAT_NETBEANS_INTG
6934 || isNetbeansBuffer(buf)
6935#endif
Bram Moolenaar8cad9302017-08-12 14:32:32 +02006936#ifdef FEAT_TERMINAL
6937 || buf->b_term != NULL
6938#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006939 )
6940 return 0;
6941
6942 if ( !(buf->b_flags & BF_NOTEDITED)
6943 && buf->b_mtime != 0
6944 && ((stat_res = mch_stat((char *)buf->b_ffname, &st)) < 0
6945 || time_differs((long)st.st_mtime, buf->b_mtime)
Bram Moolenaara7611f62014-05-02 15:46:14 +02006946 || st.st_size != buf->b_orig_size
Bram Moolenaar071d4272004-06-13 20:20:40 +00006947#ifdef HAVE_ST_MODE
6948 || (int)st.st_mode != buf->b_orig_mode
6949#else
6950 || mch_getperm(buf->b_ffname) != buf->b_orig_mode
6951#endif
6952 ))
6953 {
6954 retval = 1;
6955
Bram Moolenaar316059c2006-01-14 21:18:42 +00006956 /* set b_mtime to stop further warnings (e.g., when executing
6957 * FileChangedShell autocmd) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006958 if (stat_res < 0)
6959 {
6960 buf->b_mtime = 0;
6961 buf->b_orig_size = 0;
6962 buf->b_orig_mode = 0;
6963 }
6964 else
6965 buf_store_time(buf, &st, buf->b_ffname);
6966
6967 /* Don't do anything for a directory. Might contain the file
6968 * explorer. */
6969 if (mch_isdir(buf->b_fname))
6970 ;
6971
6972 /*
6973 * If 'autoread' is set, the buffer has no changes and the file still
6974 * exists, reload the buffer. Use the buffer-local option value if it
6975 * was set, the global option value otherwise.
6976 */
6977 else if ((buf->b_p_ar >= 0 ? buf->b_p_ar : p_ar)
6978 && !bufIsChanged(buf) && stat_res >= 0)
6979 reload = TRUE;
6980 else
6981 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006982 if (stat_res < 0)
6983 reason = "deleted";
6984 else if (bufIsChanged(buf))
6985 reason = "conflict";
6986 else if (orig_size != buf->b_orig_size || buf_contents_changed(buf))
6987 reason = "changed";
6988 else if (orig_mode != buf->b_orig_mode)
6989 reason = "mode";
6990 else
6991 reason = "time";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006992
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006993#ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006994 /*
6995 * Only give the warning if there are no FileChangedShell
6996 * autocommands.
6997 * Avoid being called recursively by setting "busy".
6998 */
6999 busy = TRUE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00007000# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007001 set_vim_var_string(VV_FCS_REASON, (char_u *)reason, -1);
7002 set_vim_var_string(VV_FCS_CHOICE, (char_u *)"", -1);
Bram Moolenaar1e015462005-09-25 22:16:38 +00007003# endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00007004 ++allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007005 n = apply_autocmds(EVENT_FILECHANGEDSHELL,
7006 buf->b_fname, buf->b_fname, FALSE, buf);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00007007 --allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007008 busy = FALSE;
7009 if (n)
7010 {
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007011 if (!bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007012 EMSG(_("E246: FileChangedShell autocommand deleted buffer"));
Bram Moolenaar1e015462005-09-25 22:16:38 +00007013# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007014 s = get_vim_var_str(VV_FCS_CHOICE);
7015 if (STRCMP(s, "reload") == 0 && *reason != 'd')
7016 reload = TRUE;
7017 else if (STRCMP(s, "ask") == 0)
7018 n = FALSE;
7019 else
Bram Moolenaar1e015462005-09-25 22:16:38 +00007020# endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007021 return 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007022 }
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007023 if (!n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007024#endif
7025 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007026 if (*reason == 'd')
7027 mesg = _("E211: File \"%s\" no longer available");
Bram Moolenaar071d4272004-06-13 20:20:40 +00007028 else
7029 {
7030 helpmesg = TRUE;
7031#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
7032 can_reload = TRUE;
7033#endif
7034 /*
7035 * Check if the file contents really changed to avoid
7036 * giving a warning when only the timestamp was set (e.g.,
7037 * checked out of CVS). Always warn when the buffer was
7038 * changed.
7039 */
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007040 if (reason[2] == 'n')
7041 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007042 mesg = _("W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007043 mesg2 = _("See \":help W12\" for more info.");
7044 }
7045 else if (reason[1] == 'h')
7046 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007047 mesg = _("W11: Warning: File \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007048 mesg2 = _("See \":help W11\" for more info.");
7049 }
7050 else if (*reason == 'm')
7051 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007052 mesg = _("W16: Warning: Mode of file \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007053 mesg2 = _("See \":help W16\" for more info.");
7054 }
Bram Moolenaar85388b52009-06-24 09:58:32 +00007055 else
7056 /* Only timestamp changed, store it to avoid a warning
7057 * in check_mtime() later. */
7058 buf->b_mtime_read = buf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007059 }
7060 }
7061 }
7062
7063 }
7064 else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W)
7065 && vim_fexists(buf->b_ffname))
7066 {
7067 retval = 1;
7068 mesg = _("W13: Warning: File \"%s\" has been created after editing started");
7069 buf->b_flags |= BF_NEW_W;
7070#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
7071 can_reload = TRUE;
7072#endif
7073 }
7074
7075 if (mesg != NULL)
7076 {
7077 path = home_replace_save(buf, buf->b_fname);
7078 if (path != NULL)
7079 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007080 if (!helpmesg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007081 mesg2 = "";
7082 tbuf = alloc((unsigned)(STRLEN(path) + STRLEN(mesg)
7083 + STRLEN(mesg2) + 2));
7084 sprintf((char *)tbuf, mesg, path);
Bram Moolenaar496c5262009-03-18 14:42:00 +00007085#ifdef FEAT_EVAL
7086 /* Set warningmsg here, before the unimportant and output-specific
7087 * mesg2 has been appended. */
7088 set_vim_var_string(VV_WARNINGMSG, tbuf, -1);
7089#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007090#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
7091 if (can_reload)
7092 {
7093 if (*mesg2 != NUL)
7094 {
7095 STRCAT(tbuf, "\n");
7096 STRCAT(tbuf, mesg2);
7097 }
7098 if (do_dialog(VIM_WARNING, (char_u *)_("Warning"), tbuf,
Bram Moolenaard2c340a2011-01-17 20:08:11 +01007099 (char_u *)_("&OK\n&Load File"), 1, NULL, TRUE) == 2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007100 reload = TRUE;
7101 }
7102 else
7103#endif
7104 if (State > NORMAL_BUSY || (State & CMDLINE) || already_warned)
7105 {
7106 if (*mesg2 != NUL)
7107 {
7108 STRCAT(tbuf, "; ");
7109 STRCAT(tbuf, mesg2);
7110 }
7111 EMSG(tbuf);
7112 retval = 2;
7113 }
7114 else
7115 {
Bram Moolenaared203462004-06-16 11:19:22 +00007116# ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00007117 if (!autocmd_busy)
Bram Moolenaared203462004-06-16 11:19:22 +00007118# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007119 {
7120 msg_start();
Bram Moolenaar8820b482017-03-16 17:23:31 +01007121 msg_puts_attr(tbuf, HL_ATTR(HLF_E) + MSG_HIST);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007122 if (*mesg2 != NUL)
7123 msg_puts_attr((char_u *)mesg2,
Bram Moolenaar8820b482017-03-16 17:23:31 +01007124 HL_ATTR(HLF_W) + MSG_HIST);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007125 msg_clr_eos();
7126 (void)msg_end();
7127 if (emsg_silent == 0)
7128 {
7129 out_flush();
Bram Moolenaared203462004-06-16 11:19:22 +00007130# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00007131 if (!focus)
Bram Moolenaared203462004-06-16 11:19:22 +00007132# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007133 /* give the user some time to think about it */
7134 ui_delay(1000L, TRUE);
7135
7136 /* don't redraw and erase the message */
7137 redraw_cmdline = FALSE;
7138 }
7139 }
7140 already_warned = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007141 }
7142
7143 vim_free(path);
7144 vim_free(tbuf);
7145 }
7146 }
7147
7148 if (reload)
Bram Moolenaar465748e2012-08-29 18:50:54 +02007149 {
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007150 /* Reload the buffer. */
Bram Moolenaar316059c2006-01-14 21:18:42 +00007151 buf_reload(buf, orig_mode);
Bram Moolenaar465748e2012-08-29 18:50:54 +02007152#ifdef FEAT_PERSISTENT_UNDO
7153 if (buf->b_p_udf && buf->b_ffname != NULL)
7154 {
7155 char_u hash[UNDO_HASH_SIZE];
7156 buf_T *save_curbuf = curbuf;
7157
7158 /* Any existing undo file is unusable, write it now. */
7159 curbuf = buf;
7160 u_compute_hash(hash);
7161 u_write_undo(NULL, FALSE, buf, hash);
7162 curbuf = save_curbuf;
7163 }
7164#endif
7165 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007166
Bram Moolenaar56718732006-03-15 22:53:57 +00007167#ifdef FEAT_AUTOCMD
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00007168 /* Trigger FileChangedShell when the file was changed in any way. */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007169 if (bufref_valid(&bufref) && retval != 0)
Bram Moolenaar56718732006-03-15 22:53:57 +00007170 (void)apply_autocmds(EVENT_FILECHANGEDSHELLPOST,
7171 buf->b_fname, buf->b_fname, FALSE, buf);
7172#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007173#ifdef FEAT_GUI
7174 /* restore this in case an autocommand has set it; it would break
7175 * 'mousefocus' */
7176 need_mouse_correct = save_mouse_correct;
7177#endif
7178
7179 return retval;
7180}
7181
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007182/*
7183 * Reload a buffer that is already loaded.
7184 * Used when the file was changed outside of Vim.
Bram Moolenaar316059c2006-01-14 21:18:42 +00007185 * "orig_mode" is buf->b_orig_mode before the need for reloading was detected.
7186 * buf->b_orig_mode may have been reset already.
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007187 */
7188 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007189buf_reload(buf_T *buf, int orig_mode)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007190{
7191 exarg_T ea;
7192 pos_T old_cursor;
7193 linenr_T old_topline;
7194 int old_ro = buf->b_p_ro;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007195 buf_T *savebuf;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007196 bufref_T bufref;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007197 int saved = OK;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007198 aco_save_T aco;
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007199 int flags = READ_NEW;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007200
7201 /* set curwin/curbuf for "buf" and save some things */
7202 aucmd_prepbuf(&aco, buf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007203
7204 /* We only want to read the text from the file, not reset the syntax
7205 * highlighting, clear marks, diff status, etc. Force the fileformat
7206 * and encoding to be the same. */
7207 if (prep_exarg(&ea, buf) == OK)
7208 {
7209 old_cursor = curwin->w_cursor;
7210 old_topline = curwin->w_topline;
7211
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007212 if (p_ur < 0 || curbuf->b_ml.ml_line_count <= p_ur)
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007213 {
7214 /* Save all the text, so that the reload can be undone.
7215 * Sync first so that this is a separate undo-able action. */
7216 u_sync(FALSE);
7217 saved = u_savecommon(0, curbuf->b_ml.ml_line_count + 1, 0, TRUE);
7218 flags |= READ_KEEP_UNDO;
7219 }
7220
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007221 /*
7222 * To behave like when a new file is edited (matters for
7223 * BufReadPost autocommands) we first need to delete the current
7224 * buffer contents. But if reading the file fails we should keep
7225 * the old contents. Can't use memory only, the file might be
7226 * too big. Use a hidden buffer to move the buffer contents to.
7227 */
Bram Moolenaarb5aedf32017-03-12 18:23:53 +01007228 if (BUFEMPTY() || saved == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007229 savebuf = NULL;
7230 else
7231 {
7232 /* Allocate a buffer without putting it in the buffer list. */
7233 savebuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007234 set_bufref(&bufref, savebuf);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007235 if (savebuf != NULL && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007236 {
7237 /* Open the memline. */
7238 curbuf = savebuf;
7239 curwin->w_buffer = savebuf;
Bram Moolenaar4770d092006-01-12 23:22:24 +00007240 saved = ml_open(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007241 curbuf = buf;
7242 curwin->w_buffer = buf;
7243 }
Bram Moolenaar8424a622006-04-19 21:23:36 +00007244 if (savebuf == NULL || saved == FAIL || buf != curbuf
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007245 || move_lines(buf, savebuf) == FAIL)
7246 {
7247 EMSG2(_("E462: Could not prepare for reloading \"%s\""),
7248 buf->b_fname);
7249 saved = FAIL;
7250 }
7251 }
7252
7253 if (saved == OK)
7254 {
7255 curbuf->b_flags |= BF_CHECK_RO; /* check for RO again */
7256#ifdef FEAT_AUTOCMD
7257 keep_filetype = TRUE; /* don't detect 'filetype' */
7258#endif
7259 if (readfile(buf->b_ffname, buf->b_fname, (linenr_T)0,
7260 (linenr_T)0,
Bram Moolenaare13b9af2017-01-13 22:01:02 +01007261 (linenr_T)MAXLNUM, &ea, flags) != OK)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007262 {
7263#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
7264 if (!aborting())
7265#endif
7266 EMSG2(_("E321: Could not reload \"%s\""), buf->b_fname);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007267 if (savebuf != NULL && bufref_valid(&bufref) && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007268 {
7269 /* Put the text back from the save buffer. First
7270 * delete any lines that readfile() added. */
Bram Moolenaarb5aedf32017-03-12 18:23:53 +01007271 while (!BUFEMPTY())
Bram Moolenaar8424a622006-04-19 21:23:36 +00007272 if (ml_delete(buf->b_ml.ml_line_count, FALSE) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007273 break;
7274 (void)move_lines(savebuf, buf);
7275 }
7276 }
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007277 else if (buf == curbuf) /* "buf" still valid */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007278 {
7279 /* Mark the buffer as unmodified and free undo info. */
7280 unchanged(buf, TRUE);
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007281 if ((flags & READ_KEEP_UNDO) == 0)
7282 {
7283 u_blockfree(buf);
7284 u_clearall(buf);
7285 }
7286 else
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007287 {
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007288 /* Mark all undo states as changed. */
7289 u_unchanged(curbuf);
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007290 }
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007291 }
7292 }
7293 vim_free(ea.cmd);
7294
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007295 if (savebuf != NULL && bufref_valid(&bufref))
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007296 wipe_buffer(savebuf, FALSE);
7297
7298#ifdef FEAT_DIFF
7299 /* Invalidate diff info if necessary. */
Bram Moolenaar8424a622006-04-19 21:23:36 +00007300 diff_invalidate(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007301#endif
7302
7303 /* Restore the topline and cursor position and check it (lines may
7304 * have been removed). */
7305 if (old_topline > curbuf->b_ml.ml_line_count)
7306 curwin->w_topline = curbuf->b_ml.ml_line_count;
7307 else
7308 curwin->w_topline = old_topline;
7309 curwin->w_cursor = old_cursor;
7310 check_cursor();
7311 update_topline();
7312#ifdef FEAT_AUTOCMD
7313 keep_filetype = FALSE;
7314#endif
7315#ifdef FEAT_FOLDING
7316 {
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007317 win_T *wp;
7318 tabpage_T *tp;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007319
7320 /* Update folds unless they are defined manually. */
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007321 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007322 if (wp->w_buffer == curwin->w_buffer
7323 && !foldmethodIsManual(wp))
7324 foldUpdateAll(wp);
7325 }
7326#endif
7327 /* If the mode didn't change and 'readonly' was set, keep the old
7328 * value; the user probably used the ":view" command. But don't
7329 * reset it, might have had a read error. */
7330 if (orig_mode == curbuf->b_orig_mode)
7331 curbuf->b_p_ro |= old_ro;
Bram Moolenaar52f85b72013-01-30 14:13:56 +01007332
7333 /* Modelines must override settings done by autocommands. */
7334 do_modelines(0);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007335 }
7336
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007337 /* restore curwin/curbuf and a few other things */
7338 aucmd_restbuf(&aco);
7339 /* Careful: autocommands may have made "buf" invalid! */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007340}
7341
Bram Moolenaar071d4272004-06-13 20:20:40 +00007342 void
Bram Moolenaar8767f522016-07-01 17:17:39 +02007343buf_store_time(buf_T *buf, stat_T *st, char_u *fname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007344{
7345 buf->b_mtime = (long)st->st_mtime;
Bram Moolenaar914703b2010-05-31 21:59:46 +02007346 buf->b_orig_size = st->st_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007347#ifdef HAVE_ST_MODE
7348 buf->b_orig_mode = (int)st->st_mode;
7349#else
7350 buf->b_orig_mode = mch_getperm(fname);
7351#endif
7352}
7353
7354/*
7355 * Adjust the line with missing eol, used for the next write.
7356 * Used for do_filter(), when the input lines for the filter are deleted.
7357 */
7358 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007359write_lnum_adjust(linenr_T offset)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007360{
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01007361 if (curbuf->b_no_eol_lnum != 0) /* only if there is a missing eol */
7362 curbuf->b_no_eol_lnum += offset;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007363}
7364
Bram Moolenaarda440d22016-01-16 21:27:23 +01007365#if defined(TEMPDIRNAMES) || defined(FEAT_EVAL) || defined(PROTO)
7366/*
7367 * Delete "name" and everything in it, recursively.
7368 * return 0 for succes, -1 if some file was not deleted.
7369 */
7370 int
7371delete_recursive(char_u *name)
7372{
7373 int result = 0;
7374 char_u **files;
7375 int file_count;
7376 int i;
7377 char_u *exp;
7378
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007379 /* A symbolic link to a directory itself is deleted, not the directory it
7380 * points to. */
7381 if (
Bram Moolenaar203258c2016-01-17 22:15:16 +01007382# if defined(UNIX) || defined(WIN32)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007383 mch_isrealdir(name)
Bram Moolenaar203258c2016-01-17 22:15:16 +01007384# else
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007385 mch_isdir(name)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007386# endif
7387 )
Bram Moolenaarda440d22016-01-16 21:27:23 +01007388 {
7389 vim_snprintf((char *)NameBuff, MAXPATHL, "%s/*", name);
7390 exp = vim_strsave(NameBuff);
7391 if (exp == NULL)
7392 return -1;
7393 if (gen_expand_wildcards(1, &exp, &file_count, &files,
Bram Moolenaar336bd622016-01-17 18:23:58 +01007394 EW_DIR|EW_FILE|EW_SILENT|EW_ALLLINKS|EW_DODOT|EW_EMPTYOK) == OK)
Bram Moolenaarda440d22016-01-16 21:27:23 +01007395 {
7396 for (i = 0; i < file_count; ++i)
7397 if (delete_recursive(files[i]) != 0)
7398 result = -1;
7399 FreeWild(file_count, files);
7400 }
7401 else
7402 result = -1;
7403 vim_free(exp);
7404 (void)mch_rmdir(name);
7405 }
7406 else
7407 result = mch_remove(name) == 0 ? 0 : -1;
7408
7409 return result;
7410}
7411#endif
7412
Bram Moolenaar071d4272004-06-13 20:20:40 +00007413#if defined(TEMPDIRNAMES) || defined(PROTO)
7414static long temp_count = 0; /* Temp filename counter. */
7415
7416/*
7417 * Delete the temp directory and all files it contains.
7418 */
7419 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007420vim_deltempdir(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007421{
Bram Moolenaar071d4272004-06-13 20:20:40 +00007422 if (vim_tempdir != NULL)
7423 {
Bram Moolenaarda440d22016-01-16 21:27:23 +01007424 /* remove the trailing path separator */
7425 gettail(vim_tempdir)[-1] = NUL;
7426 delete_recursive(vim_tempdir);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007427 vim_free(vim_tempdir);
7428 vim_tempdir = NULL;
7429 }
7430}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007431
7432/*
Bram Moolenaareaf03392009-11-17 11:08:52 +00007433 * Directory "tempdir" was created. Expand this name to a full path and put
7434 * it in "vim_tempdir". This avoids that using ":cd" would confuse us.
7435 * "tempdir" must be no longer than MAXPATHL.
7436 */
7437 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007438vim_settempdir(char_u *tempdir)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007439{
7440 char_u *buf;
7441
7442 buf = alloc((unsigned)MAXPATHL + 2);
7443 if (buf != NULL)
7444 {
7445 if (vim_FullName(tempdir, buf, MAXPATHL, FALSE) == FAIL)
7446 STRCPY(buf, tempdir);
Bram Moolenaara06ecab2016-07-16 14:47:36 +02007447 add_pathsep(buf);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007448 vim_tempdir = vim_strsave(buf);
7449 vim_free(buf);
7450 }
7451}
Bram Moolenaar4592dee2009-11-18 19:11:58 +00007452#endif
Bram Moolenaareaf03392009-11-17 11:08:52 +00007453
7454/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007455 * vim_tempname(): Return a unique name that can be used for a temp file.
7456 *
Bram Moolenaar76ae22f2016-06-13 20:00:29 +02007457 * The temp file is NOT guaranteed to be created. If "keep" is FALSE it is
7458 * guaranteed to NOT be created.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007459 *
7460 * The returned pointer is to allocated memory.
7461 * The returned pointer is NULL if no valid name was found.
7462 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007463 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007464vim_tempname(
7465 int extra_char UNUSED, /* char to use in the name instead of '?' */
7466 int keep UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007467{
7468#ifdef USE_TMPNAM
7469 char_u itmp[L_tmpnam]; /* use tmpnam() */
7470#else
7471 char_u itmp[TEMPNAMELEN];
7472#endif
7473
7474#ifdef TEMPDIRNAMES
7475 static char *(tempdirs[]) = {TEMPDIRNAMES};
7476 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007477# ifndef EEXIST
Bram Moolenaar8767f522016-07-01 17:17:39 +02007478 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007479# endif
7480
7481 /*
7482 * This will create a directory for private use by this instance of Vim.
7483 * This is done once, and the same directory is used for all temp files.
7484 * This method avoids security problems because of symlink attacks et al.
7485 * It's also a bit faster, because we only need to check for an existing
7486 * file when creating the directory and not for each temp file.
7487 */
7488 if (vim_tempdir == NULL)
7489 {
7490 /*
7491 * Try the entries in TEMPDIRNAMES to create the temp directory.
7492 */
Bram Moolenaar78a15312009-05-15 19:33:18 +00007493 for (i = 0; i < (int)(sizeof(tempdirs) / sizeof(char *)); ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007494 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007495# ifndef HAVE_MKDTEMP
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007496 size_t itmplen;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007497 long nr;
7498 long off;
7499# endif
7500
Bram Moolenaare1a61992015-12-03 21:02:27 +01007501 /* Expand $TMP, leave room for "/v1100000/999999999".
7502 * Skip the directory check if the expansion fails. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007503 expand_env((char_u *)tempdirs[i], itmp, TEMPNAMELEN - 20);
Bram Moolenaare1a61992015-12-03 21:02:27 +01007504 if (itmp[0] != '$' && mch_isdir(itmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007505 {
Bram Moolenaare1a61992015-12-03 21:02:27 +01007506 /* directory exists */
Bram Moolenaara06ecab2016-07-16 14:47:36 +02007507 add_pathsep(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007508
Bram Moolenaareaf03392009-11-17 11:08:52 +00007509# ifdef HAVE_MKDTEMP
Bram Moolenaar35d88f42016-06-04 14:52:00 +02007510 {
7511# if defined(UNIX) || defined(VMS)
7512 /* Make sure the umask doesn't remove the executable bit.
7513 * "repl" has been reported to use "177". */
7514 mode_t umask_save = umask(077);
7515# endif
7516 /* Leave room for filename */
7517 STRCAT(itmp, "vXXXXXX");
7518 if (mkdtemp((char *)itmp) != NULL)
7519 vim_settempdir(itmp);
7520# if defined(UNIX) || defined(VMS)
7521 (void)umask(umask_save);
7522# endif
7523 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007524# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007525 /* Get an arbitrary number of up to 6 digits. When it's
7526 * unlikely that it already exists it will be faster,
7527 * otherwise it doesn't matter. The use of mkdir() avoids any
7528 * security problems because of the predictable number. */
7529 nr = (mch_get_pid() + (long)time(NULL)) % 1000000L;
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007530 itmplen = STRLEN(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007531
7532 /* Try up to 10000 different values until we find a name that
7533 * doesn't exist. */
7534 for (off = 0; off < 10000L; ++off)
7535 {
7536 int r;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007537# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007538 mode_t umask_save;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007539# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007540
Bram Moolenaareaf03392009-11-17 11:08:52 +00007541 sprintf((char *)itmp + itmplen, "v%ld", nr + off);
7542# ifndef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007543 /* If mkdir() does not set errno to EEXIST, check for
7544 * existing file here. There is a race condition then,
7545 * although it's fail-safe. */
7546 if (mch_stat((char *)itmp, &st) >= 0)
7547 continue;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007548# endif
7549# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007550 /* Make sure the umask doesn't remove the executable bit.
7551 * "repl" has been reported to use "177". */
7552 umask_save = umask(077);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007553# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007554 r = vim_mkdir(itmp, 0700);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007555# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007556 (void)umask(umask_save);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007557# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007558 if (r == 0)
7559 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007560 vim_settempdir(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007561 break;
7562 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007563# ifdef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007564 /* If the mkdir() didn't fail because the file/dir exists,
7565 * we probably can't create any dir here, try another
7566 * place. */
7567 if (errno != EEXIST)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007568# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007569 break;
7570 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007571# endif /* HAVE_MKDTEMP */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007572 if (vim_tempdir != NULL)
7573 break;
7574 }
7575 }
7576 }
7577
7578 if (vim_tempdir != NULL)
7579 {
7580 /* There is no need to check if the file exists, because we own the
7581 * directory and nobody else creates a file in it. */
7582 sprintf((char *)itmp, "%s%ld", vim_tempdir, temp_count++);
7583 return vim_strsave(itmp);
7584 }
7585
7586 return NULL;
7587
7588#else /* TEMPDIRNAMES */
7589
7590# ifdef WIN3264
7591 char szTempFile[_MAX_PATH + 1];
7592 char buf4[4];
7593 char_u *retval;
7594 char_u *p;
7595
7596 STRCPY(itmp, "");
7597 if (GetTempPath(_MAX_PATH, szTempFile) == 0)
Bram Moolenaarb1891912011-02-09 14:47:03 +01007598 {
7599 szTempFile[0] = '.'; /* GetTempPath() failed, use current dir */
7600 szTempFile[1] = NUL;
7601 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007602 strcpy(buf4, "VIM");
7603 buf4[2] = extra_char; /* make it "VIa", "VIb", etc. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007604 if (GetTempFileName(szTempFile, buf4, 0, (LPSTR)itmp) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007605 return NULL;
Bram Moolenaare5c421c2015-03-31 13:33:08 +02007606 if (!keep)
7607 /* GetTempFileName() will create the file, we don't want that */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007608 (void)DeleteFile((LPSTR)itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007609
7610 /* Backslashes in a temp file name cause problems when filtering with
7611 * "sh". NOTE: This also checks 'shellcmdflag' to help those people who
7612 * didn't set 'shellslash'. */
7613 retval = vim_strsave(itmp);
7614 if (*p_shcf == '-' || p_ssl)
7615 for (p = retval; *p; ++p)
7616 if (*p == '\\')
7617 *p = '/';
7618 return retval;
7619
7620# else /* WIN3264 */
7621
7622# ifdef USE_TMPNAM
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007623 char_u *p;
7624
Bram Moolenaar071d4272004-06-13 20:20:40 +00007625 /* tmpnam() will make its own name */
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007626 p = tmpnam((char *)itmp);
7627 if (p == NULL || *p == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007628 return NULL;
7629# else
7630 char_u *p;
7631
7632# ifdef VMS_TEMPNAM
7633 /* mktemp() is not working on VMS. It seems to be
7634 * a do-nothing function. Therefore we use tempnam().
7635 */
7636 sprintf((char *)itmp, "VIM%c", extra_char);
7637 p = (char_u *)tempnam("tmp:", (char *)itmp);
7638 if (p != NULL)
7639 {
Bram Moolenaar206f0112014-03-12 16:51:55 +01007640 /* VMS will use '.LIS' if we don't explicitly specify an extension,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007641 * and VIM will then be unable to find the file later */
7642 STRCPY(itmp, p);
7643 STRCAT(itmp, ".txt");
7644 free(p);
7645 }
7646 else
7647 return NULL;
7648# else
7649 STRCPY(itmp, TEMPNAME);
7650 if ((p = vim_strchr(itmp, '?')) != NULL)
7651 *p = extra_char;
7652 if (mktemp((char *)itmp) == NULL)
7653 return NULL;
7654# endif
7655# endif
7656
7657 return vim_strsave(itmp);
7658# endif /* WIN3264 */
7659#endif /* TEMPDIRNAMES */
7660}
7661
7662#if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
7663/*
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02007664 * Convert all backslashes in fname to forward slashes in-place, unless when
7665 * it looks like a URL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007666 */
7667 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007668forward_slash(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007669{
7670 char_u *p;
7671
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02007672 if (path_with_url(fname))
7673 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007674 for (p = fname; *p != NUL; ++p)
7675# ifdef FEAT_MBYTE
7676 /* The Big5 encoding can have '\' in the trail byte. */
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00007677 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007678 ++p;
7679 else
7680# endif
7681 if (*p == '\\')
7682 *p = '/';
7683}
7684#endif
7685
7686
7687/*
7688 * Code for automatic commands.
7689 *
7690 * Only included when "FEAT_AUTOCMD" has been defined.
7691 */
7692
7693#if defined(FEAT_AUTOCMD) || defined(PROTO)
7694
7695/*
7696 * The autocommands are stored in a list for each event.
7697 * Autocommands for the same pattern, that are consecutive, are joined
7698 * together, to avoid having to match the pattern too often.
7699 * The result is an array of Autopat lists, which point to AutoCmd lists:
7700 *
Bram Moolenaar462455e2017-11-10 21:53:11 +01007701 * last_autopat[0] -----------------------------+
7702 * V
Bram Moolenaar071d4272004-06-13 20:20:40 +00007703 * first_autopat[0] --> Autopat.next --> Autopat.next --> NULL
7704 * Autopat.cmds Autopat.cmds
7705 * | |
7706 * V V
7707 * AutoCmd.next AutoCmd.next
7708 * | |
7709 * V V
7710 * AutoCmd.next NULL
7711 * |
7712 * V
7713 * NULL
7714 *
Bram Moolenaar462455e2017-11-10 21:53:11 +01007715 * last_autopat[1] --------+
7716 * V
Bram Moolenaar071d4272004-06-13 20:20:40 +00007717 * first_autopat[1] --> Autopat.next --> NULL
7718 * Autopat.cmds
7719 * |
7720 * V
7721 * AutoCmd.next
7722 * |
7723 * V
7724 * NULL
7725 * etc.
7726 *
7727 * The order of AutoCmds is important, this is the order in which they were
7728 * defined and will have to be executed.
7729 */
7730typedef struct AutoCmd
7731{
7732 char_u *cmd; /* The command to be executed (NULL
7733 when command has been removed) */
7734 char nested; /* If autocommands nest here */
7735 char last; /* last command in list */
7736#ifdef FEAT_EVAL
7737 scid_T scriptID; /* script ID where defined */
7738#endif
7739 struct AutoCmd *next; /* Next AutoCmd in list */
7740} AutoCmd;
7741
7742typedef struct AutoPat
7743{
Bram Moolenaar462455e2017-11-10 21:53:11 +01007744 struct AutoPat *next; /* next AutoPat in AutoPat list; MUST
7745 * be the first entry */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007746 char_u *pat; /* pattern as typed (NULL when pattern
7747 has been removed) */
Bram Moolenaar748bf032005-02-02 23:04:36 +00007748 regprog_T *reg_prog; /* compiled regprog for pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007749 AutoCmd *cmds; /* list of commands to do */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007750 int group; /* group ID */
7751 int patlen; /* strlen() of pat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007752 int buflocal_nr; /* !=0 for buffer-local AutoPat */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007753 char allow_dirs; /* Pattern may match whole path */
7754 char last; /* last pattern for apply_autocmds() */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007755} AutoPat;
7756
7757static struct event_name
7758{
7759 char *name; /* event name */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007760 event_T event; /* event number */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007761} event_names[] =
7762{
7763 {"BufAdd", EVENT_BUFADD},
7764 {"BufCreate", EVENT_BUFADD},
7765 {"BufDelete", EVENT_BUFDELETE},
7766 {"BufEnter", EVENT_BUFENTER},
7767 {"BufFilePost", EVENT_BUFFILEPOST},
7768 {"BufFilePre", EVENT_BUFFILEPRE},
7769 {"BufHidden", EVENT_BUFHIDDEN},
7770 {"BufLeave", EVENT_BUFLEAVE},
7771 {"BufNew", EVENT_BUFNEW},
7772 {"BufNewFile", EVENT_BUFNEWFILE},
7773 {"BufRead", EVENT_BUFREADPOST},
7774 {"BufReadCmd", EVENT_BUFREADCMD},
7775 {"BufReadPost", EVENT_BUFREADPOST},
7776 {"BufReadPre", EVENT_BUFREADPRE},
7777 {"BufUnload", EVENT_BUFUNLOAD},
7778 {"BufWinEnter", EVENT_BUFWINENTER},
7779 {"BufWinLeave", EVENT_BUFWINLEAVE},
7780 {"BufWipeout", EVENT_BUFWIPEOUT},
7781 {"BufWrite", EVENT_BUFWRITEPRE},
7782 {"BufWritePost", EVENT_BUFWRITEPOST},
7783 {"BufWritePre", EVENT_BUFWRITEPRE},
7784 {"BufWriteCmd", EVENT_BUFWRITECMD},
Bram Moolenaarfafcf0d2017-10-19 18:35:51 +02007785 {"CmdlineEnter", EVENT_CMDLINEENTER},
7786 {"CmdlineLeave", EVENT_CMDLINELEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007787 {"CmdwinEnter", EVENT_CMDWINENTER},
7788 {"CmdwinLeave", EVENT_CMDWINLEAVE},
Bram Moolenaard5005162014-08-22 23:05:54 +02007789 {"CmdUndefined", EVENT_CMDUNDEFINED},
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007790 {"ColorScheme", EVENT_COLORSCHEME},
Bram Moolenaarcfa3cae2012-07-10 17:14:56 +02007791 {"CompleteDone", EVENT_COMPLETEDONE},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007792 {"CursorHold", EVENT_CURSORHOLD},
7793 {"CursorHoldI", EVENT_CURSORHOLDI},
7794 {"CursorMoved", EVENT_CURSORMOVED},
7795 {"CursorMovedI", EVENT_CURSORMOVEDI},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007796 {"EncodingChanged", EVENT_ENCODINGCHANGED},
7797 {"FileEncoding", EVENT_ENCODINGCHANGED},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007798 {"FileAppendPost", EVENT_FILEAPPENDPOST},
7799 {"FileAppendPre", EVENT_FILEAPPENDPRE},
7800 {"FileAppendCmd", EVENT_FILEAPPENDCMD},
7801 {"FileChangedShell",EVENT_FILECHANGEDSHELL},
Bram Moolenaar56718732006-03-15 22:53:57 +00007802 {"FileChangedShellPost",EVENT_FILECHANGEDSHELLPOST},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007803 {"FileChangedRO", EVENT_FILECHANGEDRO},
7804 {"FileReadPost", EVENT_FILEREADPOST},
7805 {"FileReadPre", EVENT_FILEREADPRE},
7806 {"FileReadCmd", EVENT_FILEREADCMD},
7807 {"FileType", EVENT_FILETYPE},
7808 {"FileWritePost", EVENT_FILEWRITEPOST},
7809 {"FileWritePre", EVENT_FILEWRITEPRE},
7810 {"FileWriteCmd", EVENT_FILEWRITECMD},
7811 {"FilterReadPost", EVENT_FILTERREADPOST},
7812 {"FilterReadPre", EVENT_FILTERREADPRE},
7813 {"FilterWritePost", EVENT_FILTERWRITEPOST},
7814 {"FilterWritePre", EVENT_FILTERWRITEPRE},
7815 {"FocusGained", EVENT_FOCUSGAINED},
7816 {"FocusLost", EVENT_FOCUSLOST},
7817 {"FuncUndefined", EVENT_FUNCUNDEFINED},
7818 {"GUIEnter", EVENT_GUIENTER},
Bram Moolenaar265e5072006-08-29 16:13:22 +00007819 {"GUIFailed", EVENT_GUIFAILED},
Bram Moolenaar843ee412004-06-30 16:16:41 +00007820 {"InsertChange", EVENT_INSERTCHANGE},
7821 {"InsertEnter", EVENT_INSERTENTER},
7822 {"InsertLeave", EVENT_INSERTLEAVE},
Bram Moolenaare659c952011-05-19 17:25:41 +02007823 {"InsertCharPre", EVENT_INSERTCHARPRE},
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00007824 {"MenuPopup", EVENT_MENUPOPUP},
Bram Moolenaar53744302015-07-17 17:38:22 +02007825 {"OptionSet", EVENT_OPTIONSET},
Bram Moolenaar7c626922005-02-07 22:01:03 +00007826 {"QuickFixCmdPost", EVENT_QUICKFIXCMDPOST},
7827 {"QuickFixCmdPre", EVENT_QUICKFIXCMDPRE},
Bram Moolenaar3b53dfb2012-06-06 18:03:07 +02007828 {"QuitPre", EVENT_QUITPRE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007829 {"RemoteReply", EVENT_REMOTEREPLY},
Bram Moolenaar9372a112005-12-06 19:59:18 +00007830 {"SessionLoadPost", EVENT_SESSIONLOADPOST},
Bram Moolenaar5c4bab02006-03-10 21:37:46 +00007831 {"ShellCmdPost", EVENT_SHELLCMDPOST},
7832 {"ShellFilterPost", EVENT_SHELLFILTERPOST},
Bram Moolenaara2031822006-03-07 22:29:51 +00007833 {"SourcePre", EVENT_SOURCEPRE},
Bram Moolenaar8dd1aa52007-01-16 20:33:19 +00007834 {"SourceCmd", EVENT_SOURCECMD},
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00007835 {"SpellFileMissing",EVENT_SPELLFILEMISSING},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007836 {"StdinReadPost", EVENT_STDINREADPOST},
7837 {"StdinReadPre", EVENT_STDINREADPRE},
Bram Moolenaarb815dac2005-12-07 20:59:24 +00007838 {"SwapExists", EVENT_SWAPEXISTS},
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00007839 {"Syntax", EVENT_SYNTAX},
Bram Moolenaarc917da42016-07-19 22:31:36 +02007840 {"TabNew", EVENT_TABNEW},
Bram Moolenaar12c11d52016-07-19 23:13:03 +02007841 {"TabClosed", EVENT_TABCLOSED},
Bram Moolenaar70836c82006-02-20 21:28:49 +00007842 {"TabEnter", EVENT_TABENTER},
7843 {"TabLeave", EVENT_TABLEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007844 {"TermChanged", EVENT_TERMCHANGED},
7845 {"TermResponse", EVENT_TERMRESPONSE},
Bram Moolenaar186628f2013-03-19 13:33:23 +01007846 {"TextChanged", EVENT_TEXTCHANGED},
7847 {"TextChangedI", EVENT_TEXTCHANGEDI},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007848 {"User", EVENT_USER},
7849 {"VimEnter", EVENT_VIMENTER},
7850 {"VimLeave", EVENT_VIMLEAVE},
7851 {"VimLeavePre", EVENT_VIMLEAVEPRE},
Bram Moolenaarc917da42016-07-19 22:31:36 +02007852 {"WinNew", EVENT_WINNEW},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007853 {"WinEnter", EVENT_WINENTER},
7854 {"WinLeave", EVENT_WINLEAVE},
Bram Moolenaar56718732006-03-15 22:53:57 +00007855 {"VimResized", EVENT_VIMRESIZED},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007856 {NULL, (event_T)0}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007857};
7858
7859static AutoPat *first_autopat[NUM_EVENTS] =
7860{
7861 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7862 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7863 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7864 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00007865 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaar53744302015-07-17 17:38:22 +02007866 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007867};
7868
Bram Moolenaar462455e2017-11-10 21:53:11 +01007869static AutoPat *last_autopat[NUM_EVENTS] =
7870{
7871 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7872 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7873 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7874 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7875 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7876 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
7877};
7878
Bram Moolenaar071d4272004-06-13 20:20:40 +00007879/*
7880 * struct used to keep status while executing autocommands for an event.
7881 */
7882typedef struct AutoPatCmd
7883{
7884 AutoPat *curpat; /* next AutoPat to examine */
7885 AutoCmd *nextcmd; /* next AutoCmd to execute */
7886 int group; /* group being used */
7887 char_u *fname; /* fname to match with */
7888 char_u *sfname; /* sfname to match with */
7889 char_u *tail; /* tail of fname */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007890 event_T event; /* current event */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007891 int arg_bufnr; /* initially equal to <abuf>, set to zero when
7892 buf is deleted */
7893 struct AutoPatCmd *next; /* chain of active apc-s for auto-invalidation*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00007894} AutoPatCmd;
7895
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007896static AutoPatCmd *active_apc_list = NULL; /* stack of active autocommands */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007897
Bram Moolenaar071d4272004-06-13 20:20:40 +00007898/*
7899 * augroups stores a list of autocmd group names.
7900 */
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007901static garray_T augroups = {0, 0, sizeof(char_u *), 10, NULL};
Bram Moolenaar071d4272004-06-13 20:20:40 +00007902#define AUGROUP_NAME(i) (((char_u **)augroups.ga_data)[i])
Bram Moolenaarb62cc362016-09-03 16:43:53 +02007903/* use get_deleted_augroup() to get this */
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02007904static char_u *deleted_augroup = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007905
7906/*
7907 * The ID of the current group. Group 0 is the default one.
7908 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007909static int current_augroup = AUGROUP_DEFAULT;
7910
7911static int au_need_clean = FALSE; /* need to delete marked patterns */
7912
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007913static void show_autocmd(AutoPat *ap, event_T event);
7914static void au_remove_pat(AutoPat *ap);
7915static void au_remove_cmds(AutoPat *ap);
7916static void au_cleanup(void);
7917static int au_new_group(char_u *name);
7918static void au_del_group(char_u *name);
7919static event_T event_name2nr(char_u *start, char_u **end);
7920static char_u *event_nr2name(event_T event);
7921static char_u *find_end_event(char_u *arg, int have_group);
7922static int event_ignored(event_T event);
7923static int au_get_grouparg(char_u **argp);
7924static int do_autocmd_event(event_T event, char_u *pat, int nested, char_u *cmd, int forceit, int group);
7925static int apply_autocmds_group(event_T event, char_u *fname, char_u *fname_io, int force, int group, buf_T *buf, exarg_T *eap);
7926static void auto_next_pat(AutoPatCmd *apc, int stop_at_last);
Bram Moolenaardffa5b82014-11-19 16:38:07 +01007927#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN)
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007928static 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 +01007929#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007930
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007931
Bram Moolenaar754b5602006-02-09 23:53:20 +00007932static event_T last_event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007933static int last_group;
Bram Moolenaar78ab3312007-09-29 12:16:41 +00007934static int autocmd_blocked = 0; /* block all autocmds */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007935
Bram Moolenaarb62cc362016-09-03 16:43:53 +02007936 static char_u *
7937get_deleted_augroup(void)
7938{
7939 if (deleted_augroup == NULL)
7940 deleted_augroup = (char_u *)_("--Deleted--");
7941 return deleted_augroup;
7942}
7943
Bram Moolenaar071d4272004-06-13 20:20:40 +00007944/*
7945 * Show the autocommands for one AutoPat.
7946 */
7947 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007948show_autocmd(AutoPat *ap, event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007949{
7950 AutoCmd *ac;
7951
7952 /* Check for "got_int" (here and at various places below), which is set
7953 * when "q" has been hit for the "--more--" prompt */
7954 if (got_int)
7955 return;
7956 if (ap->pat == NULL) /* pattern has been removed */
7957 return;
7958
7959 msg_putchar('\n');
7960 if (got_int)
7961 return;
7962 if (event != last_event || ap->group != last_group)
7963 {
7964 if (ap->group != AUGROUP_DEFAULT)
7965 {
7966 if (AUGROUP_NAME(ap->group) == NULL)
Bram Moolenaar8820b482017-03-16 17:23:31 +01007967 msg_puts_attr(get_deleted_augroup(), HL_ATTR(HLF_E));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007968 else
Bram Moolenaar8820b482017-03-16 17:23:31 +01007969 msg_puts_attr(AUGROUP_NAME(ap->group), HL_ATTR(HLF_T));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007970 msg_puts((char_u *)" ");
7971 }
Bram Moolenaar8820b482017-03-16 17:23:31 +01007972 msg_puts_attr(event_nr2name(event), HL_ATTR(HLF_T));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007973 last_event = event;
7974 last_group = ap->group;
7975 msg_putchar('\n');
7976 if (got_int)
7977 return;
7978 }
7979 msg_col = 4;
7980 msg_outtrans(ap->pat);
7981
7982 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7983 {
7984 if (ac->cmd != NULL) /* skip removed commands */
7985 {
7986 if (msg_col >= 14)
7987 msg_putchar('\n');
7988 msg_col = 14;
7989 if (got_int)
7990 return;
7991 msg_outtrans(ac->cmd);
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00007992#ifdef FEAT_EVAL
7993 if (p_verbose > 0)
7994 last_set_msg(ac->scriptID);
7995#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007996 if (got_int)
7997 return;
7998 if (ac->next != NULL)
7999 {
8000 msg_putchar('\n');
8001 if (got_int)
8002 return;
8003 }
8004 }
8005 }
8006}
8007
8008/*
8009 * Mark an autocommand pattern for deletion.
8010 */
8011 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008012au_remove_pat(AutoPat *ap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008013{
8014 vim_free(ap->pat);
8015 ap->pat = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008016 ap->buflocal_nr = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008017 au_need_clean = TRUE;
8018}
8019
8020/*
8021 * Mark all commands for a pattern for deletion.
8022 */
8023 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008024au_remove_cmds(AutoPat *ap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008025{
8026 AutoCmd *ac;
8027
8028 for (ac = ap->cmds; ac != NULL; ac = ac->next)
8029 {
8030 vim_free(ac->cmd);
8031 ac->cmd = NULL;
8032 }
8033 au_need_clean = TRUE;
8034}
8035
8036/*
8037 * Cleanup autocommands and patterns that have been deleted.
8038 * This is only done when not executing autocommands.
8039 */
8040 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008041au_cleanup(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008042{
8043 AutoPat *ap, **prev_ap;
8044 AutoCmd *ac, **prev_ac;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008045 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008046
8047 if (autocmd_busy || !au_need_clean)
8048 return;
8049
8050 /* loop over all events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008051 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8052 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008053 {
8054 /* loop over all autocommand patterns */
8055 prev_ap = &(first_autopat[(int)event]);
8056 for (ap = *prev_ap; ap != NULL; ap = *prev_ap)
8057 {
8058 /* loop over all commands for this pattern */
8059 prev_ac = &(ap->cmds);
8060 for (ac = *prev_ac; ac != NULL; ac = *prev_ac)
8061 {
8062 /* remove the command if the pattern is to be deleted or when
8063 * the command has been marked for deletion */
8064 if (ap->pat == NULL || ac->cmd == NULL)
8065 {
8066 *prev_ac = ac->next;
8067 vim_free(ac->cmd);
8068 vim_free(ac);
8069 }
8070 else
8071 prev_ac = &(ac->next);
8072 }
8073
8074 /* remove the pattern if it has been marked for deletion */
8075 if (ap->pat == NULL)
8076 {
Bram Moolenaar462455e2017-11-10 21:53:11 +01008077 if (ap->next == NULL)
8078 {
8079 if (prev_ap == &(first_autopat[(int)event]))
8080 last_autopat[(int)event] = NULL;
8081 else
8082 /* this depends on the "next" field being the first in
8083 * the struct */
8084 last_autopat[(int)event] = (AutoPat *)prev_ap;
8085 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008086 *prev_ap = ap->next;
Bram Moolenaar473de612013-06-08 18:19:48 +02008087 vim_regfree(ap->reg_prog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008088 vim_free(ap);
8089 }
8090 else
8091 prev_ap = &(ap->next);
8092 }
8093 }
8094
8095 au_need_clean = FALSE;
8096}
8097
8098/*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008099 * Called when buffer is freed, to remove/invalidate related buffer-local
8100 * autocmds.
8101 */
8102 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008103aubuflocal_remove(buf_T *buf)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008104{
8105 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008106 event_T event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008107 AutoPatCmd *apc;
8108
8109 /* invalidate currently executing autocommands */
8110 for (apc = active_apc_list; apc; apc = apc->next)
8111 if (buf->b_fnum == apc->arg_bufnr)
8112 apc->arg_bufnr = 0;
8113
8114 /* invalidate buflocals looping through events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008115 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8116 event = (event_T)((int)event + 1))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008117 /* loop over all autocommand patterns */
8118 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8119 if (ap->buflocal_nr == buf->b_fnum)
8120 {
8121 au_remove_pat(ap);
8122 if (p_verbose >= 6)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00008123 {
8124 verbose_enter();
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008125 smsg((char_u *)
8126 _("auto-removing autocommand: %s <buffer=%d>"),
8127 event_nr2name(event), buf->b_fnum);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00008128 verbose_leave();
8129 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008130 }
8131 au_cleanup();
8132}
8133
8134/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008135 * Add an autocmd group name.
8136 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
8137 */
8138 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008139au_new_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008140{
8141 int i;
8142
8143 i = au_find_group(name);
8144 if (i == AUGROUP_ERROR) /* the group doesn't exist yet, add it */
8145 {
8146 /* First try using a free entry. */
8147 for (i = 0; i < augroups.ga_len; ++i)
8148 if (AUGROUP_NAME(i) == NULL)
8149 break;
8150 if (i == augroups.ga_len && ga_grow(&augroups, 1) == FAIL)
8151 return AUGROUP_ERROR;
8152
8153 AUGROUP_NAME(i) = vim_strsave(name);
8154 if (AUGROUP_NAME(i) == NULL)
8155 return AUGROUP_ERROR;
8156 if (i == augroups.ga_len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008157 ++augroups.ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008158 }
8159
8160 return i;
8161}
8162
8163 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008164au_del_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008165{
8166 int i;
8167
8168 i = au_find_group(name);
8169 if (i == AUGROUP_ERROR) /* the group doesn't exist */
8170 EMSG2(_("E367: No such group: \"%s\""), name);
Bram Moolenaarde653f02016-09-03 16:59:06 +02008171 else if (i == current_augroup)
8172 EMSG(_("E936: Cannot delete the current group"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008173 else
8174 {
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008175 event_T event;
8176 AutoPat *ap;
8177 int in_use = FALSE;
8178
8179 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8180 event = (event_T)((int)event + 1))
8181 {
8182 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
Bram Moolenaar5c809082016-09-01 16:21:48 +02008183 if (ap->group == i && ap->pat != NULL)
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008184 {
8185 give_warning((char_u *)_("W19: Deleting augroup that is still in use"), TRUE);
8186 in_use = TRUE;
8187 event = NUM_EVENTS;
8188 break;
8189 }
8190 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008191 vim_free(AUGROUP_NAME(i));
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008192 if (in_use)
8193 {
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008194 AUGROUP_NAME(i) = get_deleted_augroup();
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008195 }
8196 else
8197 AUGROUP_NAME(i) = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008198 }
8199}
8200
8201/*
8202 * Find the ID of an autocmd group name.
8203 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
8204 */
8205 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008206au_find_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008207{
8208 int i;
8209
8210 for (i = 0; i < augroups.ga_len; ++i)
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008211 if (AUGROUP_NAME(i) != NULL && AUGROUP_NAME(i) != get_deleted_augroup()
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008212 && STRCMP(AUGROUP_NAME(i), name) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008213 return i;
8214 return AUGROUP_ERROR;
8215}
8216
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008217/*
8218 * Return TRUE if augroup "name" exists.
8219 */
8220 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008221au_has_group(char_u *name)
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008222{
8223 return au_find_group(name) != AUGROUP_ERROR;
8224}
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008225
Bram Moolenaar071d4272004-06-13 20:20:40 +00008226/*
8227 * ":augroup {name}".
8228 */
8229 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008230do_augroup(char_u *arg, int del_group)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008231{
8232 int i;
8233
8234 if (del_group)
8235 {
8236 if (*arg == NUL)
8237 EMSG(_(e_argreq));
8238 else
8239 au_del_group(arg);
8240 }
8241 else if (STRICMP(arg, "end") == 0) /* ":aug end": back to group 0 */
8242 current_augroup = AUGROUP_DEFAULT;
8243 else if (*arg) /* ":aug xxx": switch to group xxx */
8244 {
8245 i = au_new_group(arg);
8246 if (i != AUGROUP_ERROR)
8247 current_augroup = i;
8248 }
8249 else /* ":aug": list the group names */
8250 {
8251 msg_start();
8252 for (i = 0; i < augroups.ga_len; ++i)
8253 {
8254 if (AUGROUP_NAME(i) != NULL)
8255 {
8256 msg_puts(AUGROUP_NAME(i));
8257 msg_puts((char_u *)" ");
8258 }
8259 }
8260 msg_clr_eos();
8261 msg_end();
8262 }
8263}
8264
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008265#if defined(EXITFREE) || defined(PROTO)
8266 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008267free_all_autocmds(void)
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008268{
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008269 int i;
8270 char_u *s;
8271
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008272 for (current_augroup = -1; current_augroup < augroups.ga_len;
8273 ++current_augroup)
8274 do_autocmd((char_u *)"", TRUE);
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008275
8276 for (i = 0; i < augroups.ga_len; ++i)
8277 {
8278 s = ((char_u **)(augroups.ga_data))[i];
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008279 if (s != get_deleted_augroup())
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008280 vim_free(s);
8281 }
8282 ga_clear(&augroups);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008283}
8284#endif
8285
Bram Moolenaar071d4272004-06-13 20:20:40 +00008286/*
8287 * Return the event number for event name "start".
8288 * Return NUM_EVENTS if the event name was not found.
8289 * Return a pointer to the next event name in "end".
8290 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008291 static event_T
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008292event_name2nr(char_u *start, char_u **end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008293{
8294 char_u *p;
8295 int i;
8296 int len;
8297
Bram Moolenaare99e8442016-07-26 20:43:40 +02008298 /* the event name ends with end of line, '|', a blank or a comma */
Bram Moolenaar1c465442017-03-12 20:10:05 +01008299 for (p = start; *p && !VIM_ISWHITE(*p) && *p != ',' && *p != '|'; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008300 ;
8301 for (i = 0; event_names[i].name != NULL; ++i)
8302 {
8303 len = (int)STRLEN(event_names[i].name);
8304 if (len == p - start && STRNICMP(event_names[i].name, start, len) == 0)
8305 break;
8306 }
8307 if (*p == ',')
8308 ++p;
8309 *end = p;
8310 if (event_names[i].name == NULL)
8311 return NUM_EVENTS;
8312 return event_names[i].event;
8313}
8314
8315/*
8316 * Return the name for event "event".
8317 */
8318 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008319event_nr2name(event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008320{
8321 int i;
8322
8323 for (i = 0; event_names[i].name != NULL; ++i)
8324 if (event_names[i].event == event)
8325 return (char_u *)event_names[i].name;
8326 return (char_u *)"Unknown";
8327}
8328
8329/*
8330 * Scan over the events. "*" stands for all events.
8331 */
8332 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008333find_end_event(
8334 char_u *arg,
8335 int have_group) /* TRUE when group name was found */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008336{
8337 char_u *pat;
8338 char_u *p;
8339
8340 if (*arg == '*')
8341 {
Bram Moolenaar1c465442017-03-12 20:10:05 +01008342 if (arg[1] && !VIM_ISWHITE(arg[1]))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008343 {
8344 EMSG2(_("E215: Illegal character after *: %s"), arg);
8345 return NULL;
8346 }
8347 pat = arg + 1;
8348 }
8349 else
8350 {
Bram Moolenaar1c465442017-03-12 20:10:05 +01008351 for (pat = arg; *pat && *pat != '|' && !VIM_ISWHITE(*pat); pat = p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008352 {
8353 if ((int)event_name2nr(pat, &p) >= (int)NUM_EVENTS)
8354 {
8355 if (have_group)
8356 EMSG2(_("E216: No such event: %s"), pat);
8357 else
8358 EMSG2(_("E216: No such group or event: %s"), pat);
8359 return NULL;
8360 }
8361 }
8362 }
8363 return pat;
8364}
8365
8366/*
8367 * Return TRUE if "event" is included in 'eventignore'.
8368 */
8369 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008370event_ignored(event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008371{
8372 char_u *p = p_ei;
8373
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008374 while (*p != NUL)
8375 {
8376 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8377 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008378 if (event_name2nr(p, &p) == event)
8379 return TRUE;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008380 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008381
8382 return FALSE;
8383}
8384
8385/*
8386 * Return OK when the contents of p_ei is valid, FAIL otherwise.
8387 */
8388 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008389check_ei(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008390{
8391 char_u *p = p_ei;
8392
Bram Moolenaar071d4272004-06-13 20:20:40 +00008393 while (*p)
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008394 {
8395 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8396 {
8397 p += 3;
8398 if (*p == ',')
8399 ++p;
8400 }
8401 else if (event_name2nr(p, &p) == NUM_EVENTS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008402 return FAIL;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008403 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008404
8405 return OK;
8406}
8407
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008408# if defined(FEAT_SYN_HL) || defined(PROTO)
8409
8410/*
8411 * Add "what" to 'eventignore' to skip loading syntax highlighting for every
8412 * buffer loaded into the window. "what" must start with a comma.
8413 * Returns the old value of 'eventignore' in allocated memory.
8414 */
8415 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008416au_event_disable(char *what)
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008417{
8418 char_u *new_ei;
8419 char_u *save_ei;
8420
8421 save_ei = vim_strsave(p_ei);
8422 if (save_ei != NULL)
8423 {
Bram Moolenaara5792f52005-11-23 21:25:05 +00008424 new_ei = vim_strnsave(p_ei, (int)(STRLEN(p_ei) + STRLEN(what)));
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008425 if (new_ei != NULL)
8426 {
Bram Moolenaar8cac9fd2010-03-02 12:48:05 +01008427 if (*what == ',' && *p_ei == NUL)
8428 STRCPY(new_ei, what + 1);
8429 else
8430 STRCAT(new_ei, what);
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008431 set_string_option_direct((char_u *)"ei", -1, new_ei,
8432 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008433 vim_free(new_ei);
8434 }
8435 }
8436 return save_ei;
8437}
8438
8439 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008440au_event_restore(char_u *old_ei)
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008441{
8442 if (old_ei != NULL)
8443 {
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008444 set_string_option_direct((char_u *)"ei", -1, old_ei,
8445 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008446 vim_free(old_ei);
8447 }
8448}
8449# endif /* FEAT_SYN_HL */
8450
Bram Moolenaar071d4272004-06-13 20:20:40 +00008451/*
8452 * do_autocmd() -- implements the :autocmd command. Can be used in the
8453 * following ways:
8454 *
8455 * :autocmd <event> <pat> <cmd> Add <cmd> to the list of commands that
8456 * will be automatically executed for <event>
8457 * when editing a file matching <pat>, in
8458 * the current group.
8459 * :autocmd <event> <pat> Show the auto-commands associated with
8460 * <event> and <pat>.
8461 * :autocmd <event> Show the auto-commands associated with
8462 * <event>.
8463 * :autocmd Show all auto-commands.
8464 * :autocmd! <event> <pat> <cmd> Remove all auto-commands associated with
8465 * <event> and <pat>, and add the command
8466 * <cmd>, for the current group.
8467 * :autocmd! <event> <pat> Remove all auto-commands associated with
8468 * <event> and <pat> for the current group.
8469 * :autocmd! <event> Remove all auto-commands associated with
8470 * <event> for the current group.
8471 * :autocmd! Remove ALL auto-commands for the current
8472 * group.
8473 *
8474 * Multiple events and patterns may be given separated by commas. Here are
8475 * some examples:
8476 * :autocmd bufread,bufenter *.c,*.h set tw=0 smartindent noic
8477 * :autocmd bufleave * set tw=79 nosmartindent ic infercase
8478 *
8479 * :autocmd * *.c show all autocommands for *.c files.
Bram Moolenaard35f9712005-12-18 22:02:33 +00008480 *
8481 * Mostly a {group} argument can optionally appear before <event>.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008482 */
8483 void
Bram Moolenaare99e8442016-07-26 20:43:40 +02008484do_autocmd(char_u *arg_in, int forceit)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008485{
Bram Moolenaare99e8442016-07-26 20:43:40 +02008486 char_u *arg = arg_in;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008487 char_u *pat;
8488 char_u *envpat = NULL;
8489 char_u *cmd;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008490 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008491 int need_free = FALSE;
8492 int nested = FALSE;
8493 int group;
8494
Bram Moolenaare99e8442016-07-26 20:43:40 +02008495 if (*arg == '|')
8496 {
8497 arg = (char_u *)"";
8498 group = AUGROUP_ALL; /* no argument, use all groups */
8499 }
8500 else
8501 {
8502 /*
8503 * Check for a legal group name. If not, use AUGROUP_ALL.
8504 */
8505 group = au_get_grouparg(&arg);
8506 if (arg == NULL) /* out of memory */
8507 return;
8508 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008509
8510 /*
8511 * Scan over the events.
8512 * If we find an illegal name, return here, don't do anything.
8513 */
8514 pat = find_end_event(arg, group != AUGROUP_ALL);
8515 if (pat == NULL)
8516 return;
8517
Bram Moolenaar071d4272004-06-13 20:20:40 +00008518 pat = skipwhite(pat);
Bram Moolenaare99e8442016-07-26 20:43:40 +02008519 if (*pat == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008520 {
Bram Moolenaare99e8442016-07-26 20:43:40 +02008521 pat = (char_u *)"";
8522 cmd = (char_u *)"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00008523 }
Bram Moolenaare99e8442016-07-26 20:43:40 +02008524 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00008525 {
Bram Moolenaare99e8442016-07-26 20:43:40 +02008526 /*
8527 * Scan over the pattern. Put a NUL at the end.
8528 */
8529 cmd = pat;
Bram Moolenaar1c465442017-03-12 20:10:05 +01008530 while (*cmd && (!VIM_ISWHITE(*cmd) || cmd[-1] == '\\'))
Bram Moolenaare99e8442016-07-26 20:43:40 +02008531 cmd++;
8532 if (*cmd)
8533 *cmd++ = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008534
Bram Moolenaare99e8442016-07-26 20:43:40 +02008535 /* Expand environment variables in the pattern. Set 'shellslash', we want
8536 * forward slashes here. */
8537 if (vim_strchr(pat, '$') != NULL || vim_strchr(pat, '~') != NULL)
8538 {
8539#ifdef BACKSLASH_IN_FILENAME
8540 int p_ssl_save = p_ssl;
8541
8542 p_ssl = TRUE;
8543#endif
8544 envpat = expand_env_save(pat);
8545#ifdef BACKSLASH_IN_FILENAME
8546 p_ssl = p_ssl_save;
8547#endif
8548 if (envpat != NULL)
8549 pat = envpat;
8550 }
8551
8552 /*
8553 * Check for "nested" flag.
8554 */
8555 cmd = skipwhite(cmd);
Bram Moolenaar1c465442017-03-12 20:10:05 +01008556 if (*cmd != NUL && STRNCMP(cmd, "nested", 6) == 0 && VIM_ISWHITE(cmd[6]))
Bram Moolenaare99e8442016-07-26 20:43:40 +02008557 {
8558 nested = TRUE;
8559 cmd = skipwhite(cmd + 6);
8560 }
8561
8562 /*
8563 * Find the start of the commands.
8564 * Expand <sfile> in it.
8565 */
8566 if (*cmd != NUL)
8567 {
8568 cmd = expand_sfile(cmd);
8569 if (cmd == NULL) /* some error */
8570 return;
8571 need_free = TRUE;
8572 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008573 }
8574
8575 /*
8576 * Print header when showing autocommands.
8577 */
8578 if (!forceit && *cmd == NUL)
8579 {
8580 /* Highlight title */
8581 MSG_PUTS_TITLE(_("\n--- Auto-Commands ---"));
8582 }
8583
8584 /*
8585 * Loop over the events.
8586 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008587 last_event = (event_T)-1; /* for listing the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008588 last_group = AUGROUP_ERROR; /* for listing the group name */
Bram Moolenaare99e8442016-07-26 20:43:40 +02008589 if (*arg == '*' || *arg == NUL || *arg == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008590 {
Bram Moolenaar754b5602006-02-09 23:53:20 +00008591 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8592 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008593 if (do_autocmd_event(event, pat,
8594 nested, cmd, forceit, group) == FAIL)
8595 break;
8596 }
8597 else
8598 {
Bram Moolenaar1c465442017-03-12 20:10:05 +01008599 while (*arg && *arg != '|' && !VIM_ISWHITE(*arg))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008600 if (do_autocmd_event(event_name2nr(arg, &arg), pat,
8601 nested, cmd, forceit, group) == FAIL)
8602 break;
8603 }
8604
8605 if (need_free)
8606 vim_free(cmd);
8607 vim_free(envpat);
8608}
8609
8610/*
8611 * Find the group ID in a ":autocmd" or ":doautocmd" argument.
8612 * The "argp" argument is advanced to the following argument.
8613 *
8614 * Returns the group ID, AUGROUP_ERROR for error (out of memory).
8615 */
8616 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008617au_get_grouparg(char_u **argp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008618{
8619 char_u *group_name;
8620 char_u *p;
8621 char_u *arg = *argp;
8622 int group = AUGROUP_ALL;
8623
Bram Moolenaar1c465442017-03-12 20:10:05 +01008624 for (p = arg; *p && !VIM_ISWHITE(*p) && *p != '|'; ++p)
Bram Moolenaare99e8442016-07-26 20:43:40 +02008625 ;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008626 if (p > arg)
8627 {
8628 group_name = vim_strnsave(arg, (int)(p - arg));
8629 if (group_name == NULL) /* out of memory */
8630 return AUGROUP_ERROR;
8631 group = au_find_group(group_name);
8632 if (group == AUGROUP_ERROR)
8633 group = AUGROUP_ALL; /* no match, use all groups */
8634 else
8635 *argp = skipwhite(p); /* match, skip over group name */
8636 vim_free(group_name);
8637 }
8638 return group;
8639}
8640
8641/*
8642 * do_autocmd() for one event.
8643 * If *pat == NUL do for all patterns.
8644 * If *cmd == NUL show entries.
8645 * If forceit == TRUE delete entries.
8646 * If group is not AUGROUP_ALL, only use this group.
8647 */
8648 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008649do_autocmd_event(
8650 event_T event,
8651 char_u *pat,
8652 int nested,
8653 char_u *cmd,
8654 int forceit,
8655 int group)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008656{
8657 AutoPat *ap;
8658 AutoPat **prev_ap;
8659 AutoCmd *ac;
8660 AutoCmd **prev_ac;
8661 int brace_level;
8662 char_u *endpat;
8663 int findgroup;
8664 int allgroups;
8665 int patlen;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00008666 int is_buflocal;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008667 int buflocal_nr;
8668 char_u buflocal_pat[25]; /* for "<buffer=X>" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008669
8670 if (group == AUGROUP_ALL)
8671 findgroup = current_augroup;
8672 else
8673 findgroup = group;
8674 allgroups = (group == AUGROUP_ALL && !forceit && *cmd == NUL);
8675
8676 /*
8677 * Show or delete all patterns for an event.
8678 */
8679 if (*pat == NUL)
8680 {
8681 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8682 {
8683 if (forceit) /* delete the AutoPat, if it's in the current group */
8684 {
8685 if (ap->group == findgroup)
8686 au_remove_pat(ap);
8687 }
8688 else if (group == AUGROUP_ALL || ap->group == group)
8689 show_autocmd(ap, event);
8690 }
8691 }
8692
8693 /*
8694 * Loop through all the specified patterns.
8695 */
8696 for ( ; *pat; pat = (*endpat == ',' ? endpat + 1 : endpat))
8697 {
8698 /*
8699 * Find end of the pattern.
8700 * Watch out for a comma in braces, like "*.\{obj,o\}".
8701 */
8702 brace_level = 0;
8703 for (endpat = pat; *endpat && (*endpat != ',' || brace_level
Bram Moolenaar6b9be1b2015-07-28 13:33:45 +02008704 || (endpat > pat && endpat[-1] == '\\')); ++endpat)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008705 {
8706 if (*endpat == '{')
8707 brace_level++;
8708 else if (*endpat == '}')
8709 brace_level--;
8710 }
8711 if (pat == endpat) /* ignore single comma */
8712 continue;
8713 patlen = (int)(endpat - pat);
8714
8715 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008716 * detect special <buflocal[=X]> buffer-local patterns
8717 */
8718 is_buflocal = FALSE;
8719 buflocal_nr = 0;
8720
Bram Moolenaar1e997822015-02-17 16:04:57 +01008721 if (patlen >= 8 && STRNCMP(pat, "<buffer", 7) == 0
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008722 && pat[patlen - 1] == '>')
8723 {
Bram Moolenaar1e997822015-02-17 16:04:57 +01008724 /* "<buffer...>": Error will be printed only for addition.
8725 * printing and removing will proceed silently. */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008726 is_buflocal = TRUE;
8727 if (patlen == 8)
Bram Moolenaar1e997822015-02-17 16:04:57 +01008728 /* "<buffer>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008729 buflocal_nr = curbuf->b_fnum;
8730 else if (patlen > 9 && pat[7] == '=')
8731 {
Bram Moolenaar1e997822015-02-17 16:04:57 +01008732 if (patlen == 13 && STRNICMP(pat, "<buffer=abuf>", 13) == 0)
8733 /* "<buffer=abuf>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008734 buflocal_nr = autocmd_bufnr;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008735 else if (skipdigits(pat + 8) == pat + patlen - 1)
Bram Moolenaar1e997822015-02-17 16:04:57 +01008736 /* "<buffer=123>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008737 buflocal_nr = atoi((char *)pat + 8);
8738 }
8739 }
8740
8741 if (is_buflocal)
8742 {
8743 /* normalize pat into standard "<buffer>#N" form */
8744 sprintf((char *)buflocal_pat, "<buffer=%d>", buflocal_nr);
8745 pat = buflocal_pat; /* can modify pat and patlen */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008746 patlen = (int)STRLEN(buflocal_pat); /* but not endpat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008747 }
8748
8749 /*
Bram Moolenaar462455e2017-11-10 21:53:11 +01008750 * Find AutoPat entries with this pattern. When adding a command it
8751 * always goes at or after the last one, so start at the end.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008752 */
Bram Moolenaar462455e2017-11-10 21:53:11 +01008753 if (!forceit && *cmd != NUL && last_autopat[(int)event] != NULL)
8754 prev_ap = &last_autopat[(int)event];
8755 else
8756 prev_ap = &first_autopat[(int)event];
Bram Moolenaar071d4272004-06-13 20:20:40 +00008757 while ((ap = *prev_ap) != NULL)
8758 {
8759 if (ap->pat != NULL)
8760 {
8761 /* Accept a pattern when:
8762 * - a group was specified and it's that group, or a group was
8763 * not specified and it's the current group, or a group was
8764 * not specified and we are listing
8765 * - the length of the pattern matches
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008766 * - the pattern matches.
8767 * For <buffer[=X]>, this condition works because we normalize
8768 * all buffer-local patterns.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008769 */
8770 if ((allgroups || ap->group == findgroup)
8771 && ap->patlen == patlen
8772 && STRNCMP(pat, ap->pat, patlen) == 0)
8773 {
8774 /*
8775 * Remove existing autocommands.
8776 * If adding any new autocmd's for this AutoPat, don't
8777 * delete the pattern from the autopat list, append to
8778 * this list.
8779 */
8780 if (forceit)
8781 {
8782 if (*cmd != NUL && ap->next == NULL)
8783 {
8784 au_remove_cmds(ap);
8785 break;
8786 }
8787 au_remove_pat(ap);
8788 }
8789
8790 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008791 * Show autocmd's for this autopat, or buflocals <buffer=X>
Bram Moolenaar071d4272004-06-13 20:20:40 +00008792 */
8793 else if (*cmd == NUL)
8794 show_autocmd(ap, event);
8795
8796 /*
8797 * Add autocmd to this autopat, if it's the last one.
8798 */
8799 else if (ap->next == NULL)
8800 break;
8801 }
8802 }
8803 prev_ap = &ap->next;
8804 }
8805
8806 /*
8807 * Add a new command.
8808 */
8809 if (*cmd != NUL)
8810 {
8811 /*
8812 * If the pattern we want to add a command to does appear at the
8813 * end of the list (or not is not in the list at all), add the
8814 * pattern at the end of the list.
8815 */
8816 if (ap == NULL)
8817 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008818 /* refuse to add buffer-local ap if buffer number is invalid */
8819 if (is_buflocal && (buflocal_nr == 0
8820 || buflist_findnr(buflocal_nr) == NULL))
8821 {
8822 EMSGN(_("E680: <buffer=%d>: invalid buffer number "),
8823 buflocal_nr);
8824 return FAIL;
8825 }
8826
Bram Moolenaar071d4272004-06-13 20:20:40 +00008827 ap = (AutoPat *)alloc((unsigned)sizeof(AutoPat));
8828 if (ap == NULL)
8829 return FAIL;
8830 ap->pat = vim_strnsave(pat, patlen);
8831 ap->patlen = patlen;
8832 if (ap->pat == NULL)
8833 {
8834 vim_free(ap);
8835 return FAIL;
8836 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008837
8838 if (is_buflocal)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008839 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008840 ap->buflocal_nr = buflocal_nr;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008841 ap->reg_prog = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008842 }
8843 else
8844 {
Bram Moolenaar748bf032005-02-02 23:04:36 +00008845 char_u *reg_pat;
8846
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008847 ap->buflocal_nr = 0;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008848 reg_pat = file_pat_to_reg_pat(pat, endpat,
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008849 &ap->allow_dirs, TRUE);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008850 if (reg_pat != NULL)
8851 ap->reg_prog = vim_regcomp(reg_pat, RE_MAGIC);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008852 vim_free(reg_pat);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008853 if (reg_pat == NULL || ap->reg_prog == NULL)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008854 {
8855 vim_free(ap->pat);
8856 vim_free(ap);
8857 return FAIL;
8858 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008859 }
8860 ap->cmds = NULL;
8861 *prev_ap = ap;
Bram Moolenaar462455e2017-11-10 21:53:11 +01008862 last_autopat[(int)event] = ap;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008863 ap->next = NULL;
8864 if (group == AUGROUP_ALL)
8865 ap->group = current_augroup;
8866 else
8867 ap->group = group;
8868 }
8869
8870 /*
8871 * Add the autocmd at the end of the AutoCmd list.
8872 */
8873 prev_ac = &(ap->cmds);
8874 while ((ac = *prev_ac) != NULL)
8875 prev_ac = &ac->next;
8876 ac = (AutoCmd *)alloc((unsigned)sizeof(AutoCmd));
8877 if (ac == NULL)
8878 return FAIL;
8879 ac->cmd = vim_strsave(cmd);
8880#ifdef FEAT_EVAL
8881 ac->scriptID = current_SID;
8882#endif
8883 if (ac->cmd == NULL)
8884 {
8885 vim_free(ac);
8886 return FAIL;
8887 }
8888 ac->next = NULL;
8889 *prev_ac = ac;
8890 ac->nested = nested;
8891 }
8892 }
8893
8894 au_cleanup(); /* may really delete removed patterns/commands now */
8895 return OK;
8896}
8897
8898/*
8899 * Implementation of ":doautocmd [group] event [fname]".
8900 * Return OK for success, FAIL for failure;
8901 */
8902 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008903do_doautocmd(
8904 char_u *arg,
Bram Moolenaar1610d052016-06-09 22:53:01 +02008905 int do_msg, /* give message for no matching autocmds? */
8906 int *did_something)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008907{
8908 char_u *fname;
8909 int nothing_done = TRUE;
8910 int group;
8911
Bram Moolenaar1610d052016-06-09 22:53:01 +02008912 if (did_something != NULL)
Bram Moolenaar76ae22f2016-06-13 20:00:29 +02008913 *did_something = FALSE;
Bram Moolenaar1610d052016-06-09 22:53:01 +02008914
Bram Moolenaar071d4272004-06-13 20:20:40 +00008915 /*
8916 * Check for a legal group name. If not, use AUGROUP_ALL.
8917 */
8918 group = au_get_grouparg(&arg);
8919 if (arg == NULL) /* out of memory */
8920 return FAIL;
8921
8922 if (*arg == '*')
8923 {
8924 EMSG(_("E217: Can't execute autocommands for ALL events"));
8925 return FAIL;
8926 }
8927
8928 /*
8929 * Scan over the events.
8930 * If we find an illegal name, return here, don't do anything.
8931 */
8932 fname = find_end_event(arg, group != AUGROUP_ALL);
8933 if (fname == NULL)
8934 return FAIL;
8935
8936 fname = skipwhite(fname);
8937
8938 /*
8939 * Loop over the events.
8940 */
Bram Moolenaarfaf29d72017-07-09 11:07:16 +02008941 while (*arg && !ends_excmd(*arg) && !VIM_ISWHITE(*arg))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008942 if (apply_autocmds_group(event_name2nr(arg, &arg),
8943 fname, NULL, TRUE, group, curbuf, NULL))
8944 nothing_done = FALSE;
8945
8946 if (nothing_done && do_msg)
8947 MSG(_("No matching autocommands"));
Bram Moolenaar1610d052016-06-09 22:53:01 +02008948 if (did_something != NULL)
8949 *did_something = !nothing_done;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008950
8951#ifdef FEAT_EVAL
8952 return aborting() ? FAIL : OK;
8953#else
8954 return OK;
8955#endif
8956}
8957
8958/*
8959 * ":doautoall": execute autocommands for each loaded buffer.
8960 */
8961 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008962ex_doautoall(exarg_T *eap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008963{
8964 int retval;
8965 aco_save_T aco;
8966 buf_T *buf;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008967 bufref_T bufref;
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008968 char_u *arg = eap->arg;
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008969 int call_do_modelines = check_nomodeline(&arg);
Bram Moolenaar1610d052016-06-09 22:53:01 +02008970 int did_aucmd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008971
8972 /*
8973 * This is a bit tricky: For some commands curwin->w_buffer needs to be
8974 * equal to curbuf, but for some buffers there may not be a window.
8975 * So we change the buffer for the current window for a moment. This
8976 * gives problems when the autocommands make changes to the list of
8977 * buffers or windows...
8978 */
Bram Moolenaar29323592016-07-24 22:04:11 +02008979 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008980 {
Bram Moolenaar3a847972008-07-08 09:36:58 +00008981 if (buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008982 {
8983 /* find a window for this buffer and save some values */
8984 aucmd_prepbuf(&aco, buf);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008985 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008986
8987 /* execute the autocommands for this buffer */
Bram Moolenaar1610d052016-06-09 22:53:01 +02008988 retval = do_doautocmd(arg, FALSE, &did_aucmd);
Bram Moolenaareeefcc72007-05-01 21:21:21 +00008989
Bram Moolenaar1610d052016-06-09 22:53:01 +02008990 if (call_do_modelines && did_aucmd)
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008991 {
8992 /* Execute the modeline settings, but don't set window-local
8993 * options if we are using the current window for another
8994 * buffer. */
8995 do_modelines(curwin == aucmd_win ? OPT_NOWIN : 0);
8996 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008997
8998 /* restore the current window */
8999 aucmd_restbuf(&aco);
9000
9001 /* stop if there is some error or buffer was deleted */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009002 if (retval == FAIL || !bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009003 break;
9004 }
9005 }
9006
9007 check_cursor(); /* just in case lines got deleted */
9008}
9009
9010/*
Bram Moolenaar60542ac2012-02-12 20:14:01 +01009011 * Check *argp for <nomodeline>. When it is present return FALSE, otherwise
9012 * return TRUE and advance *argp to after it.
9013 * Thus return TRUE when do_modelines() should be called.
9014 */
9015 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009016check_nomodeline(char_u **argp)
Bram Moolenaar60542ac2012-02-12 20:14:01 +01009017{
9018 if (STRNCMP(*argp, "<nomodeline>", 12) == 0)
9019 {
9020 *argp = skipwhite(*argp + 12);
9021 return FALSE;
9022 }
9023 return TRUE;
9024}
9025
9026/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00009027 * Prepare for executing autocommands for (hidden) buffer "buf".
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009028 * Search for a visible window containing the current buffer. If there isn't
9029 * one then use "aucmd_win".
Bram Moolenaar071d4272004-06-13 20:20:40 +00009030 * Set "curbuf" and "curwin" to match "buf".
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009031 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009032 */
9033 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009034aucmd_prepbuf(
9035 aco_save_T *aco, /* structure to save values in */
9036 buf_T *buf) /* new curbuf */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009037{
9038 win_T *win;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009039 int save_ea;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02009040#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009041 int save_acd;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02009042#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009043
9044 /* Find a window that is for the new buffer */
9045 if (buf == curbuf) /* be quick when buf is curbuf */
9046 win = curwin;
9047 else
Bram Moolenaar29323592016-07-24 22:04:11 +02009048 FOR_ALL_WINDOWS(win)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009049 if (win->w_buffer == buf)
9050 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009051
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009052 /* Allocate "aucmd_win" when needed. If this fails (out of memory) fall
9053 * back to using the current window. */
9054 if (win == NULL && aucmd_win == NULL)
9055 {
9056 win_alloc_aucmd_win();
9057 if (aucmd_win == NULL)
9058 win = curwin;
9059 }
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009060 if (win == NULL && aucmd_win_used)
9061 /* Strange recursive autocommand, fall back to using the current
9062 * window. Expect a few side effects... */
9063 win = curwin;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009064
9065 aco->save_curwin = curwin;
9066 aco->save_curbuf = curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009067 if (win != NULL)
9068 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009069 /* There is a window for "buf" in the current tab page, make it the
9070 * curwin. This is preferred, it has the least side effects (esp. if
9071 * "buf" is curbuf). */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009072 aco->use_aucmd_win = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009073 curwin = win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009074 }
9075 else
9076 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009077 /* There is no window for "buf", use "aucmd_win". To minimize the side
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02009078 * effects, insert it in the current tab page.
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009079 * Anything related to a window (e.g., setting folds) may have
9080 * unexpected results. */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009081 aco->use_aucmd_win = TRUE;
9082 aucmd_win_used = TRUE;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00009083 aucmd_win->w_buffer = buf;
Bram Moolenaarcdddaa42010-06-07 23:07:44 +02009084 aucmd_win->w_s = &buf->b_s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009085 ++buf->b_nwindows;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00009086 win_init_empty(aucmd_win); /* set cursor and topline to safe values */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009087
9088 /* Make sure w_localdir and globaldir are NULL to avoid a chdir() in
9089 * win_enter_ext(). */
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009090 vim_free(aucmd_win->w_localdir);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009091 aucmd_win->w_localdir = NULL;
9092 aco->globaldir = globaldir;
9093 globaldir = NULL;
9094
Bram Moolenaar071d4272004-06-13 20:20:40 +00009095
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00009096 /* Split the current window, put the aucmd_win in the upper half.
9097 * We don't want the BufEnter or WinEnter autocommands. */
9098 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009099 make_snapshot(SNAP_AUCMD_IDX);
9100 save_ea = p_ea;
9101 p_ea = FALSE;
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009102
Bram Moolenaar4033c552017-09-16 20:54:51 +02009103#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009104 /* Prevent chdir() call in win_enter_ext(), through do_autochdir(). */
9105 save_acd = p_acd;
9106 p_acd = FALSE;
Bram Moolenaar4033c552017-09-16 20:54:51 +02009107#endif
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009108
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009109 (void)win_split_ins(0, WSP_TOP, aucmd_win, 0);
9110 (void)win_comp_pos(); /* recompute window positions */
9111 p_ea = save_ea;
Bram Moolenaar4033c552017-09-16 20:54:51 +02009112#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009113 p_acd = save_acd;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009114#endif
Bram Moolenaar4033c552017-09-16 20:54:51 +02009115 unblock_autocmds();
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00009116 curwin = aucmd_win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009117 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009118 curbuf = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009119 aco->new_curwin = curwin;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009120 set_bufref(&aco->new_curbuf, curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009121}
9122
9123/*
9124 * Cleanup after executing autocommands for a (hidden) buffer.
9125 * Restore the window as it was (if possible).
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009126 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009127 */
9128 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009129aucmd_restbuf(
9130 aco_save_T *aco) /* structure holding saved values */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009131{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009132 int dummy;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009133
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009134 if (aco->use_aucmd_win)
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009135 {
9136 --curbuf->b_nwindows;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009137 /* Find "aucmd_win", it can't be closed, but it may be in another tab
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00009138 * page. Do not trigger autocommands here. */
9139 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009140 if (curwin != aucmd_win)
9141 {
9142 tabpage_T *tp;
9143 win_T *wp;
9144
9145 FOR_ALL_TAB_WINDOWS(tp, wp)
9146 {
9147 if (wp == aucmd_win)
9148 {
9149 if (tp != curtab)
Bram Moolenaar49e649f2013-05-06 04:50:35 +02009150 goto_tabpage_tp(tp, TRUE, TRUE);
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009151 win_goto(aucmd_win);
Bram Moolenaar28f29082012-02-11 23:45:37 +01009152 goto win_found;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009153 }
9154 }
9155 }
Bram Moolenaar28f29082012-02-11 23:45:37 +01009156win_found:
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009157
9158 /* Remove the window and frame from the tree of frames. */
9159 (void)winframe_remove(curwin, &dummy, NULL);
9160 win_remove(curwin, NULL);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009161 aucmd_win_used = FALSE;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009162 last_status(FALSE); /* may need to remove last status line */
Bram Moolenaar8c752bd2017-03-19 17:09:56 +01009163
9164 if (!valid_tabpage_win(curtab))
9165 /* no valid window in current tabpage */
9166 close_tabpage(curtab);
9167
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009168 restore_snapshot(SNAP_AUCMD_IDX, FALSE);
9169 (void)win_comp_pos(); /* recompute window positions */
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00009170 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009171
9172 if (win_valid(aco->save_curwin))
9173 curwin = aco->save_curwin;
9174 else
9175 /* Hmm, original window disappeared. Just use the first one. */
9176 curwin = firstwin;
Bram Moolenaar4033c552017-09-16 20:54:51 +02009177#ifdef FEAT_EVAL
Bram Moolenaar429fa852013-04-15 12:27:36 +02009178 vars_clear(&aucmd_win->w_vars->dv_hashtab); /* free all w: variables */
9179 hash_init(&aucmd_win->w_vars->dv_hashtab); /* re-use the hashtab */
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009180#endif
9181 curbuf = curwin->w_buffer;
9182
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009183 vim_free(globaldir);
9184 globaldir = aco->globaldir;
9185
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009186 /* the buffer contents may have changed */
9187 check_cursor();
9188 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
9189 {
9190 curwin->w_topline = curbuf->b_ml.ml_line_count;
9191#ifdef FEAT_DIFF
9192 curwin->w_topfill = 0;
9193#endif
9194 }
9195#if defined(FEAT_GUI)
9196 /* Hide the scrollbars from the aucmd_win and update. */
9197 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_LEFT], FALSE);
9198 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_RIGHT], FALSE);
9199 gui_may_update_scrollbars();
9200#endif
9201 }
9202 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00009203 {
9204 /* restore curwin */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009205 if (win_valid(aco->save_curwin))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009206 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009207 /* Restore the buffer which was previously edited by curwin, if
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009208 * it was changed, we are still the same window and the buffer is
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009209 * valid. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009210 if (curwin == aco->new_curwin
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009211 && curbuf != aco->new_curbuf.br_buf
9212 && bufref_valid(&aco->new_curbuf)
9213 && aco->new_curbuf.br_buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009214 {
Bram Moolenaar7da9c372012-04-30 17:04:52 +02009215# if defined(FEAT_SYN_HL) || defined(FEAT_SPELL)
9216 if (curwin->w_s == &curbuf->b_s)
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009217 curwin->w_s = &aco->new_curbuf.br_buf->b_s;
Bram Moolenaar7da9c372012-04-30 17:04:52 +02009218# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009219 --curbuf->b_nwindows;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009220 curbuf = aco->new_curbuf.br_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009221 curwin->w_buffer = curbuf;
9222 ++curbuf->b_nwindows;
9223 }
9224
9225 curwin = aco->save_curwin;
9226 curbuf = curwin->w_buffer;
Bram Moolenaar371932a2014-09-09 16:59:38 +02009227 /* In case the autocommand move the cursor to a position that that
9228 * not exist in curbuf. */
9229 check_cursor();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009230 }
9231 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009232}
9233
9234static int autocmd_nested = FALSE;
9235
9236/*
9237 * Execute autocommands for "event" and file name "fname".
9238 * Return TRUE if some commands were executed.
9239 */
9240 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009241apply_autocmds(
9242 event_T event,
9243 char_u *fname, /* NULL or empty means use actual file name */
9244 char_u *fname_io, /* fname to use for <afile> on cmdline */
9245 int force, /* when TRUE, ignore autocmd_busy */
9246 buf_T *buf) /* buffer for <abuf> */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009247{
9248 return apply_autocmds_group(event, fname, fname_io, force,
9249 AUGROUP_ALL, buf, NULL);
9250}
9251
9252/*
9253 * Like apply_autocmds(), but with extra "eap" argument. This takes care of
9254 * setting v:filearg.
9255 */
9256 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009257apply_autocmds_exarg(
9258 event_T event,
9259 char_u *fname,
9260 char_u *fname_io,
9261 int force,
9262 buf_T *buf,
9263 exarg_T *eap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009264{
9265 return apply_autocmds_group(event, fname, fname_io, force,
9266 AUGROUP_ALL, buf, eap);
9267}
9268
9269/*
9270 * Like apply_autocmds(), but handles the caller's retval. If the script
9271 * processing is being aborted or if retval is FAIL when inside a try
9272 * conditional, no autocommands are executed. If otherwise the autocommands
9273 * cause the script to be aborted, retval is set to FAIL.
9274 */
9275 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009276apply_autocmds_retval(
9277 event_T event,
9278 char_u *fname, /* NULL or empty means use actual file name */
9279 char_u *fname_io, /* fname to use for <afile> on cmdline */
9280 int force, /* when TRUE, ignore autocmd_busy */
9281 buf_T *buf, /* buffer for <abuf> */
9282 int *retval) /* pointer to caller's retval */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009283{
9284 int did_cmd;
9285
Bram Moolenaar1e015462005-09-25 22:16:38 +00009286#ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00009287 if (should_abort(*retval))
9288 return FALSE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00009289#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009290
9291 did_cmd = apply_autocmds_group(event, fname, fname_io, force,
9292 AUGROUP_ALL, buf, NULL);
Bram Moolenaar1e015462005-09-25 22:16:38 +00009293 if (did_cmd
9294#ifdef FEAT_EVAL
9295 && aborting()
9296#endif
9297 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00009298 *retval = FAIL;
9299 return did_cmd;
9300}
9301
Bram Moolenaard35f9712005-12-18 22:02:33 +00009302/*
9303 * Return TRUE when there is a CursorHold autocommand defined.
9304 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009305 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009306has_cursorhold(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009307{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009308 return (first_autopat[(int)(get_real_state() == NORMAL_BUSY
9309 ? EVENT_CURSORHOLD : EVENT_CURSORHOLDI)] != NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009310}
Bram Moolenaard35f9712005-12-18 22:02:33 +00009311
9312/*
9313 * Return TRUE if the CursorHold event can be triggered.
9314 */
9315 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009316trigger_cursorhold(void)
Bram Moolenaard35f9712005-12-18 22:02:33 +00009317{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009318 int state;
9319
Bram Moolenaar05334432011-07-20 18:29:39 +02009320 if (!did_cursorhold
9321 && has_cursorhold()
9322 && !Recording
9323 && typebuf.tb_len == 0
Bram Moolenaard29a9ee2006-09-14 09:07:34 +00009324#ifdef FEAT_INS_EXPAND
9325 && !ins_compl_active()
9326#endif
9327 )
Bram Moolenaar754b5602006-02-09 23:53:20 +00009328 {
9329 state = get_real_state();
9330 if (state == NORMAL_BUSY || (state & INSERT) != 0)
9331 return TRUE;
9332 }
9333 return FALSE;
Bram Moolenaard35f9712005-12-18 22:02:33 +00009334}
Bram Moolenaar754b5602006-02-09 23:53:20 +00009335
9336/*
9337 * Return TRUE when there is a CursorMoved autocommand defined.
9338 */
9339 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009340has_cursormoved(void)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009341{
9342 return (first_autopat[(int)EVENT_CURSORMOVED] != NULL);
9343}
9344
9345/*
9346 * Return TRUE when there is a CursorMovedI autocommand defined.
9347 */
9348 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009349has_cursormovedI(void)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009350{
9351 return (first_autopat[(int)EVENT_CURSORMOVEDI] != NULL);
9352}
Bram Moolenaar071d4272004-06-13 20:20:40 +00009353
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009354/*
Bram Moolenaar186628f2013-03-19 13:33:23 +01009355 * Return TRUE when there is a TextChanged autocommand defined.
9356 */
9357 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009358has_textchanged(void)
Bram Moolenaar186628f2013-03-19 13:33:23 +01009359{
9360 return (first_autopat[(int)EVENT_TEXTCHANGED] != NULL);
9361}
9362
9363/*
9364 * Return TRUE when there is a TextChangedI autocommand defined.
9365 */
9366 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009367has_textchangedI(void)
Bram Moolenaar186628f2013-03-19 13:33:23 +01009368{
9369 return (first_autopat[(int)EVENT_TEXTCHANGEDI] != NULL);
9370}
9371
9372/*
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009373 * Return TRUE when there is an InsertCharPre autocommand defined.
9374 */
9375 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009376has_insertcharpre(void)
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009377{
9378 return (first_autopat[(int)EVENT_INSERTCHARPRE] != NULL);
9379}
9380
Bram Moolenaard5005162014-08-22 23:05:54 +02009381/*
9382 * Return TRUE when there is an CmdUndefined autocommand defined.
9383 */
9384 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009385has_cmdundefined(void)
Bram Moolenaard5005162014-08-22 23:05:54 +02009386{
9387 return (first_autopat[(int)EVENT_CMDUNDEFINED] != NULL);
9388}
9389
9390/*
9391 * Return TRUE when there is an FuncUndefined autocommand defined.
9392 */
9393 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009394has_funcundefined(void)
Bram Moolenaard5005162014-08-22 23:05:54 +02009395{
9396 return (first_autopat[(int)EVENT_FUNCUNDEFINED] != NULL);
9397}
9398
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009399/*
9400 * Execute autocommands for "event" and file name "fname".
9401 * Return TRUE if some commands were executed.
9402 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009403 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009404apply_autocmds_group(
9405 event_T event,
9406 char_u *fname, /* NULL or empty means use actual file name */
9407 char_u *fname_io, /* fname to use for <afile> on cmdline, NULL means
Bram Moolenaar071d4272004-06-13 20:20:40 +00009408 use fname */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009409 int force, /* when TRUE, ignore autocmd_busy */
9410 int group, /* group ID, or AUGROUP_ALL */
9411 buf_T *buf, /* buffer for <abuf> */
9412 exarg_T *eap) /* command arguments */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009413{
9414 char_u *sfname = NULL; /* short file name */
9415 char_u *tail;
9416 int save_changed;
9417 buf_T *old_curbuf;
9418 int retval = FALSE;
9419 char_u *save_sourcing_name;
9420 linenr_T save_sourcing_lnum;
9421 char_u *save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009422 int save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009423 int save_autocmd_bufnr;
9424 char_u *save_autocmd_match;
9425 int save_autocmd_busy;
9426 int save_autocmd_nested;
9427 static int nesting = 0;
9428 AutoPatCmd patcmd;
9429 AutoPat *ap;
9430#ifdef FEAT_EVAL
9431 scid_T save_current_SID;
9432 void *save_funccalp;
9433 char_u *save_cmdarg;
9434 long save_cmdbang;
9435#endif
9436 static int filechangeshell_busy = FALSE;
Bram Moolenaar05159a02005-02-26 23:04:13 +00009437#ifdef FEAT_PROFILE
9438 proftime_T wait_time;
9439#endif
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009440 int did_save_redobuff = FALSE;
Bram Moolenaard4863aa2017-04-07 19:50:12 +02009441 save_redo_T save_redo;
Bram Moolenaarc9e9c712017-11-09 12:29:35 +01009442 int save_KeyTyped = KeyTyped;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009443
9444 /*
9445 * Quickly return if there are no autocommands for this event or
9446 * autocommands are blocked.
9447 */
Bram Moolenaarfaf29d72017-07-09 11:07:16 +02009448 if (event == NUM_EVENTS || first_autopat[(int)event] == NULL
9449 || autocmd_blocked > 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009450 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009451
9452 /*
9453 * When autocommands are busy, new autocommands are only executed when
9454 * explicitly enabled with the "nested" flag.
9455 */
9456 if (autocmd_busy && !(force || autocmd_nested))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009457 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009458
9459#ifdef FEAT_EVAL
9460 /*
Bram Moolenaar7263a772007-05-10 17:35:54 +00009461 * Quickly return when immediately aborting on error, or when an interrupt
Bram Moolenaar071d4272004-06-13 20:20:40 +00009462 * occurred or an exception was thrown but not caught.
9463 */
9464 if (aborting())
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009465 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009466#endif
9467
9468 /*
9469 * FileChangedShell never nests, because it can create an endless loop.
9470 */
Bram Moolenaar56718732006-03-15 22:53:57 +00009471 if (filechangeshell_busy && (event == EVENT_FILECHANGEDSHELL
9472 || event == EVENT_FILECHANGEDSHELLPOST))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009473 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009474
9475 /*
9476 * Ignore events in 'eventignore'.
9477 */
9478 if (event_ignored(event))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009479 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009480
9481 /*
9482 * Allow nesting of autocommands, but restrict the depth, because it's
9483 * possible to create an endless loop.
9484 */
9485 if (nesting == 10)
9486 {
9487 EMSG(_("E218: autocommand nesting too deep"));
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009488 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009489 }
9490
9491 /*
9492 * Check if these autocommands are disabled. Used when doing ":all" or
9493 * ":ball".
9494 */
9495 if ( (autocmd_no_enter
9496 && (event == EVENT_WINENTER || event == EVENT_BUFENTER))
9497 || (autocmd_no_leave
9498 && (event == EVENT_WINLEAVE || event == EVENT_BUFLEAVE)))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009499 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009500
9501 /*
9502 * Save the autocmd_* variables and info about the current buffer.
9503 */
9504 save_autocmd_fname = autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009505 save_autocmd_fname_full = autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009506 save_autocmd_bufnr = autocmd_bufnr;
9507 save_autocmd_match = autocmd_match;
9508 save_autocmd_busy = autocmd_busy;
9509 save_autocmd_nested = autocmd_nested;
9510 save_changed = curbuf->b_changed;
9511 old_curbuf = curbuf;
9512
9513 /*
9514 * Set the file name to be used for <afile>.
Bram Moolenaara0174af2008-01-02 20:08:25 +00009515 * Make a copy to avoid that changing a buffer name or directory makes it
9516 * invalid.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009517 */
9518 if (fname_io == NULL)
9519 {
Bram Moolenaar53744302015-07-17 17:38:22 +02009520 if (event == EVENT_COLORSCHEME || event == EVENT_OPTIONSET)
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009521 autocmd_fname = NULL;
Bram Moolenaarfaf29d72017-07-09 11:07:16 +02009522 else if (fname != NULL && !ends_excmd(*fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009523 autocmd_fname = fname;
9524 else if (buf != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009525 autocmd_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009526 else
9527 autocmd_fname = NULL;
9528 }
9529 else
9530 autocmd_fname = fname_io;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009531 if (autocmd_fname != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009532 autocmd_fname = vim_strsave(autocmd_fname);
9533 autocmd_fname_full = FALSE; /* call FullName_save() later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009534
9535 /*
9536 * Set the buffer number to be used for <abuf>.
9537 */
9538 if (buf == NULL)
9539 autocmd_bufnr = 0;
9540 else
9541 autocmd_bufnr = buf->b_fnum;
9542
9543 /*
9544 * When the file name is NULL or empty, use the file name of buffer "buf".
9545 * Always use the full path of the file name to match with, in case
9546 * "allow_dirs" is set.
9547 */
9548 if (fname == NULL || *fname == NUL)
9549 {
9550 if (buf == NULL)
9551 fname = NULL;
9552 else
9553 {
9554#ifdef FEAT_SYN_HL
9555 if (event == EVENT_SYNTAX)
9556 fname = buf->b_p_syn;
9557 else
9558#endif
9559 if (event == EVENT_FILETYPE)
9560 fname = buf->b_p_ft;
9561 else
9562 {
9563 if (buf->b_sfname != NULL)
9564 sfname = vim_strsave(buf->b_sfname);
9565 fname = buf->b_ffname;
9566 }
9567 }
9568 if (fname == NULL)
9569 fname = (char_u *)"";
9570 fname = vim_strsave(fname); /* make a copy, so we can change it */
9571 }
9572 else
9573 {
9574 sfname = vim_strsave(fname);
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009575 /* Don't try expanding FileType, Syntax, FuncUndefined, WindowID,
9576 * ColorScheme or QuickFixCmd* */
Bram Moolenaar7c626922005-02-07 22:01:03 +00009577 if (event == EVENT_FILETYPE
9578 || event == EVENT_SYNTAX
Bram Moolenaar5135d462009-04-29 16:03:38 +00009579 || event == EVENT_FUNCUNDEFINED
Bram Moolenaar7c626922005-02-07 22:01:03 +00009580 || event == EVENT_REMOTEREPLY
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00009581 || event == EVENT_SPELLFILEMISSING
Bram Moolenaar7c626922005-02-07 22:01:03 +00009582 || event == EVENT_QUICKFIXCMDPRE
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009583 || event == EVENT_COLORSCHEME
Bram Moolenaar53744302015-07-17 17:38:22 +02009584 || event == EVENT_OPTIONSET
Bram Moolenaar7c626922005-02-07 22:01:03 +00009585 || event == EVENT_QUICKFIXCMDPOST)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009586 fname = vim_strsave(fname);
9587 else
9588 fname = FullName_save(fname, FALSE);
9589 }
9590 if (fname == NULL) /* out of memory */
9591 {
9592 vim_free(sfname);
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009593 retval = FALSE;
9594 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009595 }
9596
9597#ifdef BACKSLASH_IN_FILENAME
9598 /*
9599 * Replace all backslashes with forward slashes. This makes the
9600 * autocommand patterns portable between Unix and MS-DOS.
9601 */
9602 if (sfname != NULL)
9603 forward_slash(sfname);
9604 forward_slash(fname);
9605#endif
9606
9607#ifdef VMS
9608 /* remove version for correct match */
9609 if (sfname != NULL)
9610 vms_remove_version(sfname);
9611 vms_remove_version(fname);
9612#endif
9613
9614 /*
9615 * Set the name to be used for <amatch>.
9616 */
9617 autocmd_match = fname;
9618
9619
9620 /* Don't redraw while doing auto commands. */
9621 ++RedrawingDisabled;
9622 save_sourcing_name = sourcing_name;
9623 sourcing_name = NULL; /* don't free this one */
9624 save_sourcing_lnum = sourcing_lnum;
9625 sourcing_lnum = 0; /* no line number here */
9626
9627#ifdef FEAT_EVAL
9628 save_current_SID = current_SID;
9629
Bram Moolenaar05159a02005-02-26 23:04:13 +00009630# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009631 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009632 prof_child_enter(&wait_time); /* doesn't count for the caller itself */
9633# endif
9634
Bram Moolenaar071d4272004-06-13 20:20:40 +00009635 /* Don't use local function variables, if called from a function */
9636 save_funccalp = save_funccal();
9637#endif
9638
9639 /*
9640 * When starting to execute autocommands, save the search patterns.
9641 */
9642 if (!autocmd_busy)
9643 {
9644 save_search_patterns();
Bram Moolenaar20ad69c2015-12-03 13:52:52 +01009645#ifdef FEAT_INS_EXPAND
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009646 if (!ins_compl_active())
Bram Moolenaar20ad69c2015-12-03 13:52:52 +01009647#endif
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009648 {
Bram Moolenaard4863aa2017-04-07 19:50:12 +02009649 saveRedobuff(&save_redo);
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009650 did_save_redobuff = TRUE;
9651 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009652 did_filetype = keep_filetype;
9653 }
9654
9655 /*
9656 * Note that we are applying autocmds. Some commands need to know.
9657 */
9658 autocmd_busy = TRUE;
9659 filechangeshell_busy = (event == EVENT_FILECHANGEDSHELL);
9660 ++nesting; /* see matching decrement below */
9661
9662 /* Remember that FileType was triggered. Used for did_filetype(). */
9663 if (event == EVENT_FILETYPE)
9664 did_filetype = TRUE;
9665
9666 tail = gettail(fname);
9667
9668 /* Find first autocommand that matches */
9669 patcmd.curpat = first_autopat[(int)event];
9670 patcmd.nextcmd = NULL;
9671 patcmd.group = group;
9672 patcmd.fname = fname;
9673 patcmd.sfname = sfname;
9674 patcmd.tail = tail;
9675 patcmd.event = event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009676 patcmd.arg_bufnr = autocmd_bufnr;
9677 patcmd.next = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009678 auto_next_pat(&patcmd, FALSE);
9679
9680 /* found one, start executing the autocommands */
9681 if (patcmd.curpat != NULL)
9682 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009683 /* add to active_apc_list */
9684 patcmd.next = active_apc_list;
9685 active_apc_list = &patcmd;
9686
Bram Moolenaar071d4272004-06-13 20:20:40 +00009687#ifdef FEAT_EVAL
9688 /* set v:cmdarg (only when there is a matching pattern) */
Bram Moolenaar22fcfad2016-07-01 18:17:26 +02009689 save_cmdbang = (long)get_vim_var_nr(VV_CMDBANG);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009690 if (eap != NULL)
9691 {
9692 save_cmdarg = set_cmdarg(eap, NULL);
9693 set_vim_var_nr(VV_CMDBANG, (long)eap->forceit);
9694 }
9695 else
9696 save_cmdarg = NULL; /* avoid gcc warning */
9697#endif
9698 retval = TRUE;
9699 /* mark the last pattern, to avoid an endless loop when more patterns
9700 * are added when executing autocommands */
9701 for (ap = patcmd.curpat; ap->next != NULL; ap = ap->next)
9702 ap->last = FALSE;
9703 ap->last = TRUE;
9704 check_lnums(TRUE); /* make sure cursor and topline are valid */
9705 do_cmdline(NULL, getnextac, (void *)&patcmd,
9706 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
9707#ifdef FEAT_EVAL
9708 if (eap != NULL)
9709 {
9710 (void)set_cmdarg(NULL, save_cmdarg);
9711 set_vim_var_nr(VV_CMDBANG, save_cmdbang);
9712 }
9713#endif
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009714 /* delete from active_apc_list */
9715 if (active_apc_list == &patcmd) /* just in case */
9716 active_apc_list = patcmd.next;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009717 }
9718
9719 --RedrawingDisabled;
9720 autocmd_busy = save_autocmd_busy;
9721 filechangeshell_busy = FALSE;
9722 autocmd_nested = save_autocmd_nested;
9723 vim_free(sourcing_name);
9724 sourcing_name = save_sourcing_name;
9725 sourcing_lnum = save_sourcing_lnum;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009726 vim_free(autocmd_fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009727 autocmd_fname = save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009728 autocmd_fname_full = save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009729 autocmd_bufnr = save_autocmd_bufnr;
9730 autocmd_match = save_autocmd_match;
9731#ifdef FEAT_EVAL
9732 current_SID = save_current_SID;
9733 restore_funccal(save_funccalp);
Bram Moolenaar05159a02005-02-26 23:04:13 +00009734# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009735 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009736 prof_child_exit(&wait_time);
9737# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009738#endif
Bram Moolenaarc9e9c712017-11-09 12:29:35 +01009739 KeyTyped = save_KeyTyped;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009740 vim_free(fname);
9741 vim_free(sfname);
9742 --nesting; /* see matching increment above */
9743
9744 /*
9745 * When stopping to execute autocommands, restore the search patterns and
Bram Moolenaar3be85852014-06-12 14:01:31 +02009746 * the redo buffer. Free any buffers in the au_pending_free_buf list and
9747 * free any windows in the au_pending_free_win list.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009748 */
9749 if (!autocmd_busy)
9750 {
9751 restore_search_patterns();
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009752 if (did_save_redobuff)
Bram Moolenaard4863aa2017-04-07 19:50:12 +02009753 restoreRedobuff(&save_redo);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009754 did_filetype = FALSE;
Bram Moolenaar4c7ab1b2014-04-06 20:45:43 +02009755 while (au_pending_free_buf != NULL)
9756 {
9757 buf_T *b = au_pending_free_buf->b_next;
9758 vim_free(au_pending_free_buf);
9759 au_pending_free_buf = b;
9760 }
Bram Moolenaar3be85852014-06-12 14:01:31 +02009761 while (au_pending_free_win != NULL)
9762 {
9763 win_T *w = au_pending_free_win->w_next;
9764 vim_free(au_pending_free_win);
9765 au_pending_free_win = w;
9766 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009767 }
9768
9769 /*
9770 * Some events don't set or reset the Changed flag.
9771 * Check if still in the same buffer!
9772 */
9773 if (curbuf == old_curbuf
9774 && (event == EVENT_BUFREADPOST
9775 || event == EVENT_BUFWRITEPOST
9776 || event == EVENT_FILEAPPENDPOST
9777 || event == EVENT_VIMLEAVE
9778 || event == EVENT_VIMLEAVEPRE))
9779 {
9780#ifdef FEAT_TITLE
9781 if (curbuf->b_changed != save_changed)
9782 need_maketitle = TRUE;
9783#endif
9784 curbuf->b_changed = save_changed;
9785 }
9786
9787 au_cleanup(); /* may really delete removed patterns/commands now */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009788
9789BYPASS_AU:
9790 /* When wiping out a buffer make sure all its buffer-local autocommands
9791 * are deleted. */
9792 if (event == EVENT_BUFWIPEOUT && buf != NULL)
9793 aubuflocal_remove(buf);
9794
Bram Moolenaarc3691332016-04-20 12:49:49 +02009795 if (retval == OK && event == EVENT_FILETYPE)
9796 au_did_filetype = TRUE;
9797
Bram Moolenaar071d4272004-06-13 20:20:40 +00009798 return retval;
9799}
9800
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009801# ifdef FEAT_EVAL
9802static char_u *old_termresponse = NULL;
9803# endif
9804
9805/*
9806 * Block triggering autocommands until unblock_autocmd() is called.
9807 * Can be used recursively, so long as it's symmetric.
9808 */
9809 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009810block_autocmds(void)
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009811{
9812# ifdef FEAT_EVAL
9813 /* Remember the value of v:termresponse. */
9814 if (autocmd_blocked == 0)
9815 old_termresponse = get_vim_var_str(VV_TERMRESPONSE);
9816# endif
9817 ++autocmd_blocked;
9818}
9819
9820 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009821unblock_autocmds(void)
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009822{
9823 --autocmd_blocked;
9824
9825# ifdef FEAT_EVAL
9826 /* When v:termresponse was set while autocommands were blocked, trigger
9827 * the autocommands now. Esp. useful when executing a shell command
9828 * during startup (vimdiff). */
9829 if (autocmd_blocked == 0
9830 && get_vim_var_str(VV_TERMRESPONSE) != old_termresponse)
9831 apply_autocmds(EVENT_TERMRESPONSE, NULL, NULL, FALSE, curbuf);
9832# endif
9833}
9834
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009835 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009836is_autocmd_blocked(void)
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009837{
9838 return autocmd_blocked != 0;
9839}
9840
Bram Moolenaar071d4272004-06-13 20:20:40 +00009841/*
9842 * Find next autocommand pattern that matches.
9843 */
9844 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009845auto_next_pat(
9846 AutoPatCmd *apc,
9847 int stop_at_last) /* stop when 'last' flag is set */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009848{
9849 AutoPat *ap;
9850 AutoCmd *cp;
9851 char_u *name;
9852 char *s;
9853
9854 vim_free(sourcing_name);
9855 sourcing_name = NULL;
9856
9857 for (ap = apc->curpat; ap != NULL && !got_int; ap = ap->next)
9858 {
9859 apc->curpat = NULL;
9860
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009861 /* Only use a pattern when it has not been removed, has commands and
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009862 * the group matches. For buffer-local autocommands only check the
9863 * buffer number. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009864 if (ap->pat != NULL && ap->cmds != NULL
9865 && (apc->group == AUGROUP_ALL || apc->group == ap->group))
9866 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009867 /* execution-condition */
9868 if (ap->buflocal_nr == 0
Bram Moolenaardffa5b82014-11-19 16:38:07 +01009869 ? (match_file_pat(NULL, &ap->reg_prog, apc->fname,
Bram Moolenaar748bf032005-02-02 23:04:36 +00009870 apc->sfname, apc->tail, ap->allow_dirs))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009871 : ap->buflocal_nr == apc->arg_bufnr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009872 {
9873 name = event_nr2name(apc->event);
9874 s = _("%s Auto commands for \"%s\"");
9875 sourcing_name = alloc((unsigned)(STRLEN(s)
9876 + STRLEN(name) + ap->patlen + 1));
9877 if (sourcing_name != NULL)
9878 {
9879 sprintf((char *)sourcing_name, s,
9880 (char *)name, (char *)ap->pat);
9881 if (p_verbose >= 8)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009882 {
9883 verbose_enter();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009884 smsg((char_u *)_("Executing %s"), sourcing_name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009885 verbose_leave();
9886 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009887 }
9888
9889 apc->curpat = ap;
9890 apc->nextcmd = ap->cmds;
9891 /* mark last command */
9892 for (cp = ap->cmds; cp->next != NULL; cp = cp->next)
9893 cp->last = FALSE;
9894 cp->last = TRUE;
9895 }
9896 line_breakcheck();
9897 if (apc->curpat != NULL) /* found a match */
9898 break;
9899 }
9900 if (stop_at_last && ap->last)
9901 break;
9902 }
9903}
9904
9905/*
9906 * Get next autocommand command.
9907 * Called by do_cmdline() to get the next line for ":if".
9908 * Returns allocated string, or NULL for end of autocommands.
9909 */
Bram Moolenaar21691f82012-12-05 19:13:18 +01009910 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009911getnextac(int c UNUSED, void *cookie, int indent UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009912{
9913 AutoPatCmd *acp = (AutoPatCmd *)cookie;
9914 char_u *retval;
9915 AutoCmd *ac;
9916
9917 /* Can be called again after returning the last line. */
9918 if (acp->curpat == NULL)
9919 return NULL;
9920
9921 /* repeat until we find an autocommand to execute */
9922 for (;;)
9923 {
9924 /* skip removed commands */
9925 while (acp->nextcmd != NULL && acp->nextcmd->cmd == NULL)
9926 if (acp->nextcmd->last)
9927 acp->nextcmd = NULL;
9928 else
9929 acp->nextcmd = acp->nextcmd->next;
9930
9931 if (acp->nextcmd != NULL)
9932 break;
9933
9934 /* at end of commands, find next pattern that matches */
9935 if (acp->curpat->last)
9936 acp->curpat = NULL;
9937 else
9938 acp->curpat = acp->curpat->next;
9939 if (acp->curpat != NULL)
9940 auto_next_pat(acp, TRUE);
9941 if (acp->curpat == NULL)
9942 return NULL;
9943 }
9944
9945 ac = acp->nextcmd;
9946
9947 if (p_verbose >= 9)
9948 {
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009949 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009950 smsg((char_u *)_("autocommand %s"), ac->cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009951 msg_puts((char_u *)"\n"); /* don't overwrite this either */
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009952 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009953 }
9954 retval = vim_strsave(ac->cmd);
9955 autocmd_nested = ac->nested;
9956#ifdef FEAT_EVAL
9957 current_SID = ac->scriptID;
9958#endif
9959 if (ac->last)
9960 acp->nextcmd = NULL;
9961 else
9962 acp->nextcmd = ac->next;
9963 return retval;
9964}
9965
9966/*
9967 * Return TRUE if there is a matching autocommand for "fname".
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009968 * To account for buffer-local autocommands, function needs to know
9969 * in which buffer the file will be opened.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009970 */
9971 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009972has_autocmd(event_T event, char_u *sfname, buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009973{
9974 AutoPat *ap;
9975 char_u *fname;
9976 char_u *tail = gettail(sfname);
9977 int retval = FALSE;
9978
9979 fname = FullName_save(sfname, FALSE);
9980 if (fname == NULL)
9981 return FALSE;
9982
9983#ifdef BACKSLASH_IN_FILENAME
9984 /*
9985 * Replace all backslashes with forward slashes. This makes the
9986 * autocommand patterns portable between Unix and MS-DOS.
9987 */
9988 sfname = vim_strsave(sfname);
9989 if (sfname != NULL)
9990 forward_slash(sfname);
9991 forward_slash(fname);
9992#endif
9993
9994 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
9995 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009996 && (ap->buflocal_nr == 0
Bram Moolenaardffa5b82014-11-19 16:38:07 +01009997 ? match_file_pat(NULL, &ap->reg_prog,
Bram Moolenaar748bf032005-02-02 23:04:36 +00009998 fname, sfname, tail, ap->allow_dirs)
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009999 : buf != NULL && ap->buflocal_nr == buf->b_fnum
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010000 ))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010001 {
10002 retval = TRUE;
10003 break;
10004 }
10005
10006 vim_free(fname);
10007#ifdef BACKSLASH_IN_FILENAME
10008 vim_free(sfname);
10009#endif
10010
10011 return retval;
10012}
10013
10014#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
10015/*
10016 * Function given to ExpandGeneric() to obtain the list of autocommand group
10017 * names.
10018 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010019 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010020get_augroup_name(expand_T *xp UNUSED, int idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010021{
10022 if (idx == augroups.ga_len) /* add "END" add the end */
10023 return (char_u *)"END";
10024 if (idx >= augroups.ga_len) /* end of list */
10025 return NULL;
Bram Moolenaarb62cc362016-09-03 16:43:53 +020010026 if (AUGROUP_NAME(idx) == NULL || AUGROUP_NAME(idx) == get_deleted_augroup())
Bram Moolenaarf2c4c392016-07-29 20:50:24 +020010027 /* skip deleted entries */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010028 return (char_u *)"";
10029 return AUGROUP_NAME(idx); /* return a name */
10030}
10031
10032static int include_groups = FALSE;
10033
10034 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010035set_context_in_autocmd(
10036 expand_T *xp,
10037 char_u *arg,
10038 int doautocmd) /* TRUE for :doauto*, FALSE for :autocmd */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010039{
10040 char_u *p;
10041 int group;
10042
10043 /* check for a group name, skip it if present */
10044 include_groups = FALSE;
10045 p = arg;
10046 group = au_get_grouparg(&arg);
10047 if (group == AUGROUP_ERROR)
10048 return NULL;
10049 /* If there only is a group name that's what we expand. */
Bram Moolenaar1c465442017-03-12 20:10:05 +010010050 if (*arg == NUL && group != AUGROUP_ALL && !VIM_ISWHITE(arg[-1]))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010051 {
10052 arg = p;
10053 group = AUGROUP_ALL;
10054 }
10055
10056 /* skip over event name */
Bram Moolenaar1c465442017-03-12 20:10:05 +010010057 for (p = arg; *p != NUL && !VIM_ISWHITE(*p); ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010058 if (*p == ',')
10059 arg = p + 1;
10060 if (*p == NUL)
10061 {
10062 if (group == AUGROUP_ALL)
10063 include_groups = TRUE;
10064 xp->xp_context = EXPAND_EVENTS; /* expand event name */
10065 xp->xp_pattern = arg;
10066 return NULL;
10067 }
10068
10069 /* skip over pattern */
10070 arg = skipwhite(p);
Bram Moolenaar1c465442017-03-12 20:10:05 +010010071 while (*arg && (!VIM_ISWHITE(*arg) || arg[-1] == '\\'))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010072 arg++;
10073 if (*arg)
10074 return arg; /* expand (next) command */
10075
10076 if (doautocmd)
10077 xp->xp_context = EXPAND_FILES; /* expand file names */
10078 else
10079 xp->xp_context = EXPAND_NOTHING; /* pattern is not expanded */
10080 return NULL;
10081}
10082
10083/*
10084 * Function given to ExpandGeneric() to obtain the list of event names.
10085 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010086 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010087get_event_name(expand_T *xp UNUSED, int idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010088{
10089 if (idx < augroups.ga_len) /* First list group names, if wanted */
10090 {
Bram Moolenaarf2c4c392016-07-29 20:50:24 +020010091 if (!include_groups || AUGROUP_NAME(idx) == NULL
Bram Moolenaarb62cc362016-09-03 16:43:53 +020010092 || AUGROUP_NAME(idx) == get_deleted_augroup())
Bram Moolenaar071d4272004-06-13 20:20:40 +000010093 return (char_u *)""; /* skip deleted entries */
10094 return AUGROUP_NAME(idx); /* return a name */
10095 }
10096 return (char_u *)event_names[idx - augroups.ga_len].name;
10097}
10098
10099#endif /* FEAT_CMDL_COMPL */
10100
10101/*
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010102 * Return TRUE if autocmd is supported.
10103 */
10104 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010105autocmd_supported(char_u *name)
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010106{
10107 char_u *p;
10108
10109 return (event_name2nr(name, &p) != NUM_EVENTS);
10110}
10111
10112/*
Bram Moolenaar195d6352005-12-19 22:08:24 +000010113 * Return TRUE if an autocommand is defined for a group, event and
10114 * pattern: The group can be omitted to accept any group. "event" and "pattern"
10115 * can be NULL to accept any event and pattern. "pattern" can be NULL to accept
10116 * any pattern. Buffer-local patterns <buffer> or <buffer=N> are accepted.
10117 * Used for:
10118 * exists("#Group") or
10119 * exists("#Group#Event") or
10120 * exists("#Group#Event#pat") or
10121 * exists("#Event") or
10122 * exists("#Event#pat")
Bram Moolenaar071d4272004-06-13 20:20:40 +000010123 */
10124 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010125au_exists(char_u *arg)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010126{
Bram Moolenaar195d6352005-12-19 22:08:24 +000010127 char_u *arg_save;
10128 char_u *pattern = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010129 char_u *event_name;
10130 char_u *p;
Bram Moolenaar754b5602006-02-09 23:53:20 +000010131 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010132 AutoPat *ap;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010133 buf_T *buflocal_buf = NULL;
Bram Moolenaar195d6352005-12-19 22:08:24 +000010134 int group;
10135 int retval = FALSE;
10136
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010137 /* Make a copy so that we can change the '#' chars to a NUL. */
Bram Moolenaar195d6352005-12-19 22:08:24 +000010138 arg_save = vim_strsave(arg);
10139 if (arg_save == NULL)
10140 return FALSE;
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010141 p = vim_strchr(arg_save, '#');
Bram Moolenaar195d6352005-12-19 22:08:24 +000010142 if (p != NULL)
10143 *p++ = NUL;
10144
10145 /* First, look for an autocmd group name */
10146 group = au_find_group(arg_save);
10147 if (group == AUGROUP_ERROR)
10148 {
10149 /* Didn't match a group name, assume the first argument is an event. */
10150 group = AUGROUP_ALL;
10151 event_name = arg_save;
10152 }
10153 else
10154 {
10155 if (p == NULL)
10156 {
10157 /* "Group": group name is present and it's recognized */
10158 retval = TRUE;
10159 goto theend;
10160 }
10161
10162 /* Must be "Group#Event" or "Group#Event#pat". */
10163 event_name = p;
10164 p = vim_strchr(event_name, '#');
10165 if (p != NULL)
10166 *p++ = NUL; /* "Group#Event#pat" */
10167 }
10168
10169 pattern = p; /* "pattern" is NULL when there is no pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010170
10171 /* find the index (enum) for the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010172 event = event_name2nr(event_name, &p);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010173
10174 /* return FALSE if the event name is not recognized */
Bram Moolenaar195d6352005-12-19 22:08:24 +000010175 if (event == NUM_EVENTS)
10176 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010177
10178 /* Find the first autocommand for this event.
10179 * If there isn't any, return FALSE;
10180 * If there is one and no pattern given, return TRUE; */
10181 ap = first_autopat[(int)event];
10182 if (ap == NULL)
Bram Moolenaar195d6352005-12-19 22:08:24 +000010183 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010184
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010185 /* if pattern is "<buffer>", special handling is needed which uses curbuf */
10186 /* for pattern "<buffer=N>, fnamecmp() will work fine */
Bram Moolenaar5b7880d2009-09-11 15:24:31 +000010187 if (pattern != NULL && STRICMP(pattern, "<buffer>") == 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010188 buflocal_buf = curbuf;
10189
Bram Moolenaar071d4272004-06-13 20:20:40 +000010190 /* Check if there is an autocommand with the given pattern. */
10191 for ( ; ap != NULL; ap = ap->next)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010192 /* only use a pattern when it has not been removed and has commands. */
10193 /* For buffer-local autocommands, fnamecmp() works fine. */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010194 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaar195d6352005-12-19 22:08:24 +000010195 && (group == AUGROUP_ALL || ap->group == group)
Bram Moolenaar5b7880d2009-09-11 15:24:31 +000010196 && (pattern == NULL
10197 || (buflocal_buf == NULL
10198 ? fnamecmp(ap->pat, pattern) == 0
10199 : ap->buflocal_nr == buflocal_buf->b_fnum)))
Bram Moolenaar195d6352005-12-19 22:08:24 +000010200 {
10201 retval = TRUE;
10202 break;
10203 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010204
Bram Moolenaar195d6352005-12-19 22:08:24 +000010205theend:
10206 vim_free(arg_save);
10207 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010208}
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010209
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010210#else /* FEAT_AUTOCMD */
10211
10212/*
10213 * Prepare for executing commands for (hidden) buffer "buf".
10214 * This is the non-autocommand version, it simply saves "curbuf" and sets
10215 * "curbuf" and "curwin" to match "buf".
10216 */
10217 void
Bram Moolenaard14e00e2016-01-31 17:30:51 +010010218aucmd_prepbuf(
10219 aco_save_T *aco, /* structure to save values in */
10220 buf_T *buf) /* new curbuf */
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010221{
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010222 aco->save_curbuf = curbuf;
10223 --curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010224 curbuf = buf;
10225 curwin->w_buffer = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010226 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010227}
10228
10229/*
10230 * Restore after executing commands for a (hidden) buffer.
10231 * This is the non-autocommand version.
10232 */
10233 void
Bram Moolenaard14e00e2016-01-31 17:30:51 +010010234aucmd_restbuf(
10235 aco_save_T *aco) /* structure holding saved values */
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010236{
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010237 --curbuf->b_nwindows;
10238 curbuf = aco->save_curbuf;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010239 curwin->w_buffer = curbuf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010240 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010241}
10242
Bram Moolenaar071d4272004-06-13 20:20:40 +000010243#endif /* FEAT_AUTOCMD */
10244
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010245
Bram Moolenaar071d4272004-06-13 20:20:40 +000010246#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN) || defined(PROTO)
10247/*
Bram Moolenaar748bf032005-02-02 23:04:36 +000010248 * Try matching a filename with a "pattern" ("prog" is NULL), or use the
10249 * precompiled regprog "prog" ("pattern" is NULL). That avoids calling
10250 * vim_regcomp() often.
Bram Moolenaar071d4272004-06-13 20:20:40 +000010251 * Used for autocommands and 'wildignore'.
10252 * Returns TRUE if there is a match, FALSE otherwise.
10253 */
Bram Moolenaardffa5b82014-11-19 16:38:07 +010010254 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010255match_file_pat(
10256 char_u *pattern, /* pattern to match with */
10257 regprog_T **prog, /* pre-compiled regprog or NULL */
10258 char_u *fname, /* full path of file name */
10259 char_u *sfname, /* short file name or NULL */
10260 char_u *tail, /* tail of path */
10261 int allow_dirs) /* allow matching with dir */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010262{
10263 regmatch_T regmatch;
10264 int result = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010265
Bram Moolenaar71afbfe2013-03-19 16:49:16 +010010266 regmatch.rm_ic = p_fic; /* ignore case if 'fileignorecase' is set */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010267 if (prog != NULL)
10268 regmatch.regprog = *prog;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010269 else
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010270 regmatch.regprog = vim_regcomp(pattern, RE_MAGIC);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010271
10272 /*
10273 * Try for a match with the pattern with:
10274 * 1. the full file name, when the pattern has a '/'.
10275 * 2. the short file name, when the pattern has a '/'.
10276 * 3. the tail of the file name, when the pattern has no '/'.
10277 */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010278 if (regmatch.regprog != NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +000010279 && ((allow_dirs
10280 && (vim_regexec(&regmatch, fname, (colnr_T)0)
10281 || (sfname != NULL
10282 && vim_regexec(&regmatch, sfname, (colnr_T)0))))
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010283 || (!allow_dirs && vim_regexec(&regmatch, tail, (colnr_T)0))))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010284 result = TRUE;
10285
Bram Moolenaardffa5b82014-11-19 16:38:07 +010010286 if (prog != NULL)
10287 *prog = regmatch.regprog;
10288 else
Bram Moolenaar473de612013-06-08 18:19:48 +020010289 vim_regfree(regmatch.regprog);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010290 return result;
10291}
10292#endif
10293
10294#if defined(FEAT_WILDIGN) || defined(PROTO)
10295/*
10296 * Return TRUE if a file matches with a pattern in "list".
10297 * "list" is a comma-separated list of patterns, like 'wildignore'.
10298 * "sfname" is the short file name or NULL, "ffname" the long file name.
10299 */
10300 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010301match_file_list(char_u *list, char_u *sfname, char_u *ffname)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010302{
10303 char_u buf[100];
10304 char_u *tail;
10305 char_u *regpat;
10306 char allow_dirs;
10307 int match;
10308 char_u *p;
10309
10310 tail = gettail(sfname);
10311
10312 /* try all patterns in 'wildignore' */
10313 p = list;
10314 while (*p)
10315 {
10316 copy_option_part(&p, buf, 100, ",");
10317 regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, FALSE);
10318 if (regpat == NULL)
10319 break;
Bram Moolenaar748bf032005-02-02 23:04:36 +000010320 match = match_file_pat(regpat, NULL, ffname, sfname,
10321 tail, (int)allow_dirs);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010322 vim_free(regpat);
10323 if (match)
10324 return TRUE;
10325 }
10326 return FALSE;
10327}
10328#endif
10329
10330/*
10331 * Convert the given pattern "pat" which has shell style wildcards in it, into
10332 * a regular expression, and return the result in allocated memory. If there
10333 * is a directory path separator to be matched, then TRUE is put in
10334 * allow_dirs, otherwise FALSE is put there -- webb.
10335 * Handle backslashes before special characters, like "\*" and "\ ".
10336 *
Bram Moolenaar071d4272004-06-13 20:20:40 +000010337 * Returns NULL when out of memory.
10338 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010339 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010340file_pat_to_reg_pat(
10341 char_u *pat,
10342 char_u *pat_end, /* first char after pattern or NULL */
10343 char *allow_dirs, /* Result passed back out in here */
10344 int no_bslash UNUSED) /* Don't use a backward slash as pathsep */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010345{
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010346 int size = 2; /* '^' at start, '$' at end */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010347 char_u *endp;
10348 char_u *reg_pat;
10349 char_u *p;
10350 int i;
10351 int nested = 0;
10352 int add_dollar = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010353
10354 if (allow_dirs != NULL)
10355 *allow_dirs = FALSE;
10356 if (pat_end == NULL)
10357 pat_end = pat + STRLEN(pat);
10358
Bram Moolenaar071d4272004-06-13 20:20:40 +000010359 for (p = pat; p < pat_end; p++)
10360 {
10361 switch (*p)
10362 {
10363 case '*':
10364 case '.':
10365 case ',':
10366 case '{':
10367 case '}':
10368 case '~':
10369 size += 2; /* extra backslash */
10370 break;
10371#ifdef BACKSLASH_IN_FILENAME
10372 case '\\':
10373 case '/':
10374 size += 4; /* could become "[\/]" */
10375 break;
10376#endif
10377 default:
10378 size++;
Bram Moolenaar2288afe2015-08-11 16:20:05 +020010379# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010380 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010381 {
10382 ++p;
10383 ++size;
10384 }
10385# endif
10386 break;
10387 }
10388 }
10389 reg_pat = alloc(size + 1);
10390 if (reg_pat == NULL)
10391 return NULL;
10392
Bram Moolenaar071d4272004-06-13 20:20:40 +000010393 i = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010394
10395 if (pat[0] == '*')
10396 while (pat[0] == '*' && pat < pat_end - 1)
10397 pat++;
10398 else
10399 reg_pat[i++] = '^';
10400 endp = pat_end - 1;
Bram Moolenaar8fee8782015-08-11 18:45:48 +020010401 if (endp >= pat && *endp == '*')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010402 {
10403 while (endp - pat > 0 && *endp == '*')
10404 endp--;
10405 add_dollar = FALSE;
10406 }
10407 for (p = pat; *p && nested >= 0 && p <= endp; p++)
10408 {
10409 switch (*p)
10410 {
10411 case '*':
10412 reg_pat[i++] = '.';
10413 reg_pat[i++] = '*';
Bram Moolenaar02743632005-07-25 20:42:36 +000010414 while (p[1] == '*') /* "**" matches like "*" */
10415 ++p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010416 break;
10417 case '.':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010418 case '~':
10419 reg_pat[i++] = '\\';
10420 reg_pat[i++] = *p;
10421 break;
10422 case '?':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010423 reg_pat[i++] = '.';
10424 break;
10425 case '\\':
10426 if (p[1] == NUL)
10427 break;
10428#ifdef BACKSLASH_IN_FILENAME
10429 if (!no_bslash)
10430 {
10431 /* translate:
10432 * "\x" to "\\x" e.g., "dir\file"
10433 * "\*" to "\\.*" e.g., "dir\*.c"
10434 * "\?" to "\\." e.g., "dir\??.c"
10435 * "\+" to "\+" e.g., "fileX\+.c"
10436 */
10437 if ((vim_isfilec(p[1]) || p[1] == '*' || p[1] == '?')
10438 && p[1] != '+')
10439 {
10440 reg_pat[i++] = '[';
10441 reg_pat[i++] = '\\';
10442 reg_pat[i++] = '/';
10443 reg_pat[i++] = ']';
10444 if (allow_dirs != NULL)
10445 *allow_dirs = TRUE;
10446 break;
10447 }
10448 }
10449#endif
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010450 /* Undo escaping from ExpandEscape():
10451 * foo\?bar -> foo?bar
10452 * foo\%bar -> foo%bar
10453 * foo\,bar -> foo,bar
10454 * foo\ bar -> foo bar
10455 * Don't unescape \, * and others that are also special in a
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010456 * regexp.
10457 * An escaped { must be unescaped since we use magic not
Bram Moolenaara946afe2013-08-02 15:22:39 +020010458 * verymagic. Use "\\\{n,m\}"" to get "\{n,m}".
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010459 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010460 if (*++p == '?'
10461#ifdef BACKSLASH_IN_FILENAME
10462 && no_bslash
10463#endif
10464 )
10465 reg_pat[i++] = '?';
10466 else
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010467 if (*p == ',' || *p == '%' || *p == '#'
Bram Moolenaar2288afe2015-08-11 16:20:05 +020010468 || vim_isspace(*p) || *p == '{' || *p == '}')
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010469 reg_pat[i++] = *p;
Bram Moolenaara946afe2013-08-02 15:22:39 +020010470 else if (*p == '\\' && p[1] == '\\' && p[2] == '{')
10471 {
10472 reg_pat[i++] = '\\';
10473 reg_pat[i++] = '{';
10474 p += 2;
10475 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010476 else
10477 {
10478 if (allow_dirs != NULL && vim_ispathsep(*p)
10479#ifdef BACKSLASH_IN_FILENAME
10480 && (!no_bslash || *p != '\\')
10481#endif
10482 )
10483 *allow_dirs = TRUE;
10484 reg_pat[i++] = '\\';
10485 reg_pat[i++] = *p;
10486 }
10487 break;
10488#ifdef BACKSLASH_IN_FILENAME
10489 case '/':
10490 reg_pat[i++] = '[';
10491 reg_pat[i++] = '\\';
10492 reg_pat[i++] = '/';
10493 reg_pat[i++] = ']';
10494 if (allow_dirs != NULL)
10495 *allow_dirs = TRUE;
10496 break;
10497#endif
10498 case '{':
10499 reg_pat[i++] = '\\';
10500 reg_pat[i++] = '(';
10501 nested++;
10502 break;
10503 case '}':
10504 reg_pat[i++] = '\\';
10505 reg_pat[i++] = ')';
10506 --nested;
10507 break;
10508 case ',':
10509 if (nested)
10510 {
10511 reg_pat[i++] = '\\';
10512 reg_pat[i++] = '|';
10513 }
10514 else
10515 reg_pat[i++] = ',';
10516 break;
10517 default:
10518# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010519 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010520 reg_pat[i++] = *p++;
10521 else
10522# endif
10523 if (allow_dirs != NULL && vim_ispathsep(*p))
10524 *allow_dirs = TRUE;
10525 reg_pat[i++] = *p;
10526 break;
10527 }
10528 }
10529 if (add_dollar)
10530 reg_pat[i++] = '$';
10531 reg_pat[i] = NUL;
10532 if (nested != 0)
10533 {
10534 if (nested < 0)
10535 EMSG(_("E219: Missing {."));
10536 else
10537 EMSG(_("E220: Missing }."));
10538 vim_free(reg_pat);
10539 reg_pat = NULL;
10540 }
10541 return reg_pat;
10542}
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010543
10544#if defined(EINTR) || defined(PROTO)
10545/*
10546 * Version of read() that retries when interrupted by EINTR (possibly
10547 * by a SIGWINCH).
10548 */
10549 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010550read_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010551{
10552 long ret;
10553
10554 for (;;)
10555 {
10556 ret = vim_read(fd, buf, bufsize);
10557 if (ret >= 0 || errno != EINTR)
10558 break;
10559 }
10560 return ret;
10561}
10562
10563/*
10564 * Version of write() that retries when interrupted by EINTR (possibly
10565 * by a SIGWINCH).
10566 */
10567 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010568write_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010569{
10570 long ret = 0;
10571 long wlen;
10572
10573 /* Repeat the write() so long it didn't fail, other than being interrupted
10574 * by a signal. */
10575 while (ret < (long)bufsize)
10576 {
Bram Moolenaar9c263032010-12-17 18:06:06 +010010577 wlen = vim_write(fd, (char *)buf + ret, bufsize - ret);
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010578 if (wlen < 0)
10579 {
10580 if (errno != EINTR)
10581 break;
10582 }
10583 else
10584 ret += wlen;
10585 }
10586 return ret;
10587}
10588#endif