blob: fb49f28f8165b896fa8523e65bab7902fdb86050 [file] [log] [blame]
Bram Moolenaaredf3f972016-08-29 22:49:24 +02001/* vi:set ts=8 sts=4 sw=4 noet:
Bram Moolenaar071d4272004-06-13 20:20:40 +00002 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
11 * fileio.c: read from and write to a file
12 */
13
Bram Moolenaar071d4272004-06-13 20:20:40 +000014#include "vim.h"
15
Bram Moolenaarf4888d02009-12-02 12:31:27 +000016#if defined(__TANDEM) || defined(__MINT__)
Bram Moolenaar071d4272004-06-13 20:20:40 +000017# include <limits.h> /* for SSIZE_MAX */
18#endif
19
20#if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
21# include <utime.h> /* for struct utimbuf */
22#endif
23
24#define BUFSIZE 8192 /* size of normal write buffer */
25#define SMBUFSIZE 256 /* size of emergency write buffer */
26
Bram Moolenaar071d4272004-06-13 20:20:40 +000027/* Is there any system that doesn't have access()? */
Bram Moolenaar9372a112005-12-06 19:59:18 +000028#define USE_MCH_ACCESS
Bram Moolenaar071d4272004-06-13 20:20:40 +000029
30#ifdef FEAT_MBYTE
Bram Moolenaard25c16e2016-01-29 22:13:30 +010031static char_u *next_fenc(char_u **pp);
Bram Moolenaar071d4272004-06-13 20:20:40 +000032# ifdef FEAT_EVAL
Bram Moolenaard25c16e2016-01-29 22:13:30 +010033static char_u *readfile_charconvert(char_u *fname, char_u *fenc, int *fdp);
Bram Moolenaar071d4272004-06-13 20:20:40 +000034# endif
35#endif
36#ifdef FEAT_VIMINFO
Bram Moolenaard25c16e2016-01-29 22:13:30 +010037static void check_marks_read(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +000038#endif
39#ifdef FEAT_CRYPT
Bram Moolenaar8767f522016-07-01 17:17:39 +020040static char_u *check_for_cryptkey(char_u *cryptkey, char_u *ptr, long *sizep, off_T *filesizep, int newfile, char_u *fname, int *did_ask);
Bram Moolenaar071d4272004-06-13 20:20:40 +000041#endif
42#ifdef UNIX
Bram Moolenaard25c16e2016-01-29 22:13:30 +010043static void set_file_time(char_u *fname, time_t atime, time_t mtime);
Bram Moolenaar071d4272004-06-13 20:20:40 +000044#endif
Bram Moolenaard25c16e2016-01-29 22:13:30 +010045static int set_rw_fname(char_u *fname, char_u *sfname);
46static int msg_add_fileformat(int eol_type);
47static void msg_add_eol(void);
Bram Moolenaar8767f522016-07-01 17:17:39 +020048static int check_mtime(buf_T *buf, stat_T *s);
Bram Moolenaard25c16e2016-01-29 22:13:30 +010049static int time_differs(long t1, long t2);
Bram Moolenaar071d4272004-06-13 20:20:40 +000050#ifdef FEAT_AUTOCMD
Bram Moolenaard25c16e2016-01-29 22:13:30 +010051static int apply_autocmds_exarg(event_T event, char_u *fname, char_u *fname_io, int force, buf_T *buf, exarg_T *eap);
52static int au_find_group(char_u *name);
Bram Moolenaar70836c82006-02-20 21:28:49 +000053
54# define AUGROUP_DEFAULT -1 /* default autocmd group */
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +000055# define AUGROUP_ERROR -2 /* erroneous autocmd group */
Bram Moolenaar70836c82006-02-20 21:28:49 +000056# define AUGROUP_ALL -3 /* all autocmd groups */
Bram Moolenaar071d4272004-06-13 20:20:40 +000057#endif
58
59#if defined(FEAT_CRYPT) || defined(FEAT_MBYTE)
60# define HAS_BW_FLAGS
61# define FIO_LATIN1 0x01 /* convert Latin1 */
62# define FIO_UTF8 0x02 /* convert UTF-8 */
63# define FIO_UCS2 0x04 /* convert UCS-2 */
64# define FIO_UCS4 0x08 /* convert UCS-4 */
65# define FIO_UTF16 0x10 /* convert UTF-16 */
66# ifdef WIN3264
67# define FIO_CODEPAGE 0x20 /* convert MS-Windows codepage */
68# define FIO_PUT_CP(x) (((x) & 0xffff) << 16) /* put codepage in top word */
69# define FIO_GET_CP(x) (((x)>>16) & 0xffff) /* get codepage from top word */
70# endif
Bram Moolenaard0573012017-10-28 21:11:06 +020071# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +000072# define FIO_MACROMAN 0x20 /* convert MacRoman */
73# endif
74# define FIO_ENDIAN_L 0x80 /* little endian */
75# define FIO_ENCRYPTED 0x1000 /* encrypt written bytes */
76# define FIO_NOCONVERT 0x2000 /* skip encoding conversion */
77# define FIO_UCSBOM 0x4000 /* check for BOM at start of file */
78# define FIO_ALL -1 /* allow all formats */
79#endif
80
81/* When converting, a read() or write() may leave some bytes to be converted
82 * for the next call. The value is guessed... */
83#define CONV_RESTLEN 30
84
85/* We have to guess how much a sequence of bytes may expand when converting
86 * with iconv() to be able to allocate a buffer. */
87#define ICONV_MULT 8
88
89/*
90 * Structure to pass arguments from buf_write() to buf_write_bytes().
91 */
92struct bw_info
93{
94 int bw_fd; /* file descriptor */
95 char_u *bw_buf; /* buffer with data to be written */
Bram Moolenaard089d9b2007-09-30 12:02:55 +000096 int bw_len; /* length of data */
Bram Moolenaar071d4272004-06-13 20:20:40 +000097#ifdef HAS_BW_FLAGS
98 int bw_flags; /* FIO_ flags */
99#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +0200100#ifdef FEAT_CRYPT
101 buf_T *bw_buffer; /* buffer being written */
102#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000103#ifdef FEAT_MBYTE
104 char_u bw_rest[CONV_RESTLEN]; /* not converted bytes */
105 int bw_restlen; /* nr of bytes in bw_rest[] */
106 int bw_first; /* first write call */
107 char_u *bw_conv_buf; /* buffer for writing converted chars */
108 int bw_conv_buflen; /* size of bw_conv_buf */
109 int bw_conv_error; /* set for conversion error */
Bram Moolenaar32b485f2009-07-29 16:06:27 +0000110 linenr_T bw_conv_error_lnum; /* first line with error or zero */
111 linenr_T bw_start_lnum; /* line number at start of buffer */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000112# ifdef USE_ICONV
113 iconv_t bw_iconv_fd; /* descriptor for iconv() or -1 */
114# endif
115#endif
116};
117
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100118static int buf_write_bytes(struct bw_info *ip);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000119
120#ifdef FEAT_MBYTE
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100121static linenr_T readfile_linenr(linenr_T linecnt, char_u *p, char_u *endp);
122static int ucs2bytes(unsigned c, char_u **pp, int flags);
123static int need_conversion(char_u *fenc);
124static int get_fio_flags(char_u *ptr);
125static char_u *check_for_bom(char_u *p, long size, int *lenp, int flags);
126static int make_bom(char_u *buf, char_u *name);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000127# ifdef WIN3264
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100128static int get_win_fio_flags(char_u *ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000129# endif
Bram Moolenaard0573012017-10-28 21:11:06 +0200130# ifdef MACOS_CONVERT
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100131static int get_mac_fio_flags(char_u *ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000132# endif
133#endif
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100134static int move_lines(buf_T *frombuf, buf_T *tobuf);
Bram Moolenaar4592dee2009-11-18 19:11:58 +0000135#ifdef TEMPDIRNAMES
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100136static void vim_settempdir(char_u *tempdir);
Bram Moolenaar4592dee2009-11-18 19:11:58 +0000137#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000138#ifdef FEAT_AUTOCMD
139static char *e_auchangedbuf = N_("E812: Autocommands changed buffer or buffer name");
140#endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000141
Bram Moolenaarc3691332016-04-20 12:49:49 +0200142#ifdef FEAT_AUTOCMD
143/*
144 * Set by the apply_autocmds_group function if the given event is equal to
145 * EVENT_FILETYPE. Used by the readfile function in order to determine if
146 * EVENT_BUFREADPOST triggered the EVENT_FILETYPE.
147 *
148 * Relying on this value requires one to reset it prior calling
149 * apply_autocmds_group.
150 */
151static int au_did_filetype INIT(= FALSE);
152#endif
153
Bram Moolenaar071d4272004-06-13 20:20:40 +0000154 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +0100155filemess(
156 buf_T *buf,
157 char_u *name,
158 char_u *s,
159 int attr)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000160{
161 int msg_scroll_save;
162
163 if (msg_silent != 0)
164 return;
165 msg_add_fname(buf, name); /* put file name in IObuff with quotes */
166 /* If it's extremely long, truncate it. */
167 if (STRLEN(IObuff) > IOSIZE - 80)
168 IObuff[IOSIZE - 80] = NUL;
169 STRCAT(IObuff, s);
170 /*
171 * For the first message may have to start a new line.
172 * For further ones overwrite the previous one, reset msg_scroll before
173 * calling filemess().
174 */
175 msg_scroll_save = msg_scroll;
176 if (shortmess(SHM_OVERALL) && !exiting && p_verbose == 0)
177 msg_scroll = FALSE;
178 if (!msg_scroll) /* wait a bit when overwriting an error msg */
179 check_for_delay(FALSE);
180 msg_start();
181 msg_scroll = msg_scroll_save;
182 msg_scrolled_ign = TRUE;
183 /* may truncate the message to avoid a hit-return prompt */
184 msg_outtrans_attr(msg_may_trunc(FALSE, IObuff), attr);
185 msg_clr_eos();
186 out_flush();
187 msg_scrolled_ign = FALSE;
188}
189
190/*
191 * Read lines from file "fname" into the buffer after line "from".
192 *
193 * 1. We allocate blocks with lalloc, as big as possible.
194 * 2. Each block is filled with characters from the file with a single read().
195 * 3. The lines are inserted in the buffer with ml_append().
196 *
197 * (caller must check that fname != NULL, unless READ_STDIN is used)
198 *
199 * "lines_to_skip" is the number of lines that must be skipped
200 * "lines_to_read" is the number of lines that are appended
201 * When not recovering lines_to_skip is 0 and lines_to_read MAXLNUM.
202 *
203 * flags:
204 * READ_NEW starting to edit a new buffer
205 * READ_FILTER reading filter output
206 * READ_STDIN read from stdin instead of a file
207 * READ_BUFFER read from curbuf instead of a file (converting after reading
208 * stdin)
209 * READ_DUMMY read into a dummy buffer (to check if file contents changed)
Bram Moolenaar59f931e2010-07-24 20:27:03 +0200210 * READ_KEEP_UNDO don't clear undo info or read it from a file
Bram Moolenaarf71d7b92016-08-09 22:14:05 +0200211 * READ_FIFO read from fifo/socket instead of a file
Bram Moolenaar071d4272004-06-13 20:20:40 +0000212 *
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100213 * return FAIL for failure, NOTDONE for directory (failure), or OK
Bram Moolenaar071d4272004-06-13 20:20:40 +0000214 */
215 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +0100216readfile(
217 char_u *fname,
218 char_u *sfname,
219 linenr_T from,
220 linenr_T lines_to_skip,
221 linenr_T lines_to_read,
222 exarg_T *eap, /* can be NULL! */
223 int flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000224{
225 int fd = 0;
226 int newfile = (flags & READ_NEW);
227 int check_readonly;
228 int filtering = (flags & READ_FILTER);
229 int read_stdin = (flags & READ_STDIN);
230 int read_buffer = (flags & READ_BUFFER);
Bram Moolenaarf71d7b92016-08-09 22:14:05 +0200231 int read_fifo = (flags & READ_FIFO);
Bram Moolenaar690ffc02008-01-04 15:31:21 +0000232 int set_options = newfile || read_buffer
233 || (eap != NULL && eap->read_edit);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000234 linenr_T read_buf_lnum = 1; /* next line to read from curbuf */
235 colnr_T read_buf_col = 0; /* next char to read from this line */
236 char_u c;
237 linenr_T lnum = from;
238 char_u *ptr = NULL; /* pointer into read buffer */
239 char_u *buffer = NULL; /* read buffer */
240 char_u *new_buffer = NULL; /* init to shut up gcc */
241 char_u *line_start = NULL; /* init to shut up gcc */
242 int wasempty; /* buffer was empty before reading */
243 colnr_T len;
244 long size = 0;
245 char_u *p;
Bram Moolenaar8767f522016-07-01 17:17:39 +0200246 off_T filesize = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000247 int skip_read = FALSE;
248#ifdef FEAT_CRYPT
249 char_u *cryptkey = NULL;
Bram Moolenaarf50a2532010-05-21 15:36:08 +0200250 int did_ask_for_key = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000251#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +0200252#ifdef FEAT_PERSISTENT_UNDO
253 context_sha256_T sha_ctx;
254 int read_undo_file = FALSE;
255#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000256 int split = 0; /* number of split lines */
257#define UNKNOWN 0x0fffffff /* file size is unknown */
258 linenr_T linecnt;
259 int error = FALSE; /* errors encountered */
260 int ff_error = EOL_UNKNOWN; /* file format with errors */
261 long linerest = 0; /* remaining chars in line */
262#ifdef UNIX
263 int perm = 0;
264 int swap_mode = -1; /* protection bits for swap file */
265#else
266 int perm;
267#endif
268 int fileformat = 0; /* end-of-line format */
269 int keep_fileformat = FALSE;
Bram Moolenaar8767f522016-07-01 17:17:39 +0200270 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000271 int file_readonly;
272 linenr_T skip_count = 0;
273 linenr_T read_count = 0;
274 int msg_save = msg_scroll;
275 linenr_T read_no_eol_lnum = 0; /* non-zero lnum when last line of
276 * last read was missing the eol */
Bram Moolenaar7a2699e2017-01-23 21:31:09 +0100277 int try_mac;
278 int try_dos;
279 int try_unix;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000280 int file_rewind = FALSE;
281#ifdef FEAT_MBYTE
282 int can_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000283 linenr_T conv_error = 0; /* line nr with conversion error */
284 linenr_T illegal_byte = 0; /* line nr with illegal byte */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000285 int keep_dest_enc = FALSE; /* don't retry when char doesn't fit
286 in destination encoding */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000287 int bad_char_behavior = BAD_REPLACE;
288 /* BAD_KEEP, BAD_DROP or character to
289 * replace with */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000290 char_u *tmpname = NULL; /* name of 'charconvert' output file */
291 int fio_flags = 0;
292 char_u *fenc; /* fileencoding to use */
293 int fenc_alloced; /* fenc_next is in allocated memory */
294 char_u *fenc_next = NULL; /* next item in 'fencs' or NULL */
295 int advance_fenc = FALSE;
296 long real_size = 0;
297# ifdef USE_ICONV
298 iconv_t iconv_fd = (iconv_t)-1; /* descriptor for iconv() or -1 */
299# ifdef FEAT_EVAL
300 int did_iconv = FALSE; /* TRUE when iconv() failed and trying
301 'charconvert' next */
302# endif
303# endif
304 int converted = FALSE; /* TRUE if conversion done */
305 int notconverted = FALSE; /* TRUE if conversion wanted but it
306 wasn't possible */
307 char_u conv_rest[CONV_RESTLEN];
308 int conv_restlen = 0; /* nr of bytes in conv_rest[] */
309#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000310#ifdef FEAT_AUTOCMD
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200311 buf_T *old_curbuf;
312 char_u *old_b_ffname;
313 char_u *old_b_fname;
314 int using_b_ffname;
315 int using_b_fname;
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000316#endif
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200317
Bram Moolenaarc3691332016-04-20 12:49:49 +0200318#ifdef FEAT_AUTOCMD
319 au_did_filetype = FALSE; /* reset before triggering any autocommands */
320#endif
321
Bram Moolenaarcab35ad2011-02-15 17:39:22 +0100322 curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000323
324 /*
325 * If there is no file name yet, use the one for the read file.
326 * BF_NOTEDITED is set to reflect this.
327 * Don't do this for a read from a filter.
328 * Only do this when 'cpoptions' contains the 'f' flag.
329 */
330 if (curbuf->b_ffname == NULL
331 && !filtering
332 && fname != NULL
333 && vim_strchr(p_cpo, CPO_FNAMER) != NULL
334 && !(flags & READ_DUMMY))
335 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000336 if (set_rw_fname(fname, sfname) == FAIL)
337 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000338 }
339
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200340#ifdef FEAT_AUTOCMD
341 /* Remember the initial values of curbuf, curbuf->b_ffname and
342 * curbuf->b_fname to detect whether they are altered as a result of
343 * executing nasty autocommands. Also check if "fname" and "sfname"
344 * point to one of these values. */
345 old_curbuf = curbuf;
346 old_b_ffname = curbuf->b_ffname;
347 old_b_fname = curbuf->b_fname;
348 using_b_ffname = (fname == curbuf->b_ffname)
349 || (sfname == curbuf->b_ffname);
350 using_b_fname = (fname == curbuf->b_fname) || (sfname == curbuf->b_fname);
351#endif
352
Bram Moolenaardf177f62005-02-22 08:39:57 +0000353 /* After reading a file the cursor line changes but we don't want to
354 * display the line. */
355 ex_no_reprint = TRUE;
356
Bram Moolenaar55b7cf82006-09-09 12:52:42 +0000357 /* don't display the file info for another buffer now */
358 need_fileinfo = FALSE;
359
Bram Moolenaar071d4272004-06-13 20:20:40 +0000360 /*
361 * For Unix: Use the short file name whenever possible.
362 * Avoids problems with networks and when directory names are changed.
363 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
364 * another directory, which we don't detect.
365 */
366 if (sfname == NULL)
367 sfname = fname;
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200368#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000369 fname = sfname;
370#endif
371
372#ifdef FEAT_AUTOCMD
373 /*
374 * The BufReadCmd and FileReadCmd events intercept the reading process by
375 * executing the associated commands instead.
376 */
377 if (!filtering && !read_stdin && !read_buffer)
378 {
379 pos_T pos;
380
381 pos = curbuf->b_op_start;
382
383 /* Set '[ mark to the line above where the lines go (line 1 if zero). */
384 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
385 curbuf->b_op_start.col = 0;
386
387 if (newfile)
388 {
389 if (apply_autocmds_exarg(EVENT_BUFREADCMD, NULL, sfname,
390 FALSE, curbuf, eap))
391#ifdef FEAT_EVAL
392 return aborting() ? FAIL : OK;
393#else
394 return OK;
395#endif
396 }
397 else if (apply_autocmds_exarg(EVENT_FILEREADCMD, sfname, sfname,
398 FALSE, NULL, eap))
399#ifdef FEAT_EVAL
400 return aborting() ? FAIL : OK;
401#else
402 return OK;
403#endif
404
405 curbuf->b_op_start = pos;
406 }
407#endif
408
409 if ((shortmess(SHM_OVER) || curbuf->b_help) && p_verbose == 0)
410 msg_scroll = FALSE; /* overwrite previous file message */
411 else
412 msg_scroll = TRUE; /* don't overwrite previous file message */
413
414 /*
415 * If the name ends in a path separator, we can't open it. Check here,
416 * because reading the file may actually work, but then creating the swap
417 * file may destroy it! Reported on MS-DOS and Win 95.
418 * If the name is too long we might crash further on, quit here.
419 */
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000420 if (fname != NULL && *fname != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000421 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000422 p = fname + STRLEN(fname);
423 if (after_pathsep(fname, p) || STRLEN(fname) >= MAXPATHL)
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000424 {
425 filemess(curbuf, fname, (char_u *)_("Illegal file name"), 0);
426 msg_end();
427 msg_scroll = msg_save;
428 return FAIL;
429 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000430 }
431
Bram Moolenaarf71d7b92016-08-09 22:14:05 +0200432 if (!read_stdin && !read_buffer && !read_fifo)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000433 {
Bram Moolenaar4e4f5292013-08-30 17:07:01 +0200434#ifdef UNIX
435 /*
436 * On Unix it is possible to read a directory, so we have to
437 * check for it before the mch_open().
438 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000439 perm = mch_getperm(fname);
440 if (perm >= 0 && !S_ISREG(perm) /* not a regular file ... */
441# ifdef S_ISFIFO
442 && !S_ISFIFO(perm) /* ... or fifo */
443# endif
444# ifdef S_ISSOCK
445 && !S_ISSOCK(perm) /* ... or socket */
446# endif
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +0000447# ifdef OPEN_CHR_FILES
448 && !(S_ISCHR(perm) && is_dev_fd_file(fname))
449 /* ... or a character special file named /dev/fd/<n> */
450# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000451 )
452 {
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100453 int retval = FAIL;
454
Bram Moolenaar071d4272004-06-13 20:20:40 +0000455 if (S_ISDIR(perm))
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100456 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000457 filemess(curbuf, fname, (char_u *)_("is a directory"), 0);
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100458 retval = NOTDONE;
459 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000460 else
461 filemess(curbuf, fname, (char_u *)_("is not a file"), 0);
462 msg_end();
463 msg_scroll = msg_save;
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100464 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000465 }
Bram Moolenaar4e4f5292013-08-30 17:07:01 +0200466#endif
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100467#if defined(MSWIN)
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000468 /*
469 * MS-Windows allows opening a device, but we will probably get stuck
470 * trying to read it.
471 */
472 if (!p_odev && mch_nodetype(fname) == NODE_WRITABLE)
473 {
Bram Moolenaar5386a122007-06-28 20:02:32 +0000474 filemess(curbuf, fname, (char_u *)_("is a device (disabled with 'opendevice' option)"), 0);
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000475 msg_end();
476 msg_scroll = msg_save;
477 return FAIL;
478 }
Bram Moolenaar043545e2006-10-10 16:44:07 +0000479#endif
Bram Moolenaar4e4f5292013-08-30 17:07:01 +0200480 }
Bram Moolenaar043545e2006-10-10 16:44:07 +0000481
Bram Moolenaarad875fb2013-07-24 15:02:03 +0200482 /* Set default or forced 'fileformat' and 'binary'. */
483 set_file_options(set_options, eap);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000484
485 /*
486 * When opening a new file we take the readonly flag from the file.
487 * Default is r/w, can be set to r/o below.
488 * Don't reset it when in readonly mode
489 * Only set/reset b_p_ro when BF_CHECK_RO is set.
490 */
491 check_readonly = (newfile && (curbuf->b_flags & BF_CHECK_RO));
Bram Moolenaar4399ef42005-02-12 14:29:27 +0000492 if (check_readonly && !readonlymode)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000493 curbuf->b_p_ro = FALSE;
494
Bram Moolenaarf71d7b92016-08-09 22:14:05 +0200495 if (newfile && !read_stdin && !read_buffer && !read_fifo)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000496 {
Bram Moolenaare60acc12011-05-10 16:41:25 +0200497 /* Remember time of file. */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000498 if (mch_stat((char *)fname, &st) >= 0)
499 {
500 buf_store_time(curbuf, &st, fname);
501 curbuf->b_mtime_read = curbuf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000502#ifdef UNIX
503 /*
504 * Use the protection bits of the original file for the swap file.
505 * This makes it possible for others to read the name of the
506 * edited file from the swapfile, but only if they can read the
507 * edited file.
508 * Remove the "write" and "execute" bits for group and others
509 * (they must not write the swapfile).
510 * Add the "read" and "write" bits for the user, otherwise we may
511 * not be able to write to the file ourselves.
512 * Setting the bits is done below, after creating the swap file.
513 */
514 swap_mode = (st.st_mode & 0644) | 0600;
515#endif
516#ifdef FEAT_CW_EDITOR
517 /* Get the FSSpec on MacOS
518 * TODO: Update it properly when the buffer name changes
519 */
520 (void)GetFSSpecFromPath(curbuf->b_ffname, &curbuf->b_FSSpec);
521#endif
522#ifdef VMS
523 curbuf->b_fab_rfm = st.st_fab_rfm;
Bram Moolenaard4755bb2004-09-02 19:12:26 +0000524 curbuf->b_fab_rat = st.st_fab_rat;
525 curbuf->b_fab_mrs = st.st_fab_mrs;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000526#endif
527 }
528 else
529 {
530 curbuf->b_mtime = 0;
531 curbuf->b_mtime_read = 0;
532 curbuf->b_orig_size = 0;
533 curbuf->b_orig_mode = 0;
534 }
535
536 /* Reset the "new file" flag. It will be set again below when the
537 * file doesn't exist. */
538 curbuf->b_flags &= ~(BF_NEW | BF_NEW_W);
539 }
540
541/*
542 * for UNIX: check readonly with perm and mch_access()
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100543 * for Amiga: check readonly by trying to open the file for writing
Bram Moolenaar071d4272004-06-13 20:20:40 +0000544 */
545 file_readonly = FALSE;
546 if (read_stdin)
547 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100548#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000549 /* Force binary I/O on stdin to avoid CR-LF -> LF conversion. */
550 setmode(0, O_BINARY);
551#endif
552 }
553 else if (!read_buffer)
554 {
555#ifdef USE_MCH_ACCESS
556 if (
557# ifdef UNIX
558 !(perm & 0222) ||
559# endif
560 mch_access((char *)fname, W_OK))
561 file_readonly = TRUE;
562 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
563#else
564 if (!newfile
565 || readonlymode
566 || (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0)
567 {
568 file_readonly = TRUE;
569 /* try to open ro */
570 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
571 }
572#endif
573 }
574
575 if (fd < 0) /* cannot open at all */
576 {
577#ifndef UNIX
578 int isdir_f;
579#endif
580 msg_scroll = msg_save;
581#ifndef UNIX
582 /*
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100583 * On Amiga we can't open a directory, check here.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000584 */
585 isdir_f = (mch_isdir(fname));
586 perm = mch_getperm(fname); /* check if the file exists */
587 if (isdir_f)
588 {
589 filemess(curbuf, sfname, (char_u *)_("is a directory"), 0);
590 curbuf->b_p_ro = TRUE; /* must use "w!" now */
591 }
592 else
593#endif
594 if (newfile)
595 {
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200596 if (perm < 0
597#ifdef ENOENT
598 && errno == ENOENT
599#endif
600 )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000601 {
602 /*
603 * Set the 'new-file' flag, so that when the file has
604 * been created by someone else, a ":w" will complain.
605 */
606 curbuf->b_flags |= BF_NEW;
607
608 /* Create a swap file now, so that other Vims are warned
609 * that we are editing this file. Don't do this for a
610 * "nofile" or "nowrite" buffer type. */
611#ifdef FEAT_QUICKFIX
612 if (!bt_dontwrite(curbuf))
613#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000614 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000615 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000616#ifdef FEAT_AUTOCMD
617 /* SwapExists autocommand may mess things up */
618 if (curbuf != old_curbuf
619 || (using_b_ffname
620 && (old_b_ffname != curbuf->b_ffname))
621 || (using_b_fname
622 && (old_b_fname != curbuf->b_fname)))
623 {
624 EMSG(_(e_auchangedbuf));
625 return FAIL;
626 }
627#endif
628 }
Bram Moolenaar5b962cf2005-12-12 21:58:40 +0000629 if (dir_of_file_exists(fname))
630 filemess(curbuf, sfname, (char_u *)_("[New File]"), 0);
631 else
632 filemess(curbuf, sfname,
633 (char_u *)_("[New DIRECTORY]"), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000634#ifdef FEAT_VIMINFO
635 /* Even though this is a new file, it might have been
636 * edited before and deleted. Get the old marks. */
637 check_marks_read();
638#endif
639#ifdef FEAT_MBYTE
Bram Moolenaarad875fb2013-07-24 15:02:03 +0200640 /* Set forced 'fileencoding'. */
641 if (eap != NULL)
642 set_forced_fenc(eap);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000643#endif
644#ifdef FEAT_AUTOCMD
645 apply_autocmds_exarg(EVENT_BUFNEWFILE, sfname, sfname,
646 FALSE, curbuf, eap);
647#endif
648 /* remember the current fileformat */
649 save_file_ff(curbuf);
650
651#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
652 if (aborting()) /* autocmds may abort script processing */
653 return FAIL;
654#endif
655 return OK; /* a new file is not an error */
656 }
657 else
658 {
Bram Moolenaar202795b2005-10-11 20:29:39 +0000659 filemess(curbuf, sfname, (char_u *)(
660# ifdef EFBIG
661 (errno == EFBIG) ? _("[File too big]") :
662# endif
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200663# ifdef EOVERFLOW
664 (errno == EOVERFLOW) ? _("[File too big]") :
665# endif
Bram Moolenaar202795b2005-10-11 20:29:39 +0000666 _("[Permission Denied]")), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000667 curbuf->b_p_ro = TRUE; /* must use "w!" now */
668 }
669 }
670
671 return FAIL;
672 }
673
674 /*
675 * Only set the 'ro' flag for readonly files the first time they are
676 * loaded. Help files always get readonly mode
677 */
678 if ((check_readonly && file_readonly) || curbuf->b_help)
679 curbuf->b_p_ro = TRUE;
680
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000681 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000682 {
Bram Moolenaar690ffc02008-01-04 15:31:21 +0000683 /* Don't change 'eol' if reading from buffer as it will already be
684 * correctly set when reading stdin. */
685 if (!read_buffer)
686 {
687 curbuf->b_p_eol = TRUE;
688 curbuf->b_start_eol = TRUE;
689 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000690#ifdef FEAT_MBYTE
691 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000692 curbuf->b_start_bomb = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000693#endif
694 }
695
696 /* Create a swap file now, so that other Vims are warned that we are
697 * editing this file.
698 * Don't do this for a "nofile" or "nowrite" buffer type. */
699#ifdef FEAT_QUICKFIX
700 if (!bt_dontwrite(curbuf))
701#endif
702 {
703 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000704#ifdef FEAT_AUTOCMD
705 if (!read_stdin && (curbuf != old_curbuf
706 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
707 || (using_b_fname && (old_b_fname != curbuf->b_fname))))
708 {
709 EMSG(_(e_auchangedbuf));
710 if (!read_buffer)
711 close(fd);
712 return FAIL;
713 }
714#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000715#ifdef UNIX
716 /* Set swap file protection bits after creating it. */
Bram Moolenaarf061e0b2009-06-24 15:32:01 +0000717 if (swap_mode > 0 && curbuf->b_ml.ml_mfp != NULL
718 && curbuf->b_ml.ml_mfp->mf_fname != NULL)
Bram Moolenaar5a73e0c2017-11-04 21:35:01 +0100719 {
720 char_u *swap_fname = curbuf->b_ml.ml_mfp->mf_fname;
721
722 /*
723 * If the group-read bit is set but not the world-read bit, then
724 * the group must be equal to the group of the original file. If
725 * we can't make that happen then reset the group-read bit. This
726 * avoids making the swap file readable to more users when the
727 * primary group of the user is too permissive.
728 */
729 if ((swap_mode & 044) == 040)
730 {
731 stat_T swap_st;
732
733 if (mch_stat((char *)swap_fname, &swap_st) >= 0
734 && st.st_gid != swap_st.st_gid
735 && fchown(curbuf->b_ml.ml_mfp->mf_fd, -1, st.st_gid)
736 == -1)
737 swap_mode &= 0600;
738 }
739
740 (void)mch_setperm(swap_fname, (long)swap_mode);
741 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000742#endif
743 }
744
Bram Moolenaarb815dac2005-12-07 20:59:24 +0000745#if defined(HAS_SWAP_EXISTS_ACTION)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000746 /* If "Quit" selected at ATTENTION dialog, don't load the file */
747 if (swap_exists_action == SEA_QUIT)
748 {
749 if (!read_buffer && !read_stdin)
750 close(fd);
751 return FAIL;
752 }
753#endif
754
755 ++no_wait_return; /* don't wait for return yet */
756
757 /*
758 * Set '[ mark to the line above where the lines go (line 1 if zero).
759 */
760 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
761 curbuf->b_op_start.col = 0;
762
Bram Moolenaar7a2699e2017-01-23 21:31:09 +0100763 try_mac = (vim_strchr(p_ffs, 'm') != NULL);
764 try_dos = (vim_strchr(p_ffs, 'd') != NULL);
765 try_unix = (vim_strchr(p_ffs, 'x') != NULL);
766
Bram Moolenaar071d4272004-06-13 20:20:40 +0000767#ifdef FEAT_AUTOCMD
768 if (!read_buffer)
769 {
770 int m = msg_scroll;
771 int n = msg_scrolled;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000772
773 /*
774 * The file must be closed again, the autocommands may want to change
775 * the file before reading it.
776 */
777 if (!read_stdin)
778 close(fd); /* ignore errors */
779
780 /*
781 * The output from the autocommands should not overwrite anything and
782 * should not be overwritten: Set msg_scroll, restore its value if no
783 * output was done.
784 */
785 msg_scroll = TRUE;
786 if (filtering)
787 apply_autocmds_exarg(EVENT_FILTERREADPRE, NULL, sfname,
788 FALSE, curbuf, eap);
789 else if (read_stdin)
790 apply_autocmds_exarg(EVENT_STDINREADPRE, NULL, sfname,
791 FALSE, curbuf, eap);
792 else if (newfile)
793 apply_autocmds_exarg(EVENT_BUFREADPRE, NULL, sfname,
794 FALSE, curbuf, eap);
795 else
796 apply_autocmds_exarg(EVENT_FILEREADPRE, sfname, sfname,
797 FALSE, NULL, eap);
Bram Moolenaar7a2699e2017-01-23 21:31:09 +0100798 /* autocommands may have changed it */
799 try_mac = (vim_strchr(p_ffs, 'm') != NULL);
800 try_dos = (vim_strchr(p_ffs, 'd') != NULL);
801 try_unix = (vim_strchr(p_ffs, 'x') != NULL);
802
Bram Moolenaar071d4272004-06-13 20:20:40 +0000803 if (msg_scrolled == n)
804 msg_scroll = m;
805
806#ifdef FEAT_EVAL
807 if (aborting()) /* autocmds may abort script processing */
808 {
809 --no_wait_return;
810 msg_scroll = msg_save;
811 curbuf->b_p_ro = TRUE; /* must use "w!" now */
812 return FAIL;
813 }
814#endif
815 /*
816 * Don't allow the autocommands to change the current buffer.
817 * Try to re-open the file.
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000818 *
819 * Don't allow the autocommands to change the buffer name either
820 * (cd for example) if it invalidates fname or sfname.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000821 */
822 if (!read_stdin && (curbuf != old_curbuf
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000823 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
824 || (using_b_fname && (old_b_fname != curbuf->b_fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000825 || (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) < 0))
826 {
827 --no_wait_return;
828 msg_scroll = msg_save;
829 if (fd < 0)
830 EMSG(_("E200: *ReadPre autocommands made the file unreadable"));
831 else
832 EMSG(_("E201: *ReadPre autocommands must not change current buffer"));
833 curbuf->b_p_ro = TRUE; /* must use "w!" now */
834 return FAIL;
835 }
836 }
837#endif /* FEAT_AUTOCMD */
838
839 /* Autocommands may add lines to the file, need to check if it is empty */
840 wasempty = (curbuf->b_ml.ml_flags & ML_EMPTY);
841
842 if (!recoverymode && !filtering && !(flags & READ_DUMMY))
843 {
844 /*
845 * Show the user that we are busy reading the input. Sometimes this
846 * may take a while. When reading from stdin another program may
847 * still be running, don't move the cursor to the last line, unless
848 * always using the GUI.
849 */
850 if (read_stdin)
851 {
Bram Moolenaar234d1622017-11-18 14:55:23 +0100852 if (!is_not_a_term())
853 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000854#ifndef ALWAYS_USE_GUI
Bram Moolenaar234d1622017-11-18 14:55:23 +0100855 mch_msg(_("Vim: Reading from stdin...\n"));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000856#endif
857#ifdef FEAT_GUI
Bram Moolenaar234d1622017-11-18 14:55:23 +0100858 /* Also write a message in the GUI window, if there is one. */
859 if (gui.in_use && !gui.dying && !gui.starting)
860 {
861 p = (char_u *)_("Reading from stdin...");
862 gui_write(p, (int)STRLEN(p));
863 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000864#endif
Bram Moolenaar234d1622017-11-18 14:55:23 +0100865 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000866 }
867 else if (!read_buffer)
868 filemess(curbuf, sfname, (char_u *)"", 0);
869 }
870
871 msg_scroll = FALSE; /* overwrite the file message */
872
873 /*
874 * Set linecnt now, before the "retry" caused by a wrong guess for
875 * fileformat, and after the autocommands, which may change them.
876 */
877 linecnt = curbuf->b_ml.ml_line_count;
878
879#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000880 /* "++bad=" argument. */
881 if (eap != NULL && eap->bad_char != 0)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000882 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000883 bad_char_behavior = eap->bad_char;
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000884 if (set_options)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000885 curbuf->b_bad_char = eap->bad_char;
886 }
887 else
888 curbuf->b_bad_char = 0;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000889
Bram Moolenaar071d4272004-06-13 20:20:40 +0000890 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000891 * Decide which 'encoding' to use or use first.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000892 */
893 if (eap != NULL && eap->force_enc != 0)
894 {
895 fenc = enc_canonize(eap->cmd + eap->force_enc);
896 fenc_alloced = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000897 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000898 }
899 else if (curbuf->b_p_bin)
900 {
901 fenc = (char_u *)""; /* binary: don't convert */
902 fenc_alloced = FALSE;
903 }
904 else if (curbuf->b_help)
905 {
906 char_u firstline[80];
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000907 int fc;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000908
909 /* Help files are either utf-8 or latin1. Try utf-8 first, if this
910 * fails it must be latin1.
911 * Always do this when 'encoding' is "utf-8". Otherwise only do
912 * this when needed to avoid [converted] remarks all the time.
913 * It is needed when the first line contains non-ASCII characters.
914 * That is only in *.??x files. */
915 fenc = (char_u *)"latin1";
916 c = enc_utf8;
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000917 if (!c && !read_stdin)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000918 {
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000919 fc = fname[STRLEN(fname) - 1];
920 if (TOLOWER_ASC(fc) == 'x')
921 {
922 /* Read the first line (and a bit more). Immediately rewind to
923 * the start of the file. If the read() fails "len" is -1. */
Bram Moolenaar540fc6f2010-12-17 16:27:16 +0100924 len = read_eintr(fd, firstline, 80);
Bram Moolenaar8767f522016-07-01 17:17:39 +0200925 vim_lseek(fd, (off_T)0L, SEEK_SET);
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000926 for (p = firstline; p < firstline + len; ++p)
927 if (*p >= 0x80)
928 {
929 c = TRUE;
930 break;
931 }
932 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000933 }
934
935 if (c)
936 {
937 fenc_next = fenc;
938 fenc = (char_u *)"utf-8";
939
940 /* When the file is utf-8 but a character doesn't fit in
941 * 'encoding' don't retry. In help text editing utf-8 bytes
942 * doesn't make sense. */
Bram Moolenaarf193fff2006-04-27 00:02:13 +0000943 if (!enc_utf8)
944 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000945 }
946 fenc_alloced = FALSE;
947 }
948 else if (*p_fencs == NUL)
949 {
950 fenc = curbuf->b_p_fenc; /* use format from buffer */
951 fenc_alloced = FALSE;
952 }
953 else
954 {
955 fenc_next = p_fencs; /* try items in 'fileencodings' */
956 fenc = next_fenc(&fenc_next);
957 fenc_alloced = TRUE;
958 }
959#endif
960
961 /*
962 * Jump back here to retry reading the file in different ways.
963 * Reasons to retry:
964 * - encoding conversion failed: try another one from "fenc_next"
965 * - BOM detected and fenc was set, need to setup conversion
966 * - "fileformat" check failed: try another
967 *
968 * Variables set for special retry actions:
969 * "file_rewind" Rewind the file to start reading it again.
970 * "advance_fenc" Advance "fenc" using "fenc_next".
971 * "skip_read" Re-use already read bytes (BOM detected).
972 * "did_iconv" iconv() conversion failed, try 'charconvert'.
973 * "keep_fileformat" Don't reset "fileformat".
974 *
975 * Other status indicators:
976 * "tmpname" When != NULL did conversion with 'charconvert'.
977 * Output file has to be deleted afterwards.
978 * "iconv_fd" When != -1 did conversion with iconv().
979 */
980retry:
981
982 if (file_rewind)
983 {
984 if (read_buffer)
985 {
986 read_buf_lnum = 1;
987 read_buf_col = 0;
988 }
Bram Moolenaar8767f522016-07-01 17:17:39 +0200989 else if (read_stdin || vim_lseek(fd, (off_T)0L, SEEK_SET) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000990 {
991 /* Can't rewind the file, give up. */
992 error = TRUE;
993 goto failed;
994 }
995 /* Delete the previously read lines. */
996 while (lnum > from)
997 ml_delete(lnum--, FALSE);
998 file_rewind = FALSE;
999#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +00001000 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001001 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001002 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001003 curbuf->b_start_bomb = FALSE;
1004 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001005 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001006#endif
1007 }
1008
1009 /*
1010 * When retrying with another "fenc" and the first time "fileformat"
1011 * will be reset.
1012 */
1013 if (keep_fileformat)
1014 keep_fileformat = FALSE;
1015 else
1016 {
1017 if (eap != NULL && eap->force_ff != 0)
Bram Moolenaar1c860362008-11-12 15:05:21 +00001018 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001019 fileformat = get_fileformat_force(curbuf, eap);
Bram Moolenaar1c860362008-11-12 15:05:21 +00001020 try_unix = try_dos = try_mac = FALSE;
1021 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001022 else if (curbuf->b_p_bin)
1023 fileformat = EOL_UNIX; /* binary: use Unix format */
1024 else if (*p_ffs == NUL)
1025 fileformat = get_fileformat(curbuf);/* use format from buffer */
1026 else
1027 fileformat = EOL_UNKNOWN; /* detect from file */
1028 }
1029
1030#ifdef FEAT_MBYTE
1031# ifdef USE_ICONV
1032 if (iconv_fd != (iconv_t)-1)
1033 {
1034 /* aborted conversion with iconv(), close the descriptor */
1035 iconv_close(iconv_fd);
1036 iconv_fd = (iconv_t)-1;
1037 }
1038# endif
1039
1040 if (advance_fenc)
1041 {
1042 /*
1043 * Try the next entry in 'fileencodings'.
1044 */
1045 advance_fenc = FALSE;
1046
1047 if (eap != NULL && eap->force_enc != 0)
1048 {
1049 /* Conversion given with "++cc=" wasn't possible, read
1050 * without conversion. */
1051 notconverted = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001052 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001053 if (fenc_alloced)
1054 vim_free(fenc);
1055 fenc = (char_u *)"";
1056 fenc_alloced = FALSE;
1057 }
1058 else
1059 {
1060 if (fenc_alloced)
1061 vim_free(fenc);
1062 if (fenc_next != NULL)
1063 {
1064 fenc = next_fenc(&fenc_next);
1065 fenc_alloced = (fenc_next != NULL);
1066 }
1067 else
1068 {
1069 fenc = (char_u *)"";
1070 fenc_alloced = FALSE;
1071 }
1072 }
1073 if (tmpname != NULL)
1074 {
1075 mch_remove(tmpname); /* delete converted file */
1076 vim_free(tmpname);
1077 tmpname = NULL;
1078 }
1079 }
1080
1081 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001082 * Conversion may be required when the encoding of the file is different
1083 * from 'encoding' or 'encoding' is UTF-16, UCS-2 or UCS-4.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001084 */
1085 fio_flags = 0;
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001086 converted = need_conversion(fenc);
1087 if (converted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001088 {
1089
1090 /* "ucs-bom" means we need to check the first bytes of the file
1091 * for a BOM. */
1092 if (STRCMP(fenc, ENC_UCSBOM) == 0)
1093 fio_flags = FIO_UCSBOM;
1094
1095 /*
1096 * Check if UCS-2/4 or Latin1 to UTF-8 conversion needs to be
1097 * done. This is handled below after read(). Prepare the
1098 * fio_flags to avoid having to parse the string each time.
1099 * Also check for Unicode to Latin1 conversion, because iconv()
1100 * appears not to handle this correctly. This works just like
1101 * conversion to UTF-8 except how the resulting character is put in
1102 * the buffer.
1103 */
1104 else if (enc_utf8 || STRCMP(p_enc, "latin1") == 0)
1105 fio_flags = get_fio_flags(fenc);
1106
1107# ifdef WIN3264
1108 /*
1109 * Conversion from an MS-Windows codepage to UTF-8 or another codepage
1110 * is handled with MultiByteToWideChar().
1111 */
1112 if (fio_flags == 0)
1113 fio_flags = get_win_fio_flags(fenc);
1114# endif
1115
Bram Moolenaard0573012017-10-28 21:11:06 +02001116# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001117 /* Conversion from Apple MacRoman to latin1 or UTF-8 */
1118 if (fio_flags == 0)
1119 fio_flags = get_mac_fio_flags(fenc);
1120# endif
1121
1122# ifdef USE_ICONV
1123 /*
1124 * Try using iconv() if we can't convert internally.
1125 */
1126 if (fio_flags == 0
1127# ifdef FEAT_EVAL
1128 && !did_iconv
1129# endif
1130 )
1131 iconv_fd = (iconv_t)my_iconv_open(
1132 enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc);
1133# endif
1134
1135# ifdef FEAT_EVAL
1136 /*
1137 * Use the 'charconvert' expression when conversion is required
1138 * and we can't do it internally or with iconv().
1139 */
1140 if (fio_flags == 0 && !read_stdin && !read_buffer && *p_ccv != NUL
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02001141 && !read_fifo
Bram Moolenaar071d4272004-06-13 20:20:40 +00001142# ifdef USE_ICONV
1143 && iconv_fd == (iconv_t)-1
1144# endif
1145 )
1146 {
1147# ifdef USE_ICONV
1148 did_iconv = FALSE;
1149# endif
1150 /* Skip conversion when it's already done (retry for wrong
1151 * "fileformat"). */
1152 if (tmpname == NULL)
1153 {
1154 tmpname = readfile_charconvert(fname, fenc, &fd);
1155 if (tmpname == NULL)
1156 {
1157 /* Conversion failed. Try another one. */
1158 advance_fenc = TRUE;
1159 if (fd < 0)
1160 {
1161 /* Re-opening the original file failed! */
1162 EMSG(_("E202: Conversion made file unreadable!"));
1163 error = TRUE;
1164 goto failed;
1165 }
1166 goto retry;
1167 }
1168 }
1169 }
1170 else
1171# endif
1172 {
1173 if (fio_flags == 0
1174# ifdef USE_ICONV
1175 && iconv_fd == (iconv_t)-1
1176# endif
1177 )
1178 {
1179 /* Conversion wanted but we can't.
1180 * Try the next conversion in 'fileencodings' */
1181 advance_fenc = TRUE;
1182 goto retry;
1183 }
1184 }
1185 }
1186
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001187 /* Set "can_retry" when it's possible to rewind the file and try with
Bram Moolenaar071d4272004-06-13 20:20:40 +00001188 * another "fenc" value. It's FALSE when no other "fenc" to try, reading
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001189 * stdin or fixed at a specific encoding. */
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02001190 can_retry = (*fenc != NUL && !read_stdin && !read_fifo && !keep_dest_enc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001191#endif
1192
1193 if (!skip_read)
1194 {
1195 linerest = 0;
1196 filesize = 0;
1197 skip_count = lines_to_skip;
1198 read_count = lines_to_read;
1199#ifdef FEAT_MBYTE
1200 conv_restlen = 0;
1201#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001202#ifdef FEAT_PERSISTENT_UNDO
Bram Moolenaar59f931e2010-07-24 20:27:03 +02001203 read_undo_file = (newfile && (flags & READ_KEEP_UNDO) == 0
1204 && curbuf->b_ffname != NULL
1205 && curbuf->b_p_udf
1206 && !filtering
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02001207 && !read_fifo
Bram Moolenaar59f931e2010-07-24 20:27:03 +02001208 && !read_stdin
1209 && !read_buffer);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001210 if (read_undo_file)
1211 sha256_start(&sha_ctx);
1212#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001213#ifdef FEAT_CRYPT
1214 if (curbuf->b_cryptstate != NULL)
1215 {
1216 /* Need to free the state, but keep the key, don't want to ask for
1217 * it again. */
1218 crypt_free_state(curbuf->b_cryptstate);
1219 curbuf->b_cryptstate = NULL;
1220 }
1221#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001222 }
1223
1224 while (!error && !got_int)
1225 {
1226 /*
1227 * We allocate as much space for the file as we can get, plus
1228 * space for the old line plus room for one terminating NUL.
1229 * The amount is limited by the fact that read() only can read
1230 * upto max_unsigned characters (and other things).
1231 */
Bram Moolenaara2aa31a2014-02-23 22:52:40 +01001232#if VIM_SIZEOF_INT <= 2
Bram Moolenaar071d4272004-06-13 20:20:40 +00001233 if (linerest >= 0x7ff0)
1234 {
1235 ++split;
1236 *ptr = NL; /* split line by inserting a NL */
1237 size = 1;
1238 }
1239 else
1240#endif
1241 {
1242 if (!skip_read)
1243 {
Bram Moolenaara2aa31a2014-02-23 22:52:40 +01001244#if VIM_SIZEOF_INT > 2
Bram Moolenaar311d9822007-02-27 15:48:28 +00001245# if defined(SSIZE_MAX) && (SSIZE_MAX < 0x10000L)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001246 size = SSIZE_MAX; /* use max I/O size, 52K */
1247# else
1248 size = 0x10000L; /* use buffer >= 64K */
1249# endif
1250#else
1251 size = 0x7ff0L - linerest; /* limit buffer to 32K */
1252#endif
1253
Bram Moolenaarc1e37902006-04-18 21:55:01 +00001254 for ( ; size >= 10; size = (long)((long_u)size >> 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001255 {
1256 if ((new_buffer = lalloc((long_u)(size + linerest + 1),
1257 FALSE)) != NULL)
1258 break;
1259 }
1260 if (new_buffer == NULL)
1261 {
1262 do_outofmem_msg((long_u)(size * 2 + linerest + 1));
1263 error = TRUE;
1264 break;
1265 }
1266 if (linerest) /* copy characters from the previous buffer */
1267 mch_memmove(new_buffer, ptr - linerest, (size_t)linerest);
1268 vim_free(buffer);
1269 buffer = new_buffer;
1270 ptr = buffer + linerest;
1271 line_start = buffer;
1272
1273#ifdef FEAT_MBYTE
1274 /* May need room to translate into.
1275 * For iconv() we don't really know the required space, use a
1276 * factor ICONV_MULT.
1277 * latin1 to utf-8: 1 byte becomes up to 2 bytes
1278 * utf-16 to utf-8: 2 bytes become up to 3 bytes, 4 bytes
1279 * become up to 4 bytes, size must be multiple of 2
1280 * ucs-2 to utf-8: 2 bytes become up to 3 bytes, size must be
1281 * multiple of 2
1282 * ucs-4 to utf-8: 4 bytes become up to 6 bytes, size must be
1283 * multiple of 4 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001284 real_size = (int)size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001285# ifdef USE_ICONV
1286 if (iconv_fd != (iconv_t)-1)
1287 size = size / ICONV_MULT;
1288 else
1289# endif
1290 if (fio_flags & FIO_LATIN1)
1291 size = size / 2;
1292 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1293 size = (size * 2 / 3) & ~1;
1294 else if (fio_flags & FIO_UCS4)
1295 size = (size * 2 / 3) & ~3;
1296 else if (fio_flags == FIO_UCSBOM)
1297 size = size / ICONV_MULT; /* worst case */
1298# ifdef WIN3264
1299 else if (fio_flags & FIO_CODEPAGE)
1300 size = size / ICONV_MULT; /* also worst case */
1301# endif
Bram Moolenaard0573012017-10-28 21:11:06 +02001302# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001303 else if (fio_flags & FIO_MACROMAN)
1304 size = size / ICONV_MULT; /* also worst case */
1305# endif
1306#endif
1307
1308#ifdef FEAT_MBYTE
1309 if (conv_restlen > 0)
1310 {
1311 /* Insert unconverted bytes from previous line. */
1312 mch_memmove(ptr, conv_rest, conv_restlen);
1313 ptr += conv_restlen;
1314 size -= conv_restlen;
1315 }
1316#endif
1317
1318 if (read_buffer)
1319 {
1320 /*
1321 * Read bytes from curbuf. Used for converting text read
1322 * from stdin.
1323 */
1324 if (read_buf_lnum > from)
1325 size = 0;
1326 else
1327 {
1328 int n, ni;
1329 long tlen;
1330
1331 tlen = 0;
1332 for (;;)
1333 {
1334 p = ml_get(read_buf_lnum) + read_buf_col;
1335 n = (int)STRLEN(p);
1336 if ((int)tlen + n + 1 > size)
1337 {
1338 /* Filled up to "size", append partial line.
1339 * Change NL to NUL to reverse the effect done
1340 * below. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001341 n = (int)(size - tlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001342 for (ni = 0; ni < n; ++ni)
1343 {
1344 if (p[ni] == NL)
1345 ptr[tlen++] = NUL;
1346 else
1347 ptr[tlen++] = p[ni];
1348 }
1349 read_buf_col += n;
1350 break;
1351 }
1352 else
1353 {
1354 /* Append whole line and new-line. Change NL
1355 * to NUL to reverse the effect done below. */
1356 for (ni = 0; ni < n; ++ni)
1357 {
1358 if (p[ni] == NL)
1359 ptr[tlen++] = NUL;
1360 else
1361 ptr[tlen++] = p[ni];
1362 }
1363 ptr[tlen++] = NL;
1364 read_buf_col = 0;
1365 if (++read_buf_lnum > from)
1366 {
1367 /* When the last line didn't have an
1368 * end-of-line don't add it now either. */
1369 if (!curbuf->b_p_eol)
1370 --tlen;
1371 size = tlen;
1372 break;
1373 }
1374 }
1375 }
1376 }
1377 }
1378 else
1379 {
1380 /*
1381 * Read bytes from the file.
1382 */
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01001383 size = read_eintr(fd, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001384 }
1385
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001386#ifdef FEAT_CRYPT
1387 /*
1388 * At start of file: Check for magic number of encryption.
1389 */
1390 if (filesize == 0 && size > 0)
1391 cryptkey = check_for_cryptkey(cryptkey, ptr, &size,
1392 &filesize, newfile, sfname,
1393 &did_ask_for_key);
1394 /*
1395 * Decrypt the read bytes. This is done before checking for
1396 * EOF because the crypt layer may be buffering.
1397 */
Bram Moolenaar829aa642017-08-23 22:32:35 +02001398 if (cryptkey != NULL && curbuf->b_cryptstate != NULL
1399 && size > 0)
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001400 {
1401 if (crypt_works_inplace(curbuf->b_cryptstate))
1402 {
1403 crypt_decode_inplace(curbuf->b_cryptstate, ptr, size);
1404 }
1405 else
1406 {
1407 char_u *newptr = NULL;
1408 int decrypted_size;
1409
1410 decrypted_size = crypt_decode_alloc(
1411 curbuf->b_cryptstate, ptr, size, &newptr);
1412
1413 /* If the crypt layer is buffering, not producing
1414 * anything yet, need to read more. */
1415 if (size > 0 && decrypted_size == 0)
1416 continue;
1417
1418 if (linerest == 0)
1419 {
1420 /* Simple case: reuse returned buffer (may be
1421 * NULL, checked later). */
1422 new_buffer = newptr;
1423 }
1424 else
1425 {
1426 long_u new_size;
1427
1428 /* Need new buffer to add bytes carried over. */
1429 new_size = (long_u)(decrypted_size + linerest + 1);
1430 new_buffer = lalloc(new_size, FALSE);
1431 if (new_buffer == NULL)
1432 {
1433 do_outofmem_msg(new_size);
1434 error = TRUE;
1435 break;
1436 }
1437
1438 mch_memmove(new_buffer, buffer, linerest);
1439 if (newptr != NULL)
1440 mch_memmove(new_buffer + linerest, newptr,
1441 decrypted_size);
1442 }
1443
1444 if (new_buffer != NULL)
1445 {
1446 vim_free(buffer);
1447 buffer = new_buffer;
1448 new_buffer = NULL;
1449 line_start = buffer;
1450 ptr = buffer + linerest;
1451 }
1452 size = decrypted_size;
1453 }
1454 }
1455#endif
1456
Bram Moolenaar071d4272004-06-13 20:20:40 +00001457 if (size <= 0)
1458 {
1459 if (size < 0) /* read error */
1460 error = TRUE;
1461#ifdef FEAT_MBYTE
1462 else if (conv_restlen > 0)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001463 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001464 /*
1465 * Reached end-of-file but some trailing bytes could
1466 * not be converted. Truncated file?
1467 */
1468
1469 /* When we did a conversion report an error. */
1470 if (fio_flags != 0
1471# ifdef USE_ICONV
1472 || iconv_fd != (iconv_t)-1
1473# endif
1474 )
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001475 {
Bram Moolenaare8d95302013-04-24 16:34:02 +02001476 if (can_retry)
1477 goto rewind_retry;
Bram Moolenaarf453d352008-06-04 17:37:34 +00001478 if (conv_error == 0)
1479 conv_error = curbuf->b_ml.ml_line_count
1480 - linecnt + 1;
1481 }
1482 /* Remember the first linenr with an illegal byte */
1483 else if (illegal_byte == 0)
1484 illegal_byte = curbuf->b_ml.ml_line_count
1485 - linecnt + 1;
1486 if (bad_char_behavior == BAD_DROP)
1487 {
1488 *(ptr - conv_restlen) = NUL;
1489 conv_restlen = 0;
1490 }
1491 else
1492 {
1493 /* Replace the trailing bytes with the replacement
1494 * character if we were converting; if we weren't,
1495 * leave the UTF8 checking code to do it, as it
1496 * works slightly differently. */
1497 if (bad_char_behavior != BAD_KEEP && (fio_flags != 0
1498# ifdef USE_ICONV
1499 || iconv_fd != (iconv_t)-1
1500# endif
1501 ))
1502 {
1503 while (conv_restlen > 0)
1504 {
1505 *(--ptr) = bad_char_behavior;
1506 --conv_restlen;
1507 }
1508 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001509 fio_flags = 0; /* don't convert this */
Bram Moolenaarb21e5842006-04-16 18:30:08 +00001510# ifdef USE_ICONV
1511 if (iconv_fd != (iconv_t)-1)
1512 {
1513 iconv_close(iconv_fd);
1514 iconv_fd = (iconv_t)-1;
1515 }
1516# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001517 }
1518 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001519#endif
1520 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001521 }
1522 skip_read = FALSE;
1523
1524#ifdef FEAT_MBYTE
1525 /*
1526 * At start of file (or after crypt magic number): Check for BOM.
1527 * Also check for a BOM for other Unicode encodings, but not after
1528 * converting with 'charconvert' or when a BOM has already been
1529 * found.
1530 */
1531 if ((filesize == 0
1532# ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001533 || (cryptkey != NULL
1534 && filesize == crypt_get_header_len(
1535 crypt_get_method_nr(curbuf)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001536# endif
1537 )
1538 && (fio_flags == FIO_UCSBOM
1539 || (!curbuf->b_p_bomb
1540 && tmpname == NULL
1541 && (*fenc == 'u' || (*fenc == NUL && enc_utf8)))))
1542 {
1543 char_u *ccname;
1544 int blen;
1545
1546 /* no BOM detection in a short file or in binary mode */
1547 if (size < 2 || curbuf->b_p_bin)
1548 ccname = NULL;
1549 else
1550 ccname = check_for_bom(ptr, size, &blen,
1551 fio_flags == FIO_UCSBOM ? FIO_ALL : get_fio_flags(fenc));
1552 if (ccname != NULL)
1553 {
1554 /* Remove BOM from the text */
1555 filesize += blen;
1556 size -= blen;
1557 mch_memmove(ptr, ptr + blen, (size_t)size);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00001558 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001559 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001560 curbuf->b_p_bomb = TRUE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001561 curbuf->b_start_bomb = TRUE;
1562 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001563 }
1564
1565 if (fio_flags == FIO_UCSBOM)
1566 {
1567 if (ccname == NULL)
1568 {
1569 /* No BOM detected: retry with next encoding. */
1570 advance_fenc = TRUE;
1571 }
1572 else
1573 {
1574 /* BOM detected: set "fenc" and jump back */
1575 if (fenc_alloced)
1576 vim_free(fenc);
1577 fenc = ccname;
1578 fenc_alloced = FALSE;
1579 }
1580 /* retry reading without getting new bytes or rewinding */
1581 skip_read = TRUE;
1582 goto retry;
1583 }
1584 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001585
1586 /* Include not converted bytes. */
1587 ptr -= conv_restlen;
1588 size += conv_restlen;
1589 conv_restlen = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001590#endif
1591 /*
1592 * Break here for a read error or end-of-file.
1593 */
1594 if (size <= 0)
1595 break;
1596
1597#ifdef FEAT_MBYTE
1598
Bram Moolenaar071d4272004-06-13 20:20:40 +00001599# ifdef USE_ICONV
1600 if (iconv_fd != (iconv_t)-1)
1601 {
1602 /*
1603 * Attempt conversion of the read bytes to 'encoding' using
1604 * iconv().
1605 */
1606 const char *fromp;
1607 char *top;
1608 size_t from_size;
1609 size_t to_size;
1610
1611 fromp = (char *)ptr;
1612 from_size = size;
1613 ptr += size;
1614 top = (char *)ptr;
1615 to_size = real_size - size;
1616
1617 /*
1618 * If there is conversion error or not enough room try using
Bram Moolenaar19a09a12005-03-04 23:39:37 +00001619 * another conversion. Except for when there is no
1620 * alternative (help files).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001621 */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001622 while ((iconv(iconv_fd, (void *)&fromp, &from_size,
1623 &top, &to_size)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001624 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
1625 || from_size > CONV_RESTLEN)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001626 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001627 if (can_retry)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001628 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001629 if (conv_error == 0)
1630 conv_error = readfile_linenr(linecnt,
1631 ptr, (char_u *)top);
Bram Moolenaar42eeac32005-06-29 22:40:58 +00001632
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001633 /* Deal with a bad byte and continue with the next. */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001634 ++fromp;
1635 --from_size;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001636 if (bad_char_behavior == BAD_KEEP)
1637 {
1638 *top++ = *(fromp - 1);
1639 --to_size;
1640 }
1641 else if (bad_char_behavior != BAD_DROP)
1642 {
1643 *top++ = bad_char_behavior;
1644 --to_size;
1645 }
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001646 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001647
1648 if (from_size > 0)
1649 {
1650 /* Some remaining characters, keep them for the next
1651 * round. */
1652 mch_memmove(conv_rest, (char_u *)fromp, from_size);
1653 conv_restlen = (int)from_size;
1654 }
1655
1656 /* move the linerest to before the converted characters */
1657 line_start = ptr - linerest;
1658 mch_memmove(line_start, buffer, (size_t)linerest);
1659 size = (long)((char_u *)top - ptr);
1660 }
1661# endif
1662
1663# ifdef WIN3264
1664 if (fio_flags & FIO_CODEPAGE)
1665 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001666 char_u *src, *dst;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001667 WCHAR ucs2buf[3];
1668 int ucs2len;
1669 int codepage = FIO_GET_CP(fio_flags);
1670 int bytelen;
1671 int found_bad;
1672 char replstr[2];
1673
Bram Moolenaar071d4272004-06-13 20:20:40 +00001674 /*
1675 * Conversion from an MS-Windows codepage or UTF-8 to UTF-8 or
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001676 * a codepage, using standard MS-Windows functions. This
1677 * requires two steps:
1678 * 1. convert from 'fileencoding' to ucs-2
1679 * 2. convert from ucs-2 to 'encoding'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001680 *
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001681 * Because there may be illegal bytes AND an incomplete byte
1682 * sequence at the end, we may have to do the conversion one
1683 * character at a time to get it right.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001684 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001685
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001686 /* Replacement string for WideCharToMultiByte(). */
1687 if (bad_char_behavior > 0)
1688 replstr[0] = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001689 else
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001690 replstr[0] = '?';
1691 replstr[1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001692
1693 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001694 * Move the bytes to the end of the buffer, so that we have
1695 * room to put the result at the start.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001696 */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001697 src = ptr + real_size - size;
1698 mch_memmove(src, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001699
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001700 /*
1701 * Do the conversion.
1702 */
1703 dst = ptr;
1704 size = size;
1705 while (size > 0)
1706 {
1707 found_bad = FALSE;
1708
1709# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
1710 if (codepage == CP_UTF8)
1711 {
1712 /* Handle CP_UTF8 input ourselves to be able to handle
1713 * trailing bytes properly.
1714 * Get one UTF-8 character from src. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001715 bytelen = (int)utf_ptr2len_len(src, size);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001716 if (bytelen > size)
1717 {
1718 /* Only got some bytes of a character. Normally
1719 * it's put in "conv_rest", but if it's too long
1720 * deal with it as if they were illegal bytes. */
1721 if (bytelen <= CONV_RESTLEN)
1722 break;
1723
1724 /* weird overlong byte sequence */
1725 bytelen = size;
1726 found_bad = TRUE;
1727 }
1728 else
1729 {
Bram Moolenaarc01140a2006-03-24 22:21:52 +00001730 int u8c = utf_ptr2char(src);
1731
Bram Moolenaar86e01082005-12-29 22:45:34 +00001732 if (u8c > 0xffff || (*src >= 0x80 && bytelen == 1))
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001733 found_bad = TRUE;
1734 ucs2buf[0] = u8c;
1735 ucs2len = 1;
1736 }
1737 }
1738 else
1739# endif
1740 {
1741 /* We don't know how long the byte sequence is, try
1742 * from one to three bytes. */
1743 for (bytelen = 1; bytelen <= size && bytelen <= 3;
1744 ++bytelen)
1745 {
1746 ucs2len = MultiByteToWideChar(codepage,
1747 MB_ERR_INVALID_CHARS,
1748 (LPCSTR)src, bytelen,
1749 ucs2buf, 3);
1750 if (ucs2len > 0)
1751 break;
1752 }
1753 if (ucs2len == 0)
1754 {
1755 /* If we have only one byte then it's probably an
1756 * incomplete byte sequence. Otherwise discard
1757 * one byte as a bad character. */
1758 if (size == 1)
1759 break;
1760 found_bad = TRUE;
1761 bytelen = 1;
1762 }
1763 }
1764
1765 if (!found_bad)
1766 {
1767 int i;
1768
1769 /* Convert "ucs2buf[ucs2len]" to 'enc' in "dst". */
1770 if (enc_utf8)
1771 {
1772 /* From UCS-2 to UTF-8. Cannot fail. */
1773 for (i = 0; i < ucs2len; ++i)
1774 dst += utf_char2bytes(ucs2buf[i], dst);
1775 }
1776 else
1777 {
1778 BOOL bad = FALSE;
1779 int dstlen;
1780
1781 /* From UCS-2 to "enc_codepage". If the
1782 * conversion uses the default character "?",
1783 * the data doesn't fit in this encoding. */
1784 dstlen = WideCharToMultiByte(enc_codepage, 0,
1785 (LPCWSTR)ucs2buf, ucs2len,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001786 (LPSTR)dst, (int)(src - dst),
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001787 replstr, &bad);
1788 if (bad)
1789 found_bad = TRUE;
1790 else
1791 dst += dstlen;
1792 }
1793 }
1794
1795 if (found_bad)
1796 {
1797 /* Deal with bytes we can't convert. */
1798 if (can_retry)
1799 goto rewind_retry;
1800 if (conv_error == 0)
1801 conv_error = readfile_linenr(linecnt, ptr, dst);
1802 if (bad_char_behavior != BAD_DROP)
1803 {
1804 if (bad_char_behavior == BAD_KEEP)
1805 {
1806 mch_memmove(dst, src, bytelen);
1807 dst += bytelen;
1808 }
1809 else
1810 *dst++ = bad_char_behavior;
1811 }
1812 }
1813
1814 src += bytelen;
1815 size -= bytelen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001816 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001817
1818 if (size > 0)
1819 {
1820 /* An incomplete byte sequence remaining. */
1821 mch_memmove(conv_rest, src, size);
1822 conv_restlen = size;
1823 }
1824
1825 /* The new size is equal to how much "dst" was advanced. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001826 size = (long)(dst - ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001827 }
1828 else
1829# endif
Bram Moolenaar56718732006-03-15 22:53:57 +00001830# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001831 if (fio_flags & FIO_MACROMAN)
1832 {
1833 /*
1834 * Conversion from Apple MacRoman char encoding to UTF-8 or
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001835 * latin1. This is in os_mac_conv.c.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001836 */
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001837 if (macroman2enc(ptr, &size, real_size) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001838 goto rewind_retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001839 }
1840 else
1841# endif
1842 if (fio_flags != 0)
1843 {
1844 int u8c;
1845 char_u *dest;
1846 char_u *tail = NULL;
1847
1848 /*
1849 * "enc_utf8" set: Convert Unicode or Latin1 to UTF-8.
1850 * "enc_utf8" not set: Convert Unicode to Latin1.
1851 * Go from end to start through the buffer, because the number
1852 * of bytes may increase.
1853 * "dest" points to after where the UTF-8 bytes go, "p" points
1854 * to after the next character to convert.
1855 */
1856 dest = ptr + real_size;
1857 if (fio_flags == FIO_LATIN1 || fio_flags == FIO_UTF8)
1858 {
1859 p = ptr + size;
1860 if (fio_flags == FIO_UTF8)
1861 {
1862 /* Check for a trailing incomplete UTF-8 sequence */
1863 tail = ptr + size - 1;
1864 while (tail > ptr && (*tail & 0xc0) == 0x80)
1865 --tail;
1866 if (tail + utf_byte2len(*tail) <= ptr + size)
1867 tail = NULL;
1868 else
1869 p = tail;
1870 }
1871 }
1872 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1873 {
1874 /* Check for a trailing byte */
1875 p = ptr + (size & ~1);
1876 if (size & 1)
1877 tail = p;
1878 if ((fio_flags & FIO_UTF16) && p > ptr)
1879 {
1880 /* Check for a trailing leading word */
1881 if (fio_flags & FIO_ENDIAN_L)
1882 {
1883 u8c = (*--p << 8);
1884 u8c += *--p;
1885 }
1886 else
1887 {
1888 u8c = *--p;
1889 u8c += (*--p << 8);
1890 }
1891 if (u8c >= 0xd800 && u8c <= 0xdbff)
1892 tail = p;
1893 else
1894 p += 2;
1895 }
1896 }
1897 else /* FIO_UCS4 */
1898 {
1899 /* Check for trailing 1, 2 or 3 bytes */
1900 p = ptr + (size & ~3);
1901 if (size & 3)
1902 tail = p;
1903 }
1904
1905 /* If there is a trailing incomplete sequence move it to
1906 * conv_rest[]. */
1907 if (tail != NULL)
1908 {
1909 conv_restlen = (int)((ptr + size) - tail);
1910 mch_memmove(conv_rest, (char_u *)tail, conv_restlen);
1911 size -= conv_restlen;
1912 }
1913
1914
1915 while (p > ptr)
1916 {
1917 if (fio_flags & FIO_LATIN1)
1918 u8c = *--p;
1919 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1920 {
1921 if (fio_flags & FIO_ENDIAN_L)
1922 {
1923 u8c = (*--p << 8);
1924 u8c += *--p;
1925 }
1926 else
1927 {
1928 u8c = *--p;
1929 u8c += (*--p << 8);
1930 }
1931 if ((fio_flags & FIO_UTF16)
1932 && u8c >= 0xdc00 && u8c <= 0xdfff)
1933 {
1934 int u16c;
1935
1936 if (p == ptr)
1937 {
1938 /* Missing leading word. */
1939 if (can_retry)
1940 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001941 if (conv_error == 0)
1942 conv_error = readfile_linenr(linecnt,
1943 ptr, p);
1944 if (bad_char_behavior == BAD_DROP)
1945 continue;
1946 if (bad_char_behavior != BAD_KEEP)
1947 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001948 }
1949
1950 /* found second word of double-word, get the first
1951 * word and compute the resulting character */
1952 if (fio_flags & FIO_ENDIAN_L)
1953 {
1954 u16c = (*--p << 8);
1955 u16c += *--p;
1956 }
1957 else
1958 {
1959 u16c = *--p;
1960 u16c += (*--p << 8);
1961 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001962 u8c = 0x10000 + ((u16c & 0x3ff) << 10)
1963 + (u8c & 0x3ff);
1964
Bram Moolenaar071d4272004-06-13 20:20:40 +00001965 /* Check if the word is indeed a leading word. */
1966 if (u16c < 0xd800 || u16c > 0xdbff)
1967 {
1968 if (can_retry)
1969 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001970 if (conv_error == 0)
1971 conv_error = readfile_linenr(linecnt,
1972 ptr, p);
1973 if (bad_char_behavior == BAD_DROP)
1974 continue;
1975 if (bad_char_behavior != BAD_KEEP)
1976 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001977 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001978 }
1979 }
1980 else if (fio_flags & FIO_UCS4)
1981 {
1982 if (fio_flags & FIO_ENDIAN_L)
1983 {
Bram Moolenaardc1c9812017-10-27 22:15:24 +02001984 u8c = (unsigned)*--p << 24;
1985 u8c += (unsigned)*--p << 16;
1986 u8c += (unsigned)*--p << 8;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001987 u8c += *--p;
1988 }
1989 else /* big endian */
1990 {
1991 u8c = *--p;
Bram Moolenaardc1c9812017-10-27 22:15:24 +02001992 u8c += (unsigned)*--p << 8;
1993 u8c += (unsigned)*--p << 16;
1994 u8c += (unsigned)*--p << 24;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001995 }
1996 }
1997 else /* UTF-8 */
1998 {
1999 if (*--p < 0x80)
2000 u8c = *p;
2001 else
2002 {
2003 len = utf_head_off(ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002004 p -= len;
2005 u8c = utf_ptr2char(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002006 if (len == 0)
2007 {
2008 /* Not a valid UTF-8 character, retry with
2009 * another fenc when possible, otherwise just
2010 * report the error. */
2011 if (can_retry)
2012 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002013 if (conv_error == 0)
2014 conv_error = readfile_linenr(linecnt,
2015 ptr, p);
2016 if (bad_char_behavior == BAD_DROP)
2017 continue;
2018 if (bad_char_behavior != BAD_KEEP)
2019 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002020 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002021 }
2022 }
2023 if (enc_utf8) /* produce UTF-8 */
2024 {
2025 dest -= utf_char2len(u8c);
2026 (void)utf_char2bytes(u8c, dest);
2027 }
2028 else /* produce Latin1 */
2029 {
2030 --dest;
2031 if (u8c >= 0x100)
2032 {
2033 /* character doesn't fit in latin1, retry with
2034 * another fenc when possible, otherwise just
2035 * report the error. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002036 if (can_retry)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002037 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002038 if (conv_error == 0)
2039 conv_error = readfile_linenr(linecnt, ptr, p);
2040 if (bad_char_behavior == BAD_DROP)
2041 ++dest;
2042 else if (bad_char_behavior == BAD_KEEP)
2043 *dest = u8c;
2044 else if (eap != NULL && eap->bad_char != 0)
2045 *dest = bad_char_behavior;
2046 else
2047 *dest = 0xBF;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002048 }
2049 else
2050 *dest = u8c;
2051 }
2052 }
2053
2054 /* move the linerest to before the converted characters */
2055 line_start = dest - linerest;
2056 mch_memmove(line_start, buffer, (size_t)linerest);
2057 size = (long)((ptr + real_size) - dest);
2058 ptr = dest;
2059 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002060 else if (enc_utf8 && !curbuf->b_p_bin)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002061 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002062 int incomplete_tail = FALSE;
2063
2064 /* Reading UTF-8: Check if the bytes are valid UTF-8. */
2065 for (p = ptr; ; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002066 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002067 int todo = (int)((ptr + size) - p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002068 int l;
2069
2070 if (todo <= 0)
2071 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002072 if (*p >= 0x80)
2073 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002074 /* A length of 1 means it's an illegal byte. Accept
2075 * an incomplete character at the end though, the next
2076 * read() will get the next bytes, we'll check it
2077 * then. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002078 l = utf_ptr2len_len(p, todo);
Bram Moolenaarf453d352008-06-04 17:37:34 +00002079 if (l > todo && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002080 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002081 /* Avoid retrying with a different encoding when
2082 * a truncated file is more likely, or attempting
2083 * to read the rest of an incomplete sequence when
2084 * we have already done so. */
2085 if (p > ptr || filesize > 0)
2086 incomplete_tail = TRUE;
2087 /* Incomplete byte sequence, move it to conv_rest[]
2088 * and try to read the rest of it, unless we've
2089 * already done so. */
2090 if (p > ptr)
2091 {
2092 conv_restlen = todo;
2093 mch_memmove(conv_rest, p, conv_restlen);
2094 size -= conv_restlen;
2095 break;
2096 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002097 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002098 if (l == 1 || l > todo)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002099 {
2100 /* Illegal byte. If we can try another encoding
Bram Moolenaarf453d352008-06-04 17:37:34 +00002101 * do that, unless at EOF where a truncated
2102 * file is more likely than a conversion error. */
2103 if (can_retry && !incomplete_tail)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002104 break;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002105# ifdef USE_ICONV
2106 /* When we did a conversion report an error. */
2107 if (iconv_fd != (iconv_t)-1 && conv_error == 0)
2108 conv_error = readfile_linenr(linecnt, ptr, p);
2109# endif
Bram Moolenaarf453d352008-06-04 17:37:34 +00002110 /* Remember the first linenr with an illegal byte */
2111 if (conv_error == 0 && illegal_byte == 0)
2112 illegal_byte = readfile_linenr(linecnt, ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002113
2114 /* Drop, keep or replace the bad byte. */
2115 if (bad_char_behavior == BAD_DROP)
2116 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002117 mch_memmove(p, p + 1, todo - 1);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002118 --p;
2119 --size;
2120 }
2121 else if (bad_char_behavior != BAD_KEEP)
2122 *p = bad_char_behavior;
2123 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002124 else
2125 p += l - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002126 }
2127 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002128 if (p < ptr + size && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002129 {
2130 /* Detected a UTF-8 error. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002131rewind_retry:
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002132 /* Retry reading with another conversion. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002133# if defined(FEAT_EVAL) && defined(USE_ICONV)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002134 if (*p_ccv != NUL && iconv_fd != (iconv_t)-1)
2135 /* iconv() failed, try 'charconvert' */
2136 did_iconv = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002137 else
2138# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002139 /* use next item from 'fileencodings' */
2140 advance_fenc = TRUE;
2141 file_rewind = TRUE;
2142 goto retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002143 }
2144 }
2145#endif
2146
2147 /* count the number of characters (after conversion!) */
2148 filesize += size;
2149
2150 /*
2151 * when reading the first part of a file: guess EOL type
2152 */
2153 if (fileformat == EOL_UNKNOWN)
2154 {
2155 /* First try finding a NL, for Dos and Unix */
2156 if (try_dos || try_unix)
2157 {
Bram Moolenaarc6b72172015-02-27 17:48:09 +01002158 /* Reset the carriage return counter. */
2159 if (try_mac)
2160 try_mac = 1;
2161
Bram Moolenaar071d4272004-06-13 20:20:40 +00002162 for (p = ptr; p < ptr + size; ++p)
2163 {
2164 if (*p == NL)
2165 {
2166 if (!try_unix
2167 || (try_dos && p > ptr && p[-1] == CAR))
2168 fileformat = EOL_DOS;
2169 else
2170 fileformat = EOL_UNIX;
2171 break;
2172 }
Bram Moolenaar05eb6122015-02-17 14:15:19 +01002173 else if (*p == CAR && try_mac)
2174 try_mac++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002175 }
2176
2177 /* Don't give in to EOL_UNIX if EOL_MAC is more likely */
2178 if (fileformat == EOL_UNIX && try_mac)
2179 {
2180 /* Need to reset the counters when retrying fenc. */
2181 try_mac = 1;
2182 try_unix = 1;
2183 for (; p >= ptr && *p != CAR; p--)
2184 ;
2185 if (p >= ptr)
2186 {
2187 for (p = ptr; p < ptr + size; ++p)
2188 {
2189 if (*p == NL)
2190 try_unix++;
2191 else if (*p == CAR)
2192 try_mac++;
2193 }
2194 if (try_mac > try_unix)
2195 fileformat = EOL_MAC;
2196 }
2197 }
Bram Moolenaar05eb6122015-02-17 14:15:19 +01002198 else if (fileformat == EOL_UNKNOWN && try_mac == 1)
2199 /* Looking for CR but found no end-of-line markers at
2200 * all: use the default format. */
2201 fileformat = default_fileformat();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002202 }
2203
2204 /* No NL found: may use Mac format */
2205 if (fileformat == EOL_UNKNOWN && try_mac)
2206 fileformat = EOL_MAC;
2207
2208 /* Still nothing found? Use first format in 'ffs' */
2209 if (fileformat == EOL_UNKNOWN)
2210 fileformat = default_fileformat();
2211
2212 /* if editing a new file: may set p_tx and p_ff */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002213 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002214 set_fileformat(fileformat, OPT_LOCAL);
2215 }
2216 }
2217
2218 /*
2219 * This loop is executed once for every character read.
2220 * Keep it fast!
2221 */
2222 if (fileformat == EOL_MAC)
2223 {
2224 --ptr;
2225 while (++ptr, --size >= 0)
2226 {
2227 /* catch most common case first */
2228 if ((c = *ptr) != NUL && c != CAR && c != NL)
2229 continue;
2230 if (c == NUL)
2231 *ptr = NL; /* NULs are replaced by newlines! */
2232 else if (c == NL)
2233 *ptr = CAR; /* NLs are replaced by CRs! */
2234 else
2235 {
2236 if (skip_count == 0)
2237 {
2238 *ptr = NUL; /* end of line */
2239 len = (colnr_T) (ptr - line_start + 1);
2240 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2241 {
2242 error = TRUE;
2243 break;
2244 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002245#ifdef FEAT_PERSISTENT_UNDO
2246 if (read_undo_file)
2247 sha256_update(&sha_ctx, line_start, len);
2248#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002249 ++lnum;
2250 if (--read_count == 0)
2251 {
2252 error = TRUE; /* break loop */
2253 line_start = ptr; /* nothing left to write */
2254 break;
2255 }
2256 }
2257 else
2258 --skip_count;
2259 line_start = ptr + 1;
2260 }
2261 }
2262 }
2263 else
2264 {
2265 --ptr;
2266 while (++ptr, --size >= 0)
2267 {
2268 if ((c = *ptr) != NUL && c != NL) /* catch most common case */
2269 continue;
2270 if (c == NUL)
2271 *ptr = NL; /* NULs are replaced by newlines! */
2272 else
2273 {
2274 if (skip_count == 0)
2275 {
2276 *ptr = NUL; /* end of line */
2277 len = (colnr_T)(ptr - line_start + 1);
2278 if (fileformat == EOL_DOS)
2279 {
Bram Moolenaar2aa5f692017-01-24 15:46:48 +01002280 if (ptr > line_start && ptr[-1] == CAR)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002281 {
Bram Moolenaar2aa5f692017-01-24 15:46:48 +01002282 /* remove CR before NL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002283 ptr[-1] = NUL;
2284 --len;
2285 }
2286 /*
2287 * Reading in Dos format, but no CR-LF found!
2288 * When 'fileformats' includes "unix", delete all
2289 * the lines read so far and start all over again.
2290 * Otherwise give an error message later.
2291 */
2292 else if (ff_error != EOL_DOS)
2293 {
2294 if ( try_unix
2295 && !read_stdin
2296 && (read_buffer
Bram Moolenaar8767f522016-07-01 17:17:39 +02002297 || vim_lseek(fd, (off_T)0L, SEEK_SET)
2298 == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002299 {
2300 fileformat = EOL_UNIX;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002301 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002302 set_fileformat(EOL_UNIX, OPT_LOCAL);
2303 file_rewind = TRUE;
2304 keep_fileformat = TRUE;
2305 goto retry;
2306 }
2307 ff_error = EOL_DOS;
2308 }
2309 }
2310 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2311 {
2312 error = TRUE;
2313 break;
2314 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002315#ifdef FEAT_PERSISTENT_UNDO
2316 if (read_undo_file)
2317 sha256_update(&sha_ctx, line_start, len);
2318#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002319 ++lnum;
2320 if (--read_count == 0)
2321 {
2322 error = TRUE; /* break loop */
2323 line_start = ptr; /* nothing left to write */
2324 break;
2325 }
2326 }
2327 else
2328 --skip_count;
2329 line_start = ptr + 1;
2330 }
2331 }
2332 }
2333 linerest = (long)(ptr - line_start);
2334 ui_breakcheck();
2335 }
2336
2337failed:
2338 /* not an error, max. number of lines reached */
2339 if (error && read_count == 0)
2340 error = FALSE;
2341
2342 /*
2343 * If we get EOF in the middle of a line, note the fact and
2344 * complete the line ourselves.
2345 * In Dos format ignore a trailing CTRL-Z, unless 'binary' set.
2346 */
2347 if (!error
2348 && !got_int
2349 && linerest != 0
2350 && !(!curbuf->b_p_bin
2351 && fileformat == EOL_DOS
2352 && *line_start == Ctrl_Z
2353 && ptr == line_start + 1))
2354 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002355 /* remember for when writing */
2356 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002357 curbuf->b_p_eol = FALSE;
2358 *ptr = NUL;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002359 len = (colnr_T)(ptr - line_start + 1);
2360 if (ml_append(lnum, line_start, len, newfile) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002361 error = TRUE;
2362 else
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002363 {
2364#ifdef FEAT_PERSISTENT_UNDO
2365 if (read_undo_file)
2366 sha256_update(&sha_ctx, line_start, len);
2367#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002368 read_no_eol_lnum = ++lnum;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002369 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002370 }
2371
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002372 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002373 save_file_ff(curbuf); /* remember the current file format */
2374
2375#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002376 if (curbuf->b_cryptstate != NULL)
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002377 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002378 crypt_free_state(curbuf->b_cryptstate);
2379 curbuf->b_cryptstate = NULL;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002380 }
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002381 if (cryptkey != NULL && cryptkey != curbuf->b_p_key)
2382 crypt_free_key(cryptkey);
2383 /* Don't set cryptkey to NULL, it's used below as a flag that
2384 * encryption was used. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002385#endif
2386
2387#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002388 /* If editing a new file: set 'fenc' for the current buffer.
2389 * Also for ":read ++edit file". */
2390 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002391 set_string_option_direct((char_u *)"fenc", -1, fenc,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00002392 OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002393 if (fenc_alloced)
2394 vim_free(fenc);
2395# ifdef USE_ICONV
2396 if (iconv_fd != (iconv_t)-1)
2397 {
2398 iconv_close(iconv_fd);
2399 iconv_fd = (iconv_t)-1;
2400 }
2401# endif
2402#endif
2403
2404 if (!read_buffer && !read_stdin)
2405 close(fd); /* errors are ignored */
Bram Moolenaarf05da212009-11-17 16:13:15 +00002406#ifdef HAVE_FD_CLOEXEC
2407 else
2408 {
2409 int fdflags = fcntl(fd, F_GETFD);
2410 if (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0)
Bram Moolenaarfbc4b4d2016-02-07 15:14:01 +01002411 (void)fcntl(fd, F_SETFD, fdflags | FD_CLOEXEC);
Bram Moolenaarf05da212009-11-17 16:13:15 +00002412 }
2413#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002414 vim_free(buffer);
2415
2416#ifdef HAVE_DUP
2417 if (read_stdin)
2418 {
2419 /* Use stderr for stdin, makes shell commands work. */
2420 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00002421 ignored = dup(2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002422 }
2423#endif
2424
2425#ifdef FEAT_MBYTE
2426 if (tmpname != NULL)
2427 {
2428 mch_remove(tmpname); /* delete converted file */
2429 vim_free(tmpname);
2430 }
2431#endif
2432 --no_wait_return; /* may wait for return now */
2433
2434 /*
2435 * In recovery mode everything but autocommands is skipped.
2436 */
2437 if (!recoverymode)
2438 {
2439 /* need to delete the last line, which comes from the empty buffer */
2440 if (newfile && wasempty && !(curbuf->b_ml.ml_flags & ML_EMPTY))
2441 {
2442#ifdef FEAT_NETBEANS_INTG
2443 netbeansFireChanges = 0;
2444#endif
2445 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
2446#ifdef FEAT_NETBEANS_INTG
2447 netbeansFireChanges = 1;
2448#endif
2449 --linecnt;
2450 }
2451 linecnt = curbuf->b_ml.ml_line_count - linecnt;
2452 if (filesize == 0)
2453 linecnt = 0;
2454 if (newfile || read_buffer)
Bram Moolenaar7263a772007-05-10 17:35:54 +00002455 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002456 redraw_curbuf_later(NOT_VALID);
Bram Moolenaar7263a772007-05-10 17:35:54 +00002457#ifdef FEAT_DIFF
2458 /* After reading the text into the buffer the diff info needs to
2459 * be updated. */
2460 diff_invalidate(curbuf);
2461#endif
2462#ifdef FEAT_FOLDING
2463 /* All folds in the window are invalid now. Mark them for update
2464 * before triggering autocommands. */
2465 foldUpdateAll(curwin);
2466#endif
2467 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002468 else if (linecnt) /* appended at least one line */
2469 appended_lines_mark(from, linecnt);
2470
Bram Moolenaar071d4272004-06-13 20:20:40 +00002471#ifndef ALWAYS_USE_GUI
2472 /*
2473 * If we were reading from the same terminal as where messages go,
2474 * the screen will have been messed up.
2475 * Switch on raw mode now and clear the screen.
2476 */
2477 if (read_stdin)
2478 {
2479 settmode(TMODE_RAW); /* set to raw mode */
2480 starttermcap();
2481 screenclear();
2482 }
2483#endif
2484
2485 if (got_int)
2486 {
2487 if (!(flags & READ_DUMMY))
2488 {
2489 filemess(curbuf, sfname, (char_u *)_(e_interr), 0);
2490 if (newfile)
2491 curbuf->b_p_ro = TRUE; /* must use "w!" now */
2492 }
2493 msg_scroll = msg_save;
2494#ifdef FEAT_VIMINFO
2495 check_marks_read();
2496#endif
2497 return OK; /* an interrupt isn't really an error */
2498 }
2499
2500 if (!filtering && !(flags & READ_DUMMY))
2501 {
2502 msg_add_fname(curbuf, sfname); /* fname in IObuff with quotes */
2503 c = FALSE;
2504
2505#ifdef UNIX
2506# ifdef S_ISFIFO
2507 if (S_ISFIFO(perm)) /* fifo or socket */
2508 {
2509 STRCAT(IObuff, _("[fifo/socket]"));
2510 c = TRUE;
2511 }
2512# else
2513# ifdef S_IFIFO
2514 if ((perm & S_IFMT) == S_IFIFO) /* fifo */
2515 {
2516 STRCAT(IObuff, _("[fifo]"));
2517 c = TRUE;
2518 }
2519# endif
2520# ifdef S_IFSOCK
2521 if ((perm & S_IFMT) == S_IFSOCK) /* or socket */
2522 {
2523 STRCAT(IObuff, _("[socket]"));
2524 c = TRUE;
2525 }
2526# endif
2527# endif
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002528# ifdef OPEN_CHR_FILES
2529 if (S_ISCHR(perm)) /* or character special */
2530 {
2531 STRCAT(IObuff, _("[character special]"));
2532 c = TRUE;
2533 }
2534# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002535#endif
2536 if (curbuf->b_p_ro)
2537 {
2538 STRCAT(IObuff, shortmess(SHM_RO) ? _("[RO]") : _("[readonly]"));
2539 c = TRUE;
2540 }
2541 if (read_no_eol_lnum)
2542 {
2543 msg_add_eol();
2544 c = TRUE;
2545 }
2546 if (ff_error == EOL_DOS)
2547 {
2548 STRCAT(IObuff, _("[CR missing]"));
2549 c = TRUE;
2550 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002551 if (split)
2552 {
2553 STRCAT(IObuff, _("[long lines split]"));
2554 c = TRUE;
2555 }
2556#ifdef FEAT_MBYTE
2557 if (notconverted)
2558 {
2559 STRCAT(IObuff, _("[NOT converted]"));
2560 c = TRUE;
2561 }
2562 else if (converted)
2563 {
2564 STRCAT(IObuff, _("[converted]"));
2565 c = TRUE;
2566 }
2567#endif
2568#ifdef FEAT_CRYPT
2569 if (cryptkey != NULL)
2570 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002571 crypt_append_msg(curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002572 c = TRUE;
2573 }
2574#endif
2575#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002576 if (conv_error != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002577 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002578 sprintf((char *)IObuff + STRLEN(IObuff),
2579 _("[CONVERSION ERROR in line %ld]"), (long)conv_error);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002580 c = TRUE;
2581 }
2582 else if (illegal_byte > 0)
2583 {
2584 sprintf((char *)IObuff + STRLEN(IObuff),
2585 _("[ILLEGAL BYTE in line %ld]"), (long)illegal_byte);
2586 c = TRUE;
2587 }
2588 else
2589#endif
2590 if (error)
2591 {
2592 STRCAT(IObuff, _("[READ ERRORS]"));
2593 c = TRUE;
2594 }
2595 if (msg_add_fileformat(fileformat))
2596 c = TRUE;
2597#ifdef FEAT_CRYPT
2598 if (cryptkey != NULL)
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002599 msg_add_lines(c, (long)linecnt, filesize
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002600 - crypt_get_header_len(crypt_get_method_nr(curbuf)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002601 else
2602#endif
2603 msg_add_lines(c, (long)linecnt, filesize);
2604
2605 vim_free(keep_msg);
2606 keep_msg = NULL;
2607 msg_scrolled_ign = TRUE;
2608#ifdef ALWAYS_USE_GUI
2609 /* Don't show the message when reading stdin, it would end up in a
2610 * message box (which might be shown when exiting!) */
2611 if (read_stdin || read_buffer)
2612 p = msg_may_trunc(FALSE, IObuff);
2613 else
2614#endif
2615 p = msg_trunc_attr(IObuff, FALSE, 0);
2616 if (read_stdin || read_buffer || restart_edit != 0
Bram Moolenaar1c7715d2005-10-03 22:02:18 +00002617 || (msg_scrolled != 0 && !need_wait_return))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002618 /* Need to repeat the message after redrawing when:
2619 * - When reading from stdin (the screen will be cleared next).
2620 * - When restart_edit is set (otherwise there will be a delay
2621 * before redrawing).
2622 * - When the screen was scrolled but there is no wait-return
2623 * prompt. */
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002624 set_keep_msg(p, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002625 msg_scrolled_ign = FALSE;
2626 }
2627
2628 /* with errors writing the file requires ":w!" */
2629 if (newfile && (error
2630#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002631 || conv_error != 0
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002632 || (illegal_byte > 0 && bad_char_behavior != BAD_KEEP)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002633#endif
2634 ))
2635 curbuf->b_p_ro = TRUE;
2636
2637 u_clearline(); /* cannot use "U" command after adding lines */
2638
2639 /*
2640 * In Ex mode: cursor at last new line.
2641 * Otherwise: cursor at first new line.
2642 */
2643 if (exmode_active)
2644 curwin->w_cursor.lnum = from + linecnt;
2645 else
2646 curwin->w_cursor.lnum = from + 1;
2647 check_cursor_lnum();
2648 beginline(BL_WHITE | BL_FIX); /* on first non-blank */
2649
2650 /*
2651 * Set '[ and '] marks to the newly read lines.
2652 */
2653 curbuf->b_op_start.lnum = from + 1;
2654 curbuf->b_op_start.col = 0;
2655 curbuf->b_op_end.lnum = from + linecnt;
2656 curbuf->b_op_end.col = 0;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002657
2658#ifdef WIN32
2659 /*
2660 * Work around a weird problem: When a file has two links (only
2661 * possible on NTFS) and we write through one link, then stat() it
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00002662 * through the other link, the timestamp information may be wrong.
Bram Moolenaar03f48552006-02-28 23:52:23 +00002663 * It's correct again after reading the file, thus reset the timestamp
2664 * here.
2665 */
2666 if (newfile && !read_stdin && !read_buffer
2667 && mch_stat((char *)fname, &st) >= 0)
2668 {
2669 buf_store_time(curbuf, &st, fname);
2670 curbuf->b_mtime_read = curbuf->b_mtime;
2671 }
2672#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002673 }
2674 msg_scroll = msg_save;
2675
2676#ifdef FEAT_VIMINFO
2677 /*
2678 * Get the marks before executing autocommands, so they can be used there.
2679 */
2680 check_marks_read();
2681#endif
2682
Bram Moolenaar071d4272004-06-13 20:20:40 +00002683 /*
Bram Moolenaar34d72d42015-07-17 14:18:08 +02002684 * We remember if the last line of the read didn't have
2685 * an eol even when 'binary' is off, to support turning 'fixeol' off,
2686 * or writing the read again with 'binary' on. The latter is required
2687 * for ":autocmd FileReadPost *.gz set bin|'[,']!gunzip" to work.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002688 */
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002689 curbuf->b_no_eol_lnum = read_no_eol_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002690
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02002691 /* When reloading a buffer put the cursor at the first line that is
2692 * different. */
2693 if (flags & READ_KEEP_UNDO)
2694 u_find_first_changed();
2695
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002696#ifdef FEAT_PERSISTENT_UNDO
2697 /*
2698 * When opening a new file locate undo info and read it.
2699 */
2700 if (read_undo_file)
2701 {
2702 char_u hash[UNDO_HASH_SIZE];
2703
2704 sha256_finish(&sha_ctx, hash);
Bram Moolenaar6ed8ed82010-05-30 20:40:11 +02002705 u_read_undo(NULL, hash, fname);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002706 }
2707#endif
2708
Bram Moolenaardf177f62005-02-22 08:39:57 +00002709#ifdef FEAT_AUTOCMD
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02002710 if (!read_stdin && !read_fifo && (!read_buffer || sfname != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002711 {
2712 int m = msg_scroll;
2713 int n = msg_scrolled;
2714
2715 /* Save the fileformat now, otherwise the buffer will be considered
2716 * modified if the format/encoding was automatically detected. */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002717 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002718 save_file_ff(curbuf);
2719
2720 /*
2721 * The output from the autocommands should not overwrite anything and
2722 * should not be overwritten: Set msg_scroll, restore its value if no
2723 * output was done.
2724 */
2725 msg_scroll = TRUE;
2726 if (filtering)
2727 apply_autocmds_exarg(EVENT_FILTERREADPOST, NULL, sfname,
2728 FALSE, curbuf, eap);
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02002729 else if (newfile || (read_buffer && sfname != NULL))
Bram Moolenaarc3691332016-04-20 12:49:49 +02002730 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002731 apply_autocmds_exarg(EVENT_BUFREADPOST, NULL, sfname,
2732 FALSE, curbuf, eap);
Bram Moolenaarc3691332016-04-20 12:49:49 +02002733 if (!au_did_filetype && *curbuf->b_p_ft != NUL)
2734 /*
2735 * EVENT_FILETYPE was not triggered but the buffer already has a
2736 * filetype. Trigger EVENT_FILETYPE using the existing filetype.
2737 */
2738 apply_autocmds(EVENT_FILETYPE, curbuf->b_p_ft, curbuf->b_fname,
2739 TRUE, curbuf);
2740 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002741 else
2742 apply_autocmds_exarg(EVENT_FILEREADPOST, sfname, sfname,
2743 FALSE, NULL, eap);
2744 if (msg_scrolled == n)
2745 msg_scroll = m;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002746# ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002747 if (aborting()) /* autocmds may abort script processing */
2748 return FAIL;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002749# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002750 }
2751#endif
2752
2753 if (recoverymode && error)
2754 return FAIL;
2755 return OK;
2756}
2757
Bram Moolenaarf04507d2016-08-20 15:05:39 +02002758#if defined(OPEN_CHR_FILES) || defined(PROTO)
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002759/*
2760 * Returns TRUE if the file name argument is of the form "/dev/fd/\d\+",
2761 * which is the name of files used for process substitution output by
2762 * some shells on some operating systems, e.g., bash on SunOS.
2763 * Do not accept "/dev/fd/[012]", opening these may hang Vim.
2764 */
Bram Moolenaarf04507d2016-08-20 15:05:39 +02002765 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002766is_dev_fd_file(char_u *fname)
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002767{
2768 return (STRNCMP(fname, "/dev/fd/", 8) == 0
2769 && VIM_ISDIGIT(fname[8])
2770 && *skipdigits(fname + 9) == NUL
2771 && (fname[9] != NUL
2772 || (fname[8] != '0' && fname[8] != '1' && fname[8] != '2')));
2773}
2774#endif
2775
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002776#ifdef FEAT_MBYTE
2777
2778/*
2779 * From the current line count and characters read after that, estimate the
2780 * line number where we are now.
2781 * Used for error messages that include a line number.
2782 */
2783 static linenr_T
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002784readfile_linenr(
2785 linenr_T linecnt, /* line count before reading more bytes */
2786 char_u *p, /* start of more bytes read */
2787 char_u *endp) /* end of more bytes read */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002788{
2789 char_u *s;
2790 linenr_T lnum;
2791
2792 lnum = curbuf->b_ml.ml_line_count - linecnt + 1;
2793 for (s = p; s < endp; ++s)
2794 if (*s == '\n')
2795 ++lnum;
2796 return lnum;
2797}
2798#endif
2799
Bram Moolenaar071d4272004-06-13 20:20:40 +00002800/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00002801 * Fill "*eap" to force the 'fileencoding', 'fileformat' and 'binary to be
2802 * equal to the buffer "buf". Used for calling readfile().
Bram Moolenaar071d4272004-06-13 20:20:40 +00002803 * Returns OK or FAIL.
2804 */
2805 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002806prep_exarg(exarg_T *eap, buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002807{
2808 eap->cmd = alloc((unsigned)(STRLEN(buf->b_p_ff)
2809#ifdef FEAT_MBYTE
2810 + STRLEN(buf->b_p_fenc)
2811#endif
2812 + 15));
2813 if (eap->cmd == NULL)
2814 return FAIL;
2815
2816#ifdef FEAT_MBYTE
2817 sprintf((char *)eap->cmd, "e ++ff=%s ++enc=%s", buf->b_p_ff, buf->b_p_fenc);
2818 eap->force_enc = 14 + (int)STRLEN(buf->b_p_ff);
Bram Moolenaar195d6352005-12-19 22:08:24 +00002819 eap->bad_char = buf->b_bad_char;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002820#else
2821 sprintf((char *)eap->cmd, "e ++ff=%s", buf->b_p_ff);
2822#endif
2823 eap->force_ff = 7;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002824
2825 eap->force_bin = buf->b_p_bin ? FORCE_BIN : FORCE_NOBIN;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002826 eap->read_edit = FALSE;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002827 eap->forceit = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002828 return OK;
2829}
2830
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002831/*
2832 * Set default or forced 'fileformat' and 'binary'.
2833 */
2834 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002835set_file_options(int set_options, exarg_T *eap)
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002836{
2837 /* set default 'fileformat' */
2838 if (set_options)
2839 {
2840 if (eap != NULL && eap->force_ff != 0)
2841 set_fileformat(get_fileformat_force(curbuf, eap), OPT_LOCAL);
2842 else if (*p_ffs != NUL)
2843 set_fileformat(default_fileformat(), OPT_LOCAL);
2844 }
2845
2846 /* set or reset 'binary' */
2847 if (eap != NULL && eap->force_bin != 0)
2848 {
2849 int oldval = curbuf->b_p_bin;
2850
2851 curbuf->b_p_bin = (eap->force_bin == FORCE_BIN);
2852 set_options_bin(oldval, curbuf->b_p_bin, OPT_LOCAL);
2853 }
2854}
2855
2856#if defined(FEAT_MBYTE) || defined(PROTO)
2857/*
2858 * Set forced 'fileencoding'.
2859 */
2860 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002861set_forced_fenc(exarg_T *eap)
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002862{
2863 if (eap->force_enc != 0)
2864 {
2865 char_u *fenc = enc_canonize(eap->cmd + eap->force_enc);
2866
2867 if (fenc != NULL)
2868 set_string_option_direct((char_u *)"fenc", -1,
2869 fenc, OPT_FREE|OPT_LOCAL, 0);
2870 vim_free(fenc);
2871 }
2872}
2873
Bram Moolenaar071d4272004-06-13 20:20:40 +00002874/*
2875 * Find next fileencoding to use from 'fileencodings'.
2876 * "pp" points to fenc_next. It's advanced to the next item.
2877 * When there are no more items, an empty string is returned and *pp is set to
2878 * NULL.
2879 * When *pp is not set to NULL, the result is in allocated memory.
2880 */
2881 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002882next_fenc(char_u **pp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002883{
2884 char_u *p;
2885 char_u *r;
2886
2887 if (**pp == NUL)
2888 {
2889 *pp = NULL;
2890 return (char_u *)"";
2891 }
2892 p = vim_strchr(*pp, ',');
2893 if (p == NULL)
2894 {
2895 r = enc_canonize(*pp);
2896 *pp += STRLEN(*pp);
2897 }
2898 else
2899 {
2900 r = vim_strnsave(*pp, (int)(p - *pp));
2901 *pp = p + 1;
2902 if (r != NULL)
2903 {
2904 p = enc_canonize(r);
2905 vim_free(r);
2906 r = p;
2907 }
2908 }
2909 if (r == NULL) /* out of memory */
2910 {
2911 r = (char_u *)"";
2912 *pp = NULL;
2913 }
2914 return r;
2915}
2916
2917# ifdef FEAT_EVAL
2918/*
2919 * Convert a file with the 'charconvert' expression.
2920 * This closes the file which is to be read, converts it and opens the
2921 * resulting file for reading.
2922 * Returns name of the resulting converted file (the caller should delete it
2923 * after reading it).
2924 * Returns NULL if the conversion failed ("*fdp" is not set) .
2925 */
2926 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002927readfile_charconvert(
2928 char_u *fname, /* name of input file */
2929 char_u *fenc, /* converted from */
2930 int *fdp) /* in/out: file descriptor of file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002931{
2932 char_u *tmpname;
2933 char_u *errmsg = NULL;
2934
Bram Moolenaare5c421c2015-03-31 13:33:08 +02002935 tmpname = vim_tempname('r', FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002936 if (tmpname == NULL)
2937 errmsg = (char_u *)_("Can't find temp file for conversion");
2938 else
2939 {
2940 close(*fdp); /* close the input file, ignore errors */
2941 *fdp = -1;
2942 if (eval_charconvert(fenc, enc_utf8 ? (char_u *)"utf-8" : p_enc,
2943 fname, tmpname) == FAIL)
2944 errmsg = (char_u *)_("Conversion with 'charconvert' failed");
2945 if (errmsg == NULL && (*fdp = mch_open((char *)tmpname,
2946 O_RDONLY | O_EXTRA, 0)) < 0)
2947 errmsg = (char_u *)_("can't read output of 'charconvert'");
2948 }
2949
2950 if (errmsg != NULL)
2951 {
2952 /* Don't use emsg(), it breaks mappings, the retry with
2953 * another type of conversion might still work. */
2954 MSG(errmsg);
2955 if (tmpname != NULL)
2956 {
2957 mch_remove(tmpname); /* delete converted file */
2958 vim_free(tmpname);
2959 tmpname = NULL;
2960 }
2961 }
2962
2963 /* If the input file is closed, open it (caller should check for error). */
2964 if (*fdp < 0)
2965 *fdp = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
2966
2967 return tmpname;
2968}
2969# endif
2970
2971#endif
2972
2973#ifdef FEAT_VIMINFO
2974/*
2975 * Read marks for the current buffer from the viminfo file, when we support
2976 * buffer marks and the buffer has a name.
2977 */
2978 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002979check_marks_read(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002980{
2981 if (!curbuf->b_marks_read && get_viminfo_parameter('\'') > 0
2982 && curbuf->b_ffname != NULL)
Bram Moolenaard812df62008-11-09 12:46:09 +00002983 read_viminfo(NULL, VIF_WANT_MARKS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002984
2985 /* Always set b_marks_read; needed when 'viminfo' is changed to include
2986 * the ' parameter after opening a buffer. */
2987 curbuf->b_marks_read = TRUE;
2988}
2989#endif
2990
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002991#if defined(FEAT_CRYPT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002992/*
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002993 * Check for magic number used for encryption. Applies to the current buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002994 * If found, the magic number is removed from ptr[*sizep] and *sizep and
2995 * *filesizep are updated.
2996 * Return the (new) encryption key, NULL for no encryption.
2997 */
2998 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002999check_for_cryptkey(
3000 char_u *cryptkey, /* previous encryption key or NULL */
3001 char_u *ptr, /* pointer to read bytes */
3002 long *sizep, /* length of read bytes */
Bram Moolenaar8767f522016-07-01 17:17:39 +02003003 off_T *filesizep, /* nr of bytes used from file */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003004 int newfile, /* editing a new buffer */
3005 char_u *fname, /* file name to display */
3006 int *did_ask) /* flag: whether already asked for key */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003007{
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003008 int method = crypt_method_nr_from_magic((char *)ptr, *sizep);
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02003009 int b_p_ro = curbuf->b_p_ro;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003010
3011 if (method >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003012 {
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02003013 /* Mark the buffer as read-only until the decryption has taken place.
3014 * Avoids accidentally overwriting the file with garbage. */
3015 curbuf->b_p_ro = TRUE;
3016
Bram Moolenaar2be79502014-08-13 21:58:28 +02003017 /* Set the cryptmethod local to the buffer. */
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003018 crypt_set_cm_option(curbuf, method);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02003019 if (cryptkey == NULL && !*did_ask)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003020 {
3021 if (*curbuf->b_p_key)
3022 cryptkey = curbuf->b_p_key;
3023 else
3024 {
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003025 /* When newfile is TRUE, store the typed key in the 'key'
3026 * option and don't free it. bf needs hash of the key saved.
Bram Moolenaarf50a2532010-05-21 15:36:08 +02003027 * Don't ask for the key again when first time Enter was hit.
3028 * Happens when retrying to detect encoding. */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003029 smsg((char_u *)_(need_key_msg), fname);
3030 msg_scroll = TRUE;
Bram Moolenaar3a0c9082014-11-12 15:15:42 +01003031 crypt_check_method(method);
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003032 cryptkey = crypt_get_key(newfile, FALSE);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02003033 *did_ask = TRUE;
3034
Bram Moolenaar071d4272004-06-13 20:20:40 +00003035 /* check if empty key entered */
3036 if (cryptkey != NULL && *cryptkey == NUL)
3037 {
3038 if (cryptkey != curbuf->b_p_key)
3039 vim_free(cryptkey);
3040 cryptkey = NULL;
3041 }
3042 }
3043 }
3044
3045 if (cryptkey != NULL)
3046 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003047 int header_len;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003048
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003049 curbuf->b_cryptstate = crypt_create_from_header(
3050 method, cryptkey, ptr);
3051 crypt_set_cm_option(curbuf, method);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003052
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003053 /* Remove cryptmethod specific header from the text. */
3054 header_len = crypt_get_header_len(method);
Bram Moolenaar680e0152016-09-25 20:54:11 +02003055 if (*sizep <= header_len)
3056 /* invalid header, buffer can't be encrypted */
3057 return NULL;
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003058 *filesizep += header_len;
3059 *sizep -= header_len;
3060 mch_memmove(ptr, ptr + header_len, (size_t)*sizep);
3061
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02003062 /* Restore the read-only flag. */
3063 curbuf->b_p_ro = b_p_ro;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003064 }
3065 }
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003066 /* When starting to edit a new file which does not have encryption, clear
3067 * the 'key' option, except when starting up (called with -x argument) */
Bram Moolenaarfa0ff9a2010-07-25 16:05:19 +02003068 else if (newfile && *curbuf->b_p_key != NUL && !starting)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003069 set_option_value((char_u *)"key", 0L, (char_u *)"", OPT_LOCAL);
3070
3071 return cryptkey;
3072}
Bram Moolenaar80794b12010-06-13 05:20:42 +02003073#endif /* FEAT_CRYPT */
3074
Bram Moolenaar071d4272004-06-13 20:20:40 +00003075#ifdef UNIX
3076 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003077set_file_time(
3078 char_u *fname,
3079 time_t atime, /* access time */
3080 time_t mtime) /* modification time */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003081{
3082# if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
3083 struct utimbuf buf;
3084
3085 buf.actime = atime;
3086 buf.modtime = mtime;
3087 (void)utime((char *)fname, &buf);
3088# else
3089# if defined(HAVE_UTIMES)
3090 struct timeval tvp[2];
3091
3092 tvp[0].tv_sec = atime;
3093 tvp[0].tv_usec = 0;
3094 tvp[1].tv_sec = mtime;
3095 tvp[1].tv_usec = 0;
3096# ifdef NeXT
3097 (void)utimes((char *)fname, tvp);
3098# else
3099 (void)utimes((char *)fname, (const struct timeval *)&tvp);
3100# endif
3101# endif
3102# endif
3103}
3104#endif /* UNIX */
3105
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003106#if defined(VMS) && !defined(MIN)
3107/* Older DECC compiler for VAX doesn't define MIN() */
3108# define MIN(a, b) ((a) < (b) ? (a) : (b))
3109#endif
3110
Bram Moolenaar071d4272004-06-13 20:20:40 +00003111/*
Bram Moolenaar5386a122007-06-28 20:02:32 +00003112 * Return TRUE if a file appears to be read-only from the file permissions.
3113 */
3114 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003115check_file_readonly(
3116 char_u *fname, /* full path to file */
3117 int perm) /* known permissions on file */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003118{
3119#ifndef USE_MCH_ACCESS
3120 int fd = 0;
3121#endif
3122
3123 return (
3124#ifdef USE_MCH_ACCESS
3125# ifdef UNIX
3126 (perm & 0222) == 0 ||
3127# endif
3128 mch_access((char *)fname, W_OK)
3129#else
3130 (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0
3131 ? TRUE : (close(fd), FALSE)
3132#endif
3133 );
3134}
3135
3136
3137/*
Bram Moolenaar292ad192005-12-11 21:29:51 +00003138 * buf_write() - write to file "fname" lines "start" through "end"
Bram Moolenaar071d4272004-06-13 20:20:40 +00003139 *
3140 * We do our own buffering here because fwrite() is so slow.
3141 *
Bram Moolenaar292ad192005-12-11 21:29:51 +00003142 * If "forceit" is true, we don't care for errors when attempting backups.
3143 * In case of an error everything possible is done to restore the original
Bram Moolenaare37d50a2008-08-06 17:06:04 +00003144 * file. But when "forceit" is TRUE, we risk losing it.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003145 *
3146 * When "reset_changed" is TRUE and "append" == FALSE and "start" == 1 and
3147 * "end" == curbuf->b_ml.ml_line_count, reset curbuf->b_changed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003148 *
3149 * This function must NOT use NameBuff (because it's called by autowrite()).
3150 *
3151 * return FAIL for failure, OK otherwise
3152 */
3153 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003154buf_write(
3155 buf_T *buf,
3156 char_u *fname,
3157 char_u *sfname,
3158 linenr_T start,
3159 linenr_T end,
3160 exarg_T *eap, /* for forced 'ff' and 'fenc', can be
Bram Moolenaar071d4272004-06-13 20:20:40 +00003161 NULL! */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003162 int append, /* append to the file */
3163 int forceit,
3164 int reset_changed,
3165 int filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003166{
3167 int fd;
3168 char_u *backup = NULL;
3169 int backup_copy = FALSE; /* copy the original file? */
3170 int dobackup;
3171 char_u *ffname;
3172 char_u *wfname = NULL; /* name of file to write to */
3173 char_u *s;
3174 char_u *ptr;
3175 char_u c;
3176 int len;
3177 linenr_T lnum;
3178 long nchars;
3179 char_u *errmsg = NULL;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003180 int errmsg_allocated = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003181 char_u *errnum = NULL;
3182 char_u *buffer;
3183 char_u smallbuf[SMBUFSIZE];
3184 char_u *backup_ext;
3185 int bufsize;
3186 long perm; /* file permissions */
3187 int retval = OK;
3188 int newfile = FALSE; /* TRUE if file doesn't exist yet */
3189 int msg_save = msg_scroll;
3190 int overwriting; /* TRUE if writing over original */
3191 int no_eol = FALSE; /* no end-of-line written */
3192 int device = FALSE; /* writing to a device */
Bram Moolenaar8767f522016-07-01 17:17:39 +02003193 stat_T st_old;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003194 int prev_got_int = got_int;
Bram Moolenaare6bf6552017-06-27 22:11:51 +02003195 int checking_conversion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003196 int file_readonly = FALSE; /* overwritten file is read-only */
3197 static char *err_readonly = "is read-only (cannot override: \"W\" in 'cpoptions')";
Bram Moolenaara06ecab2016-07-16 14:47:36 +02003198#if defined(UNIX) /*XXX fix me sometime? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003199 int made_writable = FALSE; /* 'w' bit has been set */
3200#endif
3201 /* writing everything */
3202 int whole = (start == 1 && end == buf->b_ml.ml_line_count);
3203#ifdef FEAT_AUTOCMD
3204 linenr_T old_line_count = buf->b_ml.ml_line_count;
3205#endif
3206 int attr;
3207 int fileformat;
3208 int write_bin;
3209 struct bw_info write_info; /* info for buf_write_bytes() */
3210#ifdef FEAT_MBYTE
3211 int converted = FALSE;
3212 int notconverted = FALSE;
3213 char_u *fenc; /* effective 'fileencoding' */
3214 char_u *fenc_tofree = NULL; /* allocated "fenc" */
3215#endif
3216#ifdef HAS_BW_FLAGS
3217 int wb_flags = 0;
3218#endif
3219#ifdef HAVE_ACL
3220 vim_acl_T acl = NULL; /* ACL copied from original file to
3221 backup or new file */
3222#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003223#ifdef FEAT_PERSISTENT_UNDO
3224 int write_undo_file = FALSE;
3225 context_sha256_T sha_ctx;
3226#endif
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003227 unsigned int bkc = get_bkc_value(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003228
3229 if (fname == NULL || *fname == NUL) /* safety check */
3230 return FAIL;
Bram Moolenaar70d60e92009-12-31 13:53:33 +00003231 if (buf->b_ml.ml_mfp == NULL)
3232 {
3233 /* This can happen during startup when there is a stray "w" in the
3234 * vimrc file. */
3235 EMSG(_(e_emptybuf));
3236 return FAIL;
3237 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003238
3239 /*
3240 * Disallow writing from .exrc and .vimrc in current directory for
3241 * security reasons.
3242 */
3243 if (check_secure())
3244 return FAIL;
3245
3246 /* Avoid a crash for a long name. */
3247 if (STRLEN(fname) >= MAXPATHL)
3248 {
3249 EMSG(_(e_longname));
3250 return FAIL;
3251 }
3252
3253#ifdef FEAT_MBYTE
3254 /* must init bw_conv_buf and bw_iconv_fd before jumping to "fail" */
3255 write_info.bw_conv_buf = NULL;
3256 write_info.bw_conv_error = FALSE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003257 write_info.bw_conv_error_lnum = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003258 write_info.bw_restlen = 0;
3259# ifdef USE_ICONV
3260 write_info.bw_iconv_fd = (iconv_t)-1;
3261# endif
3262#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003263#ifdef FEAT_CRYPT
3264 write_info.bw_buffer = buf;
3265#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003266
Bram Moolenaardf177f62005-02-22 08:39:57 +00003267 /* After writing a file changedtick changes but we don't want to display
3268 * the line. */
3269 ex_no_reprint = TRUE;
3270
Bram Moolenaar071d4272004-06-13 20:20:40 +00003271 /*
3272 * If there is no file name yet, use the one for the written file.
3273 * BF_NOTEDITED is set to reflect this (in case the write fails).
3274 * Don't do this when the write is for a filter command.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003275 * Don't do this when appending.
3276 * Only do this when 'cpoptions' contains the 'F' flag.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003277 */
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003278 if (buf->b_ffname == NULL
3279 && reset_changed
Bram Moolenaar071d4272004-06-13 20:20:40 +00003280 && whole
3281 && buf == curbuf
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00003282#ifdef FEAT_QUICKFIX
3283 && !bt_nofile(buf)
3284#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003285 && !filtering
Bram Moolenaar292ad192005-12-11 21:29:51 +00003286 && (!append || vim_strchr(p_cpo, CPO_FNAMEAPP) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003287 && vim_strchr(p_cpo, CPO_FNAMEW) != NULL)
3288 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003289 if (set_rw_fname(fname, sfname) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003290 return FAIL;
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003291 buf = curbuf; /* just in case autocmds made "buf" invalid */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003292 }
3293
3294 if (sfname == NULL)
3295 sfname = fname;
3296 /*
3297 * For Unix: Use the short file name whenever possible.
3298 * Avoids problems with networks and when directory names are changed.
3299 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
3300 * another directory, which we don't detect
3301 */
3302 ffname = fname; /* remember full fname */
3303#ifdef UNIX
3304 fname = sfname;
3305#endif
3306
3307 if (buf->b_ffname != NULL && fnamecmp(ffname, buf->b_ffname) == 0)
3308 overwriting = TRUE;
3309 else
3310 overwriting = FALSE;
3311
3312 if (exiting)
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003313 settmode(TMODE_COOK); /* when exiting allow typeahead now */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003314
3315 ++no_wait_return; /* don't wait for return yet */
3316
3317 /*
3318 * Set '[ and '] marks to the lines to be written.
3319 */
3320 buf->b_op_start.lnum = start;
3321 buf->b_op_start.col = 0;
3322 buf->b_op_end.lnum = end;
3323 buf->b_op_end.col = 0;
3324
3325#ifdef FEAT_AUTOCMD
3326 {
3327 aco_save_T aco;
3328 int buf_ffname = FALSE;
3329 int buf_sfname = FALSE;
3330 int buf_fname_f = FALSE;
3331 int buf_fname_s = FALSE;
3332 int did_cmd = FALSE;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003333 int nofile_err = FALSE;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003334 int empty_memline = (buf->b_ml.ml_mfp == NULL);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003335 bufref_T bufref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003336
3337 /*
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003338 * Apply PRE autocommands.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003339 * Set curbuf to the buffer to be written.
3340 * Careful: The autocommands may call buf_write() recursively!
3341 */
3342 if (ffname == buf->b_ffname)
3343 buf_ffname = TRUE;
3344 if (sfname == buf->b_sfname)
3345 buf_sfname = TRUE;
3346 if (fname == buf->b_ffname)
3347 buf_fname_f = TRUE;
3348 if (fname == buf->b_sfname)
3349 buf_fname_s = TRUE;
3350
3351 /* set curwin/curbuf to buf and save a few things */
3352 aucmd_prepbuf(&aco, buf);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003353 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003354
3355 if (append)
3356 {
3357 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD,
3358 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003359 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003360#ifdef FEAT_QUICKFIX
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00003361 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003362 nofile_err = TRUE;
3363 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003364#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003365 apply_autocmds_exarg(EVENT_FILEAPPENDPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003366 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003367 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003368 }
3369 else if (filtering)
3370 {
3371 apply_autocmds_exarg(EVENT_FILTERWRITEPRE,
3372 NULL, sfname, FALSE, curbuf, eap);
3373 }
3374 else if (reset_changed && whole)
3375 {
Bram Moolenaar39fc42e2011-09-02 11:56:20 +02003376 int was_changed = curbufIsChanged();
3377
3378 did_cmd = apply_autocmds_exarg(EVENT_BUFWRITECMD,
3379 sfname, sfname, FALSE, curbuf, eap);
3380 if (did_cmd)
3381 {
3382 if (was_changed && !curbufIsChanged())
3383 {
3384 /* Written everything correctly and BufWriteCmd has reset
3385 * 'modified': Correct the undo information so that an
3386 * undo now sets 'modified'. */
3387 u_unchanged(curbuf);
3388 u_update_save_nr(curbuf);
3389 }
3390 }
3391 else
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003392 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003393#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003394 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003395 nofile_err = TRUE;
3396 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003397#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003398 apply_autocmds_exarg(EVENT_BUFWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003399 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003400 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003401 }
3402 else
3403 {
3404 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD,
3405 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003406 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003407#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003408 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003409 nofile_err = TRUE;
3410 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003411#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003412 apply_autocmds_exarg(EVENT_FILEWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003413 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003414 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003415 }
3416
3417 /* restore curwin/curbuf and a few other things */
3418 aucmd_restbuf(&aco);
3419
3420 /*
3421 * In three situations we return here and don't write the file:
3422 * 1. the autocommands deleted or unloaded the buffer.
3423 * 2. The autocommands abort script processing.
3424 * 3. If one of the "Cmd" autocommands was executed.
3425 */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003426 if (!bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003427 buf = NULL;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003428 if (buf == NULL || (buf->b_ml.ml_mfp == NULL && !empty_memline)
Bram Moolenaar1e015462005-09-25 22:16:38 +00003429 || did_cmd || nofile_err
3430#ifdef FEAT_EVAL
3431 || aborting()
3432#endif
3433 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003434 {
3435 --no_wait_return;
3436 msg_scroll = msg_save;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003437 if (nofile_err)
3438 EMSG(_("E676: No matching autocommands for acwrite buffer"));
3439
Bram Moolenaar1e015462005-09-25 22:16:38 +00003440 if (nofile_err
3441#ifdef FEAT_EVAL
3442 || aborting()
3443#endif
3444 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003445 /* An aborting error, interrupt or exception in the
3446 * autocommands. */
3447 return FAIL;
3448 if (did_cmd)
3449 {
3450 if (buf == NULL)
3451 /* The buffer was deleted. We assume it was written
3452 * (can't retry anyway). */
3453 return OK;
3454 if (overwriting)
3455 {
3456 /* Assume the buffer was written, update the timestamp. */
3457 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00003458 if (append)
3459 buf->b_flags &= ~BF_NEW;
3460 else
3461 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003462 }
Bram Moolenaar292ad192005-12-11 21:29:51 +00003463 if (reset_changed && buf->b_changed && !append
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003464 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003465 /* Buffer still changed, the autocommands didn't work
3466 * properly. */
3467 return FAIL;
3468 return OK;
3469 }
3470#ifdef FEAT_EVAL
3471 if (!aborting())
3472#endif
3473 EMSG(_("E203: Autocommands deleted or unloaded buffer to be written"));
3474 return FAIL;
3475 }
3476
3477 /*
3478 * The autocommands may have changed the number of lines in the file.
3479 * When writing the whole file, adjust the end.
3480 * When writing part of the file, assume that the autocommands only
3481 * changed the number of lines that are to be written (tricky!).
3482 */
3483 if (buf->b_ml.ml_line_count != old_line_count)
3484 {
3485 if (whole) /* write all */
3486 end = buf->b_ml.ml_line_count;
3487 else if (buf->b_ml.ml_line_count > old_line_count) /* more lines */
3488 end += buf->b_ml.ml_line_count - old_line_count;
3489 else /* less lines */
3490 {
3491 end -= old_line_count - buf->b_ml.ml_line_count;
3492 if (end < start)
3493 {
3494 --no_wait_return;
3495 msg_scroll = msg_save;
3496 EMSG(_("E204: Autocommand changed number of lines in unexpected way"));
3497 return FAIL;
3498 }
3499 }
3500 }
3501
3502 /*
3503 * The autocommands may have changed the name of the buffer, which may
3504 * be kept in fname, ffname and sfname.
3505 */
3506 if (buf_ffname)
3507 ffname = buf->b_ffname;
3508 if (buf_sfname)
3509 sfname = buf->b_sfname;
3510 if (buf_fname_f)
3511 fname = buf->b_ffname;
3512 if (buf_fname_s)
3513 fname = buf->b_sfname;
3514 }
3515#endif
3516
3517#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003518 if (netbeans_active() && isNetbeansBuffer(buf))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003519 {
3520 if (whole)
3521 {
3522 /*
3523 * b_changed can be 0 after an undo, but we still need to write
3524 * the buffer to NetBeans.
3525 */
3526 if (buf->b_changed || isNetbeansModified(buf))
3527 {
Bram Moolenaar009b2592004-10-24 19:18:58 +00003528 --no_wait_return; /* may wait for return now */
3529 msg_scroll = msg_save;
3530 netbeans_save_buffer(buf); /* no error checking... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003531 return retval;
3532 }
3533 else
3534 {
3535 errnum = (char_u *)"E656: ";
Bram Moolenaared0e7452008-06-27 19:17:34 +00003536 errmsg = (char_u *)_("NetBeans disallows writes of unmodified buffers");
Bram Moolenaar071d4272004-06-13 20:20:40 +00003537 buffer = NULL;
3538 goto fail;
3539 }
3540 }
3541 else
3542 {
3543 errnum = (char_u *)"E657: ";
3544 errmsg = (char_u *)_("Partial writes disallowed for NetBeans buffers");
3545 buffer = NULL;
3546 goto fail;
3547 }
3548 }
3549#endif
3550
3551 if (shortmess(SHM_OVER) && !exiting)
3552 msg_scroll = FALSE; /* overwrite previous file message */
3553 else
3554 msg_scroll = TRUE; /* don't overwrite previous file message */
3555 if (!filtering)
3556 filemess(buf,
3557#ifndef UNIX
3558 sfname,
3559#else
3560 fname,
3561#endif
3562 (char_u *)"", 0); /* show that we are busy */
3563 msg_scroll = FALSE; /* always overwrite the file message now */
3564
3565 buffer = alloc(BUFSIZE);
3566 if (buffer == NULL) /* can't allocate big buffer, use small
3567 * one (to be able to write when out of
3568 * memory) */
3569 {
3570 buffer = smallbuf;
3571 bufsize = SMBUFSIZE;
3572 }
3573 else
3574 bufsize = BUFSIZE;
3575
3576 /*
3577 * Get information about original file (if there is one).
3578 */
Bram Moolenaar53076832015-12-31 19:53:21 +01003579#if defined(UNIX)
Bram Moolenaar6f192452007-11-08 19:49:02 +00003580 st_old.st_dev = 0;
3581 st_old.st_ino = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003582 perm = -1;
3583 if (mch_stat((char *)fname, &st_old) < 0)
3584 newfile = TRUE;
3585 else
3586 {
3587 perm = st_old.st_mode;
3588 if (!S_ISREG(st_old.st_mode)) /* not a file */
3589 {
3590 if (S_ISDIR(st_old.st_mode))
3591 {
3592 errnum = (char_u *)"E502: ";
3593 errmsg = (char_u *)_("is a directory");
3594 goto fail;
3595 }
3596 if (mch_nodetype(fname) != NODE_WRITABLE)
3597 {
3598 errnum = (char_u *)"E503: ";
3599 errmsg = (char_u *)_("is not a file or writable device");
3600 goto fail;
3601 }
3602 /* It's a device of some kind (or a fifo) which we can write to
3603 * but for which we can't make a backup. */
3604 device = TRUE;
3605 newfile = TRUE;
3606 perm = -1;
3607 }
3608 }
3609#else /* !UNIX */
3610 /*
3611 * Check for a writable device name.
3612 */
3613 c = mch_nodetype(fname);
3614 if (c == NODE_OTHER)
3615 {
3616 errnum = (char_u *)"E503: ";
3617 errmsg = (char_u *)_("is not a file or writable device");
3618 goto fail;
3619 }
3620 if (c == NODE_WRITABLE)
3621 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003622# if defined(MSWIN)
Bram Moolenaar043545e2006-10-10 16:44:07 +00003623 /* MS-Windows allows opening a device, but we will probably get stuck
3624 * trying to write to it. */
3625 if (!p_odev)
3626 {
3627 errnum = (char_u *)"E796: ";
3628 errmsg = (char_u *)_("writing to device disabled with 'opendevice' option");
3629 goto fail;
3630 }
3631# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003632 device = TRUE;
3633 newfile = TRUE;
3634 perm = -1;
3635 }
3636 else
3637 {
3638 perm = mch_getperm(fname);
3639 if (perm < 0)
3640 newfile = TRUE;
3641 else if (mch_isdir(fname))
3642 {
3643 errnum = (char_u *)"E502: ";
3644 errmsg = (char_u *)_("is a directory");
3645 goto fail;
3646 }
3647 if (overwriting)
3648 (void)mch_stat((char *)fname, &st_old);
3649 }
3650#endif /* !UNIX */
3651
3652 if (!device && !newfile)
3653 {
3654 /*
3655 * Check if the file is really writable (when renaming the file to
3656 * make a backup we won't discover it later).
3657 */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003658 file_readonly = check_file_readonly(fname, (int)perm);
3659
Bram Moolenaar071d4272004-06-13 20:20:40 +00003660 if (!forceit && file_readonly)
3661 {
3662 if (vim_strchr(p_cpo, CPO_FWRITE) != NULL)
3663 {
3664 errnum = (char_u *)"E504: ";
3665 errmsg = (char_u *)_(err_readonly);
3666 }
3667 else
3668 {
3669 errnum = (char_u *)"E505: ";
3670 errmsg = (char_u *)_("is read-only (add ! to override)");
3671 }
3672 goto fail;
3673 }
3674
3675 /*
3676 * Check if the timestamp hasn't changed since reading the file.
3677 */
3678 if (overwriting)
3679 {
3680 retval = check_mtime(buf, &st_old);
3681 if (retval == FAIL)
3682 goto fail;
3683 }
3684 }
3685
3686#ifdef HAVE_ACL
3687 /*
3688 * For systems that support ACL: get the ACL from the original file.
3689 */
3690 if (!newfile)
3691 acl = mch_get_acl(fname);
3692#endif
3693
3694 /*
3695 * If 'backupskip' is not empty, don't make a backup for some files.
3696 */
3697 dobackup = (p_wb || p_bk || *p_pm != NUL);
3698#ifdef FEAT_WILDIGN
3699 if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname))
3700 dobackup = FALSE;
3701#endif
3702
3703 /*
3704 * Save the value of got_int and reset it. We don't want a previous
3705 * interruption cancel writing, only hitting CTRL-C while writing should
3706 * abort it.
3707 */
3708 prev_got_int = got_int;
3709 got_int = FALSE;
3710
3711 /* Mark the buffer as 'being saved' to prevent changed buffer warnings */
3712 buf->b_saving = TRUE;
3713
3714 /*
3715 * If we are not appending or filtering, the file exists, and the
3716 * 'writebackup', 'backup' or 'patchmode' option is set, need a backup.
3717 * When 'patchmode' is set also make a backup when appending.
3718 *
3719 * Do not make any backup, if 'writebackup' and 'backup' are both switched
3720 * off. This helps when editing large files on almost-full disks.
3721 */
3722 if (!(append && *p_pm == NUL) && !filtering && perm >= 0 && dobackup)
3723 {
3724#if defined(UNIX) || defined(WIN32)
Bram Moolenaar8767f522016-07-01 17:17:39 +02003725 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003726#endif
3727
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003728 if ((bkc & BKC_YES) || append) /* "yes" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003729 backup_copy = TRUE;
3730#if defined(UNIX) || defined(WIN32)
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003731 else if ((bkc & BKC_AUTO)) /* "auto" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003732 {
3733 int i;
3734
3735# ifdef UNIX
3736 /*
3737 * Don't rename the file when:
3738 * - it's a hard link
3739 * - it's a symbolic link
3740 * - we don't have write permission in the directory
3741 * - we can't set the owner/group of the new file
3742 */
3743 if (st_old.st_nlink > 1
3744 || mch_lstat((char *)fname, &st) < 0
3745 || st.st_dev != st_old.st_dev
Bram Moolenaara5792f52005-11-23 21:25:05 +00003746 || st.st_ino != st_old.st_ino
3747# ifndef HAVE_FCHOWN
3748 || st.st_uid != st_old.st_uid
3749 || st.st_gid != st_old.st_gid
3750# endif
3751 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003752 backup_copy = TRUE;
3753 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003754# else
3755# ifdef WIN32
3756 /* On NTFS file systems hard links are possible. */
3757 if (mch_is_linked(fname))
3758 backup_copy = TRUE;
3759 else
3760# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003761# endif
3762 {
3763 /*
3764 * Check if we can create a file and set the owner/group to
3765 * the ones from the original file.
3766 * First find a file name that doesn't exist yet (use some
3767 * arbitrary numbers).
3768 */
3769 STRCPY(IObuff, fname);
3770 for (i = 4913; ; i += 123)
3771 {
3772 sprintf((char *)gettail(IObuff), "%d", i);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003773 if (mch_lstat((char *)IObuff, &st) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003774 break;
3775 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00003776 fd = mch_open((char *)IObuff,
3777 O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003778 if (fd < 0) /* can't write in directory */
3779 backup_copy = TRUE;
3780 else
3781 {
3782# ifdef UNIX
Bram Moolenaara5792f52005-11-23 21:25:05 +00003783# ifdef HAVE_FCHOWN
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00003784 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003785# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003786 if (mch_stat((char *)IObuff, &st) < 0
3787 || st.st_uid != st_old.st_uid
3788 || st.st_gid != st_old.st_gid
Bram Moolenaar78a15312009-05-15 19:33:18 +00003789 || (long)st.st_mode != perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003790 backup_copy = TRUE;
3791# endif
Bram Moolenaar98358622005-11-28 22:58:23 +00003792 /* Close the file before removing it, on MS-Windows we
3793 * can't delete an open file. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003794 close(fd);
Bram Moolenaar98358622005-11-28 22:58:23 +00003795 mch_remove(IObuff);
Bram Moolenaar3479c5d2010-08-08 18:46:06 +02003796# ifdef MSWIN
3797 /* MS-Windows may trigger a virus scanner to open the
3798 * file, we can't delete it then. Keep trying for half a
3799 * second. */
3800 {
3801 int try;
3802
3803 for (try = 0; try < 10; ++try)
3804 {
3805 if (mch_lstat((char *)IObuff, &st) < 0)
3806 break;
3807 ui_delay(50L, TRUE); /* wait 50 msec */
3808 mch_remove(IObuff);
3809 }
3810 }
3811# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003812 }
3813 }
3814 }
3815
Bram Moolenaar071d4272004-06-13 20:20:40 +00003816 /*
3817 * Break symlinks and/or hardlinks if we've been asked to.
3818 */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003819 if ((bkc & BKC_BREAKSYMLINK) || (bkc & BKC_BREAKHARDLINK))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003820 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003821# ifdef UNIX
Bram Moolenaar071d4272004-06-13 20:20:40 +00003822 int lstat_res;
3823
3824 lstat_res = mch_lstat((char *)fname, &st);
3825
3826 /* Symlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003827 if ((bkc & BKC_BREAKSYMLINK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003828 && lstat_res == 0
3829 && st.st_ino != st_old.st_ino)
3830 backup_copy = FALSE;
3831
3832 /* Hardlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003833 if ((bkc & BKC_BREAKHARDLINK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003834 && st_old.st_nlink > 1
3835 && (lstat_res != 0 || st.st_ino == st_old.st_ino))
3836 backup_copy = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003837# else
3838# if defined(WIN32)
3839 /* Symlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003840 if ((bkc & BKC_BREAKSYMLINK) && mch_is_symbolic_link(fname))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003841 backup_copy = FALSE;
3842
3843 /* Hardlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003844 if ((bkc & BKC_BREAKHARDLINK) && mch_is_hard_link(fname))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003845 backup_copy = FALSE;
3846# endif
3847# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003848 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003849
3850#endif
3851
3852 /* make sure we have a valid backup extension to use */
3853 if (*p_bex == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003854 backup_ext = (char_u *)".bak";
Bram Moolenaar071d4272004-06-13 20:20:40 +00003855 else
3856 backup_ext = p_bex;
3857
3858 if (backup_copy
3859 && (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) >= 0)
3860 {
3861 int bfd;
3862 char_u *copybuf, *wp;
3863 int some_error = FALSE;
Bram Moolenaar8767f522016-07-01 17:17:39 +02003864 stat_T st_new;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003865 char_u *dirp;
3866 char_u *rootname;
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003867#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003868 int did_set_shortname;
Bram Moolenaarcd142e32017-11-16 17:03:45 +01003869 mode_t umask_save;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003870#endif
3871
3872 copybuf = alloc(BUFSIZE + 1);
3873 if (copybuf == NULL)
3874 {
3875 some_error = TRUE; /* out of memory */
3876 goto nobackup;
3877 }
3878
3879 /*
3880 * Try to make the backup in each directory in the 'bdir' option.
3881 *
3882 * Unix semantics has it, that we may have a writable file,
3883 * that cannot be recreated with a simple open(..., O_CREAT, ) e.g:
3884 * - the directory is not writable,
3885 * - the file may be a symbolic link,
3886 * - the file may belong to another user/group, etc.
3887 *
3888 * For these reasons, the existing writable file must be truncated
3889 * and reused. Creation of a backup COPY will be attempted.
3890 */
3891 dirp = p_bdir;
3892 while (*dirp)
3893 {
3894#ifdef UNIX
3895 st_new.st_ino = 0;
3896 st_new.st_dev = 0;
3897 st_new.st_gid = 0;
3898#endif
3899
3900 /*
3901 * Isolate one directory name, using an entry in 'bdir'.
3902 */
3903 (void)copy_option_part(&dirp, copybuf, BUFSIZE, ",");
3904 rootname = get_file_in_dir(fname, copybuf);
3905 if (rootname == NULL)
3906 {
3907 some_error = TRUE; /* out of memory */
3908 goto nobackup;
3909 }
3910
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003911#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003912 did_set_shortname = FALSE;
3913#endif
3914
3915 /*
3916 * May try twice if 'shortname' not set.
3917 */
3918 for (;;)
3919 {
3920 /*
3921 * Make backup file name.
3922 */
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003923 backup = buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003924 rootname, backup_ext, FALSE);
3925 if (backup == NULL)
3926 {
3927 vim_free(rootname);
3928 some_error = TRUE; /* out of memory */
3929 goto nobackup;
3930 }
3931
3932 /*
3933 * Check if backup file already exists.
3934 */
3935 if (mch_stat((char *)backup, &st_new) >= 0)
3936 {
3937#ifdef UNIX
3938 /*
3939 * Check if backup file is same as original file.
3940 * May happen when modname() gave the same file back.
3941 * E.g. silly link, or file name-length reached.
3942 * If we don't check here, we either ruin the file
3943 * when copying or erase it after writing. jw.
3944 */
3945 if (st_new.st_dev == st_old.st_dev
3946 && st_new.st_ino == st_old.st_ino)
3947 {
3948 vim_free(backup);
3949 backup = NULL; /* no backup file to delete */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003950 /*
3951 * may try again with 'shortname' set
3952 */
3953 if (!(buf->b_shortname || buf->b_p_sn))
3954 {
3955 buf->b_shortname = TRUE;
3956 did_set_shortname = TRUE;
3957 continue;
3958 }
3959 /* setting shortname didn't help */
3960 if (did_set_shortname)
3961 buf->b_shortname = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003962 break;
3963 }
3964#endif
3965
3966 /*
3967 * If we are not going to keep the backup file, don't
3968 * delete an existing one, try to use another name.
3969 * Change one character, just before the extension.
3970 */
3971 if (!p_bk)
3972 {
3973 wp = backup + STRLEN(backup) - 1
3974 - STRLEN(backup_ext);
3975 if (wp < backup) /* empty file name ??? */
3976 wp = backup;
3977 *wp = 'z';
3978 while (*wp > 'a'
3979 && mch_stat((char *)backup, &st_new) >= 0)
3980 --*wp;
3981 /* They all exist??? Must be something wrong. */
3982 if (*wp == 'a')
3983 {
3984 vim_free(backup);
3985 backup = NULL;
3986 }
3987 }
3988 }
3989 break;
3990 }
3991 vim_free(rootname);
3992
3993 /*
3994 * Try to create the backup file
3995 */
3996 if (backup != NULL)
3997 {
3998 /* remove old backup, if present */
3999 mch_remove(backup);
4000 /* Open with O_EXCL to avoid the file being created while
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004001 * we were sleeping (symlink hacker attack?). Reset umask
4002 * if possible to avoid mch_setperm() below. */
4003#ifdef UNIX
4004 umask_save = umask(0);
4005#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004006 bfd = mch_open((char *)backup,
Bram Moolenaara5792f52005-11-23 21:25:05 +00004007 O_WRONLY|O_CREAT|O_EXTRA|O_EXCL|O_NOFOLLOW,
4008 perm & 0777);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004009#ifdef UNIX
4010 (void)umask(umask_save);
4011#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004012 if (bfd < 0)
4013 {
4014 vim_free(backup);
4015 backup = NULL;
4016 }
4017 else
4018 {
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004019 /* Set file protection same as original file, but
4020 * strip s-bit. Only needed if umask() wasn't used
4021 * above. */
4022#ifndef UNIX
Bram Moolenaar071d4272004-06-13 20:20:40 +00004023 (void)mch_setperm(backup, perm & 0777);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004024#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004025 /*
4026 * Try to set the group of the backup same as the
4027 * original file. If this fails, set the protection
4028 * bits for the group same as the protection bits for
4029 * others.
4030 */
Bram Moolenaara5792f52005-11-23 21:25:05 +00004031 if (st_new.st_gid != st_old.st_gid
Bram Moolenaar071d4272004-06-13 20:20:40 +00004032# ifdef HAVE_FCHOWN /* sequent-ptx lacks fchown() */
Bram Moolenaara5792f52005-11-23 21:25:05 +00004033 && fchown(bfd, (uid_t)-1, st_old.st_gid) != 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00004034# endif
4035 )
4036 mch_setperm(backup,
4037 (perm & 0707) | ((perm & 07) << 3));
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004038# if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004039 mch_copy_sec(fname, backup);
4040# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004041#endif
4042
4043 /*
4044 * copy the file.
4045 */
4046 write_info.bw_fd = bfd;
4047 write_info.bw_buf = copybuf;
4048#ifdef HAS_BW_FLAGS
4049 write_info.bw_flags = FIO_NOCONVERT;
4050#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004051 while ((write_info.bw_len = read_eintr(fd, copybuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004052 BUFSIZE)) > 0)
4053 {
4054 if (buf_write_bytes(&write_info) == FAIL)
4055 {
4056 errmsg = (char_u *)_("E506: Can't write to backup file (add ! to override)");
4057 break;
4058 }
4059 ui_breakcheck();
4060 if (got_int)
4061 {
4062 errmsg = (char_u *)_(e_interr);
4063 break;
4064 }
4065 }
4066
4067 if (close(bfd) < 0 && errmsg == NULL)
4068 errmsg = (char_u *)_("E507: Close error for backup file (add ! to override)");
4069 if (write_info.bw_len < 0)
4070 errmsg = (char_u *)_("E508: Can't read file for backup (add ! to override)");
4071#ifdef UNIX
4072 set_file_time(backup, st_old.st_atime, st_old.st_mtime);
4073#endif
4074#ifdef HAVE_ACL
4075 mch_set_acl(backup, acl);
4076#endif
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004077#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004078 mch_copy_sec(fname, backup);
4079#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004080 break;
4081 }
4082 }
4083 }
4084 nobackup:
4085 close(fd); /* ignore errors for closing read file */
4086 vim_free(copybuf);
4087
4088 if (backup == NULL && errmsg == NULL)
4089 errmsg = (char_u *)_("E509: Cannot create backup file (add ! to override)");
4090 /* ignore errors when forceit is TRUE */
4091 if ((some_error || errmsg != NULL) && !forceit)
4092 {
4093 retval = FAIL;
4094 goto fail;
4095 }
4096 errmsg = NULL;
4097 }
4098 else
4099 {
4100 char_u *dirp;
4101 char_u *p;
4102 char_u *rootname;
4103
4104 /*
4105 * Make a backup by renaming the original file.
4106 */
4107 /*
4108 * If 'cpoptions' includes the "W" flag, we don't want to
4109 * overwrite a read-only file. But rename may be possible
4110 * anyway, thus we need an extra check here.
4111 */
4112 if (file_readonly && vim_strchr(p_cpo, CPO_FWRITE) != NULL)
4113 {
4114 errnum = (char_u *)"E504: ";
4115 errmsg = (char_u *)_(err_readonly);
4116 goto fail;
4117 }
4118
4119 /*
4120 *
4121 * Form the backup file name - change path/fo.o.h to
4122 * path/fo.o.h.bak Try all directories in 'backupdir', first one
4123 * that works is used.
4124 */
4125 dirp = p_bdir;
4126 while (*dirp)
4127 {
4128 /*
4129 * Isolate one directory name and make the backup file name.
4130 */
4131 (void)copy_option_part(&dirp, IObuff, IOSIZE, ",");
4132 rootname = get_file_in_dir(fname, IObuff);
4133 if (rootname == NULL)
4134 backup = NULL;
4135 else
4136 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01004137 backup = buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00004138 rootname, backup_ext, FALSE);
4139 vim_free(rootname);
4140 }
4141
4142 if (backup != NULL)
4143 {
4144 /*
4145 * If we are not going to keep the backup file, don't
4146 * delete an existing one, try to use another name.
4147 * Change one character, just before the extension.
4148 */
4149 if (!p_bk && mch_getperm(backup) >= 0)
4150 {
4151 p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext);
4152 if (p < backup) /* empty file name ??? */
4153 p = backup;
4154 *p = 'z';
4155 while (*p > 'a' && mch_getperm(backup) >= 0)
4156 --*p;
4157 /* They all exist??? Must be something wrong! */
4158 if (*p == 'a')
4159 {
4160 vim_free(backup);
4161 backup = NULL;
4162 }
4163 }
4164 }
4165 if (backup != NULL)
4166 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004167 /*
Bram Moolenaarbfd8fc02005-09-20 23:22:24 +00004168 * Delete any existing backup and move the current version
4169 * to the backup. For safety, we don't remove the backup
4170 * until the write has finished successfully. And if the
4171 * 'backup' option is set, leave it around.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004172 */
4173 /*
4174 * If the renaming of the original file to the backup file
4175 * works, quit here.
4176 */
4177 if (vim_rename(fname, backup) == 0)
4178 break;
4179
4180 vim_free(backup); /* don't do the rename below */
4181 backup = NULL;
4182 }
4183 }
4184 if (backup == NULL && !forceit)
4185 {
4186 errmsg = (char_u *)_("E510: Can't make backup file (add ! to override)");
4187 goto fail;
4188 }
4189 }
4190 }
4191
Bram Moolenaar53076832015-12-31 19:53:21 +01004192#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004193 /* When using ":w!" and the file was read-only: make it writable */
4194 if (forceit && perm >= 0 && !(perm & 0200) && st_old.st_uid == getuid()
4195 && vim_strchr(p_cpo, CPO_FWRITE) == NULL)
4196 {
4197 perm |= 0200;
4198 (void)mch_setperm(fname, perm);
4199 made_writable = TRUE;
4200 }
4201#endif
4202
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004203 /* When using ":w!" and writing to the current file, 'readonly' makes no
Bram Moolenaar4399ef42005-02-12 14:29:27 +00004204 * sense, reset it, unless 'Z' appears in 'cpoptions'. */
4205 if (forceit && overwriting && vim_strchr(p_cpo, CPO_KEEPRO) == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004206 {
4207 buf->b_p_ro = FALSE;
4208#ifdef FEAT_TITLE
4209 need_maketitle = TRUE; /* set window title later */
4210#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004211 status_redraw_all(); /* redraw status lines later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004212 }
4213
4214 if (end > buf->b_ml.ml_line_count)
4215 end = buf->b_ml.ml_line_count;
4216 if (buf->b_ml.ml_flags & ML_EMPTY)
4217 start = end + 1;
4218
4219 /*
4220 * If the original file is being overwritten, there is a small chance that
4221 * we crash in the middle of writing. Therefore the file is preserved now.
4222 * This makes all block numbers positive so that recovery does not need
4223 * the original file.
4224 * Don't do this if there is a backup file and we are exiting.
4225 */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004226 if (reset_changed && !newfile && overwriting
Bram Moolenaar071d4272004-06-13 20:20:40 +00004227 && !(exiting && backup != NULL))
4228 {
4229 ml_preserve(buf, FALSE);
4230 if (got_int)
4231 {
4232 errmsg = (char_u *)_(e_interr);
4233 goto restore_backup;
4234 }
4235 }
4236
Bram Moolenaar071d4272004-06-13 20:20:40 +00004237#ifdef VMS
4238 vms_remove_version(fname); /* remove version */
4239#endif
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00004240 /* Default: write the file directly. May write to a temp file for
Bram Moolenaar071d4272004-06-13 20:20:40 +00004241 * multi-byte conversion. */
4242 wfname = fname;
4243
4244#ifdef FEAT_MBYTE
4245 /* Check for forced 'fileencoding' from "++opt=val" argument. */
4246 if (eap != NULL && eap->force_enc != 0)
4247 {
4248 fenc = eap->cmd + eap->force_enc;
4249 fenc = enc_canonize(fenc);
4250 fenc_tofree = fenc;
4251 }
4252 else
4253 fenc = buf->b_p_fenc;
4254
4255 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004256 * Check if the file needs to be converted.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004257 */
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004258 converted = need_conversion(fenc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004259
4260 /*
4261 * Check if UTF-8 to UCS-2/4 or Latin1 conversion needs to be done. Or
4262 * Latin1 to Unicode conversion. This is handled in buf_write_bytes().
4263 * Prepare the flags for it and allocate bw_conv_buf when needed.
4264 */
4265 if (converted && (enc_utf8 || STRCMP(p_enc, "latin1") == 0))
4266 {
4267 wb_flags = get_fio_flags(fenc);
4268 if (wb_flags & (FIO_UCS2 | FIO_UCS4 | FIO_UTF16 | FIO_UTF8))
4269 {
4270 /* Need to allocate a buffer to translate into. */
4271 if (wb_flags & (FIO_UCS2 | FIO_UTF16 | FIO_UTF8))
4272 write_info.bw_conv_buflen = bufsize * 2;
4273 else /* FIO_UCS4 */
4274 write_info.bw_conv_buflen = bufsize * 4;
4275 write_info.bw_conv_buf
4276 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4277 if (write_info.bw_conv_buf == NULL)
4278 end = 0;
4279 }
4280 }
4281
4282# ifdef WIN3264
4283 if (converted && wb_flags == 0 && (wb_flags = get_win_fio_flags(fenc)) != 0)
4284 {
4285 /* Convert UTF-8 -> UCS-2 and UCS-2 -> DBCS. Worst-case * 4: */
4286 write_info.bw_conv_buflen = bufsize * 4;
4287 write_info.bw_conv_buf
4288 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4289 if (write_info.bw_conv_buf == NULL)
4290 end = 0;
4291 }
4292# endif
4293
Bram Moolenaard0573012017-10-28 21:11:06 +02004294# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00004295 if (converted && wb_flags == 0 && (wb_flags = get_mac_fio_flags(fenc)) != 0)
4296 {
4297 write_info.bw_conv_buflen = bufsize * 3;
4298 write_info.bw_conv_buf
4299 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4300 if (write_info.bw_conv_buf == NULL)
4301 end = 0;
4302 }
4303# endif
4304
4305# if defined(FEAT_EVAL) || defined(USE_ICONV)
4306 if (converted && wb_flags == 0)
4307 {
4308# ifdef USE_ICONV
4309 /*
4310 * Use iconv() conversion when conversion is needed and it's not done
4311 * internally.
4312 */
4313 write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc,
4314 enc_utf8 ? (char_u *)"utf-8" : p_enc);
4315 if (write_info.bw_iconv_fd != (iconv_t)-1)
4316 {
4317 /* We're going to use iconv(), allocate a buffer to convert in. */
4318 write_info.bw_conv_buflen = bufsize * ICONV_MULT;
4319 write_info.bw_conv_buf
4320 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4321 if (write_info.bw_conv_buf == NULL)
4322 end = 0;
4323 write_info.bw_first = TRUE;
4324 }
4325# ifdef FEAT_EVAL
4326 else
4327# endif
4328# endif
4329
4330# ifdef FEAT_EVAL
4331 /*
4332 * When the file needs to be converted with 'charconvert' after
4333 * writing, write to a temp file instead and let the conversion
4334 * overwrite the original file.
4335 */
4336 if (*p_ccv != NUL)
4337 {
Bram Moolenaare5c421c2015-03-31 13:33:08 +02004338 wfname = vim_tempname('w', FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004339 if (wfname == NULL) /* Can't write without a tempfile! */
4340 {
4341 errmsg = (char_u *)_("E214: Can't find temp file for writing");
4342 goto restore_backup;
4343 }
4344 }
4345# endif
4346 }
4347# endif
4348 if (converted && wb_flags == 0
4349# ifdef USE_ICONV
4350 && write_info.bw_iconv_fd == (iconv_t)-1
4351# endif
4352# ifdef FEAT_EVAL
4353 && wfname == fname
4354# endif
4355 )
4356 {
4357 if (!forceit)
4358 {
4359 errmsg = (char_u *)_("E213: Cannot convert (add ! to write without conversion)");
4360 goto restore_backup;
4361 }
4362 notconverted = TRUE;
4363 }
4364#endif
4365
4366 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004367 * If conversion is taking place, we may first pretend to write and check
4368 * for conversion errors. Then loop again to write for real.
4369 * When not doing conversion this writes for real right away.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004370 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004371 for (checking_conversion = TRUE; ; checking_conversion = FALSE)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004372 {
4373 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004374 * There is no need to check conversion when:
4375 * - there is no conversion
4376 * - we make a backup file, that can be restored in case of conversion
4377 * failure.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004378 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004379#ifdef FEAT_MBYTE
4380 if (!converted || dobackup)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004381#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004382 checking_conversion = FALSE;
4383
4384 if (checking_conversion)
4385 {
4386 /* Make sure we don't write anything. */
4387 fd = -1;
4388 write_info.bw_fd = fd;
4389 }
4390 else
4391 {
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004392#ifdef HAVE_FTRUNCATE
4393# define TRUNC_ON_OPEN 0
4394#else
4395# define TRUNC_ON_OPEN O_TRUNC
4396#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004397 /*
4398 * Open the file "wfname" for writing.
4399 * We may try to open the file twice: If we can't write to the file
4400 * and forceit is TRUE we delete the existing file and try to
4401 * create a new one. If this still fails we may have lost the
4402 * original file! (this may happen when the user reached his
4403 * quotum for number of files).
4404 * Appending will fail if the file does not exist and forceit is
4405 * FALSE.
4406 */
4407 while ((fd = mch_open((char *)wfname, O_WRONLY | O_EXTRA | (append
4408 ? (forceit ? (O_APPEND | O_CREAT) : O_APPEND)
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004409 : (O_CREAT | TRUNC_ON_OPEN))
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004410 , perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004411 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004412 /*
4413 * A forced write will try to create a new file if the old one
4414 * is still readonly. This may also happen when the directory
4415 * is read-only. In that case the mch_remove() will fail.
4416 */
4417 if (errmsg == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004418 {
4419#ifdef UNIX
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004420 stat_T st;
4421
4422 /* Don't delete the file when it's a hard or symbolic link.
4423 */
4424 if ((!newfile && st_old.st_nlink > 1)
4425 || (mch_lstat((char *)fname, &st) == 0
4426 && (st.st_dev != st_old.st_dev
4427 || st.st_ino != st_old.st_ino)))
4428 errmsg = (char_u *)_("E166: Can't open linked file for writing");
4429 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004430#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004431 {
4432 errmsg = (char_u *)_("E212: Can't open file for writing");
4433 if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL
4434 && perm >= 0)
4435 {
4436#ifdef UNIX
4437 /* we write to the file, thus it should be marked
4438 writable after all */
4439 if (!(perm & 0200))
4440 made_writable = TRUE;
4441 perm |= 0200;
4442 if (st_old.st_uid != getuid()
4443 || st_old.st_gid != getgid())
4444 perm &= 0777;
4445#endif
4446 if (!append) /* don't remove when appending */
4447 mch_remove(wfname);
4448 continue;
4449 }
4450 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004451 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004452
4453restore_backup:
Bram Moolenaar071d4272004-06-13 20:20:40 +00004454 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004455 stat_T st;
4456
Bram Moolenaar071d4272004-06-13 20:20:40 +00004457 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004458 * If we failed to open the file, we don't need a backup.
4459 * Throw it away. If we moved or removed the original file
4460 * try to put the backup in its place.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004461 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004462 if (backup != NULL && wfname == fname)
4463 {
4464 if (backup_copy)
4465 {
4466 /*
4467 * There is a small chance that we removed the
4468 * original, try to move the copy in its place.
4469 * This may not work if the vim_rename() fails.
4470 * In that case we leave the copy around.
4471 */
4472 /* If file does not exist, put the copy in its
4473 * place */
4474 if (mch_stat((char *)fname, &st) < 0)
4475 vim_rename(backup, fname);
4476 /* if original file does exist throw away the copy
4477 */
4478 if (mch_stat((char *)fname, &st) >= 0)
4479 mch_remove(backup);
4480 }
4481 else
4482 {
4483 /* try to put the original file back */
4484 vim_rename(backup, fname);
4485 }
4486 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004487
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004488 /* if original file no longer exists give an extra warning
4489 */
4490 if (!newfile && mch_stat((char *)fname, &st) < 0)
4491 end = 0;
4492 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004493
4494#ifdef FEAT_MBYTE
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004495 if (wfname != fname)
4496 vim_free(wfname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004497#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004498 goto fail;
4499 }
4500 write_info.bw_fd = fd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004501
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004502#if defined(UNIX)
4503 {
4504 stat_T st;
4505
4506 /* Double check we are writing the intended file before making
4507 * any changes. */
4508 if (overwriting
4509 && (!dobackup || backup_copy)
4510 && fname == wfname
4511 && perm >= 0
4512 && mch_fstat(fd, &st) == 0
4513 && st.st_ino != st_old.st_ino)
4514 {
4515 close(fd);
4516 errmsg = (char_u *)_("E949: File changed while writing");
4517 goto fail;
4518 }
4519 }
4520#endif
4521#ifdef HAVE_FTRUNCATE
4522 if (!append)
Bram Moolenaarae1e1082017-11-17 21:35:24 +01004523 ignored = ftruncate(fd, (off_t)0);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004524#endif
4525
Bram Moolenaard0573012017-10-28 21:11:06 +02004526#if defined(WIN3264)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004527 if (backup != NULL && overwriting && !append)
4528 {
4529 if (backup_copy)
4530 (void)mch_copy_file_attribute(wfname, backup);
4531 else
4532 (void)mch_copy_file_attribute(backup, wfname);
4533 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004534
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004535 if (!overwriting && !append)
4536 {
4537 if (buf->b_ffname != NULL)
4538 (void)mch_copy_file_attribute(buf->b_ffname, wfname);
4539 /* Should copy resource fork */
4540 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004541#endif
4542
Bram Moolenaar071d4272004-06-13 20:20:40 +00004543#ifdef FEAT_CRYPT
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004544 if (*buf->b_p_key != NUL && !filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004545 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004546 char_u *header;
4547 int header_len;
4548
4549 buf->b_cryptstate = crypt_create_for_writing(
4550 crypt_get_method_nr(buf),
4551 buf->b_p_key, &header, &header_len);
4552 if (buf->b_cryptstate == NULL || header == NULL)
4553 end = 0;
4554 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004555 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004556 /* Write magic number, so that Vim knows how this file is
4557 * encrypted when reading it back. */
4558 write_info.bw_buf = header;
4559 write_info.bw_len = header_len;
4560 write_info.bw_flags = FIO_NOCONVERT;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004561 if (buf_write_bytes(&write_info) == FAIL)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004562 end = 0;
4563 wb_flags |= FIO_ENCRYPTED;
4564 vim_free(header);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004565 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004566 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004567#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004568 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004569 errmsg = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004570
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004571 write_info.bw_buf = buffer;
4572 nchars = 0;
4573
4574 /* use "++bin", "++nobin" or 'binary' */
4575 if (eap != NULL && eap->force_bin != 0)
4576 write_bin = (eap->force_bin == FORCE_BIN);
4577 else
4578 write_bin = buf->b_p_bin;
4579
4580#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004581 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004582 * The BOM is written just after the encryption magic number.
4583 * Skip it when appending and the file already existed, the BOM only
4584 * makes sense at the start of the file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004585 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004586 if (buf->b_p_bomb && !write_bin && (!append || perm < 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004587 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004588 write_info.bw_len = make_bom(buffer, fenc);
4589 if (write_info.bw_len > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004590 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004591 /* don't convert, do encryption */
4592 write_info.bw_flags = FIO_NOCONVERT | wb_flags;
4593 if (buf_write_bytes(&write_info) == FAIL)
4594 end = 0;
4595 else
4596 nchars += write_info.bw_len;
4597 }
4598 }
4599 write_info.bw_start_lnum = start;
4600#endif
4601
4602#ifdef FEAT_PERSISTENT_UNDO
4603 write_undo_file = (buf->b_p_udf
4604 && overwriting
4605 && !append
4606 && !filtering
4607 && reset_changed
4608 && !checking_conversion);
4609 if (write_undo_file)
4610 /* Prepare for computing the hash value of the text. */
4611 sha256_start(&sha_ctx);
4612#endif
4613
4614 write_info.bw_len = bufsize;
4615#ifdef HAS_BW_FLAGS
4616 write_info.bw_flags = wb_flags;
4617#endif
4618 fileformat = get_fileformat_force(buf, eap);
4619 s = buffer;
4620 len = 0;
4621 for (lnum = start; lnum <= end; ++lnum)
4622 {
4623 /*
4624 * The next while loop is done once for each character written.
4625 * Keep it fast!
4626 */
4627 ptr = ml_get_buf(buf, lnum, FALSE) - 1;
4628#ifdef FEAT_PERSISTENT_UNDO
4629 if (write_undo_file)
4630 sha256_update(&sha_ctx, ptr + 1,
4631 (UINT32_T)(STRLEN(ptr + 1) + 1));
4632#endif
4633 while ((c = *++ptr) != NUL)
4634 {
4635 if (c == NL)
4636 *s = NUL; /* replace newlines with NULs */
4637 else if (c == CAR && fileformat == EOL_MAC)
4638 *s = NL; /* Mac: replace CRs with NLs */
4639 else
4640 *s = c;
4641 ++s;
4642 if (++len != bufsize)
4643 continue;
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004644 if (buf_write_bytes(&write_info) == FAIL)
4645 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004646 end = 0; /* write error: break loop */
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004647 break;
4648 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004649 nchars += bufsize;
4650 s = buffer;
4651 len = 0;
4652#ifdef FEAT_MBYTE
4653 write_info.bw_start_lnum = lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004654#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004655 }
4656 /* write failed or last line has no EOL: stop here */
4657 if (end == 0
4658 || (lnum == end
4659 && (write_bin || !buf->b_p_fixeol)
4660 && (lnum == buf->b_no_eol_lnum
4661 || (lnum == buf->b_ml.ml_line_count
4662 && !buf->b_p_eol))))
4663 {
4664 ++lnum; /* written the line, count it */
4665 no_eol = TRUE;
4666 break;
4667 }
4668 if (fileformat == EOL_UNIX)
4669 *s++ = NL;
4670 else
4671 {
4672 *s++ = CAR; /* EOL_MAC or EOL_DOS: write CR */
4673 if (fileformat == EOL_DOS) /* write CR-NL */
4674 {
4675 if (++len == bufsize)
4676 {
4677 if (buf_write_bytes(&write_info) == FAIL)
4678 {
4679 end = 0; /* write error: break loop */
4680 break;
4681 }
4682 nchars += bufsize;
4683 s = buffer;
4684 len = 0;
4685 }
4686 *s++ = NL;
4687 }
4688 }
4689 if (++len == bufsize && end)
4690 {
4691 if (buf_write_bytes(&write_info) == FAIL)
4692 {
4693 end = 0; /* write error: break loop */
4694 break;
4695 }
4696 nchars += bufsize;
4697 s = buffer;
4698 len = 0;
4699
4700 ui_breakcheck();
4701 if (got_int)
4702 {
4703 end = 0; /* Interrupted, break loop */
4704 break;
4705 }
4706 }
4707#ifdef VMS
4708 /*
4709 * On VMS there is a problem: newlines get added when writing
4710 * blocks at a time. Fix it by writing a line at a time.
4711 * This is much slower!
4712 * Explanation: VAX/DECC RTL insists that records in some RMS
4713 * structures end with a newline (carriage return) character, and
4714 * if they don't it adds one.
4715 * With other RMS structures it works perfect without this fix.
4716 */
4717 if (buf->b_fab_rfm == FAB$C_VFC
4718 || ((buf->b_fab_rat & (FAB$M_FTN | FAB$M_CR)) != 0))
4719 {
4720 int b2write;
4721
4722 buf->b_fab_mrs = (buf->b_fab_mrs == 0
4723 ? MIN(4096, bufsize)
4724 : MIN(buf->b_fab_mrs, bufsize));
4725
4726 b2write = len;
4727 while (b2write > 0)
4728 {
4729 write_info.bw_len = MIN(b2write, buf->b_fab_mrs);
4730 if (buf_write_bytes(&write_info) == FAIL)
4731 {
4732 end = 0;
4733 break;
4734 }
4735 b2write -= MIN(b2write, buf->b_fab_mrs);
4736 }
4737 write_info.bw_len = bufsize;
4738 nchars += len;
4739 s = buffer;
4740 len = 0;
4741 }
4742#endif
4743 }
4744 if (len > 0 && end > 0)
4745 {
4746 write_info.bw_len = len;
4747 if (buf_write_bytes(&write_info) == FAIL)
4748 end = 0; /* write error */
4749 nchars += len;
4750 }
4751
4752 /* Stop when writing done or an error was encountered. */
4753 if (!checking_conversion || end == 0)
4754 break;
4755
4756 /* If no error happened until now, writing should be ok, so loop to
4757 * really write the buffer. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004758 }
4759
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004760 /* If we started writing, finish writing. Also when an error was
4761 * encountered. */
4762 if (!checking_conversion)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004763 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004764#if defined(UNIX) && defined(HAVE_FSYNC)
4765 /*
4766 * On many journalling file systems there is a bug that causes both the
4767 * original and the backup file to be lost when halting the system
4768 * right after writing the file. That's because only the meta-data is
4769 * journalled. Syncing the file slows down the system, but assures it
4770 * has been written to disk and we don't lose it.
4771 * For a device do try the fsync() but don't complain if it does not
4772 * work (could be a pipe).
4773 * If the 'fsync' option is FALSE, don't fsync(). Useful for laptops.
4774 */
4775 if (p_fs && fsync(fd) != 0 && !device)
4776 {
Bram Moolenaar7567d0b2017-11-16 23:04:15 +01004777 errmsg = (char_u *)_(e_fsync);
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004778 end = 0;
4779 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004780#endif
4781
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004782#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004783 /* Probably need to set the security context. */
4784 if (!backup_copy)
4785 mch_copy_sec(backup, wfname);
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004786#endif
4787
Bram Moolenaara5792f52005-11-23 21:25:05 +00004788#ifdef UNIX
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004789 /* When creating a new file, set its owner/group to that of the
4790 * original file. Get the new device and inode number. */
4791 if (backup != NULL && !backup_copy)
Bram Moolenaara5792f52005-11-23 21:25:05 +00004792 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004793# ifdef HAVE_FCHOWN
4794 stat_T st;
4795
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004796 /* Don't change the owner when it's already OK, some systems remove
4797 * permission or ACL stuff. */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004798 if (mch_stat((char *)wfname, &st) < 0
4799 || st.st_uid != st_old.st_uid
4800 || st.st_gid != st_old.st_gid)
4801 {
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004802 /* changing owner might not be possible */
4803 ignored = fchown(fd, st_old.st_uid, -1);
4804 /* if changing group fails clear the group permissions */
4805 if (fchown(fd, -1, st_old.st_gid) == -1 && perm > 0)
4806 perm &= ~070;
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004807 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00004808# endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004809 buf_setino(buf);
4810 }
4811 else if (!buf->b_dev_valid)
4812 /* Set the inode when creating a new file. */
4813 buf_setino(buf);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004814#endif
4815
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004816#ifdef UNIX
4817 if (made_writable)
4818 perm &= ~0200; /* reset 'w' bit for security reasons */
4819#endif
4820#ifdef HAVE_FCHMOD
4821 /* set permission of new file same as old file */
4822 if (perm >= 0)
4823 (void)mch_fsetperm(fd, perm);
4824#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004825 if (close(fd) != 0)
4826 {
4827 errmsg = (char_u *)_("E512: Close failed");
4828 end = 0;
4829 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004830
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004831#ifndef HAVE_FCHMOD
4832 /* set permission of new file same as old file */
4833 if (perm >= 0)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004834 (void)mch_setperm(wfname, perm);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004835#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004836#ifdef HAVE_ACL
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004837 /*
4838 * Probably need to set the ACL before changing the user (can't set the
4839 * ACL on a file the user doesn't own).
4840 * On Solaris, with ZFS and the aclmode property set to "discard" (the
4841 * default), chmod() discards all part of a file's ACL that don't
4842 * represent the mode of the file. It's non-trivial for us to discover
4843 * whether we're in that situation, so we simply always re-set the ACL.
4844 */
Bram Moolenaarda412772016-07-14 20:37:07 +02004845# ifndef HAVE_SOLARIS_ZFS_ACL
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004846 if (!backup_copy)
Bram Moolenaarda412772016-07-14 20:37:07 +02004847# endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004848 mch_set_acl(wfname, acl);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004849#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004850#ifdef FEAT_CRYPT
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004851 if (buf->b_cryptstate != NULL)
4852 {
4853 crypt_free_state(buf->b_cryptstate);
4854 buf->b_cryptstate = NULL;
4855 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004856#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004857
Bram Moolenaar071d4272004-06-13 20:20:40 +00004858#if defined(FEAT_MBYTE) && defined(FEAT_EVAL)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004859 if (wfname != fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004860 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004861 /*
4862 * The file was written to a temp file, now it needs to be
4863 * converted with 'charconvert' to (overwrite) the output file.
4864 */
4865 if (end != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004866 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004867 if (eval_charconvert(enc_utf8 ? (char_u *)"utf-8" : p_enc,
4868 fenc, wfname, fname) == FAIL)
4869 {
4870 write_info.bw_conv_error = TRUE;
4871 end = 0;
4872 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004873 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004874 mch_remove(wfname);
4875 vim_free(wfname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004876 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004877#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004878 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004879
4880 if (end == 0)
4881 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004882 /*
4883 * Error encountered.
4884 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004885 if (errmsg == NULL)
4886 {
4887#ifdef FEAT_MBYTE
4888 if (write_info.bw_conv_error)
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004889 {
4890 if (write_info.bw_conv_error_lnum == 0)
4891 errmsg = (char_u *)_("E513: write error, conversion failed (make 'fenc' empty to override)");
4892 else
4893 {
4894 errmsg_allocated = TRUE;
4895 errmsg = alloc(300);
4896 vim_snprintf((char *)errmsg, 300, _("E513: write error, conversion failed in line %ld (make 'fenc' empty to override)"),
4897 (long)write_info.bw_conv_error_lnum);
4898 }
4899 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004900 else
4901#endif
4902 if (got_int)
4903 errmsg = (char_u *)_(e_interr);
4904 else
4905 errmsg = (char_u *)_("E514: write error (file system full?)");
4906 }
4907
4908 /*
4909 * If we have a backup file, try to put it in place of the new file,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004910 * because the new file is probably corrupt. This avoids losing the
Bram Moolenaar071d4272004-06-13 20:20:40 +00004911 * original file when trying to make a backup when writing the file a
4912 * second time.
4913 * When "backup_copy" is set we need to copy the backup over the new
4914 * file. Otherwise rename the backup file.
4915 * If this is OK, don't give the extra warning message.
4916 */
4917 if (backup != NULL)
4918 {
4919 if (backup_copy)
4920 {
4921 /* This may take a while, if we were interrupted let the user
4922 * know we got the message. */
4923 if (got_int)
4924 {
4925 MSG(_(e_interr));
4926 out_flush();
4927 }
4928 if ((fd = mch_open((char *)backup, O_RDONLY | O_EXTRA, 0)) >= 0)
4929 {
4930 if ((write_info.bw_fd = mch_open((char *)fname,
Bram Moolenaar9be038d2005-03-08 22:34:32 +00004931 O_WRONLY | O_CREAT | O_TRUNC | O_EXTRA,
4932 perm & 0777)) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004933 {
4934 /* copy the file. */
4935 write_info.bw_buf = smallbuf;
4936#ifdef HAS_BW_FLAGS
4937 write_info.bw_flags = FIO_NOCONVERT;
4938#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004939 while ((write_info.bw_len = read_eintr(fd, smallbuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004940 SMBUFSIZE)) > 0)
4941 if (buf_write_bytes(&write_info) == FAIL)
4942 break;
4943
4944 if (close(write_info.bw_fd) >= 0
4945 && write_info.bw_len == 0)
4946 end = 1; /* success */
4947 }
4948 close(fd); /* ignore errors for closing read file */
4949 }
4950 }
4951 else
4952 {
4953 if (vim_rename(backup, fname) == 0)
4954 end = 1;
4955 }
4956 }
4957 goto fail;
4958 }
4959
4960 lnum -= start; /* compute number of written lines */
4961 --no_wait_return; /* may wait for return now */
4962
4963#if !(defined(UNIX) || defined(VMS))
4964 fname = sfname; /* use shortname now, for the messages */
4965#endif
4966 if (!filtering)
4967 {
4968 msg_add_fname(buf, fname); /* put fname in IObuff with quotes */
4969 c = FALSE;
4970#ifdef FEAT_MBYTE
4971 if (write_info.bw_conv_error)
4972 {
4973 STRCAT(IObuff, _(" CONVERSION ERROR"));
4974 c = TRUE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004975 if (write_info.bw_conv_error_lnum != 0)
Bram Moolenaara800b422010-06-27 01:15:55 +02004976 vim_snprintf_add((char *)IObuff, IOSIZE, _(" in line %ld;"),
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004977 (long)write_info.bw_conv_error_lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004978 }
4979 else if (notconverted)
4980 {
4981 STRCAT(IObuff, _("[NOT converted]"));
4982 c = TRUE;
4983 }
4984 else if (converted)
4985 {
4986 STRCAT(IObuff, _("[converted]"));
4987 c = TRUE;
4988 }
4989#endif
4990 if (device)
4991 {
4992 STRCAT(IObuff, _("[Device]"));
4993 c = TRUE;
4994 }
4995 else if (newfile)
4996 {
4997 STRCAT(IObuff, shortmess(SHM_NEW) ? _("[New]") : _("[New File]"));
4998 c = TRUE;
4999 }
5000 if (no_eol)
5001 {
5002 msg_add_eol();
5003 c = TRUE;
5004 }
5005 /* may add [unix/dos/mac] */
5006 if (msg_add_fileformat(fileformat))
5007 c = TRUE;
5008#ifdef FEAT_CRYPT
5009 if (wb_flags & FIO_ENCRYPTED)
5010 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02005011 crypt_append_msg(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005012 c = TRUE;
5013 }
5014#endif
5015 msg_add_lines(c, (long)lnum, nchars); /* add line/char count */
5016 if (!shortmess(SHM_WRITE))
5017 {
5018 if (append)
5019 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended"));
5020 else
5021 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written"));
5022 }
5023
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00005024 set_keep_msg(msg_trunc_attr(IObuff, FALSE, 0), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005025 }
5026
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005027 /* When written everything correctly: reset 'modified'. Unless not
5028 * writing to the original file and '+' is not in 'cpoptions'. */
Bram Moolenaar292ad192005-12-11 21:29:51 +00005029 if (reset_changed && whole && !append
Bram Moolenaar071d4272004-06-13 20:20:40 +00005030#ifdef FEAT_MBYTE
5031 && !write_info.bw_conv_error
5032#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005033 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL)
5034 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00005035 {
5036 unchanged(buf, TRUE);
Bram Moolenaar086329d2014-10-31 19:51:36 +01005037#ifdef FEAT_AUTOCMD
Bram Moolenaar95c526e2017-02-25 14:59:34 +01005038 /* b:changedtick is always incremented in unchanged() but that
Bram Moolenaar086329d2014-10-31 19:51:36 +01005039 * should not trigger a TextChanged event. */
Bram Moolenaar95c526e2017-02-25 14:59:34 +01005040 if (last_changedtick + 1 == CHANGEDTICK(buf)
Bram Moolenaar086329d2014-10-31 19:51:36 +01005041 && last_changedtick_buf == buf)
Bram Moolenaar95c526e2017-02-25 14:59:34 +01005042 last_changedtick = CHANGEDTICK(buf);
Bram Moolenaar086329d2014-10-31 19:51:36 +01005043#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005044 u_unchanged(buf);
Bram Moolenaar730cde92010-06-27 05:18:54 +02005045 u_update_save_nr(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005046 }
5047
5048 /*
5049 * If written to the current file, update the timestamp of the swap file
5050 * and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
5051 */
5052 if (overwriting)
5053 {
5054 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00005055 if (append)
5056 buf->b_flags &= ~BF_NEW;
5057 else
5058 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005059 }
5060
5061 /*
5062 * If we kept a backup until now, and we are in patch mode, then we make
5063 * the backup file our 'original' file.
5064 */
5065 if (*p_pm && dobackup)
5066 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01005067 char *org = (char *)buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005068 fname, p_pm, FALSE);
5069
5070 if (backup != NULL)
5071 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02005072 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005073
5074 /*
5075 * If the original file does not exist yet
5076 * the current backup file becomes the original file
5077 */
5078 if (org == NULL)
5079 EMSG(_("E205: Patchmode: can't save original file"));
5080 else if (mch_stat(org, &st) < 0)
5081 {
5082 vim_rename(backup, (char_u *)org);
5083 vim_free(backup); /* don't delete the file */
5084 backup = NULL;
5085#ifdef UNIX
5086 set_file_time((char_u *)org, st_old.st_atime, st_old.st_mtime);
5087#endif
5088 }
5089 }
5090 /*
5091 * If there is no backup file, remember that a (new) file was
5092 * created.
5093 */
5094 else
5095 {
5096 int empty_fd;
5097
5098 if (org == NULL
Bram Moolenaara5792f52005-11-23 21:25:05 +00005099 || (empty_fd = mch_open(org,
5100 O_CREAT | O_EXTRA | O_EXCL | O_NOFOLLOW,
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00005101 perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005102 EMSG(_("E206: patchmode: can't touch empty original file"));
5103 else
5104 close(empty_fd);
5105 }
5106 if (org != NULL)
5107 {
5108 mch_setperm((char_u *)org, mch_getperm(fname) & 0777);
5109 vim_free(org);
5110 }
5111 }
5112
5113 /*
5114 * Remove the backup unless 'backup' option is set
5115 */
5116 if (!p_bk && backup != NULL && mch_remove(backup) != 0)
5117 EMSG(_("E207: Can't delete backup file"));
5118
5119#ifdef FEAT_SUN_WORKSHOP
5120 if (usingSunWorkShop)
5121 workshop_file_saved((char *) ffname);
5122#endif
5123
5124 goto nofail;
5125
5126 /*
5127 * Finish up. We get here either after failure or success.
5128 */
5129fail:
5130 --no_wait_return; /* may wait for return now */
5131nofail:
5132
5133 /* Done saving, we accept changed buffer warnings again */
5134 buf->b_saving = FALSE;
5135
5136 vim_free(backup);
5137 if (buffer != smallbuf)
5138 vim_free(buffer);
5139#ifdef FEAT_MBYTE
5140 vim_free(fenc_tofree);
5141 vim_free(write_info.bw_conv_buf);
5142# ifdef USE_ICONV
5143 if (write_info.bw_iconv_fd != (iconv_t)-1)
5144 {
5145 iconv_close(write_info.bw_iconv_fd);
5146 write_info.bw_iconv_fd = (iconv_t)-1;
5147 }
5148# endif
5149#endif
5150#ifdef HAVE_ACL
5151 mch_free_acl(acl);
5152#endif
5153
5154 if (errmsg != NULL)
5155 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005156 int numlen = errnum != NULL ? (int)STRLEN(errnum) : 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005157
Bram Moolenaar8820b482017-03-16 17:23:31 +01005158 attr = HL_ATTR(HLF_E); /* set highlight for error messages */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005159 msg_add_fname(buf,
5160#ifndef UNIX
5161 sfname
5162#else
5163 fname
5164#endif
5165 ); /* put file name in IObuff with quotes */
5166 if (STRLEN(IObuff) + STRLEN(errmsg) + numlen >= IOSIZE)
5167 IObuff[IOSIZE - STRLEN(errmsg) - numlen - 1] = NUL;
5168 /* If the error message has the form "is ...", put the error number in
5169 * front of the file name. */
5170 if (errnum != NULL)
5171 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00005172 STRMOVE(IObuff + numlen, IObuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005173 mch_memmove(IObuff, errnum, (size_t)numlen);
5174 }
5175 STRCAT(IObuff, errmsg);
5176 emsg(IObuff);
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005177 if (errmsg_allocated)
5178 vim_free(errmsg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005179
5180 retval = FAIL;
5181 if (end == 0)
5182 {
5183 MSG_PUTS_ATTR(_("\nWARNING: Original file may be lost or damaged\n"),
5184 attr | MSG_HIST);
5185 MSG_PUTS_ATTR(_("don't quit the editor until the file is successfully written!"),
5186 attr | MSG_HIST);
5187
5188 /* Update the timestamp to avoid an "overwrite changed file"
5189 * prompt when writing again. */
5190 if (mch_stat((char *)fname, &st_old) >= 0)
5191 {
5192 buf_store_time(buf, &st_old, fname);
5193 buf->b_mtime_read = buf->b_mtime;
5194 }
5195 }
5196 }
5197 msg_scroll = msg_save;
5198
Bram Moolenaar55debbe2010-05-23 23:34:36 +02005199#ifdef FEAT_PERSISTENT_UNDO
5200 /*
5201 * When writing the whole file and 'undofile' is set, also write the undo
5202 * file.
5203 */
5204 if (retval == OK && write_undo_file)
5205 {
5206 char_u hash[UNDO_HASH_SIZE];
5207
5208 sha256_finish(&sha_ctx, hash);
5209 u_write_undo(NULL, FALSE, buf, hash);
5210 }
5211#endif
5212
Bram Moolenaar071d4272004-06-13 20:20:40 +00005213#ifdef FEAT_AUTOCMD
5214#ifdef FEAT_EVAL
5215 if (!should_abort(retval))
5216#else
5217 if (!got_int)
5218#endif
5219 {
5220 aco_save_T aco;
5221
Bram Moolenaar68a33fc2012-04-25 16:50:48 +02005222 curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */
5223
Bram Moolenaar071d4272004-06-13 20:20:40 +00005224 /*
5225 * Apply POST autocommands.
5226 * Careful: The autocommands may call buf_write() recursively!
5227 */
5228 aucmd_prepbuf(&aco, buf);
5229
5230 if (append)
5231 apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname,
5232 FALSE, curbuf, eap);
5233 else if (filtering)
5234 apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname,
5235 FALSE, curbuf, eap);
5236 else if (reset_changed && whole)
5237 apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname,
5238 FALSE, curbuf, eap);
5239 else
5240 apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname,
5241 FALSE, curbuf, eap);
5242
5243 /* restore curwin/curbuf and a few other things */
5244 aucmd_restbuf(&aco);
5245
5246#ifdef FEAT_EVAL
5247 if (aborting()) /* autocmds may abort script processing */
5248 retval = FALSE;
5249#endif
5250 }
5251#endif
5252
5253 got_int |= prev_got_int;
5254
Bram Moolenaar071d4272004-06-13 20:20:40 +00005255 return retval;
5256}
5257
5258/*
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005259 * Set the name of the current buffer. Use when the buffer doesn't have a
5260 * name and a ":r" or ":w" command with a file name is used.
5261 */
5262 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005263set_rw_fname(char_u *fname, char_u *sfname)
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005264{
5265#ifdef FEAT_AUTOCMD
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005266 buf_T *buf = curbuf;
5267
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005268 /* It's like the unnamed buffer is deleted.... */
5269 if (curbuf->b_p_bl)
5270 apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
5271 apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf);
5272# ifdef FEAT_EVAL
5273 if (aborting()) /* autocmds may abort script processing */
5274 return FAIL;
5275# endif
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005276 if (curbuf != buf)
5277 {
5278 /* We are in another buffer now, don't do the renaming. */
5279 EMSG(_(e_auchangedbuf));
5280 return FAIL;
5281 }
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005282#endif
5283
5284 if (setfname(curbuf, fname, sfname, FALSE) == OK)
5285 curbuf->b_flags |= BF_NOTEDITED;
5286
5287#ifdef FEAT_AUTOCMD
5288 /* ....and a new named one is created */
5289 apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, curbuf);
5290 if (curbuf->b_p_bl)
5291 apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf);
5292# ifdef FEAT_EVAL
5293 if (aborting()) /* autocmds may abort script processing */
5294 return FAIL;
5295# endif
5296
5297 /* Do filetype detection now if 'filetype' is empty. */
5298 if (*curbuf->b_p_ft == NUL)
5299 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005300 if (au_has_group((char_u *)"filetypedetect"))
Bram Moolenaar1610d052016-06-09 22:53:01 +02005301 (void)do_doautocmd((char_u *)"filetypedetect BufRead", FALSE, NULL);
Bram Moolenaara3227e22006-03-08 21:32:40 +00005302 do_modelines(0);
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005303 }
5304#endif
5305
5306 return OK;
5307}
5308
5309/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00005310 * Put file name into IObuff with quotes.
5311 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005312 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005313msg_add_fname(buf_T *buf, char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005314{
5315 if (fname == NULL)
5316 fname = (char_u *)"-stdin-";
5317 home_replace(buf, fname, IObuff + 1, IOSIZE - 4, TRUE);
5318 IObuff[0] = '"';
5319 STRCAT(IObuff, "\" ");
5320}
5321
5322/*
5323 * Append message for text mode to IObuff.
5324 * Return TRUE if something appended.
5325 */
5326 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005327msg_add_fileformat(int eol_type)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005328{
5329#ifndef USE_CRNL
5330 if (eol_type == EOL_DOS)
5331 {
5332 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[dos]") : _("[dos format]"));
5333 return TRUE;
5334 }
5335#endif
5336#ifndef USE_CR
5337 if (eol_type == EOL_MAC)
5338 {
5339 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[mac]") : _("[mac format]"));
5340 return TRUE;
5341 }
5342#endif
5343#if defined(USE_CRNL) || defined(USE_CR)
5344 if (eol_type == EOL_UNIX)
5345 {
5346 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[unix]") : _("[unix format]"));
5347 return TRUE;
5348 }
5349#endif
5350 return FALSE;
5351}
5352
5353/*
5354 * Append line and character count to IObuff.
5355 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005356 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005357msg_add_lines(
5358 int insert_space,
5359 long lnum,
Bram Moolenaar8767f522016-07-01 17:17:39 +02005360 off_T nchars)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005361{
5362 char_u *p;
5363
5364 p = IObuff + STRLEN(IObuff);
5365
5366 if (insert_space)
5367 *p++ = ' ';
5368 if (shortmess(SHM_LINES))
Bram Moolenaarbde98102016-07-01 20:03:42 +02005369 vim_snprintf((char *)p, IOSIZE - (p - IObuff),
5370 "%ldL, %lldC", lnum, (varnumber_T)nchars);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005371 else
5372 {
5373 if (lnum == 1)
5374 STRCPY(p, _("1 line, "));
5375 else
5376 sprintf((char *)p, _("%ld lines, "), lnum);
5377 p += STRLEN(p);
5378 if (nchars == 1)
5379 STRCPY(p, _("1 character"));
5380 else
Bram Moolenaarbde98102016-07-01 20:03:42 +02005381 vim_snprintf((char *)p, IOSIZE - (p - IObuff),
5382 _("%lld characters"), (varnumber_T)nchars);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005383 }
5384}
5385
5386/*
5387 * Append message for missing line separator to IObuff.
5388 */
5389 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005390msg_add_eol(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005391{
5392 STRCAT(IObuff, shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]"));
5393}
5394
5395/*
5396 * Check modification time of file, before writing to it.
5397 * The size isn't checked, because using a tool like "gzip" takes care of
5398 * using the same timestamp but can't set the size.
5399 */
5400 static int
Bram Moolenaar8767f522016-07-01 17:17:39 +02005401check_mtime(buf_T *buf, stat_T *st)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005402{
5403 if (buf->b_mtime_read != 0
5404 && time_differs((long)st->st_mtime, buf->b_mtime_read))
5405 {
5406 msg_scroll = TRUE; /* don't overwrite messages here */
5407 msg_silent = 0; /* must give this prompt */
5408 /* don't use emsg() here, don't want to flush the buffers */
5409 MSG_ATTR(_("WARNING: The file has been changed since reading it!!!"),
Bram Moolenaar8820b482017-03-16 17:23:31 +01005410 HL_ATTR(HLF_E));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005411 if (ask_yesno((char_u *)_("Do you really want to write to it"),
5412 TRUE) == 'n')
5413 return FAIL;
5414 msg_scroll = FALSE; /* always overwrite the file message now */
5415 }
5416 return OK;
5417}
5418
5419 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005420time_differs(long t1, long t2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005421{
Bram Moolenaar48e330a2016-02-23 14:53:34 +01005422#if defined(__linux__) || defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005423 /* On a FAT filesystem, esp. under Linux, there are only 5 bits to store
5424 * the seconds. Since the roundoff is done when flushing the inode, the
5425 * time may change unexpectedly by one second!!! */
5426 return (t1 - t2 > 1 || t2 - t1 > 1);
5427#else
5428 return (t1 != t2);
5429#endif
5430}
5431
5432/*
5433 * Call write() to write a number of bytes to the file.
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005434 * Handles encryption and 'encoding' conversion.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005435 *
5436 * Return FAIL for failure, OK otherwise.
5437 */
5438 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005439buf_write_bytes(struct bw_info *ip)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005440{
5441 int wlen;
5442 char_u *buf = ip->bw_buf; /* data to write */
5443 int len = ip->bw_len; /* length of data */
5444#ifdef HAS_BW_FLAGS
5445 int flags = ip->bw_flags; /* extra flags */
5446#endif
5447
5448#ifdef FEAT_MBYTE
5449 /*
5450 * Skip conversion when writing the crypt magic number or the BOM.
5451 */
5452 if (!(flags & FIO_NOCONVERT))
5453 {
5454 char_u *p;
5455 unsigned c;
5456 int n;
5457
5458 if (flags & FIO_UTF8)
5459 {
5460 /*
5461 * Convert latin1 in the buffer to UTF-8 in the file.
5462 */
5463 p = ip->bw_conv_buf; /* translate to buffer */
5464 for (wlen = 0; wlen < len; ++wlen)
5465 p += utf_char2bytes(buf[wlen], p);
5466 buf = ip->bw_conv_buf;
5467 len = (int)(p - ip->bw_conv_buf);
5468 }
5469 else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1))
5470 {
5471 /*
5472 * Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
5473 * Latin1 chars in the file.
5474 */
5475 if (flags & FIO_LATIN1)
5476 p = buf; /* translate in-place (can only get shorter) */
5477 else
5478 p = ip->bw_conv_buf; /* translate to buffer */
5479 for (wlen = 0; wlen < len; wlen += n)
5480 {
5481 if (wlen == 0 && ip->bw_restlen != 0)
5482 {
5483 int l;
5484
5485 /* Use remainder of previous call. Append the start of
5486 * buf[] to get a full sequence. Might still be too
5487 * short! */
5488 l = CONV_RESTLEN - ip->bw_restlen;
5489 if (l > len)
5490 l = len;
5491 mch_memmove(ip->bw_rest + ip->bw_restlen, buf, (size_t)l);
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005492 n = utf_ptr2len_len(ip->bw_rest, ip->bw_restlen + l);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005493 if (n > ip->bw_restlen + len)
5494 {
5495 /* We have an incomplete byte sequence at the end to
5496 * be written. We can't convert it without the
5497 * remaining bytes. Keep them for the next call. */
5498 if (ip->bw_restlen + len > CONV_RESTLEN)
5499 return FAIL;
5500 ip->bw_restlen += len;
5501 break;
5502 }
5503 if (n > 1)
5504 c = utf_ptr2char(ip->bw_rest);
5505 else
5506 c = ip->bw_rest[0];
5507 if (n >= ip->bw_restlen)
5508 {
5509 n -= ip->bw_restlen;
5510 ip->bw_restlen = 0;
5511 }
5512 else
5513 {
5514 ip->bw_restlen -= n;
5515 mch_memmove(ip->bw_rest, ip->bw_rest + n,
5516 (size_t)ip->bw_restlen);
5517 n = 0;
5518 }
5519 }
5520 else
5521 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005522 n = utf_ptr2len_len(buf + wlen, len - wlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005523 if (n > len - wlen)
5524 {
5525 /* We have an incomplete byte sequence at the end to
5526 * be written. We can't convert it without the
5527 * remaining bytes. Keep them for the next call. */
5528 if (len - wlen > CONV_RESTLEN)
5529 return FAIL;
5530 ip->bw_restlen = len - wlen;
5531 mch_memmove(ip->bw_rest, buf + wlen,
5532 (size_t)ip->bw_restlen);
5533 break;
5534 }
5535 if (n > 1)
5536 c = utf_ptr2char(buf + wlen);
5537 else
5538 c = buf[wlen];
5539 }
5540
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005541 if (ucs2bytes(c, &p, flags) && !ip->bw_conv_error)
5542 {
5543 ip->bw_conv_error = TRUE;
5544 ip->bw_conv_error_lnum = ip->bw_start_lnum;
5545 }
5546 if (c == NL)
5547 ++ip->bw_start_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005548 }
5549 if (flags & FIO_LATIN1)
5550 len = (int)(p - buf);
5551 else
5552 {
5553 buf = ip->bw_conv_buf;
5554 len = (int)(p - ip->bw_conv_buf);
5555 }
5556 }
5557
5558# ifdef WIN3264
5559 else if (flags & FIO_CODEPAGE)
5560 {
5561 /*
5562 * Convert UTF-8 or codepage to UCS-2 and then to MS-Windows
5563 * codepage.
5564 */
5565 char_u *from;
5566 size_t fromlen;
5567 char_u *to;
5568 int u8c;
5569 BOOL bad = FALSE;
5570 int needed;
5571
5572 if (ip->bw_restlen > 0)
5573 {
5574 /* Need to concatenate the remainder of the previous call and
5575 * the bytes of the current call. Use the end of the
5576 * conversion buffer for this. */
5577 fromlen = len + ip->bw_restlen;
5578 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5579 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5580 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5581 }
5582 else
5583 {
5584 from = buf;
5585 fromlen = len;
5586 }
5587
5588 to = ip->bw_conv_buf;
5589 if (enc_utf8)
5590 {
5591 /* Convert from UTF-8 to UCS-2, to the start of the buffer.
5592 * The buffer has been allocated to be big enough. */
5593 while (fromlen > 0)
5594 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005595 n = (int)utf_ptr2len_len(from, (int)fromlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005596 if (n > (int)fromlen) /* incomplete byte sequence */
5597 break;
5598 u8c = utf_ptr2char(from);
5599 *to++ = (u8c & 0xff);
5600 *to++ = (u8c >> 8);
5601 fromlen -= n;
5602 from += n;
5603 }
5604
5605 /* Copy remainder to ip->bw_rest[] to be used for the next
5606 * call. */
5607 if (fromlen > CONV_RESTLEN)
5608 {
5609 /* weird overlong sequence */
5610 ip->bw_conv_error = TRUE;
5611 return FAIL;
5612 }
5613 mch_memmove(ip->bw_rest, from, fromlen);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005614 ip->bw_restlen = (int)fromlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005615 }
5616 else
5617 {
5618 /* Convert from enc_codepage to UCS-2, to the start of the
5619 * buffer. The buffer has been allocated to be big enough. */
5620 ip->bw_restlen = 0;
5621 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005622 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005623 NULL, 0);
5624 if (needed == 0)
5625 {
5626 /* When conversion fails there may be a trailing byte. */
5627 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005628 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen - 1,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005629 NULL, 0);
5630 if (needed == 0)
5631 {
5632 /* Conversion doesn't work. */
5633 ip->bw_conv_error = TRUE;
5634 return FAIL;
5635 }
5636 /* Save the trailing byte for the next call. */
5637 ip->bw_rest[0] = from[fromlen - 1];
5638 ip->bw_restlen = 1;
5639 }
5640 needed = MultiByteToWideChar(enc_codepage, MB_ERR_INVALID_CHARS,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005641 (LPCSTR)from, (int)(fromlen - ip->bw_restlen),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005642 (LPWSTR)to, needed);
5643 if (needed == 0)
5644 {
5645 /* Safety check: Conversion doesn't work. */
5646 ip->bw_conv_error = TRUE;
5647 return FAIL;
5648 }
5649 to += needed * 2;
5650 }
5651
5652 fromlen = to - ip->bw_conv_buf;
5653 buf = to;
5654# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5655 if (FIO_GET_CP(flags) == CP_UTF8)
5656 {
5657 /* Convert from UCS-2 to UTF-8, using the remainder of the
5658 * conversion buffer. Fails when out of space. */
5659 for (from = ip->bw_conv_buf; fromlen > 1; fromlen -= 2)
5660 {
5661 u8c = *from++;
5662 u8c += (*from++ << 8);
5663 to += utf_char2bytes(u8c, to);
5664 if (to + 6 >= ip->bw_conv_buf + ip->bw_conv_buflen)
5665 {
5666 ip->bw_conv_error = TRUE;
5667 return FAIL;
5668 }
5669 }
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005670 len = (int)(to - buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005671 }
5672 else
5673#endif
5674 {
5675 /* Convert from UCS-2 to the codepage, using the remainder of
5676 * the conversion buffer. If the conversion uses the default
5677 * character "0", the data doesn't fit in this encoding, so
5678 * fail. */
5679 len = WideCharToMultiByte(FIO_GET_CP(flags), 0,
5680 (LPCWSTR)ip->bw_conv_buf, (int)fromlen / sizeof(WCHAR),
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005681 (LPSTR)to, (int)(ip->bw_conv_buflen - fromlen), 0,
5682 &bad);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005683 if (bad)
5684 {
5685 ip->bw_conv_error = TRUE;
5686 return FAIL;
5687 }
5688 }
5689 }
5690# endif
5691
Bram Moolenaar56718732006-03-15 22:53:57 +00005692# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00005693 else if (flags & FIO_MACROMAN)
5694 {
5695 /*
5696 * Convert UTF-8 or latin1 to Apple MacRoman.
5697 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005698 char_u *from;
5699 size_t fromlen;
5700
5701 if (ip->bw_restlen > 0)
5702 {
5703 /* Need to concatenate the remainder of the previous call and
5704 * the bytes of the current call. Use the end of the
5705 * conversion buffer for this. */
5706 fromlen = len + ip->bw_restlen;
5707 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5708 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5709 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5710 }
5711 else
5712 {
5713 from = buf;
5714 fromlen = len;
5715 }
5716
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00005717 if (enc2macroman(from, fromlen,
5718 ip->bw_conv_buf, &len, ip->bw_conv_buflen,
5719 ip->bw_rest, &ip->bw_restlen) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005720 {
5721 ip->bw_conv_error = TRUE;
5722 return FAIL;
5723 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005724 buf = ip->bw_conv_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005725 }
5726# endif
5727
5728# ifdef USE_ICONV
5729 if (ip->bw_iconv_fd != (iconv_t)-1)
5730 {
5731 const char *from;
5732 size_t fromlen;
5733 char *to;
5734 size_t tolen;
5735
5736 /* Convert with iconv(). */
5737 if (ip->bw_restlen > 0)
5738 {
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005739 char *fp;
5740
Bram Moolenaar071d4272004-06-13 20:20:40 +00005741 /* Need to concatenate the remainder of the previous call and
5742 * the bytes of the current call. Use the end of the
5743 * conversion buffer for this. */
5744 fromlen = len + ip->bw_restlen;
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005745 fp = (char *)ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5746 mch_memmove(fp, ip->bw_rest, (size_t)ip->bw_restlen);
5747 mch_memmove(fp + ip->bw_restlen, buf, (size_t)len);
5748 from = fp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005749 tolen = ip->bw_conv_buflen - fromlen;
5750 }
5751 else
5752 {
5753 from = (const char *)buf;
5754 fromlen = len;
5755 tolen = ip->bw_conv_buflen;
5756 }
5757 to = (char *)ip->bw_conv_buf;
5758
5759 if (ip->bw_first)
5760 {
5761 size_t save_len = tolen;
5762
5763 /* output the initial shift state sequence */
5764 (void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen);
5765
5766 /* There is a bug in iconv() on Linux (which appears to be
5767 * wide-spread) which sets "to" to NULL and messes up "tolen".
5768 */
5769 if (to == NULL)
5770 {
5771 to = (char *)ip->bw_conv_buf;
5772 tolen = save_len;
5773 }
5774 ip->bw_first = FALSE;
5775 }
5776
5777 /*
5778 * If iconv() has an error or there is not enough room, fail.
5779 */
5780 if ((iconv(ip->bw_iconv_fd, (void *)&from, &fromlen, &to, &tolen)
5781 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
5782 || fromlen > CONV_RESTLEN)
5783 {
5784 ip->bw_conv_error = TRUE;
5785 return FAIL;
5786 }
5787
5788 /* copy remainder to ip->bw_rest[] to be used for the next call. */
5789 if (fromlen > 0)
5790 mch_memmove(ip->bw_rest, (void *)from, fromlen);
5791 ip->bw_restlen = (int)fromlen;
5792
5793 buf = ip->bw_conv_buf;
5794 len = (int)((char_u *)to - ip->bw_conv_buf);
5795 }
5796# endif
5797 }
5798#endif /* FEAT_MBYTE */
5799
Bram Moolenaare6bf6552017-06-27 22:11:51 +02005800 if (ip->bw_fd < 0)
5801 /* Only checking conversion, which is OK if we get here. */
5802 return OK;
5803
Bram Moolenaar071d4272004-06-13 20:20:40 +00005804#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02005805 if (flags & FIO_ENCRYPTED)
5806 {
5807 /* Encrypt the data. Do it in-place if possible, otherwise use an
5808 * allocated buffer. */
5809 if (crypt_works_inplace(ip->bw_buffer->b_cryptstate))
5810 {
5811 crypt_encode_inplace(ip->bw_buffer->b_cryptstate, buf, len);
5812 }
5813 else
5814 {
5815 char_u *outbuf;
5816
5817 len = crypt_encode_alloc(curbuf->b_cryptstate, buf, len, &outbuf);
5818 if (len == 0)
5819 return OK; /* Crypt layer is buffering, will flush later. */
5820 wlen = write_eintr(ip->bw_fd, outbuf, len);
5821 vim_free(outbuf);
5822 return (wlen < len) ? FAIL : OK;
5823 }
5824 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005825#endif
5826
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005827 wlen = write_eintr(ip->bw_fd, buf, len);
5828 return (wlen < len) ? FAIL : OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005829}
5830
5831#ifdef FEAT_MBYTE
5832/*
5833 * Convert a Unicode character to bytes.
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005834 * Return TRUE for an error, FALSE when it's OK.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005835 */
5836 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005837ucs2bytes(
5838 unsigned c, /* in: character */
5839 char_u **pp, /* in/out: pointer to result */
5840 int flags) /* FIO_ flags */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005841{
5842 char_u *p = *pp;
5843 int error = FALSE;
5844 int cc;
5845
5846
5847 if (flags & FIO_UCS4)
5848 {
5849 if (flags & FIO_ENDIAN_L)
5850 {
5851 *p++ = c;
5852 *p++ = (c >> 8);
5853 *p++ = (c >> 16);
5854 *p++ = (c >> 24);
5855 }
5856 else
5857 {
5858 *p++ = (c >> 24);
5859 *p++ = (c >> 16);
5860 *p++ = (c >> 8);
5861 *p++ = c;
5862 }
5863 }
5864 else if (flags & (FIO_UCS2 | FIO_UTF16))
5865 {
5866 if (c >= 0x10000)
5867 {
5868 if (flags & FIO_UTF16)
5869 {
5870 /* Make two words, ten bits of the character in each. First
5871 * word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff */
5872 c -= 0x10000;
5873 if (c >= 0x100000)
5874 error = TRUE;
5875 cc = ((c >> 10) & 0x3ff) + 0xd800;
5876 if (flags & FIO_ENDIAN_L)
5877 {
5878 *p++ = cc;
5879 *p++ = ((unsigned)cc >> 8);
5880 }
5881 else
5882 {
5883 *p++ = ((unsigned)cc >> 8);
5884 *p++ = cc;
5885 }
5886 c = (c & 0x3ff) + 0xdc00;
5887 }
5888 else
5889 error = TRUE;
5890 }
5891 if (flags & FIO_ENDIAN_L)
5892 {
5893 *p++ = c;
5894 *p++ = (c >> 8);
5895 }
5896 else
5897 {
5898 *p++ = (c >> 8);
5899 *p++ = c;
5900 }
5901 }
5902 else /* Latin1 */
5903 {
5904 if (c >= 0x100)
5905 {
5906 error = TRUE;
5907 *p++ = 0xBF;
5908 }
5909 else
5910 *p++ = c;
5911 }
5912
5913 *pp = p;
5914 return error;
5915}
5916
5917/*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005918 * Return TRUE if file encoding "fenc" requires conversion from or to
5919 * 'encoding'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005920 */
5921 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005922need_conversion(char_u *fenc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005923{
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005924 int same_encoding;
5925 int enc_flags;
5926 int fenc_flags;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005927
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005928 if (*fenc == NUL || STRCMP(p_enc, fenc) == 0)
Bram Moolenaar442b4222010-05-24 21:34:22 +02005929 {
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005930 same_encoding = TRUE;
Bram Moolenaar442b4222010-05-24 21:34:22 +02005931 fenc_flags = 0;
5932 }
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005933 else
5934 {
5935 /* Ignore difference between "ansi" and "latin1", "ucs-4" and
5936 * "ucs-4be", etc. */
5937 enc_flags = get_fio_flags(p_enc);
5938 fenc_flags = get_fio_flags(fenc);
5939 same_encoding = (enc_flags != 0 && fenc_flags == enc_flags);
5940 }
5941 if (same_encoding)
5942 {
5943 /* Specified encoding matches with 'encoding'. This requires
5944 * conversion when 'encoding' is Unicode but not UTF-8. */
5945 return enc_unicode != 0;
5946 }
5947
5948 /* Encodings differ. However, conversion is not needed when 'enc' is any
5949 * Unicode encoding and the file is UTF-8. */
5950 return !(enc_utf8 && fenc_flags == FIO_UTF8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005951}
5952
5953/*
5954 * Check "ptr" for a unicode encoding and return the FIO_ flags needed for the
5955 * internal conversion.
5956 * if "ptr" is an empty string, use 'encoding'.
5957 */
5958 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005959get_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005960{
5961 int prop;
5962
5963 if (*ptr == NUL)
5964 ptr = p_enc;
5965
5966 prop = enc_canon_props(ptr);
5967 if (prop & ENC_UNICODE)
5968 {
5969 if (prop & ENC_2BYTE)
5970 {
5971 if (prop & ENC_ENDIAN_L)
5972 return FIO_UCS2 | FIO_ENDIAN_L;
5973 return FIO_UCS2;
5974 }
5975 if (prop & ENC_4BYTE)
5976 {
5977 if (prop & ENC_ENDIAN_L)
5978 return FIO_UCS4 | FIO_ENDIAN_L;
5979 return FIO_UCS4;
5980 }
5981 if (prop & ENC_2WORD)
5982 {
5983 if (prop & ENC_ENDIAN_L)
5984 return FIO_UTF16 | FIO_ENDIAN_L;
5985 return FIO_UTF16;
5986 }
5987 return FIO_UTF8;
5988 }
5989 if (prop & ENC_LATIN1)
5990 return FIO_LATIN1;
5991 /* must be ENC_DBCS, requires iconv() */
5992 return 0;
5993}
5994
5995#ifdef WIN3264
5996/*
5997 * Check "ptr" for a MS-Windows codepage name and return the FIO_ flags needed
5998 * for the conversion MS-Windows can do for us. Also accept "utf-8".
5999 * Used for conversion between 'encoding' and 'fileencoding'.
6000 */
6001 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006002get_win_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006003{
6004 int cp;
6005
6006 /* Cannot do this when 'encoding' is not utf-8 and not a codepage. */
6007 if (!enc_utf8 && enc_codepage <= 0)
6008 return 0;
6009
6010 cp = encname2codepage(ptr);
6011 if (cp == 0)
6012 {
6013# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
6014 if (STRCMP(ptr, "utf-8") == 0)
6015 cp = CP_UTF8;
6016 else
6017# endif
6018 return 0;
6019 }
6020 return FIO_PUT_CP(cp) | FIO_CODEPAGE;
6021}
6022#endif
6023
Bram Moolenaard0573012017-10-28 21:11:06 +02006024#ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00006025/*
6026 * Check "ptr" for a Carbon supported encoding and return the FIO_ flags
6027 * needed for the internal conversion to/from utf-8 or latin1.
6028 */
6029 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006030get_mac_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006031{
6032 if ((enc_utf8 || STRCMP(p_enc, "latin1") == 0)
6033 && (enc_canon_props(ptr) & ENC_MACROMAN))
6034 return FIO_MACROMAN;
6035 return 0;
6036}
6037#endif
6038
6039/*
6040 * Check for a Unicode BOM (Byte Order Mark) at the start of p[size].
6041 * "size" must be at least 2.
6042 * Return the name of the encoding and set "*lenp" to the length.
6043 * Returns NULL when no BOM found.
6044 */
6045 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006046check_for_bom(
6047 char_u *p,
6048 long size,
6049 int *lenp,
6050 int flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006051{
6052 char *name = NULL;
6053 int len = 2;
6054
6055 if (p[0] == 0xef && p[1] == 0xbb && size >= 3 && p[2] == 0xbf
Bram Moolenaaree0f5a62008-07-24 20:09:16 +00006056 && (flags == FIO_ALL || flags == FIO_UTF8 || flags == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006057 {
6058 name = "utf-8"; /* EF BB BF */
6059 len = 3;
6060 }
6061 else if (p[0] == 0xff && p[1] == 0xfe)
6062 {
6063 if (size >= 4 && p[2] == 0 && p[3] == 0
6064 && (flags == FIO_ALL || flags == (FIO_UCS4 | FIO_ENDIAN_L)))
6065 {
6066 name = "ucs-4le"; /* FF FE 00 00 */
6067 len = 4;
6068 }
Bram Moolenaar223a1892008-11-11 20:57:11 +00006069 else if (flags == (FIO_UCS2 | FIO_ENDIAN_L))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006070 name = "ucs-2le"; /* FF FE */
Bram Moolenaar223a1892008-11-11 20:57:11 +00006071 else if (flags == FIO_ALL || flags == (FIO_UTF16 | FIO_ENDIAN_L))
6072 /* utf-16le is preferred, it also works for ucs-2le text */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006073 name = "utf-16le"; /* FF FE */
6074 }
6075 else if (p[0] == 0xfe && p[1] == 0xff
6076 && (flags == FIO_ALL || flags == FIO_UCS2 || flags == FIO_UTF16))
6077 {
Bram Moolenaarffd82c52008-02-20 17:15:26 +00006078 /* Default to utf-16, it works also for ucs-2 text. */
6079 if (flags == FIO_UCS2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006080 name = "ucs-2"; /* FE FF */
Bram Moolenaarffd82c52008-02-20 17:15:26 +00006081 else
6082 name = "utf-16"; /* FE FF */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006083 }
6084 else if (size >= 4 && p[0] == 0 && p[1] == 0 && p[2] == 0xfe
6085 && p[3] == 0xff && (flags == FIO_ALL || flags == FIO_UCS4))
6086 {
6087 name = "ucs-4"; /* 00 00 FE FF */
6088 len = 4;
6089 }
6090
6091 *lenp = len;
6092 return (char_u *)name;
6093}
6094
6095/*
6096 * Generate a BOM in "buf[4]" for encoding "name".
6097 * Return the length of the BOM (zero when no BOM).
6098 */
6099 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006100make_bom(char_u *buf, char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006101{
6102 int flags;
6103 char_u *p;
6104
6105 flags = get_fio_flags(name);
6106
6107 /* Can't put a BOM in a non-Unicode file. */
6108 if (flags == FIO_LATIN1 || flags == 0)
6109 return 0;
6110
6111 if (flags == FIO_UTF8) /* UTF-8 */
6112 {
6113 buf[0] = 0xef;
6114 buf[1] = 0xbb;
6115 buf[2] = 0xbf;
6116 return 3;
6117 }
6118 p = buf;
6119 (void)ucs2bytes(0xfeff, &p, flags);
6120 return (int)(p - buf);
6121}
6122#endif
6123
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00006124#if defined(FEAT_VIMINFO) || defined(FEAT_BROWSE) || \
Bram Moolenaara0174af2008-01-02 20:08:25 +00006125 defined(FEAT_QUICKFIX) || defined(FEAT_AUTOCMD) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006126/*
6127 * Try to find a shortname by comparing the fullname with the current
6128 * directory.
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006129 * Returns "full_path" or pointer into "full_path" if shortened.
6130 */
6131 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006132shorten_fname1(char_u *full_path)
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006133{
Bram Moolenaard9462e32011-04-11 21:35:11 +02006134 char_u *dirname;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006135 char_u *p = full_path;
6136
Bram Moolenaard9462e32011-04-11 21:35:11 +02006137 dirname = alloc(MAXPATHL);
6138 if (dirname == NULL)
6139 return full_path;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006140 if (mch_dirname(dirname, MAXPATHL) == OK)
6141 {
6142 p = shorten_fname(full_path, dirname);
6143 if (p == NULL || *p == NUL)
6144 p = full_path;
6145 }
Bram Moolenaard9462e32011-04-11 21:35:11 +02006146 vim_free(dirname);
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006147 return p;
6148}
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00006149#endif
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006150
6151/*
6152 * Try to find a shortname by comparing the fullname with the current
6153 * directory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006154 * Returns NULL if not shorter name possible, pointer into "full_path"
6155 * otherwise.
6156 */
6157 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006158shorten_fname(char_u *full_path, char_u *dir_name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006159{
6160 int len;
6161 char_u *p;
6162
6163 if (full_path == NULL)
6164 return NULL;
6165 len = (int)STRLEN(dir_name);
6166 if (fnamencmp(dir_name, full_path, len) == 0)
6167 {
6168 p = full_path + len;
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006169#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006170 /*
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006171 * MSWIN: when a file is in the root directory, dir_name will end in a
Bram Moolenaar071d4272004-06-13 20:20:40 +00006172 * slash, since C: by itself does not define a specific dir. In this
6173 * case p may already be correct. <negri>
6174 */
6175 if (!((len > 2) && (*(p - 2) == ':')))
6176#endif
6177 {
6178 if (vim_ispathsep(*p))
6179 ++p;
6180#ifndef VMS /* the path separator is always part of the path */
6181 else
6182 p = NULL;
6183#endif
6184 }
6185 }
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006186#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006187 /*
6188 * When using a file in the current drive, remove the drive name:
6189 * "A:\dir\file" -> "\dir\file". This helps when moving a session file on
6190 * a floppy from "A:\dir" to "B:\dir".
6191 */
6192 else if (len > 3
6193 && TOUPPER_LOC(full_path[0]) == TOUPPER_LOC(dir_name[0])
6194 && full_path[1] == ':'
6195 && vim_ispathsep(full_path[2]))
6196 p = full_path + 2;
6197#endif
6198 else
6199 p = NULL;
6200 return p;
6201}
6202
6203/*
6204 * Shorten filenames for all buffers.
6205 * When "force" is TRUE: Use full path from now on for files currently being
6206 * edited, both for file name and swap file name. Try to shorten the file
6207 * names a bit, if safe to do so.
6208 * When "force" is FALSE: Only try to shorten absolute file names.
6209 * For buffers that have buftype "nofile" or "scratch": never change the file
6210 * name.
6211 */
6212 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006213shorten_fnames(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006214{
6215 char_u dirname[MAXPATHL];
6216 buf_T *buf;
6217 char_u *p;
6218
6219 mch_dirname(dirname, MAXPATHL);
Bram Moolenaar29323592016-07-24 22:04:11 +02006220 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006221 {
6222 if (buf->b_fname != NULL
6223#ifdef FEAT_QUICKFIX
6224 && !bt_nofile(buf)
6225#endif
6226 && !path_with_url(buf->b_fname)
6227 && (force
6228 || buf->b_sfname == NULL
6229 || mch_isFullName(buf->b_sfname)))
6230 {
6231 vim_free(buf->b_sfname);
6232 buf->b_sfname = NULL;
6233 p = shorten_fname(buf->b_ffname, dirname);
6234 if (p != NULL)
6235 {
6236 buf->b_sfname = vim_strsave(p);
6237 buf->b_fname = buf->b_sfname;
6238 }
6239 if (p == NULL || buf->b_fname == NULL)
6240 buf->b_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006241 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00006242
6243 /* Always make the swap file name a full path, a "nofile" buffer may
6244 * also have a swap file. */
6245 mf_fullname(buf->b_ml.ml_mfp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006246 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006247 status_redraw_all();
Bram Moolenaar49d7bf12006-02-17 21:45:41 +00006248 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006249}
6250
6251#if (defined(FEAT_DND) && defined(FEAT_GUI_GTK)) \
6252 || defined(FEAT_GUI_MSWIN) \
6253 || defined(FEAT_GUI_MAC) \
6254 || defined(PROTO)
6255/*
6256 * Shorten all filenames in "fnames[count]" by current directory.
6257 */
6258 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006259shorten_filenames(char_u **fnames, int count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006260{
6261 int i;
6262 char_u dirname[MAXPATHL];
6263 char_u *p;
6264
6265 if (fnames == NULL || count < 1)
6266 return;
6267 mch_dirname(dirname, sizeof(dirname));
6268 for (i = 0; i < count; ++i)
6269 {
6270 if ((p = shorten_fname(fnames[i], dirname)) != NULL)
6271 {
6272 /* shorten_fname() returns pointer in given "fnames[i]". If free
6273 * "fnames[i]" first, "p" becomes invalid. So we need to copy
6274 * "p" first then free fnames[i]. */
6275 p = vim_strsave(p);
6276 vim_free(fnames[i]);
6277 fnames[i] = p;
6278 }
6279 }
6280}
6281#endif
6282
6283/*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006284 * add extension to file name - change path/fo.o.h to path/fo.o.h.ext or
Bram Moolenaar071d4272004-06-13 20:20:40 +00006285 * fo_o_h.ext for MSDOS or when shortname option set.
6286 *
6287 * Assumed that fname is a valid name found in the filesystem we assure that
6288 * the return value is a different name and ends in 'ext'.
6289 * "ext" MUST be at most 4 characters long if it starts with a dot, 3
6290 * characters otherwise.
6291 * Space for the returned name is allocated, must be freed later.
6292 * Returns NULL when out of memory.
6293 */
6294 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006295modname(
6296 char_u *fname,
6297 char_u *ext,
6298 int prepend_dot) /* may prepend a '.' to file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006299{
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006300 return buf_modname((curbuf->b_p_sn || curbuf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00006301 fname, ext, prepend_dot);
6302}
6303
6304 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006305buf_modname(
6306 int shortname, /* use 8.3 file name */
6307 char_u *fname,
6308 char_u *ext,
6309 int prepend_dot) /* may prepend a '.' to file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006310{
6311 char_u *retval;
6312 char_u *s;
6313 char_u *e;
6314 char_u *ptr;
6315 int fnamelen, extlen;
6316
6317 extlen = (int)STRLEN(ext);
6318
6319 /*
6320 * If there is no file name we must get the name of the current directory
6321 * (we need the full path in case :cd is used).
6322 */
6323 if (fname == NULL || *fname == NUL)
6324 {
6325 retval = alloc((unsigned)(MAXPATHL + extlen + 3));
6326 if (retval == NULL)
6327 return NULL;
6328 if (mch_dirname(retval, MAXPATHL) == FAIL ||
6329 (fnamelen = (int)STRLEN(retval)) == 0)
6330 {
6331 vim_free(retval);
6332 return NULL;
6333 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006334 if (!after_pathsep(retval, retval + fnamelen))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006335 {
6336 retval[fnamelen++] = PATHSEP;
6337 retval[fnamelen] = NUL;
6338 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006339 prepend_dot = FALSE; /* nothing to prepend a dot to */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006340 }
6341 else
6342 {
6343 fnamelen = (int)STRLEN(fname);
6344 retval = alloc((unsigned)(fnamelen + extlen + 3));
6345 if (retval == NULL)
6346 return NULL;
6347 STRCPY(retval, fname);
6348#ifdef VMS
6349 vms_remove_version(retval); /* we do not need versions here */
6350#endif
6351 }
6352
6353 /*
6354 * search backwards until we hit a '/', '\' or ':' replacing all '.'
6355 * by '_' for MSDOS or when shortname option set and ext starts with a dot.
6356 * Then truncate what is after the '/', '\' or ':' to 8 characters for
6357 * MSDOS and 26 characters for AMIGA, a lot more for UNIX.
6358 */
Bram Moolenaar91acfff2017-03-12 19:22:36 +01006359 for (ptr = retval + fnamelen; ptr > retval; MB_PTR_BACK(retval, ptr))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006360 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006361 if (*ext == '.'
Bram Moolenaare60acc12011-05-10 16:41:25 +02006362#ifdef USE_LONG_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00006363 && (!USE_LONG_FNAME || shortname)
Bram Moolenaare60acc12011-05-10 16:41:25 +02006364#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006365 && shortname
Bram Moolenaare60acc12011-05-10 16:41:25 +02006366#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006367 )
6368 if (*ptr == '.') /* replace '.' by '_' */
6369 *ptr = '_';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006370 if (vim_ispathsep(*ptr))
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006371 {
6372 ++ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006373 break;
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006374 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006375 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006376
6377 /* the file name has at most BASENAMELEN characters. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006378 if (STRLEN(ptr) > (unsigned)BASENAMELEN)
6379 ptr[BASENAMELEN] = '\0';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006380
6381 s = ptr + STRLEN(ptr);
6382
6383 /*
6384 * For 8.3 file names we may have to reduce the length.
6385 */
6386#ifdef USE_LONG_FNAME
6387 if (!USE_LONG_FNAME || shortname)
6388#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006389 if (shortname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006390#endif
6391 {
6392 /*
6393 * If there is no file name, or the file name ends in '/', and the
6394 * extension starts with '.', put a '_' before the dot, because just
6395 * ".ext" is invalid.
6396 */
6397 if (fname == NULL || *fname == NUL
6398 || vim_ispathsep(fname[STRLEN(fname) - 1]))
6399 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006400 if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006401 *s++ = '_';
6402 }
6403 /*
6404 * If the extension starts with '.', truncate the base name at 8
6405 * characters
6406 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006407 else if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006408 {
Bram Moolenaar78a15312009-05-15 19:33:18 +00006409 if ((size_t)(s - ptr) > (size_t)8)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006410 {
6411 s = ptr + 8;
6412 *s = '\0';
6413 }
6414 }
6415 /*
6416 * If the extension doesn't start with '.', and the file name
6417 * doesn't have an extension yet, append a '.'
6418 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006419 else if ((e = vim_strchr(ptr, '.')) == NULL)
6420 *s++ = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006421 /*
6422 * If the extension doesn't start with '.', and there already is an
Bram Moolenaar7263a772007-05-10 17:35:54 +00006423 * extension, it may need to be truncated
Bram Moolenaar071d4272004-06-13 20:20:40 +00006424 */
6425 else if ((int)STRLEN(e) + extlen > 4)
6426 s = e + 4 - extlen;
6427 }
Bram Moolenaare7fedb62015-12-31 19:07:19 +01006428#if defined(USE_LONG_FNAME) || defined(WIN3264)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006429 /*
6430 * If there is no file name, and the extension starts with '.', put a
6431 * '_' before the dot, because just ".ext" may be invalid if it's on a
6432 * FAT partition, and on HPFS it doesn't matter.
6433 */
6434 else if ((fname == NULL || *fname == NUL) && *ext == '.')
6435 *s++ = '_';
6436#endif
6437
6438 /*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006439 * Append the extension.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006440 * ext can start with '.' and cannot exceed 3 more characters.
6441 */
6442 STRCPY(s, ext);
6443
Bram Moolenaar071d4272004-06-13 20:20:40 +00006444 /*
6445 * Prepend the dot.
6446 */
Bram Moolenaare60acc12011-05-10 16:41:25 +02006447 if (prepend_dot && !shortname && *(e = gettail(retval)) != '.'
Bram Moolenaar071d4272004-06-13 20:20:40 +00006448#ifdef USE_LONG_FNAME
6449 && USE_LONG_FNAME
6450#endif
6451 )
6452 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006453 STRMOVE(e + 1, e);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006454 *e = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006455 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006456
6457 /*
6458 * Check that, after appending the extension, the file name is really
6459 * different.
6460 */
6461 if (fname != NULL && STRCMP(fname, retval) == 0)
6462 {
6463 /* we search for a character that can be replaced by '_' */
6464 while (--s >= ptr)
6465 {
6466 if (*s != '_')
6467 {
6468 *s = '_';
6469 break;
6470 }
6471 }
6472 if (s < ptr) /* fname was "________.<ext>", how tricky! */
6473 *ptr = 'v';
6474 }
6475 return retval;
6476}
6477
6478/*
6479 * Like fgets(), but if the file line is too long, it is truncated and the
6480 * rest of the line is thrown away. Returns TRUE for end-of-file.
6481 */
6482 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006483vim_fgets(char_u *buf, int size, FILE *fp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006484{
6485 char *eof;
6486#define FGETS_SIZE 200
6487 char tbuf[FGETS_SIZE];
6488
6489 buf[size - 2] = NUL;
6490#ifdef USE_CR
6491 eof = fgets_cr((char *)buf, size, fp);
6492#else
6493 eof = fgets((char *)buf, size, fp);
6494#endif
6495 if (buf[size - 2] != NUL && buf[size - 2] != '\n')
6496 {
6497 buf[size - 1] = NUL; /* Truncate the line */
6498
6499 /* Now throw away the rest of the line: */
6500 do
6501 {
6502 tbuf[FGETS_SIZE - 2] = NUL;
6503#ifdef USE_CR
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006504 ignoredp = fgets_cr((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006505#else
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006506 ignoredp = fgets((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006507#endif
6508 } while (tbuf[FGETS_SIZE - 2] != NUL && tbuf[FGETS_SIZE - 2] != '\n');
6509 }
6510 return (eof == NULL);
6511}
6512
6513#if defined(USE_CR) || defined(PROTO)
6514/*
6515 * Like vim_fgets(), but accept any line terminator: CR, CR-LF or LF.
6516 * Returns TRUE for end-of-file.
6517 * Only used for the Mac, because it's much slower than vim_fgets().
6518 */
6519 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006520tag_fgets(char_u *buf, int size, FILE *fp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006521{
6522 int i = 0;
6523 int c;
6524 int eof = FALSE;
6525
6526 for (;;)
6527 {
6528 c = fgetc(fp);
6529 if (c == EOF)
6530 {
6531 eof = TRUE;
6532 break;
6533 }
6534 if (c == '\r')
6535 {
6536 /* Always store a NL for end-of-line. */
6537 if (i < size - 1)
6538 buf[i++] = '\n';
6539 c = fgetc(fp);
6540 if (c != '\n') /* Macintosh format: single CR. */
6541 ungetc(c, fp);
6542 break;
6543 }
6544 if (i < size - 1)
6545 buf[i++] = c;
6546 if (c == '\n')
6547 break;
6548 }
6549 buf[i] = NUL;
6550 return eof;
6551}
6552#endif
6553
6554/*
6555 * rename() only works if both files are on the same file system, this
6556 * function will (attempts to?) copy the file across if rename fails -- webb
6557 * Return -1 for failure, 0 for success.
6558 */
6559 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006560vim_rename(char_u *from, char_u *to)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006561{
6562 int fd_in;
6563 int fd_out;
6564 int n;
6565 char *errmsg = NULL;
6566 char *buffer;
6567#ifdef AMIGA
6568 BPTR flock;
6569#endif
Bram Moolenaar8767f522016-07-01 17:17:39 +02006570 stat_T st;
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006571 long perm;
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006572#ifdef HAVE_ACL
6573 vim_acl_T acl; /* ACL from original file */
6574#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006575 int use_tmp_file = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006576
6577 /*
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006578 * When the names are identical, there is nothing to do. When they refer
6579 * to the same file (ignoring case and slash/backslash differences) but
6580 * the file name differs we need to go through a temp file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006581 */
6582 if (fnamecmp(from, to) == 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006583 {
Bram Moolenaar71afbfe2013-03-19 16:49:16 +01006584 if (p_fic && STRCMP(gettail(from), gettail(to)) != 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006585 use_tmp_file = TRUE;
6586 else
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006587 return 0;
6588 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006589
6590 /*
6591 * Fail if the "from" file doesn't exist. Avoids that "to" is deleted.
6592 */
6593 if (mch_stat((char *)from, &st) < 0)
6594 return -1;
6595
Bram Moolenaar3576da72008-12-30 15:15:57 +00006596#ifdef UNIX
6597 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02006598 stat_T st_to;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006599
6600 /* It's possible for the source and destination to be the same file.
6601 * This happens when "from" and "to" differ in case and are on a FAT32
6602 * filesystem. In that case go through a temp file name. */
6603 if (mch_stat((char *)to, &st_to) >= 0
6604 && st.st_dev == st_to.st_dev
6605 && st.st_ino == st_to.st_ino)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006606 use_tmp_file = TRUE;
6607 }
6608#endif
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02006609#ifdef WIN3264
6610 {
6611 BY_HANDLE_FILE_INFORMATION info1, info2;
6612
6613 /* It's possible for the source and destination to be the same file.
6614 * In that case go through a temp file name. This makes rename("foo",
6615 * "./foo") a no-op (in a complicated way). */
6616 if (win32_fileinfo(from, &info1) == FILEINFO_OK
6617 && win32_fileinfo(to, &info2) == FILEINFO_OK
6618 && info1.dwVolumeSerialNumber == info2.dwVolumeSerialNumber
6619 && info1.nFileIndexHigh == info2.nFileIndexHigh
6620 && info1.nFileIndexLow == info2.nFileIndexLow)
6621 use_tmp_file = TRUE;
6622 }
6623#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006624
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006625 if (use_tmp_file)
6626 {
6627 char tempname[MAXPATHL + 1];
6628
6629 /*
6630 * Find a name that doesn't exist and is in the same directory.
6631 * Rename "from" to "tempname" and then rename "tempname" to "to".
6632 */
6633 if (STRLEN(from) >= MAXPATHL - 5)
6634 return -1;
6635 STRCPY(tempname, from);
6636 for (n = 123; n < 99999; ++n)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006637 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006638 sprintf((char *)gettail((char_u *)tempname), "%d", n);
6639 if (mch_stat(tempname, &st) < 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006640 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006641 if (mch_rename((char *)from, tempname) == 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006642 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006643 if (mch_rename(tempname, (char *)to) == 0)
6644 return 0;
6645 /* Strange, the second step failed. Try moving the
6646 * file back and return failure. */
6647 mch_rename(tempname, (char *)from);
Bram Moolenaar3576da72008-12-30 15:15:57 +00006648 return -1;
6649 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006650 /* If it fails for one temp name it will most likely fail
6651 * for any temp name, give up. */
6652 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006653 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006654 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006655 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006656 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006657
Bram Moolenaar071d4272004-06-13 20:20:40 +00006658 /*
6659 * Delete the "to" file, this is required on some systems to make the
6660 * mch_rename() work, on other systems it makes sure that we don't have
6661 * two files when the mch_rename() fails.
6662 */
6663
6664#ifdef AMIGA
6665 /*
6666 * With MSDOS-compatible filesystems (crossdos, messydos) it is possible
6667 * that the name of the "to" file is the same as the "from" file, even
Bram Moolenaar7263a772007-05-10 17:35:54 +00006668 * though the names are different. To avoid the chance of accidentally
Bram Moolenaar071d4272004-06-13 20:20:40 +00006669 * deleting the "from" file (horror!) we lock it during the remove.
6670 *
6671 * When used for making a backup before writing the file: This should not
6672 * happen with ":w", because startscript() should detect this problem and
6673 * set buf->b_shortname, causing modname() to return a correct ".bak" file
6674 * name. This problem does exist with ":w filename", but then the
6675 * original file will be somewhere else so the backup isn't really
6676 * important. If autoscripting is off the rename may fail.
6677 */
6678 flock = Lock((UBYTE *)from, (long)ACCESS_READ);
6679#endif
6680 mch_remove(to);
6681#ifdef AMIGA
6682 if (flock)
6683 UnLock(flock);
6684#endif
6685
6686 /*
6687 * First try a normal rename, return if it works.
6688 */
6689 if (mch_rename((char *)from, (char *)to) == 0)
6690 return 0;
6691
6692 /*
6693 * Rename() failed, try copying the file.
6694 */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006695 perm = mch_getperm(from);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006696#ifdef HAVE_ACL
6697 /* For systems that support ACL: get the ACL from the original file. */
6698 acl = mch_get_acl(from);
6699#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006700 fd_in = mch_open((char *)from, O_RDONLY|O_EXTRA, 0);
6701 if (fd_in == -1)
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006702 {
6703#ifdef HAVE_ACL
6704 mch_free_acl(acl);
6705#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006706 return -1;
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006707 }
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006708
6709 /* Create the new file with same permissions as the original. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00006710 fd_out = mch_open((char *)to,
6711 O_CREAT|O_EXCL|O_WRONLY|O_EXTRA|O_NOFOLLOW, (int)perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006712 if (fd_out == -1)
6713 {
6714 close(fd_in);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006715#ifdef HAVE_ACL
6716 mch_free_acl(acl);
6717#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006718 return -1;
6719 }
6720
6721 buffer = (char *)alloc(BUFSIZE);
6722 if (buffer == NULL)
6723 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006724 close(fd_out);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006725 close(fd_in);
6726#ifdef HAVE_ACL
6727 mch_free_acl(acl);
6728#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006729 return -1;
6730 }
6731
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01006732 while ((n = read_eintr(fd_in, buffer, BUFSIZE)) > 0)
6733 if (write_eintr(fd_out, buffer, n) != n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006734 {
6735 errmsg = _("E208: Error writing to \"%s\"");
6736 break;
6737 }
6738
6739 vim_free(buffer);
6740 close(fd_in);
6741 if (close(fd_out) < 0)
6742 errmsg = _("E209: Error closing \"%s\"");
6743 if (n < 0)
6744 {
6745 errmsg = _("E210: Error reading \"%s\"");
6746 to = from;
6747 }
Bram Moolenaar7263a772007-05-10 17:35:54 +00006748#ifndef UNIX /* for Unix mch_open() already set the permission */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006749 mch_setperm(to, perm);
Bram Moolenaarc6039d82005-12-02 00:44:04 +00006750#endif
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006751#ifdef HAVE_ACL
6752 mch_set_acl(to, acl);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006753 mch_free_acl(acl);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006754#endif
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02006755#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaare8747442013-11-12 18:09:29 +01006756 mch_copy_sec(from, to);
Bram Moolenaar0671de32013-11-12 05:12:03 +01006757#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006758 if (errmsg != NULL)
6759 {
6760 EMSG2(errmsg, to);
6761 return -1;
6762 }
6763 mch_remove(from);
6764 return 0;
6765}
6766
6767static int already_warned = FALSE;
6768
6769/*
6770 * Check if any not hidden buffer has been changed.
6771 * Postpone the check if there are characters in the stuff buffer, a global
6772 * command is being executed, a mapping is being executed or an autocommand is
6773 * busy.
6774 * Returns TRUE if some message was written (screen should be redrawn and
6775 * cursor positioned).
6776 */
6777 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006778check_timestamps(
6779 int focus) /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006780{
6781 buf_T *buf;
6782 int didit = 0;
6783 int n;
6784
6785 /* Don't check timestamps while system() or another low-level function may
6786 * cause us to lose and gain focus. */
6787 if (no_check_timestamps > 0)
6788 return FALSE;
6789
6790 /* Avoid doing a check twice. The OK/Reload dialog can cause a focus
6791 * event and we would keep on checking if the file is steadily growing.
6792 * Do check again after typing something. */
6793 if (focus && did_check_timestamps)
6794 {
6795 need_check_timestamps = TRUE;
6796 return FALSE;
6797 }
6798
6799 if (!stuff_empty() || global_busy || !typebuf_typed()
6800#ifdef FEAT_AUTOCMD
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006801 || autocmd_busy || curbuf_lock > 0 || allbuf_lock > 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00006802#endif
6803 )
6804 need_check_timestamps = TRUE; /* check later */
6805 else
6806 {
6807 ++no_wait_return;
6808 did_check_timestamps = TRUE;
6809 already_warned = FALSE;
Bram Moolenaar29323592016-07-24 22:04:11 +02006810 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006811 {
6812 /* Only check buffers in a window. */
6813 if (buf->b_nwindows > 0)
6814 {
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006815 bufref_T bufref;
6816
6817 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006818 n = buf_check_timestamp(buf, focus);
6819 if (didit < n)
6820 didit = n;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006821 if (n > 0 && !bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006822 {
6823 /* Autocommands have removed the buffer, start at the
6824 * first one again. */
6825 buf = firstbuf;
6826 continue;
6827 }
6828 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006829 }
6830 --no_wait_return;
6831 need_check_timestamps = FALSE;
6832 if (need_wait_return && didit == 2)
6833 {
6834 /* make sure msg isn't overwritten */
6835 msg_puts((char_u *)"\n");
6836 out_flush();
6837 }
6838 }
6839 return didit;
6840}
6841
6842/*
6843 * Move all the lines from buffer "frombuf" to buffer "tobuf".
6844 * Return OK or FAIL. When FAIL "tobuf" is incomplete and/or "frombuf" is not
6845 * empty.
6846 */
6847 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006848move_lines(buf_T *frombuf, buf_T *tobuf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006849{
6850 buf_T *tbuf = curbuf;
6851 int retval = OK;
6852 linenr_T lnum;
6853 char_u *p;
6854
6855 /* Copy the lines in "frombuf" to "tobuf". */
6856 curbuf = tobuf;
6857 for (lnum = 1; lnum <= frombuf->b_ml.ml_line_count; ++lnum)
6858 {
6859 p = vim_strsave(ml_get_buf(frombuf, lnum, FALSE));
6860 if (p == NULL || ml_append(lnum - 1, p, 0, FALSE) == FAIL)
6861 {
6862 vim_free(p);
6863 retval = FAIL;
6864 break;
6865 }
6866 vim_free(p);
6867 }
6868
6869 /* Delete all the lines in "frombuf". */
6870 if (retval != FAIL)
6871 {
6872 curbuf = frombuf;
Bram Moolenaar9460b9d2007-01-09 14:37:01 +00006873 for (lnum = curbuf->b_ml.ml_line_count; lnum > 0; --lnum)
6874 if (ml_delete(lnum, FALSE) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006875 {
6876 /* Oops! We could try putting back the saved lines, but that
6877 * might fail again... */
6878 retval = FAIL;
6879 break;
6880 }
6881 }
6882
6883 curbuf = tbuf;
6884 return retval;
6885}
6886
6887/*
6888 * Check if buffer "buf" has been changed.
6889 * Also check if the file for a new buffer unexpectedly appeared.
6890 * return 1 if a changed buffer was found.
6891 * return 2 if a message has been displayed.
6892 * return 0 otherwise.
6893 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006894 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006895buf_check_timestamp(
6896 buf_T *buf,
6897 int focus UNUSED) /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006898{
Bram Moolenaar8767f522016-07-01 17:17:39 +02006899 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006900 int stat_res;
6901 int retval = 0;
6902 char_u *path;
6903 char_u *tbuf;
6904 char *mesg = NULL;
Bram Moolenaar44ecf652005-03-07 23:09:59 +00006905 char *mesg2 = "";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006906 int helpmesg = FALSE;
6907 int reload = FALSE;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006908 char *reason;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006909#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6910 int can_reload = FALSE;
6911#endif
Bram Moolenaar8767f522016-07-01 17:17:39 +02006912 off_T orig_size = buf->b_orig_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006913 int orig_mode = buf->b_orig_mode;
6914#ifdef FEAT_GUI
6915 int save_mouse_correct = need_mouse_correct;
6916#endif
6917#ifdef FEAT_AUTOCMD
6918 static int busy = FALSE;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006919 int n;
6920 char_u *s;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006921 bufref_T bufref;
6922
6923 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006924#endif
6925
6926 /* If there is no file name, the buffer is not loaded, 'buftype' is
6927 * set, we are in the middle of a save or being called recursively: ignore
6928 * this buffer. */
6929 if (buf->b_ffname == NULL
6930 || buf->b_ml.ml_mfp == NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00006931 || *buf->b_p_bt != NUL
Bram Moolenaar071d4272004-06-13 20:20:40 +00006932 || buf->b_saving
6933#ifdef FEAT_AUTOCMD
6934 || busy
6935#endif
Bram Moolenaar009b2592004-10-24 19:18:58 +00006936#ifdef FEAT_NETBEANS_INTG
6937 || isNetbeansBuffer(buf)
6938#endif
Bram Moolenaar8cad9302017-08-12 14:32:32 +02006939#ifdef FEAT_TERMINAL
6940 || buf->b_term != NULL
6941#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006942 )
6943 return 0;
6944
6945 if ( !(buf->b_flags & BF_NOTEDITED)
6946 && buf->b_mtime != 0
6947 && ((stat_res = mch_stat((char *)buf->b_ffname, &st)) < 0
6948 || time_differs((long)st.st_mtime, buf->b_mtime)
Bram Moolenaara7611f62014-05-02 15:46:14 +02006949 || st.st_size != buf->b_orig_size
Bram Moolenaar071d4272004-06-13 20:20:40 +00006950#ifdef HAVE_ST_MODE
6951 || (int)st.st_mode != buf->b_orig_mode
6952#else
6953 || mch_getperm(buf->b_ffname) != buf->b_orig_mode
6954#endif
6955 ))
6956 {
6957 retval = 1;
6958
Bram Moolenaar316059c2006-01-14 21:18:42 +00006959 /* set b_mtime to stop further warnings (e.g., when executing
6960 * FileChangedShell autocmd) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006961 if (stat_res < 0)
6962 {
6963 buf->b_mtime = 0;
6964 buf->b_orig_size = 0;
6965 buf->b_orig_mode = 0;
6966 }
6967 else
6968 buf_store_time(buf, &st, buf->b_ffname);
6969
6970 /* Don't do anything for a directory. Might contain the file
6971 * explorer. */
6972 if (mch_isdir(buf->b_fname))
6973 ;
6974
6975 /*
6976 * If 'autoread' is set, the buffer has no changes and the file still
6977 * exists, reload the buffer. Use the buffer-local option value if it
6978 * was set, the global option value otherwise.
6979 */
6980 else if ((buf->b_p_ar >= 0 ? buf->b_p_ar : p_ar)
6981 && !bufIsChanged(buf) && stat_res >= 0)
6982 reload = TRUE;
6983 else
6984 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006985 if (stat_res < 0)
6986 reason = "deleted";
6987 else if (bufIsChanged(buf))
6988 reason = "conflict";
6989 else if (orig_size != buf->b_orig_size || buf_contents_changed(buf))
6990 reason = "changed";
6991 else if (orig_mode != buf->b_orig_mode)
6992 reason = "mode";
6993 else
6994 reason = "time";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006995
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006996#ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006997 /*
6998 * Only give the warning if there are no FileChangedShell
6999 * autocommands.
7000 * Avoid being called recursively by setting "busy".
7001 */
7002 busy = TRUE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00007003# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007004 set_vim_var_string(VV_FCS_REASON, (char_u *)reason, -1);
7005 set_vim_var_string(VV_FCS_CHOICE, (char_u *)"", -1);
Bram Moolenaar1e015462005-09-25 22:16:38 +00007006# endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00007007 ++allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007008 n = apply_autocmds(EVENT_FILECHANGEDSHELL,
7009 buf->b_fname, buf->b_fname, FALSE, buf);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00007010 --allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007011 busy = FALSE;
7012 if (n)
7013 {
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007014 if (!bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007015 EMSG(_("E246: FileChangedShell autocommand deleted buffer"));
Bram Moolenaar1e015462005-09-25 22:16:38 +00007016# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007017 s = get_vim_var_str(VV_FCS_CHOICE);
7018 if (STRCMP(s, "reload") == 0 && *reason != 'd')
7019 reload = TRUE;
7020 else if (STRCMP(s, "ask") == 0)
7021 n = FALSE;
7022 else
Bram Moolenaar1e015462005-09-25 22:16:38 +00007023# endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007024 return 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007025 }
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007026 if (!n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007027#endif
7028 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007029 if (*reason == 'd')
7030 mesg = _("E211: File \"%s\" no longer available");
Bram Moolenaar071d4272004-06-13 20:20:40 +00007031 else
7032 {
7033 helpmesg = TRUE;
7034#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
7035 can_reload = TRUE;
7036#endif
7037 /*
7038 * Check if the file contents really changed to avoid
7039 * giving a warning when only the timestamp was set (e.g.,
7040 * checked out of CVS). Always warn when the buffer was
7041 * changed.
7042 */
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007043 if (reason[2] == 'n')
7044 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007045 mesg = _("W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007046 mesg2 = _("See \":help W12\" for more info.");
7047 }
7048 else if (reason[1] == 'h')
7049 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007050 mesg = _("W11: Warning: File \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007051 mesg2 = _("See \":help W11\" for more info.");
7052 }
7053 else if (*reason == 'm')
7054 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007055 mesg = _("W16: Warning: Mode of file \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007056 mesg2 = _("See \":help W16\" for more info.");
7057 }
Bram Moolenaar85388b52009-06-24 09:58:32 +00007058 else
7059 /* Only timestamp changed, store it to avoid a warning
7060 * in check_mtime() later. */
7061 buf->b_mtime_read = buf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007062 }
7063 }
7064 }
7065
7066 }
7067 else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W)
7068 && vim_fexists(buf->b_ffname))
7069 {
7070 retval = 1;
7071 mesg = _("W13: Warning: File \"%s\" has been created after editing started");
7072 buf->b_flags |= BF_NEW_W;
7073#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
7074 can_reload = TRUE;
7075#endif
7076 }
7077
7078 if (mesg != NULL)
7079 {
7080 path = home_replace_save(buf, buf->b_fname);
7081 if (path != NULL)
7082 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007083 if (!helpmesg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007084 mesg2 = "";
7085 tbuf = alloc((unsigned)(STRLEN(path) + STRLEN(mesg)
7086 + STRLEN(mesg2) + 2));
7087 sprintf((char *)tbuf, mesg, path);
Bram Moolenaar496c5262009-03-18 14:42:00 +00007088#ifdef FEAT_EVAL
7089 /* Set warningmsg here, before the unimportant and output-specific
7090 * mesg2 has been appended. */
7091 set_vim_var_string(VV_WARNINGMSG, tbuf, -1);
7092#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007093#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
7094 if (can_reload)
7095 {
7096 if (*mesg2 != NUL)
7097 {
7098 STRCAT(tbuf, "\n");
7099 STRCAT(tbuf, mesg2);
7100 }
7101 if (do_dialog(VIM_WARNING, (char_u *)_("Warning"), tbuf,
Bram Moolenaard2c340a2011-01-17 20:08:11 +01007102 (char_u *)_("&OK\n&Load File"), 1, NULL, TRUE) == 2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007103 reload = TRUE;
7104 }
7105 else
7106#endif
7107 if (State > NORMAL_BUSY || (State & CMDLINE) || already_warned)
7108 {
7109 if (*mesg2 != NUL)
7110 {
7111 STRCAT(tbuf, "; ");
7112 STRCAT(tbuf, mesg2);
7113 }
7114 EMSG(tbuf);
7115 retval = 2;
7116 }
7117 else
7118 {
Bram Moolenaared203462004-06-16 11:19:22 +00007119# ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00007120 if (!autocmd_busy)
Bram Moolenaared203462004-06-16 11:19:22 +00007121# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007122 {
7123 msg_start();
Bram Moolenaar8820b482017-03-16 17:23:31 +01007124 msg_puts_attr(tbuf, HL_ATTR(HLF_E) + MSG_HIST);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007125 if (*mesg2 != NUL)
7126 msg_puts_attr((char_u *)mesg2,
Bram Moolenaar8820b482017-03-16 17:23:31 +01007127 HL_ATTR(HLF_W) + MSG_HIST);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007128 msg_clr_eos();
7129 (void)msg_end();
7130 if (emsg_silent == 0)
7131 {
7132 out_flush();
Bram Moolenaared203462004-06-16 11:19:22 +00007133# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00007134 if (!focus)
Bram Moolenaared203462004-06-16 11:19:22 +00007135# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007136 /* give the user some time to think about it */
7137 ui_delay(1000L, TRUE);
7138
7139 /* don't redraw and erase the message */
7140 redraw_cmdline = FALSE;
7141 }
7142 }
7143 already_warned = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007144 }
7145
7146 vim_free(path);
7147 vim_free(tbuf);
7148 }
7149 }
7150
7151 if (reload)
Bram Moolenaar465748e2012-08-29 18:50:54 +02007152 {
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007153 /* Reload the buffer. */
Bram Moolenaar316059c2006-01-14 21:18:42 +00007154 buf_reload(buf, orig_mode);
Bram Moolenaar465748e2012-08-29 18:50:54 +02007155#ifdef FEAT_PERSISTENT_UNDO
7156 if (buf->b_p_udf && buf->b_ffname != NULL)
7157 {
7158 char_u hash[UNDO_HASH_SIZE];
7159 buf_T *save_curbuf = curbuf;
7160
7161 /* Any existing undo file is unusable, write it now. */
7162 curbuf = buf;
7163 u_compute_hash(hash);
7164 u_write_undo(NULL, FALSE, buf, hash);
7165 curbuf = save_curbuf;
7166 }
7167#endif
7168 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007169
Bram Moolenaar56718732006-03-15 22:53:57 +00007170#ifdef FEAT_AUTOCMD
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00007171 /* Trigger FileChangedShell when the file was changed in any way. */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007172 if (bufref_valid(&bufref) && retval != 0)
Bram Moolenaar56718732006-03-15 22:53:57 +00007173 (void)apply_autocmds(EVENT_FILECHANGEDSHELLPOST,
7174 buf->b_fname, buf->b_fname, FALSE, buf);
7175#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007176#ifdef FEAT_GUI
7177 /* restore this in case an autocommand has set it; it would break
7178 * 'mousefocus' */
7179 need_mouse_correct = save_mouse_correct;
7180#endif
7181
7182 return retval;
7183}
7184
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007185/*
7186 * Reload a buffer that is already loaded.
7187 * Used when the file was changed outside of Vim.
Bram Moolenaar316059c2006-01-14 21:18:42 +00007188 * "orig_mode" is buf->b_orig_mode before the need for reloading was detected.
7189 * buf->b_orig_mode may have been reset already.
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007190 */
7191 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007192buf_reload(buf_T *buf, int orig_mode)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007193{
7194 exarg_T ea;
7195 pos_T old_cursor;
7196 linenr_T old_topline;
7197 int old_ro = buf->b_p_ro;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007198 buf_T *savebuf;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007199 bufref_T bufref;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007200 int saved = OK;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007201 aco_save_T aco;
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007202 int flags = READ_NEW;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007203
7204 /* set curwin/curbuf for "buf" and save some things */
7205 aucmd_prepbuf(&aco, buf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007206
7207 /* We only want to read the text from the file, not reset the syntax
7208 * highlighting, clear marks, diff status, etc. Force the fileformat
7209 * and encoding to be the same. */
7210 if (prep_exarg(&ea, buf) == OK)
7211 {
7212 old_cursor = curwin->w_cursor;
7213 old_topline = curwin->w_topline;
7214
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007215 if (p_ur < 0 || curbuf->b_ml.ml_line_count <= p_ur)
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007216 {
7217 /* Save all the text, so that the reload can be undone.
7218 * Sync first so that this is a separate undo-able action. */
7219 u_sync(FALSE);
7220 saved = u_savecommon(0, curbuf->b_ml.ml_line_count + 1, 0, TRUE);
7221 flags |= READ_KEEP_UNDO;
7222 }
7223
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007224 /*
7225 * To behave like when a new file is edited (matters for
7226 * BufReadPost autocommands) we first need to delete the current
7227 * buffer contents. But if reading the file fails we should keep
7228 * the old contents. Can't use memory only, the file might be
7229 * too big. Use a hidden buffer to move the buffer contents to.
7230 */
Bram Moolenaarb5aedf32017-03-12 18:23:53 +01007231 if (BUFEMPTY() || saved == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007232 savebuf = NULL;
7233 else
7234 {
7235 /* Allocate a buffer without putting it in the buffer list. */
7236 savebuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007237 set_bufref(&bufref, savebuf);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007238 if (savebuf != NULL && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007239 {
7240 /* Open the memline. */
7241 curbuf = savebuf;
7242 curwin->w_buffer = savebuf;
Bram Moolenaar4770d092006-01-12 23:22:24 +00007243 saved = ml_open(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007244 curbuf = buf;
7245 curwin->w_buffer = buf;
7246 }
Bram Moolenaar8424a622006-04-19 21:23:36 +00007247 if (savebuf == NULL || saved == FAIL || buf != curbuf
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007248 || move_lines(buf, savebuf) == FAIL)
7249 {
7250 EMSG2(_("E462: Could not prepare for reloading \"%s\""),
7251 buf->b_fname);
7252 saved = FAIL;
7253 }
7254 }
7255
7256 if (saved == OK)
7257 {
7258 curbuf->b_flags |= BF_CHECK_RO; /* check for RO again */
7259#ifdef FEAT_AUTOCMD
7260 keep_filetype = TRUE; /* don't detect 'filetype' */
7261#endif
7262 if (readfile(buf->b_ffname, buf->b_fname, (linenr_T)0,
7263 (linenr_T)0,
Bram Moolenaare13b9af2017-01-13 22:01:02 +01007264 (linenr_T)MAXLNUM, &ea, flags) != OK)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007265 {
7266#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
7267 if (!aborting())
7268#endif
7269 EMSG2(_("E321: Could not reload \"%s\""), buf->b_fname);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007270 if (savebuf != NULL && bufref_valid(&bufref) && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007271 {
7272 /* Put the text back from the save buffer. First
7273 * delete any lines that readfile() added. */
Bram Moolenaarb5aedf32017-03-12 18:23:53 +01007274 while (!BUFEMPTY())
Bram Moolenaar8424a622006-04-19 21:23:36 +00007275 if (ml_delete(buf->b_ml.ml_line_count, FALSE) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007276 break;
7277 (void)move_lines(savebuf, buf);
7278 }
7279 }
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007280 else if (buf == curbuf) /* "buf" still valid */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007281 {
7282 /* Mark the buffer as unmodified and free undo info. */
7283 unchanged(buf, TRUE);
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007284 if ((flags & READ_KEEP_UNDO) == 0)
7285 {
7286 u_blockfree(buf);
7287 u_clearall(buf);
7288 }
7289 else
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007290 {
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007291 /* Mark all undo states as changed. */
7292 u_unchanged(curbuf);
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007293 }
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007294 }
7295 }
7296 vim_free(ea.cmd);
7297
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007298 if (savebuf != NULL && bufref_valid(&bufref))
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007299 wipe_buffer(savebuf, FALSE);
7300
7301#ifdef FEAT_DIFF
7302 /* Invalidate diff info if necessary. */
Bram Moolenaar8424a622006-04-19 21:23:36 +00007303 diff_invalidate(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007304#endif
7305
7306 /* Restore the topline and cursor position and check it (lines may
7307 * have been removed). */
7308 if (old_topline > curbuf->b_ml.ml_line_count)
7309 curwin->w_topline = curbuf->b_ml.ml_line_count;
7310 else
7311 curwin->w_topline = old_topline;
7312 curwin->w_cursor = old_cursor;
7313 check_cursor();
7314 update_topline();
7315#ifdef FEAT_AUTOCMD
7316 keep_filetype = FALSE;
7317#endif
7318#ifdef FEAT_FOLDING
7319 {
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007320 win_T *wp;
7321 tabpage_T *tp;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007322
7323 /* Update folds unless they are defined manually. */
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007324 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007325 if (wp->w_buffer == curwin->w_buffer
7326 && !foldmethodIsManual(wp))
7327 foldUpdateAll(wp);
7328 }
7329#endif
7330 /* If the mode didn't change and 'readonly' was set, keep the old
7331 * value; the user probably used the ":view" command. But don't
7332 * reset it, might have had a read error. */
7333 if (orig_mode == curbuf->b_orig_mode)
7334 curbuf->b_p_ro |= old_ro;
Bram Moolenaar52f85b72013-01-30 14:13:56 +01007335
7336 /* Modelines must override settings done by autocommands. */
7337 do_modelines(0);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007338 }
7339
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007340 /* restore curwin/curbuf and a few other things */
7341 aucmd_restbuf(&aco);
7342 /* Careful: autocommands may have made "buf" invalid! */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007343}
7344
Bram Moolenaar071d4272004-06-13 20:20:40 +00007345 void
Bram Moolenaar8767f522016-07-01 17:17:39 +02007346buf_store_time(buf_T *buf, stat_T *st, char_u *fname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007347{
7348 buf->b_mtime = (long)st->st_mtime;
Bram Moolenaar914703b2010-05-31 21:59:46 +02007349 buf->b_orig_size = st->st_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007350#ifdef HAVE_ST_MODE
7351 buf->b_orig_mode = (int)st->st_mode;
7352#else
7353 buf->b_orig_mode = mch_getperm(fname);
7354#endif
7355}
7356
7357/*
7358 * Adjust the line with missing eol, used for the next write.
7359 * Used for do_filter(), when the input lines for the filter are deleted.
7360 */
7361 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007362write_lnum_adjust(linenr_T offset)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007363{
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01007364 if (curbuf->b_no_eol_lnum != 0) /* only if there is a missing eol */
7365 curbuf->b_no_eol_lnum += offset;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007366}
7367
Bram Moolenaarda440d22016-01-16 21:27:23 +01007368#if defined(TEMPDIRNAMES) || defined(FEAT_EVAL) || defined(PROTO)
7369/*
7370 * Delete "name" and everything in it, recursively.
7371 * return 0 for succes, -1 if some file was not deleted.
7372 */
7373 int
7374delete_recursive(char_u *name)
7375{
7376 int result = 0;
7377 char_u **files;
7378 int file_count;
7379 int i;
7380 char_u *exp;
7381
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007382 /* A symbolic link to a directory itself is deleted, not the directory it
7383 * points to. */
7384 if (
Bram Moolenaar203258c2016-01-17 22:15:16 +01007385# if defined(UNIX) || defined(WIN32)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007386 mch_isrealdir(name)
Bram Moolenaar203258c2016-01-17 22:15:16 +01007387# else
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007388 mch_isdir(name)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007389# endif
7390 )
Bram Moolenaarda440d22016-01-16 21:27:23 +01007391 {
7392 vim_snprintf((char *)NameBuff, MAXPATHL, "%s/*", name);
7393 exp = vim_strsave(NameBuff);
7394 if (exp == NULL)
7395 return -1;
7396 if (gen_expand_wildcards(1, &exp, &file_count, &files,
Bram Moolenaar336bd622016-01-17 18:23:58 +01007397 EW_DIR|EW_FILE|EW_SILENT|EW_ALLLINKS|EW_DODOT|EW_EMPTYOK) == OK)
Bram Moolenaarda440d22016-01-16 21:27:23 +01007398 {
7399 for (i = 0; i < file_count; ++i)
7400 if (delete_recursive(files[i]) != 0)
7401 result = -1;
7402 FreeWild(file_count, files);
7403 }
7404 else
7405 result = -1;
7406 vim_free(exp);
7407 (void)mch_rmdir(name);
7408 }
7409 else
7410 result = mch_remove(name) == 0 ? 0 : -1;
7411
7412 return result;
7413}
7414#endif
7415
Bram Moolenaar071d4272004-06-13 20:20:40 +00007416#if defined(TEMPDIRNAMES) || defined(PROTO)
7417static long temp_count = 0; /* Temp filename counter. */
7418
7419/*
7420 * Delete the temp directory and all files it contains.
7421 */
7422 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007423vim_deltempdir(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007424{
Bram Moolenaar071d4272004-06-13 20:20:40 +00007425 if (vim_tempdir != NULL)
7426 {
Bram Moolenaarda440d22016-01-16 21:27:23 +01007427 /* remove the trailing path separator */
7428 gettail(vim_tempdir)[-1] = NUL;
7429 delete_recursive(vim_tempdir);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007430 vim_free(vim_tempdir);
7431 vim_tempdir = NULL;
7432 }
7433}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007434
7435/*
Bram Moolenaareaf03392009-11-17 11:08:52 +00007436 * Directory "tempdir" was created. Expand this name to a full path and put
7437 * it in "vim_tempdir". This avoids that using ":cd" would confuse us.
7438 * "tempdir" must be no longer than MAXPATHL.
7439 */
7440 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007441vim_settempdir(char_u *tempdir)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007442{
7443 char_u *buf;
7444
7445 buf = alloc((unsigned)MAXPATHL + 2);
7446 if (buf != NULL)
7447 {
7448 if (vim_FullName(tempdir, buf, MAXPATHL, FALSE) == FAIL)
7449 STRCPY(buf, tempdir);
Bram Moolenaara06ecab2016-07-16 14:47:36 +02007450 add_pathsep(buf);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007451 vim_tempdir = vim_strsave(buf);
7452 vim_free(buf);
7453 }
7454}
Bram Moolenaar4592dee2009-11-18 19:11:58 +00007455#endif
Bram Moolenaareaf03392009-11-17 11:08:52 +00007456
7457/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007458 * vim_tempname(): Return a unique name that can be used for a temp file.
7459 *
Bram Moolenaar76ae22f2016-06-13 20:00:29 +02007460 * The temp file is NOT guaranteed to be created. If "keep" is FALSE it is
7461 * guaranteed to NOT be created.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007462 *
7463 * The returned pointer is to allocated memory.
7464 * The returned pointer is NULL if no valid name was found.
7465 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007466 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007467vim_tempname(
7468 int extra_char UNUSED, /* char to use in the name instead of '?' */
7469 int keep UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007470{
7471#ifdef USE_TMPNAM
7472 char_u itmp[L_tmpnam]; /* use tmpnam() */
7473#else
7474 char_u itmp[TEMPNAMELEN];
7475#endif
7476
7477#ifdef TEMPDIRNAMES
7478 static char *(tempdirs[]) = {TEMPDIRNAMES};
7479 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007480# ifndef EEXIST
Bram Moolenaar8767f522016-07-01 17:17:39 +02007481 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007482# endif
7483
7484 /*
7485 * This will create a directory for private use by this instance of Vim.
7486 * This is done once, and the same directory is used for all temp files.
7487 * This method avoids security problems because of symlink attacks et al.
7488 * It's also a bit faster, because we only need to check for an existing
7489 * file when creating the directory and not for each temp file.
7490 */
7491 if (vim_tempdir == NULL)
7492 {
7493 /*
7494 * Try the entries in TEMPDIRNAMES to create the temp directory.
7495 */
Bram Moolenaar78a15312009-05-15 19:33:18 +00007496 for (i = 0; i < (int)(sizeof(tempdirs) / sizeof(char *)); ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007497 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007498# ifndef HAVE_MKDTEMP
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007499 size_t itmplen;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007500 long nr;
7501 long off;
7502# endif
7503
Bram Moolenaare1a61992015-12-03 21:02:27 +01007504 /* Expand $TMP, leave room for "/v1100000/999999999".
7505 * Skip the directory check if the expansion fails. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007506 expand_env((char_u *)tempdirs[i], itmp, TEMPNAMELEN - 20);
Bram Moolenaare1a61992015-12-03 21:02:27 +01007507 if (itmp[0] != '$' && mch_isdir(itmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007508 {
Bram Moolenaare1a61992015-12-03 21:02:27 +01007509 /* directory exists */
Bram Moolenaara06ecab2016-07-16 14:47:36 +02007510 add_pathsep(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007511
Bram Moolenaareaf03392009-11-17 11:08:52 +00007512# ifdef HAVE_MKDTEMP
Bram Moolenaar35d88f42016-06-04 14:52:00 +02007513 {
7514# if defined(UNIX) || defined(VMS)
7515 /* Make sure the umask doesn't remove the executable bit.
7516 * "repl" has been reported to use "177". */
7517 mode_t umask_save = umask(077);
7518# endif
7519 /* Leave room for filename */
7520 STRCAT(itmp, "vXXXXXX");
7521 if (mkdtemp((char *)itmp) != NULL)
7522 vim_settempdir(itmp);
7523# if defined(UNIX) || defined(VMS)
7524 (void)umask(umask_save);
7525# endif
7526 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007527# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007528 /* Get an arbitrary number of up to 6 digits. When it's
7529 * unlikely that it already exists it will be faster,
7530 * otherwise it doesn't matter. The use of mkdir() avoids any
7531 * security problems because of the predictable number. */
7532 nr = (mch_get_pid() + (long)time(NULL)) % 1000000L;
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007533 itmplen = STRLEN(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007534
7535 /* Try up to 10000 different values until we find a name that
7536 * doesn't exist. */
7537 for (off = 0; off < 10000L; ++off)
7538 {
7539 int r;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007540# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007541 mode_t umask_save;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007542# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007543
Bram Moolenaareaf03392009-11-17 11:08:52 +00007544 sprintf((char *)itmp + itmplen, "v%ld", nr + off);
7545# ifndef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007546 /* If mkdir() does not set errno to EEXIST, check for
7547 * existing file here. There is a race condition then,
7548 * although it's fail-safe. */
7549 if (mch_stat((char *)itmp, &st) >= 0)
7550 continue;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007551# endif
7552# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007553 /* Make sure the umask doesn't remove the executable bit.
7554 * "repl" has been reported to use "177". */
7555 umask_save = umask(077);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007556# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007557 r = vim_mkdir(itmp, 0700);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007558# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007559 (void)umask(umask_save);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007560# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007561 if (r == 0)
7562 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007563 vim_settempdir(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007564 break;
7565 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007566# ifdef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007567 /* If the mkdir() didn't fail because the file/dir exists,
7568 * we probably can't create any dir here, try another
7569 * place. */
7570 if (errno != EEXIST)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007571# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007572 break;
7573 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007574# endif /* HAVE_MKDTEMP */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007575 if (vim_tempdir != NULL)
7576 break;
7577 }
7578 }
7579 }
7580
7581 if (vim_tempdir != NULL)
7582 {
7583 /* There is no need to check if the file exists, because we own the
7584 * directory and nobody else creates a file in it. */
7585 sprintf((char *)itmp, "%s%ld", vim_tempdir, temp_count++);
7586 return vim_strsave(itmp);
7587 }
7588
7589 return NULL;
7590
7591#else /* TEMPDIRNAMES */
7592
7593# ifdef WIN3264
7594 char szTempFile[_MAX_PATH + 1];
7595 char buf4[4];
7596 char_u *retval;
7597 char_u *p;
7598
7599 STRCPY(itmp, "");
7600 if (GetTempPath(_MAX_PATH, szTempFile) == 0)
Bram Moolenaarb1891912011-02-09 14:47:03 +01007601 {
7602 szTempFile[0] = '.'; /* GetTempPath() failed, use current dir */
7603 szTempFile[1] = NUL;
7604 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007605 strcpy(buf4, "VIM");
7606 buf4[2] = extra_char; /* make it "VIa", "VIb", etc. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007607 if (GetTempFileName(szTempFile, buf4, 0, (LPSTR)itmp) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007608 return NULL;
Bram Moolenaare5c421c2015-03-31 13:33:08 +02007609 if (!keep)
7610 /* GetTempFileName() will create the file, we don't want that */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007611 (void)DeleteFile((LPSTR)itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007612
7613 /* Backslashes in a temp file name cause problems when filtering with
7614 * "sh". NOTE: This also checks 'shellcmdflag' to help those people who
7615 * didn't set 'shellslash'. */
7616 retval = vim_strsave(itmp);
7617 if (*p_shcf == '-' || p_ssl)
7618 for (p = retval; *p; ++p)
7619 if (*p == '\\')
7620 *p = '/';
7621 return retval;
7622
7623# else /* WIN3264 */
7624
7625# ifdef USE_TMPNAM
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007626 char_u *p;
7627
Bram Moolenaar071d4272004-06-13 20:20:40 +00007628 /* tmpnam() will make its own name */
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007629 p = tmpnam((char *)itmp);
7630 if (p == NULL || *p == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007631 return NULL;
7632# else
7633 char_u *p;
7634
7635# ifdef VMS_TEMPNAM
7636 /* mktemp() is not working on VMS. It seems to be
7637 * a do-nothing function. Therefore we use tempnam().
7638 */
7639 sprintf((char *)itmp, "VIM%c", extra_char);
7640 p = (char_u *)tempnam("tmp:", (char *)itmp);
7641 if (p != NULL)
7642 {
Bram Moolenaar206f0112014-03-12 16:51:55 +01007643 /* VMS will use '.LIS' if we don't explicitly specify an extension,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007644 * and VIM will then be unable to find the file later */
7645 STRCPY(itmp, p);
7646 STRCAT(itmp, ".txt");
7647 free(p);
7648 }
7649 else
7650 return NULL;
7651# else
7652 STRCPY(itmp, TEMPNAME);
7653 if ((p = vim_strchr(itmp, '?')) != NULL)
7654 *p = extra_char;
7655 if (mktemp((char *)itmp) == NULL)
7656 return NULL;
7657# endif
7658# endif
7659
7660 return vim_strsave(itmp);
7661# endif /* WIN3264 */
7662#endif /* TEMPDIRNAMES */
7663}
7664
7665#if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
7666/*
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02007667 * Convert all backslashes in fname to forward slashes in-place, unless when
7668 * it looks like a URL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007669 */
7670 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007671forward_slash(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007672{
7673 char_u *p;
7674
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02007675 if (path_with_url(fname))
7676 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007677 for (p = fname; *p != NUL; ++p)
7678# ifdef FEAT_MBYTE
7679 /* The Big5 encoding can have '\' in the trail byte. */
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00007680 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007681 ++p;
7682 else
7683# endif
7684 if (*p == '\\')
7685 *p = '/';
7686}
7687#endif
7688
7689
7690/*
7691 * Code for automatic commands.
7692 *
7693 * Only included when "FEAT_AUTOCMD" has been defined.
7694 */
7695
7696#if defined(FEAT_AUTOCMD) || defined(PROTO)
7697
7698/*
7699 * The autocommands are stored in a list for each event.
7700 * Autocommands for the same pattern, that are consecutive, are joined
7701 * together, to avoid having to match the pattern too often.
7702 * The result is an array of Autopat lists, which point to AutoCmd lists:
7703 *
Bram Moolenaar462455e2017-11-10 21:53:11 +01007704 * last_autopat[0] -----------------------------+
7705 * V
Bram Moolenaar071d4272004-06-13 20:20:40 +00007706 * first_autopat[0] --> Autopat.next --> Autopat.next --> NULL
7707 * Autopat.cmds Autopat.cmds
7708 * | |
7709 * V V
7710 * AutoCmd.next AutoCmd.next
7711 * | |
7712 * V V
7713 * AutoCmd.next NULL
7714 * |
7715 * V
7716 * NULL
7717 *
Bram Moolenaar462455e2017-11-10 21:53:11 +01007718 * last_autopat[1] --------+
7719 * V
Bram Moolenaar071d4272004-06-13 20:20:40 +00007720 * first_autopat[1] --> Autopat.next --> NULL
7721 * Autopat.cmds
7722 * |
7723 * V
7724 * AutoCmd.next
7725 * |
7726 * V
7727 * NULL
7728 * etc.
7729 *
7730 * The order of AutoCmds is important, this is the order in which they were
7731 * defined and will have to be executed.
7732 */
7733typedef struct AutoCmd
7734{
7735 char_u *cmd; /* The command to be executed (NULL
7736 when command has been removed) */
7737 char nested; /* If autocommands nest here */
7738 char last; /* last command in list */
7739#ifdef FEAT_EVAL
7740 scid_T scriptID; /* script ID where defined */
7741#endif
7742 struct AutoCmd *next; /* Next AutoCmd in list */
7743} AutoCmd;
7744
7745typedef struct AutoPat
7746{
Bram Moolenaar462455e2017-11-10 21:53:11 +01007747 struct AutoPat *next; /* next AutoPat in AutoPat list; MUST
7748 * be the first entry */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007749 char_u *pat; /* pattern as typed (NULL when pattern
7750 has been removed) */
Bram Moolenaar748bf032005-02-02 23:04:36 +00007751 regprog_T *reg_prog; /* compiled regprog for pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007752 AutoCmd *cmds; /* list of commands to do */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007753 int group; /* group ID */
7754 int patlen; /* strlen() of pat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007755 int buflocal_nr; /* !=0 for buffer-local AutoPat */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007756 char allow_dirs; /* Pattern may match whole path */
7757 char last; /* last pattern for apply_autocmds() */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007758} AutoPat;
7759
7760static struct event_name
7761{
7762 char *name; /* event name */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007763 event_T event; /* event number */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007764} event_names[] =
7765{
7766 {"BufAdd", EVENT_BUFADD},
7767 {"BufCreate", EVENT_BUFADD},
7768 {"BufDelete", EVENT_BUFDELETE},
7769 {"BufEnter", EVENT_BUFENTER},
7770 {"BufFilePost", EVENT_BUFFILEPOST},
7771 {"BufFilePre", EVENT_BUFFILEPRE},
7772 {"BufHidden", EVENT_BUFHIDDEN},
7773 {"BufLeave", EVENT_BUFLEAVE},
7774 {"BufNew", EVENT_BUFNEW},
7775 {"BufNewFile", EVENT_BUFNEWFILE},
7776 {"BufRead", EVENT_BUFREADPOST},
7777 {"BufReadCmd", EVENT_BUFREADCMD},
7778 {"BufReadPost", EVENT_BUFREADPOST},
7779 {"BufReadPre", EVENT_BUFREADPRE},
7780 {"BufUnload", EVENT_BUFUNLOAD},
7781 {"BufWinEnter", EVENT_BUFWINENTER},
7782 {"BufWinLeave", EVENT_BUFWINLEAVE},
7783 {"BufWipeout", EVENT_BUFWIPEOUT},
7784 {"BufWrite", EVENT_BUFWRITEPRE},
7785 {"BufWritePost", EVENT_BUFWRITEPOST},
7786 {"BufWritePre", EVENT_BUFWRITEPRE},
7787 {"BufWriteCmd", EVENT_BUFWRITECMD},
Bram Moolenaarfafcf0d2017-10-19 18:35:51 +02007788 {"CmdlineEnter", EVENT_CMDLINEENTER},
7789 {"CmdlineLeave", EVENT_CMDLINELEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007790 {"CmdwinEnter", EVENT_CMDWINENTER},
7791 {"CmdwinLeave", EVENT_CMDWINLEAVE},
Bram Moolenaard5005162014-08-22 23:05:54 +02007792 {"CmdUndefined", EVENT_CMDUNDEFINED},
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007793 {"ColorScheme", EVENT_COLORSCHEME},
Bram Moolenaarcfa3cae2012-07-10 17:14:56 +02007794 {"CompleteDone", EVENT_COMPLETEDONE},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007795 {"CursorHold", EVENT_CURSORHOLD},
7796 {"CursorHoldI", EVENT_CURSORHOLDI},
7797 {"CursorMoved", EVENT_CURSORMOVED},
7798 {"CursorMovedI", EVENT_CURSORMOVEDI},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007799 {"EncodingChanged", EVENT_ENCODINGCHANGED},
7800 {"FileEncoding", EVENT_ENCODINGCHANGED},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007801 {"FileAppendPost", EVENT_FILEAPPENDPOST},
7802 {"FileAppendPre", EVENT_FILEAPPENDPRE},
7803 {"FileAppendCmd", EVENT_FILEAPPENDCMD},
7804 {"FileChangedShell",EVENT_FILECHANGEDSHELL},
Bram Moolenaar56718732006-03-15 22:53:57 +00007805 {"FileChangedShellPost",EVENT_FILECHANGEDSHELLPOST},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007806 {"FileChangedRO", EVENT_FILECHANGEDRO},
7807 {"FileReadPost", EVENT_FILEREADPOST},
7808 {"FileReadPre", EVENT_FILEREADPRE},
7809 {"FileReadCmd", EVENT_FILEREADCMD},
7810 {"FileType", EVENT_FILETYPE},
7811 {"FileWritePost", EVENT_FILEWRITEPOST},
7812 {"FileWritePre", EVENT_FILEWRITEPRE},
7813 {"FileWriteCmd", EVENT_FILEWRITECMD},
7814 {"FilterReadPost", EVENT_FILTERREADPOST},
7815 {"FilterReadPre", EVENT_FILTERREADPRE},
7816 {"FilterWritePost", EVENT_FILTERWRITEPOST},
7817 {"FilterWritePre", EVENT_FILTERWRITEPRE},
7818 {"FocusGained", EVENT_FOCUSGAINED},
7819 {"FocusLost", EVENT_FOCUSLOST},
7820 {"FuncUndefined", EVENT_FUNCUNDEFINED},
7821 {"GUIEnter", EVENT_GUIENTER},
Bram Moolenaar265e5072006-08-29 16:13:22 +00007822 {"GUIFailed", EVENT_GUIFAILED},
Bram Moolenaar843ee412004-06-30 16:16:41 +00007823 {"InsertChange", EVENT_INSERTCHANGE},
7824 {"InsertEnter", EVENT_INSERTENTER},
7825 {"InsertLeave", EVENT_INSERTLEAVE},
Bram Moolenaare659c952011-05-19 17:25:41 +02007826 {"InsertCharPre", EVENT_INSERTCHARPRE},
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00007827 {"MenuPopup", EVENT_MENUPOPUP},
Bram Moolenaar53744302015-07-17 17:38:22 +02007828 {"OptionSet", EVENT_OPTIONSET},
Bram Moolenaar7c626922005-02-07 22:01:03 +00007829 {"QuickFixCmdPost", EVENT_QUICKFIXCMDPOST},
7830 {"QuickFixCmdPre", EVENT_QUICKFIXCMDPRE},
Bram Moolenaar3b53dfb2012-06-06 18:03:07 +02007831 {"QuitPre", EVENT_QUITPRE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007832 {"RemoteReply", EVENT_REMOTEREPLY},
Bram Moolenaar9372a112005-12-06 19:59:18 +00007833 {"SessionLoadPost", EVENT_SESSIONLOADPOST},
Bram Moolenaar5c4bab02006-03-10 21:37:46 +00007834 {"ShellCmdPost", EVENT_SHELLCMDPOST},
7835 {"ShellFilterPost", EVENT_SHELLFILTERPOST},
Bram Moolenaara2031822006-03-07 22:29:51 +00007836 {"SourcePre", EVENT_SOURCEPRE},
Bram Moolenaar8dd1aa52007-01-16 20:33:19 +00007837 {"SourceCmd", EVENT_SOURCECMD},
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00007838 {"SpellFileMissing",EVENT_SPELLFILEMISSING},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007839 {"StdinReadPost", EVENT_STDINREADPOST},
7840 {"StdinReadPre", EVENT_STDINREADPRE},
Bram Moolenaarb815dac2005-12-07 20:59:24 +00007841 {"SwapExists", EVENT_SWAPEXISTS},
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00007842 {"Syntax", EVENT_SYNTAX},
Bram Moolenaarc917da42016-07-19 22:31:36 +02007843 {"TabNew", EVENT_TABNEW},
Bram Moolenaar12c11d52016-07-19 23:13:03 +02007844 {"TabClosed", EVENT_TABCLOSED},
Bram Moolenaar70836c82006-02-20 21:28:49 +00007845 {"TabEnter", EVENT_TABENTER},
7846 {"TabLeave", EVENT_TABLEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007847 {"TermChanged", EVENT_TERMCHANGED},
7848 {"TermResponse", EVENT_TERMRESPONSE},
Bram Moolenaar186628f2013-03-19 13:33:23 +01007849 {"TextChanged", EVENT_TEXTCHANGED},
7850 {"TextChangedI", EVENT_TEXTCHANGEDI},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007851 {"User", EVENT_USER},
7852 {"VimEnter", EVENT_VIMENTER},
7853 {"VimLeave", EVENT_VIMLEAVE},
7854 {"VimLeavePre", EVENT_VIMLEAVEPRE},
Bram Moolenaarc917da42016-07-19 22:31:36 +02007855 {"WinNew", EVENT_WINNEW},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007856 {"WinEnter", EVENT_WINENTER},
7857 {"WinLeave", EVENT_WINLEAVE},
Bram Moolenaar56718732006-03-15 22:53:57 +00007858 {"VimResized", EVENT_VIMRESIZED},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007859 {NULL, (event_T)0}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007860};
7861
7862static AutoPat *first_autopat[NUM_EVENTS] =
7863{
7864 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7865 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7866 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7867 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00007868 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaar53744302015-07-17 17:38:22 +02007869 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007870};
7871
Bram Moolenaar462455e2017-11-10 21:53:11 +01007872static AutoPat *last_autopat[NUM_EVENTS] =
7873{
7874 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7875 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7876 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7877 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7878 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7879 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
7880};
7881
Bram Moolenaar071d4272004-06-13 20:20:40 +00007882/*
7883 * struct used to keep status while executing autocommands for an event.
7884 */
7885typedef struct AutoPatCmd
7886{
7887 AutoPat *curpat; /* next AutoPat to examine */
7888 AutoCmd *nextcmd; /* next AutoCmd to execute */
7889 int group; /* group being used */
7890 char_u *fname; /* fname to match with */
7891 char_u *sfname; /* sfname to match with */
7892 char_u *tail; /* tail of fname */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007893 event_T event; /* current event */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007894 int arg_bufnr; /* initially equal to <abuf>, set to zero when
7895 buf is deleted */
7896 struct AutoPatCmd *next; /* chain of active apc-s for auto-invalidation*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00007897} AutoPatCmd;
7898
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007899static AutoPatCmd *active_apc_list = NULL; /* stack of active autocommands */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007900
Bram Moolenaar071d4272004-06-13 20:20:40 +00007901/*
7902 * augroups stores a list of autocmd group names.
7903 */
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007904static garray_T augroups = {0, 0, sizeof(char_u *), 10, NULL};
Bram Moolenaar071d4272004-06-13 20:20:40 +00007905#define AUGROUP_NAME(i) (((char_u **)augroups.ga_data)[i])
Bram Moolenaarb62cc362016-09-03 16:43:53 +02007906/* use get_deleted_augroup() to get this */
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02007907static char_u *deleted_augroup = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007908
7909/*
7910 * The ID of the current group. Group 0 is the default one.
7911 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007912static int current_augroup = AUGROUP_DEFAULT;
7913
7914static int au_need_clean = FALSE; /* need to delete marked patterns */
7915
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007916static void show_autocmd(AutoPat *ap, event_T event);
7917static void au_remove_pat(AutoPat *ap);
7918static void au_remove_cmds(AutoPat *ap);
7919static void au_cleanup(void);
7920static int au_new_group(char_u *name);
7921static void au_del_group(char_u *name);
7922static event_T event_name2nr(char_u *start, char_u **end);
7923static char_u *event_nr2name(event_T event);
7924static char_u *find_end_event(char_u *arg, int have_group);
7925static int event_ignored(event_T event);
7926static int au_get_grouparg(char_u **argp);
7927static int do_autocmd_event(event_T event, char_u *pat, int nested, char_u *cmd, int forceit, int group);
7928static int apply_autocmds_group(event_T event, char_u *fname, char_u *fname_io, int force, int group, buf_T *buf, exarg_T *eap);
7929static void auto_next_pat(AutoPatCmd *apc, int stop_at_last);
Bram Moolenaardffa5b82014-11-19 16:38:07 +01007930#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN)
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007931static 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 +01007932#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007933
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007934
Bram Moolenaar754b5602006-02-09 23:53:20 +00007935static event_T last_event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007936static int last_group;
Bram Moolenaar78ab3312007-09-29 12:16:41 +00007937static int autocmd_blocked = 0; /* block all autocmds */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007938
Bram Moolenaarb62cc362016-09-03 16:43:53 +02007939 static char_u *
7940get_deleted_augroup(void)
7941{
7942 if (deleted_augroup == NULL)
7943 deleted_augroup = (char_u *)_("--Deleted--");
7944 return deleted_augroup;
7945}
7946
Bram Moolenaar071d4272004-06-13 20:20:40 +00007947/*
7948 * Show the autocommands for one AutoPat.
7949 */
7950 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007951show_autocmd(AutoPat *ap, event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007952{
7953 AutoCmd *ac;
7954
7955 /* Check for "got_int" (here and at various places below), which is set
7956 * when "q" has been hit for the "--more--" prompt */
7957 if (got_int)
7958 return;
7959 if (ap->pat == NULL) /* pattern has been removed */
7960 return;
7961
7962 msg_putchar('\n');
7963 if (got_int)
7964 return;
7965 if (event != last_event || ap->group != last_group)
7966 {
7967 if (ap->group != AUGROUP_DEFAULT)
7968 {
7969 if (AUGROUP_NAME(ap->group) == NULL)
Bram Moolenaar8820b482017-03-16 17:23:31 +01007970 msg_puts_attr(get_deleted_augroup(), HL_ATTR(HLF_E));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007971 else
Bram Moolenaar8820b482017-03-16 17:23:31 +01007972 msg_puts_attr(AUGROUP_NAME(ap->group), HL_ATTR(HLF_T));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007973 msg_puts((char_u *)" ");
7974 }
Bram Moolenaar8820b482017-03-16 17:23:31 +01007975 msg_puts_attr(event_nr2name(event), HL_ATTR(HLF_T));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007976 last_event = event;
7977 last_group = ap->group;
7978 msg_putchar('\n');
7979 if (got_int)
7980 return;
7981 }
7982 msg_col = 4;
7983 msg_outtrans(ap->pat);
7984
7985 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7986 {
7987 if (ac->cmd != NULL) /* skip removed commands */
7988 {
7989 if (msg_col >= 14)
7990 msg_putchar('\n');
7991 msg_col = 14;
7992 if (got_int)
7993 return;
7994 msg_outtrans(ac->cmd);
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00007995#ifdef FEAT_EVAL
7996 if (p_verbose > 0)
7997 last_set_msg(ac->scriptID);
7998#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007999 if (got_int)
8000 return;
8001 if (ac->next != NULL)
8002 {
8003 msg_putchar('\n');
8004 if (got_int)
8005 return;
8006 }
8007 }
8008 }
8009}
8010
8011/*
8012 * Mark an autocommand pattern for deletion.
8013 */
8014 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008015au_remove_pat(AutoPat *ap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008016{
8017 vim_free(ap->pat);
8018 ap->pat = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008019 ap->buflocal_nr = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008020 au_need_clean = TRUE;
8021}
8022
8023/*
8024 * Mark all commands for a pattern for deletion.
8025 */
8026 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008027au_remove_cmds(AutoPat *ap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008028{
8029 AutoCmd *ac;
8030
8031 for (ac = ap->cmds; ac != NULL; ac = ac->next)
8032 {
8033 vim_free(ac->cmd);
8034 ac->cmd = NULL;
8035 }
8036 au_need_clean = TRUE;
8037}
8038
8039/*
8040 * Cleanup autocommands and patterns that have been deleted.
8041 * This is only done when not executing autocommands.
8042 */
8043 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008044au_cleanup(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008045{
8046 AutoPat *ap, **prev_ap;
8047 AutoCmd *ac, **prev_ac;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008048 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008049
8050 if (autocmd_busy || !au_need_clean)
8051 return;
8052
8053 /* loop over all events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008054 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8055 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008056 {
8057 /* loop over all autocommand patterns */
8058 prev_ap = &(first_autopat[(int)event]);
8059 for (ap = *prev_ap; ap != NULL; ap = *prev_ap)
8060 {
8061 /* loop over all commands for this pattern */
8062 prev_ac = &(ap->cmds);
8063 for (ac = *prev_ac; ac != NULL; ac = *prev_ac)
8064 {
8065 /* remove the command if the pattern is to be deleted or when
8066 * the command has been marked for deletion */
8067 if (ap->pat == NULL || ac->cmd == NULL)
8068 {
8069 *prev_ac = ac->next;
8070 vim_free(ac->cmd);
8071 vim_free(ac);
8072 }
8073 else
8074 prev_ac = &(ac->next);
8075 }
8076
8077 /* remove the pattern if it has been marked for deletion */
8078 if (ap->pat == NULL)
8079 {
Bram Moolenaar462455e2017-11-10 21:53:11 +01008080 if (ap->next == NULL)
8081 {
8082 if (prev_ap == &(first_autopat[(int)event]))
8083 last_autopat[(int)event] = NULL;
8084 else
8085 /* this depends on the "next" field being the first in
8086 * the struct */
8087 last_autopat[(int)event] = (AutoPat *)prev_ap;
8088 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008089 *prev_ap = ap->next;
Bram Moolenaar473de612013-06-08 18:19:48 +02008090 vim_regfree(ap->reg_prog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008091 vim_free(ap);
8092 }
8093 else
8094 prev_ap = &(ap->next);
8095 }
8096 }
8097
8098 au_need_clean = FALSE;
8099}
8100
8101/*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008102 * Called when buffer is freed, to remove/invalidate related buffer-local
8103 * autocmds.
8104 */
8105 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008106aubuflocal_remove(buf_T *buf)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008107{
8108 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008109 event_T event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008110 AutoPatCmd *apc;
8111
8112 /* invalidate currently executing autocommands */
8113 for (apc = active_apc_list; apc; apc = apc->next)
8114 if (buf->b_fnum == apc->arg_bufnr)
8115 apc->arg_bufnr = 0;
8116
8117 /* invalidate buflocals looping through events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008118 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8119 event = (event_T)((int)event + 1))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008120 /* loop over all autocommand patterns */
8121 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8122 if (ap->buflocal_nr == buf->b_fnum)
8123 {
8124 au_remove_pat(ap);
8125 if (p_verbose >= 6)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00008126 {
8127 verbose_enter();
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008128 smsg((char_u *)
8129 _("auto-removing autocommand: %s <buffer=%d>"),
8130 event_nr2name(event), buf->b_fnum);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00008131 verbose_leave();
8132 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008133 }
8134 au_cleanup();
8135}
8136
8137/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008138 * Add an autocmd group name.
8139 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
8140 */
8141 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008142au_new_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008143{
8144 int i;
8145
8146 i = au_find_group(name);
8147 if (i == AUGROUP_ERROR) /* the group doesn't exist yet, add it */
8148 {
8149 /* First try using a free entry. */
8150 for (i = 0; i < augroups.ga_len; ++i)
8151 if (AUGROUP_NAME(i) == NULL)
8152 break;
8153 if (i == augroups.ga_len && ga_grow(&augroups, 1) == FAIL)
8154 return AUGROUP_ERROR;
8155
8156 AUGROUP_NAME(i) = vim_strsave(name);
8157 if (AUGROUP_NAME(i) == NULL)
8158 return AUGROUP_ERROR;
8159 if (i == augroups.ga_len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008160 ++augroups.ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008161 }
8162
8163 return i;
8164}
8165
8166 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008167au_del_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008168{
8169 int i;
8170
8171 i = au_find_group(name);
8172 if (i == AUGROUP_ERROR) /* the group doesn't exist */
8173 EMSG2(_("E367: No such group: \"%s\""), name);
Bram Moolenaarde653f02016-09-03 16:59:06 +02008174 else if (i == current_augroup)
8175 EMSG(_("E936: Cannot delete the current group"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008176 else
8177 {
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008178 event_T event;
8179 AutoPat *ap;
8180 int in_use = FALSE;
8181
8182 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8183 event = (event_T)((int)event + 1))
8184 {
8185 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
Bram Moolenaar5c809082016-09-01 16:21:48 +02008186 if (ap->group == i && ap->pat != NULL)
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008187 {
8188 give_warning((char_u *)_("W19: Deleting augroup that is still in use"), TRUE);
8189 in_use = TRUE;
8190 event = NUM_EVENTS;
8191 break;
8192 }
8193 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008194 vim_free(AUGROUP_NAME(i));
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008195 if (in_use)
8196 {
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008197 AUGROUP_NAME(i) = get_deleted_augroup();
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008198 }
8199 else
8200 AUGROUP_NAME(i) = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008201 }
8202}
8203
8204/*
8205 * Find the ID of an autocmd group name.
8206 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
8207 */
8208 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008209au_find_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008210{
8211 int i;
8212
8213 for (i = 0; i < augroups.ga_len; ++i)
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008214 if (AUGROUP_NAME(i) != NULL && AUGROUP_NAME(i) != get_deleted_augroup()
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008215 && STRCMP(AUGROUP_NAME(i), name) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008216 return i;
8217 return AUGROUP_ERROR;
8218}
8219
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008220/*
8221 * Return TRUE if augroup "name" exists.
8222 */
8223 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008224au_has_group(char_u *name)
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008225{
8226 return au_find_group(name) != AUGROUP_ERROR;
8227}
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008228
Bram Moolenaar071d4272004-06-13 20:20:40 +00008229/*
8230 * ":augroup {name}".
8231 */
8232 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008233do_augroup(char_u *arg, int del_group)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008234{
8235 int i;
8236
8237 if (del_group)
8238 {
8239 if (*arg == NUL)
8240 EMSG(_(e_argreq));
8241 else
8242 au_del_group(arg);
8243 }
8244 else if (STRICMP(arg, "end") == 0) /* ":aug end": back to group 0 */
8245 current_augroup = AUGROUP_DEFAULT;
8246 else if (*arg) /* ":aug xxx": switch to group xxx */
8247 {
8248 i = au_new_group(arg);
8249 if (i != AUGROUP_ERROR)
8250 current_augroup = i;
8251 }
8252 else /* ":aug": list the group names */
8253 {
8254 msg_start();
8255 for (i = 0; i < augroups.ga_len; ++i)
8256 {
8257 if (AUGROUP_NAME(i) != NULL)
8258 {
8259 msg_puts(AUGROUP_NAME(i));
8260 msg_puts((char_u *)" ");
8261 }
8262 }
8263 msg_clr_eos();
8264 msg_end();
8265 }
8266}
8267
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008268#if defined(EXITFREE) || defined(PROTO)
8269 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008270free_all_autocmds(void)
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008271{
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008272 int i;
8273 char_u *s;
8274
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008275 for (current_augroup = -1; current_augroup < augroups.ga_len;
8276 ++current_augroup)
8277 do_autocmd((char_u *)"", TRUE);
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008278
8279 for (i = 0; i < augroups.ga_len; ++i)
8280 {
8281 s = ((char_u **)(augroups.ga_data))[i];
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008282 if (s != get_deleted_augroup())
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008283 vim_free(s);
8284 }
8285 ga_clear(&augroups);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008286}
8287#endif
8288
Bram Moolenaar071d4272004-06-13 20:20:40 +00008289/*
8290 * Return the event number for event name "start".
8291 * Return NUM_EVENTS if the event name was not found.
8292 * Return a pointer to the next event name in "end".
8293 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008294 static event_T
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008295event_name2nr(char_u *start, char_u **end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008296{
8297 char_u *p;
8298 int i;
8299 int len;
8300
Bram Moolenaare99e8442016-07-26 20:43:40 +02008301 /* the event name ends with end of line, '|', a blank or a comma */
Bram Moolenaar1c465442017-03-12 20:10:05 +01008302 for (p = start; *p && !VIM_ISWHITE(*p) && *p != ',' && *p != '|'; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008303 ;
8304 for (i = 0; event_names[i].name != NULL; ++i)
8305 {
8306 len = (int)STRLEN(event_names[i].name);
8307 if (len == p - start && STRNICMP(event_names[i].name, start, len) == 0)
8308 break;
8309 }
8310 if (*p == ',')
8311 ++p;
8312 *end = p;
8313 if (event_names[i].name == NULL)
8314 return NUM_EVENTS;
8315 return event_names[i].event;
8316}
8317
8318/*
8319 * Return the name for event "event".
8320 */
8321 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008322event_nr2name(event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008323{
8324 int i;
8325
8326 for (i = 0; event_names[i].name != NULL; ++i)
8327 if (event_names[i].event == event)
8328 return (char_u *)event_names[i].name;
8329 return (char_u *)"Unknown";
8330}
8331
8332/*
8333 * Scan over the events. "*" stands for all events.
8334 */
8335 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008336find_end_event(
8337 char_u *arg,
8338 int have_group) /* TRUE when group name was found */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008339{
8340 char_u *pat;
8341 char_u *p;
8342
8343 if (*arg == '*')
8344 {
Bram Moolenaar1c465442017-03-12 20:10:05 +01008345 if (arg[1] && !VIM_ISWHITE(arg[1]))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008346 {
8347 EMSG2(_("E215: Illegal character after *: %s"), arg);
8348 return NULL;
8349 }
8350 pat = arg + 1;
8351 }
8352 else
8353 {
Bram Moolenaar1c465442017-03-12 20:10:05 +01008354 for (pat = arg; *pat && *pat != '|' && !VIM_ISWHITE(*pat); pat = p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008355 {
8356 if ((int)event_name2nr(pat, &p) >= (int)NUM_EVENTS)
8357 {
8358 if (have_group)
8359 EMSG2(_("E216: No such event: %s"), pat);
8360 else
8361 EMSG2(_("E216: No such group or event: %s"), pat);
8362 return NULL;
8363 }
8364 }
8365 }
8366 return pat;
8367}
8368
8369/*
8370 * Return TRUE if "event" is included in 'eventignore'.
8371 */
8372 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008373event_ignored(event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008374{
8375 char_u *p = p_ei;
8376
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008377 while (*p != NUL)
8378 {
8379 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8380 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008381 if (event_name2nr(p, &p) == event)
8382 return TRUE;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008383 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008384
8385 return FALSE;
8386}
8387
8388/*
8389 * Return OK when the contents of p_ei is valid, FAIL otherwise.
8390 */
8391 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008392check_ei(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008393{
8394 char_u *p = p_ei;
8395
Bram Moolenaar071d4272004-06-13 20:20:40 +00008396 while (*p)
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008397 {
8398 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8399 {
8400 p += 3;
8401 if (*p == ',')
8402 ++p;
8403 }
8404 else if (event_name2nr(p, &p) == NUM_EVENTS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008405 return FAIL;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008406 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008407
8408 return OK;
8409}
8410
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008411# if defined(FEAT_SYN_HL) || defined(PROTO)
8412
8413/*
8414 * Add "what" to 'eventignore' to skip loading syntax highlighting for every
8415 * buffer loaded into the window. "what" must start with a comma.
8416 * Returns the old value of 'eventignore' in allocated memory.
8417 */
8418 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008419au_event_disable(char *what)
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008420{
8421 char_u *new_ei;
8422 char_u *save_ei;
8423
8424 save_ei = vim_strsave(p_ei);
8425 if (save_ei != NULL)
8426 {
Bram Moolenaara5792f52005-11-23 21:25:05 +00008427 new_ei = vim_strnsave(p_ei, (int)(STRLEN(p_ei) + STRLEN(what)));
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008428 if (new_ei != NULL)
8429 {
Bram Moolenaar8cac9fd2010-03-02 12:48:05 +01008430 if (*what == ',' && *p_ei == NUL)
8431 STRCPY(new_ei, what + 1);
8432 else
8433 STRCAT(new_ei, what);
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008434 set_string_option_direct((char_u *)"ei", -1, new_ei,
8435 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008436 vim_free(new_ei);
8437 }
8438 }
8439 return save_ei;
8440}
8441
8442 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008443au_event_restore(char_u *old_ei)
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008444{
8445 if (old_ei != NULL)
8446 {
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008447 set_string_option_direct((char_u *)"ei", -1, old_ei,
8448 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008449 vim_free(old_ei);
8450 }
8451}
8452# endif /* FEAT_SYN_HL */
8453
Bram Moolenaar071d4272004-06-13 20:20:40 +00008454/*
8455 * do_autocmd() -- implements the :autocmd command. Can be used in the
8456 * following ways:
8457 *
8458 * :autocmd <event> <pat> <cmd> Add <cmd> to the list of commands that
8459 * will be automatically executed for <event>
8460 * when editing a file matching <pat>, in
8461 * the current group.
8462 * :autocmd <event> <pat> Show the auto-commands associated with
8463 * <event> and <pat>.
8464 * :autocmd <event> Show the auto-commands associated with
8465 * <event>.
8466 * :autocmd Show all auto-commands.
8467 * :autocmd! <event> <pat> <cmd> Remove all auto-commands associated with
8468 * <event> and <pat>, and add the command
8469 * <cmd>, for the current group.
8470 * :autocmd! <event> <pat> Remove all auto-commands associated with
8471 * <event> and <pat> for the current group.
8472 * :autocmd! <event> Remove all auto-commands associated with
8473 * <event> for the current group.
8474 * :autocmd! Remove ALL auto-commands for the current
8475 * group.
8476 *
8477 * Multiple events and patterns may be given separated by commas. Here are
8478 * some examples:
8479 * :autocmd bufread,bufenter *.c,*.h set tw=0 smartindent noic
8480 * :autocmd bufleave * set tw=79 nosmartindent ic infercase
8481 *
8482 * :autocmd * *.c show all autocommands for *.c files.
Bram Moolenaard35f9712005-12-18 22:02:33 +00008483 *
8484 * Mostly a {group} argument can optionally appear before <event>.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008485 */
8486 void
Bram Moolenaare99e8442016-07-26 20:43:40 +02008487do_autocmd(char_u *arg_in, int forceit)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008488{
Bram Moolenaare99e8442016-07-26 20:43:40 +02008489 char_u *arg = arg_in;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008490 char_u *pat;
8491 char_u *envpat = NULL;
8492 char_u *cmd;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008493 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008494 int need_free = FALSE;
8495 int nested = FALSE;
8496 int group;
8497
Bram Moolenaare99e8442016-07-26 20:43:40 +02008498 if (*arg == '|')
8499 {
8500 arg = (char_u *)"";
8501 group = AUGROUP_ALL; /* no argument, use all groups */
8502 }
8503 else
8504 {
8505 /*
8506 * Check for a legal group name. If not, use AUGROUP_ALL.
8507 */
8508 group = au_get_grouparg(&arg);
8509 if (arg == NULL) /* out of memory */
8510 return;
8511 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008512
8513 /*
8514 * Scan over the events.
8515 * If we find an illegal name, return here, don't do anything.
8516 */
8517 pat = find_end_event(arg, group != AUGROUP_ALL);
8518 if (pat == NULL)
8519 return;
8520
Bram Moolenaar071d4272004-06-13 20:20:40 +00008521 pat = skipwhite(pat);
Bram Moolenaare99e8442016-07-26 20:43:40 +02008522 if (*pat == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008523 {
Bram Moolenaare99e8442016-07-26 20:43:40 +02008524 pat = (char_u *)"";
8525 cmd = (char_u *)"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00008526 }
Bram Moolenaare99e8442016-07-26 20:43:40 +02008527 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00008528 {
Bram Moolenaare99e8442016-07-26 20:43:40 +02008529 /*
8530 * Scan over the pattern. Put a NUL at the end.
8531 */
8532 cmd = pat;
Bram Moolenaar1c465442017-03-12 20:10:05 +01008533 while (*cmd && (!VIM_ISWHITE(*cmd) || cmd[-1] == '\\'))
Bram Moolenaare99e8442016-07-26 20:43:40 +02008534 cmd++;
8535 if (*cmd)
8536 *cmd++ = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008537
Bram Moolenaare99e8442016-07-26 20:43:40 +02008538 /* Expand environment variables in the pattern. Set 'shellslash', we want
8539 * forward slashes here. */
8540 if (vim_strchr(pat, '$') != NULL || vim_strchr(pat, '~') != NULL)
8541 {
8542#ifdef BACKSLASH_IN_FILENAME
8543 int p_ssl_save = p_ssl;
8544
8545 p_ssl = TRUE;
8546#endif
8547 envpat = expand_env_save(pat);
8548#ifdef BACKSLASH_IN_FILENAME
8549 p_ssl = p_ssl_save;
8550#endif
8551 if (envpat != NULL)
8552 pat = envpat;
8553 }
8554
8555 /*
8556 * Check for "nested" flag.
8557 */
8558 cmd = skipwhite(cmd);
Bram Moolenaar1c465442017-03-12 20:10:05 +01008559 if (*cmd != NUL && STRNCMP(cmd, "nested", 6) == 0 && VIM_ISWHITE(cmd[6]))
Bram Moolenaare99e8442016-07-26 20:43:40 +02008560 {
8561 nested = TRUE;
8562 cmd = skipwhite(cmd + 6);
8563 }
8564
8565 /*
8566 * Find the start of the commands.
8567 * Expand <sfile> in it.
8568 */
8569 if (*cmd != NUL)
8570 {
8571 cmd = expand_sfile(cmd);
8572 if (cmd == NULL) /* some error */
8573 return;
8574 need_free = TRUE;
8575 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008576 }
8577
8578 /*
8579 * Print header when showing autocommands.
8580 */
8581 if (!forceit && *cmd == NUL)
8582 {
8583 /* Highlight title */
8584 MSG_PUTS_TITLE(_("\n--- Auto-Commands ---"));
8585 }
8586
8587 /*
8588 * Loop over the events.
8589 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008590 last_event = (event_T)-1; /* for listing the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008591 last_group = AUGROUP_ERROR; /* for listing the group name */
Bram Moolenaare99e8442016-07-26 20:43:40 +02008592 if (*arg == '*' || *arg == NUL || *arg == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008593 {
Bram Moolenaar754b5602006-02-09 23:53:20 +00008594 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8595 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008596 if (do_autocmd_event(event, pat,
8597 nested, cmd, forceit, group) == FAIL)
8598 break;
8599 }
8600 else
8601 {
Bram Moolenaar1c465442017-03-12 20:10:05 +01008602 while (*arg && *arg != '|' && !VIM_ISWHITE(*arg))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008603 if (do_autocmd_event(event_name2nr(arg, &arg), pat,
8604 nested, cmd, forceit, group) == FAIL)
8605 break;
8606 }
8607
8608 if (need_free)
8609 vim_free(cmd);
8610 vim_free(envpat);
8611}
8612
8613/*
8614 * Find the group ID in a ":autocmd" or ":doautocmd" argument.
8615 * The "argp" argument is advanced to the following argument.
8616 *
8617 * Returns the group ID, AUGROUP_ERROR for error (out of memory).
8618 */
8619 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008620au_get_grouparg(char_u **argp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008621{
8622 char_u *group_name;
8623 char_u *p;
8624 char_u *arg = *argp;
8625 int group = AUGROUP_ALL;
8626
Bram Moolenaar1c465442017-03-12 20:10:05 +01008627 for (p = arg; *p && !VIM_ISWHITE(*p) && *p != '|'; ++p)
Bram Moolenaare99e8442016-07-26 20:43:40 +02008628 ;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008629 if (p > arg)
8630 {
8631 group_name = vim_strnsave(arg, (int)(p - arg));
8632 if (group_name == NULL) /* out of memory */
8633 return AUGROUP_ERROR;
8634 group = au_find_group(group_name);
8635 if (group == AUGROUP_ERROR)
8636 group = AUGROUP_ALL; /* no match, use all groups */
8637 else
8638 *argp = skipwhite(p); /* match, skip over group name */
8639 vim_free(group_name);
8640 }
8641 return group;
8642}
8643
8644/*
8645 * do_autocmd() for one event.
8646 * If *pat == NUL do for all patterns.
8647 * If *cmd == NUL show entries.
8648 * If forceit == TRUE delete entries.
8649 * If group is not AUGROUP_ALL, only use this group.
8650 */
8651 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008652do_autocmd_event(
8653 event_T event,
8654 char_u *pat,
8655 int nested,
8656 char_u *cmd,
8657 int forceit,
8658 int group)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008659{
8660 AutoPat *ap;
8661 AutoPat **prev_ap;
8662 AutoCmd *ac;
8663 AutoCmd **prev_ac;
8664 int brace_level;
8665 char_u *endpat;
8666 int findgroup;
8667 int allgroups;
8668 int patlen;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00008669 int is_buflocal;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008670 int buflocal_nr;
8671 char_u buflocal_pat[25]; /* for "<buffer=X>" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008672
8673 if (group == AUGROUP_ALL)
8674 findgroup = current_augroup;
8675 else
8676 findgroup = group;
8677 allgroups = (group == AUGROUP_ALL && !forceit && *cmd == NUL);
8678
8679 /*
8680 * Show or delete all patterns for an event.
8681 */
8682 if (*pat == NUL)
8683 {
8684 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8685 {
8686 if (forceit) /* delete the AutoPat, if it's in the current group */
8687 {
8688 if (ap->group == findgroup)
8689 au_remove_pat(ap);
8690 }
8691 else if (group == AUGROUP_ALL || ap->group == group)
8692 show_autocmd(ap, event);
8693 }
8694 }
8695
8696 /*
8697 * Loop through all the specified patterns.
8698 */
8699 for ( ; *pat; pat = (*endpat == ',' ? endpat + 1 : endpat))
8700 {
8701 /*
8702 * Find end of the pattern.
8703 * Watch out for a comma in braces, like "*.\{obj,o\}".
8704 */
8705 brace_level = 0;
8706 for (endpat = pat; *endpat && (*endpat != ',' || brace_level
Bram Moolenaar6b9be1b2015-07-28 13:33:45 +02008707 || (endpat > pat && endpat[-1] == '\\')); ++endpat)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008708 {
8709 if (*endpat == '{')
8710 brace_level++;
8711 else if (*endpat == '}')
8712 brace_level--;
8713 }
8714 if (pat == endpat) /* ignore single comma */
8715 continue;
8716 patlen = (int)(endpat - pat);
8717
8718 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008719 * detect special <buflocal[=X]> buffer-local patterns
8720 */
8721 is_buflocal = FALSE;
8722 buflocal_nr = 0;
8723
Bram Moolenaar1e997822015-02-17 16:04:57 +01008724 if (patlen >= 8 && STRNCMP(pat, "<buffer", 7) == 0
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008725 && pat[patlen - 1] == '>')
8726 {
Bram Moolenaar1e997822015-02-17 16:04:57 +01008727 /* "<buffer...>": Error will be printed only for addition.
8728 * printing and removing will proceed silently. */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008729 is_buflocal = TRUE;
8730 if (patlen == 8)
Bram Moolenaar1e997822015-02-17 16:04:57 +01008731 /* "<buffer>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008732 buflocal_nr = curbuf->b_fnum;
8733 else if (patlen > 9 && pat[7] == '=')
8734 {
Bram Moolenaar1e997822015-02-17 16:04:57 +01008735 if (patlen == 13 && STRNICMP(pat, "<buffer=abuf>", 13) == 0)
8736 /* "<buffer=abuf>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008737 buflocal_nr = autocmd_bufnr;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008738 else if (skipdigits(pat + 8) == pat + patlen - 1)
Bram Moolenaar1e997822015-02-17 16:04:57 +01008739 /* "<buffer=123>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008740 buflocal_nr = atoi((char *)pat + 8);
8741 }
8742 }
8743
8744 if (is_buflocal)
8745 {
8746 /* normalize pat into standard "<buffer>#N" form */
8747 sprintf((char *)buflocal_pat, "<buffer=%d>", buflocal_nr);
8748 pat = buflocal_pat; /* can modify pat and patlen */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008749 patlen = (int)STRLEN(buflocal_pat); /* but not endpat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008750 }
8751
8752 /*
Bram Moolenaar462455e2017-11-10 21:53:11 +01008753 * Find AutoPat entries with this pattern. When adding a command it
8754 * always goes at or after the last one, so start at the end.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008755 */
Bram Moolenaar462455e2017-11-10 21:53:11 +01008756 if (!forceit && *cmd != NUL && last_autopat[(int)event] != NULL)
8757 prev_ap = &last_autopat[(int)event];
8758 else
8759 prev_ap = &first_autopat[(int)event];
Bram Moolenaar071d4272004-06-13 20:20:40 +00008760 while ((ap = *prev_ap) != NULL)
8761 {
8762 if (ap->pat != NULL)
8763 {
8764 /* Accept a pattern when:
8765 * - a group was specified and it's that group, or a group was
8766 * not specified and it's the current group, or a group was
8767 * not specified and we are listing
8768 * - the length of the pattern matches
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008769 * - the pattern matches.
8770 * For <buffer[=X]>, this condition works because we normalize
8771 * all buffer-local patterns.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008772 */
8773 if ((allgroups || ap->group == findgroup)
8774 && ap->patlen == patlen
8775 && STRNCMP(pat, ap->pat, patlen) == 0)
8776 {
8777 /*
8778 * Remove existing autocommands.
8779 * If adding any new autocmd's for this AutoPat, don't
8780 * delete the pattern from the autopat list, append to
8781 * this list.
8782 */
8783 if (forceit)
8784 {
8785 if (*cmd != NUL && ap->next == NULL)
8786 {
8787 au_remove_cmds(ap);
8788 break;
8789 }
8790 au_remove_pat(ap);
8791 }
8792
8793 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008794 * Show autocmd's for this autopat, or buflocals <buffer=X>
Bram Moolenaar071d4272004-06-13 20:20:40 +00008795 */
8796 else if (*cmd == NUL)
8797 show_autocmd(ap, event);
8798
8799 /*
8800 * Add autocmd to this autopat, if it's the last one.
8801 */
8802 else if (ap->next == NULL)
8803 break;
8804 }
8805 }
8806 prev_ap = &ap->next;
8807 }
8808
8809 /*
8810 * Add a new command.
8811 */
8812 if (*cmd != NUL)
8813 {
8814 /*
8815 * If the pattern we want to add a command to does appear at the
8816 * end of the list (or not is not in the list at all), add the
8817 * pattern at the end of the list.
8818 */
8819 if (ap == NULL)
8820 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008821 /* refuse to add buffer-local ap if buffer number is invalid */
8822 if (is_buflocal && (buflocal_nr == 0
8823 || buflist_findnr(buflocal_nr) == NULL))
8824 {
8825 EMSGN(_("E680: <buffer=%d>: invalid buffer number "),
8826 buflocal_nr);
8827 return FAIL;
8828 }
8829
Bram Moolenaar071d4272004-06-13 20:20:40 +00008830 ap = (AutoPat *)alloc((unsigned)sizeof(AutoPat));
8831 if (ap == NULL)
8832 return FAIL;
8833 ap->pat = vim_strnsave(pat, patlen);
8834 ap->patlen = patlen;
8835 if (ap->pat == NULL)
8836 {
8837 vim_free(ap);
8838 return FAIL;
8839 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008840
8841 if (is_buflocal)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008842 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008843 ap->buflocal_nr = buflocal_nr;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008844 ap->reg_prog = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008845 }
8846 else
8847 {
Bram Moolenaar748bf032005-02-02 23:04:36 +00008848 char_u *reg_pat;
8849
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008850 ap->buflocal_nr = 0;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008851 reg_pat = file_pat_to_reg_pat(pat, endpat,
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008852 &ap->allow_dirs, TRUE);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008853 if (reg_pat != NULL)
8854 ap->reg_prog = vim_regcomp(reg_pat, RE_MAGIC);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008855 vim_free(reg_pat);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008856 if (reg_pat == NULL || ap->reg_prog == NULL)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008857 {
8858 vim_free(ap->pat);
8859 vim_free(ap);
8860 return FAIL;
8861 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008862 }
8863 ap->cmds = NULL;
8864 *prev_ap = ap;
Bram Moolenaar462455e2017-11-10 21:53:11 +01008865 last_autopat[(int)event] = ap;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008866 ap->next = NULL;
8867 if (group == AUGROUP_ALL)
8868 ap->group = current_augroup;
8869 else
8870 ap->group = group;
8871 }
8872
8873 /*
8874 * Add the autocmd at the end of the AutoCmd list.
8875 */
8876 prev_ac = &(ap->cmds);
8877 while ((ac = *prev_ac) != NULL)
8878 prev_ac = &ac->next;
8879 ac = (AutoCmd *)alloc((unsigned)sizeof(AutoCmd));
8880 if (ac == NULL)
8881 return FAIL;
8882 ac->cmd = vim_strsave(cmd);
8883#ifdef FEAT_EVAL
8884 ac->scriptID = current_SID;
8885#endif
8886 if (ac->cmd == NULL)
8887 {
8888 vim_free(ac);
8889 return FAIL;
8890 }
8891 ac->next = NULL;
8892 *prev_ac = ac;
8893 ac->nested = nested;
8894 }
8895 }
8896
8897 au_cleanup(); /* may really delete removed patterns/commands now */
8898 return OK;
8899}
8900
8901/*
8902 * Implementation of ":doautocmd [group] event [fname]".
8903 * Return OK for success, FAIL for failure;
8904 */
8905 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008906do_doautocmd(
8907 char_u *arg,
Bram Moolenaar1610d052016-06-09 22:53:01 +02008908 int do_msg, /* give message for no matching autocmds? */
8909 int *did_something)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008910{
8911 char_u *fname;
8912 int nothing_done = TRUE;
8913 int group;
8914
Bram Moolenaar1610d052016-06-09 22:53:01 +02008915 if (did_something != NULL)
Bram Moolenaar76ae22f2016-06-13 20:00:29 +02008916 *did_something = FALSE;
Bram Moolenaar1610d052016-06-09 22:53:01 +02008917
Bram Moolenaar071d4272004-06-13 20:20:40 +00008918 /*
8919 * Check for a legal group name. If not, use AUGROUP_ALL.
8920 */
8921 group = au_get_grouparg(&arg);
8922 if (arg == NULL) /* out of memory */
8923 return FAIL;
8924
8925 if (*arg == '*')
8926 {
8927 EMSG(_("E217: Can't execute autocommands for ALL events"));
8928 return FAIL;
8929 }
8930
8931 /*
8932 * Scan over the events.
8933 * If we find an illegal name, return here, don't do anything.
8934 */
8935 fname = find_end_event(arg, group != AUGROUP_ALL);
8936 if (fname == NULL)
8937 return FAIL;
8938
8939 fname = skipwhite(fname);
8940
8941 /*
8942 * Loop over the events.
8943 */
Bram Moolenaarfaf29d72017-07-09 11:07:16 +02008944 while (*arg && !ends_excmd(*arg) && !VIM_ISWHITE(*arg))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008945 if (apply_autocmds_group(event_name2nr(arg, &arg),
8946 fname, NULL, TRUE, group, curbuf, NULL))
8947 nothing_done = FALSE;
8948
8949 if (nothing_done && do_msg)
8950 MSG(_("No matching autocommands"));
Bram Moolenaar1610d052016-06-09 22:53:01 +02008951 if (did_something != NULL)
8952 *did_something = !nothing_done;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008953
8954#ifdef FEAT_EVAL
8955 return aborting() ? FAIL : OK;
8956#else
8957 return OK;
8958#endif
8959}
8960
8961/*
8962 * ":doautoall": execute autocommands for each loaded buffer.
8963 */
8964 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008965ex_doautoall(exarg_T *eap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008966{
8967 int retval;
8968 aco_save_T aco;
8969 buf_T *buf;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008970 bufref_T bufref;
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008971 char_u *arg = eap->arg;
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008972 int call_do_modelines = check_nomodeline(&arg);
Bram Moolenaar1610d052016-06-09 22:53:01 +02008973 int did_aucmd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008974
8975 /*
8976 * This is a bit tricky: For some commands curwin->w_buffer needs to be
8977 * equal to curbuf, but for some buffers there may not be a window.
8978 * So we change the buffer for the current window for a moment. This
8979 * gives problems when the autocommands make changes to the list of
8980 * buffers or windows...
8981 */
Bram Moolenaar29323592016-07-24 22:04:11 +02008982 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008983 {
Bram Moolenaar3a847972008-07-08 09:36:58 +00008984 if (buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008985 {
8986 /* find a window for this buffer and save some values */
8987 aucmd_prepbuf(&aco, buf);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008988 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008989
8990 /* execute the autocommands for this buffer */
Bram Moolenaar1610d052016-06-09 22:53:01 +02008991 retval = do_doautocmd(arg, FALSE, &did_aucmd);
Bram Moolenaareeefcc72007-05-01 21:21:21 +00008992
Bram Moolenaar1610d052016-06-09 22:53:01 +02008993 if (call_do_modelines && did_aucmd)
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008994 {
8995 /* Execute the modeline settings, but don't set window-local
8996 * options if we are using the current window for another
8997 * buffer. */
8998 do_modelines(curwin == aucmd_win ? OPT_NOWIN : 0);
8999 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009000
9001 /* restore the current window */
9002 aucmd_restbuf(&aco);
9003
9004 /* stop if there is some error or buffer was deleted */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009005 if (retval == FAIL || !bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009006 break;
9007 }
9008 }
9009
9010 check_cursor(); /* just in case lines got deleted */
9011}
9012
9013/*
Bram Moolenaar60542ac2012-02-12 20:14:01 +01009014 * Check *argp for <nomodeline>. When it is present return FALSE, otherwise
9015 * return TRUE and advance *argp to after it.
9016 * Thus return TRUE when do_modelines() should be called.
9017 */
9018 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009019check_nomodeline(char_u **argp)
Bram Moolenaar60542ac2012-02-12 20:14:01 +01009020{
9021 if (STRNCMP(*argp, "<nomodeline>", 12) == 0)
9022 {
9023 *argp = skipwhite(*argp + 12);
9024 return FALSE;
9025 }
9026 return TRUE;
9027}
9028
9029/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00009030 * Prepare for executing autocommands for (hidden) buffer "buf".
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009031 * Search for a visible window containing the current buffer. If there isn't
9032 * one then use "aucmd_win".
Bram Moolenaar071d4272004-06-13 20:20:40 +00009033 * Set "curbuf" and "curwin" to match "buf".
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009034 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009035 */
9036 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009037aucmd_prepbuf(
9038 aco_save_T *aco, /* structure to save values in */
9039 buf_T *buf) /* new curbuf */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009040{
9041 win_T *win;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009042 int save_ea;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02009043#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009044 int save_acd;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02009045#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009046
9047 /* Find a window that is for the new buffer */
9048 if (buf == curbuf) /* be quick when buf is curbuf */
9049 win = curwin;
9050 else
Bram Moolenaar29323592016-07-24 22:04:11 +02009051 FOR_ALL_WINDOWS(win)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009052 if (win->w_buffer == buf)
9053 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009054
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009055 /* Allocate "aucmd_win" when needed. If this fails (out of memory) fall
9056 * back to using the current window. */
9057 if (win == NULL && aucmd_win == NULL)
9058 {
9059 win_alloc_aucmd_win();
9060 if (aucmd_win == NULL)
9061 win = curwin;
9062 }
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009063 if (win == NULL && aucmd_win_used)
9064 /* Strange recursive autocommand, fall back to using the current
9065 * window. Expect a few side effects... */
9066 win = curwin;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009067
9068 aco->save_curwin = curwin;
9069 aco->save_curbuf = curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009070 if (win != NULL)
9071 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009072 /* There is a window for "buf" in the current tab page, make it the
9073 * curwin. This is preferred, it has the least side effects (esp. if
9074 * "buf" is curbuf). */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009075 aco->use_aucmd_win = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009076 curwin = win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009077 }
9078 else
9079 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009080 /* There is no window for "buf", use "aucmd_win". To minimize the side
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02009081 * effects, insert it in the current tab page.
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009082 * Anything related to a window (e.g., setting folds) may have
9083 * unexpected results. */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009084 aco->use_aucmd_win = TRUE;
9085 aucmd_win_used = TRUE;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00009086 aucmd_win->w_buffer = buf;
Bram Moolenaarcdddaa42010-06-07 23:07:44 +02009087 aucmd_win->w_s = &buf->b_s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009088 ++buf->b_nwindows;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00009089 win_init_empty(aucmd_win); /* set cursor and topline to safe values */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009090
9091 /* Make sure w_localdir and globaldir are NULL to avoid a chdir() in
9092 * win_enter_ext(). */
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009093 vim_free(aucmd_win->w_localdir);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009094 aucmd_win->w_localdir = NULL;
9095 aco->globaldir = globaldir;
9096 globaldir = NULL;
9097
Bram Moolenaar071d4272004-06-13 20:20:40 +00009098
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00009099 /* Split the current window, put the aucmd_win in the upper half.
9100 * We don't want the BufEnter or WinEnter autocommands. */
9101 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009102 make_snapshot(SNAP_AUCMD_IDX);
9103 save_ea = p_ea;
9104 p_ea = FALSE;
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009105
Bram Moolenaar4033c552017-09-16 20:54:51 +02009106#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009107 /* Prevent chdir() call in win_enter_ext(), through do_autochdir(). */
9108 save_acd = p_acd;
9109 p_acd = FALSE;
Bram Moolenaar4033c552017-09-16 20:54:51 +02009110#endif
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009111
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009112 (void)win_split_ins(0, WSP_TOP, aucmd_win, 0);
9113 (void)win_comp_pos(); /* recompute window positions */
9114 p_ea = save_ea;
Bram Moolenaar4033c552017-09-16 20:54:51 +02009115#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009116 p_acd = save_acd;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009117#endif
Bram Moolenaar4033c552017-09-16 20:54:51 +02009118 unblock_autocmds();
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00009119 curwin = aucmd_win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009120 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009121 curbuf = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009122 aco->new_curwin = curwin;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009123 set_bufref(&aco->new_curbuf, curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009124}
9125
9126/*
9127 * Cleanup after executing autocommands for a (hidden) buffer.
9128 * Restore the window as it was (if possible).
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009129 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009130 */
9131 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009132aucmd_restbuf(
9133 aco_save_T *aco) /* structure holding saved values */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009134{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009135 int dummy;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009136
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009137 if (aco->use_aucmd_win)
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009138 {
9139 --curbuf->b_nwindows;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009140 /* Find "aucmd_win", it can't be closed, but it may be in another tab
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00009141 * page. Do not trigger autocommands here. */
9142 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009143 if (curwin != aucmd_win)
9144 {
9145 tabpage_T *tp;
9146 win_T *wp;
9147
9148 FOR_ALL_TAB_WINDOWS(tp, wp)
9149 {
9150 if (wp == aucmd_win)
9151 {
9152 if (tp != curtab)
Bram Moolenaar49e649f2013-05-06 04:50:35 +02009153 goto_tabpage_tp(tp, TRUE, TRUE);
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009154 win_goto(aucmd_win);
Bram Moolenaar28f29082012-02-11 23:45:37 +01009155 goto win_found;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009156 }
9157 }
9158 }
Bram Moolenaar28f29082012-02-11 23:45:37 +01009159win_found:
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009160
9161 /* Remove the window and frame from the tree of frames. */
9162 (void)winframe_remove(curwin, &dummy, NULL);
9163 win_remove(curwin, NULL);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009164 aucmd_win_used = FALSE;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009165 last_status(FALSE); /* may need to remove last status line */
Bram Moolenaar8c752bd2017-03-19 17:09:56 +01009166
9167 if (!valid_tabpage_win(curtab))
9168 /* no valid window in current tabpage */
9169 close_tabpage(curtab);
9170
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009171 restore_snapshot(SNAP_AUCMD_IDX, FALSE);
9172 (void)win_comp_pos(); /* recompute window positions */
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00009173 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009174
9175 if (win_valid(aco->save_curwin))
9176 curwin = aco->save_curwin;
9177 else
9178 /* Hmm, original window disappeared. Just use the first one. */
9179 curwin = firstwin;
Bram Moolenaar4033c552017-09-16 20:54:51 +02009180#ifdef FEAT_EVAL
Bram Moolenaar429fa852013-04-15 12:27:36 +02009181 vars_clear(&aucmd_win->w_vars->dv_hashtab); /* free all w: variables */
9182 hash_init(&aucmd_win->w_vars->dv_hashtab); /* re-use the hashtab */
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009183#endif
9184 curbuf = curwin->w_buffer;
9185
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009186 vim_free(globaldir);
9187 globaldir = aco->globaldir;
9188
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009189 /* the buffer contents may have changed */
9190 check_cursor();
9191 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
9192 {
9193 curwin->w_topline = curbuf->b_ml.ml_line_count;
9194#ifdef FEAT_DIFF
9195 curwin->w_topfill = 0;
9196#endif
9197 }
9198#if defined(FEAT_GUI)
9199 /* Hide the scrollbars from the aucmd_win and update. */
9200 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_LEFT], FALSE);
9201 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_RIGHT], FALSE);
9202 gui_may_update_scrollbars();
9203#endif
9204 }
9205 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00009206 {
9207 /* restore curwin */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009208 if (win_valid(aco->save_curwin))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009209 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009210 /* Restore the buffer which was previously edited by curwin, if
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009211 * it was changed, we are still the same window and the buffer is
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009212 * valid. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009213 if (curwin == aco->new_curwin
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009214 && curbuf != aco->new_curbuf.br_buf
9215 && bufref_valid(&aco->new_curbuf)
9216 && aco->new_curbuf.br_buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009217 {
Bram Moolenaar7da9c372012-04-30 17:04:52 +02009218# if defined(FEAT_SYN_HL) || defined(FEAT_SPELL)
9219 if (curwin->w_s == &curbuf->b_s)
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009220 curwin->w_s = &aco->new_curbuf.br_buf->b_s;
Bram Moolenaar7da9c372012-04-30 17:04:52 +02009221# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009222 --curbuf->b_nwindows;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009223 curbuf = aco->new_curbuf.br_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009224 curwin->w_buffer = curbuf;
9225 ++curbuf->b_nwindows;
9226 }
9227
9228 curwin = aco->save_curwin;
9229 curbuf = curwin->w_buffer;
Bram Moolenaar371932a2014-09-09 16:59:38 +02009230 /* In case the autocommand move the cursor to a position that that
9231 * not exist in curbuf. */
9232 check_cursor();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009233 }
9234 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009235}
9236
9237static int autocmd_nested = FALSE;
9238
9239/*
9240 * Execute autocommands for "event" and file name "fname".
9241 * Return TRUE if some commands were executed.
9242 */
9243 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009244apply_autocmds(
9245 event_T event,
9246 char_u *fname, /* NULL or empty means use actual file name */
9247 char_u *fname_io, /* fname to use for <afile> on cmdline */
9248 int force, /* when TRUE, ignore autocmd_busy */
9249 buf_T *buf) /* buffer for <abuf> */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009250{
9251 return apply_autocmds_group(event, fname, fname_io, force,
9252 AUGROUP_ALL, buf, NULL);
9253}
9254
9255/*
9256 * Like apply_autocmds(), but with extra "eap" argument. This takes care of
9257 * setting v:filearg.
9258 */
9259 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009260apply_autocmds_exarg(
9261 event_T event,
9262 char_u *fname,
9263 char_u *fname_io,
9264 int force,
9265 buf_T *buf,
9266 exarg_T *eap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009267{
9268 return apply_autocmds_group(event, fname, fname_io, force,
9269 AUGROUP_ALL, buf, eap);
9270}
9271
9272/*
9273 * Like apply_autocmds(), but handles the caller's retval. If the script
9274 * processing is being aborted or if retval is FAIL when inside a try
9275 * conditional, no autocommands are executed. If otherwise the autocommands
9276 * cause the script to be aborted, retval is set to FAIL.
9277 */
9278 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009279apply_autocmds_retval(
9280 event_T event,
9281 char_u *fname, /* NULL or empty means use actual file name */
9282 char_u *fname_io, /* fname to use for <afile> on cmdline */
9283 int force, /* when TRUE, ignore autocmd_busy */
9284 buf_T *buf, /* buffer for <abuf> */
9285 int *retval) /* pointer to caller's retval */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009286{
9287 int did_cmd;
9288
Bram Moolenaar1e015462005-09-25 22:16:38 +00009289#ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00009290 if (should_abort(*retval))
9291 return FALSE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00009292#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009293
9294 did_cmd = apply_autocmds_group(event, fname, fname_io, force,
9295 AUGROUP_ALL, buf, NULL);
Bram Moolenaar1e015462005-09-25 22:16:38 +00009296 if (did_cmd
9297#ifdef FEAT_EVAL
9298 && aborting()
9299#endif
9300 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00009301 *retval = FAIL;
9302 return did_cmd;
9303}
9304
Bram Moolenaard35f9712005-12-18 22:02:33 +00009305/*
9306 * Return TRUE when there is a CursorHold autocommand defined.
9307 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009308 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009309has_cursorhold(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009310{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009311 return (first_autopat[(int)(get_real_state() == NORMAL_BUSY
9312 ? EVENT_CURSORHOLD : EVENT_CURSORHOLDI)] != NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009313}
Bram Moolenaard35f9712005-12-18 22:02:33 +00009314
9315/*
9316 * Return TRUE if the CursorHold event can be triggered.
9317 */
9318 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009319trigger_cursorhold(void)
Bram Moolenaard35f9712005-12-18 22:02:33 +00009320{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009321 int state;
9322
Bram Moolenaar05334432011-07-20 18:29:39 +02009323 if (!did_cursorhold
9324 && has_cursorhold()
9325 && !Recording
9326 && typebuf.tb_len == 0
Bram Moolenaard29a9ee2006-09-14 09:07:34 +00009327#ifdef FEAT_INS_EXPAND
9328 && !ins_compl_active()
9329#endif
9330 )
Bram Moolenaar754b5602006-02-09 23:53:20 +00009331 {
9332 state = get_real_state();
9333 if (state == NORMAL_BUSY || (state & INSERT) != 0)
9334 return TRUE;
9335 }
9336 return FALSE;
Bram Moolenaard35f9712005-12-18 22:02:33 +00009337}
Bram Moolenaar754b5602006-02-09 23:53:20 +00009338
9339/*
9340 * Return TRUE when there is a CursorMoved autocommand defined.
9341 */
9342 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009343has_cursormoved(void)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009344{
9345 return (first_autopat[(int)EVENT_CURSORMOVED] != NULL);
9346}
9347
9348/*
9349 * Return TRUE when there is a CursorMovedI autocommand defined.
9350 */
9351 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009352has_cursormovedI(void)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009353{
9354 return (first_autopat[(int)EVENT_CURSORMOVEDI] != NULL);
9355}
Bram Moolenaar071d4272004-06-13 20:20:40 +00009356
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009357/*
Bram Moolenaar186628f2013-03-19 13:33:23 +01009358 * Return TRUE when there is a TextChanged autocommand defined.
9359 */
9360 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009361has_textchanged(void)
Bram Moolenaar186628f2013-03-19 13:33:23 +01009362{
9363 return (first_autopat[(int)EVENT_TEXTCHANGED] != NULL);
9364}
9365
9366/*
9367 * Return TRUE when there is a TextChangedI autocommand defined.
9368 */
9369 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009370has_textchangedI(void)
Bram Moolenaar186628f2013-03-19 13:33:23 +01009371{
9372 return (first_autopat[(int)EVENT_TEXTCHANGEDI] != NULL);
9373}
9374
9375/*
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009376 * Return TRUE when there is an InsertCharPre autocommand defined.
9377 */
9378 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009379has_insertcharpre(void)
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009380{
9381 return (first_autopat[(int)EVENT_INSERTCHARPRE] != NULL);
9382}
9383
Bram Moolenaard5005162014-08-22 23:05:54 +02009384/*
9385 * Return TRUE when there is an CmdUndefined autocommand defined.
9386 */
9387 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009388has_cmdundefined(void)
Bram Moolenaard5005162014-08-22 23:05:54 +02009389{
9390 return (first_autopat[(int)EVENT_CMDUNDEFINED] != NULL);
9391}
9392
9393/*
9394 * Return TRUE when there is an FuncUndefined autocommand defined.
9395 */
9396 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009397has_funcundefined(void)
Bram Moolenaard5005162014-08-22 23:05:54 +02009398{
9399 return (first_autopat[(int)EVENT_FUNCUNDEFINED] != NULL);
9400}
9401
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009402/*
9403 * Execute autocommands for "event" and file name "fname".
9404 * Return TRUE if some commands were executed.
9405 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009406 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009407apply_autocmds_group(
9408 event_T event,
9409 char_u *fname, /* NULL or empty means use actual file name */
9410 char_u *fname_io, /* fname to use for <afile> on cmdline, NULL means
Bram Moolenaar071d4272004-06-13 20:20:40 +00009411 use fname */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009412 int force, /* when TRUE, ignore autocmd_busy */
9413 int group, /* group ID, or AUGROUP_ALL */
9414 buf_T *buf, /* buffer for <abuf> */
9415 exarg_T *eap) /* command arguments */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009416{
9417 char_u *sfname = NULL; /* short file name */
9418 char_u *tail;
9419 int save_changed;
9420 buf_T *old_curbuf;
9421 int retval = FALSE;
9422 char_u *save_sourcing_name;
9423 linenr_T save_sourcing_lnum;
9424 char_u *save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009425 int save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009426 int save_autocmd_bufnr;
9427 char_u *save_autocmd_match;
9428 int save_autocmd_busy;
9429 int save_autocmd_nested;
9430 static int nesting = 0;
9431 AutoPatCmd patcmd;
9432 AutoPat *ap;
9433#ifdef FEAT_EVAL
9434 scid_T save_current_SID;
9435 void *save_funccalp;
9436 char_u *save_cmdarg;
9437 long save_cmdbang;
9438#endif
9439 static int filechangeshell_busy = FALSE;
Bram Moolenaar05159a02005-02-26 23:04:13 +00009440#ifdef FEAT_PROFILE
9441 proftime_T wait_time;
9442#endif
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009443 int did_save_redobuff = FALSE;
Bram Moolenaard4863aa2017-04-07 19:50:12 +02009444 save_redo_T save_redo;
Bram Moolenaarc9e9c712017-11-09 12:29:35 +01009445 int save_KeyTyped = KeyTyped;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009446
9447 /*
9448 * Quickly return if there are no autocommands for this event or
9449 * autocommands are blocked.
9450 */
Bram Moolenaarfaf29d72017-07-09 11:07:16 +02009451 if (event == NUM_EVENTS || first_autopat[(int)event] == NULL
9452 || autocmd_blocked > 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009453 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009454
9455 /*
9456 * When autocommands are busy, new autocommands are only executed when
9457 * explicitly enabled with the "nested" flag.
9458 */
9459 if (autocmd_busy && !(force || autocmd_nested))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009460 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009461
9462#ifdef FEAT_EVAL
9463 /*
Bram Moolenaar7263a772007-05-10 17:35:54 +00009464 * Quickly return when immediately aborting on error, or when an interrupt
Bram Moolenaar071d4272004-06-13 20:20:40 +00009465 * occurred or an exception was thrown but not caught.
9466 */
9467 if (aborting())
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009468 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009469#endif
9470
9471 /*
9472 * FileChangedShell never nests, because it can create an endless loop.
9473 */
Bram Moolenaar56718732006-03-15 22:53:57 +00009474 if (filechangeshell_busy && (event == EVENT_FILECHANGEDSHELL
9475 || event == EVENT_FILECHANGEDSHELLPOST))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009476 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009477
9478 /*
9479 * Ignore events in 'eventignore'.
9480 */
9481 if (event_ignored(event))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009482 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009483
9484 /*
9485 * Allow nesting of autocommands, but restrict the depth, because it's
9486 * possible to create an endless loop.
9487 */
9488 if (nesting == 10)
9489 {
9490 EMSG(_("E218: autocommand nesting too deep"));
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009491 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009492 }
9493
9494 /*
9495 * Check if these autocommands are disabled. Used when doing ":all" or
9496 * ":ball".
9497 */
9498 if ( (autocmd_no_enter
9499 && (event == EVENT_WINENTER || event == EVENT_BUFENTER))
9500 || (autocmd_no_leave
9501 && (event == EVENT_WINLEAVE || event == EVENT_BUFLEAVE)))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009502 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009503
9504 /*
9505 * Save the autocmd_* variables and info about the current buffer.
9506 */
9507 save_autocmd_fname = autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009508 save_autocmd_fname_full = autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009509 save_autocmd_bufnr = autocmd_bufnr;
9510 save_autocmd_match = autocmd_match;
9511 save_autocmd_busy = autocmd_busy;
9512 save_autocmd_nested = autocmd_nested;
9513 save_changed = curbuf->b_changed;
9514 old_curbuf = curbuf;
9515
9516 /*
9517 * Set the file name to be used for <afile>.
Bram Moolenaara0174af2008-01-02 20:08:25 +00009518 * Make a copy to avoid that changing a buffer name or directory makes it
9519 * invalid.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009520 */
9521 if (fname_io == NULL)
9522 {
Bram Moolenaar53744302015-07-17 17:38:22 +02009523 if (event == EVENT_COLORSCHEME || event == EVENT_OPTIONSET)
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009524 autocmd_fname = NULL;
Bram Moolenaarfaf29d72017-07-09 11:07:16 +02009525 else if (fname != NULL && !ends_excmd(*fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009526 autocmd_fname = fname;
9527 else if (buf != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009528 autocmd_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009529 else
9530 autocmd_fname = NULL;
9531 }
9532 else
9533 autocmd_fname = fname_io;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009534 if (autocmd_fname != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009535 autocmd_fname = vim_strsave(autocmd_fname);
9536 autocmd_fname_full = FALSE; /* call FullName_save() later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009537
9538 /*
9539 * Set the buffer number to be used for <abuf>.
9540 */
9541 if (buf == NULL)
9542 autocmd_bufnr = 0;
9543 else
9544 autocmd_bufnr = buf->b_fnum;
9545
9546 /*
9547 * When the file name is NULL or empty, use the file name of buffer "buf".
9548 * Always use the full path of the file name to match with, in case
9549 * "allow_dirs" is set.
9550 */
9551 if (fname == NULL || *fname == NUL)
9552 {
9553 if (buf == NULL)
9554 fname = NULL;
9555 else
9556 {
9557#ifdef FEAT_SYN_HL
9558 if (event == EVENT_SYNTAX)
9559 fname = buf->b_p_syn;
9560 else
9561#endif
9562 if (event == EVENT_FILETYPE)
9563 fname = buf->b_p_ft;
9564 else
9565 {
9566 if (buf->b_sfname != NULL)
9567 sfname = vim_strsave(buf->b_sfname);
9568 fname = buf->b_ffname;
9569 }
9570 }
9571 if (fname == NULL)
9572 fname = (char_u *)"";
9573 fname = vim_strsave(fname); /* make a copy, so we can change it */
9574 }
9575 else
9576 {
9577 sfname = vim_strsave(fname);
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009578 /* Don't try expanding FileType, Syntax, FuncUndefined, WindowID,
9579 * ColorScheme or QuickFixCmd* */
Bram Moolenaar7c626922005-02-07 22:01:03 +00009580 if (event == EVENT_FILETYPE
9581 || event == EVENT_SYNTAX
Bram Moolenaar5135d462009-04-29 16:03:38 +00009582 || event == EVENT_FUNCUNDEFINED
Bram Moolenaar7c626922005-02-07 22:01:03 +00009583 || event == EVENT_REMOTEREPLY
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00009584 || event == EVENT_SPELLFILEMISSING
Bram Moolenaar7c626922005-02-07 22:01:03 +00009585 || event == EVENT_QUICKFIXCMDPRE
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009586 || event == EVENT_COLORSCHEME
Bram Moolenaar53744302015-07-17 17:38:22 +02009587 || event == EVENT_OPTIONSET
Bram Moolenaar7c626922005-02-07 22:01:03 +00009588 || event == EVENT_QUICKFIXCMDPOST)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009589 fname = vim_strsave(fname);
9590 else
9591 fname = FullName_save(fname, FALSE);
9592 }
9593 if (fname == NULL) /* out of memory */
9594 {
9595 vim_free(sfname);
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009596 retval = FALSE;
9597 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009598 }
9599
9600#ifdef BACKSLASH_IN_FILENAME
9601 /*
9602 * Replace all backslashes with forward slashes. This makes the
9603 * autocommand patterns portable between Unix and MS-DOS.
9604 */
9605 if (sfname != NULL)
9606 forward_slash(sfname);
9607 forward_slash(fname);
9608#endif
9609
9610#ifdef VMS
9611 /* remove version for correct match */
9612 if (sfname != NULL)
9613 vms_remove_version(sfname);
9614 vms_remove_version(fname);
9615#endif
9616
9617 /*
9618 * Set the name to be used for <amatch>.
9619 */
9620 autocmd_match = fname;
9621
9622
9623 /* Don't redraw while doing auto commands. */
9624 ++RedrawingDisabled;
9625 save_sourcing_name = sourcing_name;
9626 sourcing_name = NULL; /* don't free this one */
9627 save_sourcing_lnum = sourcing_lnum;
9628 sourcing_lnum = 0; /* no line number here */
9629
9630#ifdef FEAT_EVAL
9631 save_current_SID = current_SID;
9632
Bram Moolenaar05159a02005-02-26 23:04:13 +00009633# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009634 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009635 prof_child_enter(&wait_time); /* doesn't count for the caller itself */
9636# endif
9637
Bram Moolenaar071d4272004-06-13 20:20:40 +00009638 /* Don't use local function variables, if called from a function */
9639 save_funccalp = save_funccal();
9640#endif
9641
9642 /*
9643 * When starting to execute autocommands, save the search patterns.
9644 */
9645 if (!autocmd_busy)
9646 {
9647 save_search_patterns();
Bram Moolenaar20ad69c2015-12-03 13:52:52 +01009648#ifdef FEAT_INS_EXPAND
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009649 if (!ins_compl_active())
Bram Moolenaar20ad69c2015-12-03 13:52:52 +01009650#endif
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009651 {
Bram Moolenaard4863aa2017-04-07 19:50:12 +02009652 saveRedobuff(&save_redo);
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009653 did_save_redobuff = TRUE;
9654 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009655 did_filetype = keep_filetype;
9656 }
9657
9658 /*
9659 * Note that we are applying autocmds. Some commands need to know.
9660 */
9661 autocmd_busy = TRUE;
9662 filechangeshell_busy = (event == EVENT_FILECHANGEDSHELL);
9663 ++nesting; /* see matching decrement below */
9664
9665 /* Remember that FileType was triggered. Used for did_filetype(). */
9666 if (event == EVENT_FILETYPE)
9667 did_filetype = TRUE;
9668
9669 tail = gettail(fname);
9670
9671 /* Find first autocommand that matches */
9672 patcmd.curpat = first_autopat[(int)event];
9673 patcmd.nextcmd = NULL;
9674 patcmd.group = group;
9675 patcmd.fname = fname;
9676 patcmd.sfname = sfname;
9677 patcmd.tail = tail;
9678 patcmd.event = event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009679 patcmd.arg_bufnr = autocmd_bufnr;
9680 patcmd.next = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009681 auto_next_pat(&patcmd, FALSE);
9682
9683 /* found one, start executing the autocommands */
9684 if (patcmd.curpat != NULL)
9685 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009686 /* add to active_apc_list */
9687 patcmd.next = active_apc_list;
9688 active_apc_list = &patcmd;
9689
Bram Moolenaar071d4272004-06-13 20:20:40 +00009690#ifdef FEAT_EVAL
9691 /* set v:cmdarg (only when there is a matching pattern) */
Bram Moolenaar22fcfad2016-07-01 18:17:26 +02009692 save_cmdbang = (long)get_vim_var_nr(VV_CMDBANG);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009693 if (eap != NULL)
9694 {
9695 save_cmdarg = set_cmdarg(eap, NULL);
9696 set_vim_var_nr(VV_CMDBANG, (long)eap->forceit);
9697 }
9698 else
9699 save_cmdarg = NULL; /* avoid gcc warning */
9700#endif
9701 retval = TRUE;
9702 /* mark the last pattern, to avoid an endless loop when more patterns
9703 * are added when executing autocommands */
9704 for (ap = patcmd.curpat; ap->next != NULL; ap = ap->next)
9705 ap->last = FALSE;
9706 ap->last = TRUE;
9707 check_lnums(TRUE); /* make sure cursor and topline are valid */
9708 do_cmdline(NULL, getnextac, (void *)&patcmd,
9709 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
9710#ifdef FEAT_EVAL
9711 if (eap != NULL)
9712 {
9713 (void)set_cmdarg(NULL, save_cmdarg);
9714 set_vim_var_nr(VV_CMDBANG, save_cmdbang);
9715 }
9716#endif
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009717 /* delete from active_apc_list */
9718 if (active_apc_list == &patcmd) /* just in case */
9719 active_apc_list = patcmd.next;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009720 }
9721
9722 --RedrawingDisabled;
9723 autocmd_busy = save_autocmd_busy;
9724 filechangeshell_busy = FALSE;
9725 autocmd_nested = save_autocmd_nested;
9726 vim_free(sourcing_name);
9727 sourcing_name = save_sourcing_name;
9728 sourcing_lnum = save_sourcing_lnum;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009729 vim_free(autocmd_fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009730 autocmd_fname = save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009731 autocmd_fname_full = save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009732 autocmd_bufnr = save_autocmd_bufnr;
9733 autocmd_match = save_autocmd_match;
9734#ifdef FEAT_EVAL
9735 current_SID = save_current_SID;
9736 restore_funccal(save_funccalp);
Bram Moolenaar05159a02005-02-26 23:04:13 +00009737# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009738 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009739 prof_child_exit(&wait_time);
9740# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009741#endif
Bram Moolenaarc9e9c712017-11-09 12:29:35 +01009742 KeyTyped = save_KeyTyped;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009743 vim_free(fname);
9744 vim_free(sfname);
9745 --nesting; /* see matching increment above */
9746
9747 /*
9748 * When stopping to execute autocommands, restore the search patterns and
Bram Moolenaar3be85852014-06-12 14:01:31 +02009749 * the redo buffer. Free any buffers in the au_pending_free_buf list and
9750 * free any windows in the au_pending_free_win list.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009751 */
9752 if (!autocmd_busy)
9753 {
9754 restore_search_patterns();
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009755 if (did_save_redobuff)
Bram Moolenaard4863aa2017-04-07 19:50:12 +02009756 restoreRedobuff(&save_redo);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009757 did_filetype = FALSE;
Bram Moolenaar4c7ab1b2014-04-06 20:45:43 +02009758 while (au_pending_free_buf != NULL)
9759 {
9760 buf_T *b = au_pending_free_buf->b_next;
9761 vim_free(au_pending_free_buf);
9762 au_pending_free_buf = b;
9763 }
Bram Moolenaar3be85852014-06-12 14:01:31 +02009764 while (au_pending_free_win != NULL)
9765 {
9766 win_T *w = au_pending_free_win->w_next;
9767 vim_free(au_pending_free_win);
9768 au_pending_free_win = w;
9769 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009770 }
9771
9772 /*
9773 * Some events don't set or reset the Changed flag.
9774 * Check if still in the same buffer!
9775 */
9776 if (curbuf == old_curbuf
9777 && (event == EVENT_BUFREADPOST
9778 || event == EVENT_BUFWRITEPOST
9779 || event == EVENT_FILEAPPENDPOST
9780 || event == EVENT_VIMLEAVE
9781 || event == EVENT_VIMLEAVEPRE))
9782 {
9783#ifdef FEAT_TITLE
9784 if (curbuf->b_changed != save_changed)
9785 need_maketitle = TRUE;
9786#endif
9787 curbuf->b_changed = save_changed;
9788 }
9789
9790 au_cleanup(); /* may really delete removed patterns/commands now */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009791
9792BYPASS_AU:
9793 /* When wiping out a buffer make sure all its buffer-local autocommands
9794 * are deleted. */
9795 if (event == EVENT_BUFWIPEOUT && buf != NULL)
9796 aubuflocal_remove(buf);
9797
Bram Moolenaarc3691332016-04-20 12:49:49 +02009798 if (retval == OK && event == EVENT_FILETYPE)
9799 au_did_filetype = TRUE;
9800
Bram Moolenaar071d4272004-06-13 20:20:40 +00009801 return retval;
9802}
9803
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009804# ifdef FEAT_EVAL
9805static char_u *old_termresponse = NULL;
9806# endif
9807
9808/*
9809 * Block triggering autocommands until unblock_autocmd() is called.
9810 * Can be used recursively, so long as it's symmetric.
9811 */
9812 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009813block_autocmds(void)
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009814{
9815# ifdef FEAT_EVAL
9816 /* Remember the value of v:termresponse. */
9817 if (autocmd_blocked == 0)
9818 old_termresponse = get_vim_var_str(VV_TERMRESPONSE);
9819# endif
9820 ++autocmd_blocked;
9821}
9822
9823 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009824unblock_autocmds(void)
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009825{
9826 --autocmd_blocked;
9827
9828# ifdef FEAT_EVAL
9829 /* When v:termresponse was set while autocommands were blocked, trigger
9830 * the autocommands now. Esp. useful when executing a shell command
9831 * during startup (vimdiff). */
9832 if (autocmd_blocked == 0
9833 && get_vim_var_str(VV_TERMRESPONSE) != old_termresponse)
9834 apply_autocmds(EVENT_TERMRESPONSE, NULL, NULL, FALSE, curbuf);
9835# endif
9836}
9837
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009838 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009839is_autocmd_blocked(void)
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009840{
9841 return autocmd_blocked != 0;
9842}
9843
Bram Moolenaar071d4272004-06-13 20:20:40 +00009844/*
9845 * Find next autocommand pattern that matches.
9846 */
9847 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009848auto_next_pat(
9849 AutoPatCmd *apc,
9850 int stop_at_last) /* stop when 'last' flag is set */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009851{
9852 AutoPat *ap;
9853 AutoCmd *cp;
9854 char_u *name;
9855 char *s;
9856
9857 vim_free(sourcing_name);
9858 sourcing_name = NULL;
9859
9860 for (ap = apc->curpat; ap != NULL && !got_int; ap = ap->next)
9861 {
9862 apc->curpat = NULL;
9863
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009864 /* Only use a pattern when it has not been removed, has commands and
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009865 * the group matches. For buffer-local autocommands only check the
9866 * buffer number. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009867 if (ap->pat != NULL && ap->cmds != NULL
9868 && (apc->group == AUGROUP_ALL || apc->group == ap->group))
9869 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009870 /* execution-condition */
9871 if (ap->buflocal_nr == 0
Bram Moolenaardffa5b82014-11-19 16:38:07 +01009872 ? (match_file_pat(NULL, &ap->reg_prog, apc->fname,
Bram Moolenaar748bf032005-02-02 23:04:36 +00009873 apc->sfname, apc->tail, ap->allow_dirs))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009874 : ap->buflocal_nr == apc->arg_bufnr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009875 {
9876 name = event_nr2name(apc->event);
9877 s = _("%s Auto commands for \"%s\"");
9878 sourcing_name = alloc((unsigned)(STRLEN(s)
9879 + STRLEN(name) + ap->patlen + 1));
9880 if (sourcing_name != NULL)
9881 {
9882 sprintf((char *)sourcing_name, s,
9883 (char *)name, (char *)ap->pat);
9884 if (p_verbose >= 8)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009885 {
9886 verbose_enter();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009887 smsg((char_u *)_("Executing %s"), sourcing_name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009888 verbose_leave();
9889 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009890 }
9891
9892 apc->curpat = ap;
9893 apc->nextcmd = ap->cmds;
9894 /* mark last command */
9895 for (cp = ap->cmds; cp->next != NULL; cp = cp->next)
9896 cp->last = FALSE;
9897 cp->last = TRUE;
9898 }
9899 line_breakcheck();
9900 if (apc->curpat != NULL) /* found a match */
9901 break;
9902 }
9903 if (stop_at_last && ap->last)
9904 break;
9905 }
9906}
9907
9908/*
9909 * Get next autocommand command.
9910 * Called by do_cmdline() to get the next line for ":if".
9911 * Returns allocated string, or NULL for end of autocommands.
9912 */
Bram Moolenaar21691f82012-12-05 19:13:18 +01009913 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009914getnextac(int c UNUSED, void *cookie, int indent UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009915{
9916 AutoPatCmd *acp = (AutoPatCmd *)cookie;
9917 char_u *retval;
9918 AutoCmd *ac;
9919
9920 /* Can be called again after returning the last line. */
9921 if (acp->curpat == NULL)
9922 return NULL;
9923
9924 /* repeat until we find an autocommand to execute */
9925 for (;;)
9926 {
9927 /* skip removed commands */
9928 while (acp->nextcmd != NULL && acp->nextcmd->cmd == NULL)
9929 if (acp->nextcmd->last)
9930 acp->nextcmd = NULL;
9931 else
9932 acp->nextcmd = acp->nextcmd->next;
9933
9934 if (acp->nextcmd != NULL)
9935 break;
9936
9937 /* at end of commands, find next pattern that matches */
9938 if (acp->curpat->last)
9939 acp->curpat = NULL;
9940 else
9941 acp->curpat = acp->curpat->next;
9942 if (acp->curpat != NULL)
9943 auto_next_pat(acp, TRUE);
9944 if (acp->curpat == NULL)
9945 return NULL;
9946 }
9947
9948 ac = acp->nextcmd;
9949
9950 if (p_verbose >= 9)
9951 {
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009952 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009953 smsg((char_u *)_("autocommand %s"), ac->cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009954 msg_puts((char_u *)"\n"); /* don't overwrite this either */
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009955 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009956 }
9957 retval = vim_strsave(ac->cmd);
9958 autocmd_nested = ac->nested;
9959#ifdef FEAT_EVAL
9960 current_SID = ac->scriptID;
9961#endif
9962 if (ac->last)
9963 acp->nextcmd = NULL;
9964 else
9965 acp->nextcmd = ac->next;
9966 return retval;
9967}
9968
9969/*
9970 * Return TRUE if there is a matching autocommand for "fname".
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009971 * To account for buffer-local autocommands, function needs to know
9972 * in which buffer the file will be opened.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009973 */
9974 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009975has_autocmd(event_T event, char_u *sfname, buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009976{
9977 AutoPat *ap;
9978 char_u *fname;
9979 char_u *tail = gettail(sfname);
9980 int retval = FALSE;
9981
9982 fname = FullName_save(sfname, FALSE);
9983 if (fname == NULL)
9984 return FALSE;
9985
9986#ifdef BACKSLASH_IN_FILENAME
9987 /*
9988 * Replace all backslashes with forward slashes. This makes the
9989 * autocommand patterns portable between Unix and MS-DOS.
9990 */
9991 sfname = vim_strsave(sfname);
9992 if (sfname != NULL)
9993 forward_slash(sfname);
9994 forward_slash(fname);
9995#endif
9996
9997 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
9998 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009999 && (ap->buflocal_nr == 0
Bram Moolenaardffa5b82014-11-19 16:38:07 +010010000 ? match_file_pat(NULL, &ap->reg_prog,
Bram Moolenaar748bf032005-02-02 23:04:36 +000010001 fname, sfname, tail, ap->allow_dirs)
Bram Moolenaarc9b4b052006-04-30 18:54:39 +000010002 : buf != NULL && ap->buflocal_nr == buf->b_fnum
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010003 ))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010004 {
10005 retval = TRUE;
10006 break;
10007 }
10008
10009 vim_free(fname);
10010#ifdef BACKSLASH_IN_FILENAME
10011 vim_free(sfname);
10012#endif
10013
10014 return retval;
10015}
10016
10017#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
10018/*
10019 * Function given to ExpandGeneric() to obtain the list of autocommand group
10020 * names.
10021 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010022 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010023get_augroup_name(expand_T *xp UNUSED, int idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010024{
10025 if (idx == augroups.ga_len) /* add "END" add the end */
10026 return (char_u *)"END";
10027 if (idx >= augroups.ga_len) /* end of list */
10028 return NULL;
Bram Moolenaarb62cc362016-09-03 16:43:53 +020010029 if (AUGROUP_NAME(idx) == NULL || AUGROUP_NAME(idx) == get_deleted_augroup())
Bram Moolenaarf2c4c392016-07-29 20:50:24 +020010030 /* skip deleted entries */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010031 return (char_u *)"";
10032 return AUGROUP_NAME(idx); /* return a name */
10033}
10034
10035static int include_groups = FALSE;
10036
10037 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010038set_context_in_autocmd(
10039 expand_T *xp,
10040 char_u *arg,
10041 int doautocmd) /* TRUE for :doauto*, FALSE for :autocmd */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010042{
10043 char_u *p;
10044 int group;
10045
10046 /* check for a group name, skip it if present */
10047 include_groups = FALSE;
10048 p = arg;
10049 group = au_get_grouparg(&arg);
10050 if (group == AUGROUP_ERROR)
10051 return NULL;
10052 /* If there only is a group name that's what we expand. */
Bram Moolenaar1c465442017-03-12 20:10:05 +010010053 if (*arg == NUL && group != AUGROUP_ALL && !VIM_ISWHITE(arg[-1]))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010054 {
10055 arg = p;
10056 group = AUGROUP_ALL;
10057 }
10058
10059 /* skip over event name */
Bram Moolenaar1c465442017-03-12 20:10:05 +010010060 for (p = arg; *p != NUL && !VIM_ISWHITE(*p); ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010061 if (*p == ',')
10062 arg = p + 1;
10063 if (*p == NUL)
10064 {
10065 if (group == AUGROUP_ALL)
10066 include_groups = TRUE;
10067 xp->xp_context = EXPAND_EVENTS; /* expand event name */
10068 xp->xp_pattern = arg;
10069 return NULL;
10070 }
10071
10072 /* skip over pattern */
10073 arg = skipwhite(p);
Bram Moolenaar1c465442017-03-12 20:10:05 +010010074 while (*arg && (!VIM_ISWHITE(*arg) || arg[-1] == '\\'))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010075 arg++;
10076 if (*arg)
10077 return arg; /* expand (next) command */
10078
10079 if (doautocmd)
10080 xp->xp_context = EXPAND_FILES; /* expand file names */
10081 else
10082 xp->xp_context = EXPAND_NOTHING; /* pattern is not expanded */
10083 return NULL;
10084}
10085
10086/*
10087 * Function given to ExpandGeneric() to obtain the list of event names.
10088 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010089 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010090get_event_name(expand_T *xp UNUSED, int idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010091{
10092 if (idx < augroups.ga_len) /* First list group names, if wanted */
10093 {
Bram Moolenaarf2c4c392016-07-29 20:50:24 +020010094 if (!include_groups || AUGROUP_NAME(idx) == NULL
Bram Moolenaarb62cc362016-09-03 16:43:53 +020010095 || AUGROUP_NAME(idx) == get_deleted_augroup())
Bram Moolenaar071d4272004-06-13 20:20:40 +000010096 return (char_u *)""; /* skip deleted entries */
10097 return AUGROUP_NAME(idx); /* return a name */
10098 }
10099 return (char_u *)event_names[idx - augroups.ga_len].name;
10100}
10101
10102#endif /* FEAT_CMDL_COMPL */
10103
10104/*
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010105 * Return TRUE if autocmd is supported.
10106 */
10107 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010108autocmd_supported(char_u *name)
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010109{
10110 char_u *p;
10111
10112 return (event_name2nr(name, &p) != NUM_EVENTS);
10113}
10114
10115/*
Bram Moolenaar195d6352005-12-19 22:08:24 +000010116 * Return TRUE if an autocommand is defined for a group, event and
10117 * pattern: The group can be omitted to accept any group. "event" and "pattern"
10118 * can be NULL to accept any event and pattern. "pattern" can be NULL to accept
10119 * any pattern. Buffer-local patterns <buffer> or <buffer=N> are accepted.
10120 * Used for:
10121 * exists("#Group") or
10122 * exists("#Group#Event") or
10123 * exists("#Group#Event#pat") or
10124 * exists("#Event") or
10125 * exists("#Event#pat")
Bram Moolenaar071d4272004-06-13 20:20:40 +000010126 */
10127 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010128au_exists(char_u *arg)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010129{
Bram Moolenaar195d6352005-12-19 22:08:24 +000010130 char_u *arg_save;
10131 char_u *pattern = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010132 char_u *event_name;
10133 char_u *p;
Bram Moolenaar754b5602006-02-09 23:53:20 +000010134 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010135 AutoPat *ap;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010136 buf_T *buflocal_buf = NULL;
Bram Moolenaar195d6352005-12-19 22:08:24 +000010137 int group;
10138 int retval = FALSE;
10139
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010140 /* Make a copy so that we can change the '#' chars to a NUL. */
Bram Moolenaar195d6352005-12-19 22:08:24 +000010141 arg_save = vim_strsave(arg);
10142 if (arg_save == NULL)
10143 return FALSE;
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010144 p = vim_strchr(arg_save, '#');
Bram Moolenaar195d6352005-12-19 22:08:24 +000010145 if (p != NULL)
10146 *p++ = NUL;
10147
10148 /* First, look for an autocmd group name */
10149 group = au_find_group(arg_save);
10150 if (group == AUGROUP_ERROR)
10151 {
10152 /* Didn't match a group name, assume the first argument is an event. */
10153 group = AUGROUP_ALL;
10154 event_name = arg_save;
10155 }
10156 else
10157 {
10158 if (p == NULL)
10159 {
10160 /* "Group": group name is present and it's recognized */
10161 retval = TRUE;
10162 goto theend;
10163 }
10164
10165 /* Must be "Group#Event" or "Group#Event#pat". */
10166 event_name = p;
10167 p = vim_strchr(event_name, '#');
10168 if (p != NULL)
10169 *p++ = NUL; /* "Group#Event#pat" */
10170 }
10171
10172 pattern = p; /* "pattern" is NULL when there is no pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010173
10174 /* find the index (enum) for the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010175 event = event_name2nr(event_name, &p);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010176
10177 /* return FALSE if the event name is not recognized */
Bram Moolenaar195d6352005-12-19 22:08:24 +000010178 if (event == NUM_EVENTS)
10179 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010180
10181 /* Find the first autocommand for this event.
10182 * If there isn't any, return FALSE;
10183 * If there is one and no pattern given, return TRUE; */
10184 ap = first_autopat[(int)event];
10185 if (ap == NULL)
Bram Moolenaar195d6352005-12-19 22:08:24 +000010186 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010187
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010188 /* if pattern is "<buffer>", special handling is needed which uses curbuf */
10189 /* for pattern "<buffer=N>, fnamecmp() will work fine */
Bram Moolenaar5b7880d2009-09-11 15:24:31 +000010190 if (pattern != NULL && STRICMP(pattern, "<buffer>") == 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010191 buflocal_buf = curbuf;
10192
Bram Moolenaar071d4272004-06-13 20:20:40 +000010193 /* Check if there is an autocommand with the given pattern. */
10194 for ( ; ap != NULL; ap = ap->next)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010195 /* only use a pattern when it has not been removed and has commands. */
10196 /* For buffer-local autocommands, fnamecmp() works fine. */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010197 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaar195d6352005-12-19 22:08:24 +000010198 && (group == AUGROUP_ALL || ap->group == group)
Bram Moolenaar5b7880d2009-09-11 15:24:31 +000010199 && (pattern == NULL
10200 || (buflocal_buf == NULL
10201 ? fnamecmp(ap->pat, pattern) == 0
10202 : ap->buflocal_nr == buflocal_buf->b_fnum)))
Bram Moolenaar195d6352005-12-19 22:08:24 +000010203 {
10204 retval = TRUE;
10205 break;
10206 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010207
Bram Moolenaar195d6352005-12-19 22:08:24 +000010208theend:
10209 vim_free(arg_save);
10210 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010211}
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010212
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010213#else /* FEAT_AUTOCMD */
10214
10215/*
10216 * Prepare for executing commands for (hidden) buffer "buf".
10217 * This is the non-autocommand version, it simply saves "curbuf" and sets
10218 * "curbuf" and "curwin" to match "buf".
10219 */
10220 void
Bram Moolenaard14e00e2016-01-31 17:30:51 +010010221aucmd_prepbuf(
10222 aco_save_T *aco, /* structure to save values in */
10223 buf_T *buf) /* new curbuf */
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010224{
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010225 aco->save_curbuf = curbuf;
10226 --curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010227 curbuf = buf;
10228 curwin->w_buffer = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010229 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010230}
10231
10232/*
10233 * Restore after executing commands for a (hidden) buffer.
10234 * This is the non-autocommand version.
10235 */
10236 void
Bram Moolenaard14e00e2016-01-31 17:30:51 +010010237aucmd_restbuf(
10238 aco_save_T *aco) /* structure holding saved values */
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010239{
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010240 --curbuf->b_nwindows;
10241 curbuf = aco->save_curbuf;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010242 curwin->w_buffer = curbuf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010243 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010244}
10245
Bram Moolenaar071d4272004-06-13 20:20:40 +000010246#endif /* FEAT_AUTOCMD */
10247
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010248
Bram Moolenaar071d4272004-06-13 20:20:40 +000010249#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN) || defined(PROTO)
10250/*
Bram Moolenaar748bf032005-02-02 23:04:36 +000010251 * Try matching a filename with a "pattern" ("prog" is NULL), or use the
10252 * precompiled regprog "prog" ("pattern" is NULL). That avoids calling
10253 * vim_regcomp() often.
Bram Moolenaar071d4272004-06-13 20:20:40 +000010254 * Used for autocommands and 'wildignore'.
10255 * Returns TRUE if there is a match, FALSE otherwise.
10256 */
Bram Moolenaardffa5b82014-11-19 16:38:07 +010010257 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010258match_file_pat(
10259 char_u *pattern, /* pattern to match with */
10260 regprog_T **prog, /* pre-compiled regprog or NULL */
10261 char_u *fname, /* full path of file name */
10262 char_u *sfname, /* short file name or NULL */
10263 char_u *tail, /* tail of path */
10264 int allow_dirs) /* allow matching with dir */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010265{
10266 regmatch_T regmatch;
10267 int result = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010268
Bram Moolenaar71afbfe2013-03-19 16:49:16 +010010269 regmatch.rm_ic = p_fic; /* ignore case if 'fileignorecase' is set */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010270 if (prog != NULL)
10271 regmatch.regprog = *prog;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010272 else
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010273 regmatch.regprog = vim_regcomp(pattern, RE_MAGIC);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010274
10275 /*
10276 * Try for a match with the pattern with:
10277 * 1. the full file name, when the pattern has a '/'.
10278 * 2. the short file name, when the pattern has a '/'.
10279 * 3. the tail of the file name, when the pattern has no '/'.
10280 */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010281 if (regmatch.regprog != NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +000010282 && ((allow_dirs
10283 && (vim_regexec(&regmatch, fname, (colnr_T)0)
10284 || (sfname != NULL
10285 && vim_regexec(&regmatch, sfname, (colnr_T)0))))
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010286 || (!allow_dirs && vim_regexec(&regmatch, tail, (colnr_T)0))))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010287 result = TRUE;
10288
Bram Moolenaardffa5b82014-11-19 16:38:07 +010010289 if (prog != NULL)
10290 *prog = regmatch.regprog;
10291 else
Bram Moolenaar473de612013-06-08 18:19:48 +020010292 vim_regfree(regmatch.regprog);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010293 return result;
10294}
10295#endif
10296
10297#if defined(FEAT_WILDIGN) || defined(PROTO)
10298/*
10299 * Return TRUE if a file matches with a pattern in "list".
10300 * "list" is a comma-separated list of patterns, like 'wildignore'.
10301 * "sfname" is the short file name or NULL, "ffname" the long file name.
10302 */
10303 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010304match_file_list(char_u *list, char_u *sfname, char_u *ffname)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010305{
10306 char_u buf[100];
10307 char_u *tail;
10308 char_u *regpat;
10309 char allow_dirs;
10310 int match;
10311 char_u *p;
10312
10313 tail = gettail(sfname);
10314
10315 /* try all patterns in 'wildignore' */
10316 p = list;
10317 while (*p)
10318 {
10319 copy_option_part(&p, buf, 100, ",");
10320 regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, FALSE);
10321 if (regpat == NULL)
10322 break;
Bram Moolenaar748bf032005-02-02 23:04:36 +000010323 match = match_file_pat(regpat, NULL, ffname, sfname,
10324 tail, (int)allow_dirs);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010325 vim_free(regpat);
10326 if (match)
10327 return TRUE;
10328 }
10329 return FALSE;
10330}
10331#endif
10332
10333/*
10334 * Convert the given pattern "pat" which has shell style wildcards in it, into
10335 * a regular expression, and return the result in allocated memory. If there
10336 * is a directory path separator to be matched, then TRUE is put in
10337 * allow_dirs, otherwise FALSE is put there -- webb.
10338 * Handle backslashes before special characters, like "\*" and "\ ".
10339 *
Bram Moolenaar071d4272004-06-13 20:20:40 +000010340 * Returns NULL when out of memory.
10341 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010342 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010343file_pat_to_reg_pat(
10344 char_u *pat,
10345 char_u *pat_end, /* first char after pattern or NULL */
10346 char *allow_dirs, /* Result passed back out in here */
10347 int no_bslash UNUSED) /* Don't use a backward slash as pathsep */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010348{
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010349 int size = 2; /* '^' at start, '$' at end */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010350 char_u *endp;
10351 char_u *reg_pat;
10352 char_u *p;
10353 int i;
10354 int nested = 0;
10355 int add_dollar = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010356
10357 if (allow_dirs != NULL)
10358 *allow_dirs = FALSE;
10359 if (pat_end == NULL)
10360 pat_end = pat + STRLEN(pat);
10361
Bram Moolenaar071d4272004-06-13 20:20:40 +000010362 for (p = pat; p < pat_end; p++)
10363 {
10364 switch (*p)
10365 {
10366 case '*':
10367 case '.':
10368 case ',':
10369 case '{':
10370 case '}':
10371 case '~':
10372 size += 2; /* extra backslash */
10373 break;
10374#ifdef BACKSLASH_IN_FILENAME
10375 case '\\':
10376 case '/':
10377 size += 4; /* could become "[\/]" */
10378 break;
10379#endif
10380 default:
10381 size++;
Bram Moolenaar2288afe2015-08-11 16:20:05 +020010382# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010383 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010384 {
10385 ++p;
10386 ++size;
10387 }
10388# endif
10389 break;
10390 }
10391 }
10392 reg_pat = alloc(size + 1);
10393 if (reg_pat == NULL)
10394 return NULL;
10395
Bram Moolenaar071d4272004-06-13 20:20:40 +000010396 i = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010397
10398 if (pat[0] == '*')
10399 while (pat[0] == '*' && pat < pat_end - 1)
10400 pat++;
10401 else
10402 reg_pat[i++] = '^';
10403 endp = pat_end - 1;
Bram Moolenaar8fee8782015-08-11 18:45:48 +020010404 if (endp >= pat && *endp == '*')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010405 {
10406 while (endp - pat > 0 && *endp == '*')
10407 endp--;
10408 add_dollar = FALSE;
10409 }
10410 for (p = pat; *p && nested >= 0 && p <= endp; p++)
10411 {
10412 switch (*p)
10413 {
10414 case '*':
10415 reg_pat[i++] = '.';
10416 reg_pat[i++] = '*';
Bram Moolenaar02743632005-07-25 20:42:36 +000010417 while (p[1] == '*') /* "**" matches like "*" */
10418 ++p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010419 break;
10420 case '.':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010421 case '~':
10422 reg_pat[i++] = '\\';
10423 reg_pat[i++] = *p;
10424 break;
10425 case '?':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010426 reg_pat[i++] = '.';
10427 break;
10428 case '\\':
10429 if (p[1] == NUL)
10430 break;
10431#ifdef BACKSLASH_IN_FILENAME
10432 if (!no_bslash)
10433 {
10434 /* translate:
10435 * "\x" to "\\x" e.g., "dir\file"
10436 * "\*" to "\\.*" e.g., "dir\*.c"
10437 * "\?" to "\\." e.g., "dir\??.c"
10438 * "\+" to "\+" e.g., "fileX\+.c"
10439 */
10440 if ((vim_isfilec(p[1]) || p[1] == '*' || p[1] == '?')
10441 && p[1] != '+')
10442 {
10443 reg_pat[i++] = '[';
10444 reg_pat[i++] = '\\';
10445 reg_pat[i++] = '/';
10446 reg_pat[i++] = ']';
10447 if (allow_dirs != NULL)
10448 *allow_dirs = TRUE;
10449 break;
10450 }
10451 }
10452#endif
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010453 /* Undo escaping from ExpandEscape():
10454 * foo\?bar -> foo?bar
10455 * foo\%bar -> foo%bar
10456 * foo\,bar -> foo,bar
10457 * foo\ bar -> foo bar
10458 * Don't unescape \, * and others that are also special in a
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010459 * regexp.
10460 * An escaped { must be unescaped since we use magic not
Bram Moolenaara946afe2013-08-02 15:22:39 +020010461 * verymagic. Use "\\\{n,m\}"" to get "\{n,m}".
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010462 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010463 if (*++p == '?'
10464#ifdef BACKSLASH_IN_FILENAME
10465 && no_bslash
10466#endif
10467 )
10468 reg_pat[i++] = '?';
10469 else
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010470 if (*p == ',' || *p == '%' || *p == '#'
Bram Moolenaar2288afe2015-08-11 16:20:05 +020010471 || vim_isspace(*p) || *p == '{' || *p == '}')
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010472 reg_pat[i++] = *p;
Bram Moolenaara946afe2013-08-02 15:22:39 +020010473 else if (*p == '\\' && p[1] == '\\' && p[2] == '{')
10474 {
10475 reg_pat[i++] = '\\';
10476 reg_pat[i++] = '{';
10477 p += 2;
10478 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010479 else
10480 {
10481 if (allow_dirs != NULL && vim_ispathsep(*p)
10482#ifdef BACKSLASH_IN_FILENAME
10483 && (!no_bslash || *p != '\\')
10484#endif
10485 )
10486 *allow_dirs = TRUE;
10487 reg_pat[i++] = '\\';
10488 reg_pat[i++] = *p;
10489 }
10490 break;
10491#ifdef BACKSLASH_IN_FILENAME
10492 case '/':
10493 reg_pat[i++] = '[';
10494 reg_pat[i++] = '\\';
10495 reg_pat[i++] = '/';
10496 reg_pat[i++] = ']';
10497 if (allow_dirs != NULL)
10498 *allow_dirs = TRUE;
10499 break;
10500#endif
10501 case '{':
10502 reg_pat[i++] = '\\';
10503 reg_pat[i++] = '(';
10504 nested++;
10505 break;
10506 case '}':
10507 reg_pat[i++] = '\\';
10508 reg_pat[i++] = ')';
10509 --nested;
10510 break;
10511 case ',':
10512 if (nested)
10513 {
10514 reg_pat[i++] = '\\';
10515 reg_pat[i++] = '|';
10516 }
10517 else
10518 reg_pat[i++] = ',';
10519 break;
10520 default:
10521# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010522 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010523 reg_pat[i++] = *p++;
10524 else
10525# endif
10526 if (allow_dirs != NULL && vim_ispathsep(*p))
10527 *allow_dirs = TRUE;
10528 reg_pat[i++] = *p;
10529 break;
10530 }
10531 }
10532 if (add_dollar)
10533 reg_pat[i++] = '$';
10534 reg_pat[i] = NUL;
10535 if (nested != 0)
10536 {
10537 if (nested < 0)
10538 EMSG(_("E219: Missing {."));
10539 else
10540 EMSG(_("E220: Missing }."));
10541 vim_free(reg_pat);
10542 reg_pat = NULL;
10543 }
10544 return reg_pat;
10545}
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010546
10547#if defined(EINTR) || defined(PROTO)
10548/*
10549 * Version of read() that retries when interrupted by EINTR (possibly
10550 * by a SIGWINCH).
10551 */
10552 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010553read_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010554{
10555 long ret;
10556
10557 for (;;)
10558 {
10559 ret = vim_read(fd, buf, bufsize);
10560 if (ret >= 0 || errno != EINTR)
10561 break;
10562 }
10563 return ret;
10564}
10565
10566/*
10567 * Version of write() that retries when interrupted by EINTR (possibly
10568 * by a SIGWINCH).
10569 */
10570 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010571write_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010572{
10573 long ret = 0;
10574 long wlen;
10575
10576 /* Repeat the write() so long it didn't fail, other than being interrupted
10577 * by a signal. */
10578 while (ret < (long)bufsize)
10579 {
Bram Moolenaar9c263032010-12-17 18:06:06 +010010580 wlen = vim_write(fd, (char *)buf + ret, bufsize - ret);
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010581 if (wlen < 0)
10582 {
10583 if (errno != EINTR)
10584 break;
10585 }
10586 else
10587 ret += wlen;
10588 }
10589 return ret;
10590}
10591#endif