blob: d991822c3431a68df34e6c7b9127b0b2db1a1692 [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;
3866#endif
3867
3868 copybuf = alloc(BUFSIZE + 1);
3869 if (copybuf == NULL)
3870 {
3871 some_error = TRUE; /* out of memory */
3872 goto nobackup;
3873 }
3874
3875 /*
3876 * Try to make the backup in each directory in the 'bdir' option.
3877 *
3878 * Unix semantics has it, that we may have a writable file,
3879 * that cannot be recreated with a simple open(..., O_CREAT, ) e.g:
3880 * - the directory is not writable,
3881 * - the file may be a symbolic link,
3882 * - the file may belong to another user/group, etc.
3883 *
3884 * For these reasons, the existing writable file must be truncated
3885 * and reused. Creation of a backup COPY will be attempted.
3886 */
3887 dirp = p_bdir;
3888 while (*dirp)
3889 {
3890#ifdef UNIX
3891 st_new.st_ino = 0;
3892 st_new.st_dev = 0;
3893 st_new.st_gid = 0;
3894#endif
3895
3896 /*
3897 * Isolate one directory name, using an entry in 'bdir'.
3898 */
3899 (void)copy_option_part(&dirp, copybuf, BUFSIZE, ",");
3900 rootname = get_file_in_dir(fname, copybuf);
3901 if (rootname == NULL)
3902 {
3903 some_error = TRUE; /* out of memory */
3904 goto nobackup;
3905 }
3906
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003907#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003908 did_set_shortname = FALSE;
3909#endif
3910
3911 /*
3912 * May try twice if 'shortname' not set.
3913 */
3914 for (;;)
3915 {
3916 /*
3917 * Make backup file name.
3918 */
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003919 backup = buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003920 rootname, backup_ext, FALSE);
3921 if (backup == NULL)
3922 {
3923 vim_free(rootname);
3924 some_error = TRUE; /* out of memory */
3925 goto nobackup;
3926 }
3927
3928 /*
3929 * Check if backup file already exists.
3930 */
3931 if (mch_stat((char *)backup, &st_new) >= 0)
3932 {
3933#ifdef UNIX
3934 /*
3935 * Check if backup file is same as original file.
3936 * May happen when modname() gave the same file back.
3937 * E.g. silly link, or file name-length reached.
3938 * If we don't check here, we either ruin the file
3939 * when copying or erase it after writing. jw.
3940 */
3941 if (st_new.st_dev == st_old.st_dev
3942 && st_new.st_ino == st_old.st_ino)
3943 {
3944 vim_free(backup);
3945 backup = NULL; /* no backup file to delete */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003946 /*
3947 * may try again with 'shortname' set
3948 */
3949 if (!(buf->b_shortname || buf->b_p_sn))
3950 {
3951 buf->b_shortname = TRUE;
3952 did_set_shortname = TRUE;
3953 continue;
3954 }
3955 /* setting shortname didn't help */
3956 if (did_set_shortname)
3957 buf->b_shortname = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003958 break;
3959 }
3960#endif
3961
3962 /*
3963 * If we are not going to keep the backup file, don't
3964 * delete an existing one, try to use another name.
3965 * Change one character, just before the extension.
3966 */
3967 if (!p_bk)
3968 {
3969 wp = backup + STRLEN(backup) - 1
3970 - STRLEN(backup_ext);
3971 if (wp < backup) /* empty file name ??? */
3972 wp = backup;
3973 *wp = 'z';
3974 while (*wp > 'a'
3975 && mch_stat((char *)backup, &st_new) >= 0)
3976 --*wp;
3977 /* They all exist??? Must be something wrong. */
3978 if (*wp == 'a')
3979 {
3980 vim_free(backup);
3981 backup = NULL;
3982 }
3983 }
3984 }
3985 break;
3986 }
3987 vim_free(rootname);
3988
3989 /*
3990 * Try to create the backup file
3991 */
3992 if (backup != NULL)
3993 {
3994 /* remove old backup, if present */
3995 mch_remove(backup);
3996 /* Open with O_EXCL to avoid the file being created while
3997 * we were sleeping (symlink hacker attack?) */
3998 bfd = mch_open((char *)backup,
Bram Moolenaara5792f52005-11-23 21:25:05 +00003999 O_WRONLY|O_CREAT|O_EXTRA|O_EXCL|O_NOFOLLOW,
4000 perm & 0777);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004001 if (bfd < 0)
4002 {
4003 vim_free(backup);
4004 backup = NULL;
4005 }
4006 else
4007 {
4008 /* set file protection same as original file, but
4009 * strip s-bit */
4010 (void)mch_setperm(backup, perm & 0777);
4011
4012#ifdef UNIX
4013 /*
4014 * Try to set the group of the backup same as the
4015 * original file. If this fails, set the protection
4016 * bits for the group same as the protection bits for
4017 * others.
4018 */
Bram Moolenaara5792f52005-11-23 21:25:05 +00004019 if (st_new.st_gid != st_old.st_gid
Bram Moolenaar071d4272004-06-13 20:20:40 +00004020# ifdef HAVE_FCHOWN /* sequent-ptx lacks fchown() */
Bram Moolenaara5792f52005-11-23 21:25:05 +00004021 && fchown(bfd, (uid_t)-1, st_old.st_gid) != 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00004022# endif
4023 )
4024 mch_setperm(backup,
4025 (perm & 0707) | ((perm & 07) << 3));
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004026# if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004027 mch_copy_sec(fname, backup);
4028# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004029#endif
4030
4031 /*
4032 * copy the file.
4033 */
4034 write_info.bw_fd = bfd;
4035 write_info.bw_buf = copybuf;
4036#ifdef HAS_BW_FLAGS
4037 write_info.bw_flags = FIO_NOCONVERT;
4038#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004039 while ((write_info.bw_len = read_eintr(fd, copybuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004040 BUFSIZE)) > 0)
4041 {
4042 if (buf_write_bytes(&write_info) == FAIL)
4043 {
4044 errmsg = (char_u *)_("E506: Can't write to backup file (add ! to override)");
4045 break;
4046 }
4047 ui_breakcheck();
4048 if (got_int)
4049 {
4050 errmsg = (char_u *)_(e_interr);
4051 break;
4052 }
4053 }
4054
4055 if (close(bfd) < 0 && errmsg == NULL)
4056 errmsg = (char_u *)_("E507: Close error for backup file (add ! to override)");
4057 if (write_info.bw_len < 0)
4058 errmsg = (char_u *)_("E508: Can't read file for backup (add ! to override)");
4059#ifdef UNIX
4060 set_file_time(backup, st_old.st_atime, st_old.st_mtime);
4061#endif
4062#ifdef HAVE_ACL
4063 mch_set_acl(backup, acl);
4064#endif
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004065#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004066 mch_copy_sec(fname, backup);
4067#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004068 break;
4069 }
4070 }
4071 }
4072 nobackup:
4073 close(fd); /* ignore errors for closing read file */
4074 vim_free(copybuf);
4075
4076 if (backup == NULL && errmsg == NULL)
4077 errmsg = (char_u *)_("E509: Cannot create backup file (add ! to override)");
4078 /* ignore errors when forceit is TRUE */
4079 if ((some_error || errmsg != NULL) && !forceit)
4080 {
4081 retval = FAIL;
4082 goto fail;
4083 }
4084 errmsg = NULL;
4085 }
4086 else
4087 {
4088 char_u *dirp;
4089 char_u *p;
4090 char_u *rootname;
4091
4092 /*
4093 * Make a backup by renaming the original file.
4094 */
4095 /*
4096 * If 'cpoptions' includes the "W" flag, we don't want to
4097 * overwrite a read-only file. But rename may be possible
4098 * anyway, thus we need an extra check here.
4099 */
4100 if (file_readonly && vim_strchr(p_cpo, CPO_FWRITE) != NULL)
4101 {
4102 errnum = (char_u *)"E504: ";
4103 errmsg = (char_u *)_(err_readonly);
4104 goto fail;
4105 }
4106
4107 /*
4108 *
4109 * Form the backup file name - change path/fo.o.h to
4110 * path/fo.o.h.bak Try all directories in 'backupdir', first one
4111 * that works is used.
4112 */
4113 dirp = p_bdir;
4114 while (*dirp)
4115 {
4116 /*
4117 * Isolate one directory name and make the backup file name.
4118 */
4119 (void)copy_option_part(&dirp, IObuff, IOSIZE, ",");
4120 rootname = get_file_in_dir(fname, IObuff);
4121 if (rootname == NULL)
4122 backup = NULL;
4123 else
4124 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01004125 backup = buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00004126 rootname, backup_ext, FALSE);
4127 vim_free(rootname);
4128 }
4129
4130 if (backup != NULL)
4131 {
4132 /*
4133 * If we are not going to keep the backup file, don't
4134 * delete an existing one, try to use another name.
4135 * Change one character, just before the extension.
4136 */
4137 if (!p_bk && mch_getperm(backup) >= 0)
4138 {
4139 p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext);
4140 if (p < backup) /* empty file name ??? */
4141 p = backup;
4142 *p = 'z';
4143 while (*p > 'a' && mch_getperm(backup) >= 0)
4144 --*p;
4145 /* They all exist??? Must be something wrong! */
4146 if (*p == 'a')
4147 {
4148 vim_free(backup);
4149 backup = NULL;
4150 }
4151 }
4152 }
4153 if (backup != NULL)
4154 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004155 /*
Bram Moolenaarbfd8fc02005-09-20 23:22:24 +00004156 * Delete any existing backup and move the current version
4157 * to the backup. For safety, we don't remove the backup
4158 * until the write has finished successfully. And if the
4159 * 'backup' option is set, leave it around.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004160 */
4161 /*
4162 * If the renaming of the original file to the backup file
4163 * works, quit here.
4164 */
4165 if (vim_rename(fname, backup) == 0)
4166 break;
4167
4168 vim_free(backup); /* don't do the rename below */
4169 backup = NULL;
4170 }
4171 }
4172 if (backup == NULL && !forceit)
4173 {
4174 errmsg = (char_u *)_("E510: Can't make backup file (add ! to override)");
4175 goto fail;
4176 }
4177 }
4178 }
4179
Bram Moolenaar53076832015-12-31 19:53:21 +01004180#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004181 /* When using ":w!" and the file was read-only: make it writable */
4182 if (forceit && perm >= 0 && !(perm & 0200) && st_old.st_uid == getuid()
4183 && vim_strchr(p_cpo, CPO_FWRITE) == NULL)
4184 {
4185 perm |= 0200;
4186 (void)mch_setperm(fname, perm);
4187 made_writable = TRUE;
4188 }
4189#endif
4190
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004191 /* When using ":w!" and writing to the current file, 'readonly' makes no
Bram Moolenaar4399ef42005-02-12 14:29:27 +00004192 * sense, reset it, unless 'Z' appears in 'cpoptions'. */
4193 if (forceit && overwriting && vim_strchr(p_cpo, CPO_KEEPRO) == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004194 {
4195 buf->b_p_ro = FALSE;
4196#ifdef FEAT_TITLE
4197 need_maketitle = TRUE; /* set window title later */
4198#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004199 status_redraw_all(); /* redraw status lines later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004200 }
4201
4202 if (end > buf->b_ml.ml_line_count)
4203 end = buf->b_ml.ml_line_count;
4204 if (buf->b_ml.ml_flags & ML_EMPTY)
4205 start = end + 1;
4206
4207 /*
4208 * If the original file is being overwritten, there is a small chance that
4209 * we crash in the middle of writing. Therefore the file is preserved now.
4210 * This makes all block numbers positive so that recovery does not need
4211 * the original file.
4212 * Don't do this if there is a backup file and we are exiting.
4213 */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004214 if (reset_changed && !newfile && overwriting
Bram Moolenaar071d4272004-06-13 20:20:40 +00004215 && !(exiting && backup != NULL))
4216 {
4217 ml_preserve(buf, FALSE);
4218 if (got_int)
4219 {
4220 errmsg = (char_u *)_(e_interr);
4221 goto restore_backup;
4222 }
4223 }
4224
Bram Moolenaar071d4272004-06-13 20:20:40 +00004225#ifdef VMS
4226 vms_remove_version(fname); /* remove version */
4227#endif
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00004228 /* Default: write the file directly. May write to a temp file for
Bram Moolenaar071d4272004-06-13 20:20:40 +00004229 * multi-byte conversion. */
4230 wfname = fname;
4231
4232#ifdef FEAT_MBYTE
4233 /* Check for forced 'fileencoding' from "++opt=val" argument. */
4234 if (eap != NULL && eap->force_enc != 0)
4235 {
4236 fenc = eap->cmd + eap->force_enc;
4237 fenc = enc_canonize(fenc);
4238 fenc_tofree = fenc;
4239 }
4240 else
4241 fenc = buf->b_p_fenc;
4242
4243 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004244 * Check if the file needs to be converted.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004245 */
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004246 converted = need_conversion(fenc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004247
4248 /*
4249 * Check if UTF-8 to UCS-2/4 or Latin1 conversion needs to be done. Or
4250 * Latin1 to Unicode conversion. This is handled in buf_write_bytes().
4251 * Prepare the flags for it and allocate bw_conv_buf when needed.
4252 */
4253 if (converted && (enc_utf8 || STRCMP(p_enc, "latin1") == 0))
4254 {
4255 wb_flags = get_fio_flags(fenc);
4256 if (wb_flags & (FIO_UCS2 | FIO_UCS4 | FIO_UTF16 | FIO_UTF8))
4257 {
4258 /* Need to allocate a buffer to translate into. */
4259 if (wb_flags & (FIO_UCS2 | FIO_UTF16 | FIO_UTF8))
4260 write_info.bw_conv_buflen = bufsize * 2;
4261 else /* FIO_UCS4 */
4262 write_info.bw_conv_buflen = bufsize * 4;
4263 write_info.bw_conv_buf
4264 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4265 if (write_info.bw_conv_buf == NULL)
4266 end = 0;
4267 }
4268 }
4269
4270# ifdef WIN3264
4271 if (converted && wb_flags == 0 && (wb_flags = get_win_fio_flags(fenc)) != 0)
4272 {
4273 /* Convert UTF-8 -> UCS-2 and UCS-2 -> DBCS. Worst-case * 4: */
4274 write_info.bw_conv_buflen = bufsize * 4;
4275 write_info.bw_conv_buf
4276 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4277 if (write_info.bw_conv_buf == NULL)
4278 end = 0;
4279 }
4280# endif
4281
Bram Moolenaard0573012017-10-28 21:11:06 +02004282# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00004283 if (converted && wb_flags == 0 && (wb_flags = get_mac_fio_flags(fenc)) != 0)
4284 {
4285 write_info.bw_conv_buflen = bufsize * 3;
4286 write_info.bw_conv_buf
4287 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4288 if (write_info.bw_conv_buf == NULL)
4289 end = 0;
4290 }
4291# endif
4292
4293# if defined(FEAT_EVAL) || defined(USE_ICONV)
4294 if (converted && wb_flags == 0)
4295 {
4296# ifdef USE_ICONV
4297 /*
4298 * Use iconv() conversion when conversion is needed and it's not done
4299 * internally.
4300 */
4301 write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc,
4302 enc_utf8 ? (char_u *)"utf-8" : p_enc);
4303 if (write_info.bw_iconv_fd != (iconv_t)-1)
4304 {
4305 /* We're going to use iconv(), allocate a buffer to convert in. */
4306 write_info.bw_conv_buflen = bufsize * ICONV_MULT;
4307 write_info.bw_conv_buf
4308 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4309 if (write_info.bw_conv_buf == NULL)
4310 end = 0;
4311 write_info.bw_first = TRUE;
4312 }
4313# ifdef FEAT_EVAL
4314 else
4315# endif
4316# endif
4317
4318# ifdef FEAT_EVAL
4319 /*
4320 * When the file needs to be converted with 'charconvert' after
4321 * writing, write to a temp file instead and let the conversion
4322 * overwrite the original file.
4323 */
4324 if (*p_ccv != NUL)
4325 {
Bram Moolenaare5c421c2015-03-31 13:33:08 +02004326 wfname = vim_tempname('w', FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004327 if (wfname == NULL) /* Can't write without a tempfile! */
4328 {
4329 errmsg = (char_u *)_("E214: Can't find temp file for writing");
4330 goto restore_backup;
4331 }
4332 }
4333# endif
4334 }
4335# endif
4336 if (converted && wb_flags == 0
4337# ifdef USE_ICONV
4338 && write_info.bw_iconv_fd == (iconv_t)-1
4339# endif
4340# ifdef FEAT_EVAL
4341 && wfname == fname
4342# endif
4343 )
4344 {
4345 if (!forceit)
4346 {
4347 errmsg = (char_u *)_("E213: Cannot convert (add ! to write without conversion)");
4348 goto restore_backup;
4349 }
4350 notconverted = TRUE;
4351 }
4352#endif
4353
4354 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004355 * If conversion is taking place, we may first pretend to write and check
4356 * for conversion errors. Then loop again to write for real.
4357 * When not doing conversion this writes for real right away.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004358 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004359 for (checking_conversion = TRUE; ; checking_conversion = FALSE)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004360 {
4361 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004362 * There is no need to check conversion when:
4363 * - there is no conversion
4364 * - we make a backup file, that can be restored in case of conversion
4365 * failure.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004366 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004367#ifdef FEAT_MBYTE
4368 if (!converted || dobackup)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004369#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004370 checking_conversion = FALSE;
4371
4372 if (checking_conversion)
4373 {
4374 /* Make sure we don't write anything. */
4375 fd = -1;
4376 write_info.bw_fd = fd;
4377 }
4378 else
4379 {
4380 /*
4381 * Open the file "wfname" for writing.
4382 * We may try to open the file twice: If we can't write to the file
4383 * and forceit is TRUE we delete the existing file and try to
4384 * create a new one. If this still fails we may have lost the
4385 * original file! (this may happen when the user reached his
4386 * quotum for number of files).
4387 * Appending will fail if the file does not exist and forceit is
4388 * FALSE.
4389 */
4390 while ((fd = mch_open((char *)wfname, O_WRONLY | O_EXTRA | (append
4391 ? (forceit ? (O_APPEND | O_CREAT) : O_APPEND)
4392 : (O_CREAT | O_TRUNC))
4393 , perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004394 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004395 /*
4396 * A forced write will try to create a new file if the old one
4397 * is still readonly. This may also happen when the directory
4398 * is read-only. In that case the mch_remove() will fail.
4399 */
4400 if (errmsg == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004401 {
4402#ifdef UNIX
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004403 stat_T st;
4404
4405 /* Don't delete the file when it's a hard or symbolic link.
4406 */
4407 if ((!newfile && st_old.st_nlink > 1)
4408 || (mch_lstat((char *)fname, &st) == 0
4409 && (st.st_dev != st_old.st_dev
4410 || st.st_ino != st_old.st_ino)))
4411 errmsg = (char_u *)_("E166: Can't open linked file for writing");
4412 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004413#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004414 {
4415 errmsg = (char_u *)_("E212: Can't open file for writing");
4416 if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL
4417 && perm >= 0)
4418 {
4419#ifdef UNIX
4420 /* we write to the file, thus it should be marked
4421 writable after all */
4422 if (!(perm & 0200))
4423 made_writable = TRUE;
4424 perm |= 0200;
4425 if (st_old.st_uid != getuid()
4426 || st_old.st_gid != getgid())
4427 perm &= 0777;
4428#endif
4429 if (!append) /* don't remove when appending */
4430 mch_remove(wfname);
4431 continue;
4432 }
4433 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004434 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004435
4436restore_backup:
Bram Moolenaar071d4272004-06-13 20:20:40 +00004437 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004438 stat_T st;
4439
Bram Moolenaar071d4272004-06-13 20:20:40 +00004440 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004441 * If we failed to open the file, we don't need a backup.
4442 * Throw it away. If we moved or removed the original file
4443 * try to put the backup in its place.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004444 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004445 if (backup != NULL && wfname == fname)
4446 {
4447 if (backup_copy)
4448 {
4449 /*
4450 * There is a small chance that we removed the
4451 * original, try to move the copy in its place.
4452 * This may not work if the vim_rename() fails.
4453 * In that case we leave the copy around.
4454 */
4455 /* If file does not exist, put the copy in its
4456 * place */
4457 if (mch_stat((char *)fname, &st) < 0)
4458 vim_rename(backup, fname);
4459 /* if original file does exist throw away the copy
4460 */
4461 if (mch_stat((char *)fname, &st) >= 0)
4462 mch_remove(backup);
4463 }
4464 else
4465 {
4466 /* try to put the original file back */
4467 vim_rename(backup, fname);
4468 }
4469 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004470
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004471 /* if original file no longer exists give an extra warning
4472 */
4473 if (!newfile && mch_stat((char *)fname, &st) < 0)
4474 end = 0;
4475 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004476
4477#ifdef FEAT_MBYTE
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004478 if (wfname != fname)
4479 vim_free(wfname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004480#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004481 goto fail;
4482 }
4483 write_info.bw_fd = fd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004484
Bram Moolenaard0573012017-10-28 21:11:06 +02004485#if defined(WIN3264)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004486 if (backup != NULL && overwriting && !append)
4487 {
4488 if (backup_copy)
4489 (void)mch_copy_file_attribute(wfname, backup);
4490 else
4491 (void)mch_copy_file_attribute(backup, wfname);
4492 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004493
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004494 if (!overwriting && !append)
4495 {
4496 if (buf->b_ffname != NULL)
4497 (void)mch_copy_file_attribute(buf->b_ffname, wfname);
4498 /* Should copy resource fork */
4499 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004500#endif
4501
Bram Moolenaar071d4272004-06-13 20:20:40 +00004502#ifdef FEAT_CRYPT
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004503 if (*buf->b_p_key != NUL && !filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004504 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004505 char_u *header;
4506 int header_len;
4507
4508 buf->b_cryptstate = crypt_create_for_writing(
4509 crypt_get_method_nr(buf),
4510 buf->b_p_key, &header, &header_len);
4511 if (buf->b_cryptstate == NULL || header == NULL)
4512 end = 0;
4513 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004514 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004515 /* Write magic number, so that Vim knows how this file is
4516 * encrypted when reading it back. */
4517 write_info.bw_buf = header;
4518 write_info.bw_len = header_len;
4519 write_info.bw_flags = FIO_NOCONVERT;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004520 if (buf_write_bytes(&write_info) == FAIL)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004521 end = 0;
4522 wb_flags |= FIO_ENCRYPTED;
4523 vim_free(header);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004524 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004525 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004526#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004527 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004528 errmsg = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004529
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004530 write_info.bw_buf = buffer;
4531 nchars = 0;
4532
4533 /* use "++bin", "++nobin" or 'binary' */
4534 if (eap != NULL && eap->force_bin != 0)
4535 write_bin = (eap->force_bin == FORCE_BIN);
4536 else
4537 write_bin = buf->b_p_bin;
4538
4539#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004540 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004541 * The BOM is written just after the encryption magic number.
4542 * Skip it when appending and the file already existed, the BOM only
4543 * makes sense at the start of the file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004544 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004545 if (buf->b_p_bomb && !write_bin && (!append || perm < 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004546 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004547 write_info.bw_len = make_bom(buffer, fenc);
4548 if (write_info.bw_len > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004549 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004550 /* don't convert, do encryption */
4551 write_info.bw_flags = FIO_NOCONVERT | wb_flags;
4552 if (buf_write_bytes(&write_info) == FAIL)
4553 end = 0;
4554 else
4555 nchars += write_info.bw_len;
4556 }
4557 }
4558 write_info.bw_start_lnum = start;
4559#endif
4560
4561#ifdef FEAT_PERSISTENT_UNDO
4562 write_undo_file = (buf->b_p_udf
4563 && overwriting
4564 && !append
4565 && !filtering
4566 && reset_changed
4567 && !checking_conversion);
4568 if (write_undo_file)
4569 /* Prepare for computing the hash value of the text. */
4570 sha256_start(&sha_ctx);
4571#endif
4572
4573 write_info.bw_len = bufsize;
4574#ifdef HAS_BW_FLAGS
4575 write_info.bw_flags = wb_flags;
4576#endif
4577 fileformat = get_fileformat_force(buf, eap);
4578 s = buffer;
4579 len = 0;
4580 for (lnum = start; lnum <= end; ++lnum)
4581 {
4582 /*
4583 * The next while loop is done once for each character written.
4584 * Keep it fast!
4585 */
4586 ptr = ml_get_buf(buf, lnum, FALSE) - 1;
4587#ifdef FEAT_PERSISTENT_UNDO
4588 if (write_undo_file)
4589 sha256_update(&sha_ctx, ptr + 1,
4590 (UINT32_T)(STRLEN(ptr + 1) + 1));
4591#endif
4592 while ((c = *++ptr) != NUL)
4593 {
4594 if (c == NL)
4595 *s = NUL; /* replace newlines with NULs */
4596 else if (c == CAR && fileformat == EOL_MAC)
4597 *s = NL; /* Mac: replace CRs with NLs */
4598 else
4599 *s = c;
4600 ++s;
4601 if (++len != bufsize)
4602 continue;
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004603 if (buf_write_bytes(&write_info) == FAIL)
4604 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004605 end = 0; /* write error: break loop */
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004606 break;
4607 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004608 nchars += bufsize;
4609 s = buffer;
4610 len = 0;
4611#ifdef FEAT_MBYTE
4612 write_info.bw_start_lnum = lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004613#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004614 }
4615 /* write failed or last line has no EOL: stop here */
4616 if (end == 0
4617 || (lnum == end
4618 && (write_bin || !buf->b_p_fixeol)
4619 && (lnum == buf->b_no_eol_lnum
4620 || (lnum == buf->b_ml.ml_line_count
4621 && !buf->b_p_eol))))
4622 {
4623 ++lnum; /* written the line, count it */
4624 no_eol = TRUE;
4625 break;
4626 }
4627 if (fileformat == EOL_UNIX)
4628 *s++ = NL;
4629 else
4630 {
4631 *s++ = CAR; /* EOL_MAC or EOL_DOS: write CR */
4632 if (fileformat == EOL_DOS) /* write CR-NL */
4633 {
4634 if (++len == bufsize)
4635 {
4636 if (buf_write_bytes(&write_info) == FAIL)
4637 {
4638 end = 0; /* write error: break loop */
4639 break;
4640 }
4641 nchars += bufsize;
4642 s = buffer;
4643 len = 0;
4644 }
4645 *s++ = NL;
4646 }
4647 }
4648 if (++len == bufsize && end)
4649 {
4650 if (buf_write_bytes(&write_info) == FAIL)
4651 {
4652 end = 0; /* write error: break loop */
4653 break;
4654 }
4655 nchars += bufsize;
4656 s = buffer;
4657 len = 0;
4658
4659 ui_breakcheck();
4660 if (got_int)
4661 {
4662 end = 0; /* Interrupted, break loop */
4663 break;
4664 }
4665 }
4666#ifdef VMS
4667 /*
4668 * On VMS there is a problem: newlines get added when writing
4669 * blocks at a time. Fix it by writing a line at a time.
4670 * This is much slower!
4671 * Explanation: VAX/DECC RTL insists that records in some RMS
4672 * structures end with a newline (carriage return) character, and
4673 * if they don't it adds one.
4674 * With other RMS structures it works perfect without this fix.
4675 */
4676 if (buf->b_fab_rfm == FAB$C_VFC
4677 || ((buf->b_fab_rat & (FAB$M_FTN | FAB$M_CR)) != 0))
4678 {
4679 int b2write;
4680
4681 buf->b_fab_mrs = (buf->b_fab_mrs == 0
4682 ? MIN(4096, bufsize)
4683 : MIN(buf->b_fab_mrs, bufsize));
4684
4685 b2write = len;
4686 while (b2write > 0)
4687 {
4688 write_info.bw_len = MIN(b2write, buf->b_fab_mrs);
4689 if (buf_write_bytes(&write_info) == FAIL)
4690 {
4691 end = 0;
4692 break;
4693 }
4694 b2write -= MIN(b2write, buf->b_fab_mrs);
4695 }
4696 write_info.bw_len = bufsize;
4697 nchars += len;
4698 s = buffer;
4699 len = 0;
4700 }
4701#endif
4702 }
4703 if (len > 0 && end > 0)
4704 {
4705 write_info.bw_len = len;
4706 if (buf_write_bytes(&write_info) == FAIL)
4707 end = 0; /* write error */
4708 nchars += len;
4709 }
4710
4711 /* Stop when writing done or an error was encountered. */
4712 if (!checking_conversion || end == 0)
4713 break;
4714
4715 /* If no error happened until now, writing should be ok, so loop to
4716 * really write the buffer. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004717 }
4718
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004719 /* If we started writing, finish writing. Also when an error was
4720 * encountered. */
4721 if (!checking_conversion)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004722 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004723#if defined(UNIX) && defined(HAVE_FSYNC)
4724 /*
4725 * On many journalling file systems there is a bug that causes both the
4726 * original and the backup file to be lost when halting the system
4727 * right after writing the file. That's because only the meta-data is
4728 * journalled. Syncing the file slows down the system, but assures it
4729 * has been written to disk and we don't lose it.
4730 * For a device do try the fsync() but don't complain if it does not
4731 * work (could be a pipe).
4732 * If the 'fsync' option is FALSE, don't fsync(). Useful for laptops.
4733 */
4734 if (p_fs && fsync(fd) != 0 && !device)
4735 {
4736 errmsg = (char_u *)_("E667: Fsync failed");
4737 end = 0;
4738 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004739#endif
4740
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004741#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004742 /* Probably need to set the security context. */
4743 if (!backup_copy)
4744 mch_copy_sec(backup, wfname);
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004745#endif
4746
Bram Moolenaara5792f52005-11-23 21:25:05 +00004747#ifdef UNIX
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004748 /* When creating a new file, set its owner/group to that of the
4749 * original file. Get the new device and inode number. */
4750 if (backup != NULL && !backup_copy)
Bram Moolenaara5792f52005-11-23 21:25:05 +00004751 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004752# ifdef HAVE_FCHOWN
4753 stat_T st;
4754
4755 /* don't change the owner when it's already OK, some systems remove
4756 * permission or ACL stuff */
4757 if (mch_stat((char *)wfname, &st) < 0
4758 || st.st_uid != st_old.st_uid
4759 || st.st_gid != st_old.st_gid)
4760 {
4761 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
4762 if (perm >= 0) /* set permission again, may have changed */
4763 (void)mch_setperm(wfname, perm);
4764 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00004765# endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004766 buf_setino(buf);
4767 }
4768 else if (!buf->b_dev_valid)
4769 /* Set the inode when creating a new file. */
4770 buf_setino(buf);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004771#endif
4772
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004773 if (close(fd) != 0)
4774 {
4775 errmsg = (char_u *)_("E512: Close failed");
4776 end = 0;
4777 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004778
4779#ifdef UNIX
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004780 if (made_writable)
4781 perm &= ~0200; /* reset 'w' bit for security reasons */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004782#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004783 if (perm >= 0) /* set perm. of new file same as old file */
4784 (void)mch_setperm(wfname, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004785#ifdef HAVE_ACL
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004786 /*
4787 * Probably need to set the ACL before changing the user (can't set the
4788 * ACL on a file the user doesn't own).
4789 * On Solaris, with ZFS and the aclmode property set to "discard" (the
4790 * default), chmod() discards all part of a file's ACL that don't
4791 * represent the mode of the file. It's non-trivial for us to discover
4792 * whether we're in that situation, so we simply always re-set the ACL.
4793 */
Bram Moolenaarda412772016-07-14 20:37:07 +02004794# ifndef HAVE_SOLARIS_ZFS_ACL
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004795 if (!backup_copy)
Bram Moolenaarda412772016-07-14 20:37:07 +02004796# endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004797 mch_set_acl(wfname, acl);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004798#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004799#ifdef FEAT_CRYPT
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004800 if (buf->b_cryptstate != NULL)
4801 {
4802 crypt_free_state(buf->b_cryptstate);
4803 buf->b_cryptstate = NULL;
4804 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004805#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004806
Bram Moolenaar071d4272004-06-13 20:20:40 +00004807#if defined(FEAT_MBYTE) && defined(FEAT_EVAL)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004808 if (wfname != fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004809 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004810 /*
4811 * The file was written to a temp file, now it needs to be
4812 * converted with 'charconvert' to (overwrite) the output file.
4813 */
4814 if (end != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004815 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004816 if (eval_charconvert(enc_utf8 ? (char_u *)"utf-8" : p_enc,
4817 fenc, wfname, fname) == FAIL)
4818 {
4819 write_info.bw_conv_error = TRUE;
4820 end = 0;
4821 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004822 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004823 mch_remove(wfname);
4824 vim_free(wfname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004825 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004826#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004827 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004828
4829 if (end == 0)
4830 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004831 /*
4832 * Error encountered.
4833 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004834 if (errmsg == NULL)
4835 {
4836#ifdef FEAT_MBYTE
4837 if (write_info.bw_conv_error)
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004838 {
4839 if (write_info.bw_conv_error_lnum == 0)
4840 errmsg = (char_u *)_("E513: write error, conversion failed (make 'fenc' empty to override)");
4841 else
4842 {
4843 errmsg_allocated = TRUE;
4844 errmsg = alloc(300);
4845 vim_snprintf((char *)errmsg, 300, _("E513: write error, conversion failed in line %ld (make 'fenc' empty to override)"),
4846 (long)write_info.bw_conv_error_lnum);
4847 }
4848 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004849 else
4850#endif
4851 if (got_int)
4852 errmsg = (char_u *)_(e_interr);
4853 else
4854 errmsg = (char_u *)_("E514: write error (file system full?)");
4855 }
4856
4857 /*
4858 * If we have a backup file, try to put it in place of the new file,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004859 * because the new file is probably corrupt. This avoids losing the
Bram Moolenaar071d4272004-06-13 20:20:40 +00004860 * original file when trying to make a backup when writing the file a
4861 * second time.
4862 * When "backup_copy" is set we need to copy the backup over the new
4863 * file. Otherwise rename the backup file.
4864 * If this is OK, don't give the extra warning message.
4865 */
4866 if (backup != NULL)
4867 {
4868 if (backup_copy)
4869 {
4870 /* This may take a while, if we were interrupted let the user
4871 * know we got the message. */
4872 if (got_int)
4873 {
4874 MSG(_(e_interr));
4875 out_flush();
4876 }
4877 if ((fd = mch_open((char *)backup, O_RDONLY | O_EXTRA, 0)) >= 0)
4878 {
4879 if ((write_info.bw_fd = mch_open((char *)fname,
Bram Moolenaar9be038d2005-03-08 22:34:32 +00004880 O_WRONLY | O_CREAT | O_TRUNC | O_EXTRA,
4881 perm & 0777)) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004882 {
4883 /* copy the file. */
4884 write_info.bw_buf = smallbuf;
4885#ifdef HAS_BW_FLAGS
4886 write_info.bw_flags = FIO_NOCONVERT;
4887#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004888 while ((write_info.bw_len = read_eintr(fd, smallbuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004889 SMBUFSIZE)) > 0)
4890 if (buf_write_bytes(&write_info) == FAIL)
4891 break;
4892
4893 if (close(write_info.bw_fd) >= 0
4894 && write_info.bw_len == 0)
4895 end = 1; /* success */
4896 }
4897 close(fd); /* ignore errors for closing read file */
4898 }
4899 }
4900 else
4901 {
4902 if (vim_rename(backup, fname) == 0)
4903 end = 1;
4904 }
4905 }
4906 goto fail;
4907 }
4908
4909 lnum -= start; /* compute number of written lines */
4910 --no_wait_return; /* may wait for return now */
4911
4912#if !(defined(UNIX) || defined(VMS))
4913 fname = sfname; /* use shortname now, for the messages */
4914#endif
4915 if (!filtering)
4916 {
4917 msg_add_fname(buf, fname); /* put fname in IObuff with quotes */
4918 c = FALSE;
4919#ifdef FEAT_MBYTE
4920 if (write_info.bw_conv_error)
4921 {
4922 STRCAT(IObuff, _(" CONVERSION ERROR"));
4923 c = TRUE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004924 if (write_info.bw_conv_error_lnum != 0)
Bram Moolenaara800b422010-06-27 01:15:55 +02004925 vim_snprintf_add((char *)IObuff, IOSIZE, _(" in line %ld;"),
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004926 (long)write_info.bw_conv_error_lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004927 }
4928 else if (notconverted)
4929 {
4930 STRCAT(IObuff, _("[NOT converted]"));
4931 c = TRUE;
4932 }
4933 else if (converted)
4934 {
4935 STRCAT(IObuff, _("[converted]"));
4936 c = TRUE;
4937 }
4938#endif
4939 if (device)
4940 {
4941 STRCAT(IObuff, _("[Device]"));
4942 c = TRUE;
4943 }
4944 else if (newfile)
4945 {
4946 STRCAT(IObuff, shortmess(SHM_NEW) ? _("[New]") : _("[New File]"));
4947 c = TRUE;
4948 }
4949 if (no_eol)
4950 {
4951 msg_add_eol();
4952 c = TRUE;
4953 }
4954 /* may add [unix/dos/mac] */
4955 if (msg_add_fileformat(fileformat))
4956 c = TRUE;
4957#ifdef FEAT_CRYPT
4958 if (wb_flags & FIO_ENCRYPTED)
4959 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004960 crypt_append_msg(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004961 c = TRUE;
4962 }
4963#endif
4964 msg_add_lines(c, (long)lnum, nchars); /* add line/char count */
4965 if (!shortmess(SHM_WRITE))
4966 {
4967 if (append)
4968 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended"));
4969 else
4970 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written"));
4971 }
4972
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00004973 set_keep_msg(msg_trunc_attr(IObuff, FALSE, 0), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004974 }
4975
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004976 /* When written everything correctly: reset 'modified'. Unless not
4977 * writing to the original file and '+' is not in 'cpoptions'. */
Bram Moolenaar292ad192005-12-11 21:29:51 +00004978 if (reset_changed && whole && !append
Bram Moolenaar071d4272004-06-13 20:20:40 +00004979#ifdef FEAT_MBYTE
4980 && !write_info.bw_conv_error
4981#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004982 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL)
4983 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004984 {
4985 unchanged(buf, TRUE);
Bram Moolenaar086329d2014-10-31 19:51:36 +01004986#ifdef FEAT_AUTOCMD
Bram Moolenaar95c526e2017-02-25 14:59:34 +01004987 /* b:changedtick is always incremented in unchanged() but that
Bram Moolenaar086329d2014-10-31 19:51:36 +01004988 * should not trigger a TextChanged event. */
Bram Moolenaar95c526e2017-02-25 14:59:34 +01004989 if (last_changedtick + 1 == CHANGEDTICK(buf)
Bram Moolenaar086329d2014-10-31 19:51:36 +01004990 && last_changedtick_buf == buf)
Bram Moolenaar95c526e2017-02-25 14:59:34 +01004991 last_changedtick = CHANGEDTICK(buf);
Bram Moolenaar086329d2014-10-31 19:51:36 +01004992#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004993 u_unchanged(buf);
Bram Moolenaar730cde92010-06-27 05:18:54 +02004994 u_update_save_nr(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004995 }
4996
4997 /*
4998 * If written to the current file, update the timestamp of the swap file
4999 * and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
5000 */
5001 if (overwriting)
5002 {
5003 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00005004 if (append)
5005 buf->b_flags &= ~BF_NEW;
5006 else
5007 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005008 }
5009
5010 /*
5011 * If we kept a backup until now, and we are in patch mode, then we make
5012 * the backup file our 'original' file.
5013 */
5014 if (*p_pm && dobackup)
5015 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01005016 char *org = (char *)buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005017 fname, p_pm, FALSE);
5018
5019 if (backup != NULL)
5020 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02005021 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005022
5023 /*
5024 * If the original file does not exist yet
5025 * the current backup file becomes the original file
5026 */
5027 if (org == NULL)
5028 EMSG(_("E205: Patchmode: can't save original file"));
5029 else if (mch_stat(org, &st) < 0)
5030 {
5031 vim_rename(backup, (char_u *)org);
5032 vim_free(backup); /* don't delete the file */
5033 backup = NULL;
5034#ifdef UNIX
5035 set_file_time((char_u *)org, st_old.st_atime, st_old.st_mtime);
5036#endif
5037 }
5038 }
5039 /*
5040 * If there is no backup file, remember that a (new) file was
5041 * created.
5042 */
5043 else
5044 {
5045 int empty_fd;
5046
5047 if (org == NULL
Bram Moolenaara5792f52005-11-23 21:25:05 +00005048 || (empty_fd = mch_open(org,
5049 O_CREAT | O_EXTRA | O_EXCL | O_NOFOLLOW,
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00005050 perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005051 EMSG(_("E206: patchmode: can't touch empty original file"));
5052 else
5053 close(empty_fd);
5054 }
5055 if (org != NULL)
5056 {
5057 mch_setperm((char_u *)org, mch_getperm(fname) & 0777);
5058 vim_free(org);
5059 }
5060 }
5061
5062 /*
5063 * Remove the backup unless 'backup' option is set
5064 */
5065 if (!p_bk && backup != NULL && mch_remove(backup) != 0)
5066 EMSG(_("E207: Can't delete backup file"));
5067
5068#ifdef FEAT_SUN_WORKSHOP
5069 if (usingSunWorkShop)
5070 workshop_file_saved((char *) ffname);
5071#endif
5072
5073 goto nofail;
5074
5075 /*
5076 * Finish up. We get here either after failure or success.
5077 */
5078fail:
5079 --no_wait_return; /* may wait for return now */
5080nofail:
5081
5082 /* Done saving, we accept changed buffer warnings again */
5083 buf->b_saving = FALSE;
5084
5085 vim_free(backup);
5086 if (buffer != smallbuf)
5087 vim_free(buffer);
5088#ifdef FEAT_MBYTE
5089 vim_free(fenc_tofree);
5090 vim_free(write_info.bw_conv_buf);
5091# ifdef USE_ICONV
5092 if (write_info.bw_iconv_fd != (iconv_t)-1)
5093 {
5094 iconv_close(write_info.bw_iconv_fd);
5095 write_info.bw_iconv_fd = (iconv_t)-1;
5096 }
5097# endif
5098#endif
5099#ifdef HAVE_ACL
5100 mch_free_acl(acl);
5101#endif
5102
5103 if (errmsg != NULL)
5104 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005105 int numlen = errnum != NULL ? (int)STRLEN(errnum) : 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005106
Bram Moolenaar8820b482017-03-16 17:23:31 +01005107 attr = HL_ATTR(HLF_E); /* set highlight for error messages */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005108 msg_add_fname(buf,
5109#ifndef UNIX
5110 sfname
5111#else
5112 fname
5113#endif
5114 ); /* put file name in IObuff with quotes */
5115 if (STRLEN(IObuff) + STRLEN(errmsg) + numlen >= IOSIZE)
5116 IObuff[IOSIZE - STRLEN(errmsg) - numlen - 1] = NUL;
5117 /* If the error message has the form "is ...", put the error number in
5118 * front of the file name. */
5119 if (errnum != NULL)
5120 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00005121 STRMOVE(IObuff + numlen, IObuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005122 mch_memmove(IObuff, errnum, (size_t)numlen);
5123 }
5124 STRCAT(IObuff, errmsg);
5125 emsg(IObuff);
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005126 if (errmsg_allocated)
5127 vim_free(errmsg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005128
5129 retval = FAIL;
5130 if (end == 0)
5131 {
5132 MSG_PUTS_ATTR(_("\nWARNING: Original file may be lost or damaged\n"),
5133 attr | MSG_HIST);
5134 MSG_PUTS_ATTR(_("don't quit the editor until the file is successfully written!"),
5135 attr | MSG_HIST);
5136
5137 /* Update the timestamp to avoid an "overwrite changed file"
5138 * prompt when writing again. */
5139 if (mch_stat((char *)fname, &st_old) >= 0)
5140 {
5141 buf_store_time(buf, &st_old, fname);
5142 buf->b_mtime_read = buf->b_mtime;
5143 }
5144 }
5145 }
5146 msg_scroll = msg_save;
5147
Bram Moolenaar55debbe2010-05-23 23:34:36 +02005148#ifdef FEAT_PERSISTENT_UNDO
5149 /*
5150 * When writing the whole file and 'undofile' is set, also write the undo
5151 * file.
5152 */
5153 if (retval == OK && write_undo_file)
5154 {
5155 char_u hash[UNDO_HASH_SIZE];
5156
5157 sha256_finish(&sha_ctx, hash);
5158 u_write_undo(NULL, FALSE, buf, hash);
5159 }
5160#endif
5161
Bram Moolenaar071d4272004-06-13 20:20:40 +00005162#ifdef FEAT_AUTOCMD
5163#ifdef FEAT_EVAL
5164 if (!should_abort(retval))
5165#else
5166 if (!got_int)
5167#endif
5168 {
5169 aco_save_T aco;
5170
Bram Moolenaar68a33fc2012-04-25 16:50:48 +02005171 curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */
5172
Bram Moolenaar071d4272004-06-13 20:20:40 +00005173 /*
5174 * Apply POST autocommands.
5175 * Careful: The autocommands may call buf_write() recursively!
5176 */
5177 aucmd_prepbuf(&aco, buf);
5178
5179 if (append)
5180 apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname,
5181 FALSE, curbuf, eap);
5182 else if (filtering)
5183 apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname,
5184 FALSE, curbuf, eap);
5185 else if (reset_changed && whole)
5186 apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname,
5187 FALSE, curbuf, eap);
5188 else
5189 apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname,
5190 FALSE, curbuf, eap);
5191
5192 /* restore curwin/curbuf and a few other things */
5193 aucmd_restbuf(&aco);
5194
5195#ifdef FEAT_EVAL
5196 if (aborting()) /* autocmds may abort script processing */
5197 retval = FALSE;
5198#endif
5199 }
5200#endif
5201
5202 got_int |= prev_got_int;
5203
Bram Moolenaar071d4272004-06-13 20:20:40 +00005204 return retval;
5205}
5206
5207/*
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005208 * Set the name of the current buffer. Use when the buffer doesn't have a
5209 * name and a ":r" or ":w" command with a file name is used.
5210 */
5211 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005212set_rw_fname(char_u *fname, char_u *sfname)
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005213{
5214#ifdef FEAT_AUTOCMD
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005215 buf_T *buf = curbuf;
5216
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005217 /* It's like the unnamed buffer is deleted.... */
5218 if (curbuf->b_p_bl)
5219 apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
5220 apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf);
5221# ifdef FEAT_EVAL
5222 if (aborting()) /* autocmds may abort script processing */
5223 return FAIL;
5224# endif
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005225 if (curbuf != buf)
5226 {
5227 /* We are in another buffer now, don't do the renaming. */
5228 EMSG(_(e_auchangedbuf));
5229 return FAIL;
5230 }
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005231#endif
5232
5233 if (setfname(curbuf, fname, sfname, FALSE) == OK)
5234 curbuf->b_flags |= BF_NOTEDITED;
5235
5236#ifdef FEAT_AUTOCMD
5237 /* ....and a new named one is created */
5238 apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, curbuf);
5239 if (curbuf->b_p_bl)
5240 apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf);
5241# ifdef FEAT_EVAL
5242 if (aborting()) /* autocmds may abort script processing */
5243 return FAIL;
5244# endif
5245
5246 /* Do filetype detection now if 'filetype' is empty. */
5247 if (*curbuf->b_p_ft == NUL)
5248 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005249 if (au_has_group((char_u *)"filetypedetect"))
Bram Moolenaar1610d052016-06-09 22:53:01 +02005250 (void)do_doautocmd((char_u *)"filetypedetect BufRead", FALSE, NULL);
Bram Moolenaara3227e22006-03-08 21:32:40 +00005251 do_modelines(0);
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005252 }
5253#endif
5254
5255 return OK;
5256}
5257
5258/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00005259 * Put file name into IObuff with quotes.
5260 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005261 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005262msg_add_fname(buf_T *buf, char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005263{
5264 if (fname == NULL)
5265 fname = (char_u *)"-stdin-";
5266 home_replace(buf, fname, IObuff + 1, IOSIZE - 4, TRUE);
5267 IObuff[0] = '"';
5268 STRCAT(IObuff, "\" ");
5269}
5270
5271/*
5272 * Append message for text mode to IObuff.
5273 * Return TRUE if something appended.
5274 */
5275 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005276msg_add_fileformat(int eol_type)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005277{
5278#ifndef USE_CRNL
5279 if (eol_type == EOL_DOS)
5280 {
5281 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[dos]") : _("[dos format]"));
5282 return TRUE;
5283 }
5284#endif
5285#ifndef USE_CR
5286 if (eol_type == EOL_MAC)
5287 {
5288 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[mac]") : _("[mac format]"));
5289 return TRUE;
5290 }
5291#endif
5292#if defined(USE_CRNL) || defined(USE_CR)
5293 if (eol_type == EOL_UNIX)
5294 {
5295 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[unix]") : _("[unix format]"));
5296 return TRUE;
5297 }
5298#endif
5299 return FALSE;
5300}
5301
5302/*
5303 * Append line and character count to IObuff.
5304 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005305 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005306msg_add_lines(
5307 int insert_space,
5308 long lnum,
Bram Moolenaar8767f522016-07-01 17:17:39 +02005309 off_T nchars)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005310{
5311 char_u *p;
5312
5313 p = IObuff + STRLEN(IObuff);
5314
5315 if (insert_space)
5316 *p++ = ' ';
5317 if (shortmess(SHM_LINES))
Bram Moolenaarbde98102016-07-01 20:03:42 +02005318 vim_snprintf((char *)p, IOSIZE - (p - IObuff),
5319 "%ldL, %lldC", lnum, (varnumber_T)nchars);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005320 else
5321 {
5322 if (lnum == 1)
5323 STRCPY(p, _("1 line, "));
5324 else
5325 sprintf((char *)p, _("%ld lines, "), lnum);
5326 p += STRLEN(p);
5327 if (nchars == 1)
5328 STRCPY(p, _("1 character"));
5329 else
Bram Moolenaarbde98102016-07-01 20:03:42 +02005330 vim_snprintf((char *)p, IOSIZE - (p - IObuff),
5331 _("%lld characters"), (varnumber_T)nchars);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005332 }
5333}
5334
5335/*
5336 * Append message for missing line separator to IObuff.
5337 */
5338 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005339msg_add_eol(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005340{
5341 STRCAT(IObuff, shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]"));
5342}
5343
5344/*
5345 * Check modification time of file, before writing to it.
5346 * The size isn't checked, because using a tool like "gzip" takes care of
5347 * using the same timestamp but can't set the size.
5348 */
5349 static int
Bram Moolenaar8767f522016-07-01 17:17:39 +02005350check_mtime(buf_T *buf, stat_T *st)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005351{
5352 if (buf->b_mtime_read != 0
5353 && time_differs((long)st->st_mtime, buf->b_mtime_read))
5354 {
5355 msg_scroll = TRUE; /* don't overwrite messages here */
5356 msg_silent = 0; /* must give this prompt */
5357 /* don't use emsg() here, don't want to flush the buffers */
5358 MSG_ATTR(_("WARNING: The file has been changed since reading it!!!"),
Bram Moolenaar8820b482017-03-16 17:23:31 +01005359 HL_ATTR(HLF_E));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005360 if (ask_yesno((char_u *)_("Do you really want to write to it"),
5361 TRUE) == 'n')
5362 return FAIL;
5363 msg_scroll = FALSE; /* always overwrite the file message now */
5364 }
5365 return OK;
5366}
5367
5368 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005369time_differs(long t1, long t2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005370{
Bram Moolenaar48e330a2016-02-23 14:53:34 +01005371#if defined(__linux__) || defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005372 /* On a FAT filesystem, esp. under Linux, there are only 5 bits to store
5373 * the seconds. Since the roundoff is done when flushing the inode, the
5374 * time may change unexpectedly by one second!!! */
5375 return (t1 - t2 > 1 || t2 - t1 > 1);
5376#else
5377 return (t1 != t2);
5378#endif
5379}
5380
5381/*
5382 * Call write() to write a number of bytes to the file.
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005383 * Handles encryption and 'encoding' conversion.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005384 *
5385 * Return FAIL for failure, OK otherwise.
5386 */
5387 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005388buf_write_bytes(struct bw_info *ip)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005389{
5390 int wlen;
5391 char_u *buf = ip->bw_buf; /* data to write */
5392 int len = ip->bw_len; /* length of data */
5393#ifdef HAS_BW_FLAGS
5394 int flags = ip->bw_flags; /* extra flags */
5395#endif
5396
5397#ifdef FEAT_MBYTE
5398 /*
5399 * Skip conversion when writing the crypt magic number or the BOM.
5400 */
5401 if (!(flags & FIO_NOCONVERT))
5402 {
5403 char_u *p;
5404 unsigned c;
5405 int n;
5406
5407 if (flags & FIO_UTF8)
5408 {
5409 /*
5410 * Convert latin1 in the buffer to UTF-8 in the file.
5411 */
5412 p = ip->bw_conv_buf; /* translate to buffer */
5413 for (wlen = 0; wlen < len; ++wlen)
5414 p += utf_char2bytes(buf[wlen], p);
5415 buf = ip->bw_conv_buf;
5416 len = (int)(p - ip->bw_conv_buf);
5417 }
5418 else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1))
5419 {
5420 /*
5421 * Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
5422 * Latin1 chars in the file.
5423 */
5424 if (flags & FIO_LATIN1)
5425 p = buf; /* translate in-place (can only get shorter) */
5426 else
5427 p = ip->bw_conv_buf; /* translate to buffer */
5428 for (wlen = 0; wlen < len; wlen += n)
5429 {
5430 if (wlen == 0 && ip->bw_restlen != 0)
5431 {
5432 int l;
5433
5434 /* Use remainder of previous call. Append the start of
5435 * buf[] to get a full sequence. Might still be too
5436 * short! */
5437 l = CONV_RESTLEN - ip->bw_restlen;
5438 if (l > len)
5439 l = len;
5440 mch_memmove(ip->bw_rest + ip->bw_restlen, buf, (size_t)l);
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005441 n = utf_ptr2len_len(ip->bw_rest, ip->bw_restlen + l);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005442 if (n > ip->bw_restlen + len)
5443 {
5444 /* We have an incomplete byte sequence at the end to
5445 * be written. We can't convert it without the
5446 * remaining bytes. Keep them for the next call. */
5447 if (ip->bw_restlen + len > CONV_RESTLEN)
5448 return FAIL;
5449 ip->bw_restlen += len;
5450 break;
5451 }
5452 if (n > 1)
5453 c = utf_ptr2char(ip->bw_rest);
5454 else
5455 c = ip->bw_rest[0];
5456 if (n >= ip->bw_restlen)
5457 {
5458 n -= ip->bw_restlen;
5459 ip->bw_restlen = 0;
5460 }
5461 else
5462 {
5463 ip->bw_restlen -= n;
5464 mch_memmove(ip->bw_rest, ip->bw_rest + n,
5465 (size_t)ip->bw_restlen);
5466 n = 0;
5467 }
5468 }
5469 else
5470 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005471 n = utf_ptr2len_len(buf + wlen, len - wlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005472 if (n > len - wlen)
5473 {
5474 /* We have an incomplete byte sequence at the end to
5475 * be written. We can't convert it without the
5476 * remaining bytes. Keep them for the next call. */
5477 if (len - wlen > CONV_RESTLEN)
5478 return FAIL;
5479 ip->bw_restlen = len - wlen;
5480 mch_memmove(ip->bw_rest, buf + wlen,
5481 (size_t)ip->bw_restlen);
5482 break;
5483 }
5484 if (n > 1)
5485 c = utf_ptr2char(buf + wlen);
5486 else
5487 c = buf[wlen];
5488 }
5489
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005490 if (ucs2bytes(c, &p, flags) && !ip->bw_conv_error)
5491 {
5492 ip->bw_conv_error = TRUE;
5493 ip->bw_conv_error_lnum = ip->bw_start_lnum;
5494 }
5495 if (c == NL)
5496 ++ip->bw_start_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005497 }
5498 if (flags & FIO_LATIN1)
5499 len = (int)(p - buf);
5500 else
5501 {
5502 buf = ip->bw_conv_buf;
5503 len = (int)(p - ip->bw_conv_buf);
5504 }
5505 }
5506
5507# ifdef WIN3264
5508 else if (flags & FIO_CODEPAGE)
5509 {
5510 /*
5511 * Convert UTF-8 or codepage to UCS-2 and then to MS-Windows
5512 * codepage.
5513 */
5514 char_u *from;
5515 size_t fromlen;
5516 char_u *to;
5517 int u8c;
5518 BOOL bad = FALSE;
5519 int needed;
5520
5521 if (ip->bw_restlen > 0)
5522 {
5523 /* Need to concatenate the remainder of the previous call and
5524 * the bytes of the current call. Use the end of the
5525 * conversion buffer for this. */
5526 fromlen = len + ip->bw_restlen;
5527 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5528 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5529 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5530 }
5531 else
5532 {
5533 from = buf;
5534 fromlen = len;
5535 }
5536
5537 to = ip->bw_conv_buf;
5538 if (enc_utf8)
5539 {
5540 /* Convert from UTF-8 to UCS-2, to the start of the buffer.
5541 * The buffer has been allocated to be big enough. */
5542 while (fromlen > 0)
5543 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005544 n = (int)utf_ptr2len_len(from, (int)fromlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005545 if (n > (int)fromlen) /* incomplete byte sequence */
5546 break;
5547 u8c = utf_ptr2char(from);
5548 *to++ = (u8c & 0xff);
5549 *to++ = (u8c >> 8);
5550 fromlen -= n;
5551 from += n;
5552 }
5553
5554 /* Copy remainder to ip->bw_rest[] to be used for the next
5555 * call. */
5556 if (fromlen > CONV_RESTLEN)
5557 {
5558 /* weird overlong sequence */
5559 ip->bw_conv_error = TRUE;
5560 return FAIL;
5561 }
5562 mch_memmove(ip->bw_rest, from, fromlen);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005563 ip->bw_restlen = (int)fromlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005564 }
5565 else
5566 {
5567 /* Convert from enc_codepage to UCS-2, to the start of the
5568 * buffer. The buffer has been allocated to be big enough. */
5569 ip->bw_restlen = 0;
5570 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005571 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005572 NULL, 0);
5573 if (needed == 0)
5574 {
5575 /* When conversion fails there may be a trailing byte. */
5576 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005577 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen - 1,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005578 NULL, 0);
5579 if (needed == 0)
5580 {
5581 /* Conversion doesn't work. */
5582 ip->bw_conv_error = TRUE;
5583 return FAIL;
5584 }
5585 /* Save the trailing byte for the next call. */
5586 ip->bw_rest[0] = from[fromlen - 1];
5587 ip->bw_restlen = 1;
5588 }
5589 needed = MultiByteToWideChar(enc_codepage, MB_ERR_INVALID_CHARS,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005590 (LPCSTR)from, (int)(fromlen - ip->bw_restlen),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005591 (LPWSTR)to, needed);
5592 if (needed == 0)
5593 {
5594 /* Safety check: Conversion doesn't work. */
5595 ip->bw_conv_error = TRUE;
5596 return FAIL;
5597 }
5598 to += needed * 2;
5599 }
5600
5601 fromlen = to - ip->bw_conv_buf;
5602 buf = to;
5603# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5604 if (FIO_GET_CP(flags) == CP_UTF8)
5605 {
5606 /* Convert from UCS-2 to UTF-8, using the remainder of the
5607 * conversion buffer. Fails when out of space. */
5608 for (from = ip->bw_conv_buf; fromlen > 1; fromlen -= 2)
5609 {
5610 u8c = *from++;
5611 u8c += (*from++ << 8);
5612 to += utf_char2bytes(u8c, to);
5613 if (to + 6 >= ip->bw_conv_buf + ip->bw_conv_buflen)
5614 {
5615 ip->bw_conv_error = TRUE;
5616 return FAIL;
5617 }
5618 }
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005619 len = (int)(to - buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005620 }
5621 else
5622#endif
5623 {
5624 /* Convert from UCS-2 to the codepage, using the remainder of
5625 * the conversion buffer. If the conversion uses the default
5626 * character "0", the data doesn't fit in this encoding, so
5627 * fail. */
5628 len = WideCharToMultiByte(FIO_GET_CP(flags), 0,
5629 (LPCWSTR)ip->bw_conv_buf, (int)fromlen / sizeof(WCHAR),
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005630 (LPSTR)to, (int)(ip->bw_conv_buflen - fromlen), 0,
5631 &bad);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005632 if (bad)
5633 {
5634 ip->bw_conv_error = TRUE;
5635 return FAIL;
5636 }
5637 }
5638 }
5639# endif
5640
Bram Moolenaar56718732006-03-15 22:53:57 +00005641# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00005642 else if (flags & FIO_MACROMAN)
5643 {
5644 /*
5645 * Convert UTF-8 or latin1 to Apple MacRoman.
5646 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005647 char_u *from;
5648 size_t fromlen;
5649
5650 if (ip->bw_restlen > 0)
5651 {
5652 /* Need to concatenate the remainder of the previous call and
5653 * the bytes of the current call. Use the end of the
5654 * conversion buffer for this. */
5655 fromlen = len + ip->bw_restlen;
5656 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5657 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5658 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5659 }
5660 else
5661 {
5662 from = buf;
5663 fromlen = len;
5664 }
5665
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00005666 if (enc2macroman(from, fromlen,
5667 ip->bw_conv_buf, &len, ip->bw_conv_buflen,
5668 ip->bw_rest, &ip->bw_restlen) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005669 {
5670 ip->bw_conv_error = TRUE;
5671 return FAIL;
5672 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005673 buf = ip->bw_conv_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005674 }
5675# endif
5676
5677# ifdef USE_ICONV
5678 if (ip->bw_iconv_fd != (iconv_t)-1)
5679 {
5680 const char *from;
5681 size_t fromlen;
5682 char *to;
5683 size_t tolen;
5684
5685 /* Convert with iconv(). */
5686 if (ip->bw_restlen > 0)
5687 {
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005688 char *fp;
5689
Bram Moolenaar071d4272004-06-13 20:20:40 +00005690 /* Need to concatenate the remainder of the previous call and
5691 * the bytes of the current call. Use the end of the
5692 * conversion buffer for this. */
5693 fromlen = len + ip->bw_restlen;
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005694 fp = (char *)ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5695 mch_memmove(fp, ip->bw_rest, (size_t)ip->bw_restlen);
5696 mch_memmove(fp + ip->bw_restlen, buf, (size_t)len);
5697 from = fp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005698 tolen = ip->bw_conv_buflen - fromlen;
5699 }
5700 else
5701 {
5702 from = (const char *)buf;
5703 fromlen = len;
5704 tolen = ip->bw_conv_buflen;
5705 }
5706 to = (char *)ip->bw_conv_buf;
5707
5708 if (ip->bw_first)
5709 {
5710 size_t save_len = tolen;
5711
5712 /* output the initial shift state sequence */
5713 (void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen);
5714
5715 /* There is a bug in iconv() on Linux (which appears to be
5716 * wide-spread) which sets "to" to NULL and messes up "tolen".
5717 */
5718 if (to == NULL)
5719 {
5720 to = (char *)ip->bw_conv_buf;
5721 tolen = save_len;
5722 }
5723 ip->bw_first = FALSE;
5724 }
5725
5726 /*
5727 * If iconv() has an error or there is not enough room, fail.
5728 */
5729 if ((iconv(ip->bw_iconv_fd, (void *)&from, &fromlen, &to, &tolen)
5730 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
5731 || fromlen > CONV_RESTLEN)
5732 {
5733 ip->bw_conv_error = TRUE;
5734 return FAIL;
5735 }
5736
5737 /* copy remainder to ip->bw_rest[] to be used for the next call. */
5738 if (fromlen > 0)
5739 mch_memmove(ip->bw_rest, (void *)from, fromlen);
5740 ip->bw_restlen = (int)fromlen;
5741
5742 buf = ip->bw_conv_buf;
5743 len = (int)((char_u *)to - ip->bw_conv_buf);
5744 }
5745# endif
5746 }
5747#endif /* FEAT_MBYTE */
5748
Bram Moolenaare6bf6552017-06-27 22:11:51 +02005749 if (ip->bw_fd < 0)
5750 /* Only checking conversion, which is OK if we get here. */
5751 return OK;
5752
Bram Moolenaar071d4272004-06-13 20:20:40 +00005753#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02005754 if (flags & FIO_ENCRYPTED)
5755 {
5756 /* Encrypt the data. Do it in-place if possible, otherwise use an
5757 * allocated buffer. */
5758 if (crypt_works_inplace(ip->bw_buffer->b_cryptstate))
5759 {
5760 crypt_encode_inplace(ip->bw_buffer->b_cryptstate, buf, len);
5761 }
5762 else
5763 {
5764 char_u *outbuf;
5765
5766 len = crypt_encode_alloc(curbuf->b_cryptstate, buf, len, &outbuf);
5767 if (len == 0)
5768 return OK; /* Crypt layer is buffering, will flush later. */
5769 wlen = write_eintr(ip->bw_fd, outbuf, len);
5770 vim_free(outbuf);
5771 return (wlen < len) ? FAIL : OK;
5772 }
5773 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005774#endif
5775
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005776 wlen = write_eintr(ip->bw_fd, buf, len);
5777 return (wlen < len) ? FAIL : OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005778}
5779
5780#ifdef FEAT_MBYTE
5781/*
5782 * Convert a Unicode character to bytes.
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005783 * Return TRUE for an error, FALSE when it's OK.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005784 */
5785 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005786ucs2bytes(
5787 unsigned c, /* in: character */
5788 char_u **pp, /* in/out: pointer to result */
5789 int flags) /* FIO_ flags */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005790{
5791 char_u *p = *pp;
5792 int error = FALSE;
5793 int cc;
5794
5795
5796 if (flags & FIO_UCS4)
5797 {
5798 if (flags & FIO_ENDIAN_L)
5799 {
5800 *p++ = c;
5801 *p++ = (c >> 8);
5802 *p++ = (c >> 16);
5803 *p++ = (c >> 24);
5804 }
5805 else
5806 {
5807 *p++ = (c >> 24);
5808 *p++ = (c >> 16);
5809 *p++ = (c >> 8);
5810 *p++ = c;
5811 }
5812 }
5813 else if (flags & (FIO_UCS2 | FIO_UTF16))
5814 {
5815 if (c >= 0x10000)
5816 {
5817 if (flags & FIO_UTF16)
5818 {
5819 /* Make two words, ten bits of the character in each. First
5820 * word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff */
5821 c -= 0x10000;
5822 if (c >= 0x100000)
5823 error = TRUE;
5824 cc = ((c >> 10) & 0x3ff) + 0xd800;
5825 if (flags & FIO_ENDIAN_L)
5826 {
5827 *p++ = cc;
5828 *p++ = ((unsigned)cc >> 8);
5829 }
5830 else
5831 {
5832 *p++ = ((unsigned)cc >> 8);
5833 *p++ = cc;
5834 }
5835 c = (c & 0x3ff) + 0xdc00;
5836 }
5837 else
5838 error = TRUE;
5839 }
5840 if (flags & FIO_ENDIAN_L)
5841 {
5842 *p++ = c;
5843 *p++ = (c >> 8);
5844 }
5845 else
5846 {
5847 *p++ = (c >> 8);
5848 *p++ = c;
5849 }
5850 }
5851 else /* Latin1 */
5852 {
5853 if (c >= 0x100)
5854 {
5855 error = TRUE;
5856 *p++ = 0xBF;
5857 }
5858 else
5859 *p++ = c;
5860 }
5861
5862 *pp = p;
5863 return error;
5864}
5865
5866/*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005867 * Return TRUE if file encoding "fenc" requires conversion from or to
5868 * 'encoding'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005869 */
5870 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005871need_conversion(char_u *fenc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005872{
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005873 int same_encoding;
5874 int enc_flags;
5875 int fenc_flags;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005876
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005877 if (*fenc == NUL || STRCMP(p_enc, fenc) == 0)
Bram Moolenaar442b4222010-05-24 21:34:22 +02005878 {
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005879 same_encoding = TRUE;
Bram Moolenaar442b4222010-05-24 21:34:22 +02005880 fenc_flags = 0;
5881 }
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005882 else
5883 {
5884 /* Ignore difference between "ansi" and "latin1", "ucs-4" and
5885 * "ucs-4be", etc. */
5886 enc_flags = get_fio_flags(p_enc);
5887 fenc_flags = get_fio_flags(fenc);
5888 same_encoding = (enc_flags != 0 && fenc_flags == enc_flags);
5889 }
5890 if (same_encoding)
5891 {
5892 /* Specified encoding matches with 'encoding'. This requires
5893 * conversion when 'encoding' is Unicode but not UTF-8. */
5894 return enc_unicode != 0;
5895 }
5896
5897 /* Encodings differ. However, conversion is not needed when 'enc' is any
5898 * Unicode encoding and the file is UTF-8. */
5899 return !(enc_utf8 && fenc_flags == FIO_UTF8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005900}
5901
5902/*
5903 * Check "ptr" for a unicode encoding and return the FIO_ flags needed for the
5904 * internal conversion.
5905 * if "ptr" is an empty string, use 'encoding'.
5906 */
5907 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005908get_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005909{
5910 int prop;
5911
5912 if (*ptr == NUL)
5913 ptr = p_enc;
5914
5915 prop = enc_canon_props(ptr);
5916 if (prop & ENC_UNICODE)
5917 {
5918 if (prop & ENC_2BYTE)
5919 {
5920 if (prop & ENC_ENDIAN_L)
5921 return FIO_UCS2 | FIO_ENDIAN_L;
5922 return FIO_UCS2;
5923 }
5924 if (prop & ENC_4BYTE)
5925 {
5926 if (prop & ENC_ENDIAN_L)
5927 return FIO_UCS4 | FIO_ENDIAN_L;
5928 return FIO_UCS4;
5929 }
5930 if (prop & ENC_2WORD)
5931 {
5932 if (prop & ENC_ENDIAN_L)
5933 return FIO_UTF16 | FIO_ENDIAN_L;
5934 return FIO_UTF16;
5935 }
5936 return FIO_UTF8;
5937 }
5938 if (prop & ENC_LATIN1)
5939 return FIO_LATIN1;
5940 /* must be ENC_DBCS, requires iconv() */
5941 return 0;
5942}
5943
5944#ifdef WIN3264
5945/*
5946 * Check "ptr" for a MS-Windows codepage name and return the FIO_ flags needed
5947 * for the conversion MS-Windows can do for us. Also accept "utf-8".
5948 * Used for conversion between 'encoding' and 'fileencoding'.
5949 */
5950 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005951get_win_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005952{
5953 int cp;
5954
5955 /* Cannot do this when 'encoding' is not utf-8 and not a codepage. */
5956 if (!enc_utf8 && enc_codepage <= 0)
5957 return 0;
5958
5959 cp = encname2codepage(ptr);
5960 if (cp == 0)
5961 {
5962# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5963 if (STRCMP(ptr, "utf-8") == 0)
5964 cp = CP_UTF8;
5965 else
5966# endif
5967 return 0;
5968 }
5969 return FIO_PUT_CP(cp) | FIO_CODEPAGE;
5970}
5971#endif
5972
Bram Moolenaard0573012017-10-28 21:11:06 +02005973#ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00005974/*
5975 * Check "ptr" for a Carbon supported encoding and return the FIO_ flags
5976 * needed for the internal conversion to/from utf-8 or latin1.
5977 */
5978 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005979get_mac_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005980{
5981 if ((enc_utf8 || STRCMP(p_enc, "latin1") == 0)
5982 && (enc_canon_props(ptr) & ENC_MACROMAN))
5983 return FIO_MACROMAN;
5984 return 0;
5985}
5986#endif
5987
5988/*
5989 * Check for a Unicode BOM (Byte Order Mark) at the start of p[size].
5990 * "size" must be at least 2.
5991 * Return the name of the encoding and set "*lenp" to the length.
5992 * Returns NULL when no BOM found.
5993 */
5994 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005995check_for_bom(
5996 char_u *p,
5997 long size,
5998 int *lenp,
5999 int flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006000{
6001 char *name = NULL;
6002 int len = 2;
6003
6004 if (p[0] == 0xef && p[1] == 0xbb && size >= 3 && p[2] == 0xbf
Bram Moolenaaree0f5a62008-07-24 20:09:16 +00006005 && (flags == FIO_ALL || flags == FIO_UTF8 || flags == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006006 {
6007 name = "utf-8"; /* EF BB BF */
6008 len = 3;
6009 }
6010 else if (p[0] == 0xff && p[1] == 0xfe)
6011 {
6012 if (size >= 4 && p[2] == 0 && p[3] == 0
6013 && (flags == FIO_ALL || flags == (FIO_UCS4 | FIO_ENDIAN_L)))
6014 {
6015 name = "ucs-4le"; /* FF FE 00 00 */
6016 len = 4;
6017 }
Bram Moolenaar223a1892008-11-11 20:57:11 +00006018 else if (flags == (FIO_UCS2 | FIO_ENDIAN_L))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006019 name = "ucs-2le"; /* FF FE */
Bram Moolenaar223a1892008-11-11 20:57:11 +00006020 else if (flags == FIO_ALL || flags == (FIO_UTF16 | FIO_ENDIAN_L))
6021 /* utf-16le is preferred, it also works for ucs-2le text */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006022 name = "utf-16le"; /* FF FE */
6023 }
6024 else if (p[0] == 0xfe && p[1] == 0xff
6025 && (flags == FIO_ALL || flags == FIO_UCS2 || flags == FIO_UTF16))
6026 {
Bram Moolenaarffd82c52008-02-20 17:15:26 +00006027 /* Default to utf-16, it works also for ucs-2 text. */
6028 if (flags == FIO_UCS2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006029 name = "ucs-2"; /* FE FF */
Bram Moolenaarffd82c52008-02-20 17:15:26 +00006030 else
6031 name = "utf-16"; /* FE FF */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006032 }
6033 else if (size >= 4 && p[0] == 0 && p[1] == 0 && p[2] == 0xfe
6034 && p[3] == 0xff && (flags == FIO_ALL || flags == FIO_UCS4))
6035 {
6036 name = "ucs-4"; /* 00 00 FE FF */
6037 len = 4;
6038 }
6039
6040 *lenp = len;
6041 return (char_u *)name;
6042}
6043
6044/*
6045 * Generate a BOM in "buf[4]" for encoding "name".
6046 * Return the length of the BOM (zero when no BOM).
6047 */
6048 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006049make_bom(char_u *buf, char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006050{
6051 int flags;
6052 char_u *p;
6053
6054 flags = get_fio_flags(name);
6055
6056 /* Can't put a BOM in a non-Unicode file. */
6057 if (flags == FIO_LATIN1 || flags == 0)
6058 return 0;
6059
6060 if (flags == FIO_UTF8) /* UTF-8 */
6061 {
6062 buf[0] = 0xef;
6063 buf[1] = 0xbb;
6064 buf[2] = 0xbf;
6065 return 3;
6066 }
6067 p = buf;
6068 (void)ucs2bytes(0xfeff, &p, flags);
6069 return (int)(p - buf);
6070}
6071#endif
6072
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00006073#if defined(FEAT_VIMINFO) || defined(FEAT_BROWSE) || \
Bram Moolenaara0174af2008-01-02 20:08:25 +00006074 defined(FEAT_QUICKFIX) || defined(FEAT_AUTOCMD) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006075/*
6076 * Try to find a shortname by comparing the fullname with the current
6077 * directory.
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006078 * Returns "full_path" or pointer into "full_path" if shortened.
6079 */
6080 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006081shorten_fname1(char_u *full_path)
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006082{
Bram Moolenaard9462e32011-04-11 21:35:11 +02006083 char_u *dirname;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006084 char_u *p = full_path;
6085
Bram Moolenaard9462e32011-04-11 21:35:11 +02006086 dirname = alloc(MAXPATHL);
6087 if (dirname == NULL)
6088 return full_path;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006089 if (mch_dirname(dirname, MAXPATHL) == OK)
6090 {
6091 p = shorten_fname(full_path, dirname);
6092 if (p == NULL || *p == NUL)
6093 p = full_path;
6094 }
Bram Moolenaard9462e32011-04-11 21:35:11 +02006095 vim_free(dirname);
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006096 return p;
6097}
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00006098#endif
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006099
6100/*
6101 * Try to find a shortname by comparing the fullname with the current
6102 * directory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006103 * Returns NULL if not shorter name possible, pointer into "full_path"
6104 * otherwise.
6105 */
6106 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006107shorten_fname(char_u *full_path, char_u *dir_name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006108{
6109 int len;
6110 char_u *p;
6111
6112 if (full_path == NULL)
6113 return NULL;
6114 len = (int)STRLEN(dir_name);
6115 if (fnamencmp(dir_name, full_path, len) == 0)
6116 {
6117 p = full_path + len;
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006118#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006119 /*
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006120 * MSWIN: when a file is in the root directory, dir_name will end in a
Bram Moolenaar071d4272004-06-13 20:20:40 +00006121 * slash, since C: by itself does not define a specific dir. In this
6122 * case p may already be correct. <negri>
6123 */
6124 if (!((len > 2) && (*(p - 2) == ':')))
6125#endif
6126 {
6127 if (vim_ispathsep(*p))
6128 ++p;
6129#ifndef VMS /* the path separator is always part of the path */
6130 else
6131 p = NULL;
6132#endif
6133 }
6134 }
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006135#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006136 /*
6137 * When using a file in the current drive, remove the drive name:
6138 * "A:\dir\file" -> "\dir\file". This helps when moving a session file on
6139 * a floppy from "A:\dir" to "B:\dir".
6140 */
6141 else if (len > 3
6142 && TOUPPER_LOC(full_path[0]) == TOUPPER_LOC(dir_name[0])
6143 && full_path[1] == ':'
6144 && vim_ispathsep(full_path[2]))
6145 p = full_path + 2;
6146#endif
6147 else
6148 p = NULL;
6149 return p;
6150}
6151
6152/*
6153 * Shorten filenames for all buffers.
6154 * When "force" is TRUE: Use full path from now on for files currently being
6155 * edited, both for file name and swap file name. Try to shorten the file
6156 * names a bit, if safe to do so.
6157 * When "force" is FALSE: Only try to shorten absolute file names.
6158 * For buffers that have buftype "nofile" or "scratch": never change the file
6159 * name.
6160 */
6161 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006162shorten_fnames(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006163{
6164 char_u dirname[MAXPATHL];
6165 buf_T *buf;
6166 char_u *p;
6167
6168 mch_dirname(dirname, MAXPATHL);
Bram Moolenaar29323592016-07-24 22:04:11 +02006169 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006170 {
6171 if (buf->b_fname != NULL
6172#ifdef FEAT_QUICKFIX
6173 && !bt_nofile(buf)
6174#endif
6175 && !path_with_url(buf->b_fname)
6176 && (force
6177 || buf->b_sfname == NULL
6178 || mch_isFullName(buf->b_sfname)))
6179 {
6180 vim_free(buf->b_sfname);
6181 buf->b_sfname = NULL;
6182 p = shorten_fname(buf->b_ffname, dirname);
6183 if (p != NULL)
6184 {
6185 buf->b_sfname = vim_strsave(p);
6186 buf->b_fname = buf->b_sfname;
6187 }
6188 if (p == NULL || buf->b_fname == NULL)
6189 buf->b_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006190 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00006191
6192 /* Always make the swap file name a full path, a "nofile" buffer may
6193 * also have a swap file. */
6194 mf_fullname(buf->b_ml.ml_mfp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006195 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006196 status_redraw_all();
Bram Moolenaar49d7bf12006-02-17 21:45:41 +00006197 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006198}
6199
6200#if (defined(FEAT_DND) && defined(FEAT_GUI_GTK)) \
6201 || defined(FEAT_GUI_MSWIN) \
6202 || defined(FEAT_GUI_MAC) \
6203 || defined(PROTO)
6204/*
6205 * Shorten all filenames in "fnames[count]" by current directory.
6206 */
6207 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006208shorten_filenames(char_u **fnames, int count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006209{
6210 int i;
6211 char_u dirname[MAXPATHL];
6212 char_u *p;
6213
6214 if (fnames == NULL || count < 1)
6215 return;
6216 mch_dirname(dirname, sizeof(dirname));
6217 for (i = 0; i < count; ++i)
6218 {
6219 if ((p = shorten_fname(fnames[i], dirname)) != NULL)
6220 {
6221 /* shorten_fname() returns pointer in given "fnames[i]". If free
6222 * "fnames[i]" first, "p" becomes invalid. So we need to copy
6223 * "p" first then free fnames[i]. */
6224 p = vim_strsave(p);
6225 vim_free(fnames[i]);
6226 fnames[i] = p;
6227 }
6228 }
6229}
6230#endif
6231
6232/*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006233 * add extension to file name - change path/fo.o.h to path/fo.o.h.ext or
Bram Moolenaar071d4272004-06-13 20:20:40 +00006234 * fo_o_h.ext for MSDOS or when shortname option set.
6235 *
6236 * Assumed that fname is a valid name found in the filesystem we assure that
6237 * the return value is a different name and ends in 'ext'.
6238 * "ext" MUST be at most 4 characters long if it starts with a dot, 3
6239 * characters otherwise.
6240 * Space for the returned name is allocated, must be freed later.
6241 * Returns NULL when out of memory.
6242 */
6243 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006244modname(
6245 char_u *fname,
6246 char_u *ext,
6247 int prepend_dot) /* may prepend a '.' to file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006248{
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006249 return buf_modname((curbuf->b_p_sn || curbuf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00006250 fname, ext, prepend_dot);
6251}
6252
6253 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006254buf_modname(
6255 int shortname, /* use 8.3 file name */
6256 char_u *fname,
6257 char_u *ext,
6258 int prepend_dot) /* may prepend a '.' to file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006259{
6260 char_u *retval;
6261 char_u *s;
6262 char_u *e;
6263 char_u *ptr;
6264 int fnamelen, extlen;
6265
6266 extlen = (int)STRLEN(ext);
6267
6268 /*
6269 * If there is no file name we must get the name of the current directory
6270 * (we need the full path in case :cd is used).
6271 */
6272 if (fname == NULL || *fname == NUL)
6273 {
6274 retval = alloc((unsigned)(MAXPATHL + extlen + 3));
6275 if (retval == NULL)
6276 return NULL;
6277 if (mch_dirname(retval, MAXPATHL) == FAIL ||
6278 (fnamelen = (int)STRLEN(retval)) == 0)
6279 {
6280 vim_free(retval);
6281 return NULL;
6282 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006283 if (!after_pathsep(retval, retval + fnamelen))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006284 {
6285 retval[fnamelen++] = PATHSEP;
6286 retval[fnamelen] = NUL;
6287 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006288 prepend_dot = FALSE; /* nothing to prepend a dot to */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006289 }
6290 else
6291 {
6292 fnamelen = (int)STRLEN(fname);
6293 retval = alloc((unsigned)(fnamelen + extlen + 3));
6294 if (retval == NULL)
6295 return NULL;
6296 STRCPY(retval, fname);
6297#ifdef VMS
6298 vms_remove_version(retval); /* we do not need versions here */
6299#endif
6300 }
6301
6302 /*
6303 * search backwards until we hit a '/', '\' or ':' replacing all '.'
6304 * by '_' for MSDOS or when shortname option set and ext starts with a dot.
6305 * Then truncate what is after the '/', '\' or ':' to 8 characters for
6306 * MSDOS and 26 characters for AMIGA, a lot more for UNIX.
6307 */
Bram Moolenaar91acfff2017-03-12 19:22:36 +01006308 for (ptr = retval + fnamelen; ptr > retval; MB_PTR_BACK(retval, ptr))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006309 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006310 if (*ext == '.'
Bram Moolenaare60acc12011-05-10 16:41:25 +02006311#ifdef USE_LONG_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00006312 && (!USE_LONG_FNAME || shortname)
Bram Moolenaare60acc12011-05-10 16:41:25 +02006313#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006314 && shortname
Bram Moolenaare60acc12011-05-10 16:41:25 +02006315#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006316 )
6317 if (*ptr == '.') /* replace '.' by '_' */
6318 *ptr = '_';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006319 if (vim_ispathsep(*ptr))
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006320 {
6321 ++ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006322 break;
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006323 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006324 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006325
6326 /* the file name has at most BASENAMELEN characters. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006327 if (STRLEN(ptr) > (unsigned)BASENAMELEN)
6328 ptr[BASENAMELEN] = '\0';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006329
6330 s = ptr + STRLEN(ptr);
6331
6332 /*
6333 * For 8.3 file names we may have to reduce the length.
6334 */
6335#ifdef USE_LONG_FNAME
6336 if (!USE_LONG_FNAME || shortname)
6337#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006338 if (shortname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006339#endif
6340 {
6341 /*
6342 * If there is no file name, or the file name ends in '/', and the
6343 * extension starts with '.', put a '_' before the dot, because just
6344 * ".ext" is invalid.
6345 */
6346 if (fname == NULL || *fname == NUL
6347 || vim_ispathsep(fname[STRLEN(fname) - 1]))
6348 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006349 if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006350 *s++ = '_';
6351 }
6352 /*
6353 * If the extension starts with '.', truncate the base name at 8
6354 * characters
6355 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006356 else if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006357 {
Bram Moolenaar78a15312009-05-15 19:33:18 +00006358 if ((size_t)(s - ptr) > (size_t)8)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006359 {
6360 s = ptr + 8;
6361 *s = '\0';
6362 }
6363 }
6364 /*
6365 * If the extension doesn't start with '.', and the file name
6366 * doesn't have an extension yet, append a '.'
6367 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006368 else if ((e = vim_strchr(ptr, '.')) == NULL)
6369 *s++ = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006370 /*
6371 * If the extension doesn't start with '.', and there already is an
Bram Moolenaar7263a772007-05-10 17:35:54 +00006372 * extension, it may need to be truncated
Bram Moolenaar071d4272004-06-13 20:20:40 +00006373 */
6374 else if ((int)STRLEN(e) + extlen > 4)
6375 s = e + 4 - extlen;
6376 }
Bram Moolenaare7fedb62015-12-31 19:07:19 +01006377#if defined(USE_LONG_FNAME) || defined(WIN3264)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006378 /*
6379 * If there is no file name, and the extension starts with '.', put a
6380 * '_' before the dot, because just ".ext" may be invalid if it's on a
6381 * FAT partition, and on HPFS it doesn't matter.
6382 */
6383 else if ((fname == NULL || *fname == NUL) && *ext == '.')
6384 *s++ = '_';
6385#endif
6386
6387 /*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006388 * Append the extension.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006389 * ext can start with '.' and cannot exceed 3 more characters.
6390 */
6391 STRCPY(s, ext);
6392
Bram Moolenaar071d4272004-06-13 20:20:40 +00006393 /*
6394 * Prepend the dot.
6395 */
Bram Moolenaare60acc12011-05-10 16:41:25 +02006396 if (prepend_dot && !shortname && *(e = gettail(retval)) != '.'
Bram Moolenaar071d4272004-06-13 20:20:40 +00006397#ifdef USE_LONG_FNAME
6398 && USE_LONG_FNAME
6399#endif
6400 )
6401 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006402 STRMOVE(e + 1, e);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006403 *e = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006404 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006405
6406 /*
6407 * Check that, after appending the extension, the file name is really
6408 * different.
6409 */
6410 if (fname != NULL && STRCMP(fname, retval) == 0)
6411 {
6412 /* we search for a character that can be replaced by '_' */
6413 while (--s >= ptr)
6414 {
6415 if (*s != '_')
6416 {
6417 *s = '_';
6418 break;
6419 }
6420 }
6421 if (s < ptr) /* fname was "________.<ext>", how tricky! */
6422 *ptr = 'v';
6423 }
6424 return retval;
6425}
6426
6427/*
6428 * Like fgets(), but if the file line is too long, it is truncated and the
6429 * rest of the line is thrown away. Returns TRUE for end-of-file.
6430 */
6431 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006432vim_fgets(char_u *buf, int size, FILE *fp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006433{
6434 char *eof;
6435#define FGETS_SIZE 200
6436 char tbuf[FGETS_SIZE];
6437
6438 buf[size - 2] = NUL;
6439#ifdef USE_CR
6440 eof = fgets_cr((char *)buf, size, fp);
6441#else
6442 eof = fgets((char *)buf, size, fp);
6443#endif
6444 if (buf[size - 2] != NUL && buf[size - 2] != '\n')
6445 {
6446 buf[size - 1] = NUL; /* Truncate the line */
6447
6448 /* Now throw away the rest of the line: */
6449 do
6450 {
6451 tbuf[FGETS_SIZE - 2] = NUL;
6452#ifdef USE_CR
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006453 ignoredp = fgets_cr((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006454#else
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006455 ignoredp = fgets((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006456#endif
6457 } while (tbuf[FGETS_SIZE - 2] != NUL && tbuf[FGETS_SIZE - 2] != '\n');
6458 }
6459 return (eof == NULL);
6460}
6461
6462#if defined(USE_CR) || defined(PROTO)
6463/*
6464 * Like vim_fgets(), but accept any line terminator: CR, CR-LF or LF.
6465 * Returns TRUE for end-of-file.
6466 * Only used for the Mac, because it's much slower than vim_fgets().
6467 */
6468 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006469tag_fgets(char_u *buf, int size, FILE *fp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006470{
6471 int i = 0;
6472 int c;
6473 int eof = FALSE;
6474
6475 for (;;)
6476 {
6477 c = fgetc(fp);
6478 if (c == EOF)
6479 {
6480 eof = TRUE;
6481 break;
6482 }
6483 if (c == '\r')
6484 {
6485 /* Always store a NL for end-of-line. */
6486 if (i < size - 1)
6487 buf[i++] = '\n';
6488 c = fgetc(fp);
6489 if (c != '\n') /* Macintosh format: single CR. */
6490 ungetc(c, fp);
6491 break;
6492 }
6493 if (i < size - 1)
6494 buf[i++] = c;
6495 if (c == '\n')
6496 break;
6497 }
6498 buf[i] = NUL;
6499 return eof;
6500}
6501#endif
6502
6503/*
6504 * rename() only works if both files are on the same file system, this
6505 * function will (attempts to?) copy the file across if rename fails -- webb
6506 * Return -1 for failure, 0 for success.
6507 */
6508 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006509vim_rename(char_u *from, char_u *to)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006510{
6511 int fd_in;
6512 int fd_out;
6513 int n;
6514 char *errmsg = NULL;
6515 char *buffer;
6516#ifdef AMIGA
6517 BPTR flock;
6518#endif
Bram Moolenaar8767f522016-07-01 17:17:39 +02006519 stat_T st;
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006520 long perm;
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006521#ifdef HAVE_ACL
6522 vim_acl_T acl; /* ACL from original file */
6523#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006524 int use_tmp_file = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006525
6526 /*
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006527 * When the names are identical, there is nothing to do. When they refer
6528 * to the same file (ignoring case and slash/backslash differences) but
6529 * the file name differs we need to go through a temp file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006530 */
6531 if (fnamecmp(from, to) == 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006532 {
Bram Moolenaar71afbfe2013-03-19 16:49:16 +01006533 if (p_fic && STRCMP(gettail(from), gettail(to)) != 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006534 use_tmp_file = TRUE;
6535 else
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006536 return 0;
6537 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006538
6539 /*
6540 * Fail if the "from" file doesn't exist. Avoids that "to" is deleted.
6541 */
6542 if (mch_stat((char *)from, &st) < 0)
6543 return -1;
6544
Bram Moolenaar3576da72008-12-30 15:15:57 +00006545#ifdef UNIX
6546 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02006547 stat_T st_to;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006548
6549 /* It's possible for the source and destination to be the same file.
6550 * This happens when "from" and "to" differ in case and are on a FAT32
6551 * filesystem. In that case go through a temp file name. */
6552 if (mch_stat((char *)to, &st_to) >= 0
6553 && st.st_dev == st_to.st_dev
6554 && st.st_ino == st_to.st_ino)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006555 use_tmp_file = TRUE;
6556 }
6557#endif
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02006558#ifdef WIN3264
6559 {
6560 BY_HANDLE_FILE_INFORMATION info1, info2;
6561
6562 /* It's possible for the source and destination to be the same file.
6563 * In that case go through a temp file name. This makes rename("foo",
6564 * "./foo") a no-op (in a complicated way). */
6565 if (win32_fileinfo(from, &info1) == FILEINFO_OK
6566 && win32_fileinfo(to, &info2) == FILEINFO_OK
6567 && info1.dwVolumeSerialNumber == info2.dwVolumeSerialNumber
6568 && info1.nFileIndexHigh == info2.nFileIndexHigh
6569 && info1.nFileIndexLow == info2.nFileIndexLow)
6570 use_tmp_file = TRUE;
6571 }
6572#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006573
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006574 if (use_tmp_file)
6575 {
6576 char tempname[MAXPATHL + 1];
6577
6578 /*
6579 * Find a name that doesn't exist and is in the same directory.
6580 * Rename "from" to "tempname" and then rename "tempname" to "to".
6581 */
6582 if (STRLEN(from) >= MAXPATHL - 5)
6583 return -1;
6584 STRCPY(tempname, from);
6585 for (n = 123; n < 99999; ++n)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006586 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006587 sprintf((char *)gettail((char_u *)tempname), "%d", n);
6588 if (mch_stat(tempname, &st) < 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006589 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006590 if (mch_rename((char *)from, tempname) == 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006591 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006592 if (mch_rename(tempname, (char *)to) == 0)
6593 return 0;
6594 /* Strange, the second step failed. Try moving the
6595 * file back and return failure. */
6596 mch_rename(tempname, (char *)from);
Bram Moolenaar3576da72008-12-30 15:15:57 +00006597 return -1;
6598 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006599 /* If it fails for one temp name it will most likely fail
6600 * for any temp name, give up. */
6601 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006602 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006603 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006604 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006605 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006606
Bram Moolenaar071d4272004-06-13 20:20:40 +00006607 /*
6608 * Delete the "to" file, this is required on some systems to make the
6609 * mch_rename() work, on other systems it makes sure that we don't have
6610 * two files when the mch_rename() fails.
6611 */
6612
6613#ifdef AMIGA
6614 /*
6615 * With MSDOS-compatible filesystems (crossdos, messydos) it is possible
6616 * that the name of the "to" file is the same as the "from" file, even
Bram Moolenaar7263a772007-05-10 17:35:54 +00006617 * though the names are different. To avoid the chance of accidentally
Bram Moolenaar071d4272004-06-13 20:20:40 +00006618 * deleting the "from" file (horror!) we lock it during the remove.
6619 *
6620 * When used for making a backup before writing the file: This should not
6621 * happen with ":w", because startscript() should detect this problem and
6622 * set buf->b_shortname, causing modname() to return a correct ".bak" file
6623 * name. This problem does exist with ":w filename", but then the
6624 * original file will be somewhere else so the backup isn't really
6625 * important. If autoscripting is off the rename may fail.
6626 */
6627 flock = Lock((UBYTE *)from, (long)ACCESS_READ);
6628#endif
6629 mch_remove(to);
6630#ifdef AMIGA
6631 if (flock)
6632 UnLock(flock);
6633#endif
6634
6635 /*
6636 * First try a normal rename, return if it works.
6637 */
6638 if (mch_rename((char *)from, (char *)to) == 0)
6639 return 0;
6640
6641 /*
6642 * Rename() failed, try copying the file.
6643 */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006644 perm = mch_getperm(from);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006645#ifdef HAVE_ACL
6646 /* For systems that support ACL: get the ACL from the original file. */
6647 acl = mch_get_acl(from);
6648#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006649 fd_in = mch_open((char *)from, O_RDONLY|O_EXTRA, 0);
6650 if (fd_in == -1)
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006651 {
6652#ifdef HAVE_ACL
6653 mch_free_acl(acl);
6654#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006655 return -1;
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006656 }
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006657
6658 /* Create the new file with same permissions as the original. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00006659 fd_out = mch_open((char *)to,
6660 O_CREAT|O_EXCL|O_WRONLY|O_EXTRA|O_NOFOLLOW, (int)perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006661 if (fd_out == -1)
6662 {
6663 close(fd_in);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006664#ifdef HAVE_ACL
6665 mch_free_acl(acl);
6666#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006667 return -1;
6668 }
6669
6670 buffer = (char *)alloc(BUFSIZE);
6671 if (buffer == NULL)
6672 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006673 close(fd_out);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006674 close(fd_in);
6675#ifdef HAVE_ACL
6676 mch_free_acl(acl);
6677#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006678 return -1;
6679 }
6680
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01006681 while ((n = read_eintr(fd_in, buffer, BUFSIZE)) > 0)
6682 if (write_eintr(fd_out, buffer, n) != n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006683 {
6684 errmsg = _("E208: Error writing to \"%s\"");
6685 break;
6686 }
6687
6688 vim_free(buffer);
6689 close(fd_in);
6690 if (close(fd_out) < 0)
6691 errmsg = _("E209: Error closing \"%s\"");
6692 if (n < 0)
6693 {
6694 errmsg = _("E210: Error reading \"%s\"");
6695 to = from;
6696 }
Bram Moolenaar7263a772007-05-10 17:35:54 +00006697#ifndef UNIX /* for Unix mch_open() already set the permission */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006698 mch_setperm(to, perm);
Bram Moolenaarc6039d82005-12-02 00:44:04 +00006699#endif
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006700#ifdef HAVE_ACL
6701 mch_set_acl(to, acl);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006702 mch_free_acl(acl);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006703#endif
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02006704#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaare8747442013-11-12 18:09:29 +01006705 mch_copy_sec(from, to);
Bram Moolenaar0671de32013-11-12 05:12:03 +01006706#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006707 if (errmsg != NULL)
6708 {
6709 EMSG2(errmsg, to);
6710 return -1;
6711 }
6712 mch_remove(from);
6713 return 0;
6714}
6715
6716static int already_warned = FALSE;
6717
6718/*
6719 * Check if any not hidden buffer has been changed.
6720 * Postpone the check if there are characters in the stuff buffer, a global
6721 * command is being executed, a mapping is being executed or an autocommand is
6722 * busy.
6723 * Returns TRUE if some message was written (screen should be redrawn and
6724 * cursor positioned).
6725 */
6726 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006727check_timestamps(
6728 int focus) /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006729{
6730 buf_T *buf;
6731 int didit = 0;
6732 int n;
6733
6734 /* Don't check timestamps while system() or another low-level function may
6735 * cause us to lose and gain focus. */
6736 if (no_check_timestamps > 0)
6737 return FALSE;
6738
6739 /* Avoid doing a check twice. The OK/Reload dialog can cause a focus
6740 * event and we would keep on checking if the file is steadily growing.
6741 * Do check again after typing something. */
6742 if (focus && did_check_timestamps)
6743 {
6744 need_check_timestamps = TRUE;
6745 return FALSE;
6746 }
6747
6748 if (!stuff_empty() || global_busy || !typebuf_typed()
6749#ifdef FEAT_AUTOCMD
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006750 || autocmd_busy || curbuf_lock > 0 || allbuf_lock > 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00006751#endif
6752 )
6753 need_check_timestamps = TRUE; /* check later */
6754 else
6755 {
6756 ++no_wait_return;
6757 did_check_timestamps = TRUE;
6758 already_warned = FALSE;
Bram Moolenaar29323592016-07-24 22:04:11 +02006759 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006760 {
6761 /* Only check buffers in a window. */
6762 if (buf->b_nwindows > 0)
6763 {
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006764 bufref_T bufref;
6765
6766 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006767 n = buf_check_timestamp(buf, focus);
6768 if (didit < n)
6769 didit = n;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006770 if (n > 0 && !bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006771 {
6772 /* Autocommands have removed the buffer, start at the
6773 * first one again. */
6774 buf = firstbuf;
6775 continue;
6776 }
6777 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006778 }
6779 --no_wait_return;
6780 need_check_timestamps = FALSE;
6781 if (need_wait_return && didit == 2)
6782 {
6783 /* make sure msg isn't overwritten */
6784 msg_puts((char_u *)"\n");
6785 out_flush();
6786 }
6787 }
6788 return didit;
6789}
6790
6791/*
6792 * Move all the lines from buffer "frombuf" to buffer "tobuf".
6793 * Return OK or FAIL. When FAIL "tobuf" is incomplete and/or "frombuf" is not
6794 * empty.
6795 */
6796 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006797move_lines(buf_T *frombuf, buf_T *tobuf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006798{
6799 buf_T *tbuf = curbuf;
6800 int retval = OK;
6801 linenr_T lnum;
6802 char_u *p;
6803
6804 /* Copy the lines in "frombuf" to "tobuf". */
6805 curbuf = tobuf;
6806 for (lnum = 1; lnum <= frombuf->b_ml.ml_line_count; ++lnum)
6807 {
6808 p = vim_strsave(ml_get_buf(frombuf, lnum, FALSE));
6809 if (p == NULL || ml_append(lnum - 1, p, 0, FALSE) == FAIL)
6810 {
6811 vim_free(p);
6812 retval = FAIL;
6813 break;
6814 }
6815 vim_free(p);
6816 }
6817
6818 /* Delete all the lines in "frombuf". */
6819 if (retval != FAIL)
6820 {
6821 curbuf = frombuf;
Bram Moolenaar9460b9d2007-01-09 14:37:01 +00006822 for (lnum = curbuf->b_ml.ml_line_count; lnum > 0; --lnum)
6823 if (ml_delete(lnum, FALSE) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006824 {
6825 /* Oops! We could try putting back the saved lines, but that
6826 * might fail again... */
6827 retval = FAIL;
6828 break;
6829 }
6830 }
6831
6832 curbuf = tbuf;
6833 return retval;
6834}
6835
6836/*
6837 * Check if buffer "buf" has been changed.
6838 * Also check if the file for a new buffer unexpectedly appeared.
6839 * return 1 if a changed buffer was found.
6840 * return 2 if a message has been displayed.
6841 * return 0 otherwise.
6842 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006843 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006844buf_check_timestamp(
6845 buf_T *buf,
6846 int focus UNUSED) /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006847{
Bram Moolenaar8767f522016-07-01 17:17:39 +02006848 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006849 int stat_res;
6850 int retval = 0;
6851 char_u *path;
6852 char_u *tbuf;
6853 char *mesg = NULL;
Bram Moolenaar44ecf652005-03-07 23:09:59 +00006854 char *mesg2 = "";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006855 int helpmesg = FALSE;
6856 int reload = FALSE;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006857 char *reason;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006858#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6859 int can_reload = FALSE;
6860#endif
Bram Moolenaar8767f522016-07-01 17:17:39 +02006861 off_T orig_size = buf->b_orig_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006862 int orig_mode = buf->b_orig_mode;
6863#ifdef FEAT_GUI
6864 int save_mouse_correct = need_mouse_correct;
6865#endif
6866#ifdef FEAT_AUTOCMD
6867 static int busy = FALSE;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006868 int n;
6869 char_u *s;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006870 bufref_T bufref;
6871
6872 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006873#endif
6874
6875 /* If there is no file name, the buffer is not loaded, 'buftype' is
6876 * set, we are in the middle of a save or being called recursively: ignore
6877 * this buffer. */
6878 if (buf->b_ffname == NULL
6879 || buf->b_ml.ml_mfp == NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00006880 || *buf->b_p_bt != NUL
Bram Moolenaar071d4272004-06-13 20:20:40 +00006881 || buf->b_saving
6882#ifdef FEAT_AUTOCMD
6883 || busy
6884#endif
Bram Moolenaar009b2592004-10-24 19:18:58 +00006885#ifdef FEAT_NETBEANS_INTG
6886 || isNetbeansBuffer(buf)
6887#endif
Bram Moolenaar8cad9302017-08-12 14:32:32 +02006888#ifdef FEAT_TERMINAL
6889 || buf->b_term != NULL
6890#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006891 )
6892 return 0;
6893
6894 if ( !(buf->b_flags & BF_NOTEDITED)
6895 && buf->b_mtime != 0
6896 && ((stat_res = mch_stat((char *)buf->b_ffname, &st)) < 0
6897 || time_differs((long)st.st_mtime, buf->b_mtime)
Bram Moolenaara7611f62014-05-02 15:46:14 +02006898 || st.st_size != buf->b_orig_size
Bram Moolenaar071d4272004-06-13 20:20:40 +00006899#ifdef HAVE_ST_MODE
6900 || (int)st.st_mode != buf->b_orig_mode
6901#else
6902 || mch_getperm(buf->b_ffname) != buf->b_orig_mode
6903#endif
6904 ))
6905 {
6906 retval = 1;
6907
Bram Moolenaar316059c2006-01-14 21:18:42 +00006908 /* set b_mtime to stop further warnings (e.g., when executing
6909 * FileChangedShell autocmd) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006910 if (stat_res < 0)
6911 {
6912 buf->b_mtime = 0;
6913 buf->b_orig_size = 0;
6914 buf->b_orig_mode = 0;
6915 }
6916 else
6917 buf_store_time(buf, &st, buf->b_ffname);
6918
6919 /* Don't do anything for a directory. Might contain the file
6920 * explorer. */
6921 if (mch_isdir(buf->b_fname))
6922 ;
6923
6924 /*
6925 * If 'autoread' is set, the buffer has no changes and the file still
6926 * exists, reload the buffer. Use the buffer-local option value if it
6927 * was set, the global option value otherwise.
6928 */
6929 else if ((buf->b_p_ar >= 0 ? buf->b_p_ar : p_ar)
6930 && !bufIsChanged(buf) && stat_res >= 0)
6931 reload = TRUE;
6932 else
6933 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006934 if (stat_res < 0)
6935 reason = "deleted";
6936 else if (bufIsChanged(buf))
6937 reason = "conflict";
6938 else if (orig_size != buf->b_orig_size || buf_contents_changed(buf))
6939 reason = "changed";
6940 else if (orig_mode != buf->b_orig_mode)
6941 reason = "mode";
6942 else
6943 reason = "time";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006944
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006945#ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006946 /*
6947 * Only give the warning if there are no FileChangedShell
6948 * autocommands.
6949 * Avoid being called recursively by setting "busy".
6950 */
6951 busy = TRUE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00006952# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006953 set_vim_var_string(VV_FCS_REASON, (char_u *)reason, -1);
6954 set_vim_var_string(VV_FCS_CHOICE, (char_u *)"", -1);
Bram Moolenaar1e015462005-09-25 22:16:38 +00006955# endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006956 ++allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006957 n = apply_autocmds(EVENT_FILECHANGEDSHELL,
6958 buf->b_fname, buf->b_fname, FALSE, buf);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006959 --allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006960 busy = FALSE;
6961 if (n)
6962 {
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006963 if (!bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006964 EMSG(_("E246: FileChangedShell autocommand deleted buffer"));
Bram Moolenaar1e015462005-09-25 22:16:38 +00006965# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006966 s = get_vim_var_str(VV_FCS_CHOICE);
6967 if (STRCMP(s, "reload") == 0 && *reason != 'd')
6968 reload = TRUE;
6969 else if (STRCMP(s, "ask") == 0)
6970 n = FALSE;
6971 else
Bram Moolenaar1e015462005-09-25 22:16:38 +00006972# endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006973 return 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006974 }
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006975 if (!n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006976#endif
6977 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006978 if (*reason == 'd')
6979 mesg = _("E211: File \"%s\" no longer available");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006980 else
6981 {
6982 helpmesg = TRUE;
6983#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6984 can_reload = TRUE;
6985#endif
6986 /*
6987 * Check if the file contents really changed to avoid
6988 * giving a warning when only the timestamp was set (e.g.,
6989 * checked out of CVS). Always warn when the buffer was
6990 * changed.
6991 */
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006992 if (reason[2] == 'n')
6993 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006994 mesg = _("W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006995 mesg2 = _("See \":help W12\" for more info.");
6996 }
6997 else if (reason[1] == 'h')
6998 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006999 mesg = _("W11: Warning: File \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007000 mesg2 = _("See \":help W11\" for more info.");
7001 }
7002 else if (*reason == 'm')
7003 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007004 mesg = _("W16: Warning: Mode of file \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007005 mesg2 = _("See \":help W16\" for more info.");
7006 }
Bram Moolenaar85388b52009-06-24 09:58:32 +00007007 else
7008 /* Only timestamp changed, store it to avoid a warning
7009 * in check_mtime() later. */
7010 buf->b_mtime_read = buf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007011 }
7012 }
7013 }
7014
7015 }
7016 else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W)
7017 && vim_fexists(buf->b_ffname))
7018 {
7019 retval = 1;
7020 mesg = _("W13: Warning: File \"%s\" has been created after editing started");
7021 buf->b_flags |= BF_NEW_W;
7022#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
7023 can_reload = TRUE;
7024#endif
7025 }
7026
7027 if (mesg != NULL)
7028 {
7029 path = home_replace_save(buf, buf->b_fname);
7030 if (path != NULL)
7031 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007032 if (!helpmesg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007033 mesg2 = "";
7034 tbuf = alloc((unsigned)(STRLEN(path) + STRLEN(mesg)
7035 + STRLEN(mesg2) + 2));
7036 sprintf((char *)tbuf, mesg, path);
Bram Moolenaar496c5262009-03-18 14:42:00 +00007037#ifdef FEAT_EVAL
7038 /* Set warningmsg here, before the unimportant and output-specific
7039 * mesg2 has been appended. */
7040 set_vim_var_string(VV_WARNINGMSG, tbuf, -1);
7041#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007042#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
7043 if (can_reload)
7044 {
7045 if (*mesg2 != NUL)
7046 {
7047 STRCAT(tbuf, "\n");
7048 STRCAT(tbuf, mesg2);
7049 }
7050 if (do_dialog(VIM_WARNING, (char_u *)_("Warning"), tbuf,
Bram Moolenaard2c340a2011-01-17 20:08:11 +01007051 (char_u *)_("&OK\n&Load File"), 1, NULL, TRUE) == 2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007052 reload = TRUE;
7053 }
7054 else
7055#endif
7056 if (State > NORMAL_BUSY || (State & CMDLINE) || already_warned)
7057 {
7058 if (*mesg2 != NUL)
7059 {
7060 STRCAT(tbuf, "; ");
7061 STRCAT(tbuf, mesg2);
7062 }
7063 EMSG(tbuf);
7064 retval = 2;
7065 }
7066 else
7067 {
Bram Moolenaared203462004-06-16 11:19:22 +00007068# ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00007069 if (!autocmd_busy)
Bram Moolenaared203462004-06-16 11:19:22 +00007070# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007071 {
7072 msg_start();
Bram Moolenaar8820b482017-03-16 17:23:31 +01007073 msg_puts_attr(tbuf, HL_ATTR(HLF_E) + MSG_HIST);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007074 if (*mesg2 != NUL)
7075 msg_puts_attr((char_u *)mesg2,
Bram Moolenaar8820b482017-03-16 17:23:31 +01007076 HL_ATTR(HLF_W) + MSG_HIST);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007077 msg_clr_eos();
7078 (void)msg_end();
7079 if (emsg_silent == 0)
7080 {
7081 out_flush();
Bram Moolenaared203462004-06-16 11:19:22 +00007082# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00007083 if (!focus)
Bram Moolenaared203462004-06-16 11:19:22 +00007084# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007085 /* give the user some time to think about it */
7086 ui_delay(1000L, TRUE);
7087
7088 /* don't redraw and erase the message */
7089 redraw_cmdline = FALSE;
7090 }
7091 }
7092 already_warned = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007093 }
7094
7095 vim_free(path);
7096 vim_free(tbuf);
7097 }
7098 }
7099
7100 if (reload)
Bram Moolenaar465748e2012-08-29 18:50:54 +02007101 {
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007102 /* Reload the buffer. */
Bram Moolenaar316059c2006-01-14 21:18:42 +00007103 buf_reload(buf, orig_mode);
Bram Moolenaar465748e2012-08-29 18:50:54 +02007104#ifdef FEAT_PERSISTENT_UNDO
7105 if (buf->b_p_udf && buf->b_ffname != NULL)
7106 {
7107 char_u hash[UNDO_HASH_SIZE];
7108 buf_T *save_curbuf = curbuf;
7109
7110 /* Any existing undo file is unusable, write it now. */
7111 curbuf = buf;
7112 u_compute_hash(hash);
7113 u_write_undo(NULL, FALSE, buf, hash);
7114 curbuf = save_curbuf;
7115 }
7116#endif
7117 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007118
Bram Moolenaar56718732006-03-15 22:53:57 +00007119#ifdef FEAT_AUTOCMD
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00007120 /* Trigger FileChangedShell when the file was changed in any way. */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007121 if (bufref_valid(&bufref) && retval != 0)
Bram Moolenaar56718732006-03-15 22:53:57 +00007122 (void)apply_autocmds(EVENT_FILECHANGEDSHELLPOST,
7123 buf->b_fname, buf->b_fname, FALSE, buf);
7124#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007125#ifdef FEAT_GUI
7126 /* restore this in case an autocommand has set it; it would break
7127 * 'mousefocus' */
7128 need_mouse_correct = save_mouse_correct;
7129#endif
7130
7131 return retval;
7132}
7133
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007134/*
7135 * Reload a buffer that is already loaded.
7136 * Used when the file was changed outside of Vim.
Bram Moolenaar316059c2006-01-14 21:18:42 +00007137 * "orig_mode" is buf->b_orig_mode before the need for reloading was detected.
7138 * buf->b_orig_mode may have been reset already.
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007139 */
7140 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007141buf_reload(buf_T *buf, int orig_mode)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007142{
7143 exarg_T ea;
7144 pos_T old_cursor;
7145 linenr_T old_topline;
7146 int old_ro = buf->b_p_ro;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007147 buf_T *savebuf;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007148 bufref_T bufref;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007149 int saved = OK;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007150 aco_save_T aco;
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007151 int flags = READ_NEW;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007152
7153 /* set curwin/curbuf for "buf" and save some things */
7154 aucmd_prepbuf(&aco, buf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007155
7156 /* We only want to read the text from the file, not reset the syntax
7157 * highlighting, clear marks, diff status, etc. Force the fileformat
7158 * and encoding to be the same. */
7159 if (prep_exarg(&ea, buf) == OK)
7160 {
7161 old_cursor = curwin->w_cursor;
7162 old_topline = curwin->w_topline;
7163
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007164 if (p_ur < 0 || curbuf->b_ml.ml_line_count <= p_ur)
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007165 {
7166 /* Save all the text, so that the reload can be undone.
7167 * Sync first so that this is a separate undo-able action. */
7168 u_sync(FALSE);
7169 saved = u_savecommon(0, curbuf->b_ml.ml_line_count + 1, 0, TRUE);
7170 flags |= READ_KEEP_UNDO;
7171 }
7172
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007173 /*
7174 * To behave like when a new file is edited (matters for
7175 * BufReadPost autocommands) we first need to delete the current
7176 * buffer contents. But if reading the file fails we should keep
7177 * the old contents. Can't use memory only, the file might be
7178 * too big. Use a hidden buffer to move the buffer contents to.
7179 */
Bram Moolenaarb5aedf32017-03-12 18:23:53 +01007180 if (BUFEMPTY() || saved == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007181 savebuf = NULL;
7182 else
7183 {
7184 /* Allocate a buffer without putting it in the buffer list. */
7185 savebuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007186 set_bufref(&bufref, savebuf);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007187 if (savebuf != NULL && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007188 {
7189 /* Open the memline. */
7190 curbuf = savebuf;
7191 curwin->w_buffer = savebuf;
Bram Moolenaar4770d092006-01-12 23:22:24 +00007192 saved = ml_open(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007193 curbuf = buf;
7194 curwin->w_buffer = buf;
7195 }
Bram Moolenaar8424a622006-04-19 21:23:36 +00007196 if (savebuf == NULL || saved == FAIL || buf != curbuf
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007197 || move_lines(buf, savebuf) == FAIL)
7198 {
7199 EMSG2(_("E462: Could not prepare for reloading \"%s\""),
7200 buf->b_fname);
7201 saved = FAIL;
7202 }
7203 }
7204
7205 if (saved == OK)
7206 {
7207 curbuf->b_flags |= BF_CHECK_RO; /* check for RO again */
7208#ifdef FEAT_AUTOCMD
7209 keep_filetype = TRUE; /* don't detect 'filetype' */
7210#endif
7211 if (readfile(buf->b_ffname, buf->b_fname, (linenr_T)0,
7212 (linenr_T)0,
Bram Moolenaare13b9af2017-01-13 22:01:02 +01007213 (linenr_T)MAXLNUM, &ea, flags) != OK)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007214 {
7215#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
7216 if (!aborting())
7217#endif
7218 EMSG2(_("E321: Could not reload \"%s\""), buf->b_fname);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007219 if (savebuf != NULL && bufref_valid(&bufref) && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007220 {
7221 /* Put the text back from the save buffer. First
7222 * delete any lines that readfile() added. */
Bram Moolenaarb5aedf32017-03-12 18:23:53 +01007223 while (!BUFEMPTY())
Bram Moolenaar8424a622006-04-19 21:23:36 +00007224 if (ml_delete(buf->b_ml.ml_line_count, FALSE) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007225 break;
7226 (void)move_lines(savebuf, buf);
7227 }
7228 }
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007229 else if (buf == curbuf) /* "buf" still valid */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007230 {
7231 /* Mark the buffer as unmodified and free undo info. */
7232 unchanged(buf, TRUE);
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007233 if ((flags & READ_KEEP_UNDO) == 0)
7234 {
7235 u_blockfree(buf);
7236 u_clearall(buf);
7237 }
7238 else
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007239 {
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007240 /* Mark all undo states as changed. */
7241 u_unchanged(curbuf);
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007242 }
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007243 }
7244 }
7245 vim_free(ea.cmd);
7246
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007247 if (savebuf != NULL && bufref_valid(&bufref))
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007248 wipe_buffer(savebuf, FALSE);
7249
7250#ifdef FEAT_DIFF
7251 /* Invalidate diff info if necessary. */
Bram Moolenaar8424a622006-04-19 21:23:36 +00007252 diff_invalidate(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007253#endif
7254
7255 /* Restore the topline and cursor position and check it (lines may
7256 * have been removed). */
7257 if (old_topline > curbuf->b_ml.ml_line_count)
7258 curwin->w_topline = curbuf->b_ml.ml_line_count;
7259 else
7260 curwin->w_topline = old_topline;
7261 curwin->w_cursor = old_cursor;
7262 check_cursor();
7263 update_topline();
7264#ifdef FEAT_AUTOCMD
7265 keep_filetype = FALSE;
7266#endif
7267#ifdef FEAT_FOLDING
7268 {
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007269 win_T *wp;
7270 tabpage_T *tp;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007271
7272 /* Update folds unless they are defined manually. */
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007273 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007274 if (wp->w_buffer == curwin->w_buffer
7275 && !foldmethodIsManual(wp))
7276 foldUpdateAll(wp);
7277 }
7278#endif
7279 /* If the mode didn't change and 'readonly' was set, keep the old
7280 * value; the user probably used the ":view" command. But don't
7281 * reset it, might have had a read error. */
7282 if (orig_mode == curbuf->b_orig_mode)
7283 curbuf->b_p_ro |= old_ro;
Bram Moolenaar52f85b72013-01-30 14:13:56 +01007284
7285 /* Modelines must override settings done by autocommands. */
7286 do_modelines(0);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007287 }
7288
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007289 /* restore curwin/curbuf and a few other things */
7290 aucmd_restbuf(&aco);
7291 /* Careful: autocommands may have made "buf" invalid! */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007292}
7293
Bram Moolenaar071d4272004-06-13 20:20:40 +00007294 void
Bram Moolenaar8767f522016-07-01 17:17:39 +02007295buf_store_time(buf_T *buf, stat_T *st, char_u *fname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007296{
7297 buf->b_mtime = (long)st->st_mtime;
Bram Moolenaar914703b2010-05-31 21:59:46 +02007298 buf->b_orig_size = st->st_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007299#ifdef HAVE_ST_MODE
7300 buf->b_orig_mode = (int)st->st_mode;
7301#else
7302 buf->b_orig_mode = mch_getperm(fname);
7303#endif
7304}
7305
7306/*
7307 * Adjust the line with missing eol, used for the next write.
7308 * Used for do_filter(), when the input lines for the filter are deleted.
7309 */
7310 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007311write_lnum_adjust(linenr_T offset)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007312{
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01007313 if (curbuf->b_no_eol_lnum != 0) /* only if there is a missing eol */
7314 curbuf->b_no_eol_lnum += offset;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007315}
7316
Bram Moolenaarda440d22016-01-16 21:27:23 +01007317#if defined(TEMPDIRNAMES) || defined(FEAT_EVAL) || defined(PROTO)
7318/*
7319 * Delete "name" and everything in it, recursively.
7320 * return 0 for succes, -1 if some file was not deleted.
7321 */
7322 int
7323delete_recursive(char_u *name)
7324{
7325 int result = 0;
7326 char_u **files;
7327 int file_count;
7328 int i;
7329 char_u *exp;
7330
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007331 /* A symbolic link to a directory itself is deleted, not the directory it
7332 * points to. */
7333 if (
Bram Moolenaar203258c2016-01-17 22:15:16 +01007334# if defined(UNIX) || defined(WIN32)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007335 mch_isrealdir(name)
Bram Moolenaar203258c2016-01-17 22:15:16 +01007336# else
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007337 mch_isdir(name)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007338# endif
7339 )
Bram Moolenaarda440d22016-01-16 21:27:23 +01007340 {
7341 vim_snprintf((char *)NameBuff, MAXPATHL, "%s/*", name);
7342 exp = vim_strsave(NameBuff);
7343 if (exp == NULL)
7344 return -1;
7345 if (gen_expand_wildcards(1, &exp, &file_count, &files,
Bram Moolenaar336bd622016-01-17 18:23:58 +01007346 EW_DIR|EW_FILE|EW_SILENT|EW_ALLLINKS|EW_DODOT|EW_EMPTYOK) == OK)
Bram Moolenaarda440d22016-01-16 21:27:23 +01007347 {
7348 for (i = 0; i < file_count; ++i)
7349 if (delete_recursive(files[i]) != 0)
7350 result = -1;
7351 FreeWild(file_count, files);
7352 }
7353 else
7354 result = -1;
7355 vim_free(exp);
7356 (void)mch_rmdir(name);
7357 }
7358 else
7359 result = mch_remove(name) == 0 ? 0 : -1;
7360
7361 return result;
7362}
7363#endif
7364
Bram Moolenaar071d4272004-06-13 20:20:40 +00007365#if defined(TEMPDIRNAMES) || defined(PROTO)
7366static long temp_count = 0; /* Temp filename counter. */
7367
7368/*
7369 * Delete the temp directory and all files it contains.
7370 */
7371 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007372vim_deltempdir(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007373{
Bram Moolenaar071d4272004-06-13 20:20:40 +00007374 if (vim_tempdir != NULL)
7375 {
Bram Moolenaarda440d22016-01-16 21:27:23 +01007376 /* remove the trailing path separator */
7377 gettail(vim_tempdir)[-1] = NUL;
7378 delete_recursive(vim_tempdir);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007379 vim_free(vim_tempdir);
7380 vim_tempdir = NULL;
7381 }
7382}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007383
7384/*
Bram Moolenaareaf03392009-11-17 11:08:52 +00007385 * Directory "tempdir" was created. Expand this name to a full path and put
7386 * it in "vim_tempdir". This avoids that using ":cd" would confuse us.
7387 * "tempdir" must be no longer than MAXPATHL.
7388 */
7389 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007390vim_settempdir(char_u *tempdir)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007391{
7392 char_u *buf;
7393
7394 buf = alloc((unsigned)MAXPATHL + 2);
7395 if (buf != NULL)
7396 {
7397 if (vim_FullName(tempdir, buf, MAXPATHL, FALSE) == FAIL)
7398 STRCPY(buf, tempdir);
Bram Moolenaara06ecab2016-07-16 14:47:36 +02007399 add_pathsep(buf);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007400 vim_tempdir = vim_strsave(buf);
7401 vim_free(buf);
7402 }
7403}
Bram Moolenaar4592dee2009-11-18 19:11:58 +00007404#endif
Bram Moolenaareaf03392009-11-17 11:08:52 +00007405
7406/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007407 * vim_tempname(): Return a unique name that can be used for a temp file.
7408 *
Bram Moolenaar76ae22f2016-06-13 20:00:29 +02007409 * The temp file is NOT guaranteed to be created. If "keep" is FALSE it is
7410 * guaranteed to NOT be created.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007411 *
7412 * The returned pointer is to allocated memory.
7413 * The returned pointer is NULL if no valid name was found.
7414 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007415 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007416vim_tempname(
7417 int extra_char UNUSED, /* char to use in the name instead of '?' */
7418 int keep UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007419{
7420#ifdef USE_TMPNAM
7421 char_u itmp[L_tmpnam]; /* use tmpnam() */
7422#else
7423 char_u itmp[TEMPNAMELEN];
7424#endif
7425
7426#ifdef TEMPDIRNAMES
7427 static char *(tempdirs[]) = {TEMPDIRNAMES};
7428 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007429# ifndef EEXIST
Bram Moolenaar8767f522016-07-01 17:17:39 +02007430 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007431# endif
7432
7433 /*
7434 * This will create a directory for private use by this instance of Vim.
7435 * This is done once, and the same directory is used for all temp files.
7436 * This method avoids security problems because of symlink attacks et al.
7437 * It's also a bit faster, because we only need to check for an existing
7438 * file when creating the directory and not for each temp file.
7439 */
7440 if (vim_tempdir == NULL)
7441 {
7442 /*
7443 * Try the entries in TEMPDIRNAMES to create the temp directory.
7444 */
Bram Moolenaar78a15312009-05-15 19:33:18 +00007445 for (i = 0; i < (int)(sizeof(tempdirs) / sizeof(char *)); ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007446 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007447# ifndef HAVE_MKDTEMP
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007448 size_t itmplen;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007449 long nr;
7450 long off;
7451# endif
7452
Bram Moolenaare1a61992015-12-03 21:02:27 +01007453 /* Expand $TMP, leave room for "/v1100000/999999999".
7454 * Skip the directory check if the expansion fails. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007455 expand_env((char_u *)tempdirs[i], itmp, TEMPNAMELEN - 20);
Bram Moolenaare1a61992015-12-03 21:02:27 +01007456 if (itmp[0] != '$' && mch_isdir(itmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007457 {
Bram Moolenaare1a61992015-12-03 21:02:27 +01007458 /* directory exists */
Bram Moolenaara06ecab2016-07-16 14:47:36 +02007459 add_pathsep(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007460
Bram Moolenaareaf03392009-11-17 11:08:52 +00007461# ifdef HAVE_MKDTEMP
Bram Moolenaar35d88f42016-06-04 14:52:00 +02007462 {
7463# if defined(UNIX) || defined(VMS)
7464 /* Make sure the umask doesn't remove the executable bit.
7465 * "repl" has been reported to use "177". */
7466 mode_t umask_save = umask(077);
7467# endif
7468 /* Leave room for filename */
7469 STRCAT(itmp, "vXXXXXX");
7470 if (mkdtemp((char *)itmp) != NULL)
7471 vim_settempdir(itmp);
7472# if defined(UNIX) || defined(VMS)
7473 (void)umask(umask_save);
7474# endif
7475 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007476# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007477 /* Get an arbitrary number of up to 6 digits. When it's
7478 * unlikely that it already exists it will be faster,
7479 * otherwise it doesn't matter. The use of mkdir() avoids any
7480 * security problems because of the predictable number. */
7481 nr = (mch_get_pid() + (long)time(NULL)) % 1000000L;
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007482 itmplen = STRLEN(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007483
7484 /* Try up to 10000 different values until we find a name that
7485 * doesn't exist. */
7486 for (off = 0; off < 10000L; ++off)
7487 {
7488 int r;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007489# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007490 mode_t umask_save;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007491# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007492
Bram Moolenaareaf03392009-11-17 11:08:52 +00007493 sprintf((char *)itmp + itmplen, "v%ld", nr + off);
7494# ifndef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007495 /* If mkdir() does not set errno to EEXIST, check for
7496 * existing file here. There is a race condition then,
7497 * although it's fail-safe. */
7498 if (mch_stat((char *)itmp, &st) >= 0)
7499 continue;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007500# endif
7501# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007502 /* Make sure the umask doesn't remove the executable bit.
7503 * "repl" has been reported to use "177". */
7504 umask_save = umask(077);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007505# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007506 r = vim_mkdir(itmp, 0700);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007507# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007508 (void)umask(umask_save);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007509# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007510 if (r == 0)
7511 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007512 vim_settempdir(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007513 break;
7514 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007515# ifdef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007516 /* If the mkdir() didn't fail because the file/dir exists,
7517 * we probably can't create any dir here, try another
7518 * place. */
7519 if (errno != EEXIST)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007520# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007521 break;
7522 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007523# endif /* HAVE_MKDTEMP */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007524 if (vim_tempdir != NULL)
7525 break;
7526 }
7527 }
7528 }
7529
7530 if (vim_tempdir != NULL)
7531 {
7532 /* There is no need to check if the file exists, because we own the
7533 * directory and nobody else creates a file in it. */
7534 sprintf((char *)itmp, "%s%ld", vim_tempdir, temp_count++);
7535 return vim_strsave(itmp);
7536 }
7537
7538 return NULL;
7539
7540#else /* TEMPDIRNAMES */
7541
7542# ifdef WIN3264
7543 char szTempFile[_MAX_PATH + 1];
7544 char buf4[4];
7545 char_u *retval;
7546 char_u *p;
7547
7548 STRCPY(itmp, "");
7549 if (GetTempPath(_MAX_PATH, szTempFile) == 0)
Bram Moolenaarb1891912011-02-09 14:47:03 +01007550 {
7551 szTempFile[0] = '.'; /* GetTempPath() failed, use current dir */
7552 szTempFile[1] = NUL;
7553 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007554 strcpy(buf4, "VIM");
7555 buf4[2] = extra_char; /* make it "VIa", "VIb", etc. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007556 if (GetTempFileName(szTempFile, buf4, 0, (LPSTR)itmp) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007557 return NULL;
Bram Moolenaare5c421c2015-03-31 13:33:08 +02007558 if (!keep)
7559 /* GetTempFileName() will create the file, we don't want that */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007560 (void)DeleteFile((LPSTR)itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007561
7562 /* Backslashes in a temp file name cause problems when filtering with
7563 * "sh". NOTE: This also checks 'shellcmdflag' to help those people who
7564 * didn't set 'shellslash'. */
7565 retval = vim_strsave(itmp);
7566 if (*p_shcf == '-' || p_ssl)
7567 for (p = retval; *p; ++p)
7568 if (*p == '\\')
7569 *p = '/';
7570 return retval;
7571
7572# else /* WIN3264 */
7573
7574# ifdef USE_TMPNAM
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007575 char_u *p;
7576
Bram Moolenaar071d4272004-06-13 20:20:40 +00007577 /* tmpnam() will make its own name */
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007578 p = tmpnam((char *)itmp);
7579 if (p == NULL || *p == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007580 return NULL;
7581# else
7582 char_u *p;
7583
7584# ifdef VMS_TEMPNAM
7585 /* mktemp() is not working on VMS. It seems to be
7586 * a do-nothing function. Therefore we use tempnam().
7587 */
7588 sprintf((char *)itmp, "VIM%c", extra_char);
7589 p = (char_u *)tempnam("tmp:", (char *)itmp);
7590 if (p != NULL)
7591 {
Bram Moolenaar206f0112014-03-12 16:51:55 +01007592 /* VMS will use '.LIS' if we don't explicitly specify an extension,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007593 * and VIM will then be unable to find the file later */
7594 STRCPY(itmp, p);
7595 STRCAT(itmp, ".txt");
7596 free(p);
7597 }
7598 else
7599 return NULL;
7600# else
7601 STRCPY(itmp, TEMPNAME);
7602 if ((p = vim_strchr(itmp, '?')) != NULL)
7603 *p = extra_char;
7604 if (mktemp((char *)itmp) == NULL)
7605 return NULL;
7606# endif
7607# endif
7608
7609 return vim_strsave(itmp);
7610# endif /* WIN3264 */
7611#endif /* TEMPDIRNAMES */
7612}
7613
7614#if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
7615/*
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02007616 * Convert all backslashes in fname to forward slashes in-place, unless when
7617 * it looks like a URL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007618 */
7619 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007620forward_slash(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007621{
7622 char_u *p;
7623
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02007624 if (path_with_url(fname))
7625 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007626 for (p = fname; *p != NUL; ++p)
7627# ifdef FEAT_MBYTE
7628 /* The Big5 encoding can have '\' in the trail byte. */
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00007629 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007630 ++p;
7631 else
7632# endif
7633 if (*p == '\\')
7634 *p = '/';
7635}
7636#endif
7637
7638
7639/*
7640 * Code for automatic commands.
7641 *
7642 * Only included when "FEAT_AUTOCMD" has been defined.
7643 */
7644
7645#if defined(FEAT_AUTOCMD) || defined(PROTO)
7646
7647/*
7648 * The autocommands are stored in a list for each event.
7649 * Autocommands for the same pattern, that are consecutive, are joined
7650 * together, to avoid having to match the pattern too often.
7651 * The result is an array of Autopat lists, which point to AutoCmd lists:
7652 *
Bram Moolenaar462455e2017-11-10 21:53:11 +01007653 * last_autopat[0] -----------------------------+
7654 * V
Bram Moolenaar071d4272004-06-13 20:20:40 +00007655 * first_autopat[0] --> Autopat.next --> Autopat.next --> NULL
7656 * Autopat.cmds Autopat.cmds
7657 * | |
7658 * V V
7659 * AutoCmd.next AutoCmd.next
7660 * | |
7661 * V V
7662 * AutoCmd.next NULL
7663 * |
7664 * V
7665 * NULL
7666 *
Bram Moolenaar462455e2017-11-10 21:53:11 +01007667 * last_autopat[1] --------+
7668 * V
Bram Moolenaar071d4272004-06-13 20:20:40 +00007669 * first_autopat[1] --> Autopat.next --> NULL
7670 * Autopat.cmds
7671 * |
7672 * V
7673 * AutoCmd.next
7674 * |
7675 * V
7676 * NULL
7677 * etc.
7678 *
7679 * The order of AutoCmds is important, this is the order in which they were
7680 * defined and will have to be executed.
7681 */
7682typedef struct AutoCmd
7683{
7684 char_u *cmd; /* The command to be executed (NULL
7685 when command has been removed) */
7686 char nested; /* If autocommands nest here */
7687 char last; /* last command in list */
7688#ifdef FEAT_EVAL
7689 scid_T scriptID; /* script ID where defined */
7690#endif
7691 struct AutoCmd *next; /* Next AutoCmd in list */
7692} AutoCmd;
7693
7694typedef struct AutoPat
7695{
Bram Moolenaar462455e2017-11-10 21:53:11 +01007696 struct AutoPat *next; /* next AutoPat in AutoPat list; MUST
7697 * be the first entry */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007698 char_u *pat; /* pattern as typed (NULL when pattern
7699 has been removed) */
Bram Moolenaar748bf032005-02-02 23:04:36 +00007700 regprog_T *reg_prog; /* compiled regprog for pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007701 AutoCmd *cmds; /* list of commands to do */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007702 int group; /* group ID */
7703 int patlen; /* strlen() of pat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007704 int buflocal_nr; /* !=0 for buffer-local AutoPat */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007705 char allow_dirs; /* Pattern may match whole path */
7706 char last; /* last pattern for apply_autocmds() */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007707} AutoPat;
7708
7709static struct event_name
7710{
7711 char *name; /* event name */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007712 event_T event; /* event number */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007713} event_names[] =
7714{
7715 {"BufAdd", EVENT_BUFADD},
7716 {"BufCreate", EVENT_BUFADD},
7717 {"BufDelete", EVENT_BUFDELETE},
7718 {"BufEnter", EVENT_BUFENTER},
7719 {"BufFilePost", EVENT_BUFFILEPOST},
7720 {"BufFilePre", EVENT_BUFFILEPRE},
7721 {"BufHidden", EVENT_BUFHIDDEN},
7722 {"BufLeave", EVENT_BUFLEAVE},
7723 {"BufNew", EVENT_BUFNEW},
7724 {"BufNewFile", EVENT_BUFNEWFILE},
7725 {"BufRead", EVENT_BUFREADPOST},
7726 {"BufReadCmd", EVENT_BUFREADCMD},
7727 {"BufReadPost", EVENT_BUFREADPOST},
7728 {"BufReadPre", EVENT_BUFREADPRE},
7729 {"BufUnload", EVENT_BUFUNLOAD},
7730 {"BufWinEnter", EVENT_BUFWINENTER},
7731 {"BufWinLeave", EVENT_BUFWINLEAVE},
7732 {"BufWipeout", EVENT_BUFWIPEOUT},
7733 {"BufWrite", EVENT_BUFWRITEPRE},
7734 {"BufWritePost", EVENT_BUFWRITEPOST},
7735 {"BufWritePre", EVENT_BUFWRITEPRE},
7736 {"BufWriteCmd", EVENT_BUFWRITECMD},
Bram Moolenaarfafcf0d2017-10-19 18:35:51 +02007737 {"CmdlineEnter", EVENT_CMDLINEENTER},
7738 {"CmdlineLeave", EVENT_CMDLINELEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007739 {"CmdwinEnter", EVENT_CMDWINENTER},
7740 {"CmdwinLeave", EVENT_CMDWINLEAVE},
Bram Moolenaard5005162014-08-22 23:05:54 +02007741 {"CmdUndefined", EVENT_CMDUNDEFINED},
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007742 {"ColorScheme", EVENT_COLORSCHEME},
Bram Moolenaarcfa3cae2012-07-10 17:14:56 +02007743 {"CompleteDone", EVENT_COMPLETEDONE},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007744 {"CursorHold", EVENT_CURSORHOLD},
7745 {"CursorHoldI", EVENT_CURSORHOLDI},
7746 {"CursorMoved", EVENT_CURSORMOVED},
7747 {"CursorMovedI", EVENT_CURSORMOVEDI},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007748 {"EncodingChanged", EVENT_ENCODINGCHANGED},
7749 {"FileEncoding", EVENT_ENCODINGCHANGED},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007750 {"FileAppendPost", EVENT_FILEAPPENDPOST},
7751 {"FileAppendPre", EVENT_FILEAPPENDPRE},
7752 {"FileAppendCmd", EVENT_FILEAPPENDCMD},
7753 {"FileChangedShell",EVENT_FILECHANGEDSHELL},
Bram Moolenaar56718732006-03-15 22:53:57 +00007754 {"FileChangedShellPost",EVENT_FILECHANGEDSHELLPOST},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007755 {"FileChangedRO", EVENT_FILECHANGEDRO},
7756 {"FileReadPost", EVENT_FILEREADPOST},
7757 {"FileReadPre", EVENT_FILEREADPRE},
7758 {"FileReadCmd", EVENT_FILEREADCMD},
7759 {"FileType", EVENT_FILETYPE},
7760 {"FileWritePost", EVENT_FILEWRITEPOST},
7761 {"FileWritePre", EVENT_FILEWRITEPRE},
7762 {"FileWriteCmd", EVENT_FILEWRITECMD},
7763 {"FilterReadPost", EVENT_FILTERREADPOST},
7764 {"FilterReadPre", EVENT_FILTERREADPRE},
7765 {"FilterWritePost", EVENT_FILTERWRITEPOST},
7766 {"FilterWritePre", EVENT_FILTERWRITEPRE},
7767 {"FocusGained", EVENT_FOCUSGAINED},
7768 {"FocusLost", EVENT_FOCUSLOST},
7769 {"FuncUndefined", EVENT_FUNCUNDEFINED},
7770 {"GUIEnter", EVENT_GUIENTER},
Bram Moolenaar265e5072006-08-29 16:13:22 +00007771 {"GUIFailed", EVENT_GUIFAILED},
Bram Moolenaar843ee412004-06-30 16:16:41 +00007772 {"InsertChange", EVENT_INSERTCHANGE},
7773 {"InsertEnter", EVENT_INSERTENTER},
7774 {"InsertLeave", EVENT_INSERTLEAVE},
Bram Moolenaare659c952011-05-19 17:25:41 +02007775 {"InsertCharPre", EVENT_INSERTCHARPRE},
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00007776 {"MenuPopup", EVENT_MENUPOPUP},
Bram Moolenaar53744302015-07-17 17:38:22 +02007777 {"OptionSet", EVENT_OPTIONSET},
Bram Moolenaar7c626922005-02-07 22:01:03 +00007778 {"QuickFixCmdPost", EVENT_QUICKFIXCMDPOST},
7779 {"QuickFixCmdPre", EVENT_QUICKFIXCMDPRE},
Bram Moolenaar3b53dfb2012-06-06 18:03:07 +02007780 {"QuitPre", EVENT_QUITPRE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007781 {"RemoteReply", EVENT_REMOTEREPLY},
Bram Moolenaar9372a112005-12-06 19:59:18 +00007782 {"SessionLoadPost", EVENT_SESSIONLOADPOST},
Bram Moolenaar5c4bab02006-03-10 21:37:46 +00007783 {"ShellCmdPost", EVENT_SHELLCMDPOST},
7784 {"ShellFilterPost", EVENT_SHELLFILTERPOST},
Bram Moolenaara2031822006-03-07 22:29:51 +00007785 {"SourcePre", EVENT_SOURCEPRE},
Bram Moolenaar8dd1aa52007-01-16 20:33:19 +00007786 {"SourceCmd", EVENT_SOURCECMD},
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00007787 {"SpellFileMissing",EVENT_SPELLFILEMISSING},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007788 {"StdinReadPost", EVENT_STDINREADPOST},
7789 {"StdinReadPre", EVENT_STDINREADPRE},
Bram Moolenaarb815dac2005-12-07 20:59:24 +00007790 {"SwapExists", EVENT_SWAPEXISTS},
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00007791 {"Syntax", EVENT_SYNTAX},
Bram Moolenaarc917da42016-07-19 22:31:36 +02007792 {"TabNew", EVENT_TABNEW},
Bram Moolenaar12c11d52016-07-19 23:13:03 +02007793 {"TabClosed", EVENT_TABCLOSED},
Bram Moolenaar70836c82006-02-20 21:28:49 +00007794 {"TabEnter", EVENT_TABENTER},
7795 {"TabLeave", EVENT_TABLEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007796 {"TermChanged", EVENT_TERMCHANGED},
7797 {"TermResponse", EVENT_TERMRESPONSE},
Bram Moolenaar186628f2013-03-19 13:33:23 +01007798 {"TextChanged", EVENT_TEXTCHANGED},
7799 {"TextChangedI", EVENT_TEXTCHANGEDI},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007800 {"User", EVENT_USER},
7801 {"VimEnter", EVENT_VIMENTER},
7802 {"VimLeave", EVENT_VIMLEAVE},
7803 {"VimLeavePre", EVENT_VIMLEAVEPRE},
Bram Moolenaarc917da42016-07-19 22:31:36 +02007804 {"WinNew", EVENT_WINNEW},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007805 {"WinEnter", EVENT_WINENTER},
7806 {"WinLeave", EVENT_WINLEAVE},
Bram Moolenaar56718732006-03-15 22:53:57 +00007807 {"VimResized", EVENT_VIMRESIZED},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007808 {NULL, (event_T)0}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007809};
7810
7811static AutoPat *first_autopat[NUM_EVENTS] =
7812{
7813 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7814 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7815 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7816 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00007817 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaar53744302015-07-17 17:38:22 +02007818 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007819};
7820
Bram Moolenaar462455e2017-11-10 21:53:11 +01007821static AutoPat *last_autopat[NUM_EVENTS] =
7822{
7823 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7824 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7825 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7826 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7827 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7828 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
7829};
7830
Bram Moolenaar071d4272004-06-13 20:20:40 +00007831/*
7832 * struct used to keep status while executing autocommands for an event.
7833 */
7834typedef struct AutoPatCmd
7835{
7836 AutoPat *curpat; /* next AutoPat to examine */
7837 AutoCmd *nextcmd; /* next AutoCmd to execute */
7838 int group; /* group being used */
7839 char_u *fname; /* fname to match with */
7840 char_u *sfname; /* sfname to match with */
7841 char_u *tail; /* tail of fname */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007842 event_T event; /* current event */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007843 int arg_bufnr; /* initially equal to <abuf>, set to zero when
7844 buf is deleted */
7845 struct AutoPatCmd *next; /* chain of active apc-s for auto-invalidation*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00007846} AutoPatCmd;
7847
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007848static AutoPatCmd *active_apc_list = NULL; /* stack of active autocommands */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007849
Bram Moolenaar071d4272004-06-13 20:20:40 +00007850/*
7851 * augroups stores a list of autocmd group names.
7852 */
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007853static garray_T augroups = {0, 0, sizeof(char_u *), 10, NULL};
Bram Moolenaar071d4272004-06-13 20:20:40 +00007854#define AUGROUP_NAME(i) (((char_u **)augroups.ga_data)[i])
Bram Moolenaarb62cc362016-09-03 16:43:53 +02007855/* use get_deleted_augroup() to get this */
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02007856static char_u *deleted_augroup = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007857
7858/*
7859 * The ID of the current group. Group 0 is the default one.
7860 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007861static int current_augroup = AUGROUP_DEFAULT;
7862
7863static int au_need_clean = FALSE; /* need to delete marked patterns */
7864
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007865static void show_autocmd(AutoPat *ap, event_T event);
7866static void au_remove_pat(AutoPat *ap);
7867static void au_remove_cmds(AutoPat *ap);
7868static void au_cleanup(void);
7869static int au_new_group(char_u *name);
7870static void au_del_group(char_u *name);
7871static event_T event_name2nr(char_u *start, char_u **end);
7872static char_u *event_nr2name(event_T event);
7873static char_u *find_end_event(char_u *arg, int have_group);
7874static int event_ignored(event_T event);
7875static int au_get_grouparg(char_u **argp);
7876static int do_autocmd_event(event_T event, char_u *pat, int nested, char_u *cmd, int forceit, int group);
7877static int apply_autocmds_group(event_T event, char_u *fname, char_u *fname_io, int force, int group, buf_T *buf, exarg_T *eap);
7878static void auto_next_pat(AutoPatCmd *apc, int stop_at_last);
Bram Moolenaardffa5b82014-11-19 16:38:07 +01007879#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN)
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007880static 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 +01007881#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007882
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007883
Bram Moolenaar754b5602006-02-09 23:53:20 +00007884static event_T last_event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007885static int last_group;
Bram Moolenaar78ab3312007-09-29 12:16:41 +00007886static int autocmd_blocked = 0; /* block all autocmds */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007887
Bram Moolenaarb62cc362016-09-03 16:43:53 +02007888 static char_u *
7889get_deleted_augroup(void)
7890{
7891 if (deleted_augroup == NULL)
7892 deleted_augroup = (char_u *)_("--Deleted--");
7893 return deleted_augroup;
7894}
7895
Bram Moolenaar071d4272004-06-13 20:20:40 +00007896/*
7897 * Show the autocommands for one AutoPat.
7898 */
7899 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007900show_autocmd(AutoPat *ap, event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007901{
7902 AutoCmd *ac;
7903
7904 /* Check for "got_int" (here and at various places below), which is set
7905 * when "q" has been hit for the "--more--" prompt */
7906 if (got_int)
7907 return;
7908 if (ap->pat == NULL) /* pattern has been removed */
7909 return;
7910
7911 msg_putchar('\n');
7912 if (got_int)
7913 return;
7914 if (event != last_event || ap->group != last_group)
7915 {
7916 if (ap->group != AUGROUP_DEFAULT)
7917 {
7918 if (AUGROUP_NAME(ap->group) == NULL)
Bram Moolenaar8820b482017-03-16 17:23:31 +01007919 msg_puts_attr(get_deleted_augroup(), HL_ATTR(HLF_E));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007920 else
Bram Moolenaar8820b482017-03-16 17:23:31 +01007921 msg_puts_attr(AUGROUP_NAME(ap->group), HL_ATTR(HLF_T));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007922 msg_puts((char_u *)" ");
7923 }
Bram Moolenaar8820b482017-03-16 17:23:31 +01007924 msg_puts_attr(event_nr2name(event), HL_ATTR(HLF_T));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007925 last_event = event;
7926 last_group = ap->group;
7927 msg_putchar('\n');
7928 if (got_int)
7929 return;
7930 }
7931 msg_col = 4;
7932 msg_outtrans(ap->pat);
7933
7934 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7935 {
7936 if (ac->cmd != NULL) /* skip removed commands */
7937 {
7938 if (msg_col >= 14)
7939 msg_putchar('\n');
7940 msg_col = 14;
7941 if (got_int)
7942 return;
7943 msg_outtrans(ac->cmd);
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00007944#ifdef FEAT_EVAL
7945 if (p_verbose > 0)
7946 last_set_msg(ac->scriptID);
7947#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007948 if (got_int)
7949 return;
7950 if (ac->next != NULL)
7951 {
7952 msg_putchar('\n');
7953 if (got_int)
7954 return;
7955 }
7956 }
7957 }
7958}
7959
7960/*
7961 * Mark an autocommand pattern for deletion.
7962 */
7963 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007964au_remove_pat(AutoPat *ap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007965{
7966 vim_free(ap->pat);
7967 ap->pat = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007968 ap->buflocal_nr = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007969 au_need_clean = TRUE;
7970}
7971
7972/*
7973 * Mark all commands for a pattern for deletion.
7974 */
7975 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007976au_remove_cmds(AutoPat *ap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007977{
7978 AutoCmd *ac;
7979
7980 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7981 {
7982 vim_free(ac->cmd);
7983 ac->cmd = NULL;
7984 }
7985 au_need_clean = TRUE;
7986}
7987
7988/*
7989 * Cleanup autocommands and patterns that have been deleted.
7990 * This is only done when not executing autocommands.
7991 */
7992 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007993au_cleanup(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007994{
7995 AutoPat *ap, **prev_ap;
7996 AutoCmd *ac, **prev_ac;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007997 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007998
7999 if (autocmd_busy || !au_need_clean)
8000 return;
8001
8002 /* loop over all events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008003 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8004 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008005 {
8006 /* loop over all autocommand patterns */
8007 prev_ap = &(first_autopat[(int)event]);
8008 for (ap = *prev_ap; ap != NULL; ap = *prev_ap)
8009 {
8010 /* loop over all commands for this pattern */
8011 prev_ac = &(ap->cmds);
8012 for (ac = *prev_ac; ac != NULL; ac = *prev_ac)
8013 {
8014 /* remove the command if the pattern is to be deleted or when
8015 * the command has been marked for deletion */
8016 if (ap->pat == NULL || ac->cmd == NULL)
8017 {
8018 *prev_ac = ac->next;
8019 vim_free(ac->cmd);
8020 vim_free(ac);
8021 }
8022 else
8023 prev_ac = &(ac->next);
8024 }
8025
8026 /* remove the pattern if it has been marked for deletion */
8027 if (ap->pat == NULL)
8028 {
Bram Moolenaar462455e2017-11-10 21:53:11 +01008029 if (ap->next == NULL)
8030 {
8031 if (prev_ap == &(first_autopat[(int)event]))
8032 last_autopat[(int)event] = NULL;
8033 else
8034 /* this depends on the "next" field being the first in
8035 * the struct */
8036 last_autopat[(int)event] = (AutoPat *)prev_ap;
8037 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008038 *prev_ap = ap->next;
Bram Moolenaar473de612013-06-08 18:19:48 +02008039 vim_regfree(ap->reg_prog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008040 vim_free(ap);
8041 }
8042 else
8043 prev_ap = &(ap->next);
8044 }
8045 }
8046
8047 au_need_clean = FALSE;
8048}
8049
8050/*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008051 * Called when buffer is freed, to remove/invalidate related buffer-local
8052 * autocmds.
8053 */
8054 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008055aubuflocal_remove(buf_T *buf)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008056{
8057 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008058 event_T event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008059 AutoPatCmd *apc;
8060
8061 /* invalidate currently executing autocommands */
8062 for (apc = active_apc_list; apc; apc = apc->next)
8063 if (buf->b_fnum == apc->arg_bufnr)
8064 apc->arg_bufnr = 0;
8065
8066 /* invalidate buflocals looping through events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008067 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8068 event = (event_T)((int)event + 1))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008069 /* loop over all autocommand patterns */
8070 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8071 if (ap->buflocal_nr == buf->b_fnum)
8072 {
8073 au_remove_pat(ap);
8074 if (p_verbose >= 6)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00008075 {
8076 verbose_enter();
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008077 smsg((char_u *)
8078 _("auto-removing autocommand: %s <buffer=%d>"),
8079 event_nr2name(event), buf->b_fnum);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00008080 verbose_leave();
8081 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008082 }
8083 au_cleanup();
8084}
8085
8086/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008087 * Add an autocmd group name.
8088 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
8089 */
8090 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008091au_new_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008092{
8093 int i;
8094
8095 i = au_find_group(name);
8096 if (i == AUGROUP_ERROR) /* the group doesn't exist yet, add it */
8097 {
8098 /* First try using a free entry. */
8099 for (i = 0; i < augroups.ga_len; ++i)
8100 if (AUGROUP_NAME(i) == NULL)
8101 break;
8102 if (i == augroups.ga_len && ga_grow(&augroups, 1) == FAIL)
8103 return AUGROUP_ERROR;
8104
8105 AUGROUP_NAME(i) = vim_strsave(name);
8106 if (AUGROUP_NAME(i) == NULL)
8107 return AUGROUP_ERROR;
8108 if (i == augroups.ga_len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008109 ++augroups.ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008110 }
8111
8112 return i;
8113}
8114
8115 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008116au_del_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008117{
8118 int i;
8119
8120 i = au_find_group(name);
8121 if (i == AUGROUP_ERROR) /* the group doesn't exist */
8122 EMSG2(_("E367: No such group: \"%s\""), name);
Bram Moolenaarde653f02016-09-03 16:59:06 +02008123 else if (i == current_augroup)
8124 EMSG(_("E936: Cannot delete the current group"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008125 else
8126 {
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008127 event_T event;
8128 AutoPat *ap;
8129 int in_use = FALSE;
8130
8131 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8132 event = (event_T)((int)event + 1))
8133 {
8134 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
Bram Moolenaar5c809082016-09-01 16:21:48 +02008135 if (ap->group == i && ap->pat != NULL)
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008136 {
8137 give_warning((char_u *)_("W19: Deleting augroup that is still in use"), TRUE);
8138 in_use = TRUE;
8139 event = NUM_EVENTS;
8140 break;
8141 }
8142 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008143 vim_free(AUGROUP_NAME(i));
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008144 if (in_use)
8145 {
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008146 AUGROUP_NAME(i) = get_deleted_augroup();
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008147 }
8148 else
8149 AUGROUP_NAME(i) = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008150 }
8151}
8152
8153/*
8154 * Find the ID of an autocmd group name.
8155 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
8156 */
8157 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008158au_find_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008159{
8160 int i;
8161
8162 for (i = 0; i < augroups.ga_len; ++i)
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008163 if (AUGROUP_NAME(i) != NULL && AUGROUP_NAME(i) != get_deleted_augroup()
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008164 && STRCMP(AUGROUP_NAME(i), name) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008165 return i;
8166 return AUGROUP_ERROR;
8167}
8168
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008169/*
8170 * Return TRUE if augroup "name" exists.
8171 */
8172 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008173au_has_group(char_u *name)
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008174{
8175 return au_find_group(name) != AUGROUP_ERROR;
8176}
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008177
Bram Moolenaar071d4272004-06-13 20:20:40 +00008178/*
8179 * ":augroup {name}".
8180 */
8181 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008182do_augroup(char_u *arg, int del_group)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008183{
8184 int i;
8185
8186 if (del_group)
8187 {
8188 if (*arg == NUL)
8189 EMSG(_(e_argreq));
8190 else
8191 au_del_group(arg);
8192 }
8193 else if (STRICMP(arg, "end") == 0) /* ":aug end": back to group 0 */
8194 current_augroup = AUGROUP_DEFAULT;
8195 else if (*arg) /* ":aug xxx": switch to group xxx */
8196 {
8197 i = au_new_group(arg);
8198 if (i != AUGROUP_ERROR)
8199 current_augroup = i;
8200 }
8201 else /* ":aug": list the group names */
8202 {
8203 msg_start();
8204 for (i = 0; i < augroups.ga_len; ++i)
8205 {
8206 if (AUGROUP_NAME(i) != NULL)
8207 {
8208 msg_puts(AUGROUP_NAME(i));
8209 msg_puts((char_u *)" ");
8210 }
8211 }
8212 msg_clr_eos();
8213 msg_end();
8214 }
8215}
8216
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008217#if defined(EXITFREE) || defined(PROTO)
8218 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008219free_all_autocmds(void)
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008220{
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008221 int i;
8222 char_u *s;
8223
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008224 for (current_augroup = -1; current_augroup < augroups.ga_len;
8225 ++current_augroup)
8226 do_autocmd((char_u *)"", TRUE);
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008227
8228 for (i = 0; i < augroups.ga_len; ++i)
8229 {
8230 s = ((char_u **)(augroups.ga_data))[i];
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008231 if (s != get_deleted_augroup())
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008232 vim_free(s);
8233 }
8234 ga_clear(&augroups);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008235}
8236#endif
8237
Bram Moolenaar071d4272004-06-13 20:20:40 +00008238/*
8239 * Return the event number for event name "start".
8240 * Return NUM_EVENTS if the event name was not found.
8241 * Return a pointer to the next event name in "end".
8242 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008243 static event_T
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008244event_name2nr(char_u *start, char_u **end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008245{
8246 char_u *p;
8247 int i;
8248 int len;
8249
Bram Moolenaare99e8442016-07-26 20:43:40 +02008250 /* the event name ends with end of line, '|', a blank or a comma */
Bram Moolenaar1c465442017-03-12 20:10:05 +01008251 for (p = start; *p && !VIM_ISWHITE(*p) && *p != ',' && *p != '|'; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008252 ;
8253 for (i = 0; event_names[i].name != NULL; ++i)
8254 {
8255 len = (int)STRLEN(event_names[i].name);
8256 if (len == p - start && STRNICMP(event_names[i].name, start, len) == 0)
8257 break;
8258 }
8259 if (*p == ',')
8260 ++p;
8261 *end = p;
8262 if (event_names[i].name == NULL)
8263 return NUM_EVENTS;
8264 return event_names[i].event;
8265}
8266
8267/*
8268 * Return the name for event "event".
8269 */
8270 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008271event_nr2name(event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008272{
8273 int i;
8274
8275 for (i = 0; event_names[i].name != NULL; ++i)
8276 if (event_names[i].event == event)
8277 return (char_u *)event_names[i].name;
8278 return (char_u *)"Unknown";
8279}
8280
8281/*
8282 * Scan over the events. "*" stands for all events.
8283 */
8284 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008285find_end_event(
8286 char_u *arg,
8287 int have_group) /* TRUE when group name was found */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008288{
8289 char_u *pat;
8290 char_u *p;
8291
8292 if (*arg == '*')
8293 {
Bram Moolenaar1c465442017-03-12 20:10:05 +01008294 if (arg[1] && !VIM_ISWHITE(arg[1]))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008295 {
8296 EMSG2(_("E215: Illegal character after *: %s"), arg);
8297 return NULL;
8298 }
8299 pat = arg + 1;
8300 }
8301 else
8302 {
Bram Moolenaar1c465442017-03-12 20:10:05 +01008303 for (pat = arg; *pat && *pat != '|' && !VIM_ISWHITE(*pat); pat = p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008304 {
8305 if ((int)event_name2nr(pat, &p) >= (int)NUM_EVENTS)
8306 {
8307 if (have_group)
8308 EMSG2(_("E216: No such event: %s"), pat);
8309 else
8310 EMSG2(_("E216: No such group or event: %s"), pat);
8311 return NULL;
8312 }
8313 }
8314 }
8315 return pat;
8316}
8317
8318/*
8319 * Return TRUE if "event" is included in 'eventignore'.
8320 */
8321 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008322event_ignored(event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008323{
8324 char_u *p = p_ei;
8325
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008326 while (*p != NUL)
8327 {
8328 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8329 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008330 if (event_name2nr(p, &p) == event)
8331 return TRUE;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008332 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008333
8334 return FALSE;
8335}
8336
8337/*
8338 * Return OK when the contents of p_ei is valid, FAIL otherwise.
8339 */
8340 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008341check_ei(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008342{
8343 char_u *p = p_ei;
8344
Bram Moolenaar071d4272004-06-13 20:20:40 +00008345 while (*p)
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008346 {
8347 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8348 {
8349 p += 3;
8350 if (*p == ',')
8351 ++p;
8352 }
8353 else if (event_name2nr(p, &p) == NUM_EVENTS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008354 return FAIL;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008355 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008356
8357 return OK;
8358}
8359
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008360# if defined(FEAT_SYN_HL) || defined(PROTO)
8361
8362/*
8363 * Add "what" to 'eventignore' to skip loading syntax highlighting for every
8364 * buffer loaded into the window. "what" must start with a comma.
8365 * Returns the old value of 'eventignore' in allocated memory.
8366 */
8367 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008368au_event_disable(char *what)
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008369{
8370 char_u *new_ei;
8371 char_u *save_ei;
8372
8373 save_ei = vim_strsave(p_ei);
8374 if (save_ei != NULL)
8375 {
Bram Moolenaara5792f52005-11-23 21:25:05 +00008376 new_ei = vim_strnsave(p_ei, (int)(STRLEN(p_ei) + STRLEN(what)));
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008377 if (new_ei != NULL)
8378 {
Bram Moolenaar8cac9fd2010-03-02 12:48:05 +01008379 if (*what == ',' && *p_ei == NUL)
8380 STRCPY(new_ei, what + 1);
8381 else
8382 STRCAT(new_ei, what);
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008383 set_string_option_direct((char_u *)"ei", -1, new_ei,
8384 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008385 vim_free(new_ei);
8386 }
8387 }
8388 return save_ei;
8389}
8390
8391 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008392au_event_restore(char_u *old_ei)
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008393{
8394 if (old_ei != NULL)
8395 {
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008396 set_string_option_direct((char_u *)"ei", -1, old_ei,
8397 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008398 vim_free(old_ei);
8399 }
8400}
8401# endif /* FEAT_SYN_HL */
8402
Bram Moolenaar071d4272004-06-13 20:20:40 +00008403/*
8404 * do_autocmd() -- implements the :autocmd command. Can be used in the
8405 * following ways:
8406 *
8407 * :autocmd <event> <pat> <cmd> Add <cmd> to the list of commands that
8408 * will be automatically executed for <event>
8409 * when editing a file matching <pat>, in
8410 * the current group.
8411 * :autocmd <event> <pat> Show the auto-commands associated with
8412 * <event> and <pat>.
8413 * :autocmd <event> Show the auto-commands associated with
8414 * <event>.
8415 * :autocmd Show all auto-commands.
8416 * :autocmd! <event> <pat> <cmd> Remove all auto-commands associated with
8417 * <event> and <pat>, and add the command
8418 * <cmd>, for the current group.
8419 * :autocmd! <event> <pat> Remove all auto-commands associated with
8420 * <event> and <pat> for the current group.
8421 * :autocmd! <event> Remove all auto-commands associated with
8422 * <event> for the current group.
8423 * :autocmd! Remove ALL auto-commands for the current
8424 * group.
8425 *
8426 * Multiple events and patterns may be given separated by commas. Here are
8427 * some examples:
8428 * :autocmd bufread,bufenter *.c,*.h set tw=0 smartindent noic
8429 * :autocmd bufleave * set tw=79 nosmartindent ic infercase
8430 *
8431 * :autocmd * *.c show all autocommands for *.c files.
Bram Moolenaard35f9712005-12-18 22:02:33 +00008432 *
8433 * Mostly a {group} argument can optionally appear before <event>.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008434 */
8435 void
Bram Moolenaare99e8442016-07-26 20:43:40 +02008436do_autocmd(char_u *arg_in, int forceit)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008437{
Bram Moolenaare99e8442016-07-26 20:43:40 +02008438 char_u *arg = arg_in;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008439 char_u *pat;
8440 char_u *envpat = NULL;
8441 char_u *cmd;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008442 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008443 int need_free = FALSE;
8444 int nested = FALSE;
8445 int group;
8446
Bram Moolenaare99e8442016-07-26 20:43:40 +02008447 if (*arg == '|')
8448 {
8449 arg = (char_u *)"";
8450 group = AUGROUP_ALL; /* no argument, use all groups */
8451 }
8452 else
8453 {
8454 /*
8455 * Check for a legal group name. If not, use AUGROUP_ALL.
8456 */
8457 group = au_get_grouparg(&arg);
8458 if (arg == NULL) /* out of memory */
8459 return;
8460 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008461
8462 /*
8463 * Scan over the events.
8464 * If we find an illegal name, return here, don't do anything.
8465 */
8466 pat = find_end_event(arg, group != AUGROUP_ALL);
8467 if (pat == NULL)
8468 return;
8469
Bram Moolenaar071d4272004-06-13 20:20:40 +00008470 pat = skipwhite(pat);
Bram Moolenaare99e8442016-07-26 20:43:40 +02008471 if (*pat == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008472 {
Bram Moolenaare99e8442016-07-26 20:43:40 +02008473 pat = (char_u *)"";
8474 cmd = (char_u *)"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00008475 }
Bram Moolenaare99e8442016-07-26 20:43:40 +02008476 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00008477 {
Bram Moolenaare99e8442016-07-26 20:43:40 +02008478 /*
8479 * Scan over the pattern. Put a NUL at the end.
8480 */
8481 cmd = pat;
Bram Moolenaar1c465442017-03-12 20:10:05 +01008482 while (*cmd && (!VIM_ISWHITE(*cmd) || cmd[-1] == '\\'))
Bram Moolenaare99e8442016-07-26 20:43:40 +02008483 cmd++;
8484 if (*cmd)
8485 *cmd++ = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008486
Bram Moolenaare99e8442016-07-26 20:43:40 +02008487 /* Expand environment variables in the pattern. Set 'shellslash', we want
8488 * forward slashes here. */
8489 if (vim_strchr(pat, '$') != NULL || vim_strchr(pat, '~') != NULL)
8490 {
8491#ifdef BACKSLASH_IN_FILENAME
8492 int p_ssl_save = p_ssl;
8493
8494 p_ssl = TRUE;
8495#endif
8496 envpat = expand_env_save(pat);
8497#ifdef BACKSLASH_IN_FILENAME
8498 p_ssl = p_ssl_save;
8499#endif
8500 if (envpat != NULL)
8501 pat = envpat;
8502 }
8503
8504 /*
8505 * Check for "nested" flag.
8506 */
8507 cmd = skipwhite(cmd);
Bram Moolenaar1c465442017-03-12 20:10:05 +01008508 if (*cmd != NUL && STRNCMP(cmd, "nested", 6) == 0 && VIM_ISWHITE(cmd[6]))
Bram Moolenaare99e8442016-07-26 20:43:40 +02008509 {
8510 nested = TRUE;
8511 cmd = skipwhite(cmd + 6);
8512 }
8513
8514 /*
8515 * Find the start of the commands.
8516 * Expand <sfile> in it.
8517 */
8518 if (*cmd != NUL)
8519 {
8520 cmd = expand_sfile(cmd);
8521 if (cmd == NULL) /* some error */
8522 return;
8523 need_free = TRUE;
8524 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008525 }
8526
8527 /*
8528 * Print header when showing autocommands.
8529 */
8530 if (!forceit && *cmd == NUL)
8531 {
8532 /* Highlight title */
8533 MSG_PUTS_TITLE(_("\n--- Auto-Commands ---"));
8534 }
8535
8536 /*
8537 * Loop over the events.
8538 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008539 last_event = (event_T)-1; /* for listing the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008540 last_group = AUGROUP_ERROR; /* for listing the group name */
Bram Moolenaare99e8442016-07-26 20:43:40 +02008541 if (*arg == '*' || *arg == NUL || *arg == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008542 {
Bram Moolenaar754b5602006-02-09 23:53:20 +00008543 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8544 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008545 if (do_autocmd_event(event, pat,
8546 nested, cmd, forceit, group) == FAIL)
8547 break;
8548 }
8549 else
8550 {
Bram Moolenaar1c465442017-03-12 20:10:05 +01008551 while (*arg && *arg != '|' && !VIM_ISWHITE(*arg))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008552 if (do_autocmd_event(event_name2nr(arg, &arg), pat,
8553 nested, cmd, forceit, group) == FAIL)
8554 break;
8555 }
8556
8557 if (need_free)
8558 vim_free(cmd);
8559 vim_free(envpat);
8560}
8561
8562/*
8563 * Find the group ID in a ":autocmd" or ":doautocmd" argument.
8564 * The "argp" argument is advanced to the following argument.
8565 *
8566 * Returns the group ID, AUGROUP_ERROR for error (out of memory).
8567 */
8568 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008569au_get_grouparg(char_u **argp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008570{
8571 char_u *group_name;
8572 char_u *p;
8573 char_u *arg = *argp;
8574 int group = AUGROUP_ALL;
8575
Bram Moolenaar1c465442017-03-12 20:10:05 +01008576 for (p = arg; *p && !VIM_ISWHITE(*p) && *p != '|'; ++p)
Bram Moolenaare99e8442016-07-26 20:43:40 +02008577 ;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008578 if (p > arg)
8579 {
8580 group_name = vim_strnsave(arg, (int)(p - arg));
8581 if (group_name == NULL) /* out of memory */
8582 return AUGROUP_ERROR;
8583 group = au_find_group(group_name);
8584 if (group == AUGROUP_ERROR)
8585 group = AUGROUP_ALL; /* no match, use all groups */
8586 else
8587 *argp = skipwhite(p); /* match, skip over group name */
8588 vim_free(group_name);
8589 }
8590 return group;
8591}
8592
8593/*
8594 * do_autocmd() for one event.
8595 * If *pat == NUL do for all patterns.
8596 * If *cmd == NUL show entries.
8597 * If forceit == TRUE delete entries.
8598 * If group is not AUGROUP_ALL, only use this group.
8599 */
8600 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008601do_autocmd_event(
8602 event_T event,
8603 char_u *pat,
8604 int nested,
8605 char_u *cmd,
8606 int forceit,
8607 int group)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008608{
8609 AutoPat *ap;
8610 AutoPat **prev_ap;
8611 AutoCmd *ac;
8612 AutoCmd **prev_ac;
8613 int brace_level;
8614 char_u *endpat;
8615 int findgroup;
8616 int allgroups;
8617 int patlen;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00008618 int is_buflocal;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008619 int buflocal_nr;
8620 char_u buflocal_pat[25]; /* for "<buffer=X>" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008621
8622 if (group == AUGROUP_ALL)
8623 findgroup = current_augroup;
8624 else
8625 findgroup = group;
8626 allgroups = (group == AUGROUP_ALL && !forceit && *cmd == NUL);
8627
8628 /*
8629 * Show or delete all patterns for an event.
8630 */
8631 if (*pat == NUL)
8632 {
8633 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8634 {
8635 if (forceit) /* delete the AutoPat, if it's in the current group */
8636 {
8637 if (ap->group == findgroup)
8638 au_remove_pat(ap);
8639 }
8640 else if (group == AUGROUP_ALL || ap->group == group)
8641 show_autocmd(ap, event);
8642 }
8643 }
8644
8645 /*
8646 * Loop through all the specified patterns.
8647 */
8648 for ( ; *pat; pat = (*endpat == ',' ? endpat + 1 : endpat))
8649 {
8650 /*
8651 * Find end of the pattern.
8652 * Watch out for a comma in braces, like "*.\{obj,o\}".
8653 */
8654 brace_level = 0;
8655 for (endpat = pat; *endpat && (*endpat != ',' || brace_level
Bram Moolenaar6b9be1b2015-07-28 13:33:45 +02008656 || (endpat > pat && endpat[-1] == '\\')); ++endpat)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008657 {
8658 if (*endpat == '{')
8659 brace_level++;
8660 else if (*endpat == '}')
8661 brace_level--;
8662 }
8663 if (pat == endpat) /* ignore single comma */
8664 continue;
8665 patlen = (int)(endpat - pat);
8666
8667 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008668 * detect special <buflocal[=X]> buffer-local patterns
8669 */
8670 is_buflocal = FALSE;
8671 buflocal_nr = 0;
8672
Bram Moolenaar1e997822015-02-17 16:04:57 +01008673 if (patlen >= 8 && STRNCMP(pat, "<buffer", 7) == 0
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008674 && pat[patlen - 1] == '>')
8675 {
Bram Moolenaar1e997822015-02-17 16:04:57 +01008676 /* "<buffer...>": Error will be printed only for addition.
8677 * printing and removing will proceed silently. */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008678 is_buflocal = TRUE;
8679 if (patlen == 8)
Bram Moolenaar1e997822015-02-17 16:04:57 +01008680 /* "<buffer>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008681 buflocal_nr = curbuf->b_fnum;
8682 else if (patlen > 9 && pat[7] == '=')
8683 {
Bram Moolenaar1e997822015-02-17 16:04:57 +01008684 if (patlen == 13 && STRNICMP(pat, "<buffer=abuf>", 13) == 0)
8685 /* "<buffer=abuf>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008686 buflocal_nr = autocmd_bufnr;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008687 else if (skipdigits(pat + 8) == pat + patlen - 1)
Bram Moolenaar1e997822015-02-17 16:04:57 +01008688 /* "<buffer=123>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008689 buflocal_nr = atoi((char *)pat + 8);
8690 }
8691 }
8692
8693 if (is_buflocal)
8694 {
8695 /* normalize pat into standard "<buffer>#N" form */
8696 sprintf((char *)buflocal_pat, "<buffer=%d>", buflocal_nr);
8697 pat = buflocal_pat; /* can modify pat and patlen */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008698 patlen = (int)STRLEN(buflocal_pat); /* but not endpat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008699 }
8700
8701 /*
Bram Moolenaar462455e2017-11-10 21:53:11 +01008702 * Find AutoPat entries with this pattern. When adding a command it
8703 * always goes at or after the last one, so start at the end.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008704 */
Bram Moolenaar462455e2017-11-10 21:53:11 +01008705 if (!forceit && *cmd != NUL && last_autopat[(int)event] != NULL)
8706 prev_ap = &last_autopat[(int)event];
8707 else
8708 prev_ap = &first_autopat[(int)event];
Bram Moolenaar071d4272004-06-13 20:20:40 +00008709 while ((ap = *prev_ap) != NULL)
8710 {
8711 if (ap->pat != NULL)
8712 {
8713 /* Accept a pattern when:
8714 * - a group was specified and it's that group, or a group was
8715 * not specified and it's the current group, or a group was
8716 * not specified and we are listing
8717 * - the length of the pattern matches
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008718 * - the pattern matches.
8719 * For <buffer[=X]>, this condition works because we normalize
8720 * all buffer-local patterns.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008721 */
8722 if ((allgroups || ap->group == findgroup)
8723 && ap->patlen == patlen
8724 && STRNCMP(pat, ap->pat, patlen) == 0)
8725 {
8726 /*
8727 * Remove existing autocommands.
8728 * If adding any new autocmd's for this AutoPat, don't
8729 * delete the pattern from the autopat list, append to
8730 * this list.
8731 */
8732 if (forceit)
8733 {
8734 if (*cmd != NUL && ap->next == NULL)
8735 {
8736 au_remove_cmds(ap);
8737 break;
8738 }
8739 au_remove_pat(ap);
8740 }
8741
8742 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008743 * Show autocmd's for this autopat, or buflocals <buffer=X>
Bram Moolenaar071d4272004-06-13 20:20:40 +00008744 */
8745 else if (*cmd == NUL)
8746 show_autocmd(ap, event);
8747
8748 /*
8749 * Add autocmd to this autopat, if it's the last one.
8750 */
8751 else if (ap->next == NULL)
8752 break;
8753 }
8754 }
8755 prev_ap = &ap->next;
8756 }
8757
8758 /*
8759 * Add a new command.
8760 */
8761 if (*cmd != NUL)
8762 {
8763 /*
8764 * If the pattern we want to add a command to does appear at the
8765 * end of the list (or not is not in the list at all), add the
8766 * pattern at the end of the list.
8767 */
8768 if (ap == NULL)
8769 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008770 /* refuse to add buffer-local ap if buffer number is invalid */
8771 if (is_buflocal && (buflocal_nr == 0
8772 || buflist_findnr(buflocal_nr) == NULL))
8773 {
8774 EMSGN(_("E680: <buffer=%d>: invalid buffer number "),
8775 buflocal_nr);
8776 return FAIL;
8777 }
8778
Bram Moolenaar071d4272004-06-13 20:20:40 +00008779 ap = (AutoPat *)alloc((unsigned)sizeof(AutoPat));
8780 if (ap == NULL)
8781 return FAIL;
8782 ap->pat = vim_strnsave(pat, patlen);
8783 ap->patlen = patlen;
8784 if (ap->pat == NULL)
8785 {
8786 vim_free(ap);
8787 return FAIL;
8788 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008789
8790 if (is_buflocal)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008791 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008792 ap->buflocal_nr = buflocal_nr;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008793 ap->reg_prog = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008794 }
8795 else
8796 {
Bram Moolenaar748bf032005-02-02 23:04:36 +00008797 char_u *reg_pat;
8798
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008799 ap->buflocal_nr = 0;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008800 reg_pat = file_pat_to_reg_pat(pat, endpat,
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008801 &ap->allow_dirs, TRUE);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008802 if (reg_pat != NULL)
8803 ap->reg_prog = vim_regcomp(reg_pat, RE_MAGIC);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008804 vim_free(reg_pat);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008805 if (reg_pat == NULL || ap->reg_prog == NULL)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008806 {
8807 vim_free(ap->pat);
8808 vim_free(ap);
8809 return FAIL;
8810 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008811 }
8812 ap->cmds = NULL;
8813 *prev_ap = ap;
Bram Moolenaar462455e2017-11-10 21:53:11 +01008814 last_autopat[(int)event] = ap;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008815 ap->next = NULL;
8816 if (group == AUGROUP_ALL)
8817 ap->group = current_augroup;
8818 else
8819 ap->group = group;
8820 }
8821
8822 /*
8823 * Add the autocmd at the end of the AutoCmd list.
8824 */
8825 prev_ac = &(ap->cmds);
8826 while ((ac = *prev_ac) != NULL)
8827 prev_ac = &ac->next;
8828 ac = (AutoCmd *)alloc((unsigned)sizeof(AutoCmd));
8829 if (ac == NULL)
8830 return FAIL;
8831 ac->cmd = vim_strsave(cmd);
8832#ifdef FEAT_EVAL
8833 ac->scriptID = current_SID;
8834#endif
8835 if (ac->cmd == NULL)
8836 {
8837 vim_free(ac);
8838 return FAIL;
8839 }
8840 ac->next = NULL;
8841 *prev_ac = ac;
8842 ac->nested = nested;
8843 }
8844 }
8845
8846 au_cleanup(); /* may really delete removed patterns/commands now */
8847 return OK;
8848}
8849
8850/*
8851 * Implementation of ":doautocmd [group] event [fname]".
8852 * Return OK for success, FAIL for failure;
8853 */
8854 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008855do_doautocmd(
8856 char_u *arg,
Bram Moolenaar1610d052016-06-09 22:53:01 +02008857 int do_msg, /* give message for no matching autocmds? */
8858 int *did_something)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008859{
8860 char_u *fname;
8861 int nothing_done = TRUE;
8862 int group;
8863
Bram Moolenaar1610d052016-06-09 22:53:01 +02008864 if (did_something != NULL)
Bram Moolenaar76ae22f2016-06-13 20:00:29 +02008865 *did_something = FALSE;
Bram Moolenaar1610d052016-06-09 22:53:01 +02008866
Bram Moolenaar071d4272004-06-13 20:20:40 +00008867 /*
8868 * Check for a legal group name. If not, use AUGROUP_ALL.
8869 */
8870 group = au_get_grouparg(&arg);
8871 if (arg == NULL) /* out of memory */
8872 return FAIL;
8873
8874 if (*arg == '*')
8875 {
8876 EMSG(_("E217: Can't execute autocommands for ALL events"));
8877 return FAIL;
8878 }
8879
8880 /*
8881 * Scan over the events.
8882 * If we find an illegal name, return here, don't do anything.
8883 */
8884 fname = find_end_event(arg, group != AUGROUP_ALL);
8885 if (fname == NULL)
8886 return FAIL;
8887
8888 fname = skipwhite(fname);
8889
8890 /*
8891 * Loop over the events.
8892 */
Bram Moolenaarfaf29d72017-07-09 11:07:16 +02008893 while (*arg && !ends_excmd(*arg) && !VIM_ISWHITE(*arg))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008894 if (apply_autocmds_group(event_name2nr(arg, &arg),
8895 fname, NULL, TRUE, group, curbuf, NULL))
8896 nothing_done = FALSE;
8897
8898 if (nothing_done && do_msg)
8899 MSG(_("No matching autocommands"));
Bram Moolenaar1610d052016-06-09 22:53:01 +02008900 if (did_something != NULL)
8901 *did_something = !nothing_done;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008902
8903#ifdef FEAT_EVAL
8904 return aborting() ? FAIL : OK;
8905#else
8906 return OK;
8907#endif
8908}
8909
8910/*
8911 * ":doautoall": execute autocommands for each loaded buffer.
8912 */
8913 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008914ex_doautoall(exarg_T *eap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008915{
8916 int retval;
8917 aco_save_T aco;
8918 buf_T *buf;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008919 bufref_T bufref;
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008920 char_u *arg = eap->arg;
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008921 int call_do_modelines = check_nomodeline(&arg);
Bram Moolenaar1610d052016-06-09 22:53:01 +02008922 int did_aucmd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008923
8924 /*
8925 * This is a bit tricky: For some commands curwin->w_buffer needs to be
8926 * equal to curbuf, but for some buffers there may not be a window.
8927 * So we change the buffer for the current window for a moment. This
8928 * gives problems when the autocommands make changes to the list of
8929 * buffers or windows...
8930 */
Bram Moolenaar29323592016-07-24 22:04:11 +02008931 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008932 {
Bram Moolenaar3a847972008-07-08 09:36:58 +00008933 if (buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008934 {
8935 /* find a window for this buffer and save some values */
8936 aucmd_prepbuf(&aco, buf);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008937 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008938
8939 /* execute the autocommands for this buffer */
Bram Moolenaar1610d052016-06-09 22:53:01 +02008940 retval = do_doautocmd(arg, FALSE, &did_aucmd);
Bram Moolenaareeefcc72007-05-01 21:21:21 +00008941
Bram Moolenaar1610d052016-06-09 22:53:01 +02008942 if (call_do_modelines && did_aucmd)
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008943 {
8944 /* Execute the modeline settings, but don't set window-local
8945 * options if we are using the current window for another
8946 * buffer. */
8947 do_modelines(curwin == aucmd_win ? OPT_NOWIN : 0);
8948 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008949
8950 /* restore the current window */
8951 aucmd_restbuf(&aco);
8952
8953 /* stop if there is some error or buffer was deleted */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008954 if (retval == FAIL || !bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008955 break;
8956 }
8957 }
8958
8959 check_cursor(); /* just in case lines got deleted */
8960}
8961
8962/*
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008963 * Check *argp for <nomodeline>. When it is present return FALSE, otherwise
8964 * return TRUE and advance *argp to after it.
8965 * Thus return TRUE when do_modelines() should be called.
8966 */
8967 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008968check_nomodeline(char_u **argp)
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008969{
8970 if (STRNCMP(*argp, "<nomodeline>", 12) == 0)
8971 {
8972 *argp = skipwhite(*argp + 12);
8973 return FALSE;
8974 }
8975 return TRUE;
8976}
8977
8978/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008979 * Prepare for executing autocommands for (hidden) buffer "buf".
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008980 * Search for a visible window containing the current buffer. If there isn't
8981 * one then use "aucmd_win".
Bram Moolenaar071d4272004-06-13 20:20:40 +00008982 * Set "curbuf" and "curwin" to match "buf".
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00008983 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008984 */
8985 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008986aucmd_prepbuf(
8987 aco_save_T *aco, /* structure to save values in */
8988 buf_T *buf) /* new curbuf */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008989{
8990 win_T *win;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008991 int save_ea;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008992#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008993 int save_acd;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008994#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008995
8996 /* Find a window that is for the new buffer */
8997 if (buf == curbuf) /* be quick when buf is curbuf */
8998 win = curwin;
8999 else
Bram Moolenaar29323592016-07-24 22:04:11 +02009000 FOR_ALL_WINDOWS(win)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009001 if (win->w_buffer == buf)
9002 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009003
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009004 /* Allocate "aucmd_win" when needed. If this fails (out of memory) fall
9005 * back to using the current window. */
9006 if (win == NULL && aucmd_win == NULL)
9007 {
9008 win_alloc_aucmd_win();
9009 if (aucmd_win == NULL)
9010 win = curwin;
9011 }
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009012 if (win == NULL && aucmd_win_used)
9013 /* Strange recursive autocommand, fall back to using the current
9014 * window. Expect a few side effects... */
9015 win = curwin;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009016
9017 aco->save_curwin = curwin;
9018 aco->save_curbuf = curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009019 if (win != NULL)
9020 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009021 /* There is a window for "buf" in the current tab page, make it the
9022 * curwin. This is preferred, it has the least side effects (esp. if
9023 * "buf" is curbuf). */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009024 aco->use_aucmd_win = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009025 curwin = win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009026 }
9027 else
9028 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009029 /* There is no window for "buf", use "aucmd_win". To minimize the side
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02009030 * effects, insert it in the current tab page.
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009031 * Anything related to a window (e.g., setting folds) may have
9032 * unexpected results. */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009033 aco->use_aucmd_win = TRUE;
9034 aucmd_win_used = TRUE;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00009035 aucmd_win->w_buffer = buf;
Bram Moolenaarcdddaa42010-06-07 23:07:44 +02009036 aucmd_win->w_s = &buf->b_s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009037 ++buf->b_nwindows;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00009038 win_init_empty(aucmd_win); /* set cursor and topline to safe values */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009039
9040 /* Make sure w_localdir and globaldir are NULL to avoid a chdir() in
9041 * win_enter_ext(). */
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009042 vim_free(aucmd_win->w_localdir);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009043 aucmd_win->w_localdir = NULL;
9044 aco->globaldir = globaldir;
9045 globaldir = NULL;
9046
Bram Moolenaar071d4272004-06-13 20:20:40 +00009047
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00009048 /* Split the current window, put the aucmd_win in the upper half.
9049 * We don't want the BufEnter or WinEnter autocommands. */
9050 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009051 make_snapshot(SNAP_AUCMD_IDX);
9052 save_ea = p_ea;
9053 p_ea = FALSE;
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009054
Bram Moolenaar4033c552017-09-16 20:54:51 +02009055#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009056 /* Prevent chdir() call in win_enter_ext(), through do_autochdir(). */
9057 save_acd = p_acd;
9058 p_acd = FALSE;
Bram Moolenaar4033c552017-09-16 20:54:51 +02009059#endif
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009060
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009061 (void)win_split_ins(0, WSP_TOP, aucmd_win, 0);
9062 (void)win_comp_pos(); /* recompute window positions */
9063 p_ea = save_ea;
Bram Moolenaar4033c552017-09-16 20:54:51 +02009064#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009065 p_acd = save_acd;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009066#endif
Bram Moolenaar4033c552017-09-16 20:54:51 +02009067 unblock_autocmds();
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00009068 curwin = aucmd_win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009069 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009070 curbuf = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009071 aco->new_curwin = curwin;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009072 set_bufref(&aco->new_curbuf, curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009073}
9074
9075/*
9076 * Cleanup after executing autocommands for a (hidden) buffer.
9077 * Restore the window as it was (if possible).
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009078 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009079 */
9080 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009081aucmd_restbuf(
9082 aco_save_T *aco) /* structure holding saved values */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009083{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009084 int dummy;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009085
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009086 if (aco->use_aucmd_win)
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009087 {
9088 --curbuf->b_nwindows;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009089 /* Find "aucmd_win", it can't be closed, but it may be in another tab
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00009090 * page. Do not trigger autocommands here. */
9091 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009092 if (curwin != aucmd_win)
9093 {
9094 tabpage_T *tp;
9095 win_T *wp;
9096
9097 FOR_ALL_TAB_WINDOWS(tp, wp)
9098 {
9099 if (wp == aucmd_win)
9100 {
9101 if (tp != curtab)
Bram Moolenaar49e649f2013-05-06 04:50:35 +02009102 goto_tabpage_tp(tp, TRUE, TRUE);
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009103 win_goto(aucmd_win);
Bram Moolenaar28f29082012-02-11 23:45:37 +01009104 goto win_found;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009105 }
9106 }
9107 }
Bram Moolenaar28f29082012-02-11 23:45:37 +01009108win_found:
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009109
9110 /* Remove the window and frame from the tree of frames. */
9111 (void)winframe_remove(curwin, &dummy, NULL);
9112 win_remove(curwin, NULL);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009113 aucmd_win_used = FALSE;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009114 last_status(FALSE); /* may need to remove last status line */
Bram Moolenaar8c752bd2017-03-19 17:09:56 +01009115
9116 if (!valid_tabpage_win(curtab))
9117 /* no valid window in current tabpage */
9118 close_tabpage(curtab);
9119
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009120 restore_snapshot(SNAP_AUCMD_IDX, FALSE);
9121 (void)win_comp_pos(); /* recompute window positions */
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00009122 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009123
9124 if (win_valid(aco->save_curwin))
9125 curwin = aco->save_curwin;
9126 else
9127 /* Hmm, original window disappeared. Just use the first one. */
9128 curwin = firstwin;
Bram Moolenaar4033c552017-09-16 20:54:51 +02009129#ifdef FEAT_EVAL
Bram Moolenaar429fa852013-04-15 12:27:36 +02009130 vars_clear(&aucmd_win->w_vars->dv_hashtab); /* free all w: variables */
9131 hash_init(&aucmd_win->w_vars->dv_hashtab); /* re-use the hashtab */
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009132#endif
9133 curbuf = curwin->w_buffer;
9134
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009135 vim_free(globaldir);
9136 globaldir = aco->globaldir;
9137
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009138 /* the buffer contents may have changed */
9139 check_cursor();
9140 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
9141 {
9142 curwin->w_topline = curbuf->b_ml.ml_line_count;
9143#ifdef FEAT_DIFF
9144 curwin->w_topfill = 0;
9145#endif
9146 }
9147#if defined(FEAT_GUI)
9148 /* Hide the scrollbars from the aucmd_win and update. */
9149 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_LEFT], FALSE);
9150 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_RIGHT], FALSE);
9151 gui_may_update_scrollbars();
9152#endif
9153 }
9154 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00009155 {
9156 /* restore curwin */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009157 if (win_valid(aco->save_curwin))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009158 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009159 /* Restore the buffer which was previously edited by curwin, if
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009160 * it was changed, we are still the same window and the buffer is
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009161 * valid. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009162 if (curwin == aco->new_curwin
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009163 && curbuf != aco->new_curbuf.br_buf
9164 && bufref_valid(&aco->new_curbuf)
9165 && aco->new_curbuf.br_buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009166 {
Bram Moolenaar7da9c372012-04-30 17:04:52 +02009167# if defined(FEAT_SYN_HL) || defined(FEAT_SPELL)
9168 if (curwin->w_s == &curbuf->b_s)
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009169 curwin->w_s = &aco->new_curbuf.br_buf->b_s;
Bram Moolenaar7da9c372012-04-30 17:04:52 +02009170# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009171 --curbuf->b_nwindows;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009172 curbuf = aco->new_curbuf.br_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009173 curwin->w_buffer = curbuf;
9174 ++curbuf->b_nwindows;
9175 }
9176
9177 curwin = aco->save_curwin;
9178 curbuf = curwin->w_buffer;
Bram Moolenaar371932a2014-09-09 16:59:38 +02009179 /* In case the autocommand move the cursor to a position that that
9180 * not exist in curbuf. */
9181 check_cursor();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009182 }
9183 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009184}
9185
9186static int autocmd_nested = FALSE;
9187
9188/*
9189 * Execute autocommands for "event" and file name "fname".
9190 * Return TRUE if some commands were executed.
9191 */
9192 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009193apply_autocmds(
9194 event_T event,
9195 char_u *fname, /* NULL or empty means use actual file name */
9196 char_u *fname_io, /* fname to use for <afile> on cmdline */
9197 int force, /* when TRUE, ignore autocmd_busy */
9198 buf_T *buf) /* buffer for <abuf> */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009199{
9200 return apply_autocmds_group(event, fname, fname_io, force,
9201 AUGROUP_ALL, buf, NULL);
9202}
9203
9204/*
9205 * Like apply_autocmds(), but with extra "eap" argument. This takes care of
9206 * setting v:filearg.
9207 */
9208 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009209apply_autocmds_exarg(
9210 event_T event,
9211 char_u *fname,
9212 char_u *fname_io,
9213 int force,
9214 buf_T *buf,
9215 exarg_T *eap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009216{
9217 return apply_autocmds_group(event, fname, fname_io, force,
9218 AUGROUP_ALL, buf, eap);
9219}
9220
9221/*
9222 * Like apply_autocmds(), but handles the caller's retval. If the script
9223 * processing is being aborted or if retval is FAIL when inside a try
9224 * conditional, no autocommands are executed. If otherwise the autocommands
9225 * cause the script to be aborted, retval is set to FAIL.
9226 */
9227 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009228apply_autocmds_retval(
9229 event_T event,
9230 char_u *fname, /* NULL or empty means use actual file name */
9231 char_u *fname_io, /* fname to use for <afile> on cmdline */
9232 int force, /* when TRUE, ignore autocmd_busy */
9233 buf_T *buf, /* buffer for <abuf> */
9234 int *retval) /* pointer to caller's retval */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009235{
9236 int did_cmd;
9237
Bram Moolenaar1e015462005-09-25 22:16:38 +00009238#ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00009239 if (should_abort(*retval))
9240 return FALSE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00009241#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009242
9243 did_cmd = apply_autocmds_group(event, fname, fname_io, force,
9244 AUGROUP_ALL, buf, NULL);
Bram Moolenaar1e015462005-09-25 22:16:38 +00009245 if (did_cmd
9246#ifdef FEAT_EVAL
9247 && aborting()
9248#endif
9249 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00009250 *retval = FAIL;
9251 return did_cmd;
9252}
9253
Bram Moolenaard35f9712005-12-18 22:02:33 +00009254/*
9255 * Return TRUE when there is a CursorHold autocommand defined.
9256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009257 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009258has_cursorhold(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009259{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009260 return (first_autopat[(int)(get_real_state() == NORMAL_BUSY
9261 ? EVENT_CURSORHOLD : EVENT_CURSORHOLDI)] != NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009262}
Bram Moolenaard35f9712005-12-18 22:02:33 +00009263
9264/*
9265 * Return TRUE if the CursorHold event can be triggered.
9266 */
9267 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009268trigger_cursorhold(void)
Bram Moolenaard35f9712005-12-18 22:02:33 +00009269{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009270 int state;
9271
Bram Moolenaar05334432011-07-20 18:29:39 +02009272 if (!did_cursorhold
9273 && has_cursorhold()
9274 && !Recording
9275 && typebuf.tb_len == 0
Bram Moolenaard29a9ee2006-09-14 09:07:34 +00009276#ifdef FEAT_INS_EXPAND
9277 && !ins_compl_active()
9278#endif
9279 )
Bram Moolenaar754b5602006-02-09 23:53:20 +00009280 {
9281 state = get_real_state();
9282 if (state == NORMAL_BUSY || (state & INSERT) != 0)
9283 return TRUE;
9284 }
9285 return FALSE;
Bram Moolenaard35f9712005-12-18 22:02:33 +00009286}
Bram Moolenaar754b5602006-02-09 23:53:20 +00009287
9288/*
9289 * Return TRUE when there is a CursorMoved autocommand defined.
9290 */
9291 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009292has_cursormoved(void)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009293{
9294 return (first_autopat[(int)EVENT_CURSORMOVED] != NULL);
9295}
9296
9297/*
9298 * Return TRUE when there is a CursorMovedI autocommand defined.
9299 */
9300 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009301has_cursormovedI(void)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009302{
9303 return (first_autopat[(int)EVENT_CURSORMOVEDI] != NULL);
9304}
Bram Moolenaar071d4272004-06-13 20:20:40 +00009305
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009306/*
Bram Moolenaar186628f2013-03-19 13:33:23 +01009307 * Return TRUE when there is a TextChanged autocommand defined.
9308 */
9309 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009310has_textchanged(void)
Bram Moolenaar186628f2013-03-19 13:33:23 +01009311{
9312 return (first_autopat[(int)EVENT_TEXTCHANGED] != NULL);
9313}
9314
9315/*
9316 * Return TRUE when there is a TextChangedI autocommand defined.
9317 */
9318 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009319has_textchangedI(void)
Bram Moolenaar186628f2013-03-19 13:33:23 +01009320{
9321 return (first_autopat[(int)EVENT_TEXTCHANGEDI] != NULL);
9322}
9323
9324/*
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009325 * Return TRUE when there is an InsertCharPre autocommand defined.
9326 */
9327 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009328has_insertcharpre(void)
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009329{
9330 return (first_autopat[(int)EVENT_INSERTCHARPRE] != NULL);
9331}
9332
Bram Moolenaard5005162014-08-22 23:05:54 +02009333/*
9334 * Return TRUE when there is an CmdUndefined autocommand defined.
9335 */
9336 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009337has_cmdundefined(void)
Bram Moolenaard5005162014-08-22 23:05:54 +02009338{
9339 return (first_autopat[(int)EVENT_CMDUNDEFINED] != NULL);
9340}
9341
9342/*
9343 * Return TRUE when there is an FuncUndefined autocommand defined.
9344 */
9345 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009346has_funcundefined(void)
Bram Moolenaard5005162014-08-22 23:05:54 +02009347{
9348 return (first_autopat[(int)EVENT_FUNCUNDEFINED] != NULL);
9349}
9350
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009351/*
9352 * Execute autocommands for "event" and file name "fname".
9353 * Return TRUE if some commands were executed.
9354 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009355 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009356apply_autocmds_group(
9357 event_T event,
9358 char_u *fname, /* NULL or empty means use actual file name */
9359 char_u *fname_io, /* fname to use for <afile> on cmdline, NULL means
Bram Moolenaar071d4272004-06-13 20:20:40 +00009360 use fname */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009361 int force, /* when TRUE, ignore autocmd_busy */
9362 int group, /* group ID, or AUGROUP_ALL */
9363 buf_T *buf, /* buffer for <abuf> */
9364 exarg_T *eap) /* command arguments */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009365{
9366 char_u *sfname = NULL; /* short file name */
9367 char_u *tail;
9368 int save_changed;
9369 buf_T *old_curbuf;
9370 int retval = FALSE;
9371 char_u *save_sourcing_name;
9372 linenr_T save_sourcing_lnum;
9373 char_u *save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009374 int save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009375 int save_autocmd_bufnr;
9376 char_u *save_autocmd_match;
9377 int save_autocmd_busy;
9378 int save_autocmd_nested;
9379 static int nesting = 0;
9380 AutoPatCmd patcmd;
9381 AutoPat *ap;
9382#ifdef FEAT_EVAL
9383 scid_T save_current_SID;
9384 void *save_funccalp;
9385 char_u *save_cmdarg;
9386 long save_cmdbang;
9387#endif
9388 static int filechangeshell_busy = FALSE;
Bram Moolenaar05159a02005-02-26 23:04:13 +00009389#ifdef FEAT_PROFILE
9390 proftime_T wait_time;
9391#endif
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009392 int did_save_redobuff = FALSE;
Bram Moolenaard4863aa2017-04-07 19:50:12 +02009393 save_redo_T save_redo;
Bram Moolenaarc9e9c712017-11-09 12:29:35 +01009394 int save_KeyTyped = KeyTyped;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009395
9396 /*
9397 * Quickly return if there are no autocommands for this event or
9398 * autocommands are blocked.
9399 */
Bram Moolenaarfaf29d72017-07-09 11:07:16 +02009400 if (event == NUM_EVENTS || first_autopat[(int)event] == NULL
9401 || autocmd_blocked > 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009402 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009403
9404 /*
9405 * When autocommands are busy, new autocommands are only executed when
9406 * explicitly enabled with the "nested" flag.
9407 */
9408 if (autocmd_busy && !(force || autocmd_nested))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009409 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009410
9411#ifdef FEAT_EVAL
9412 /*
Bram Moolenaar7263a772007-05-10 17:35:54 +00009413 * Quickly return when immediately aborting on error, or when an interrupt
Bram Moolenaar071d4272004-06-13 20:20:40 +00009414 * occurred or an exception was thrown but not caught.
9415 */
9416 if (aborting())
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009417 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009418#endif
9419
9420 /*
9421 * FileChangedShell never nests, because it can create an endless loop.
9422 */
Bram Moolenaar56718732006-03-15 22:53:57 +00009423 if (filechangeshell_busy && (event == EVENT_FILECHANGEDSHELL
9424 || event == EVENT_FILECHANGEDSHELLPOST))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009425 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009426
9427 /*
9428 * Ignore events in 'eventignore'.
9429 */
9430 if (event_ignored(event))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009431 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009432
9433 /*
9434 * Allow nesting of autocommands, but restrict the depth, because it's
9435 * possible to create an endless loop.
9436 */
9437 if (nesting == 10)
9438 {
9439 EMSG(_("E218: autocommand nesting too deep"));
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009440 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009441 }
9442
9443 /*
9444 * Check if these autocommands are disabled. Used when doing ":all" or
9445 * ":ball".
9446 */
9447 if ( (autocmd_no_enter
9448 && (event == EVENT_WINENTER || event == EVENT_BUFENTER))
9449 || (autocmd_no_leave
9450 && (event == EVENT_WINLEAVE || event == EVENT_BUFLEAVE)))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009451 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009452
9453 /*
9454 * Save the autocmd_* variables and info about the current buffer.
9455 */
9456 save_autocmd_fname = autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009457 save_autocmd_fname_full = autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009458 save_autocmd_bufnr = autocmd_bufnr;
9459 save_autocmd_match = autocmd_match;
9460 save_autocmd_busy = autocmd_busy;
9461 save_autocmd_nested = autocmd_nested;
9462 save_changed = curbuf->b_changed;
9463 old_curbuf = curbuf;
9464
9465 /*
9466 * Set the file name to be used for <afile>.
Bram Moolenaara0174af2008-01-02 20:08:25 +00009467 * Make a copy to avoid that changing a buffer name or directory makes it
9468 * invalid.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009469 */
9470 if (fname_io == NULL)
9471 {
Bram Moolenaar53744302015-07-17 17:38:22 +02009472 if (event == EVENT_COLORSCHEME || event == EVENT_OPTIONSET)
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009473 autocmd_fname = NULL;
Bram Moolenaarfaf29d72017-07-09 11:07:16 +02009474 else if (fname != NULL && !ends_excmd(*fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009475 autocmd_fname = fname;
9476 else if (buf != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009477 autocmd_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009478 else
9479 autocmd_fname = NULL;
9480 }
9481 else
9482 autocmd_fname = fname_io;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009483 if (autocmd_fname != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009484 autocmd_fname = vim_strsave(autocmd_fname);
9485 autocmd_fname_full = FALSE; /* call FullName_save() later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009486
9487 /*
9488 * Set the buffer number to be used for <abuf>.
9489 */
9490 if (buf == NULL)
9491 autocmd_bufnr = 0;
9492 else
9493 autocmd_bufnr = buf->b_fnum;
9494
9495 /*
9496 * When the file name is NULL or empty, use the file name of buffer "buf".
9497 * Always use the full path of the file name to match with, in case
9498 * "allow_dirs" is set.
9499 */
9500 if (fname == NULL || *fname == NUL)
9501 {
9502 if (buf == NULL)
9503 fname = NULL;
9504 else
9505 {
9506#ifdef FEAT_SYN_HL
9507 if (event == EVENT_SYNTAX)
9508 fname = buf->b_p_syn;
9509 else
9510#endif
9511 if (event == EVENT_FILETYPE)
9512 fname = buf->b_p_ft;
9513 else
9514 {
9515 if (buf->b_sfname != NULL)
9516 sfname = vim_strsave(buf->b_sfname);
9517 fname = buf->b_ffname;
9518 }
9519 }
9520 if (fname == NULL)
9521 fname = (char_u *)"";
9522 fname = vim_strsave(fname); /* make a copy, so we can change it */
9523 }
9524 else
9525 {
9526 sfname = vim_strsave(fname);
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009527 /* Don't try expanding FileType, Syntax, FuncUndefined, WindowID,
9528 * ColorScheme or QuickFixCmd* */
Bram Moolenaar7c626922005-02-07 22:01:03 +00009529 if (event == EVENT_FILETYPE
9530 || event == EVENT_SYNTAX
Bram Moolenaar5135d462009-04-29 16:03:38 +00009531 || event == EVENT_FUNCUNDEFINED
Bram Moolenaar7c626922005-02-07 22:01:03 +00009532 || event == EVENT_REMOTEREPLY
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00009533 || event == EVENT_SPELLFILEMISSING
Bram Moolenaar7c626922005-02-07 22:01:03 +00009534 || event == EVENT_QUICKFIXCMDPRE
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009535 || event == EVENT_COLORSCHEME
Bram Moolenaar53744302015-07-17 17:38:22 +02009536 || event == EVENT_OPTIONSET
Bram Moolenaar7c626922005-02-07 22:01:03 +00009537 || event == EVENT_QUICKFIXCMDPOST)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009538 fname = vim_strsave(fname);
9539 else
9540 fname = FullName_save(fname, FALSE);
9541 }
9542 if (fname == NULL) /* out of memory */
9543 {
9544 vim_free(sfname);
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009545 retval = FALSE;
9546 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009547 }
9548
9549#ifdef BACKSLASH_IN_FILENAME
9550 /*
9551 * Replace all backslashes with forward slashes. This makes the
9552 * autocommand patterns portable between Unix and MS-DOS.
9553 */
9554 if (sfname != NULL)
9555 forward_slash(sfname);
9556 forward_slash(fname);
9557#endif
9558
9559#ifdef VMS
9560 /* remove version for correct match */
9561 if (sfname != NULL)
9562 vms_remove_version(sfname);
9563 vms_remove_version(fname);
9564#endif
9565
9566 /*
9567 * Set the name to be used for <amatch>.
9568 */
9569 autocmd_match = fname;
9570
9571
9572 /* Don't redraw while doing auto commands. */
9573 ++RedrawingDisabled;
9574 save_sourcing_name = sourcing_name;
9575 sourcing_name = NULL; /* don't free this one */
9576 save_sourcing_lnum = sourcing_lnum;
9577 sourcing_lnum = 0; /* no line number here */
9578
9579#ifdef FEAT_EVAL
9580 save_current_SID = current_SID;
9581
Bram Moolenaar05159a02005-02-26 23:04:13 +00009582# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009583 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009584 prof_child_enter(&wait_time); /* doesn't count for the caller itself */
9585# endif
9586
Bram Moolenaar071d4272004-06-13 20:20:40 +00009587 /* Don't use local function variables, if called from a function */
9588 save_funccalp = save_funccal();
9589#endif
9590
9591 /*
9592 * When starting to execute autocommands, save the search patterns.
9593 */
9594 if (!autocmd_busy)
9595 {
9596 save_search_patterns();
Bram Moolenaar20ad69c2015-12-03 13:52:52 +01009597#ifdef FEAT_INS_EXPAND
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009598 if (!ins_compl_active())
Bram Moolenaar20ad69c2015-12-03 13:52:52 +01009599#endif
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009600 {
Bram Moolenaard4863aa2017-04-07 19:50:12 +02009601 saveRedobuff(&save_redo);
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009602 did_save_redobuff = TRUE;
9603 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009604 did_filetype = keep_filetype;
9605 }
9606
9607 /*
9608 * Note that we are applying autocmds. Some commands need to know.
9609 */
9610 autocmd_busy = TRUE;
9611 filechangeshell_busy = (event == EVENT_FILECHANGEDSHELL);
9612 ++nesting; /* see matching decrement below */
9613
9614 /* Remember that FileType was triggered. Used for did_filetype(). */
9615 if (event == EVENT_FILETYPE)
9616 did_filetype = TRUE;
9617
9618 tail = gettail(fname);
9619
9620 /* Find first autocommand that matches */
9621 patcmd.curpat = first_autopat[(int)event];
9622 patcmd.nextcmd = NULL;
9623 patcmd.group = group;
9624 patcmd.fname = fname;
9625 patcmd.sfname = sfname;
9626 patcmd.tail = tail;
9627 patcmd.event = event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009628 patcmd.arg_bufnr = autocmd_bufnr;
9629 patcmd.next = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009630 auto_next_pat(&patcmd, FALSE);
9631
9632 /* found one, start executing the autocommands */
9633 if (patcmd.curpat != NULL)
9634 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009635 /* add to active_apc_list */
9636 patcmd.next = active_apc_list;
9637 active_apc_list = &patcmd;
9638
Bram Moolenaar071d4272004-06-13 20:20:40 +00009639#ifdef FEAT_EVAL
9640 /* set v:cmdarg (only when there is a matching pattern) */
Bram Moolenaar22fcfad2016-07-01 18:17:26 +02009641 save_cmdbang = (long)get_vim_var_nr(VV_CMDBANG);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009642 if (eap != NULL)
9643 {
9644 save_cmdarg = set_cmdarg(eap, NULL);
9645 set_vim_var_nr(VV_CMDBANG, (long)eap->forceit);
9646 }
9647 else
9648 save_cmdarg = NULL; /* avoid gcc warning */
9649#endif
9650 retval = TRUE;
9651 /* mark the last pattern, to avoid an endless loop when more patterns
9652 * are added when executing autocommands */
9653 for (ap = patcmd.curpat; ap->next != NULL; ap = ap->next)
9654 ap->last = FALSE;
9655 ap->last = TRUE;
9656 check_lnums(TRUE); /* make sure cursor and topline are valid */
9657 do_cmdline(NULL, getnextac, (void *)&patcmd,
9658 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
9659#ifdef FEAT_EVAL
9660 if (eap != NULL)
9661 {
9662 (void)set_cmdarg(NULL, save_cmdarg);
9663 set_vim_var_nr(VV_CMDBANG, save_cmdbang);
9664 }
9665#endif
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009666 /* delete from active_apc_list */
9667 if (active_apc_list == &patcmd) /* just in case */
9668 active_apc_list = patcmd.next;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009669 }
9670
9671 --RedrawingDisabled;
9672 autocmd_busy = save_autocmd_busy;
9673 filechangeshell_busy = FALSE;
9674 autocmd_nested = save_autocmd_nested;
9675 vim_free(sourcing_name);
9676 sourcing_name = save_sourcing_name;
9677 sourcing_lnum = save_sourcing_lnum;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009678 vim_free(autocmd_fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009679 autocmd_fname = save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009680 autocmd_fname_full = save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009681 autocmd_bufnr = save_autocmd_bufnr;
9682 autocmd_match = save_autocmd_match;
9683#ifdef FEAT_EVAL
9684 current_SID = save_current_SID;
9685 restore_funccal(save_funccalp);
Bram Moolenaar05159a02005-02-26 23:04:13 +00009686# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009687 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009688 prof_child_exit(&wait_time);
9689# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009690#endif
Bram Moolenaarc9e9c712017-11-09 12:29:35 +01009691 KeyTyped = save_KeyTyped;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009692 vim_free(fname);
9693 vim_free(sfname);
9694 --nesting; /* see matching increment above */
9695
9696 /*
9697 * When stopping to execute autocommands, restore the search patterns and
Bram Moolenaar3be85852014-06-12 14:01:31 +02009698 * the redo buffer. Free any buffers in the au_pending_free_buf list and
9699 * free any windows in the au_pending_free_win list.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009700 */
9701 if (!autocmd_busy)
9702 {
9703 restore_search_patterns();
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009704 if (did_save_redobuff)
Bram Moolenaard4863aa2017-04-07 19:50:12 +02009705 restoreRedobuff(&save_redo);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009706 did_filetype = FALSE;
Bram Moolenaar4c7ab1b2014-04-06 20:45:43 +02009707 while (au_pending_free_buf != NULL)
9708 {
9709 buf_T *b = au_pending_free_buf->b_next;
9710 vim_free(au_pending_free_buf);
9711 au_pending_free_buf = b;
9712 }
Bram Moolenaar3be85852014-06-12 14:01:31 +02009713 while (au_pending_free_win != NULL)
9714 {
9715 win_T *w = au_pending_free_win->w_next;
9716 vim_free(au_pending_free_win);
9717 au_pending_free_win = w;
9718 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009719 }
9720
9721 /*
9722 * Some events don't set or reset the Changed flag.
9723 * Check if still in the same buffer!
9724 */
9725 if (curbuf == old_curbuf
9726 && (event == EVENT_BUFREADPOST
9727 || event == EVENT_BUFWRITEPOST
9728 || event == EVENT_FILEAPPENDPOST
9729 || event == EVENT_VIMLEAVE
9730 || event == EVENT_VIMLEAVEPRE))
9731 {
9732#ifdef FEAT_TITLE
9733 if (curbuf->b_changed != save_changed)
9734 need_maketitle = TRUE;
9735#endif
9736 curbuf->b_changed = save_changed;
9737 }
9738
9739 au_cleanup(); /* may really delete removed patterns/commands now */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009740
9741BYPASS_AU:
9742 /* When wiping out a buffer make sure all its buffer-local autocommands
9743 * are deleted. */
9744 if (event == EVENT_BUFWIPEOUT && buf != NULL)
9745 aubuflocal_remove(buf);
9746
Bram Moolenaarc3691332016-04-20 12:49:49 +02009747 if (retval == OK && event == EVENT_FILETYPE)
9748 au_did_filetype = TRUE;
9749
Bram Moolenaar071d4272004-06-13 20:20:40 +00009750 return retval;
9751}
9752
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009753# ifdef FEAT_EVAL
9754static char_u *old_termresponse = NULL;
9755# endif
9756
9757/*
9758 * Block triggering autocommands until unblock_autocmd() is called.
9759 * Can be used recursively, so long as it's symmetric.
9760 */
9761 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009762block_autocmds(void)
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009763{
9764# ifdef FEAT_EVAL
9765 /* Remember the value of v:termresponse. */
9766 if (autocmd_blocked == 0)
9767 old_termresponse = get_vim_var_str(VV_TERMRESPONSE);
9768# endif
9769 ++autocmd_blocked;
9770}
9771
9772 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009773unblock_autocmds(void)
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009774{
9775 --autocmd_blocked;
9776
9777# ifdef FEAT_EVAL
9778 /* When v:termresponse was set while autocommands were blocked, trigger
9779 * the autocommands now. Esp. useful when executing a shell command
9780 * during startup (vimdiff). */
9781 if (autocmd_blocked == 0
9782 && get_vim_var_str(VV_TERMRESPONSE) != old_termresponse)
9783 apply_autocmds(EVENT_TERMRESPONSE, NULL, NULL, FALSE, curbuf);
9784# endif
9785}
9786
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009787 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009788is_autocmd_blocked(void)
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009789{
9790 return autocmd_blocked != 0;
9791}
9792
Bram Moolenaar071d4272004-06-13 20:20:40 +00009793/*
9794 * Find next autocommand pattern that matches.
9795 */
9796 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009797auto_next_pat(
9798 AutoPatCmd *apc,
9799 int stop_at_last) /* stop when 'last' flag is set */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009800{
9801 AutoPat *ap;
9802 AutoCmd *cp;
9803 char_u *name;
9804 char *s;
9805
9806 vim_free(sourcing_name);
9807 sourcing_name = NULL;
9808
9809 for (ap = apc->curpat; ap != NULL && !got_int; ap = ap->next)
9810 {
9811 apc->curpat = NULL;
9812
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009813 /* Only use a pattern when it has not been removed, has commands and
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009814 * the group matches. For buffer-local autocommands only check the
9815 * buffer number. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009816 if (ap->pat != NULL && ap->cmds != NULL
9817 && (apc->group == AUGROUP_ALL || apc->group == ap->group))
9818 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009819 /* execution-condition */
9820 if (ap->buflocal_nr == 0
Bram Moolenaardffa5b82014-11-19 16:38:07 +01009821 ? (match_file_pat(NULL, &ap->reg_prog, apc->fname,
Bram Moolenaar748bf032005-02-02 23:04:36 +00009822 apc->sfname, apc->tail, ap->allow_dirs))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009823 : ap->buflocal_nr == apc->arg_bufnr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009824 {
9825 name = event_nr2name(apc->event);
9826 s = _("%s Auto commands for \"%s\"");
9827 sourcing_name = alloc((unsigned)(STRLEN(s)
9828 + STRLEN(name) + ap->patlen + 1));
9829 if (sourcing_name != NULL)
9830 {
9831 sprintf((char *)sourcing_name, s,
9832 (char *)name, (char *)ap->pat);
9833 if (p_verbose >= 8)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009834 {
9835 verbose_enter();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009836 smsg((char_u *)_("Executing %s"), sourcing_name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009837 verbose_leave();
9838 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009839 }
9840
9841 apc->curpat = ap;
9842 apc->nextcmd = ap->cmds;
9843 /* mark last command */
9844 for (cp = ap->cmds; cp->next != NULL; cp = cp->next)
9845 cp->last = FALSE;
9846 cp->last = TRUE;
9847 }
9848 line_breakcheck();
9849 if (apc->curpat != NULL) /* found a match */
9850 break;
9851 }
9852 if (stop_at_last && ap->last)
9853 break;
9854 }
9855}
9856
9857/*
9858 * Get next autocommand command.
9859 * Called by do_cmdline() to get the next line for ":if".
9860 * Returns allocated string, or NULL for end of autocommands.
9861 */
Bram Moolenaar21691f82012-12-05 19:13:18 +01009862 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009863getnextac(int c UNUSED, void *cookie, int indent UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009864{
9865 AutoPatCmd *acp = (AutoPatCmd *)cookie;
9866 char_u *retval;
9867 AutoCmd *ac;
9868
9869 /* Can be called again after returning the last line. */
9870 if (acp->curpat == NULL)
9871 return NULL;
9872
9873 /* repeat until we find an autocommand to execute */
9874 for (;;)
9875 {
9876 /* skip removed commands */
9877 while (acp->nextcmd != NULL && acp->nextcmd->cmd == NULL)
9878 if (acp->nextcmd->last)
9879 acp->nextcmd = NULL;
9880 else
9881 acp->nextcmd = acp->nextcmd->next;
9882
9883 if (acp->nextcmd != NULL)
9884 break;
9885
9886 /* at end of commands, find next pattern that matches */
9887 if (acp->curpat->last)
9888 acp->curpat = NULL;
9889 else
9890 acp->curpat = acp->curpat->next;
9891 if (acp->curpat != NULL)
9892 auto_next_pat(acp, TRUE);
9893 if (acp->curpat == NULL)
9894 return NULL;
9895 }
9896
9897 ac = acp->nextcmd;
9898
9899 if (p_verbose >= 9)
9900 {
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009901 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009902 smsg((char_u *)_("autocommand %s"), ac->cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009903 msg_puts((char_u *)"\n"); /* don't overwrite this either */
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009904 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009905 }
9906 retval = vim_strsave(ac->cmd);
9907 autocmd_nested = ac->nested;
9908#ifdef FEAT_EVAL
9909 current_SID = ac->scriptID;
9910#endif
9911 if (ac->last)
9912 acp->nextcmd = NULL;
9913 else
9914 acp->nextcmd = ac->next;
9915 return retval;
9916}
9917
9918/*
9919 * Return TRUE if there is a matching autocommand for "fname".
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009920 * To account for buffer-local autocommands, function needs to know
9921 * in which buffer the file will be opened.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009922 */
9923 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009924has_autocmd(event_T event, char_u *sfname, buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009925{
9926 AutoPat *ap;
9927 char_u *fname;
9928 char_u *tail = gettail(sfname);
9929 int retval = FALSE;
9930
9931 fname = FullName_save(sfname, FALSE);
9932 if (fname == NULL)
9933 return FALSE;
9934
9935#ifdef BACKSLASH_IN_FILENAME
9936 /*
9937 * Replace all backslashes with forward slashes. This makes the
9938 * autocommand patterns portable between Unix and MS-DOS.
9939 */
9940 sfname = vim_strsave(sfname);
9941 if (sfname != NULL)
9942 forward_slash(sfname);
9943 forward_slash(fname);
9944#endif
9945
9946 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
9947 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009948 && (ap->buflocal_nr == 0
Bram Moolenaardffa5b82014-11-19 16:38:07 +01009949 ? match_file_pat(NULL, &ap->reg_prog,
Bram Moolenaar748bf032005-02-02 23:04:36 +00009950 fname, sfname, tail, ap->allow_dirs)
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009951 : buf != NULL && ap->buflocal_nr == buf->b_fnum
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009952 ))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009953 {
9954 retval = TRUE;
9955 break;
9956 }
9957
9958 vim_free(fname);
9959#ifdef BACKSLASH_IN_FILENAME
9960 vim_free(sfname);
9961#endif
9962
9963 return retval;
9964}
9965
9966#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
9967/*
9968 * Function given to ExpandGeneric() to obtain the list of autocommand group
9969 * names.
9970 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009971 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009972get_augroup_name(expand_T *xp UNUSED, int idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009973{
9974 if (idx == augroups.ga_len) /* add "END" add the end */
9975 return (char_u *)"END";
9976 if (idx >= augroups.ga_len) /* end of list */
9977 return NULL;
Bram Moolenaarb62cc362016-09-03 16:43:53 +02009978 if (AUGROUP_NAME(idx) == NULL || AUGROUP_NAME(idx) == get_deleted_augroup())
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02009979 /* skip deleted entries */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009980 return (char_u *)"";
9981 return AUGROUP_NAME(idx); /* return a name */
9982}
9983
9984static int include_groups = FALSE;
9985
9986 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009987set_context_in_autocmd(
9988 expand_T *xp,
9989 char_u *arg,
9990 int doautocmd) /* TRUE for :doauto*, FALSE for :autocmd */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009991{
9992 char_u *p;
9993 int group;
9994
9995 /* check for a group name, skip it if present */
9996 include_groups = FALSE;
9997 p = arg;
9998 group = au_get_grouparg(&arg);
9999 if (group == AUGROUP_ERROR)
10000 return NULL;
10001 /* If there only is a group name that's what we expand. */
Bram Moolenaar1c465442017-03-12 20:10:05 +010010002 if (*arg == NUL && group != AUGROUP_ALL && !VIM_ISWHITE(arg[-1]))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010003 {
10004 arg = p;
10005 group = AUGROUP_ALL;
10006 }
10007
10008 /* skip over event name */
Bram Moolenaar1c465442017-03-12 20:10:05 +010010009 for (p = arg; *p != NUL && !VIM_ISWHITE(*p); ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010010 if (*p == ',')
10011 arg = p + 1;
10012 if (*p == NUL)
10013 {
10014 if (group == AUGROUP_ALL)
10015 include_groups = TRUE;
10016 xp->xp_context = EXPAND_EVENTS; /* expand event name */
10017 xp->xp_pattern = arg;
10018 return NULL;
10019 }
10020
10021 /* skip over pattern */
10022 arg = skipwhite(p);
Bram Moolenaar1c465442017-03-12 20:10:05 +010010023 while (*arg && (!VIM_ISWHITE(*arg) || arg[-1] == '\\'))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010024 arg++;
10025 if (*arg)
10026 return arg; /* expand (next) command */
10027
10028 if (doautocmd)
10029 xp->xp_context = EXPAND_FILES; /* expand file names */
10030 else
10031 xp->xp_context = EXPAND_NOTHING; /* pattern is not expanded */
10032 return NULL;
10033}
10034
10035/*
10036 * Function given to ExpandGeneric() to obtain the list of event names.
10037 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010038 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010039get_event_name(expand_T *xp UNUSED, int idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010040{
10041 if (idx < augroups.ga_len) /* First list group names, if wanted */
10042 {
Bram Moolenaarf2c4c392016-07-29 20:50:24 +020010043 if (!include_groups || AUGROUP_NAME(idx) == NULL
Bram Moolenaarb62cc362016-09-03 16:43:53 +020010044 || AUGROUP_NAME(idx) == get_deleted_augroup())
Bram Moolenaar071d4272004-06-13 20:20:40 +000010045 return (char_u *)""; /* skip deleted entries */
10046 return AUGROUP_NAME(idx); /* return a name */
10047 }
10048 return (char_u *)event_names[idx - augroups.ga_len].name;
10049}
10050
10051#endif /* FEAT_CMDL_COMPL */
10052
10053/*
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010054 * Return TRUE if autocmd is supported.
10055 */
10056 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010057autocmd_supported(char_u *name)
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010058{
10059 char_u *p;
10060
10061 return (event_name2nr(name, &p) != NUM_EVENTS);
10062}
10063
10064/*
Bram Moolenaar195d6352005-12-19 22:08:24 +000010065 * Return TRUE if an autocommand is defined for a group, event and
10066 * pattern: The group can be omitted to accept any group. "event" and "pattern"
10067 * can be NULL to accept any event and pattern. "pattern" can be NULL to accept
10068 * any pattern. Buffer-local patterns <buffer> or <buffer=N> are accepted.
10069 * Used for:
10070 * exists("#Group") or
10071 * exists("#Group#Event") or
10072 * exists("#Group#Event#pat") or
10073 * exists("#Event") or
10074 * exists("#Event#pat")
Bram Moolenaar071d4272004-06-13 20:20:40 +000010075 */
10076 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010077au_exists(char_u *arg)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010078{
Bram Moolenaar195d6352005-12-19 22:08:24 +000010079 char_u *arg_save;
10080 char_u *pattern = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010081 char_u *event_name;
10082 char_u *p;
Bram Moolenaar754b5602006-02-09 23:53:20 +000010083 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010084 AutoPat *ap;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010085 buf_T *buflocal_buf = NULL;
Bram Moolenaar195d6352005-12-19 22:08:24 +000010086 int group;
10087 int retval = FALSE;
10088
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010089 /* Make a copy so that we can change the '#' chars to a NUL. */
Bram Moolenaar195d6352005-12-19 22:08:24 +000010090 arg_save = vim_strsave(arg);
10091 if (arg_save == NULL)
10092 return FALSE;
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010093 p = vim_strchr(arg_save, '#');
Bram Moolenaar195d6352005-12-19 22:08:24 +000010094 if (p != NULL)
10095 *p++ = NUL;
10096
10097 /* First, look for an autocmd group name */
10098 group = au_find_group(arg_save);
10099 if (group == AUGROUP_ERROR)
10100 {
10101 /* Didn't match a group name, assume the first argument is an event. */
10102 group = AUGROUP_ALL;
10103 event_name = arg_save;
10104 }
10105 else
10106 {
10107 if (p == NULL)
10108 {
10109 /* "Group": group name is present and it's recognized */
10110 retval = TRUE;
10111 goto theend;
10112 }
10113
10114 /* Must be "Group#Event" or "Group#Event#pat". */
10115 event_name = p;
10116 p = vim_strchr(event_name, '#');
10117 if (p != NULL)
10118 *p++ = NUL; /* "Group#Event#pat" */
10119 }
10120
10121 pattern = p; /* "pattern" is NULL when there is no pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010122
10123 /* find the index (enum) for the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010124 event = event_name2nr(event_name, &p);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010125
10126 /* return FALSE if the event name is not recognized */
Bram Moolenaar195d6352005-12-19 22:08:24 +000010127 if (event == NUM_EVENTS)
10128 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010129
10130 /* Find the first autocommand for this event.
10131 * If there isn't any, return FALSE;
10132 * If there is one and no pattern given, return TRUE; */
10133 ap = first_autopat[(int)event];
10134 if (ap == NULL)
Bram Moolenaar195d6352005-12-19 22:08:24 +000010135 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010136
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010137 /* if pattern is "<buffer>", special handling is needed which uses curbuf */
10138 /* for pattern "<buffer=N>, fnamecmp() will work fine */
Bram Moolenaar5b7880d2009-09-11 15:24:31 +000010139 if (pattern != NULL && STRICMP(pattern, "<buffer>") == 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010140 buflocal_buf = curbuf;
10141
Bram Moolenaar071d4272004-06-13 20:20:40 +000010142 /* Check if there is an autocommand with the given pattern. */
10143 for ( ; ap != NULL; ap = ap->next)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010144 /* only use a pattern when it has not been removed and has commands. */
10145 /* For buffer-local autocommands, fnamecmp() works fine. */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010146 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaar195d6352005-12-19 22:08:24 +000010147 && (group == AUGROUP_ALL || ap->group == group)
Bram Moolenaar5b7880d2009-09-11 15:24:31 +000010148 && (pattern == NULL
10149 || (buflocal_buf == NULL
10150 ? fnamecmp(ap->pat, pattern) == 0
10151 : ap->buflocal_nr == buflocal_buf->b_fnum)))
Bram Moolenaar195d6352005-12-19 22:08:24 +000010152 {
10153 retval = TRUE;
10154 break;
10155 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010156
Bram Moolenaar195d6352005-12-19 22:08:24 +000010157theend:
10158 vim_free(arg_save);
10159 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010160}
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010161
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010162#else /* FEAT_AUTOCMD */
10163
10164/*
10165 * Prepare for executing commands for (hidden) buffer "buf".
10166 * This is the non-autocommand version, it simply saves "curbuf" and sets
10167 * "curbuf" and "curwin" to match "buf".
10168 */
10169 void
Bram Moolenaard14e00e2016-01-31 17:30:51 +010010170aucmd_prepbuf(
10171 aco_save_T *aco, /* structure to save values in */
10172 buf_T *buf) /* new curbuf */
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010173{
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010174 aco->save_curbuf = curbuf;
10175 --curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010176 curbuf = buf;
10177 curwin->w_buffer = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010178 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010179}
10180
10181/*
10182 * Restore after executing commands for a (hidden) buffer.
10183 * This is the non-autocommand version.
10184 */
10185 void
Bram Moolenaard14e00e2016-01-31 17:30:51 +010010186aucmd_restbuf(
10187 aco_save_T *aco) /* structure holding saved values */
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010188{
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010189 --curbuf->b_nwindows;
10190 curbuf = aco->save_curbuf;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010191 curwin->w_buffer = curbuf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010192 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010193}
10194
Bram Moolenaar071d4272004-06-13 20:20:40 +000010195#endif /* FEAT_AUTOCMD */
10196
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010197
Bram Moolenaar071d4272004-06-13 20:20:40 +000010198#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN) || defined(PROTO)
10199/*
Bram Moolenaar748bf032005-02-02 23:04:36 +000010200 * Try matching a filename with a "pattern" ("prog" is NULL), or use the
10201 * precompiled regprog "prog" ("pattern" is NULL). That avoids calling
10202 * vim_regcomp() often.
Bram Moolenaar071d4272004-06-13 20:20:40 +000010203 * Used for autocommands and 'wildignore'.
10204 * Returns TRUE if there is a match, FALSE otherwise.
10205 */
Bram Moolenaardffa5b82014-11-19 16:38:07 +010010206 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010207match_file_pat(
10208 char_u *pattern, /* pattern to match with */
10209 regprog_T **prog, /* pre-compiled regprog or NULL */
10210 char_u *fname, /* full path of file name */
10211 char_u *sfname, /* short file name or NULL */
10212 char_u *tail, /* tail of path */
10213 int allow_dirs) /* allow matching with dir */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010214{
10215 regmatch_T regmatch;
10216 int result = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010217
Bram Moolenaar71afbfe2013-03-19 16:49:16 +010010218 regmatch.rm_ic = p_fic; /* ignore case if 'fileignorecase' is set */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010219 if (prog != NULL)
10220 regmatch.regprog = *prog;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010221 else
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010222 regmatch.regprog = vim_regcomp(pattern, RE_MAGIC);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010223
10224 /*
10225 * Try for a match with the pattern with:
10226 * 1. the full file name, when the pattern has a '/'.
10227 * 2. the short file name, when the pattern has a '/'.
10228 * 3. the tail of the file name, when the pattern has no '/'.
10229 */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010230 if (regmatch.regprog != NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +000010231 && ((allow_dirs
10232 && (vim_regexec(&regmatch, fname, (colnr_T)0)
10233 || (sfname != NULL
10234 && vim_regexec(&regmatch, sfname, (colnr_T)0))))
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010235 || (!allow_dirs && vim_regexec(&regmatch, tail, (colnr_T)0))))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010236 result = TRUE;
10237
Bram Moolenaardffa5b82014-11-19 16:38:07 +010010238 if (prog != NULL)
10239 *prog = regmatch.regprog;
10240 else
Bram Moolenaar473de612013-06-08 18:19:48 +020010241 vim_regfree(regmatch.regprog);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010242 return result;
10243}
10244#endif
10245
10246#if defined(FEAT_WILDIGN) || defined(PROTO)
10247/*
10248 * Return TRUE if a file matches with a pattern in "list".
10249 * "list" is a comma-separated list of patterns, like 'wildignore'.
10250 * "sfname" is the short file name or NULL, "ffname" the long file name.
10251 */
10252 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010253match_file_list(char_u *list, char_u *sfname, char_u *ffname)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010254{
10255 char_u buf[100];
10256 char_u *tail;
10257 char_u *regpat;
10258 char allow_dirs;
10259 int match;
10260 char_u *p;
10261
10262 tail = gettail(sfname);
10263
10264 /* try all patterns in 'wildignore' */
10265 p = list;
10266 while (*p)
10267 {
10268 copy_option_part(&p, buf, 100, ",");
10269 regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, FALSE);
10270 if (regpat == NULL)
10271 break;
Bram Moolenaar748bf032005-02-02 23:04:36 +000010272 match = match_file_pat(regpat, NULL, ffname, sfname,
10273 tail, (int)allow_dirs);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010274 vim_free(regpat);
10275 if (match)
10276 return TRUE;
10277 }
10278 return FALSE;
10279}
10280#endif
10281
10282/*
10283 * Convert the given pattern "pat" which has shell style wildcards in it, into
10284 * a regular expression, and return the result in allocated memory. If there
10285 * is a directory path separator to be matched, then TRUE is put in
10286 * allow_dirs, otherwise FALSE is put there -- webb.
10287 * Handle backslashes before special characters, like "\*" and "\ ".
10288 *
Bram Moolenaar071d4272004-06-13 20:20:40 +000010289 * Returns NULL when out of memory.
10290 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010291 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010292file_pat_to_reg_pat(
10293 char_u *pat,
10294 char_u *pat_end, /* first char after pattern or NULL */
10295 char *allow_dirs, /* Result passed back out in here */
10296 int no_bslash UNUSED) /* Don't use a backward slash as pathsep */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010297{
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010298 int size = 2; /* '^' at start, '$' at end */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010299 char_u *endp;
10300 char_u *reg_pat;
10301 char_u *p;
10302 int i;
10303 int nested = 0;
10304 int add_dollar = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010305
10306 if (allow_dirs != NULL)
10307 *allow_dirs = FALSE;
10308 if (pat_end == NULL)
10309 pat_end = pat + STRLEN(pat);
10310
Bram Moolenaar071d4272004-06-13 20:20:40 +000010311 for (p = pat; p < pat_end; p++)
10312 {
10313 switch (*p)
10314 {
10315 case '*':
10316 case '.':
10317 case ',':
10318 case '{':
10319 case '}':
10320 case '~':
10321 size += 2; /* extra backslash */
10322 break;
10323#ifdef BACKSLASH_IN_FILENAME
10324 case '\\':
10325 case '/':
10326 size += 4; /* could become "[\/]" */
10327 break;
10328#endif
10329 default:
10330 size++;
Bram Moolenaar2288afe2015-08-11 16:20:05 +020010331# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010332 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010333 {
10334 ++p;
10335 ++size;
10336 }
10337# endif
10338 break;
10339 }
10340 }
10341 reg_pat = alloc(size + 1);
10342 if (reg_pat == NULL)
10343 return NULL;
10344
Bram Moolenaar071d4272004-06-13 20:20:40 +000010345 i = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010346
10347 if (pat[0] == '*')
10348 while (pat[0] == '*' && pat < pat_end - 1)
10349 pat++;
10350 else
10351 reg_pat[i++] = '^';
10352 endp = pat_end - 1;
Bram Moolenaar8fee8782015-08-11 18:45:48 +020010353 if (endp >= pat && *endp == '*')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010354 {
10355 while (endp - pat > 0 && *endp == '*')
10356 endp--;
10357 add_dollar = FALSE;
10358 }
10359 for (p = pat; *p && nested >= 0 && p <= endp; p++)
10360 {
10361 switch (*p)
10362 {
10363 case '*':
10364 reg_pat[i++] = '.';
10365 reg_pat[i++] = '*';
Bram Moolenaar02743632005-07-25 20:42:36 +000010366 while (p[1] == '*') /* "**" matches like "*" */
10367 ++p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010368 break;
10369 case '.':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010370 case '~':
10371 reg_pat[i++] = '\\';
10372 reg_pat[i++] = *p;
10373 break;
10374 case '?':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010375 reg_pat[i++] = '.';
10376 break;
10377 case '\\':
10378 if (p[1] == NUL)
10379 break;
10380#ifdef BACKSLASH_IN_FILENAME
10381 if (!no_bslash)
10382 {
10383 /* translate:
10384 * "\x" to "\\x" e.g., "dir\file"
10385 * "\*" to "\\.*" e.g., "dir\*.c"
10386 * "\?" to "\\." e.g., "dir\??.c"
10387 * "\+" to "\+" e.g., "fileX\+.c"
10388 */
10389 if ((vim_isfilec(p[1]) || p[1] == '*' || p[1] == '?')
10390 && p[1] != '+')
10391 {
10392 reg_pat[i++] = '[';
10393 reg_pat[i++] = '\\';
10394 reg_pat[i++] = '/';
10395 reg_pat[i++] = ']';
10396 if (allow_dirs != NULL)
10397 *allow_dirs = TRUE;
10398 break;
10399 }
10400 }
10401#endif
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010402 /* Undo escaping from ExpandEscape():
10403 * foo\?bar -> foo?bar
10404 * foo\%bar -> foo%bar
10405 * foo\,bar -> foo,bar
10406 * foo\ bar -> foo bar
10407 * Don't unescape \, * and others that are also special in a
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010408 * regexp.
10409 * An escaped { must be unescaped since we use magic not
Bram Moolenaara946afe2013-08-02 15:22:39 +020010410 * verymagic. Use "\\\{n,m\}"" to get "\{n,m}".
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010411 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010412 if (*++p == '?'
10413#ifdef BACKSLASH_IN_FILENAME
10414 && no_bslash
10415#endif
10416 )
10417 reg_pat[i++] = '?';
10418 else
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010419 if (*p == ',' || *p == '%' || *p == '#'
Bram Moolenaar2288afe2015-08-11 16:20:05 +020010420 || vim_isspace(*p) || *p == '{' || *p == '}')
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010421 reg_pat[i++] = *p;
Bram Moolenaara946afe2013-08-02 15:22:39 +020010422 else if (*p == '\\' && p[1] == '\\' && p[2] == '{')
10423 {
10424 reg_pat[i++] = '\\';
10425 reg_pat[i++] = '{';
10426 p += 2;
10427 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010428 else
10429 {
10430 if (allow_dirs != NULL && vim_ispathsep(*p)
10431#ifdef BACKSLASH_IN_FILENAME
10432 && (!no_bslash || *p != '\\')
10433#endif
10434 )
10435 *allow_dirs = TRUE;
10436 reg_pat[i++] = '\\';
10437 reg_pat[i++] = *p;
10438 }
10439 break;
10440#ifdef BACKSLASH_IN_FILENAME
10441 case '/':
10442 reg_pat[i++] = '[';
10443 reg_pat[i++] = '\\';
10444 reg_pat[i++] = '/';
10445 reg_pat[i++] = ']';
10446 if (allow_dirs != NULL)
10447 *allow_dirs = TRUE;
10448 break;
10449#endif
10450 case '{':
10451 reg_pat[i++] = '\\';
10452 reg_pat[i++] = '(';
10453 nested++;
10454 break;
10455 case '}':
10456 reg_pat[i++] = '\\';
10457 reg_pat[i++] = ')';
10458 --nested;
10459 break;
10460 case ',':
10461 if (nested)
10462 {
10463 reg_pat[i++] = '\\';
10464 reg_pat[i++] = '|';
10465 }
10466 else
10467 reg_pat[i++] = ',';
10468 break;
10469 default:
10470# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010471 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010472 reg_pat[i++] = *p++;
10473 else
10474# endif
10475 if (allow_dirs != NULL && vim_ispathsep(*p))
10476 *allow_dirs = TRUE;
10477 reg_pat[i++] = *p;
10478 break;
10479 }
10480 }
10481 if (add_dollar)
10482 reg_pat[i++] = '$';
10483 reg_pat[i] = NUL;
10484 if (nested != 0)
10485 {
10486 if (nested < 0)
10487 EMSG(_("E219: Missing {."));
10488 else
10489 EMSG(_("E220: Missing }."));
10490 vim_free(reg_pat);
10491 reg_pat = NULL;
10492 }
10493 return reg_pat;
10494}
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010495
10496#if defined(EINTR) || defined(PROTO)
10497/*
10498 * Version of read() that retries when interrupted by EINTR (possibly
10499 * by a SIGWINCH).
10500 */
10501 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010502read_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010503{
10504 long ret;
10505
10506 for (;;)
10507 {
10508 ret = vim_read(fd, buf, bufsize);
10509 if (ret >= 0 || errno != EINTR)
10510 break;
10511 }
10512 return ret;
10513}
10514
10515/*
10516 * Version of write() that retries when interrupted by EINTR (possibly
10517 * by a SIGWINCH).
10518 */
10519 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010520write_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010521{
10522 long ret = 0;
10523 long wlen;
10524
10525 /* Repeat the write() so long it didn't fail, other than being interrupted
10526 * by a signal. */
10527 while (ret < (long)bufsize)
10528 {
Bram Moolenaar9c263032010-12-17 18:06:06 +010010529 wlen = vim_write(fd, (char *)buf + ret, bufsize - ret);
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010530 if (wlen < 0)
10531 {
10532 if (errno != EINTR)
10533 break;
10534 }
10535 else
10536 ret += wlen;
10537 }
10538 return ret;
10539}
10540#endif