blob: f54fb84657ee8527b88bc29ad48dcce9c986577e [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
71# ifdef MACOS_X
72# 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
130# ifdef MACOS_X
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 Moolenaar071d4272004-06-13 20:20:40 +0000719 (void)mch_setperm(curbuf->b_ml.ml_mfp->mf_fname, (long)swap_mode);
720#endif
721 }
722
Bram Moolenaarb815dac2005-12-07 20:59:24 +0000723#if defined(HAS_SWAP_EXISTS_ACTION)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000724 /* If "Quit" selected at ATTENTION dialog, don't load the file */
725 if (swap_exists_action == SEA_QUIT)
726 {
727 if (!read_buffer && !read_stdin)
728 close(fd);
729 return FAIL;
730 }
731#endif
732
733 ++no_wait_return; /* don't wait for return yet */
734
735 /*
736 * Set '[ mark to the line above where the lines go (line 1 if zero).
737 */
738 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
739 curbuf->b_op_start.col = 0;
740
Bram Moolenaar7a2699e2017-01-23 21:31:09 +0100741 try_mac = (vim_strchr(p_ffs, 'm') != NULL);
742 try_dos = (vim_strchr(p_ffs, 'd') != NULL);
743 try_unix = (vim_strchr(p_ffs, 'x') != NULL);
744
Bram Moolenaar071d4272004-06-13 20:20:40 +0000745#ifdef FEAT_AUTOCMD
746 if (!read_buffer)
747 {
748 int m = msg_scroll;
749 int n = msg_scrolled;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000750
751 /*
752 * The file must be closed again, the autocommands may want to change
753 * the file before reading it.
754 */
755 if (!read_stdin)
756 close(fd); /* ignore errors */
757
758 /*
759 * The output from the autocommands should not overwrite anything and
760 * should not be overwritten: Set msg_scroll, restore its value if no
761 * output was done.
762 */
763 msg_scroll = TRUE;
764 if (filtering)
765 apply_autocmds_exarg(EVENT_FILTERREADPRE, NULL, sfname,
766 FALSE, curbuf, eap);
767 else if (read_stdin)
768 apply_autocmds_exarg(EVENT_STDINREADPRE, NULL, sfname,
769 FALSE, curbuf, eap);
770 else if (newfile)
771 apply_autocmds_exarg(EVENT_BUFREADPRE, NULL, sfname,
772 FALSE, curbuf, eap);
773 else
774 apply_autocmds_exarg(EVENT_FILEREADPRE, sfname, sfname,
775 FALSE, NULL, eap);
Bram Moolenaar7a2699e2017-01-23 21:31:09 +0100776 /* autocommands may have changed it */
777 try_mac = (vim_strchr(p_ffs, 'm') != NULL);
778 try_dos = (vim_strchr(p_ffs, 'd') != NULL);
779 try_unix = (vim_strchr(p_ffs, 'x') != NULL);
780
Bram Moolenaar071d4272004-06-13 20:20:40 +0000781 if (msg_scrolled == n)
782 msg_scroll = m;
783
784#ifdef FEAT_EVAL
785 if (aborting()) /* autocmds may abort script processing */
786 {
787 --no_wait_return;
788 msg_scroll = msg_save;
789 curbuf->b_p_ro = TRUE; /* must use "w!" now */
790 return FAIL;
791 }
792#endif
793 /*
794 * Don't allow the autocommands to change the current buffer.
795 * Try to re-open the file.
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000796 *
797 * Don't allow the autocommands to change the buffer name either
798 * (cd for example) if it invalidates fname or sfname.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000799 */
800 if (!read_stdin && (curbuf != old_curbuf
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000801 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
802 || (using_b_fname && (old_b_fname != curbuf->b_fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000803 || (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) < 0))
804 {
805 --no_wait_return;
806 msg_scroll = msg_save;
807 if (fd < 0)
808 EMSG(_("E200: *ReadPre autocommands made the file unreadable"));
809 else
810 EMSG(_("E201: *ReadPre autocommands must not change current buffer"));
811 curbuf->b_p_ro = TRUE; /* must use "w!" now */
812 return FAIL;
813 }
814 }
815#endif /* FEAT_AUTOCMD */
816
817 /* Autocommands may add lines to the file, need to check if it is empty */
818 wasempty = (curbuf->b_ml.ml_flags & ML_EMPTY);
819
820 if (!recoverymode && !filtering && !(flags & READ_DUMMY))
821 {
822 /*
823 * Show the user that we are busy reading the input. Sometimes this
824 * may take a while. When reading from stdin another program may
825 * still be running, don't move the cursor to the last line, unless
826 * always using the GUI.
827 */
828 if (read_stdin)
829 {
830#ifndef ALWAYS_USE_GUI
831 mch_msg(_("Vim: Reading from stdin...\n"));
832#endif
833#ifdef FEAT_GUI
834 /* Also write a message in the GUI window, if there is one. */
835 if (gui.in_use && !gui.dying && !gui.starting)
836 {
837 p = (char_u *)_("Reading from stdin...");
838 gui_write(p, (int)STRLEN(p));
839 }
840#endif
841 }
842 else if (!read_buffer)
843 filemess(curbuf, sfname, (char_u *)"", 0);
844 }
845
846 msg_scroll = FALSE; /* overwrite the file message */
847
848 /*
849 * Set linecnt now, before the "retry" caused by a wrong guess for
850 * fileformat, and after the autocommands, which may change them.
851 */
852 linecnt = curbuf->b_ml.ml_line_count;
853
854#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000855 /* "++bad=" argument. */
856 if (eap != NULL && eap->bad_char != 0)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000857 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000858 bad_char_behavior = eap->bad_char;
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000859 if (set_options)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000860 curbuf->b_bad_char = eap->bad_char;
861 }
862 else
863 curbuf->b_bad_char = 0;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000864
Bram Moolenaar071d4272004-06-13 20:20:40 +0000865 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000866 * Decide which 'encoding' to use or use first.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000867 */
868 if (eap != NULL && eap->force_enc != 0)
869 {
870 fenc = enc_canonize(eap->cmd + eap->force_enc);
871 fenc_alloced = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000872 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000873 }
874 else if (curbuf->b_p_bin)
875 {
876 fenc = (char_u *)""; /* binary: don't convert */
877 fenc_alloced = FALSE;
878 }
879 else if (curbuf->b_help)
880 {
881 char_u firstline[80];
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000882 int fc;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000883
884 /* Help files are either utf-8 or latin1. Try utf-8 first, if this
885 * fails it must be latin1.
886 * Always do this when 'encoding' is "utf-8". Otherwise only do
887 * this when needed to avoid [converted] remarks all the time.
888 * It is needed when the first line contains non-ASCII characters.
889 * That is only in *.??x files. */
890 fenc = (char_u *)"latin1";
891 c = enc_utf8;
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000892 if (!c && !read_stdin)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000893 {
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000894 fc = fname[STRLEN(fname) - 1];
895 if (TOLOWER_ASC(fc) == 'x')
896 {
897 /* Read the first line (and a bit more). Immediately rewind to
898 * the start of the file. If the read() fails "len" is -1. */
Bram Moolenaar540fc6f2010-12-17 16:27:16 +0100899 len = read_eintr(fd, firstline, 80);
Bram Moolenaar8767f522016-07-01 17:17:39 +0200900 vim_lseek(fd, (off_T)0L, SEEK_SET);
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000901 for (p = firstline; p < firstline + len; ++p)
902 if (*p >= 0x80)
903 {
904 c = TRUE;
905 break;
906 }
907 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000908 }
909
910 if (c)
911 {
912 fenc_next = fenc;
913 fenc = (char_u *)"utf-8";
914
915 /* When the file is utf-8 but a character doesn't fit in
916 * 'encoding' don't retry. In help text editing utf-8 bytes
917 * doesn't make sense. */
Bram Moolenaarf193fff2006-04-27 00:02:13 +0000918 if (!enc_utf8)
919 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000920 }
921 fenc_alloced = FALSE;
922 }
923 else if (*p_fencs == NUL)
924 {
925 fenc = curbuf->b_p_fenc; /* use format from buffer */
926 fenc_alloced = FALSE;
927 }
928 else
929 {
930 fenc_next = p_fencs; /* try items in 'fileencodings' */
931 fenc = next_fenc(&fenc_next);
932 fenc_alloced = TRUE;
933 }
934#endif
935
936 /*
937 * Jump back here to retry reading the file in different ways.
938 * Reasons to retry:
939 * - encoding conversion failed: try another one from "fenc_next"
940 * - BOM detected and fenc was set, need to setup conversion
941 * - "fileformat" check failed: try another
942 *
943 * Variables set for special retry actions:
944 * "file_rewind" Rewind the file to start reading it again.
945 * "advance_fenc" Advance "fenc" using "fenc_next".
946 * "skip_read" Re-use already read bytes (BOM detected).
947 * "did_iconv" iconv() conversion failed, try 'charconvert'.
948 * "keep_fileformat" Don't reset "fileformat".
949 *
950 * Other status indicators:
951 * "tmpname" When != NULL did conversion with 'charconvert'.
952 * Output file has to be deleted afterwards.
953 * "iconv_fd" When != -1 did conversion with iconv().
954 */
955retry:
956
957 if (file_rewind)
958 {
959 if (read_buffer)
960 {
961 read_buf_lnum = 1;
962 read_buf_col = 0;
963 }
Bram Moolenaar8767f522016-07-01 17:17:39 +0200964 else if (read_stdin || vim_lseek(fd, (off_T)0L, SEEK_SET) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000965 {
966 /* Can't rewind the file, give up. */
967 error = TRUE;
968 goto failed;
969 }
970 /* Delete the previously read lines. */
971 while (lnum > from)
972 ml_delete(lnum--, FALSE);
973 file_rewind = FALSE;
974#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000975 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000976 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000977 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000978 curbuf->b_start_bomb = FALSE;
979 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000980 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000981#endif
982 }
983
984 /*
985 * When retrying with another "fenc" and the first time "fileformat"
986 * will be reset.
987 */
988 if (keep_fileformat)
989 keep_fileformat = FALSE;
990 else
991 {
992 if (eap != NULL && eap->force_ff != 0)
Bram Moolenaar1c860362008-11-12 15:05:21 +0000993 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000994 fileformat = get_fileformat_force(curbuf, eap);
Bram Moolenaar1c860362008-11-12 15:05:21 +0000995 try_unix = try_dos = try_mac = FALSE;
996 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000997 else if (curbuf->b_p_bin)
998 fileformat = EOL_UNIX; /* binary: use Unix format */
999 else if (*p_ffs == NUL)
1000 fileformat = get_fileformat(curbuf);/* use format from buffer */
1001 else
1002 fileformat = EOL_UNKNOWN; /* detect from file */
1003 }
1004
1005#ifdef FEAT_MBYTE
1006# ifdef USE_ICONV
1007 if (iconv_fd != (iconv_t)-1)
1008 {
1009 /* aborted conversion with iconv(), close the descriptor */
1010 iconv_close(iconv_fd);
1011 iconv_fd = (iconv_t)-1;
1012 }
1013# endif
1014
1015 if (advance_fenc)
1016 {
1017 /*
1018 * Try the next entry in 'fileencodings'.
1019 */
1020 advance_fenc = FALSE;
1021
1022 if (eap != NULL && eap->force_enc != 0)
1023 {
1024 /* Conversion given with "++cc=" wasn't possible, read
1025 * without conversion. */
1026 notconverted = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001027 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001028 if (fenc_alloced)
1029 vim_free(fenc);
1030 fenc = (char_u *)"";
1031 fenc_alloced = FALSE;
1032 }
1033 else
1034 {
1035 if (fenc_alloced)
1036 vim_free(fenc);
1037 if (fenc_next != NULL)
1038 {
1039 fenc = next_fenc(&fenc_next);
1040 fenc_alloced = (fenc_next != NULL);
1041 }
1042 else
1043 {
1044 fenc = (char_u *)"";
1045 fenc_alloced = FALSE;
1046 }
1047 }
1048 if (tmpname != NULL)
1049 {
1050 mch_remove(tmpname); /* delete converted file */
1051 vim_free(tmpname);
1052 tmpname = NULL;
1053 }
1054 }
1055
1056 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001057 * Conversion may be required when the encoding of the file is different
1058 * from 'encoding' or 'encoding' is UTF-16, UCS-2 or UCS-4.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001059 */
1060 fio_flags = 0;
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001061 converted = need_conversion(fenc);
1062 if (converted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001063 {
1064
1065 /* "ucs-bom" means we need to check the first bytes of the file
1066 * for a BOM. */
1067 if (STRCMP(fenc, ENC_UCSBOM) == 0)
1068 fio_flags = FIO_UCSBOM;
1069
1070 /*
1071 * Check if UCS-2/4 or Latin1 to UTF-8 conversion needs to be
1072 * done. This is handled below after read(). Prepare the
1073 * fio_flags to avoid having to parse the string each time.
1074 * Also check for Unicode to Latin1 conversion, because iconv()
1075 * appears not to handle this correctly. This works just like
1076 * conversion to UTF-8 except how the resulting character is put in
1077 * the buffer.
1078 */
1079 else if (enc_utf8 || STRCMP(p_enc, "latin1") == 0)
1080 fio_flags = get_fio_flags(fenc);
1081
1082# ifdef WIN3264
1083 /*
1084 * Conversion from an MS-Windows codepage to UTF-8 or another codepage
1085 * is handled with MultiByteToWideChar().
1086 */
1087 if (fio_flags == 0)
1088 fio_flags = get_win_fio_flags(fenc);
1089# endif
1090
1091# ifdef MACOS_X
1092 /* Conversion from Apple MacRoman to latin1 or UTF-8 */
1093 if (fio_flags == 0)
1094 fio_flags = get_mac_fio_flags(fenc);
1095# endif
1096
1097# ifdef USE_ICONV
1098 /*
1099 * Try using iconv() if we can't convert internally.
1100 */
1101 if (fio_flags == 0
1102# ifdef FEAT_EVAL
1103 && !did_iconv
1104# endif
1105 )
1106 iconv_fd = (iconv_t)my_iconv_open(
1107 enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc);
1108# endif
1109
1110# ifdef FEAT_EVAL
1111 /*
1112 * Use the 'charconvert' expression when conversion is required
1113 * and we can't do it internally or with iconv().
1114 */
1115 if (fio_flags == 0 && !read_stdin && !read_buffer && *p_ccv != NUL
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02001116 && !read_fifo
Bram Moolenaar071d4272004-06-13 20:20:40 +00001117# ifdef USE_ICONV
1118 && iconv_fd == (iconv_t)-1
1119# endif
1120 )
1121 {
1122# ifdef USE_ICONV
1123 did_iconv = FALSE;
1124# endif
1125 /* Skip conversion when it's already done (retry for wrong
1126 * "fileformat"). */
1127 if (tmpname == NULL)
1128 {
1129 tmpname = readfile_charconvert(fname, fenc, &fd);
1130 if (tmpname == NULL)
1131 {
1132 /* Conversion failed. Try another one. */
1133 advance_fenc = TRUE;
1134 if (fd < 0)
1135 {
1136 /* Re-opening the original file failed! */
1137 EMSG(_("E202: Conversion made file unreadable!"));
1138 error = TRUE;
1139 goto failed;
1140 }
1141 goto retry;
1142 }
1143 }
1144 }
1145 else
1146# endif
1147 {
1148 if (fio_flags == 0
1149# ifdef USE_ICONV
1150 && iconv_fd == (iconv_t)-1
1151# endif
1152 )
1153 {
1154 /* Conversion wanted but we can't.
1155 * Try the next conversion in 'fileencodings' */
1156 advance_fenc = TRUE;
1157 goto retry;
1158 }
1159 }
1160 }
1161
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001162 /* Set "can_retry" when it's possible to rewind the file and try with
Bram Moolenaar071d4272004-06-13 20:20:40 +00001163 * another "fenc" value. It's FALSE when no other "fenc" to try, reading
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001164 * stdin or fixed at a specific encoding. */
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02001165 can_retry = (*fenc != NUL && !read_stdin && !read_fifo && !keep_dest_enc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001166#endif
1167
1168 if (!skip_read)
1169 {
1170 linerest = 0;
1171 filesize = 0;
1172 skip_count = lines_to_skip;
1173 read_count = lines_to_read;
1174#ifdef FEAT_MBYTE
1175 conv_restlen = 0;
1176#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001177#ifdef FEAT_PERSISTENT_UNDO
Bram Moolenaar59f931e2010-07-24 20:27:03 +02001178 read_undo_file = (newfile && (flags & READ_KEEP_UNDO) == 0
1179 && curbuf->b_ffname != NULL
1180 && curbuf->b_p_udf
1181 && !filtering
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02001182 && !read_fifo
Bram Moolenaar59f931e2010-07-24 20:27:03 +02001183 && !read_stdin
1184 && !read_buffer);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001185 if (read_undo_file)
1186 sha256_start(&sha_ctx);
1187#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001188#ifdef FEAT_CRYPT
1189 if (curbuf->b_cryptstate != NULL)
1190 {
1191 /* Need to free the state, but keep the key, don't want to ask for
1192 * it again. */
1193 crypt_free_state(curbuf->b_cryptstate);
1194 curbuf->b_cryptstate = NULL;
1195 }
1196#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001197 }
1198
1199 while (!error && !got_int)
1200 {
1201 /*
1202 * We allocate as much space for the file as we can get, plus
1203 * space for the old line plus room for one terminating NUL.
1204 * The amount is limited by the fact that read() only can read
1205 * upto max_unsigned characters (and other things).
1206 */
Bram Moolenaara2aa31a2014-02-23 22:52:40 +01001207#if VIM_SIZEOF_INT <= 2
Bram Moolenaar071d4272004-06-13 20:20:40 +00001208 if (linerest >= 0x7ff0)
1209 {
1210 ++split;
1211 *ptr = NL; /* split line by inserting a NL */
1212 size = 1;
1213 }
1214 else
1215#endif
1216 {
1217 if (!skip_read)
1218 {
Bram Moolenaara2aa31a2014-02-23 22:52:40 +01001219#if VIM_SIZEOF_INT > 2
Bram Moolenaar311d9822007-02-27 15:48:28 +00001220# if defined(SSIZE_MAX) && (SSIZE_MAX < 0x10000L)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001221 size = SSIZE_MAX; /* use max I/O size, 52K */
1222# else
1223 size = 0x10000L; /* use buffer >= 64K */
1224# endif
1225#else
1226 size = 0x7ff0L - linerest; /* limit buffer to 32K */
1227#endif
1228
Bram Moolenaarc1e37902006-04-18 21:55:01 +00001229 for ( ; size >= 10; size = (long)((long_u)size >> 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001230 {
1231 if ((new_buffer = lalloc((long_u)(size + linerest + 1),
1232 FALSE)) != NULL)
1233 break;
1234 }
1235 if (new_buffer == NULL)
1236 {
1237 do_outofmem_msg((long_u)(size * 2 + linerest + 1));
1238 error = TRUE;
1239 break;
1240 }
1241 if (linerest) /* copy characters from the previous buffer */
1242 mch_memmove(new_buffer, ptr - linerest, (size_t)linerest);
1243 vim_free(buffer);
1244 buffer = new_buffer;
1245 ptr = buffer + linerest;
1246 line_start = buffer;
1247
1248#ifdef FEAT_MBYTE
1249 /* May need room to translate into.
1250 * For iconv() we don't really know the required space, use a
1251 * factor ICONV_MULT.
1252 * latin1 to utf-8: 1 byte becomes up to 2 bytes
1253 * utf-16 to utf-8: 2 bytes become up to 3 bytes, 4 bytes
1254 * become up to 4 bytes, size must be multiple of 2
1255 * ucs-2 to utf-8: 2 bytes become up to 3 bytes, size must be
1256 * multiple of 2
1257 * ucs-4 to utf-8: 4 bytes become up to 6 bytes, size must be
1258 * multiple of 4 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001259 real_size = (int)size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001260# ifdef USE_ICONV
1261 if (iconv_fd != (iconv_t)-1)
1262 size = size / ICONV_MULT;
1263 else
1264# endif
1265 if (fio_flags & FIO_LATIN1)
1266 size = size / 2;
1267 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1268 size = (size * 2 / 3) & ~1;
1269 else if (fio_flags & FIO_UCS4)
1270 size = (size * 2 / 3) & ~3;
1271 else if (fio_flags == FIO_UCSBOM)
1272 size = size / ICONV_MULT; /* worst case */
1273# ifdef WIN3264
1274 else if (fio_flags & FIO_CODEPAGE)
1275 size = size / ICONV_MULT; /* also worst case */
1276# endif
1277# ifdef MACOS_X
1278 else if (fio_flags & FIO_MACROMAN)
1279 size = size / ICONV_MULT; /* also worst case */
1280# endif
1281#endif
1282
1283#ifdef FEAT_MBYTE
1284 if (conv_restlen > 0)
1285 {
1286 /* Insert unconverted bytes from previous line. */
1287 mch_memmove(ptr, conv_rest, conv_restlen);
1288 ptr += conv_restlen;
1289 size -= conv_restlen;
1290 }
1291#endif
1292
1293 if (read_buffer)
1294 {
1295 /*
1296 * Read bytes from curbuf. Used for converting text read
1297 * from stdin.
1298 */
1299 if (read_buf_lnum > from)
1300 size = 0;
1301 else
1302 {
1303 int n, ni;
1304 long tlen;
1305
1306 tlen = 0;
1307 for (;;)
1308 {
1309 p = ml_get(read_buf_lnum) + read_buf_col;
1310 n = (int)STRLEN(p);
1311 if ((int)tlen + n + 1 > size)
1312 {
1313 /* Filled up to "size", append partial line.
1314 * Change NL to NUL to reverse the effect done
1315 * below. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001316 n = (int)(size - tlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001317 for (ni = 0; ni < n; ++ni)
1318 {
1319 if (p[ni] == NL)
1320 ptr[tlen++] = NUL;
1321 else
1322 ptr[tlen++] = p[ni];
1323 }
1324 read_buf_col += n;
1325 break;
1326 }
1327 else
1328 {
1329 /* Append whole line and new-line. Change NL
1330 * to NUL to reverse the effect done below. */
1331 for (ni = 0; ni < n; ++ni)
1332 {
1333 if (p[ni] == NL)
1334 ptr[tlen++] = NUL;
1335 else
1336 ptr[tlen++] = p[ni];
1337 }
1338 ptr[tlen++] = NL;
1339 read_buf_col = 0;
1340 if (++read_buf_lnum > from)
1341 {
1342 /* When the last line didn't have an
1343 * end-of-line don't add it now either. */
1344 if (!curbuf->b_p_eol)
1345 --tlen;
1346 size = tlen;
1347 break;
1348 }
1349 }
1350 }
1351 }
1352 }
1353 else
1354 {
1355 /*
1356 * Read bytes from the file.
1357 */
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01001358 size = read_eintr(fd, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001359 }
1360
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001361#ifdef FEAT_CRYPT
1362 /*
1363 * At start of file: Check for magic number of encryption.
1364 */
1365 if (filesize == 0 && size > 0)
1366 cryptkey = check_for_cryptkey(cryptkey, ptr, &size,
1367 &filesize, newfile, sfname,
1368 &did_ask_for_key);
1369 /*
1370 * Decrypt the read bytes. This is done before checking for
1371 * EOF because the crypt layer may be buffering.
1372 */
1373 if (cryptkey != NULL && size > 0)
1374 {
1375 if (crypt_works_inplace(curbuf->b_cryptstate))
1376 {
1377 crypt_decode_inplace(curbuf->b_cryptstate, ptr, size);
1378 }
1379 else
1380 {
1381 char_u *newptr = NULL;
1382 int decrypted_size;
1383
1384 decrypted_size = crypt_decode_alloc(
1385 curbuf->b_cryptstate, ptr, size, &newptr);
1386
1387 /* If the crypt layer is buffering, not producing
1388 * anything yet, need to read more. */
1389 if (size > 0 && decrypted_size == 0)
1390 continue;
1391
1392 if (linerest == 0)
1393 {
1394 /* Simple case: reuse returned buffer (may be
1395 * NULL, checked later). */
1396 new_buffer = newptr;
1397 }
1398 else
1399 {
1400 long_u new_size;
1401
1402 /* Need new buffer to add bytes carried over. */
1403 new_size = (long_u)(decrypted_size + linerest + 1);
1404 new_buffer = lalloc(new_size, FALSE);
1405 if (new_buffer == NULL)
1406 {
1407 do_outofmem_msg(new_size);
1408 error = TRUE;
1409 break;
1410 }
1411
1412 mch_memmove(new_buffer, buffer, linerest);
1413 if (newptr != NULL)
1414 mch_memmove(new_buffer + linerest, newptr,
1415 decrypted_size);
1416 }
1417
1418 if (new_buffer != NULL)
1419 {
1420 vim_free(buffer);
1421 buffer = new_buffer;
1422 new_buffer = NULL;
1423 line_start = buffer;
1424 ptr = buffer + linerest;
1425 }
1426 size = decrypted_size;
1427 }
1428 }
1429#endif
1430
Bram Moolenaar071d4272004-06-13 20:20:40 +00001431 if (size <= 0)
1432 {
1433 if (size < 0) /* read error */
1434 error = TRUE;
1435#ifdef FEAT_MBYTE
1436 else if (conv_restlen > 0)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001437 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001438 /*
1439 * Reached end-of-file but some trailing bytes could
1440 * not be converted. Truncated file?
1441 */
1442
1443 /* When we did a conversion report an error. */
1444 if (fio_flags != 0
1445# ifdef USE_ICONV
1446 || iconv_fd != (iconv_t)-1
1447# endif
1448 )
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001449 {
Bram Moolenaare8d95302013-04-24 16:34:02 +02001450 if (can_retry)
1451 goto rewind_retry;
Bram Moolenaarf453d352008-06-04 17:37:34 +00001452 if (conv_error == 0)
1453 conv_error = curbuf->b_ml.ml_line_count
1454 - linecnt + 1;
1455 }
1456 /* Remember the first linenr with an illegal byte */
1457 else if (illegal_byte == 0)
1458 illegal_byte = curbuf->b_ml.ml_line_count
1459 - linecnt + 1;
1460 if (bad_char_behavior == BAD_DROP)
1461 {
1462 *(ptr - conv_restlen) = NUL;
1463 conv_restlen = 0;
1464 }
1465 else
1466 {
1467 /* Replace the trailing bytes with the replacement
1468 * character if we were converting; if we weren't,
1469 * leave the UTF8 checking code to do it, as it
1470 * works slightly differently. */
1471 if (bad_char_behavior != BAD_KEEP && (fio_flags != 0
1472# ifdef USE_ICONV
1473 || iconv_fd != (iconv_t)-1
1474# endif
1475 ))
1476 {
1477 while (conv_restlen > 0)
1478 {
1479 *(--ptr) = bad_char_behavior;
1480 --conv_restlen;
1481 }
1482 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001483 fio_flags = 0; /* don't convert this */
Bram Moolenaarb21e5842006-04-16 18:30:08 +00001484# ifdef USE_ICONV
1485 if (iconv_fd != (iconv_t)-1)
1486 {
1487 iconv_close(iconv_fd);
1488 iconv_fd = (iconv_t)-1;
1489 }
1490# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001491 }
1492 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001493#endif
1494 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001495 }
1496 skip_read = FALSE;
1497
1498#ifdef FEAT_MBYTE
1499 /*
1500 * At start of file (or after crypt magic number): Check for BOM.
1501 * Also check for a BOM for other Unicode encodings, but not after
1502 * converting with 'charconvert' or when a BOM has already been
1503 * found.
1504 */
1505 if ((filesize == 0
1506# ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001507 || (cryptkey != NULL
1508 && filesize == crypt_get_header_len(
1509 crypt_get_method_nr(curbuf)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001510# endif
1511 )
1512 && (fio_flags == FIO_UCSBOM
1513 || (!curbuf->b_p_bomb
1514 && tmpname == NULL
1515 && (*fenc == 'u' || (*fenc == NUL && enc_utf8)))))
1516 {
1517 char_u *ccname;
1518 int blen;
1519
1520 /* no BOM detection in a short file or in binary mode */
1521 if (size < 2 || curbuf->b_p_bin)
1522 ccname = NULL;
1523 else
1524 ccname = check_for_bom(ptr, size, &blen,
1525 fio_flags == FIO_UCSBOM ? FIO_ALL : get_fio_flags(fenc));
1526 if (ccname != NULL)
1527 {
1528 /* Remove BOM from the text */
1529 filesize += blen;
1530 size -= blen;
1531 mch_memmove(ptr, ptr + blen, (size_t)size);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00001532 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001533 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001534 curbuf->b_p_bomb = TRUE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001535 curbuf->b_start_bomb = TRUE;
1536 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001537 }
1538
1539 if (fio_flags == FIO_UCSBOM)
1540 {
1541 if (ccname == NULL)
1542 {
1543 /* No BOM detected: retry with next encoding. */
1544 advance_fenc = TRUE;
1545 }
1546 else
1547 {
1548 /* BOM detected: set "fenc" and jump back */
1549 if (fenc_alloced)
1550 vim_free(fenc);
1551 fenc = ccname;
1552 fenc_alloced = FALSE;
1553 }
1554 /* retry reading without getting new bytes or rewinding */
1555 skip_read = TRUE;
1556 goto retry;
1557 }
1558 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001559
1560 /* Include not converted bytes. */
1561 ptr -= conv_restlen;
1562 size += conv_restlen;
1563 conv_restlen = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001564#endif
1565 /*
1566 * Break here for a read error or end-of-file.
1567 */
1568 if (size <= 0)
1569 break;
1570
1571#ifdef FEAT_MBYTE
1572
Bram Moolenaar071d4272004-06-13 20:20:40 +00001573# ifdef USE_ICONV
1574 if (iconv_fd != (iconv_t)-1)
1575 {
1576 /*
1577 * Attempt conversion of the read bytes to 'encoding' using
1578 * iconv().
1579 */
1580 const char *fromp;
1581 char *top;
1582 size_t from_size;
1583 size_t to_size;
1584
1585 fromp = (char *)ptr;
1586 from_size = size;
1587 ptr += size;
1588 top = (char *)ptr;
1589 to_size = real_size - size;
1590
1591 /*
1592 * If there is conversion error or not enough room try using
Bram Moolenaar19a09a12005-03-04 23:39:37 +00001593 * another conversion. Except for when there is no
1594 * alternative (help files).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001595 */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001596 while ((iconv(iconv_fd, (void *)&fromp, &from_size,
1597 &top, &to_size)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001598 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
1599 || from_size > CONV_RESTLEN)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001600 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001601 if (can_retry)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001602 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001603 if (conv_error == 0)
1604 conv_error = readfile_linenr(linecnt,
1605 ptr, (char_u *)top);
Bram Moolenaar42eeac32005-06-29 22:40:58 +00001606
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001607 /* Deal with a bad byte and continue with the next. */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001608 ++fromp;
1609 --from_size;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001610 if (bad_char_behavior == BAD_KEEP)
1611 {
1612 *top++ = *(fromp - 1);
1613 --to_size;
1614 }
1615 else if (bad_char_behavior != BAD_DROP)
1616 {
1617 *top++ = bad_char_behavior;
1618 --to_size;
1619 }
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001620 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001621
1622 if (from_size > 0)
1623 {
1624 /* Some remaining characters, keep them for the next
1625 * round. */
1626 mch_memmove(conv_rest, (char_u *)fromp, from_size);
1627 conv_restlen = (int)from_size;
1628 }
1629
1630 /* move the linerest to before the converted characters */
1631 line_start = ptr - linerest;
1632 mch_memmove(line_start, buffer, (size_t)linerest);
1633 size = (long)((char_u *)top - ptr);
1634 }
1635# endif
1636
1637# ifdef WIN3264
1638 if (fio_flags & FIO_CODEPAGE)
1639 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001640 char_u *src, *dst;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001641 WCHAR ucs2buf[3];
1642 int ucs2len;
1643 int codepage = FIO_GET_CP(fio_flags);
1644 int bytelen;
1645 int found_bad;
1646 char replstr[2];
1647
Bram Moolenaar071d4272004-06-13 20:20:40 +00001648 /*
1649 * Conversion from an MS-Windows codepage or UTF-8 to UTF-8 or
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001650 * a codepage, using standard MS-Windows functions. This
1651 * requires two steps:
1652 * 1. convert from 'fileencoding' to ucs-2
1653 * 2. convert from ucs-2 to 'encoding'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001654 *
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001655 * Because there may be illegal bytes AND an incomplete byte
1656 * sequence at the end, we may have to do the conversion one
1657 * character at a time to get it right.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001658 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001659
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001660 /* Replacement string for WideCharToMultiByte(). */
1661 if (bad_char_behavior > 0)
1662 replstr[0] = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001663 else
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001664 replstr[0] = '?';
1665 replstr[1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001666
1667 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001668 * Move the bytes to the end of the buffer, so that we have
1669 * room to put the result at the start.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001670 */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001671 src = ptr + real_size - size;
1672 mch_memmove(src, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001673
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001674 /*
1675 * Do the conversion.
1676 */
1677 dst = ptr;
1678 size = size;
1679 while (size > 0)
1680 {
1681 found_bad = FALSE;
1682
1683# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
1684 if (codepage == CP_UTF8)
1685 {
1686 /* Handle CP_UTF8 input ourselves to be able to handle
1687 * trailing bytes properly.
1688 * Get one UTF-8 character from src. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001689 bytelen = (int)utf_ptr2len_len(src, size);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001690 if (bytelen > size)
1691 {
1692 /* Only got some bytes of a character. Normally
1693 * it's put in "conv_rest", but if it's too long
1694 * deal with it as if they were illegal bytes. */
1695 if (bytelen <= CONV_RESTLEN)
1696 break;
1697
1698 /* weird overlong byte sequence */
1699 bytelen = size;
1700 found_bad = TRUE;
1701 }
1702 else
1703 {
Bram Moolenaarc01140a2006-03-24 22:21:52 +00001704 int u8c = utf_ptr2char(src);
1705
Bram Moolenaar86e01082005-12-29 22:45:34 +00001706 if (u8c > 0xffff || (*src >= 0x80 && bytelen == 1))
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001707 found_bad = TRUE;
1708 ucs2buf[0] = u8c;
1709 ucs2len = 1;
1710 }
1711 }
1712 else
1713# endif
1714 {
1715 /* We don't know how long the byte sequence is, try
1716 * from one to three bytes. */
1717 for (bytelen = 1; bytelen <= size && bytelen <= 3;
1718 ++bytelen)
1719 {
1720 ucs2len = MultiByteToWideChar(codepage,
1721 MB_ERR_INVALID_CHARS,
1722 (LPCSTR)src, bytelen,
1723 ucs2buf, 3);
1724 if (ucs2len > 0)
1725 break;
1726 }
1727 if (ucs2len == 0)
1728 {
1729 /* If we have only one byte then it's probably an
1730 * incomplete byte sequence. Otherwise discard
1731 * one byte as a bad character. */
1732 if (size == 1)
1733 break;
1734 found_bad = TRUE;
1735 bytelen = 1;
1736 }
1737 }
1738
1739 if (!found_bad)
1740 {
1741 int i;
1742
1743 /* Convert "ucs2buf[ucs2len]" to 'enc' in "dst". */
1744 if (enc_utf8)
1745 {
1746 /* From UCS-2 to UTF-8. Cannot fail. */
1747 for (i = 0; i < ucs2len; ++i)
1748 dst += utf_char2bytes(ucs2buf[i], dst);
1749 }
1750 else
1751 {
1752 BOOL bad = FALSE;
1753 int dstlen;
1754
1755 /* From UCS-2 to "enc_codepage". If the
1756 * conversion uses the default character "?",
1757 * the data doesn't fit in this encoding. */
1758 dstlen = WideCharToMultiByte(enc_codepage, 0,
1759 (LPCWSTR)ucs2buf, ucs2len,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001760 (LPSTR)dst, (int)(src - dst),
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001761 replstr, &bad);
1762 if (bad)
1763 found_bad = TRUE;
1764 else
1765 dst += dstlen;
1766 }
1767 }
1768
1769 if (found_bad)
1770 {
1771 /* Deal with bytes we can't convert. */
1772 if (can_retry)
1773 goto rewind_retry;
1774 if (conv_error == 0)
1775 conv_error = readfile_linenr(linecnt, ptr, dst);
1776 if (bad_char_behavior != BAD_DROP)
1777 {
1778 if (bad_char_behavior == BAD_KEEP)
1779 {
1780 mch_memmove(dst, src, bytelen);
1781 dst += bytelen;
1782 }
1783 else
1784 *dst++ = bad_char_behavior;
1785 }
1786 }
1787
1788 src += bytelen;
1789 size -= bytelen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001790 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001791
1792 if (size > 0)
1793 {
1794 /* An incomplete byte sequence remaining. */
1795 mch_memmove(conv_rest, src, size);
1796 conv_restlen = size;
1797 }
1798
1799 /* The new size is equal to how much "dst" was advanced. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001800 size = (long)(dst - ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001801 }
1802 else
1803# endif
Bram Moolenaar56718732006-03-15 22:53:57 +00001804# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001805 if (fio_flags & FIO_MACROMAN)
1806 {
1807 /*
1808 * Conversion from Apple MacRoman char encoding to UTF-8 or
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001809 * latin1. This is in os_mac_conv.c.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001810 */
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001811 if (macroman2enc(ptr, &size, real_size) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001812 goto rewind_retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001813 }
1814 else
1815# endif
1816 if (fio_flags != 0)
1817 {
1818 int u8c;
1819 char_u *dest;
1820 char_u *tail = NULL;
1821
1822 /*
1823 * "enc_utf8" set: Convert Unicode or Latin1 to UTF-8.
1824 * "enc_utf8" not set: Convert Unicode to Latin1.
1825 * Go from end to start through the buffer, because the number
1826 * of bytes may increase.
1827 * "dest" points to after where the UTF-8 bytes go, "p" points
1828 * to after the next character to convert.
1829 */
1830 dest = ptr + real_size;
1831 if (fio_flags == FIO_LATIN1 || fio_flags == FIO_UTF8)
1832 {
1833 p = ptr + size;
1834 if (fio_flags == FIO_UTF8)
1835 {
1836 /* Check for a trailing incomplete UTF-8 sequence */
1837 tail = ptr + size - 1;
1838 while (tail > ptr && (*tail & 0xc0) == 0x80)
1839 --tail;
1840 if (tail + utf_byte2len(*tail) <= ptr + size)
1841 tail = NULL;
1842 else
1843 p = tail;
1844 }
1845 }
1846 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1847 {
1848 /* Check for a trailing byte */
1849 p = ptr + (size & ~1);
1850 if (size & 1)
1851 tail = p;
1852 if ((fio_flags & FIO_UTF16) && p > ptr)
1853 {
1854 /* Check for a trailing leading word */
1855 if (fio_flags & FIO_ENDIAN_L)
1856 {
1857 u8c = (*--p << 8);
1858 u8c += *--p;
1859 }
1860 else
1861 {
1862 u8c = *--p;
1863 u8c += (*--p << 8);
1864 }
1865 if (u8c >= 0xd800 && u8c <= 0xdbff)
1866 tail = p;
1867 else
1868 p += 2;
1869 }
1870 }
1871 else /* FIO_UCS4 */
1872 {
1873 /* Check for trailing 1, 2 or 3 bytes */
1874 p = ptr + (size & ~3);
1875 if (size & 3)
1876 tail = p;
1877 }
1878
1879 /* If there is a trailing incomplete sequence move it to
1880 * conv_rest[]. */
1881 if (tail != NULL)
1882 {
1883 conv_restlen = (int)((ptr + size) - tail);
1884 mch_memmove(conv_rest, (char_u *)tail, conv_restlen);
1885 size -= conv_restlen;
1886 }
1887
1888
1889 while (p > ptr)
1890 {
1891 if (fio_flags & FIO_LATIN1)
1892 u8c = *--p;
1893 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1894 {
1895 if (fio_flags & FIO_ENDIAN_L)
1896 {
1897 u8c = (*--p << 8);
1898 u8c += *--p;
1899 }
1900 else
1901 {
1902 u8c = *--p;
1903 u8c += (*--p << 8);
1904 }
1905 if ((fio_flags & FIO_UTF16)
1906 && u8c >= 0xdc00 && u8c <= 0xdfff)
1907 {
1908 int u16c;
1909
1910 if (p == ptr)
1911 {
1912 /* Missing leading word. */
1913 if (can_retry)
1914 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001915 if (conv_error == 0)
1916 conv_error = readfile_linenr(linecnt,
1917 ptr, p);
1918 if (bad_char_behavior == BAD_DROP)
1919 continue;
1920 if (bad_char_behavior != BAD_KEEP)
1921 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001922 }
1923
1924 /* found second word of double-word, get the first
1925 * word and compute the resulting character */
1926 if (fio_flags & FIO_ENDIAN_L)
1927 {
1928 u16c = (*--p << 8);
1929 u16c += *--p;
1930 }
1931 else
1932 {
1933 u16c = *--p;
1934 u16c += (*--p << 8);
1935 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001936 u8c = 0x10000 + ((u16c & 0x3ff) << 10)
1937 + (u8c & 0x3ff);
1938
Bram Moolenaar071d4272004-06-13 20:20:40 +00001939 /* Check if the word is indeed a leading word. */
1940 if (u16c < 0xd800 || u16c > 0xdbff)
1941 {
1942 if (can_retry)
1943 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001944 if (conv_error == 0)
1945 conv_error = readfile_linenr(linecnt,
1946 ptr, p);
1947 if (bad_char_behavior == BAD_DROP)
1948 continue;
1949 if (bad_char_behavior != BAD_KEEP)
1950 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001951 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001952 }
1953 }
1954 else if (fio_flags & FIO_UCS4)
1955 {
1956 if (fio_flags & FIO_ENDIAN_L)
1957 {
1958 u8c = (*--p << 24);
1959 u8c += (*--p << 16);
1960 u8c += (*--p << 8);
1961 u8c += *--p;
1962 }
1963 else /* big endian */
1964 {
1965 u8c = *--p;
1966 u8c += (*--p << 8);
1967 u8c += (*--p << 16);
1968 u8c += (*--p << 24);
1969 }
1970 }
1971 else /* UTF-8 */
1972 {
1973 if (*--p < 0x80)
1974 u8c = *p;
1975 else
1976 {
1977 len = utf_head_off(ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001978 p -= len;
1979 u8c = utf_ptr2char(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001980 if (len == 0)
1981 {
1982 /* Not a valid UTF-8 character, retry with
1983 * another fenc when possible, otherwise just
1984 * report the error. */
1985 if (can_retry)
1986 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001987 if (conv_error == 0)
1988 conv_error = readfile_linenr(linecnt,
1989 ptr, p);
1990 if (bad_char_behavior == BAD_DROP)
1991 continue;
1992 if (bad_char_behavior != BAD_KEEP)
1993 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001994 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001995 }
1996 }
1997 if (enc_utf8) /* produce UTF-8 */
1998 {
1999 dest -= utf_char2len(u8c);
2000 (void)utf_char2bytes(u8c, dest);
2001 }
2002 else /* produce Latin1 */
2003 {
2004 --dest;
2005 if (u8c >= 0x100)
2006 {
2007 /* character doesn't fit in latin1, retry with
2008 * another fenc when possible, otherwise just
2009 * report the error. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002010 if (can_retry)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002011 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002012 if (conv_error == 0)
2013 conv_error = readfile_linenr(linecnt, ptr, p);
2014 if (bad_char_behavior == BAD_DROP)
2015 ++dest;
2016 else if (bad_char_behavior == BAD_KEEP)
2017 *dest = u8c;
2018 else if (eap != NULL && eap->bad_char != 0)
2019 *dest = bad_char_behavior;
2020 else
2021 *dest = 0xBF;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002022 }
2023 else
2024 *dest = u8c;
2025 }
2026 }
2027
2028 /* move the linerest to before the converted characters */
2029 line_start = dest - linerest;
2030 mch_memmove(line_start, buffer, (size_t)linerest);
2031 size = (long)((ptr + real_size) - dest);
2032 ptr = dest;
2033 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002034 else if (enc_utf8 && !curbuf->b_p_bin)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002035 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002036 int incomplete_tail = FALSE;
2037
2038 /* Reading UTF-8: Check if the bytes are valid UTF-8. */
2039 for (p = ptr; ; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002040 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002041 int todo = (int)((ptr + size) - p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002042 int l;
2043
2044 if (todo <= 0)
2045 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002046 if (*p >= 0x80)
2047 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002048 /* A length of 1 means it's an illegal byte. Accept
2049 * an incomplete character at the end though, the next
2050 * read() will get the next bytes, we'll check it
2051 * then. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002052 l = utf_ptr2len_len(p, todo);
Bram Moolenaarf453d352008-06-04 17:37:34 +00002053 if (l > todo && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002054 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002055 /* Avoid retrying with a different encoding when
2056 * a truncated file is more likely, or attempting
2057 * to read the rest of an incomplete sequence when
2058 * we have already done so. */
2059 if (p > ptr || filesize > 0)
2060 incomplete_tail = TRUE;
2061 /* Incomplete byte sequence, move it to conv_rest[]
2062 * and try to read the rest of it, unless we've
2063 * already done so. */
2064 if (p > ptr)
2065 {
2066 conv_restlen = todo;
2067 mch_memmove(conv_rest, p, conv_restlen);
2068 size -= conv_restlen;
2069 break;
2070 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002071 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002072 if (l == 1 || l > todo)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002073 {
2074 /* Illegal byte. If we can try another encoding
Bram Moolenaarf453d352008-06-04 17:37:34 +00002075 * do that, unless at EOF where a truncated
2076 * file is more likely than a conversion error. */
2077 if (can_retry && !incomplete_tail)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002078 break;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002079# ifdef USE_ICONV
2080 /* When we did a conversion report an error. */
2081 if (iconv_fd != (iconv_t)-1 && conv_error == 0)
2082 conv_error = readfile_linenr(linecnt, ptr, p);
2083# endif
Bram Moolenaarf453d352008-06-04 17:37:34 +00002084 /* Remember the first linenr with an illegal byte */
2085 if (conv_error == 0 && illegal_byte == 0)
2086 illegal_byte = readfile_linenr(linecnt, ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002087
2088 /* Drop, keep or replace the bad byte. */
2089 if (bad_char_behavior == BAD_DROP)
2090 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002091 mch_memmove(p, p + 1, todo - 1);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002092 --p;
2093 --size;
2094 }
2095 else if (bad_char_behavior != BAD_KEEP)
2096 *p = bad_char_behavior;
2097 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002098 else
2099 p += l - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002100 }
2101 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002102 if (p < ptr + size && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002103 {
2104 /* Detected a UTF-8 error. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002105rewind_retry:
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002106 /* Retry reading with another conversion. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002107# if defined(FEAT_EVAL) && defined(USE_ICONV)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002108 if (*p_ccv != NUL && iconv_fd != (iconv_t)-1)
2109 /* iconv() failed, try 'charconvert' */
2110 did_iconv = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002111 else
2112# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002113 /* use next item from 'fileencodings' */
2114 advance_fenc = TRUE;
2115 file_rewind = TRUE;
2116 goto retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002117 }
2118 }
2119#endif
2120
2121 /* count the number of characters (after conversion!) */
2122 filesize += size;
2123
2124 /*
2125 * when reading the first part of a file: guess EOL type
2126 */
2127 if (fileformat == EOL_UNKNOWN)
2128 {
2129 /* First try finding a NL, for Dos and Unix */
2130 if (try_dos || try_unix)
2131 {
Bram Moolenaarc6b72172015-02-27 17:48:09 +01002132 /* Reset the carriage return counter. */
2133 if (try_mac)
2134 try_mac = 1;
2135
Bram Moolenaar071d4272004-06-13 20:20:40 +00002136 for (p = ptr; p < ptr + size; ++p)
2137 {
2138 if (*p == NL)
2139 {
2140 if (!try_unix
2141 || (try_dos && p > ptr && p[-1] == CAR))
2142 fileformat = EOL_DOS;
2143 else
2144 fileformat = EOL_UNIX;
2145 break;
2146 }
Bram Moolenaar05eb6122015-02-17 14:15:19 +01002147 else if (*p == CAR && try_mac)
2148 try_mac++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002149 }
2150
2151 /* Don't give in to EOL_UNIX if EOL_MAC is more likely */
2152 if (fileformat == EOL_UNIX && try_mac)
2153 {
2154 /* Need to reset the counters when retrying fenc. */
2155 try_mac = 1;
2156 try_unix = 1;
2157 for (; p >= ptr && *p != CAR; p--)
2158 ;
2159 if (p >= ptr)
2160 {
2161 for (p = ptr; p < ptr + size; ++p)
2162 {
2163 if (*p == NL)
2164 try_unix++;
2165 else if (*p == CAR)
2166 try_mac++;
2167 }
2168 if (try_mac > try_unix)
2169 fileformat = EOL_MAC;
2170 }
2171 }
Bram Moolenaar05eb6122015-02-17 14:15:19 +01002172 else if (fileformat == EOL_UNKNOWN && try_mac == 1)
2173 /* Looking for CR but found no end-of-line markers at
2174 * all: use the default format. */
2175 fileformat = default_fileformat();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002176 }
2177
2178 /* No NL found: may use Mac format */
2179 if (fileformat == EOL_UNKNOWN && try_mac)
2180 fileformat = EOL_MAC;
2181
2182 /* Still nothing found? Use first format in 'ffs' */
2183 if (fileformat == EOL_UNKNOWN)
2184 fileformat = default_fileformat();
2185
2186 /* if editing a new file: may set p_tx and p_ff */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002187 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002188 set_fileformat(fileformat, OPT_LOCAL);
2189 }
2190 }
2191
2192 /*
2193 * This loop is executed once for every character read.
2194 * Keep it fast!
2195 */
2196 if (fileformat == EOL_MAC)
2197 {
2198 --ptr;
2199 while (++ptr, --size >= 0)
2200 {
2201 /* catch most common case first */
2202 if ((c = *ptr) != NUL && c != CAR && c != NL)
2203 continue;
2204 if (c == NUL)
2205 *ptr = NL; /* NULs are replaced by newlines! */
2206 else if (c == NL)
2207 *ptr = CAR; /* NLs are replaced by CRs! */
2208 else
2209 {
2210 if (skip_count == 0)
2211 {
2212 *ptr = NUL; /* end of line */
2213 len = (colnr_T) (ptr - line_start + 1);
2214 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2215 {
2216 error = TRUE;
2217 break;
2218 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002219#ifdef FEAT_PERSISTENT_UNDO
2220 if (read_undo_file)
2221 sha256_update(&sha_ctx, line_start, len);
2222#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002223 ++lnum;
2224 if (--read_count == 0)
2225 {
2226 error = TRUE; /* break loop */
2227 line_start = ptr; /* nothing left to write */
2228 break;
2229 }
2230 }
2231 else
2232 --skip_count;
2233 line_start = ptr + 1;
2234 }
2235 }
2236 }
2237 else
2238 {
2239 --ptr;
2240 while (++ptr, --size >= 0)
2241 {
2242 if ((c = *ptr) != NUL && c != NL) /* catch most common case */
2243 continue;
2244 if (c == NUL)
2245 *ptr = NL; /* NULs are replaced by newlines! */
2246 else
2247 {
2248 if (skip_count == 0)
2249 {
2250 *ptr = NUL; /* end of line */
2251 len = (colnr_T)(ptr - line_start + 1);
2252 if (fileformat == EOL_DOS)
2253 {
Bram Moolenaar2aa5f692017-01-24 15:46:48 +01002254 if (ptr > line_start && ptr[-1] == CAR)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002255 {
Bram Moolenaar2aa5f692017-01-24 15:46:48 +01002256 /* remove CR before NL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002257 ptr[-1] = NUL;
2258 --len;
2259 }
2260 /*
2261 * Reading in Dos format, but no CR-LF found!
2262 * When 'fileformats' includes "unix", delete all
2263 * the lines read so far and start all over again.
2264 * Otherwise give an error message later.
2265 */
2266 else if (ff_error != EOL_DOS)
2267 {
2268 if ( try_unix
2269 && !read_stdin
2270 && (read_buffer
Bram Moolenaar8767f522016-07-01 17:17:39 +02002271 || vim_lseek(fd, (off_T)0L, SEEK_SET)
2272 == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002273 {
2274 fileformat = EOL_UNIX;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002275 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002276 set_fileformat(EOL_UNIX, OPT_LOCAL);
2277 file_rewind = TRUE;
2278 keep_fileformat = TRUE;
2279 goto retry;
2280 }
2281 ff_error = EOL_DOS;
2282 }
2283 }
2284 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2285 {
2286 error = TRUE;
2287 break;
2288 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002289#ifdef FEAT_PERSISTENT_UNDO
2290 if (read_undo_file)
2291 sha256_update(&sha_ctx, line_start, len);
2292#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002293 ++lnum;
2294 if (--read_count == 0)
2295 {
2296 error = TRUE; /* break loop */
2297 line_start = ptr; /* nothing left to write */
2298 break;
2299 }
2300 }
2301 else
2302 --skip_count;
2303 line_start = ptr + 1;
2304 }
2305 }
2306 }
2307 linerest = (long)(ptr - line_start);
2308 ui_breakcheck();
2309 }
2310
2311failed:
2312 /* not an error, max. number of lines reached */
2313 if (error && read_count == 0)
2314 error = FALSE;
2315
2316 /*
2317 * If we get EOF in the middle of a line, note the fact and
2318 * complete the line ourselves.
2319 * In Dos format ignore a trailing CTRL-Z, unless 'binary' set.
2320 */
2321 if (!error
2322 && !got_int
2323 && linerest != 0
2324 && !(!curbuf->b_p_bin
2325 && fileformat == EOL_DOS
2326 && *line_start == Ctrl_Z
2327 && ptr == line_start + 1))
2328 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002329 /* remember for when writing */
2330 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002331 curbuf->b_p_eol = FALSE;
2332 *ptr = NUL;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002333 len = (colnr_T)(ptr - line_start + 1);
2334 if (ml_append(lnum, line_start, len, newfile) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002335 error = TRUE;
2336 else
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002337 {
2338#ifdef FEAT_PERSISTENT_UNDO
2339 if (read_undo_file)
2340 sha256_update(&sha_ctx, line_start, len);
2341#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002342 read_no_eol_lnum = ++lnum;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002343 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002344 }
2345
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002346 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002347 save_file_ff(curbuf); /* remember the current file format */
2348
2349#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002350 if (curbuf->b_cryptstate != NULL)
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002351 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002352 crypt_free_state(curbuf->b_cryptstate);
2353 curbuf->b_cryptstate = NULL;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002354 }
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002355 if (cryptkey != NULL && cryptkey != curbuf->b_p_key)
2356 crypt_free_key(cryptkey);
2357 /* Don't set cryptkey to NULL, it's used below as a flag that
2358 * encryption was used. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002359#endif
2360
2361#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002362 /* If editing a new file: set 'fenc' for the current buffer.
2363 * Also for ":read ++edit file". */
2364 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002365 set_string_option_direct((char_u *)"fenc", -1, fenc,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00002366 OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002367 if (fenc_alloced)
2368 vim_free(fenc);
2369# ifdef USE_ICONV
2370 if (iconv_fd != (iconv_t)-1)
2371 {
2372 iconv_close(iconv_fd);
2373 iconv_fd = (iconv_t)-1;
2374 }
2375# endif
2376#endif
2377
2378 if (!read_buffer && !read_stdin)
2379 close(fd); /* errors are ignored */
Bram Moolenaarf05da212009-11-17 16:13:15 +00002380#ifdef HAVE_FD_CLOEXEC
2381 else
2382 {
2383 int fdflags = fcntl(fd, F_GETFD);
2384 if (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0)
Bram Moolenaarfbc4b4d2016-02-07 15:14:01 +01002385 (void)fcntl(fd, F_SETFD, fdflags | FD_CLOEXEC);
Bram Moolenaarf05da212009-11-17 16:13:15 +00002386 }
2387#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002388 vim_free(buffer);
2389
2390#ifdef HAVE_DUP
2391 if (read_stdin)
2392 {
2393 /* Use stderr for stdin, makes shell commands work. */
2394 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00002395 ignored = dup(2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002396 }
2397#endif
2398
2399#ifdef FEAT_MBYTE
2400 if (tmpname != NULL)
2401 {
2402 mch_remove(tmpname); /* delete converted file */
2403 vim_free(tmpname);
2404 }
2405#endif
2406 --no_wait_return; /* may wait for return now */
2407
2408 /*
2409 * In recovery mode everything but autocommands is skipped.
2410 */
2411 if (!recoverymode)
2412 {
2413 /* need to delete the last line, which comes from the empty buffer */
2414 if (newfile && wasempty && !(curbuf->b_ml.ml_flags & ML_EMPTY))
2415 {
2416#ifdef FEAT_NETBEANS_INTG
2417 netbeansFireChanges = 0;
2418#endif
2419 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
2420#ifdef FEAT_NETBEANS_INTG
2421 netbeansFireChanges = 1;
2422#endif
2423 --linecnt;
2424 }
2425 linecnt = curbuf->b_ml.ml_line_count - linecnt;
2426 if (filesize == 0)
2427 linecnt = 0;
2428 if (newfile || read_buffer)
Bram Moolenaar7263a772007-05-10 17:35:54 +00002429 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002430 redraw_curbuf_later(NOT_VALID);
Bram Moolenaar7263a772007-05-10 17:35:54 +00002431#ifdef FEAT_DIFF
2432 /* After reading the text into the buffer the diff info needs to
2433 * be updated. */
2434 diff_invalidate(curbuf);
2435#endif
2436#ifdef FEAT_FOLDING
2437 /* All folds in the window are invalid now. Mark them for update
2438 * before triggering autocommands. */
2439 foldUpdateAll(curwin);
2440#endif
2441 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002442 else if (linecnt) /* appended at least one line */
2443 appended_lines_mark(from, linecnt);
2444
Bram Moolenaar071d4272004-06-13 20:20:40 +00002445#ifndef ALWAYS_USE_GUI
2446 /*
2447 * If we were reading from the same terminal as where messages go,
2448 * the screen will have been messed up.
2449 * Switch on raw mode now and clear the screen.
2450 */
2451 if (read_stdin)
2452 {
2453 settmode(TMODE_RAW); /* set to raw mode */
2454 starttermcap();
2455 screenclear();
2456 }
2457#endif
2458
2459 if (got_int)
2460 {
2461 if (!(flags & READ_DUMMY))
2462 {
2463 filemess(curbuf, sfname, (char_u *)_(e_interr), 0);
2464 if (newfile)
2465 curbuf->b_p_ro = TRUE; /* must use "w!" now */
2466 }
2467 msg_scroll = msg_save;
2468#ifdef FEAT_VIMINFO
2469 check_marks_read();
2470#endif
2471 return OK; /* an interrupt isn't really an error */
2472 }
2473
2474 if (!filtering && !(flags & READ_DUMMY))
2475 {
2476 msg_add_fname(curbuf, sfname); /* fname in IObuff with quotes */
2477 c = FALSE;
2478
2479#ifdef UNIX
2480# ifdef S_ISFIFO
2481 if (S_ISFIFO(perm)) /* fifo or socket */
2482 {
2483 STRCAT(IObuff, _("[fifo/socket]"));
2484 c = TRUE;
2485 }
2486# else
2487# ifdef S_IFIFO
2488 if ((perm & S_IFMT) == S_IFIFO) /* fifo */
2489 {
2490 STRCAT(IObuff, _("[fifo]"));
2491 c = TRUE;
2492 }
2493# endif
2494# ifdef S_IFSOCK
2495 if ((perm & S_IFMT) == S_IFSOCK) /* or socket */
2496 {
2497 STRCAT(IObuff, _("[socket]"));
2498 c = TRUE;
2499 }
2500# endif
2501# endif
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002502# ifdef OPEN_CHR_FILES
2503 if (S_ISCHR(perm)) /* or character special */
2504 {
2505 STRCAT(IObuff, _("[character special]"));
2506 c = TRUE;
2507 }
2508# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002509#endif
2510 if (curbuf->b_p_ro)
2511 {
2512 STRCAT(IObuff, shortmess(SHM_RO) ? _("[RO]") : _("[readonly]"));
2513 c = TRUE;
2514 }
2515 if (read_no_eol_lnum)
2516 {
2517 msg_add_eol();
2518 c = TRUE;
2519 }
2520 if (ff_error == EOL_DOS)
2521 {
2522 STRCAT(IObuff, _("[CR missing]"));
2523 c = TRUE;
2524 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002525 if (split)
2526 {
2527 STRCAT(IObuff, _("[long lines split]"));
2528 c = TRUE;
2529 }
2530#ifdef FEAT_MBYTE
2531 if (notconverted)
2532 {
2533 STRCAT(IObuff, _("[NOT converted]"));
2534 c = TRUE;
2535 }
2536 else if (converted)
2537 {
2538 STRCAT(IObuff, _("[converted]"));
2539 c = TRUE;
2540 }
2541#endif
2542#ifdef FEAT_CRYPT
2543 if (cryptkey != NULL)
2544 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002545 crypt_append_msg(curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002546 c = TRUE;
2547 }
2548#endif
2549#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002550 if (conv_error != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002551 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002552 sprintf((char *)IObuff + STRLEN(IObuff),
2553 _("[CONVERSION ERROR in line %ld]"), (long)conv_error);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002554 c = TRUE;
2555 }
2556 else if (illegal_byte > 0)
2557 {
2558 sprintf((char *)IObuff + STRLEN(IObuff),
2559 _("[ILLEGAL BYTE in line %ld]"), (long)illegal_byte);
2560 c = TRUE;
2561 }
2562 else
2563#endif
2564 if (error)
2565 {
2566 STRCAT(IObuff, _("[READ ERRORS]"));
2567 c = TRUE;
2568 }
2569 if (msg_add_fileformat(fileformat))
2570 c = TRUE;
2571#ifdef FEAT_CRYPT
2572 if (cryptkey != NULL)
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002573 msg_add_lines(c, (long)linecnt, filesize
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002574 - crypt_get_header_len(crypt_get_method_nr(curbuf)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002575 else
2576#endif
2577 msg_add_lines(c, (long)linecnt, filesize);
2578
2579 vim_free(keep_msg);
2580 keep_msg = NULL;
2581 msg_scrolled_ign = TRUE;
2582#ifdef ALWAYS_USE_GUI
2583 /* Don't show the message when reading stdin, it would end up in a
2584 * message box (which might be shown when exiting!) */
2585 if (read_stdin || read_buffer)
2586 p = msg_may_trunc(FALSE, IObuff);
2587 else
2588#endif
2589 p = msg_trunc_attr(IObuff, FALSE, 0);
2590 if (read_stdin || read_buffer || restart_edit != 0
Bram Moolenaar1c7715d2005-10-03 22:02:18 +00002591 || (msg_scrolled != 0 && !need_wait_return))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002592 /* Need to repeat the message after redrawing when:
2593 * - When reading from stdin (the screen will be cleared next).
2594 * - When restart_edit is set (otherwise there will be a delay
2595 * before redrawing).
2596 * - When the screen was scrolled but there is no wait-return
2597 * prompt. */
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002598 set_keep_msg(p, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002599 msg_scrolled_ign = FALSE;
2600 }
2601
2602 /* with errors writing the file requires ":w!" */
2603 if (newfile && (error
2604#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002605 || conv_error != 0
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002606 || (illegal_byte > 0 && bad_char_behavior != BAD_KEEP)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002607#endif
2608 ))
2609 curbuf->b_p_ro = TRUE;
2610
2611 u_clearline(); /* cannot use "U" command after adding lines */
2612
2613 /*
2614 * In Ex mode: cursor at last new line.
2615 * Otherwise: cursor at first new line.
2616 */
2617 if (exmode_active)
2618 curwin->w_cursor.lnum = from + linecnt;
2619 else
2620 curwin->w_cursor.lnum = from + 1;
2621 check_cursor_lnum();
2622 beginline(BL_WHITE | BL_FIX); /* on first non-blank */
2623
2624 /*
2625 * Set '[ and '] marks to the newly read lines.
2626 */
2627 curbuf->b_op_start.lnum = from + 1;
2628 curbuf->b_op_start.col = 0;
2629 curbuf->b_op_end.lnum = from + linecnt;
2630 curbuf->b_op_end.col = 0;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002631
2632#ifdef WIN32
2633 /*
2634 * Work around a weird problem: When a file has two links (only
2635 * possible on NTFS) and we write through one link, then stat() it
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00002636 * through the other link, the timestamp information may be wrong.
Bram Moolenaar03f48552006-02-28 23:52:23 +00002637 * It's correct again after reading the file, thus reset the timestamp
2638 * here.
2639 */
2640 if (newfile && !read_stdin && !read_buffer
2641 && mch_stat((char *)fname, &st) >= 0)
2642 {
2643 buf_store_time(curbuf, &st, fname);
2644 curbuf->b_mtime_read = curbuf->b_mtime;
2645 }
2646#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002647 }
2648 msg_scroll = msg_save;
2649
2650#ifdef FEAT_VIMINFO
2651 /*
2652 * Get the marks before executing autocommands, so they can be used there.
2653 */
2654 check_marks_read();
2655#endif
2656
Bram Moolenaar071d4272004-06-13 20:20:40 +00002657 /*
Bram Moolenaar34d72d42015-07-17 14:18:08 +02002658 * We remember if the last line of the read didn't have
2659 * an eol even when 'binary' is off, to support turning 'fixeol' off,
2660 * or writing the read again with 'binary' on. The latter is required
2661 * for ":autocmd FileReadPost *.gz set bin|'[,']!gunzip" to work.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002662 */
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002663 curbuf->b_no_eol_lnum = read_no_eol_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002664
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02002665 /* When reloading a buffer put the cursor at the first line that is
2666 * different. */
2667 if (flags & READ_KEEP_UNDO)
2668 u_find_first_changed();
2669
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002670#ifdef FEAT_PERSISTENT_UNDO
2671 /*
2672 * When opening a new file locate undo info and read it.
2673 */
2674 if (read_undo_file)
2675 {
2676 char_u hash[UNDO_HASH_SIZE];
2677
2678 sha256_finish(&sha_ctx, hash);
Bram Moolenaar6ed8ed82010-05-30 20:40:11 +02002679 u_read_undo(NULL, hash, fname);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002680 }
2681#endif
2682
Bram Moolenaardf177f62005-02-22 08:39:57 +00002683#ifdef FEAT_AUTOCMD
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02002684 if (!read_stdin && !read_fifo && (!read_buffer || sfname != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002685 {
2686 int m = msg_scroll;
2687 int n = msg_scrolled;
2688
2689 /* Save the fileformat now, otherwise the buffer will be considered
2690 * modified if the format/encoding was automatically detected. */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002691 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002692 save_file_ff(curbuf);
2693
2694 /*
2695 * The output from the autocommands should not overwrite anything and
2696 * should not be overwritten: Set msg_scroll, restore its value if no
2697 * output was done.
2698 */
2699 msg_scroll = TRUE;
2700 if (filtering)
2701 apply_autocmds_exarg(EVENT_FILTERREADPOST, NULL, sfname,
2702 FALSE, curbuf, eap);
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02002703 else if (newfile || (read_buffer && sfname != NULL))
Bram Moolenaarc3691332016-04-20 12:49:49 +02002704 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002705 apply_autocmds_exarg(EVENT_BUFREADPOST, NULL, sfname,
2706 FALSE, curbuf, eap);
Bram Moolenaarc3691332016-04-20 12:49:49 +02002707 if (!au_did_filetype && *curbuf->b_p_ft != NUL)
2708 /*
2709 * EVENT_FILETYPE was not triggered but the buffer already has a
2710 * filetype. Trigger EVENT_FILETYPE using the existing filetype.
2711 */
2712 apply_autocmds(EVENT_FILETYPE, curbuf->b_p_ft, curbuf->b_fname,
2713 TRUE, curbuf);
2714 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002715 else
2716 apply_autocmds_exarg(EVENT_FILEREADPOST, sfname, sfname,
2717 FALSE, NULL, eap);
2718 if (msg_scrolled == n)
2719 msg_scroll = m;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002720# ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002721 if (aborting()) /* autocmds may abort script processing */
2722 return FAIL;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002723# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002724 }
2725#endif
2726
2727 if (recoverymode && error)
2728 return FAIL;
2729 return OK;
2730}
2731
Bram Moolenaarf04507d2016-08-20 15:05:39 +02002732#if defined(OPEN_CHR_FILES) || defined(PROTO)
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002733/*
2734 * Returns TRUE if the file name argument is of the form "/dev/fd/\d\+",
2735 * which is the name of files used for process substitution output by
2736 * some shells on some operating systems, e.g., bash on SunOS.
2737 * Do not accept "/dev/fd/[012]", opening these may hang Vim.
2738 */
Bram Moolenaarf04507d2016-08-20 15:05:39 +02002739 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002740is_dev_fd_file(char_u *fname)
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002741{
2742 return (STRNCMP(fname, "/dev/fd/", 8) == 0
2743 && VIM_ISDIGIT(fname[8])
2744 && *skipdigits(fname + 9) == NUL
2745 && (fname[9] != NUL
2746 || (fname[8] != '0' && fname[8] != '1' && fname[8] != '2')));
2747}
2748#endif
2749
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002750#ifdef FEAT_MBYTE
2751
2752/*
2753 * From the current line count and characters read after that, estimate the
2754 * line number where we are now.
2755 * Used for error messages that include a line number.
2756 */
2757 static linenr_T
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002758readfile_linenr(
2759 linenr_T linecnt, /* line count before reading more bytes */
2760 char_u *p, /* start of more bytes read */
2761 char_u *endp) /* end of more bytes read */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002762{
2763 char_u *s;
2764 linenr_T lnum;
2765
2766 lnum = curbuf->b_ml.ml_line_count - linecnt + 1;
2767 for (s = p; s < endp; ++s)
2768 if (*s == '\n')
2769 ++lnum;
2770 return lnum;
2771}
2772#endif
2773
Bram Moolenaar071d4272004-06-13 20:20:40 +00002774/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00002775 * Fill "*eap" to force the 'fileencoding', 'fileformat' and 'binary to be
2776 * equal to the buffer "buf". Used for calling readfile().
Bram Moolenaar071d4272004-06-13 20:20:40 +00002777 * Returns OK or FAIL.
2778 */
2779 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002780prep_exarg(exarg_T *eap, buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002781{
2782 eap->cmd = alloc((unsigned)(STRLEN(buf->b_p_ff)
2783#ifdef FEAT_MBYTE
2784 + STRLEN(buf->b_p_fenc)
2785#endif
2786 + 15));
2787 if (eap->cmd == NULL)
2788 return FAIL;
2789
2790#ifdef FEAT_MBYTE
2791 sprintf((char *)eap->cmd, "e ++ff=%s ++enc=%s", buf->b_p_ff, buf->b_p_fenc);
2792 eap->force_enc = 14 + (int)STRLEN(buf->b_p_ff);
Bram Moolenaar195d6352005-12-19 22:08:24 +00002793 eap->bad_char = buf->b_bad_char;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002794#else
2795 sprintf((char *)eap->cmd, "e ++ff=%s", buf->b_p_ff);
2796#endif
2797 eap->force_ff = 7;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002798
2799 eap->force_bin = buf->b_p_bin ? FORCE_BIN : FORCE_NOBIN;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002800 eap->read_edit = FALSE;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002801 eap->forceit = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002802 return OK;
2803}
2804
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002805/*
2806 * Set default or forced 'fileformat' and 'binary'.
2807 */
2808 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002809set_file_options(int set_options, exarg_T *eap)
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002810{
2811 /* set default 'fileformat' */
2812 if (set_options)
2813 {
2814 if (eap != NULL && eap->force_ff != 0)
2815 set_fileformat(get_fileformat_force(curbuf, eap), OPT_LOCAL);
2816 else if (*p_ffs != NUL)
2817 set_fileformat(default_fileformat(), OPT_LOCAL);
2818 }
2819
2820 /* set or reset 'binary' */
2821 if (eap != NULL && eap->force_bin != 0)
2822 {
2823 int oldval = curbuf->b_p_bin;
2824
2825 curbuf->b_p_bin = (eap->force_bin == FORCE_BIN);
2826 set_options_bin(oldval, curbuf->b_p_bin, OPT_LOCAL);
2827 }
2828}
2829
2830#if defined(FEAT_MBYTE) || defined(PROTO)
2831/*
2832 * Set forced 'fileencoding'.
2833 */
2834 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002835set_forced_fenc(exarg_T *eap)
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002836{
2837 if (eap->force_enc != 0)
2838 {
2839 char_u *fenc = enc_canonize(eap->cmd + eap->force_enc);
2840
2841 if (fenc != NULL)
2842 set_string_option_direct((char_u *)"fenc", -1,
2843 fenc, OPT_FREE|OPT_LOCAL, 0);
2844 vim_free(fenc);
2845 }
2846}
2847
Bram Moolenaar071d4272004-06-13 20:20:40 +00002848/*
2849 * Find next fileencoding to use from 'fileencodings'.
2850 * "pp" points to fenc_next. It's advanced to the next item.
2851 * When there are no more items, an empty string is returned and *pp is set to
2852 * NULL.
2853 * When *pp is not set to NULL, the result is in allocated memory.
2854 */
2855 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002856next_fenc(char_u **pp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002857{
2858 char_u *p;
2859 char_u *r;
2860
2861 if (**pp == NUL)
2862 {
2863 *pp = NULL;
2864 return (char_u *)"";
2865 }
2866 p = vim_strchr(*pp, ',');
2867 if (p == NULL)
2868 {
2869 r = enc_canonize(*pp);
2870 *pp += STRLEN(*pp);
2871 }
2872 else
2873 {
2874 r = vim_strnsave(*pp, (int)(p - *pp));
2875 *pp = p + 1;
2876 if (r != NULL)
2877 {
2878 p = enc_canonize(r);
2879 vim_free(r);
2880 r = p;
2881 }
2882 }
2883 if (r == NULL) /* out of memory */
2884 {
2885 r = (char_u *)"";
2886 *pp = NULL;
2887 }
2888 return r;
2889}
2890
2891# ifdef FEAT_EVAL
2892/*
2893 * Convert a file with the 'charconvert' expression.
2894 * This closes the file which is to be read, converts it and opens the
2895 * resulting file for reading.
2896 * Returns name of the resulting converted file (the caller should delete it
2897 * after reading it).
2898 * Returns NULL if the conversion failed ("*fdp" is not set) .
2899 */
2900 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002901readfile_charconvert(
2902 char_u *fname, /* name of input file */
2903 char_u *fenc, /* converted from */
2904 int *fdp) /* in/out: file descriptor of file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002905{
2906 char_u *tmpname;
2907 char_u *errmsg = NULL;
2908
Bram Moolenaare5c421c2015-03-31 13:33:08 +02002909 tmpname = vim_tempname('r', FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002910 if (tmpname == NULL)
2911 errmsg = (char_u *)_("Can't find temp file for conversion");
2912 else
2913 {
2914 close(*fdp); /* close the input file, ignore errors */
2915 *fdp = -1;
2916 if (eval_charconvert(fenc, enc_utf8 ? (char_u *)"utf-8" : p_enc,
2917 fname, tmpname) == FAIL)
2918 errmsg = (char_u *)_("Conversion with 'charconvert' failed");
2919 if (errmsg == NULL && (*fdp = mch_open((char *)tmpname,
2920 O_RDONLY | O_EXTRA, 0)) < 0)
2921 errmsg = (char_u *)_("can't read output of 'charconvert'");
2922 }
2923
2924 if (errmsg != NULL)
2925 {
2926 /* Don't use emsg(), it breaks mappings, the retry with
2927 * another type of conversion might still work. */
2928 MSG(errmsg);
2929 if (tmpname != NULL)
2930 {
2931 mch_remove(tmpname); /* delete converted file */
2932 vim_free(tmpname);
2933 tmpname = NULL;
2934 }
2935 }
2936
2937 /* If the input file is closed, open it (caller should check for error). */
2938 if (*fdp < 0)
2939 *fdp = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
2940
2941 return tmpname;
2942}
2943# endif
2944
2945#endif
2946
2947#ifdef FEAT_VIMINFO
2948/*
2949 * Read marks for the current buffer from the viminfo file, when we support
2950 * buffer marks and the buffer has a name.
2951 */
2952 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002953check_marks_read(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002954{
2955 if (!curbuf->b_marks_read && get_viminfo_parameter('\'') > 0
2956 && curbuf->b_ffname != NULL)
Bram Moolenaard812df62008-11-09 12:46:09 +00002957 read_viminfo(NULL, VIF_WANT_MARKS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002958
2959 /* Always set b_marks_read; needed when 'viminfo' is changed to include
2960 * the ' parameter after opening a buffer. */
2961 curbuf->b_marks_read = TRUE;
2962}
2963#endif
2964
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002965#if defined(FEAT_CRYPT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002966/*
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002967 * Check for magic number used for encryption. Applies to the current buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002968 * If found, the magic number is removed from ptr[*sizep] and *sizep and
2969 * *filesizep are updated.
2970 * Return the (new) encryption key, NULL for no encryption.
2971 */
2972 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002973check_for_cryptkey(
2974 char_u *cryptkey, /* previous encryption key or NULL */
2975 char_u *ptr, /* pointer to read bytes */
2976 long *sizep, /* length of read bytes */
Bram Moolenaar8767f522016-07-01 17:17:39 +02002977 off_T *filesizep, /* nr of bytes used from file */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002978 int newfile, /* editing a new buffer */
2979 char_u *fname, /* file name to display */
2980 int *did_ask) /* flag: whether already asked for key */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002981{
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002982 int method = crypt_method_nr_from_magic((char *)ptr, *sizep);
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02002983 int b_p_ro = curbuf->b_p_ro;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002984
2985 if (method >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002986 {
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02002987 /* Mark the buffer as read-only until the decryption has taken place.
2988 * Avoids accidentally overwriting the file with garbage. */
2989 curbuf->b_p_ro = TRUE;
2990
Bram Moolenaar2be79502014-08-13 21:58:28 +02002991 /* Set the cryptmethod local to the buffer. */
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002992 crypt_set_cm_option(curbuf, method);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002993 if (cryptkey == NULL && !*did_ask)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002994 {
2995 if (*curbuf->b_p_key)
2996 cryptkey = curbuf->b_p_key;
2997 else
2998 {
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002999 /* When newfile is TRUE, store the typed key in the 'key'
3000 * option and don't free it. bf needs hash of the key saved.
Bram Moolenaarf50a2532010-05-21 15:36:08 +02003001 * Don't ask for the key again when first time Enter was hit.
3002 * Happens when retrying to detect encoding. */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003003 smsg((char_u *)_(need_key_msg), fname);
3004 msg_scroll = TRUE;
Bram Moolenaar3a0c9082014-11-12 15:15:42 +01003005 crypt_check_method(method);
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003006 cryptkey = crypt_get_key(newfile, FALSE);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02003007 *did_ask = TRUE;
3008
Bram Moolenaar071d4272004-06-13 20:20:40 +00003009 /* check if empty key entered */
3010 if (cryptkey != NULL && *cryptkey == NUL)
3011 {
3012 if (cryptkey != curbuf->b_p_key)
3013 vim_free(cryptkey);
3014 cryptkey = NULL;
3015 }
3016 }
3017 }
3018
3019 if (cryptkey != NULL)
3020 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003021 int header_len;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003022
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003023 curbuf->b_cryptstate = crypt_create_from_header(
3024 method, cryptkey, ptr);
3025 crypt_set_cm_option(curbuf, method);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003026
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003027 /* Remove cryptmethod specific header from the text. */
3028 header_len = crypt_get_header_len(method);
Bram Moolenaar680e0152016-09-25 20:54:11 +02003029 if (*sizep <= header_len)
3030 /* invalid header, buffer can't be encrypted */
3031 return NULL;
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003032 *filesizep += header_len;
3033 *sizep -= header_len;
3034 mch_memmove(ptr, ptr + header_len, (size_t)*sizep);
3035
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02003036 /* Restore the read-only flag. */
3037 curbuf->b_p_ro = b_p_ro;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003038 }
3039 }
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003040 /* When starting to edit a new file which does not have encryption, clear
3041 * the 'key' option, except when starting up (called with -x argument) */
Bram Moolenaarfa0ff9a2010-07-25 16:05:19 +02003042 else if (newfile && *curbuf->b_p_key != NUL && !starting)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003043 set_option_value((char_u *)"key", 0L, (char_u *)"", OPT_LOCAL);
3044
3045 return cryptkey;
3046}
Bram Moolenaar80794b12010-06-13 05:20:42 +02003047#endif /* FEAT_CRYPT */
3048
Bram Moolenaar071d4272004-06-13 20:20:40 +00003049#ifdef UNIX
3050 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003051set_file_time(
3052 char_u *fname,
3053 time_t atime, /* access time */
3054 time_t mtime) /* modification time */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003055{
3056# if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
3057 struct utimbuf buf;
3058
3059 buf.actime = atime;
3060 buf.modtime = mtime;
3061 (void)utime((char *)fname, &buf);
3062# else
3063# if defined(HAVE_UTIMES)
3064 struct timeval tvp[2];
3065
3066 tvp[0].tv_sec = atime;
3067 tvp[0].tv_usec = 0;
3068 tvp[1].tv_sec = mtime;
3069 tvp[1].tv_usec = 0;
3070# ifdef NeXT
3071 (void)utimes((char *)fname, tvp);
3072# else
3073 (void)utimes((char *)fname, (const struct timeval *)&tvp);
3074# endif
3075# endif
3076# endif
3077}
3078#endif /* UNIX */
3079
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003080#if defined(VMS) && !defined(MIN)
3081/* Older DECC compiler for VAX doesn't define MIN() */
3082# define MIN(a, b) ((a) < (b) ? (a) : (b))
3083#endif
3084
Bram Moolenaar071d4272004-06-13 20:20:40 +00003085/*
Bram Moolenaar5386a122007-06-28 20:02:32 +00003086 * Return TRUE if a file appears to be read-only from the file permissions.
3087 */
3088 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003089check_file_readonly(
3090 char_u *fname, /* full path to file */
3091 int perm) /* known permissions on file */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003092{
3093#ifndef USE_MCH_ACCESS
3094 int fd = 0;
3095#endif
3096
3097 return (
3098#ifdef USE_MCH_ACCESS
3099# ifdef UNIX
3100 (perm & 0222) == 0 ||
3101# endif
3102 mch_access((char *)fname, W_OK)
3103#else
3104 (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0
3105 ? TRUE : (close(fd), FALSE)
3106#endif
3107 );
3108}
3109
3110
3111/*
Bram Moolenaar292ad192005-12-11 21:29:51 +00003112 * buf_write() - write to file "fname" lines "start" through "end"
Bram Moolenaar071d4272004-06-13 20:20:40 +00003113 *
3114 * We do our own buffering here because fwrite() is so slow.
3115 *
Bram Moolenaar292ad192005-12-11 21:29:51 +00003116 * If "forceit" is true, we don't care for errors when attempting backups.
3117 * In case of an error everything possible is done to restore the original
Bram Moolenaare37d50a2008-08-06 17:06:04 +00003118 * file. But when "forceit" is TRUE, we risk losing it.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003119 *
3120 * When "reset_changed" is TRUE and "append" == FALSE and "start" == 1 and
3121 * "end" == curbuf->b_ml.ml_line_count, reset curbuf->b_changed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003122 *
3123 * This function must NOT use NameBuff (because it's called by autowrite()).
3124 *
3125 * return FAIL for failure, OK otherwise
3126 */
3127 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003128buf_write(
3129 buf_T *buf,
3130 char_u *fname,
3131 char_u *sfname,
3132 linenr_T start,
3133 linenr_T end,
3134 exarg_T *eap, /* for forced 'ff' and 'fenc', can be
Bram Moolenaar071d4272004-06-13 20:20:40 +00003135 NULL! */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003136 int append, /* append to the file */
3137 int forceit,
3138 int reset_changed,
3139 int filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003140{
3141 int fd;
3142 char_u *backup = NULL;
3143 int backup_copy = FALSE; /* copy the original file? */
3144 int dobackup;
3145 char_u *ffname;
3146 char_u *wfname = NULL; /* name of file to write to */
3147 char_u *s;
3148 char_u *ptr;
3149 char_u c;
3150 int len;
3151 linenr_T lnum;
3152 long nchars;
3153 char_u *errmsg = NULL;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003154 int errmsg_allocated = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003155 char_u *errnum = NULL;
3156 char_u *buffer;
3157 char_u smallbuf[SMBUFSIZE];
3158 char_u *backup_ext;
3159 int bufsize;
3160 long perm; /* file permissions */
3161 int retval = OK;
3162 int newfile = FALSE; /* TRUE if file doesn't exist yet */
3163 int msg_save = msg_scroll;
3164 int overwriting; /* TRUE if writing over original */
3165 int no_eol = FALSE; /* no end-of-line written */
3166 int device = FALSE; /* writing to a device */
Bram Moolenaar8767f522016-07-01 17:17:39 +02003167 stat_T st_old;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003168 int prev_got_int = got_int;
Bram Moolenaare6bf6552017-06-27 22:11:51 +02003169 int checking_conversion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003170 int file_readonly = FALSE; /* overwritten file is read-only */
3171 static char *err_readonly = "is read-only (cannot override: \"W\" in 'cpoptions')";
Bram Moolenaara06ecab2016-07-16 14:47:36 +02003172#if defined(UNIX) /*XXX fix me sometime? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003173 int made_writable = FALSE; /* 'w' bit has been set */
3174#endif
3175 /* writing everything */
3176 int whole = (start == 1 && end == buf->b_ml.ml_line_count);
3177#ifdef FEAT_AUTOCMD
3178 linenr_T old_line_count = buf->b_ml.ml_line_count;
3179#endif
3180 int attr;
3181 int fileformat;
3182 int write_bin;
3183 struct bw_info write_info; /* info for buf_write_bytes() */
3184#ifdef FEAT_MBYTE
3185 int converted = FALSE;
3186 int notconverted = FALSE;
3187 char_u *fenc; /* effective 'fileencoding' */
3188 char_u *fenc_tofree = NULL; /* allocated "fenc" */
3189#endif
3190#ifdef HAS_BW_FLAGS
3191 int wb_flags = 0;
3192#endif
3193#ifdef HAVE_ACL
3194 vim_acl_T acl = NULL; /* ACL copied from original file to
3195 backup or new file */
3196#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003197#ifdef FEAT_PERSISTENT_UNDO
3198 int write_undo_file = FALSE;
3199 context_sha256_T sha_ctx;
3200#endif
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003201 unsigned int bkc = get_bkc_value(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003202
3203 if (fname == NULL || *fname == NUL) /* safety check */
3204 return FAIL;
Bram Moolenaar70d60e92009-12-31 13:53:33 +00003205 if (buf->b_ml.ml_mfp == NULL)
3206 {
3207 /* This can happen during startup when there is a stray "w" in the
3208 * vimrc file. */
3209 EMSG(_(e_emptybuf));
3210 return FAIL;
3211 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003212
3213 /*
3214 * Disallow writing from .exrc and .vimrc in current directory for
3215 * security reasons.
3216 */
3217 if (check_secure())
3218 return FAIL;
3219
3220 /* Avoid a crash for a long name. */
3221 if (STRLEN(fname) >= MAXPATHL)
3222 {
3223 EMSG(_(e_longname));
3224 return FAIL;
3225 }
3226
3227#ifdef FEAT_MBYTE
3228 /* must init bw_conv_buf and bw_iconv_fd before jumping to "fail" */
3229 write_info.bw_conv_buf = NULL;
3230 write_info.bw_conv_error = FALSE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003231 write_info.bw_conv_error_lnum = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003232 write_info.bw_restlen = 0;
3233# ifdef USE_ICONV
3234 write_info.bw_iconv_fd = (iconv_t)-1;
3235# endif
3236#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003237#ifdef FEAT_CRYPT
3238 write_info.bw_buffer = buf;
3239#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003240
Bram Moolenaardf177f62005-02-22 08:39:57 +00003241 /* After writing a file changedtick changes but we don't want to display
3242 * the line. */
3243 ex_no_reprint = TRUE;
3244
Bram Moolenaar071d4272004-06-13 20:20:40 +00003245 /*
3246 * If there is no file name yet, use the one for the written file.
3247 * BF_NOTEDITED is set to reflect this (in case the write fails).
3248 * Don't do this when the write is for a filter command.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003249 * Don't do this when appending.
3250 * Only do this when 'cpoptions' contains the 'F' flag.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003251 */
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003252 if (buf->b_ffname == NULL
3253 && reset_changed
Bram Moolenaar071d4272004-06-13 20:20:40 +00003254 && whole
3255 && buf == curbuf
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00003256#ifdef FEAT_QUICKFIX
3257 && !bt_nofile(buf)
3258#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003259 && !filtering
Bram Moolenaar292ad192005-12-11 21:29:51 +00003260 && (!append || vim_strchr(p_cpo, CPO_FNAMEAPP) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003261 && vim_strchr(p_cpo, CPO_FNAMEW) != NULL)
3262 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003263 if (set_rw_fname(fname, sfname) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003264 return FAIL;
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003265 buf = curbuf; /* just in case autocmds made "buf" invalid */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003266 }
3267
3268 if (sfname == NULL)
3269 sfname = fname;
3270 /*
3271 * For Unix: Use the short file name whenever possible.
3272 * Avoids problems with networks and when directory names are changed.
3273 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
3274 * another directory, which we don't detect
3275 */
3276 ffname = fname; /* remember full fname */
3277#ifdef UNIX
3278 fname = sfname;
3279#endif
3280
3281 if (buf->b_ffname != NULL && fnamecmp(ffname, buf->b_ffname) == 0)
3282 overwriting = TRUE;
3283 else
3284 overwriting = FALSE;
3285
3286 if (exiting)
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003287 settmode(TMODE_COOK); /* when exiting allow typeahead now */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003288
3289 ++no_wait_return; /* don't wait for return yet */
3290
3291 /*
3292 * Set '[ and '] marks to the lines to be written.
3293 */
3294 buf->b_op_start.lnum = start;
3295 buf->b_op_start.col = 0;
3296 buf->b_op_end.lnum = end;
3297 buf->b_op_end.col = 0;
3298
3299#ifdef FEAT_AUTOCMD
3300 {
3301 aco_save_T aco;
3302 int buf_ffname = FALSE;
3303 int buf_sfname = FALSE;
3304 int buf_fname_f = FALSE;
3305 int buf_fname_s = FALSE;
3306 int did_cmd = FALSE;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003307 int nofile_err = FALSE;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003308 int empty_memline = (buf->b_ml.ml_mfp == NULL);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003309 bufref_T bufref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003310
3311 /*
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003312 * Apply PRE autocommands.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003313 * Set curbuf to the buffer to be written.
3314 * Careful: The autocommands may call buf_write() recursively!
3315 */
3316 if (ffname == buf->b_ffname)
3317 buf_ffname = TRUE;
3318 if (sfname == buf->b_sfname)
3319 buf_sfname = TRUE;
3320 if (fname == buf->b_ffname)
3321 buf_fname_f = TRUE;
3322 if (fname == buf->b_sfname)
3323 buf_fname_s = TRUE;
3324
3325 /* set curwin/curbuf to buf and save a few things */
3326 aucmd_prepbuf(&aco, buf);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003327 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003328
3329 if (append)
3330 {
3331 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD,
3332 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003333 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003334#ifdef FEAT_QUICKFIX
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00003335 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003336 nofile_err = TRUE;
3337 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003338#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003339 apply_autocmds_exarg(EVENT_FILEAPPENDPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003340 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003341 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003342 }
3343 else if (filtering)
3344 {
3345 apply_autocmds_exarg(EVENT_FILTERWRITEPRE,
3346 NULL, sfname, FALSE, curbuf, eap);
3347 }
3348 else if (reset_changed && whole)
3349 {
Bram Moolenaar39fc42e2011-09-02 11:56:20 +02003350 int was_changed = curbufIsChanged();
3351
3352 did_cmd = apply_autocmds_exarg(EVENT_BUFWRITECMD,
3353 sfname, sfname, FALSE, curbuf, eap);
3354 if (did_cmd)
3355 {
3356 if (was_changed && !curbufIsChanged())
3357 {
3358 /* Written everything correctly and BufWriteCmd has reset
3359 * 'modified': Correct the undo information so that an
3360 * undo now sets 'modified'. */
3361 u_unchanged(curbuf);
3362 u_update_save_nr(curbuf);
3363 }
3364 }
3365 else
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003366 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003367#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003368 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003369 nofile_err = TRUE;
3370 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003371#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003372 apply_autocmds_exarg(EVENT_BUFWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003373 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003374 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003375 }
3376 else
3377 {
3378 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD,
3379 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003380 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003381#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003382 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003383 nofile_err = TRUE;
3384 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003385#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003386 apply_autocmds_exarg(EVENT_FILEWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003387 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003388 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003389 }
3390
3391 /* restore curwin/curbuf and a few other things */
3392 aucmd_restbuf(&aco);
3393
3394 /*
3395 * In three situations we return here and don't write the file:
3396 * 1. the autocommands deleted or unloaded the buffer.
3397 * 2. The autocommands abort script processing.
3398 * 3. If one of the "Cmd" autocommands was executed.
3399 */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003400 if (!bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003401 buf = NULL;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003402 if (buf == NULL || (buf->b_ml.ml_mfp == NULL && !empty_memline)
Bram Moolenaar1e015462005-09-25 22:16:38 +00003403 || did_cmd || nofile_err
3404#ifdef FEAT_EVAL
3405 || aborting()
3406#endif
3407 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003408 {
3409 --no_wait_return;
3410 msg_scroll = msg_save;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003411 if (nofile_err)
3412 EMSG(_("E676: No matching autocommands for acwrite buffer"));
3413
Bram Moolenaar1e015462005-09-25 22:16:38 +00003414 if (nofile_err
3415#ifdef FEAT_EVAL
3416 || aborting()
3417#endif
3418 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003419 /* An aborting error, interrupt or exception in the
3420 * autocommands. */
3421 return FAIL;
3422 if (did_cmd)
3423 {
3424 if (buf == NULL)
3425 /* The buffer was deleted. We assume it was written
3426 * (can't retry anyway). */
3427 return OK;
3428 if (overwriting)
3429 {
3430 /* Assume the buffer was written, update the timestamp. */
3431 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00003432 if (append)
3433 buf->b_flags &= ~BF_NEW;
3434 else
3435 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003436 }
Bram Moolenaar292ad192005-12-11 21:29:51 +00003437 if (reset_changed && buf->b_changed && !append
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003438 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003439 /* Buffer still changed, the autocommands didn't work
3440 * properly. */
3441 return FAIL;
3442 return OK;
3443 }
3444#ifdef FEAT_EVAL
3445 if (!aborting())
3446#endif
3447 EMSG(_("E203: Autocommands deleted or unloaded buffer to be written"));
3448 return FAIL;
3449 }
3450
3451 /*
3452 * The autocommands may have changed the number of lines in the file.
3453 * When writing the whole file, adjust the end.
3454 * When writing part of the file, assume that the autocommands only
3455 * changed the number of lines that are to be written (tricky!).
3456 */
3457 if (buf->b_ml.ml_line_count != old_line_count)
3458 {
3459 if (whole) /* write all */
3460 end = buf->b_ml.ml_line_count;
3461 else if (buf->b_ml.ml_line_count > old_line_count) /* more lines */
3462 end += buf->b_ml.ml_line_count - old_line_count;
3463 else /* less lines */
3464 {
3465 end -= old_line_count - buf->b_ml.ml_line_count;
3466 if (end < start)
3467 {
3468 --no_wait_return;
3469 msg_scroll = msg_save;
3470 EMSG(_("E204: Autocommand changed number of lines in unexpected way"));
3471 return FAIL;
3472 }
3473 }
3474 }
3475
3476 /*
3477 * The autocommands may have changed the name of the buffer, which may
3478 * be kept in fname, ffname and sfname.
3479 */
3480 if (buf_ffname)
3481 ffname = buf->b_ffname;
3482 if (buf_sfname)
3483 sfname = buf->b_sfname;
3484 if (buf_fname_f)
3485 fname = buf->b_ffname;
3486 if (buf_fname_s)
3487 fname = buf->b_sfname;
3488 }
3489#endif
3490
3491#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003492 if (netbeans_active() && isNetbeansBuffer(buf))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003493 {
3494 if (whole)
3495 {
3496 /*
3497 * b_changed can be 0 after an undo, but we still need to write
3498 * the buffer to NetBeans.
3499 */
3500 if (buf->b_changed || isNetbeansModified(buf))
3501 {
Bram Moolenaar009b2592004-10-24 19:18:58 +00003502 --no_wait_return; /* may wait for return now */
3503 msg_scroll = msg_save;
3504 netbeans_save_buffer(buf); /* no error checking... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003505 return retval;
3506 }
3507 else
3508 {
3509 errnum = (char_u *)"E656: ";
Bram Moolenaared0e7452008-06-27 19:17:34 +00003510 errmsg = (char_u *)_("NetBeans disallows writes of unmodified buffers");
Bram Moolenaar071d4272004-06-13 20:20:40 +00003511 buffer = NULL;
3512 goto fail;
3513 }
3514 }
3515 else
3516 {
3517 errnum = (char_u *)"E657: ";
3518 errmsg = (char_u *)_("Partial writes disallowed for NetBeans buffers");
3519 buffer = NULL;
3520 goto fail;
3521 }
3522 }
3523#endif
3524
3525 if (shortmess(SHM_OVER) && !exiting)
3526 msg_scroll = FALSE; /* overwrite previous file message */
3527 else
3528 msg_scroll = TRUE; /* don't overwrite previous file message */
3529 if (!filtering)
3530 filemess(buf,
3531#ifndef UNIX
3532 sfname,
3533#else
3534 fname,
3535#endif
3536 (char_u *)"", 0); /* show that we are busy */
3537 msg_scroll = FALSE; /* always overwrite the file message now */
3538
3539 buffer = alloc(BUFSIZE);
3540 if (buffer == NULL) /* can't allocate big buffer, use small
3541 * one (to be able to write when out of
3542 * memory) */
3543 {
3544 buffer = smallbuf;
3545 bufsize = SMBUFSIZE;
3546 }
3547 else
3548 bufsize = BUFSIZE;
3549
3550 /*
3551 * Get information about original file (if there is one).
3552 */
Bram Moolenaar53076832015-12-31 19:53:21 +01003553#if defined(UNIX)
Bram Moolenaar6f192452007-11-08 19:49:02 +00003554 st_old.st_dev = 0;
3555 st_old.st_ino = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003556 perm = -1;
3557 if (mch_stat((char *)fname, &st_old) < 0)
3558 newfile = TRUE;
3559 else
3560 {
3561 perm = st_old.st_mode;
3562 if (!S_ISREG(st_old.st_mode)) /* not a file */
3563 {
3564 if (S_ISDIR(st_old.st_mode))
3565 {
3566 errnum = (char_u *)"E502: ";
3567 errmsg = (char_u *)_("is a directory");
3568 goto fail;
3569 }
3570 if (mch_nodetype(fname) != NODE_WRITABLE)
3571 {
3572 errnum = (char_u *)"E503: ";
3573 errmsg = (char_u *)_("is not a file or writable device");
3574 goto fail;
3575 }
3576 /* It's a device of some kind (or a fifo) which we can write to
3577 * but for which we can't make a backup. */
3578 device = TRUE;
3579 newfile = TRUE;
3580 perm = -1;
3581 }
3582 }
3583#else /* !UNIX */
3584 /*
3585 * Check for a writable device name.
3586 */
3587 c = mch_nodetype(fname);
3588 if (c == NODE_OTHER)
3589 {
3590 errnum = (char_u *)"E503: ";
3591 errmsg = (char_u *)_("is not a file or writable device");
3592 goto fail;
3593 }
3594 if (c == NODE_WRITABLE)
3595 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003596# if defined(MSWIN)
Bram Moolenaar043545e2006-10-10 16:44:07 +00003597 /* MS-Windows allows opening a device, but we will probably get stuck
3598 * trying to write to it. */
3599 if (!p_odev)
3600 {
3601 errnum = (char_u *)"E796: ";
3602 errmsg = (char_u *)_("writing to device disabled with 'opendevice' option");
3603 goto fail;
3604 }
3605# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003606 device = TRUE;
3607 newfile = TRUE;
3608 perm = -1;
3609 }
3610 else
3611 {
3612 perm = mch_getperm(fname);
3613 if (perm < 0)
3614 newfile = TRUE;
3615 else if (mch_isdir(fname))
3616 {
3617 errnum = (char_u *)"E502: ";
3618 errmsg = (char_u *)_("is a directory");
3619 goto fail;
3620 }
3621 if (overwriting)
3622 (void)mch_stat((char *)fname, &st_old);
3623 }
3624#endif /* !UNIX */
3625
3626 if (!device && !newfile)
3627 {
3628 /*
3629 * Check if the file is really writable (when renaming the file to
3630 * make a backup we won't discover it later).
3631 */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003632 file_readonly = check_file_readonly(fname, (int)perm);
3633
Bram Moolenaar071d4272004-06-13 20:20:40 +00003634 if (!forceit && file_readonly)
3635 {
3636 if (vim_strchr(p_cpo, CPO_FWRITE) != NULL)
3637 {
3638 errnum = (char_u *)"E504: ";
3639 errmsg = (char_u *)_(err_readonly);
3640 }
3641 else
3642 {
3643 errnum = (char_u *)"E505: ";
3644 errmsg = (char_u *)_("is read-only (add ! to override)");
3645 }
3646 goto fail;
3647 }
3648
3649 /*
3650 * Check if the timestamp hasn't changed since reading the file.
3651 */
3652 if (overwriting)
3653 {
3654 retval = check_mtime(buf, &st_old);
3655 if (retval == FAIL)
3656 goto fail;
3657 }
3658 }
3659
3660#ifdef HAVE_ACL
3661 /*
3662 * For systems that support ACL: get the ACL from the original file.
3663 */
3664 if (!newfile)
3665 acl = mch_get_acl(fname);
3666#endif
3667
3668 /*
3669 * If 'backupskip' is not empty, don't make a backup for some files.
3670 */
3671 dobackup = (p_wb || p_bk || *p_pm != NUL);
3672#ifdef FEAT_WILDIGN
3673 if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname))
3674 dobackup = FALSE;
3675#endif
3676
3677 /*
3678 * Save the value of got_int and reset it. We don't want a previous
3679 * interruption cancel writing, only hitting CTRL-C while writing should
3680 * abort it.
3681 */
3682 prev_got_int = got_int;
3683 got_int = FALSE;
3684
3685 /* Mark the buffer as 'being saved' to prevent changed buffer warnings */
3686 buf->b_saving = TRUE;
3687
3688 /*
3689 * If we are not appending or filtering, the file exists, and the
3690 * 'writebackup', 'backup' or 'patchmode' option is set, need a backup.
3691 * When 'patchmode' is set also make a backup when appending.
3692 *
3693 * Do not make any backup, if 'writebackup' and 'backup' are both switched
3694 * off. This helps when editing large files on almost-full disks.
3695 */
3696 if (!(append && *p_pm == NUL) && !filtering && perm >= 0 && dobackup)
3697 {
3698#if defined(UNIX) || defined(WIN32)
Bram Moolenaar8767f522016-07-01 17:17:39 +02003699 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003700#endif
3701
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003702 if ((bkc & BKC_YES) || append) /* "yes" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003703 backup_copy = TRUE;
3704#if defined(UNIX) || defined(WIN32)
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003705 else if ((bkc & BKC_AUTO)) /* "auto" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003706 {
3707 int i;
3708
3709# ifdef UNIX
3710 /*
3711 * Don't rename the file when:
3712 * - it's a hard link
3713 * - it's a symbolic link
3714 * - we don't have write permission in the directory
3715 * - we can't set the owner/group of the new file
3716 */
3717 if (st_old.st_nlink > 1
3718 || mch_lstat((char *)fname, &st) < 0
3719 || st.st_dev != st_old.st_dev
Bram Moolenaara5792f52005-11-23 21:25:05 +00003720 || st.st_ino != st_old.st_ino
3721# ifndef HAVE_FCHOWN
3722 || st.st_uid != st_old.st_uid
3723 || st.st_gid != st_old.st_gid
3724# endif
3725 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003726 backup_copy = TRUE;
3727 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003728# else
3729# ifdef WIN32
3730 /* On NTFS file systems hard links are possible. */
3731 if (mch_is_linked(fname))
3732 backup_copy = TRUE;
3733 else
3734# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003735# endif
3736 {
3737 /*
3738 * Check if we can create a file and set the owner/group to
3739 * the ones from the original file.
3740 * First find a file name that doesn't exist yet (use some
3741 * arbitrary numbers).
3742 */
3743 STRCPY(IObuff, fname);
3744 for (i = 4913; ; i += 123)
3745 {
3746 sprintf((char *)gettail(IObuff), "%d", i);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003747 if (mch_lstat((char *)IObuff, &st) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003748 break;
3749 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00003750 fd = mch_open((char *)IObuff,
3751 O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003752 if (fd < 0) /* can't write in directory */
3753 backup_copy = TRUE;
3754 else
3755 {
3756# ifdef UNIX
Bram Moolenaara5792f52005-11-23 21:25:05 +00003757# ifdef HAVE_FCHOWN
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00003758 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003759# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003760 if (mch_stat((char *)IObuff, &st) < 0
3761 || st.st_uid != st_old.st_uid
3762 || st.st_gid != st_old.st_gid
Bram Moolenaar78a15312009-05-15 19:33:18 +00003763 || (long)st.st_mode != perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003764 backup_copy = TRUE;
3765# endif
Bram Moolenaar98358622005-11-28 22:58:23 +00003766 /* Close the file before removing it, on MS-Windows we
3767 * can't delete an open file. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003768 close(fd);
Bram Moolenaar98358622005-11-28 22:58:23 +00003769 mch_remove(IObuff);
Bram Moolenaar3479c5d2010-08-08 18:46:06 +02003770# ifdef MSWIN
3771 /* MS-Windows may trigger a virus scanner to open the
3772 * file, we can't delete it then. Keep trying for half a
3773 * second. */
3774 {
3775 int try;
3776
3777 for (try = 0; try < 10; ++try)
3778 {
3779 if (mch_lstat((char *)IObuff, &st) < 0)
3780 break;
3781 ui_delay(50L, TRUE); /* wait 50 msec */
3782 mch_remove(IObuff);
3783 }
3784 }
3785# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003786 }
3787 }
3788 }
3789
Bram Moolenaar071d4272004-06-13 20:20:40 +00003790 /*
3791 * Break symlinks and/or hardlinks if we've been asked to.
3792 */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003793 if ((bkc & BKC_BREAKSYMLINK) || (bkc & BKC_BREAKHARDLINK))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003794 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003795# ifdef UNIX
Bram Moolenaar071d4272004-06-13 20:20:40 +00003796 int lstat_res;
3797
3798 lstat_res = mch_lstat((char *)fname, &st);
3799
3800 /* Symlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003801 if ((bkc & BKC_BREAKSYMLINK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003802 && lstat_res == 0
3803 && st.st_ino != st_old.st_ino)
3804 backup_copy = FALSE;
3805
3806 /* Hardlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003807 if ((bkc & BKC_BREAKHARDLINK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003808 && st_old.st_nlink > 1
3809 && (lstat_res != 0 || st.st_ino == st_old.st_ino))
3810 backup_copy = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003811# else
3812# if defined(WIN32)
3813 /* Symlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003814 if ((bkc & BKC_BREAKSYMLINK) && mch_is_symbolic_link(fname))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003815 backup_copy = FALSE;
3816
3817 /* Hardlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003818 if ((bkc & BKC_BREAKHARDLINK) && mch_is_hard_link(fname))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003819 backup_copy = FALSE;
3820# endif
3821# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003822 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003823
3824#endif
3825
3826 /* make sure we have a valid backup extension to use */
3827 if (*p_bex == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003828 backup_ext = (char_u *)".bak";
Bram Moolenaar071d4272004-06-13 20:20:40 +00003829 else
3830 backup_ext = p_bex;
3831
3832 if (backup_copy
3833 && (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) >= 0)
3834 {
3835 int bfd;
3836 char_u *copybuf, *wp;
3837 int some_error = FALSE;
Bram Moolenaar8767f522016-07-01 17:17:39 +02003838 stat_T st_new;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003839 char_u *dirp;
3840 char_u *rootname;
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003841#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003842 int did_set_shortname;
3843#endif
3844
3845 copybuf = alloc(BUFSIZE + 1);
3846 if (copybuf == NULL)
3847 {
3848 some_error = TRUE; /* out of memory */
3849 goto nobackup;
3850 }
3851
3852 /*
3853 * Try to make the backup in each directory in the 'bdir' option.
3854 *
3855 * Unix semantics has it, that we may have a writable file,
3856 * that cannot be recreated with a simple open(..., O_CREAT, ) e.g:
3857 * - the directory is not writable,
3858 * - the file may be a symbolic link,
3859 * - the file may belong to another user/group, etc.
3860 *
3861 * For these reasons, the existing writable file must be truncated
3862 * and reused. Creation of a backup COPY will be attempted.
3863 */
3864 dirp = p_bdir;
3865 while (*dirp)
3866 {
3867#ifdef UNIX
3868 st_new.st_ino = 0;
3869 st_new.st_dev = 0;
3870 st_new.st_gid = 0;
3871#endif
3872
3873 /*
3874 * Isolate one directory name, using an entry in 'bdir'.
3875 */
3876 (void)copy_option_part(&dirp, copybuf, BUFSIZE, ",");
3877 rootname = get_file_in_dir(fname, copybuf);
3878 if (rootname == NULL)
3879 {
3880 some_error = TRUE; /* out of memory */
3881 goto nobackup;
3882 }
3883
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003884#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003885 did_set_shortname = FALSE;
3886#endif
3887
3888 /*
3889 * May try twice if 'shortname' not set.
3890 */
3891 for (;;)
3892 {
3893 /*
3894 * Make backup file name.
3895 */
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003896 backup = buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003897 rootname, backup_ext, FALSE);
3898 if (backup == NULL)
3899 {
3900 vim_free(rootname);
3901 some_error = TRUE; /* out of memory */
3902 goto nobackup;
3903 }
3904
3905 /*
3906 * Check if backup file already exists.
3907 */
3908 if (mch_stat((char *)backup, &st_new) >= 0)
3909 {
3910#ifdef UNIX
3911 /*
3912 * Check if backup file is same as original file.
3913 * May happen when modname() gave the same file back.
3914 * E.g. silly link, or file name-length reached.
3915 * If we don't check here, we either ruin the file
3916 * when copying or erase it after writing. jw.
3917 */
3918 if (st_new.st_dev == st_old.st_dev
3919 && st_new.st_ino == st_old.st_ino)
3920 {
3921 vim_free(backup);
3922 backup = NULL; /* no backup file to delete */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003923 /*
3924 * may try again with 'shortname' set
3925 */
3926 if (!(buf->b_shortname || buf->b_p_sn))
3927 {
3928 buf->b_shortname = TRUE;
3929 did_set_shortname = TRUE;
3930 continue;
3931 }
3932 /* setting shortname didn't help */
3933 if (did_set_shortname)
3934 buf->b_shortname = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003935 break;
3936 }
3937#endif
3938
3939 /*
3940 * If we are not going to keep the backup file, don't
3941 * delete an existing one, try to use another name.
3942 * Change one character, just before the extension.
3943 */
3944 if (!p_bk)
3945 {
3946 wp = backup + STRLEN(backup) - 1
3947 - STRLEN(backup_ext);
3948 if (wp < backup) /* empty file name ??? */
3949 wp = backup;
3950 *wp = 'z';
3951 while (*wp > 'a'
3952 && mch_stat((char *)backup, &st_new) >= 0)
3953 --*wp;
3954 /* They all exist??? Must be something wrong. */
3955 if (*wp == 'a')
3956 {
3957 vim_free(backup);
3958 backup = NULL;
3959 }
3960 }
3961 }
3962 break;
3963 }
3964 vim_free(rootname);
3965
3966 /*
3967 * Try to create the backup file
3968 */
3969 if (backup != NULL)
3970 {
3971 /* remove old backup, if present */
3972 mch_remove(backup);
3973 /* Open with O_EXCL to avoid the file being created while
3974 * we were sleeping (symlink hacker attack?) */
3975 bfd = mch_open((char *)backup,
Bram Moolenaara5792f52005-11-23 21:25:05 +00003976 O_WRONLY|O_CREAT|O_EXTRA|O_EXCL|O_NOFOLLOW,
3977 perm & 0777);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003978 if (bfd < 0)
3979 {
3980 vim_free(backup);
3981 backup = NULL;
3982 }
3983 else
3984 {
3985 /* set file protection same as original file, but
3986 * strip s-bit */
3987 (void)mch_setperm(backup, perm & 0777);
3988
3989#ifdef UNIX
3990 /*
3991 * Try to set the group of the backup same as the
3992 * original file. If this fails, set the protection
3993 * bits for the group same as the protection bits for
3994 * others.
3995 */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003996 if (st_new.st_gid != st_old.st_gid
Bram Moolenaar071d4272004-06-13 20:20:40 +00003997# ifdef HAVE_FCHOWN /* sequent-ptx lacks fchown() */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003998 && fchown(bfd, (uid_t)-1, st_old.st_gid) != 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00003999# endif
4000 )
4001 mch_setperm(backup,
4002 (perm & 0707) | ((perm & 07) << 3));
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004003# if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004004 mch_copy_sec(fname, backup);
4005# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004006#endif
4007
4008 /*
4009 * copy the file.
4010 */
4011 write_info.bw_fd = bfd;
4012 write_info.bw_buf = copybuf;
4013#ifdef HAS_BW_FLAGS
4014 write_info.bw_flags = FIO_NOCONVERT;
4015#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004016 while ((write_info.bw_len = read_eintr(fd, copybuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004017 BUFSIZE)) > 0)
4018 {
4019 if (buf_write_bytes(&write_info) == FAIL)
4020 {
4021 errmsg = (char_u *)_("E506: Can't write to backup file (add ! to override)");
4022 break;
4023 }
4024 ui_breakcheck();
4025 if (got_int)
4026 {
4027 errmsg = (char_u *)_(e_interr);
4028 break;
4029 }
4030 }
4031
4032 if (close(bfd) < 0 && errmsg == NULL)
4033 errmsg = (char_u *)_("E507: Close error for backup file (add ! to override)");
4034 if (write_info.bw_len < 0)
4035 errmsg = (char_u *)_("E508: Can't read file for backup (add ! to override)");
4036#ifdef UNIX
4037 set_file_time(backup, st_old.st_atime, st_old.st_mtime);
4038#endif
4039#ifdef HAVE_ACL
4040 mch_set_acl(backup, acl);
4041#endif
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004042#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004043 mch_copy_sec(fname, backup);
4044#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004045 break;
4046 }
4047 }
4048 }
4049 nobackup:
4050 close(fd); /* ignore errors for closing read file */
4051 vim_free(copybuf);
4052
4053 if (backup == NULL && errmsg == NULL)
4054 errmsg = (char_u *)_("E509: Cannot create backup file (add ! to override)");
4055 /* ignore errors when forceit is TRUE */
4056 if ((some_error || errmsg != NULL) && !forceit)
4057 {
4058 retval = FAIL;
4059 goto fail;
4060 }
4061 errmsg = NULL;
4062 }
4063 else
4064 {
4065 char_u *dirp;
4066 char_u *p;
4067 char_u *rootname;
4068
4069 /*
4070 * Make a backup by renaming the original file.
4071 */
4072 /*
4073 * If 'cpoptions' includes the "W" flag, we don't want to
4074 * overwrite a read-only file. But rename may be possible
4075 * anyway, thus we need an extra check here.
4076 */
4077 if (file_readonly && vim_strchr(p_cpo, CPO_FWRITE) != NULL)
4078 {
4079 errnum = (char_u *)"E504: ";
4080 errmsg = (char_u *)_(err_readonly);
4081 goto fail;
4082 }
4083
4084 /*
4085 *
4086 * Form the backup file name - change path/fo.o.h to
4087 * path/fo.o.h.bak Try all directories in 'backupdir', first one
4088 * that works is used.
4089 */
4090 dirp = p_bdir;
4091 while (*dirp)
4092 {
4093 /*
4094 * Isolate one directory name and make the backup file name.
4095 */
4096 (void)copy_option_part(&dirp, IObuff, IOSIZE, ",");
4097 rootname = get_file_in_dir(fname, IObuff);
4098 if (rootname == NULL)
4099 backup = NULL;
4100 else
4101 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01004102 backup = buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00004103 rootname, backup_ext, FALSE);
4104 vim_free(rootname);
4105 }
4106
4107 if (backup != NULL)
4108 {
4109 /*
4110 * If we are not going to keep the backup file, don't
4111 * delete an existing one, try to use another name.
4112 * Change one character, just before the extension.
4113 */
4114 if (!p_bk && mch_getperm(backup) >= 0)
4115 {
4116 p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext);
4117 if (p < backup) /* empty file name ??? */
4118 p = backup;
4119 *p = 'z';
4120 while (*p > 'a' && mch_getperm(backup) >= 0)
4121 --*p;
4122 /* They all exist??? Must be something wrong! */
4123 if (*p == 'a')
4124 {
4125 vim_free(backup);
4126 backup = NULL;
4127 }
4128 }
4129 }
4130 if (backup != NULL)
4131 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004132 /*
Bram Moolenaarbfd8fc02005-09-20 23:22:24 +00004133 * Delete any existing backup and move the current version
4134 * to the backup. For safety, we don't remove the backup
4135 * until the write has finished successfully. And if the
4136 * 'backup' option is set, leave it around.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004137 */
4138 /*
4139 * If the renaming of the original file to the backup file
4140 * works, quit here.
4141 */
4142 if (vim_rename(fname, backup) == 0)
4143 break;
4144
4145 vim_free(backup); /* don't do the rename below */
4146 backup = NULL;
4147 }
4148 }
4149 if (backup == NULL && !forceit)
4150 {
4151 errmsg = (char_u *)_("E510: Can't make backup file (add ! to override)");
4152 goto fail;
4153 }
4154 }
4155 }
4156
Bram Moolenaar53076832015-12-31 19:53:21 +01004157#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004158 /* When using ":w!" and the file was read-only: make it writable */
4159 if (forceit && perm >= 0 && !(perm & 0200) && st_old.st_uid == getuid()
4160 && vim_strchr(p_cpo, CPO_FWRITE) == NULL)
4161 {
4162 perm |= 0200;
4163 (void)mch_setperm(fname, perm);
4164 made_writable = TRUE;
4165 }
4166#endif
4167
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004168 /* When using ":w!" and writing to the current file, 'readonly' makes no
Bram Moolenaar4399ef42005-02-12 14:29:27 +00004169 * sense, reset it, unless 'Z' appears in 'cpoptions'. */
4170 if (forceit && overwriting && vim_strchr(p_cpo, CPO_KEEPRO) == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004171 {
4172 buf->b_p_ro = FALSE;
4173#ifdef FEAT_TITLE
4174 need_maketitle = TRUE; /* set window title later */
4175#endif
4176#ifdef FEAT_WINDOWS
4177 status_redraw_all(); /* redraw status lines later */
4178#endif
4179 }
4180
4181 if (end > buf->b_ml.ml_line_count)
4182 end = buf->b_ml.ml_line_count;
4183 if (buf->b_ml.ml_flags & ML_EMPTY)
4184 start = end + 1;
4185
4186 /*
4187 * If the original file is being overwritten, there is a small chance that
4188 * we crash in the middle of writing. Therefore the file is preserved now.
4189 * This makes all block numbers positive so that recovery does not need
4190 * the original file.
4191 * Don't do this if there is a backup file and we are exiting.
4192 */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004193 if (reset_changed && !newfile && overwriting
Bram Moolenaar071d4272004-06-13 20:20:40 +00004194 && !(exiting && backup != NULL))
4195 {
4196 ml_preserve(buf, FALSE);
4197 if (got_int)
4198 {
4199 errmsg = (char_u *)_(e_interr);
4200 goto restore_backup;
4201 }
4202 }
4203
4204#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
4205 /*
4206 * Before risking to lose the original file verify if there's
4207 * a resource fork to preserve, and if cannot be done warn
4208 * the users. This happens when overwriting without backups.
4209 */
4210 if (backup == NULL && overwriting && !append)
4211 if (mch_has_resource_fork(fname))
4212 {
4213 errmsg = (char_u *)_("E460: The resource fork would be lost (add ! to override)");
4214 goto restore_backup;
4215 }
4216#endif
4217
4218#ifdef VMS
4219 vms_remove_version(fname); /* remove version */
4220#endif
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00004221 /* Default: write the file directly. May write to a temp file for
Bram Moolenaar071d4272004-06-13 20:20:40 +00004222 * multi-byte conversion. */
4223 wfname = fname;
4224
4225#ifdef FEAT_MBYTE
4226 /* Check for forced 'fileencoding' from "++opt=val" argument. */
4227 if (eap != NULL && eap->force_enc != 0)
4228 {
4229 fenc = eap->cmd + eap->force_enc;
4230 fenc = enc_canonize(fenc);
4231 fenc_tofree = fenc;
4232 }
4233 else
4234 fenc = buf->b_p_fenc;
4235
4236 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004237 * Check if the file needs to be converted.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004238 */
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004239 converted = need_conversion(fenc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004240
4241 /*
4242 * Check if UTF-8 to UCS-2/4 or Latin1 conversion needs to be done. Or
4243 * Latin1 to Unicode conversion. This is handled in buf_write_bytes().
4244 * Prepare the flags for it and allocate bw_conv_buf when needed.
4245 */
4246 if (converted && (enc_utf8 || STRCMP(p_enc, "latin1") == 0))
4247 {
4248 wb_flags = get_fio_flags(fenc);
4249 if (wb_flags & (FIO_UCS2 | FIO_UCS4 | FIO_UTF16 | FIO_UTF8))
4250 {
4251 /* Need to allocate a buffer to translate into. */
4252 if (wb_flags & (FIO_UCS2 | FIO_UTF16 | FIO_UTF8))
4253 write_info.bw_conv_buflen = bufsize * 2;
4254 else /* FIO_UCS4 */
4255 write_info.bw_conv_buflen = bufsize * 4;
4256 write_info.bw_conv_buf
4257 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4258 if (write_info.bw_conv_buf == NULL)
4259 end = 0;
4260 }
4261 }
4262
4263# ifdef WIN3264
4264 if (converted && wb_flags == 0 && (wb_flags = get_win_fio_flags(fenc)) != 0)
4265 {
4266 /* Convert UTF-8 -> UCS-2 and UCS-2 -> DBCS. Worst-case * 4: */
4267 write_info.bw_conv_buflen = bufsize * 4;
4268 write_info.bw_conv_buf
4269 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4270 if (write_info.bw_conv_buf == NULL)
4271 end = 0;
4272 }
4273# endif
4274
4275# ifdef MACOS_X
4276 if (converted && wb_flags == 0 && (wb_flags = get_mac_fio_flags(fenc)) != 0)
4277 {
4278 write_info.bw_conv_buflen = bufsize * 3;
4279 write_info.bw_conv_buf
4280 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4281 if (write_info.bw_conv_buf == NULL)
4282 end = 0;
4283 }
4284# endif
4285
4286# if defined(FEAT_EVAL) || defined(USE_ICONV)
4287 if (converted && wb_flags == 0)
4288 {
4289# ifdef USE_ICONV
4290 /*
4291 * Use iconv() conversion when conversion is needed and it's not done
4292 * internally.
4293 */
4294 write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc,
4295 enc_utf8 ? (char_u *)"utf-8" : p_enc);
4296 if (write_info.bw_iconv_fd != (iconv_t)-1)
4297 {
4298 /* We're going to use iconv(), allocate a buffer to convert in. */
4299 write_info.bw_conv_buflen = bufsize * ICONV_MULT;
4300 write_info.bw_conv_buf
4301 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4302 if (write_info.bw_conv_buf == NULL)
4303 end = 0;
4304 write_info.bw_first = TRUE;
4305 }
4306# ifdef FEAT_EVAL
4307 else
4308# endif
4309# endif
4310
4311# ifdef FEAT_EVAL
4312 /*
4313 * When the file needs to be converted with 'charconvert' after
4314 * writing, write to a temp file instead and let the conversion
4315 * overwrite the original file.
4316 */
4317 if (*p_ccv != NUL)
4318 {
Bram Moolenaare5c421c2015-03-31 13:33:08 +02004319 wfname = vim_tempname('w', FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004320 if (wfname == NULL) /* Can't write without a tempfile! */
4321 {
4322 errmsg = (char_u *)_("E214: Can't find temp file for writing");
4323 goto restore_backup;
4324 }
4325 }
4326# endif
4327 }
4328# endif
4329 if (converted && wb_flags == 0
4330# ifdef USE_ICONV
4331 && write_info.bw_iconv_fd == (iconv_t)-1
4332# endif
4333# ifdef FEAT_EVAL
4334 && wfname == fname
4335# endif
4336 )
4337 {
4338 if (!forceit)
4339 {
4340 errmsg = (char_u *)_("E213: Cannot convert (add ! to write without conversion)");
4341 goto restore_backup;
4342 }
4343 notconverted = TRUE;
4344 }
4345#endif
4346
4347 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004348 * If conversion is taking place, we may first pretend to write and check
4349 * for conversion errors. Then loop again to write for real.
4350 * When not doing conversion this writes for real right away.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004351 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004352 for (checking_conversion = TRUE; ; checking_conversion = FALSE)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004353 {
4354 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004355 * There is no need to check conversion when:
4356 * - there is no conversion
4357 * - we make a backup file, that can be restored in case of conversion
4358 * failure.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004359 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004360#ifdef FEAT_MBYTE
4361 if (!converted || dobackup)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004362#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004363 checking_conversion = FALSE;
4364
4365 if (checking_conversion)
4366 {
4367 /* Make sure we don't write anything. */
4368 fd = -1;
4369 write_info.bw_fd = fd;
4370 }
4371 else
4372 {
4373 /*
4374 * Open the file "wfname" for writing.
4375 * We may try to open the file twice: If we can't write to the file
4376 * and forceit is TRUE we delete the existing file and try to
4377 * create a new one. If this still fails we may have lost the
4378 * original file! (this may happen when the user reached his
4379 * quotum for number of files).
4380 * Appending will fail if the file does not exist and forceit is
4381 * FALSE.
4382 */
4383 while ((fd = mch_open((char *)wfname, O_WRONLY | O_EXTRA | (append
4384 ? (forceit ? (O_APPEND | O_CREAT) : O_APPEND)
4385 : (O_CREAT | O_TRUNC))
4386 , perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004387 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004388 /*
4389 * A forced write will try to create a new file if the old one
4390 * is still readonly. This may also happen when the directory
4391 * is read-only. In that case the mch_remove() will fail.
4392 */
4393 if (errmsg == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004394 {
4395#ifdef UNIX
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004396 stat_T st;
4397
4398 /* Don't delete the file when it's a hard or symbolic link.
4399 */
4400 if ((!newfile && st_old.st_nlink > 1)
4401 || (mch_lstat((char *)fname, &st) == 0
4402 && (st.st_dev != st_old.st_dev
4403 || st.st_ino != st_old.st_ino)))
4404 errmsg = (char_u *)_("E166: Can't open linked file for writing");
4405 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004406#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004407 {
4408 errmsg = (char_u *)_("E212: Can't open file for writing");
4409 if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL
4410 && perm >= 0)
4411 {
4412#ifdef UNIX
4413 /* we write to the file, thus it should be marked
4414 writable after all */
4415 if (!(perm & 0200))
4416 made_writable = TRUE;
4417 perm |= 0200;
4418 if (st_old.st_uid != getuid()
4419 || st_old.st_gid != getgid())
4420 perm &= 0777;
4421#endif
4422 if (!append) /* don't remove when appending */
4423 mch_remove(wfname);
4424 continue;
4425 }
4426 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004427 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004428
4429restore_backup:
Bram Moolenaar071d4272004-06-13 20:20:40 +00004430 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004431 stat_T st;
4432
Bram Moolenaar071d4272004-06-13 20:20:40 +00004433 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004434 * If we failed to open the file, we don't need a backup.
4435 * Throw it away. If we moved or removed the original file
4436 * try to put the backup in its place.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004437 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004438 if (backup != NULL && wfname == fname)
4439 {
4440 if (backup_copy)
4441 {
4442 /*
4443 * There is a small chance that we removed the
4444 * original, try to move the copy in its place.
4445 * This may not work if the vim_rename() fails.
4446 * In that case we leave the copy around.
4447 */
4448 /* If file does not exist, put the copy in its
4449 * place */
4450 if (mch_stat((char *)fname, &st) < 0)
4451 vim_rename(backup, fname);
4452 /* if original file does exist throw away the copy
4453 */
4454 if (mch_stat((char *)fname, &st) >= 0)
4455 mch_remove(backup);
4456 }
4457 else
4458 {
4459 /* try to put the original file back */
4460 vim_rename(backup, fname);
4461 }
4462 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004463
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004464 /* if original file no longer exists give an extra warning
4465 */
4466 if (!newfile && mch_stat((char *)fname, &st) < 0)
4467 end = 0;
4468 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004469
4470#ifdef FEAT_MBYTE
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004471 if (wfname != fname)
4472 vim_free(wfname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004473#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004474 goto fail;
4475 }
4476 write_info.bw_fd = fd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004477
4478#if defined(MACOS_CLASSIC) || defined(WIN3264)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004479 /* TODO: Is it need for MACOS_X? (Dany) */
4480 /*
4481 * On macintosh copy the original files attributes (i.e. the backup)
4482 * This is done in order to preserve the resource fork and the
4483 * Finder attribute (label, comments, custom icons, file creator)
4484 */
4485 if (backup != NULL && overwriting && !append)
4486 {
4487 if (backup_copy)
4488 (void)mch_copy_file_attribute(wfname, backup);
4489 else
4490 (void)mch_copy_file_attribute(backup, wfname);
4491 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004492
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004493 if (!overwriting && !append)
4494 {
4495 if (buf->b_ffname != NULL)
4496 (void)mch_copy_file_attribute(buf->b_ffname, wfname);
4497 /* Should copy resource fork */
4498 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004499#endif
4500
Bram Moolenaar071d4272004-06-13 20:20:40 +00004501#ifdef FEAT_CRYPT
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004502 if (*buf->b_p_key != NUL && !filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004503 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004504 char_u *header;
4505 int header_len;
4506
4507 buf->b_cryptstate = crypt_create_for_writing(
4508 crypt_get_method_nr(buf),
4509 buf->b_p_key, &header, &header_len);
4510 if (buf->b_cryptstate == NULL || header == NULL)
4511 end = 0;
4512 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004513 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004514 /* Write magic number, so that Vim knows how this file is
4515 * encrypted when reading it back. */
4516 write_info.bw_buf = header;
4517 write_info.bw_len = header_len;
4518 write_info.bw_flags = FIO_NOCONVERT;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004519 if (buf_write_bytes(&write_info) == FAIL)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004520 end = 0;
4521 wb_flags |= FIO_ENCRYPTED;
4522 vim_free(header);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004523 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004524 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004525#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004526 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004527 errmsg = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004528
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004529 write_info.bw_buf = buffer;
4530 nchars = 0;
4531
4532 /* use "++bin", "++nobin" or 'binary' */
4533 if (eap != NULL && eap->force_bin != 0)
4534 write_bin = (eap->force_bin == FORCE_BIN);
4535 else
4536 write_bin = buf->b_p_bin;
4537
4538#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004539 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004540 * The BOM is written just after the encryption magic number.
4541 * Skip it when appending and the file already existed, the BOM only
4542 * makes sense at the start of the file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004543 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004544 if (buf->b_p_bomb && !write_bin && (!append || perm < 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004545 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004546 write_info.bw_len = make_bom(buffer, fenc);
4547 if (write_info.bw_len > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004548 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004549 /* don't convert, do encryption */
4550 write_info.bw_flags = FIO_NOCONVERT | wb_flags;
4551 if (buf_write_bytes(&write_info) == FAIL)
4552 end = 0;
4553 else
4554 nchars += write_info.bw_len;
4555 }
4556 }
4557 write_info.bw_start_lnum = start;
4558#endif
4559
4560#ifdef FEAT_PERSISTENT_UNDO
4561 write_undo_file = (buf->b_p_udf
4562 && overwriting
4563 && !append
4564 && !filtering
4565 && reset_changed
4566 && !checking_conversion);
4567 if (write_undo_file)
4568 /* Prepare for computing the hash value of the text. */
4569 sha256_start(&sha_ctx);
4570#endif
4571
4572 write_info.bw_len = bufsize;
4573#ifdef HAS_BW_FLAGS
4574 write_info.bw_flags = wb_flags;
4575#endif
4576 fileformat = get_fileformat_force(buf, eap);
4577 s = buffer;
4578 len = 0;
4579 for (lnum = start; lnum <= end; ++lnum)
4580 {
4581 /*
4582 * The next while loop is done once for each character written.
4583 * Keep it fast!
4584 */
4585 ptr = ml_get_buf(buf, lnum, FALSE) - 1;
4586#ifdef FEAT_PERSISTENT_UNDO
4587 if (write_undo_file)
4588 sha256_update(&sha_ctx, ptr + 1,
4589 (UINT32_T)(STRLEN(ptr + 1) + 1));
4590#endif
4591 while ((c = *++ptr) != NUL)
4592 {
4593 if (c == NL)
4594 *s = NUL; /* replace newlines with NULs */
4595 else if (c == CAR && fileformat == EOL_MAC)
4596 *s = NL; /* Mac: replace CRs with NLs */
4597 else
4598 *s = c;
4599 ++s;
4600 if (++len != bufsize)
4601 continue;
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004602 if (buf_write_bytes(&write_info) == FAIL)
4603 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004604 end = 0; /* write error: break loop */
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004605 break;
4606 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004607 nchars += bufsize;
4608 s = buffer;
4609 len = 0;
4610#ifdef FEAT_MBYTE
4611 write_info.bw_start_lnum = lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004612#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004613 }
4614 /* write failed or last line has no EOL: stop here */
4615 if (end == 0
4616 || (lnum == end
4617 && (write_bin || !buf->b_p_fixeol)
4618 && (lnum == buf->b_no_eol_lnum
4619 || (lnum == buf->b_ml.ml_line_count
4620 && !buf->b_p_eol))))
4621 {
4622 ++lnum; /* written the line, count it */
4623 no_eol = TRUE;
4624 break;
4625 }
4626 if (fileformat == EOL_UNIX)
4627 *s++ = NL;
4628 else
4629 {
4630 *s++ = CAR; /* EOL_MAC or EOL_DOS: write CR */
4631 if (fileformat == EOL_DOS) /* write CR-NL */
4632 {
4633 if (++len == bufsize)
4634 {
4635 if (buf_write_bytes(&write_info) == FAIL)
4636 {
4637 end = 0; /* write error: break loop */
4638 break;
4639 }
4640 nchars += bufsize;
4641 s = buffer;
4642 len = 0;
4643 }
4644 *s++ = NL;
4645 }
4646 }
4647 if (++len == bufsize && end)
4648 {
4649 if (buf_write_bytes(&write_info) == FAIL)
4650 {
4651 end = 0; /* write error: break loop */
4652 break;
4653 }
4654 nchars += bufsize;
4655 s = buffer;
4656 len = 0;
4657
4658 ui_breakcheck();
4659 if (got_int)
4660 {
4661 end = 0; /* Interrupted, break loop */
4662 break;
4663 }
4664 }
4665#ifdef VMS
4666 /*
4667 * On VMS there is a problem: newlines get added when writing
4668 * blocks at a time. Fix it by writing a line at a time.
4669 * This is much slower!
4670 * Explanation: VAX/DECC RTL insists that records in some RMS
4671 * structures end with a newline (carriage return) character, and
4672 * if they don't it adds one.
4673 * With other RMS structures it works perfect without this fix.
4674 */
4675 if (buf->b_fab_rfm == FAB$C_VFC
4676 || ((buf->b_fab_rat & (FAB$M_FTN | FAB$M_CR)) != 0))
4677 {
4678 int b2write;
4679
4680 buf->b_fab_mrs = (buf->b_fab_mrs == 0
4681 ? MIN(4096, bufsize)
4682 : MIN(buf->b_fab_mrs, bufsize));
4683
4684 b2write = len;
4685 while (b2write > 0)
4686 {
4687 write_info.bw_len = MIN(b2write, buf->b_fab_mrs);
4688 if (buf_write_bytes(&write_info) == FAIL)
4689 {
4690 end = 0;
4691 break;
4692 }
4693 b2write -= MIN(b2write, buf->b_fab_mrs);
4694 }
4695 write_info.bw_len = bufsize;
4696 nchars += len;
4697 s = buffer;
4698 len = 0;
4699 }
4700#endif
4701 }
4702 if (len > 0 && end > 0)
4703 {
4704 write_info.bw_len = len;
4705 if (buf_write_bytes(&write_info) == FAIL)
4706 end = 0; /* write error */
4707 nchars += len;
4708 }
4709
4710 /* Stop when writing done or an error was encountered. */
4711 if (!checking_conversion || end == 0)
4712 break;
4713
4714 /* If no error happened until now, writing should be ok, so loop to
4715 * really write the buffer. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004716 }
4717
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004718 /* If we started writing, finish writing. Also when an error was
4719 * encountered. */
4720 if (!checking_conversion)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004721 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004722#if defined(UNIX) && defined(HAVE_FSYNC)
4723 /*
4724 * On many journalling file systems there is a bug that causes both the
4725 * original and the backup file to be lost when halting the system
4726 * right after writing the file. That's because only the meta-data is
4727 * journalled. Syncing the file slows down the system, but assures it
4728 * has been written to disk and we don't lose it.
4729 * For a device do try the fsync() but don't complain if it does not
4730 * work (could be a pipe).
4731 * If the 'fsync' option is FALSE, don't fsync(). Useful for laptops.
4732 */
4733 if (p_fs && fsync(fd) != 0 && !device)
4734 {
4735 errmsg = (char_u *)_("E667: Fsync failed");
4736 end = 0;
4737 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004738#endif
4739
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004740#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004741 /* Probably need to set the security context. */
4742 if (!backup_copy)
4743 mch_copy_sec(backup, wfname);
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004744#endif
4745
Bram Moolenaara5792f52005-11-23 21:25:05 +00004746#ifdef UNIX
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004747 /* When creating a new file, set its owner/group to that of the
4748 * original file. Get the new device and inode number. */
4749 if (backup != NULL && !backup_copy)
Bram Moolenaara5792f52005-11-23 21:25:05 +00004750 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004751# ifdef HAVE_FCHOWN
4752 stat_T st;
4753
4754 /* don't change the owner when it's already OK, some systems remove
4755 * permission or ACL stuff */
4756 if (mch_stat((char *)wfname, &st) < 0
4757 || st.st_uid != st_old.st_uid
4758 || st.st_gid != st_old.st_gid)
4759 {
4760 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
4761 if (perm >= 0) /* set permission again, may have changed */
4762 (void)mch_setperm(wfname, perm);
4763 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00004764# endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004765 buf_setino(buf);
4766 }
4767 else if (!buf->b_dev_valid)
4768 /* Set the inode when creating a new file. */
4769 buf_setino(buf);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004770#endif
4771
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004772 if (close(fd) != 0)
4773 {
4774 errmsg = (char_u *)_("E512: Close failed");
4775 end = 0;
4776 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004777
4778#ifdef UNIX
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004779 if (made_writable)
4780 perm &= ~0200; /* reset 'w' bit for security reasons */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004781#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004782 if (perm >= 0) /* set perm. of new file same as old file */
4783 (void)mch_setperm(wfname, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004784#ifdef HAVE_ACL
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004785 /*
4786 * Probably need to set the ACL before changing the user (can't set the
4787 * ACL on a file the user doesn't own).
4788 * On Solaris, with ZFS and the aclmode property set to "discard" (the
4789 * default), chmod() discards all part of a file's ACL that don't
4790 * represent the mode of the file. It's non-trivial for us to discover
4791 * whether we're in that situation, so we simply always re-set the ACL.
4792 */
Bram Moolenaarda412772016-07-14 20:37:07 +02004793# ifndef HAVE_SOLARIS_ZFS_ACL
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004794 if (!backup_copy)
Bram Moolenaarda412772016-07-14 20:37:07 +02004795# endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004796 mch_set_acl(wfname, acl);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004797#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004798#ifdef FEAT_CRYPT
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004799 if (buf->b_cryptstate != NULL)
4800 {
4801 crypt_free_state(buf->b_cryptstate);
4802 buf->b_cryptstate = NULL;
4803 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004804#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004805
Bram Moolenaar071d4272004-06-13 20:20:40 +00004806#if defined(FEAT_MBYTE) && defined(FEAT_EVAL)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004807 if (wfname != fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004808 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004809 /*
4810 * The file was written to a temp file, now it needs to be
4811 * converted with 'charconvert' to (overwrite) the output file.
4812 */
4813 if (end != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004814 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004815 if (eval_charconvert(enc_utf8 ? (char_u *)"utf-8" : p_enc,
4816 fenc, wfname, fname) == FAIL)
4817 {
4818 write_info.bw_conv_error = TRUE;
4819 end = 0;
4820 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004821 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004822 mch_remove(wfname);
4823 vim_free(wfname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004824 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004825#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004826 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004827
4828 if (end == 0)
4829 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004830 /*
4831 * Error encountered.
4832 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004833 if (errmsg == NULL)
4834 {
4835#ifdef FEAT_MBYTE
4836 if (write_info.bw_conv_error)
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004837 {
4838 if (write_info.bw_conv_error_lnum == 0)
4839 errmsg = (char_u *)_("E513: write error, conversion failed (make 'fenc' empty to override)");
4840 else
4841 {
4842 errmsg_allocated = TRUE;
4843 errmsg = alloc(300);
4844 vim_snprintf((char *)errmsg, 300, _("E513: write error, conversion failed in line %ld (make 'fenc' empty to override)"),
4845 (long)write_info.bw_conv_error_lnum);
4846 }
4847 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004848 else
4849#endif
4850 if (got_int)
4851 errmsg = (char_u *)_(e_interr);
4852 else
4853 errmsg = (char_u *)_("E514: write error (file system full?)");
4854 }
4855
4856 /*
4857 * If we have a backup file, try to put it in place of the new file,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004858 * because the new file is probably corrupt. This avoids losing the
Bram Moolenaar071d4272004-06-13 20:20:40 +00004859 * original file when trying to make a backup when writing the file a
4860 * second time.
4861 * When "backup_copy" is set we need to copy the backup over the new
4862 * file. Otherwise rename the backup file.
4863 * If this is OK, don't give the extra warning message.
4864 */
4865 if (backup != NULL)
4866 {
4867 if (backup_copy)
4868 {
4869 /* This may take a while, if we were interrupted let the user
4870 * know we got the message. */
4871 if (got_int)
4872 {
4873 MSG(_(e_interr));
4874 out_flush();
4875 }
4876 if ((fd = mch_open((char *)backup, O_RDONLY | O_EXTRA, 0)) >= 0)
4877 {
4878 if ((write_info.bw_fd = mch_open((char *)fname,
Bram Moolenaar9be038d2005-03-08 22:34:32 +00004879 O_WRONLY | O_CREAT | O_TRUNC | O_EXTRA,
4880 perm & 0777)) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004881 {
4882 /* copy the file. */
4883 write_info.bw_buf = smallbuf;
4884#ifdef HAS_BW_FLAGS
4885 write_info.bw_flags = FIO_NOCONVERT;
4886#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004887 while ((write_info.bw_len = read_eintr(fd, smallbuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004888 SMBUFSIZE)) > 0)
4889 if (buf_write_bytes(&write_info) == FAIL)
4890 break;
4891
4892 if (close(write_info.bw_fd) >= 0
4893 && write_info.bw_len == 0)
4894 end = 1; /* success */
4895 }
4896 close(fd); /* ignore errors for closing read file */
4897 }
4898 }
4899 else
4900 {
4901 if (vim_rename(backup, fname) == 0)
4902 end = 1;
4903 }
4904 }
4905 goto fail;
4906 }
4907
4908 lnum -= start; /* compute number of written lines */
4909 --no_wait_return; /* may wait for return now */
4910
4911#if !(defined(UNIX) || defined(VMS))
4912 fname = sfname; /* use shortname now, for the messages */
4913#endif
4914 if (!filtering)
4915 {
4916 msg_add_fname(buf, fname); /* put fname in IObuff with quotes */
4917 c = FALSE;
4918#ifdef FEAT_MBYTE
4919 if (write_info.bw_conv_error)
4920 {
4921 STRCAT(IObuff, _(" CONVERSION ERROR"));
4922 c = TRUE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004923 if (write_info.bw_conv_error_lnum != 0)
Bram Moolenaara800b422010-06-27 01:15:55 +02004924 vim_snprintf_add((char *)IObuff, IOSIZE, _(" in line %ld;"),
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004925 (long)write_info.bw_conv_error_lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004926 }
4927 else if (notconverted)
4928 {
4929 STRCAT(IObuff, _("[NOT converted]"));
4930 c = TRUE;
4931 }
4932 else if (converted)
4933 {
4934 STRCAT(IObuff, _("[converted]"));
4935 c = TRUE;
4936 }
4937#endif
4938 if (device)
4939 {
4940 STRCAT(IObuff, _("[Device]"));
4941 c = TRUE;
4942 }
4943 else if (newfile)
4944 {
4945 STRCAT(IObuff, shortmess(SHM_NEW) ? _("[New]") : _("[New File]"));
4946 c = TRUE;
4947 }
4948 if (no_eol)
4949 {
4950 msg_add_eol();
4951 c = TRUE;
4952 }
4953 /* may add [unix/dos/mac] */
4954 if (msg_add_fileformat(fileformat))
4955 c = TRUE;
4956#ifdef FEAT_CRYPT
4957 if (wb_flags & FIO_ENCRYPTED)
4958 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004959 crypt_append_msg(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004960 c = TRUE;
4961 }
4962#endif
4963 msg_add_lines(c, (long)lnum, nchars); /* add line/char count */
4964 if (!shortmess(SHM_WRITE))
4965 {
4966 if (append)
4967 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended"));
4968 else
4969 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written"));
4970 }
4971
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00004972 set_keep_msg(msg_trunc_attr(IObuff, FALSE, 0), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004973 }
4974
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004975 /* When written everything correctly: reset 'modified'. Unless not
4976 * writing to the original file and '+' is not in 'cpoptions'. */
Bram Moolenaar292ad192005-12-11 21:29:51 +00004977 if (reset_changed && whole && !append
Bram Moolenaar071d4272004-06-13 20:20:40 +00004978#ifdef FEAT_MBYTE
4979 && !write_info.bw_conv_error
4980#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004981 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL)
4982 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004983 {
4984 unchanged(buf, TRUE);
Bram Moolenaar086329d2014-10-31 19:51:36 +01004985#ifdef FEAT_AUTOCMD
Bram Moolenaar95c526e2017-02-25 14:59:34 +01004986 /* b:changedtick is always incremented in unchanged() but that
Bram Moolenaar086329d2014-10-31 19:51:36 +01004987 * should not trigger a TextChanged event. */
Bram Moolenaar95c526e2017-02-25 14:59:34 +01004988 if (last_changedtick + 1 == CHANGEDTICK(buf)
Bram Moolenaar086329d2014-10-31 19:51:36 +01004989 && last_changedtick_buf == buf)
Bram Moolenaar95c526e2017-02-25 14:59:34 +01004990 last_changedtick = CHANGEDTICK(buf);
Bram Moolenaar086329d2014-10-31 19:51:36 +01004991#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004992 u_unchanged(buf);
Bram Moolenaar730cde92010-06-27 05:18:54 +02004993 u_update_save_nr(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004994 }
4995
4996 /*
4997 * If written to the current file, update the timestamp of the swap file
4998 * and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
4999 */
5000 if (overwriting)
5001 {
5002 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00005003 if (append)
5004 buf->b_flags &= ~BF_NEW;
5005 else
5006 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005007 }
5008
5009 /*
5010 * If we kept a backup until now, and we are in patch mode, then we make
5011 * the backup file our 'original' file.
5012 */
5013 if (*p_pm && dobackup)
5014 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01005015 char *org = (char *)buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005016 fname, p_pm, FALSE);
5017
5018 if (backup != NULL)
5019 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02005020 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005021
5022 /*
5023 * If the original file does not exist yet
5024 * the current backup file becomes the original file
5025 */
5026 if (org == NULL)
5027 EMSG(_("E205: Patchmode: can't save original file"));
5028 else if (mch_stat(org, &st) < 0)
5029 {
5030 vim_rename(backup, (char_u *)org);
5031 vim_free(backup); /* don't delete the file */
5032 backup = NULL;
5033#ifdef UNIX
5034 set_file_time((char_u *)org, st_old.st_atime, st_old.st_mtime);
5035#endif
5036 }
5037 }
5038 /*
5039 * If there is no backup file, remember that a (new) file was
5040 * created.
5041 */
5042 else
5043 {
5044 int empty_fd;
5045
5046 if (org == NULL
Bram Moolenaara5792f52005-11-23 21:25:05 +00005047 || (empty_fd = mch_open(org,
5048 O_CREAT | O_EXTRA | O_EXCL | O_NOFOLLOW,
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00005049 perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005050 EMSG(_("E206: patchmode: can't touch empty original file"));
5051 else
5052 close(empty_fd);
5053 }
5054 if (org != NULL)
5055 {
5056 mch_setperm((char_u *)org, mch_getperm(fname) & 0777);
5057 vim_free(org);
5058 }
5059 }
5060
5061 /*
5062 * Remove the backup unless 'backup' option is set
5063 */
5064 if (!p_bk && backup != NULL && mch_remove(backup) != 0)
5065 EMSG(_("E207: Can't delete backup file"));
5066
5067#ifdef FEAT_SUN_WORKSHOP
5068 if (usingSunWorkShop)
5069 workshop_file_saved((char *) ffname);
5070#endif
5071
5072 goto nofail;
5073
5074 /*
5075 * Finish up. We get here either after failure or success.
5076 */
5077fail:
5078 --no_wait_return; /* may wait for return now */
5079nofail:
5080
5081 /* Done saving, we accept changed buffer warnings again */
5082 buf->b_saving = FALSE;
5083
5084 vim_free(backup);
5085 if (buffer != smallbuf)
5086 vim_free(buffer);
5087#ifdef FEAT_MBYTE
5088 vim_free(fenc_tofree);
5089 vim_free(write_info.bw_conv_buf);
5090# ifdef USE_ICONV
5091 if (write_info.bw_iconv_fd != (iconv_t)-1)
5092 {
5093 iconv_close(write_info.bw_iconv_fd);
5094 write_info.bw_iconv_fd = (iconv_t)-1;
5095 }
5096# endif
5097#endif
5098#ifdef HAVE_ACL
5099 mch_free_acl(acl);
5100#endif
5101
5102 if (errmsg != NULL)
5103 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005104 int numlen = errnum != NULL ? (int)STRLEN(errnum) : 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005105
Bram Moolenaar8820b482017-03-16 17:23:31 +01005106 attr = HL_ATTR(HLF_E); /* set highlight for error messages */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005107 msg_add_fname(buf,
5108#ifndef UNIX
5109 sfname
5110#else
5111 fname
5112#endif
5113 ); /* put file name in IObuff with quotes */
5114 if (STRLEN(IObuff) + STRLEN(errmsg) + numlen >= IOSIZE)
5115 IObuff[IOSIZE - STRLEN(errmsg) - numlen - 1] = NUL;
5116 /* If the error message has the form "is ...", put the error number in
5117 * front of the file name. */
5118 if (errnum != NULL)
5119 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00005120 STRMOVE(IObuff + numlen, IObuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005121 mch_memmove(IObuff, errnum, (size_t)numlen);
5122 }
5123 STRCAT(IObuff, errmsg);
5124 emsg(IObuff);
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005125 if (errmsg_allocated)
5126 vim_free(errmsg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005127
5128 retval = FAIL;
5129 if (end == 0)
5130 {
5131 MSG_PUTS_ATTR(_("\nWARNING: Original file may be lost or damaged\n"),
5132 attr | MSG_HIST);
5133 MSG_PUTS_ATTR(_("don't quit the editor until the file is successfully written!"),
5134 attr | MSG_HIST);
5135
5136 /* Update the timestamp to avoid an "overwrite changed file"
5137 * prompt when writing again. */
5138 if (mch_stat((char *)fname, &st_old) >= 0)
5139 {
5140 buf_store_time(buf, &st_old, fname);
5141 buf->b_mtime_read = buf->b_mtime;
5142 }
5143 }
5144 }
5145 msg_scroll = msg_save;
5146
Bram Moolenaar55debbe2010-05-23 23:34:36 +02005147#ifdef FEAT_PERSISTENT_UNDO
5148 /*
5149 * When writing the whole file and 'undofile' is set, also write the undo
5150 * file.
5151 */
5152 if (retval == OK && write_undo_file)
5153 {
5154 char_u hash[UNDO_HASH_SIZE];
5155
5156 sha256_finish(&sha_ctx, hash);
5157 u_write_undo(NULL, FALSE, buf, hash);
5158 }
5159#endif
5160
Bram Moolenaar071d4272004-06-13 20:20:40 +00005161#ifdef FEAT_AUTOCMD
5162#ifdef FEAT_EVAL
5163 if (!should_abort(retval))
5164#else
5165 if (!got_int)
5166#endif
5167 {
5168 aco_save_T aco;
5169
Bram Moolenaar68a33fc2012-04-25 16:50:48 +02005170 curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */
5171
Bram Moolenaar071d4272004-06-13 20:20:40 +00005172 /*
5173 * Apply POST autocommands.
5174 * Careful: The autocommands may call buf_write() recursively!
5175 */
5176 aucmd_prepbuf(&aco, buf);
5177
5178 if (append)
5179 apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname,
5180 FALSE, curbuf, eap);
5181 else if (filtering)
5182 apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname,
5183 FALSE, curbuf, eap);
5184 else if (reset_changed && whole)
5185 apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname,
5186 FALSE, curbuf, eap);
5187 else
5188 apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname,
5189 FALSE, curbuf, eap);
5190
5191 /* restore curwin/curbuf and a few other things */
5192 aucmd_restbuf(&aco);
5193
5194#ifdef FEAT_EVAL
5195 if (aborting()) /* autocmds may abort script processing */
5196 retval = FALSE;
5197#endif
5198 }
5199#endif
5200
5201 got_int |= prev_got_int;
5202
5203#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
5204 /* Update machine specific information. */
5205 mch_post_buffer_write(buf);
5206#endif
5207 return retval;
5208}
5209
5210/*
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005211 * Set the name of the current buffer. Use when the buffer doesn't have a
5212 * name and a ":r" or ":w" command with a file name is used.
5213 */
5214 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005215set_rw_fname(char_u *fname, char_u *sfname)
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005216{
5217#ifdef FEAT_AUTOCMD
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005218 buf_T *buf = curbuf;
5219
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005220 /* It's like the unnamed buffer is deleted.... */
5221 if (curbuf->b_p_bl)
5222 apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
5223 apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf);
5224# ifdef FEAT_EVAL
5225 if (aborting()) /* autocmds may abort script processing */
5226 return FAIL;
5227# endif
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005228 if (curbuf != buf)
5229 {
5230 /* We are in another buffer now, don't do the renaming. */
5231 EMSG(_(e_auchangedbuf));
5232 return FAIL;
5233 }
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005234#endif
5235
5236 if (setfname(curbuf, fname, sfname, FALSE) == OK)
5237 curbuf->b_flags |= BF_NOTEDITED;
5238
5239#ifdef FEAT_AUTOCMD
5240 /* ....and a new named one is created */
5241 apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, curbuf);
5242 if (curbuf->b_p_bl)
5243 apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf);
5244# ifdef FEAT_EVAL
5245 if (aborting()) /* autocmds may abort script processing */
5246 return FAIL;
5247# endif
5248
5249 /* Do filetype detection now if 'filetype' is empty. */
5250 if (*curbuf->b_p_ft == NUL)
5251 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005252 if (au_has_group((char_u *)"filetypedetect"))
Bram Moolenaar1610d052016-06-09 22:53:01 +02005253 (void)do_doautocmd((char_u *)"filetypedetect BufRead", FALSE, NULL);
Bram Moolenaara3227e22006-03-08 21:32:40 +00005254 do_modelines(0);
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005255 }
5256#endif
5257
5258 return OK;
5259}
5260
5261/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00005262 * Put file name into IObuff with quotes.
5263 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005264 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005265msg_add_fname(buf_T *buf, char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005266{
5267 if (fname == NULL)
5268 fname = (char_u *)"-stdin-";
5269 home_replace(buf, fname, IObuff + 1, IOSIZE - 4, TRUE);
5270 IObuff[0] = '"';
5271 STRCAT(IObuff, "\" ");
5272}
5273
5274/*
5275 * Append message for text mode to IObuff.
5276 * Return TRUE if something appended.
5277 */
5278 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005279msg_add_fileformat(int eol_type)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005280{
5281#ifndef USE_CRNL
5282 if (eol_type == EOL_DOS)
5283 {
5284 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[dos]") : _("[dos format]"));
5285 return TRUE;
5286 }
5287#endif
5288#ifndef USE_CR
5289 if (eol_type == EOL_MAC)
5290 {
5291 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[mac]") : _("[mac format]"));
5292 return TRUE;
5293 }
5294#endif
5295#if defined(USE_CRNL) || defined(USE_CR)
5296 if (eol_type == EOL_UNIX)
5297 {
5298 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[unix]") : _("[unix format]"));
5299 return TRUE;
5300 }
5301#endif
5302 return FALSE;
5303}
5304
5305/*
5306 * Append line and character count to IObuff.
5307 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005308 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005309msg_add_lines(
5310 int insert_space,
5311 long lnum,
Bram Moolenaar8767f522016-07-01 17:17:39 +02005312 off_T nchars)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005313{
5314 char_u *p;
5315
5316 p = IObuff + STRLEN(IObuff);
5317
5318 if (insert_space)
5319 *p++ = ' ';
5320 if (shortmess(SHM_LINES))
Bram Moolenaarbde98102016-07-01 20:03:42 +02005321 vim_snprintf((char *)p, IOSIZE - (p - IObuff),
5322 "%ldL, %lldC", lnum, (varnumber_T)nchars);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005323 else
5324 {
5325 if (lnum == 1)
5326 STRCPY(p, _("1 line, "));
5327 else
5328 sprintf((char *)p, _("%ld lines, "), lnum);
5329 p += STRLEN(p);
5330 if (nchars == 1)
5331 STRCPY(p, _("1 character"));
5332 else
Bram Moolenaarbde98102016-07-01 20:03:42 +02005333 vim_snprintf((char *)p, IOSIZE - (p - IObuff),
5334 _("%lld characters"), (varnumber_T)nchars);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005335 }
5336}
5337
5338/*
5339 * Append message for missing line separator to IObuff.
5340 */
5341 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005342msg_add_eol(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005343{
5344 STRCAT(IObuff, shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]"));
5345}
5346
5347/*
5348 * Check modification time of file, before writing to it.
5349 * The size isn't checked, because using a tool like "gzip" takes care of
5350 * using the same timestamp but can't set the size.
5351 */
5352 static int
Bram Moolenaar8767f522016-07-01 17:17:39 +02005353check_mtime(buf_T *buf, stat_T *st)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005354{
5355 if (buf->b_mtime_read != 0
5356 && time_differs((long)st->st_mtime, buf->b_mtime_read))
5357 {
5358 msg_scroll = TRUE; /* don't overwrite messages here */
5359 msg_silent = 0; /* must give this prompt */
5360 /* don't use emsg() here, don't want to flush the buffers */
5361 MSG_ATTR(_("WARNING: The file has been changed since reading it!!!"),
Bram Moolenaar8820b482017-03-16 17:23:31 +01005362 HL_ATTR(HLF_E));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005363 if (ask_yesno((char_u *)_("Do you really want to write to it"),
5364 TRUE) == 'n')
5365 return FAIL;
5366 msg_scroll = FALSE; /* always overwrite the file message now */
5367 }
5368 return OK;
5369}
5370
5371 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005372time_differs(long t1, long t2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005373{
Bram Moolenaar48e330a2016-02-23 14:53:34 +01005374#if defined(__linux__) || defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005375 /* On a FAT filesystem, esp. under Linux, there are only 5 bits to store
5376 * the seconds. Since the roundoff is done when flushing the inode, the
5377 * time may change unexpectedly by one second!!! */
5378 return (t1 - t2 > 1 || t2 - t1 > 1);
5379#else
5380 return (t1 != t2);
5381#endif
5382}
5383
5384/*
5385 * Call write() to write a number of bytes to the file.
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005386 * Handles encryption and 'encoding' conversion.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005387 *
5388 * Return FAIL for failure, OK otherwise.
5389 */
5390 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005391buf_write_bytes(struct bw_info *ip)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005392{
5393 int wlen;
5394 char_u *buf = ip->bw_buf; /* data to write */
5395 int len = ip->bw_len; /* length of data */
5396#ifdef HAS_BW_FLAGS
5397 int flags = ip->bw_flags; /* extra flags */
5398#endif
5399
5400#ifdef FEAT_MBYTE
5401 /*
5402 * Skip conversion when writing the crypt magic number or the BOM.
5403 */
5404 if (!(flags & FIO_NOCONVERT))
5405 {
5406 char_u *p;
5407 unsigned c;
5408 int n;
5409
5410 if (flags & FIO_UTF8)
5411 {
5412 /*
5413 * Convert latin1 in the buffer to UTF-8 in the file.
5414 */
5415 p = ip->bw_conv_buf; /* translate to buffer */
5416 for (wlen = 0; wlen < len; ++wlen)
5417 p += utf_char2bytes(buf[wlen], p);
5418 buf = ip->bw_conv_buf;
5419 len = (int)(p - ip->bw_conv_buf);
5420 }
5421 else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1))
5422 {
5423 /*
5424 * Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
5425 * Latin1 chars in the file.
5426 */
5427 if (flags & FIO_LATIN1)
5428 p = buf; /* translate in-place (can only get shorter) */
5429 else
5430 p = ip->bw_conv_buf; /* translate to buffer */
5431 for (wlen = 0; wlen < len; wlen += n)
5432 {
5433 if (wlen == 0 && ip->bw_restlen != 0)
5434 {
5435 int l;
5436
5437 /* Use remainder of previous call. Append the start of
5438 * buf[] to get a full sequence. Might still be too
5439 * short! */
5440 l = CONV_RESTLEN - ip->bw_restlen;
5441 if (l > len)
5442 l = len;
5443 mch_memmove(ip->bw_rest + ip->bw_restlen, buf, (size_t)l);
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005444 n = utf_ptr2len_len(ip->bw_rest, ip->bw_restlen + l);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005445 if (n > ip->bw_restlen + len)
5446 {
5447 /* We have an incomplete byte sequence at the end to
5448 * be written. We can't convert it without the
5449 * remaining bytes. Keep them for the next call. */
5450 if (ip->bw_restlen + len > CONV_RESTLEN)
5451 return FAIL;
5452 ip->bw_restlen += len;
5453 break;
5454 }
5455 if (n > 1)
5456 c = utf_ptr2char(ip->bw_rest);
5457 else
5458 c = ip->bw_rest[0];
5459 if (n >= ip->bw_restlen)
5460 {
5461 n -= ip->bw_restlen;
5462 ip->bw_restlen = 0;
5463 }
5464 else
5465 {
5466 ip->bw_restlen -= n;
5467 mch_memmove(ip->bw_rest, ip->bw_rest + n,
5468 (size_t)ip->bw_restlen);
5469 n = 0;
5470 }
5471 }
5472 else
5473 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005474 n = utf_ptr2len_len(buf + wlen, len - wlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005475 if (n > len - wlen)
5476 {
5477 /* We have an incomplete byte sequence at the end to
5478 * be written. We can't convert it without the
5479 * remaining bytes. Keep them for the next call. */
5480 if (len - wlen > CONV_RESTLEN)
5481 return FAIL;
5482 ip->bw_restlen = len - wlen;
5483 mch_memmove(ip->bw_rest, buf + wlen,
5484 (size_t)ip->bw_restlen);
5485 break;
5486 }
5487 if (n > 1)
5488 c = utf_ptr2char(buf + wlen);
5489 else
5490 c = buf[wlen];
5491 }
5492
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005493 if (ucs2bytes(c, &p, flags) && !ip->bw_conv_error)
5494 {
5495 ip->bw_conv_error = TRUE;
5496 ip->bw_conv_error_lnum = ip->bw_start_lnum;
5497 }
5498 if (c == NL)
5499 ++ip->bw_start_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005500 }
5501 if (flags & FIO_LATIN1)
5502 len = (int)(p - buf);
5503 else
5504 {
5505 buf = ip->bw_conv_buf;
5506 len = (int)(p - ip->bw_conv_buf);
5507 }
5508 }
5509
5510# ifdef WIN3264
5511 else if (flags & FIO_CODEPAGE)
5512 {
5513 /*
5514 * Convert UTF-8 or codepage to UCS-2 and then to MS-Windows
5515 * codepage.
5516 */
5517 char_u *from;
5518 size_t fromlen;
5519 char_u *to;
5520 int u8c;
5521 BOOL bad = FALSE;
5522 int needed;
5523
5524 if (ip->bw_restlen > 0)
5525 {
5526 /* Need to concatenate the remainder of the previous call and
5527 * the bytes of the current call. Use the end of the
5528 * conversion buffer for this. */
5529 fromlen = len + ip->bw_restlen;
5530 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5531 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5532 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5533 }
5534 else
5535 {
5536 from = buf;
5537 fromlen = len;
5538 }
5539
5540 to = ip->bw_conv_buf;
5541 if (enc_utf8)
5542 {
5543 /* Convert from UTF-8 to UCS-2, to the start of the buffer.
5544 * The buffer has been allocated to be big enough. */
5545 while (fromlen > 0)
5546 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005547 n = (int)utf_ptr2len_len(from, (int)fromlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005548 if (n > (int)fromlen) /* incomplete byte sequence */
5549 break;
5550 u8c = utf_ptr2char(from);
5551 *to++ = (u8c & 0xff);
5552 *to++ = (u8c >> 8);
5553 fromlen -= n;
5554 from += n;
5555 }
5556
5557 /* Copy remainder to ip->bw_rest[] to be used for the next
5558 * call. */
5559 if (fromlen > CONV_RESTLEN)
5560 {
5561 /* weird overlong sequence */
5562 ip->bw_conv_error = TRUE;
5563 return FAIL;
5564 }
5565 mch_memmove(ip->bw_rest, from, fromlen);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005566 ip->bw_restlen = (int)fromlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005567 }
5568 else
5569 {
5570 /* Convert from enc_codepage to UCS-2, to the start of the
5571 * buffer. The buffer has been allocated to be big enough. */
5572 ip->bw_restlen = 0;
5573 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005574 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005575 NULL, 0);
5576 if (needed == 0)
5577 {
5578 /* When conversion fails there may be a trailing byte. */
5579 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005580 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen - 1,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005581 NULL, 0);
5582 if (needed == 0)
5583 {
5584 /* Conversion doesn't work. */
5585 ip->bw_conv_error = TRUE;
5586 return FAIL;
5587 }
5588 /* Save the trailing byte for the next call. */
5589 ip->bw_rest[0] = from[fromlen - 1];
5590 ip->bw_restlen = 1;
5591 }
5592 needed = MultiByteToWideChar(enc_codepage, MB_ERR_INVALID_CHARS,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005593 (LPCSTR)from, (int)(fromlen - ip->bw_restlen),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005594 (LPWSTR)to, needed);
5595 if (needed == 0)
5596 {
5597 /* Safety check: Conversion doesn't work. */
5598 ip->bw_conv_error = TRUE;
5599 return FAIL;
5600 }
5601 to += needed * 2;
5602 }
5603
5604 fromlen = to - ip->bw_conv_buf;
5605 buf = to;
5606# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5607 if (FIO_GET_CP(flags) == CP_UTF8)
5608 {
5609 /* Convert from UCS-2 to UTF-8, using the remainder of the
5610 * conversion buffer. Fails when out of space. */
5611 for (from = ip->bw_conv_buf; fromlen > 1; fromlen -= 2)
5612 {
5613 u8c = *from++;
5614 u8c += (*from++ << 8);
5615 to += utf_char2bytes(u8c, to);
5616 if (to + 6 >= ip->bw_conv_buf + ip->bw_conv_buflen)
5617 {
5618 ip->bw_conv_error = TRUE;
5619 return FAIL;
5620 }
5621 }
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005622 len = (int)(to - buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005623 }
5624 else
5625#endif
5626 {
5627 /* Convert from UCS-2 to the codepage, using the remainder of
5628 * the conversion buffer. If the conversion uses the default
5629 * character "0", the data doesn't fit in this encoding, so
5630 * fail. */
5631 len = WideCharToMultiByte(FIO_GET_CP(flags), 0,
5632 (LPCWSTR)ip->bw_conv_buf, (int)fromlen / sizeof(WCHAR),
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005633 (LPSTR)to, (int)(ip->bw_conv_buflen - fromlen), 0,
5634 &bad);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005635 if (bad)
5636 {
5637 ip->bw_conv_error = TRUE;
5638 return FAIL;
5639 }
5640 }
5641 }
5642# endif
5643
Bram Moolenaar56718732006-03-15 22:53:57 +00005644# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00005645 else if (flags & FIO_MACROMAN)
5646 {
5647 /*
5648 * Convert UTF-8 or latin1 to Apple MacRoman.
5649 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005650 char_u *from;
5651 size_t fromlen;
5652
5653 if (ip->bw_restlen > 0)
5654 {
5655 /* Need to concatenate the remainder of the previous call and
5656 * the bytes of the current call. Use the end of the
5657 * conversion buffer for this. */
5658 fromlen = len + ip->bw_restlen;
5659 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5660 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5661 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5662 }
5663 else
5664 {
5665 from = buf;
5666 fromlen = len;
5667 }
5668
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00005669 if (enc2macroman(from, fromlen,
5670 ip->bw_conv_buf, &len, ip->bw_conv_buflen,
5671 ip->bw_rest, &ip->bw_restlen) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005672 {
5673 ip->bw_conv_error = TRUE;
5674 return FAIL;
5675 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005676 buf = ip->bw_conv_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005677 }
5678# endif
5679
5680# ifdef USE_ICONV
5681 if (ip->bw_iconv_fd != (iconv_t)-1)
5682 {
5683 const char *from;
5684 size_t fromlen;
5685 char *to;
5686 size_t tolen;
5687
5688 /* Convert with iconv(). */
5689 if (ip->bw_restlen > 0)
5690 {
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005691 char *fp;
5692
Bram Moolenaar071d4272004-06-13 20:20:40 +00005693 /* Need to concatenate the remainder of the previous call and
5694 * the bytes of the current call. Use the end of the
5695 * conversion buffer for this. */
5696 fromlen = len + ip->bw_restlen;
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005697 fp = (char *)ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5698 mch_memmove(fp, ip->bw_rest, (size_t)ip->bw_restlen);
5699 mch_memmove(fp + ip->bw_restlen, buf, (size_t)len);
5700 from = fp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005701 tolen = ip->bw_conv_buflen - fromlen;
5702 }
5703 else
5704 {
5705 from = (const char *)buf;
5706 fromlen = len;
5707 tolen = ip->bw_conv_buflen;
5708 }
5709 to = (char *)ip->bw_conv_buf;
5710
5711 if (ip->bw_first)
5712 {
5713 size_t save_len = tolen;
5714
5715 /* output the initial shift state sequence */
5716 (void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen);
5717
5718 /* There is a bug in iconv() on Linux (which appears to be
5719 * wide-spread) which sets "to" to NULL and messes up "tolen".
5720 */
5721 if (to == NULL)
5722 {
5723 to = (char *)ip->bw_conv_buf;
5724 tolen = save_len;
5725 }
5726 ip->bw_first = FALSE;
5727 }
5728
5729 /*
5730 * If iconv() has an error or there is not enough room, fail.
5731 */
5732 if ((iconv(ip->bw_iconv_fd, (void *)&from, &fromlen, &to, &tolen)
5733 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
5734 || fromlen > CONV_RESTLEN)
5735 {
5736 ip->bw_conv_error = TRUE;
5737 return FAIL;
5738 }
5739
5740 /* copy remainder to ip->bw_rest[] to be used for the next call. */
5741 if (fromlen > 0)
5742 mch_memmove(ip->bw_rest, (void *)from, fromlen);
5743 ip->bw_restlen = (int)fromlen;
5744
5745 buf = ip->bw_conv_buf;
5746 len = (int)((char_u *)to - ip->bw_conv_buf);
5747 }
5748# endif
5749 }
5750#endif /* FEAT_MBYTE */
5751
Bram Moolenaare6bf6552017-06-27 22:11:51 +02005752 if (ip->bw_fd < 0)
5753 /* Only checking conversion, which is OK if we get here. */
5754 return OK;
5755
Bram Moolenaar071d4272004-06-13 20:20:40 +00005756#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02005757 if (flags & FIO_ENCRYPTED)
5758 {
5759 /* Encrypt the data. Do it in-place if possible, otherwise use an
5760 * allocated buffer. */
5761 if (crypt_works_inplace(ip->bw_buffer->b_cryptstate))
5762 {
5763 crypt_encode_inplace(ip->bw_buffer->b_cryptstate, buf, len);
5764 }
5765 else
5766 {
5767 char_u *outbuf;
5768
5769 len = crypt_encode_alloc(curbuf->b_cryptstate, buf, len, &outbuf);
5770 if (len == 0)
5771 return OK; /* Crypt layer is buffering, will flush later. */
5772 wlen = write_eintr(ip->bw_fd, outbuf, len);
5773 vim_free(outbuf);
5774 return (wlen < len) ? FAIL : OK;
5775 }
5776 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005777#endif
5778
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005779 wlen = write_eintr(ip->bw_fd, buf, len);
5780 return (wlen < len) ? FAIL : OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005781}
5782
5783#ifdef FEAT_MBYTE
5784/*
5785 * Convert a Unicode character to bytes.
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005786 * Return TRUE for an error, FALSE when it's OK.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005787 */
5788 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005789ucs2bytes(
5790 unsigned c, /* in: character */
5791 char_u **pp, /* in/out: pointer to result */
5792 int flags) /* FIO_ flags */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005793{
5794 char_u *p = *pp;
5795 int error = FALSE;
5796 int cc;
5797
5798
5799 if (flags & FIO_UCS4)
5800 {
5801 if (flags & FIO_ENDIAN_L)
5802 {
5803 *p++ = c;
5804 *p++ = (c >> 8);
5805 *p++ = (c >> 16);
5806 *p++ = (c >> 24);
5807 }
5808 else
5809 {
5810 *p++ = (c >> 24);
5811 *p++ = (c >> 16);
5812 *p++ = (c >> 8);
5813 *p++ = c;
5814 }
5815 }
5816 else if (flags & (FIO_UCS2 | FIO_UTF16))
5817 {
5818 if (c >= 0x10000)
5819 {
5820 if (flags & FIO_UTF16)
5821 {
5822 /* Make two words, ten bits of the character in each. First
5823 * word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff */
5824 c -= 0x10000;
5825 if (c >= 0x100000)
5826 error = TRUE;
5827 cc = ((c >> 10) & 0x3ff) + 0xd800;
5828 if (flags & FIO_ENDIAN_L)
5829 {
5830 *p++ = cc;
5831 *p++ = ((unsigned)cc >> 8);
5832 }
5833 else
5834 {
5835 *p++ = ((unsigned)cc >> 8);
5836 *p++ = cc;
5837 }
5838 c = (c & 0x3ff) + 0xdc00;
5839 }
5840 else
5841 error = TRUE;
5842 }
5843 if (flags & FIO_ENDIAN_L)
5844 {
5845 *p++ = c;
5846 *p++ = (c >> 8);
5847 }
5848 else
5849 {
5850 *p++ = (c >> 8);
5851 *p++ = c;
5852 }
5853 }
5854 else /* Latin1 */
5855 {
5856 if (c >= 0x100)
5857 {
5858 error = TRUE;
5859 *p++ = 0xBF;
5860 }
5861 else
5862 *p++ = c;
5863 }
5864
5865 *pp = p;
5866 return error;
5867}
5868
5869/*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005870 * Return TRUE if file encoding "fenc" requires conversion from or to
5871 * 'encoding'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005872 */
5873 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005874need_conversion(char_u *fenc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005875{
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005876 int same_encoding;
5877 int enc_flags;
5878 int fenc_flags;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005879
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005880 if (*fenc == NUL || STRCMP(p_enc, fenc) == 0)
Bram Moolenaar442b4222010-05-24 21:34:22 +02005881 {
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005882 same_encoding = TRUE;
Bram Moolenaar442b4222010-05-24 21:34:22 +02005883 fenc_flags = 0;
5884 }
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005885 else
5886 {
5887 /* Ignore difference between "ansi" and "latin1", "ucs-4" and
5888 * "ucs-4be", etc. */
5889 enc_flags = get_fio_flags(p_enc);
5890 fenc_flags = get_fio_flags(fenc);
5891 same_encoding = (enc_flags != 0 && fenc_flags == enc_flags);
5892 }
5893 if (same_encoding)
5894 {
5895 /* Specified encoding matches with 'encoding'. This requires
5896 * conversion when 'encoding' is Unicode but not UTF-8. */
5897 return enc_unicode != 0;
5898 }
5899
5900 /* Encodings differ. However, conversion is not needed when 'enc' is any
5901 * Unicode encoding and the file is UTF-8. */
5902 return !(enc_utf8 && fenc_flags == FIO_UTF8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005903}
5904
5905/*
5906 * Check "ptr" for a unicode encoding and return the FIO_ flags needed for the
5907 * internal conversion.
5908 * if "ptr" is an empty string, use 'encoding'.
5909 */
5910 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005911get_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005912{
5913 int prop;
5914
5915 if (*ptr == NUL)
5916 ptr = p_enc;
5917
5918 prop = enc_canon_props(ptr);
5919 if (prop & ENC_UNICODE)
5920 {
5921 if (prop & ENC_2BYTE)
5922 {
5923 if (prop & ENC_ENDIAN_L)
5924 return FIO_UCS2 | FIO_ENDIAN_L;
5925 return FIO_UCS2;
5926 }
5927 if (prop & ENC_4BYTE)
5928 {
5929 if (prop & ENC_ENDIAN_L)
5930 return FIO_UCS4 | FIO_ENDIAN_L;
5931 return FIO_UCS4;
5932 }
5933 if (prop & ENC_2WORD)
5934 {
5935 if (prop & ENC_ENDIAN_L)
5936 return FIO_UTF16 | FIO_ENDIAN_L;
5937 return FIO_UTF16;
5938 }
5939 return FIO_UTF8;
5940 }
5941 if (prop & ENC_LATIN1)
5942 return FIO_LATIN1;
5943 /* must be ENC_DBCS, requires iconv() */
5944 return 0;
5945}
5946
5947#ifdef WIN3264
5948/*
5949 * Check "ptr" for a MS-Windows codepage name and return the FIO_ flags needed
5950 * for the conversion MS-Windows can do for us. Also accept "utf-8".
5951 * Used for conversion between 'encoding' and 'fileencoding'.
5952 */
5953 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005954get_win_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005955{
5956 int cp;
5957
5958 /* Cannot do this when 'encoding' is not utf-8 and not a codepage. */
5959 if (!enc_utf8 && enc_codepage <= 0)
5960 return 0;
5961
5962 cp = encname2codepage(ptr);
5963 if (cp == 0)
5964 {
5965# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5966 if (STRCMP(ptr, "utf-8") == 0)
5967 cp = CP_UTF8;
5968 else
5969# endif
5970 return 0;
5971 }
5972 return FIO_PUT_CP(cp) | FIO_CODEPAGE;
5973}
5974#endif
5975
5976#ifdef MACOS_X
5977/*
5978 * Check "ptr" for a Carbon supported encoding and return the FIO_ flags
5979 * needed for the internal conversion to/from utf-8 or latin1.
5980 */
5981 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005982get_mac_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005983{
5984 if ((enc_utf8 || STRCMP(p_enc, "latin1") == 0)
5985 && (enc_canon_props(ptr) & ENC_MACROMAN))
5986 return FIO_MACROMAN;
5987 return 0;
5988}
5989#endif
5990
5991/*
5992 * Check for a Unicode BOM (Byte Order Mark) at the start of p[size].
5993 * "size" must be at least 2.
5994 * Return the name of the encoding and set "*lenp" to the length.
5995 * Returns NULL when no BOM found.
5996 */
5997 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005998check_for_bom(
5999 char_u *p,
6000 long size,
6001 int *lenp,
6002 int flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006003{
6004 char *name = NULL;
6005 int len = 2;
6006
6007 if (p[0] == 0xef && p[1] == 0xbb && size >= 3 && p[2] == 0xbf
Bram Moolenaaree0f5a62008-07-24 20:09:16 +00006008 && (flags == FIO_ALL || flags == FIO_UTF8 || flags == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006009 {
6010 name = "utf-8"; /* EF BB BF */
6011 len = 3;
6012 }
6013 else if (p[0] == 0xff && p[1] == 0xfe)
6014 {
6015 if (size >= 4 && p[2] == 0 && p[3] == 0
6016 && (flags == FIO_ALL || flags == (FIO_UCS4 | FIO_ENDIAN_L)))
6017 {
6018 name = "ucs-4le"; /* FF FE 00 00 */
6019 len = 4;
6020 }
Bram Moolenaar223a1892008-11-11 20:57:11 +00006021 else if (flags == (FIO_UCS2 | FIO_ENDIAN_L))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006022 name = "ucs-2le"; /* FF FE */
Bram Moolenaar223a1892008-11-11 20:57:11 +00006023 else if (flags == FIO_ALL || flags == (FIO_UTF16 | FIO_ENDIAN_L))
6024 /* utf-16le is preferred, it also works for ucs-2le text */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006025 name = "utf-16le"; /* FF FE */
6026 }
6027 else if (p[0] == 0xfe && p[1] == 0xff
6028 && (flags == FIO_ALL || flags == FIO_UCS2 || flags == FIO_UTF16))
6029 {
Bram Moolenaarffd82c52008-02-20 17:15:26 +00006030 /* Default to utf-16, it works also for ucs-2 text. */
6031 if (flags == FIO_UCS2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006032 name = "ucs-2"; /* FE FF */
Bram Moolenaarffd82c52008-02-20 17:15:26 +00006033 else
6034 name = "utf-16"; /* FE FF */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006035 }
6036 else if (size >= 4 && p[0] == 0 && p[1] == 0 && p[2] == 0xfe
6037 && p[3] == 0xff && (flags == FIO_ALL || flags == FIO_UCS4))
6038 {
6039 name = "ucs-4"; /* 00 00 FE FF */
6040 len = 4;
6041 }
6042
6043 *lenp = len;
6044 return (char_u *)name;
6045}
6046
6047/*
6048 * Generate a BOM in "buf[4]" for encoding "name".
6049 * Return the length of the BOM (zero when no BOM).
6050 */
6051 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006052make_bom(char_u *buf, char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006053{
6054 int flags;
6055 char_u *p;
6056
6057 flags = get_fio_flags(name);
6058
6059 /* Can't put a BOM in a non-Unicode file. */
6060 if (flags == FIO_LATIN1 || flags == 0)
6061 return 0;
6062
6063 if (flags == FIO_UTF8) /* UTF-8 */
6064 {
6065 buf[0] = 0xef;
6066 buf[1] = 0xbb;
6067 buf[2] = 0xbf;
6068 return 3;
6069 }
6070 p = buf;
6071 (void)ucs2bytes(0xfeff, &p, flags);
6072 return (int)(p - buf);
6073}
6074#endif
6075
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00006076#if defined(FEAT_VIMINFO) || defined(FEAT_BROWSE) || \
Bram Moolenaara0174af2008-01-02 20:08:25 +00006077 defined(FEAT_QUICKFIX) || defined(FEAT_AUTOCMD) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006078/*
6079 * Try to find a shortname by comparing the fullname with the current
6080 * directory.
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006081 * Returns "full_path" or pointer into "full_path" if shortened.
6082 */
6083 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006084shorten_fname1(char_u *full_path)
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006085{
Bram Moolenaard9462e32011-04-11 21:35:11 +02006086 char_u *dirname;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006087 char_u *p = full_path;
6088
Bram Moolenaard9462e32011-04-11 21:35:11 +02006089 dirname = alloc(MAXPATHL);
6090 if (dirname == NULL)
6091 return full_path;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006092 if (mch_dirname(dirname, MAXPATHL) == OK)
6093 {
6094 p = shorten_fname(full_path, dirname);
6095 if (p == NULL || *p == NUL)
6096 p = full_path;
6097 }
Bram Moolenaard9462e32011-04-11 21:35:11 +02006098 vim_free(dirname);
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006099 return p;
6100}
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00006101#endif
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006102
6103/*
6104 * Try to find a shortname by comparing the fullname with the current
6105 * directory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006106 * Returns NULL if not shorter name possible, pointer into "full_path"
6107 * otherwise.
6108 */
6109 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006110shorten_fname(char_u *full_path, char_u *dir_name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006111{
6112 int len;
6113 char_u *p;
6114
6115 if (full_path == NULL)
6116 return NULL;
6117 len = (int)STRLEN(dir_name);
6118 if (fnamencmp(dir_name, full_path, len) == 0)
6119 {
6120 p = full_path + len;
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006121#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006122 /*
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006123 * MSWIN: when a file is in the root directory, dir_name will end in a
Bram Moolenaar071d4272004-06-13 20:20:40 +00006124 * slash, since C: by itself does not define a specific dir. In this
6125 * case p may already be correct. <negri>
6126 */
6127 if (!((len > 2) && (*(p - 2) == ':')))
6128#endif
6129 {
6130 if (vim_ispathsep(*p))
6131 ++p;
6132#ifndef VMS /* the path separator is always part of the path */
6133 else
6134 p = NULL;
6135#endif
6136 }
6137 }
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006138#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006139 /*
6140 * When using a file in the current drive, remove the drive name:
6141 * "A:\dir\file" -> "\dir\file". This helps when moving a session file on
6142 * a floppy from "A:\dir" to "B:\dir".
6143 */
6144 else if (len > 3
6145 && TOUPPER_LOC(full_path[0]) == TOUPPER_LOC(dir_name[0])
6146 && full_path[1] == ':'
6147 && vim_ispathsep(full_path[2]))
6148 p = full_path + 2;
6149#endif
6150 else
6151 p = NULL;
6152 return p;
6153}
6154
6155/*
6156 * Shorten filenames for all buffers.
6157 * When "force" is TRUE: Use full path from now on for files currently being
6158 * edited, both for file name and swap file name. Try to shorten the file
6159 * names a bit, if safe to do so.
6160 * When "force" is FALSE: Only try to shorten absolute file names.
6161 * For buffers that have buftype "nofile" or "scratch": never change the file
6162 * name.
6163 */
6164 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006165shorten_fnames(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006166{
6167 char_u dirname[MAXPATHL];
6168 buf_T *buf;
6169 char_u *p;
6170
6171 mch_dirname(dirname, MAXPATHL);
Bram Moolenaar29323592016-07-24 22:04:11 +02006172 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006173 {
6174 if (buf->b_fname != NULL
6175#ifdef FEAT_QUICKFIX
6176 && !bt_nofile(buf)
6177#endif
6178 && !path_with_url(buf->b_fname)
6179 && (force
6180 || buf->b_sfname == NULL
6181 || mch_isFullName(buf->b_sfname)))
6182 {
6183 vim_free(buf->b_sfname);
6184 buf->b_sfname = NULL;
6185 p = shorten_fname(buf->b_ffname, dirname);
6186 if (p != NULL)
6187 {
6188 buf->b_sfname = vim_strsave(p);
6189 buf->b_fname = buf->b_sfname;
6190 }
6191 if (p == NULL || buf->b_fname == NULL)
6192 buf->b_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006193 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00006194
6195 /* Always make the swap file name a full path, a "nofile" buffer may
6196 * also have a swap file. */
6197 mf_fullname(buf->b_ml.ml_mfp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006198 }
6199#ifdef FEAT_WINDOWS
6200 status_redraw_all();
Bram Moolenaar49d7bf12006-02-17 21:45:41 +00006201 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006202#endif
6203}
6204
6205#if (defined(FEAT_DND) && defined(FEAT_GUI_GTK)) \
6206 || defined(FEAT_GUI_MSWIN) \
6207 || defined(FEAT_GUI_MAC) \
6208 || defined(PROTO)
6209/*
6210 * Shorten all filenames in "fnames[count]" by current directory.
6211 */
6212 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006213shorten_filenames(char_u **fnames, int count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006214{
6215 int i;
6216 char_u dirname[MAXPATHL];
6217 char_u *p;
6218
6219 if (fnames == NULL || count < 1)
6220 return;
6221 mch_dirname(dirname, sizeof(dirname));
6222 for (i = 0; i < count; ++i)
6223 {
6224 if ((p = shorten_fname(fnames[i], dirname)) != NULL)
6225 {
6226 /* shorten_fname() returns pointer in given "fnames[i]". If free
6227 * "fnames[i]" first, "p" becomes invalid. So we need to copy
6228 * "p" first then free fnames[i]. */
6229 p = vim_strsave(p);
6230 vim_free(fnames[i]);
6231 fnames[i] = p;
6232 }
6233 }
6234}
6235#endif
6236
6237/*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006238 * add extension to file name - change path/fo.o.h to path/fo.o.h.ext or
Bram Moolenaar071d4272004-06-13 20:20:40 +00006239 * fo_o_h.ext for MSDOS or when shortname option set.
6240 *
6241 * Assumed that fname is a valid name found in the filesystem we assure that
6242 * the return value is a different name and ends in 'ext'.
6243 * "ext" MUST be at most 4 characters long if it starts with a dot, 3
6244 * characters otherwise.
6245 * Space for the returned name is allocated, must be freed later.
6246 * Returns NULL when out of memory.
6247 */
6248 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006249modname(
6250 char_u *fname,
6251 char_u *ext,
6252 int prepend_dot) /* may prepend a '.' to file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006253{
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006254 return buf_modname((curbuf->b_p_sn || curbuf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00006255 fname, ext, prepend_dot);
6256}
6257
6258 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006259buf_modname(
6260 int shortname, /* use 8.3 file name */
6261 char_u *fname,
6262 char_u *ext,
6263 int prepend_dot) /* may prepend a '.' to file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006264{
6265 char_u *retval;
6266 char_u *s;
6267 char_u *e;
6268 char_u *ptr;
6269 int fnamelen, extlen;
6270
6271 extlen = (int)STRLEN(ext);
6272
6273 /*
6274 * If there is no file name we must get the name of the current directory
6275 * (we need the full path in case :cd is used).
6276 */
6277 if (fname == NULL || *fname == NUL)
6278 {
6279 retval = alloc((unsigned)(MAXPATHL + extlen + 3));
6280 if (retval == NULL)
6281 return NULL;
6282 if (mch_dirname(retval, MAXPATHL) == FAIL ||
6283 (fnamelen = (int)STRLEN(retval)) == 0)
6284 {
6285 vim_free(retval);
6286 return NULL;
6287 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006288 if (!after_pathsep(retval, retval + fnamelen))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006289 {
6290 retval[fnamelen++] = PATHSEP;
6291 retval[fnamelen] = NUL;
6292 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006293 prepend_dot = FALSE; /* nothing to prepend a dot to */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006294 }
6295 else
6296 {
6297 fnamelen = (int)STRLEN(fname);
6298 retval = alloc((unsigned)(fnamelen + extlen + 3));
6299 if (retval == NULL)
6300 return NULL;
6301 STRCPY(retval, fname);
6302#ifdef VMS
6303 vms_remove_version(retval); /* we do not need versions here */
6304#endif
6305 }
6306
6307 /*
6308 * search backwards until we hit a '/', '\' or ':' replacing all '.'
6309 * by '_' for MSDOS or when shortname option set and ext starts with a dot.
6310 * Then truncate what is after the '/', '\' or ':' to 8 characters for
6311 * MSDOS and 26 characters for AMIGA, a lot more for UNIX.
6312 */
Bram Moolenaar91acfff2017-03-12 19:22:36 +01006313 for (ptr = retval + fnamelen; ptr > retval; MB_PTR_BACK(retval, ptr))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006314 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006315 if (*ext == '.'
Bram Moolenaare60acc12011-05-10 16:41:25 +02006316#ifdef USE_LONG_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00006317 && (!USE_LONG_FNAME || shortname)
Bram Moolenaare60acc12011-05-10 16:41:25 +02006318#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006319 && shortname
Bram Moolenaare60acc12011-05-10 16:41:25 +02006320#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006321 )
6322 if (*ptr == '.') /* replace '.' by '_' */
6323 *ptr = '_';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006324 if (vim_ispathsep(*ptr))
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006325 {
6326 ++ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006327 break;
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006328 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006329 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006330
6331 /* the file name has at most BASENAMELEN characters. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006332 if (STRLEN(ptr) > (unsigned)BASENAMELEN)
6333 ptr[BASENAMELEN] = '\0';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006334
6335 s = ptr + STRLEN(ptr);
6336
6337 /*
6338 * For 8.3 file names we may have to reduce the length.
6339 */
6340#ifdef USE_LONG_FNAME
6341 if (!USE_LONG_FNAME || shortname)
6342#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006343 if (shortname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006344#endif
6345 {
6346 /*
6347 * If there is no file name, or the file name ends in '/', and the
6348 * extension starts with '.', put a '_' before the dot, because just
6349 * ".ext" is invalid.
6350 */
6351 if (fname == NULL || *fname == NUL
6352 || vim_ispathsep(fname[STRLEN(fname) - 1]))
6353 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006354 if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006355 *s++ = '_';
6356 }
6357 /*
6358 * If the extension starts with '.', truncate the base name at 8
6359 * characters
6360 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006361 else if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006362 {
Bram Moolenaar78a15312009-05-15 19:33:18 +00006363 if ((size_t)(s - ptr) > (size_t)8)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006364 {
6365 s = ptr + 8;
6366 *s = '\0';
6367 }
6368 }
6369 /*
6370 * If the extension doesn't start with '.', and the file name
6371 * doesn't have an extension yet, append a '.'
6372 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006373 else if ((e = vim_strchr(ptr, '.')) == NULL)
6374 *s++ = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006375 /*
6376 * If the extension doesn't start with '.', and there already is an
Bram Moolenaar7263a772007-05-10 17:35:54 +00006377 * extension, it may need to be truncated
Bram Moolenaar071d4272004-06-13 20:20:40 +00006378 */
6379 else if ((int)STRLEN(e) + extlen > 4)
6380 s = e + 4 - extlen;
6381 }
Bram Moolenaare7fedb62015-12-31 19:07:19 +01006382#if defined(USE_LONG_FNAME) || defined(WIN3264)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006383 /*
6384 * If there is no file name, and the extension starts with '.', put a
6385 * '_' before the dot, because just ".ext" may be invalid if it's on a
6386 * FAT partition, and on HPFS it doesn't matter.
6387 */
6388 else if ((fname == NULL || *fname == NUL) && *ext == '.')
6389 *s++ = '_';
6390#endif
6391
6392 /*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006393 * Append the extension.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006394 * ext can start with '.' and cannot exceed 3 more characters.
6395 */
6396 STRCPY(s, ext);
6397
Bram Moolenaar071d4272004-06-13 20:20:40 +00006398 /*
6399 * Prepend the dot.
6400 */
Bram Moolenaare60acc12011-05-10 16:41:25 +02006401 if (prepend_dot && !shortname && *(e = gettail(retval)) != '.'
Bram Moolenaar071d4272004-06-13 20:20:40 +00006402#ifdef USE_LONG_FNAME
6403 && USE_LONG_FNAME
6404#endif
6405 )
6406 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006407 STRMOVE(e + 1, e);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006408 *e = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006409 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006410
6411 /*
6412 * Check that, after appending the extension, the file name is really
6413 * different.
6414 */
6415 if (fname != NULL && STRCMP(fname, retval) == 0)
6416 {
6417 /* we search for a character that can be replaced by '_' */
6418 while (--s >= ptr)
6419 {
6420 if (*s != '_')
6421 {
6422 *s = '_';
6423 break;
6424 }
6425 }
6426 if (s < ptr) /* fname was "________.<ext>", how tricky! */
6427 *ptr = 'v';
6428 }
6429 return retval;
6430}
6431
6432/*
6433 * Like fgets(), but if the file line is too long, it is truncated and the
6434 * rest of the line is thrown away. Returns TRUE for end-of-file.
6435 */
6436 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006437vim_fgets(char_u *buf, int size, FILE *fp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006438{
6439 char *eof;
6440#define FGETS_SIZE 200
6441 char tbuf[FGETS_SIZE];
6442
6443 buf[size - 2] = NUL;
6444#ifdef USE_CR
6445 eof = fgets_cr((char *)buf, size, fp);
6446#else
6447 eof = fgets((char *)buf, size, fp);
6448#endif
6449 if (buf[size - 2] != NUL && buf[size - 2] != '\n')
6450 {
6451 buf[size - 1] = NUL; /* Truncate the line */
6452
6453 /* Now throw away the rest of the line: */
6454 do
6455 {
6456 tbuf[FGETS_SIZE - 2] = NUL;
6457#ifdef USE_CR
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006458 ignoredp = fgets_cr((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006459#else
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006460 ignoredp = fgets((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006461#endif
6462 } while (tbuf[FGETS_SIZE - 2] != NUL && tbuf[FGETS_SIZE - 2] != '\n');
6463 }
6464 return (eof == NULL);
6465}
6466
6467#if defined(USE_CR) || defined(PROTO)
6468/*
6469 * Like vim_fgets(), but accept any line terminator: CR, CR-LF or LF.
6470 * Returns TRUE for end-of-file.
6471 * Only used for the Mac, because it's much slower than vim_fgets().
6472 */
6473 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006474tag_fgets(char_u *buf, int size, FILE *fp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006475{
6476 int i = 0;
6477 int c;
6478 int eof = FALSE;
6479
6480 for (;;)
6481 {
6482 c = fgetc(fp);
6483 if (c == EOF)
6484 {
6485 eof = TRUE;
6486 break;
6487 }
6488 if (c == '\r')
6489 {
6490 /* Always store a NL for end-of-line. */
6491 if (i < size - 1)
6492 buf[i++] = '\n';
6493 c = fgetc(fp);
6494 if (c != '\n') /* Macintosh format: single CR. */
6495 ungetc(c, fp);
6496 break;
6497 }
6498 if (i < size - 1)
6499 buf[i++] = c;
6500 if (c == '\n')
6501 break;
6502 }
6503 buf[i] = NUL;
6504 return eof;
6505}
6506#endif
6507
6508/*
6509 * rename() only works if both files are on the same file system, this
6510 * function will (attempts to?) copy the file across if rename fails -- webb
6511 * Return -1 for failure, 0 for success.
6512 */
6513 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006514vim_rename(char_u *from, char_u *to)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006515{
6516 int fd_in;
6517 int fd_out;
6518 int n;
6519 char *errmsg = NULL;
6520 char *buffer;
6521#ifdef AMIGA
6522 BPTR flock;
6523#endif
Bram Moolenaar8767f522016-07-01 17:17:39 +02006524 stat_T st;
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006525 long perm;
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006526#ifdef HAVE_ACL
6527 vim_acl_T acl; /* ACL from original file */
6528#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006529 int use_tmp_file = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006530
6531 /*
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006532 * When the names are identical, there is nothing to do. When they refer
6533 * to the same file (ignoring case and slash/backslash differences) but
6534 * the file name differs we need to go through a temp file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006535 */
6536 if (fnamecmp(from, to) == 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006537 {
Bram Moolenaar71afbfe2013-03-19 16:49:16 +01006538 if (p_fic && STRCMP(gettail(from), gettail(to)) != 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006539 use_tmp_file = TRUE;
6540 else
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006541 return 0;
6542 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006543
6544 /*
6545 * Fail if the "from" file doesn't exist. Avoids that "to" is deleted.
6546 */
6547 if (mch_stat((char *)from, &st) < 0)
6548 return -1;
6549
Bram Moolenaar3576da72008-12-30 15:15:57 +00006550#ifdef UNIX
6551 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02006552 stat_T st_to;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006553
6554 /* It's possible for the source and destination to be the same file.
6555 * This happens when "from" and "to" differ in case and are on a FAT32
6556 * filesystem. In that case go through a temp file name. */
6557 if (mch_stat((char *)to, &st_to) >= 0
6558 && st.st_dev == st_to.st_dev
6559 && st.st_ino == st_to.st_ino)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006560 use_tmp_file = TRUE;
6561 }
6562#endif
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02006563#ifdef WIN3264
6564 {
6565 BY_HANDLE_FILE_INFORMATION info1, info2;
6566
6567 /* It's possible for the source and destination to be the same file.
6568 * In that case go through a temp file name. This makes rename("foo",
6569 * "./foo") a no-op (in a complicated way). */
6570 if (win32_fileinfo(from, &info1) == FILEINFO_OK
6571 && win32_fileinfo(to, &info2) == FILEINFO_OK
6572 && info1.dwVolumeSerialNumber == info2.dwVolumeSerialNumber
6573 && info1.nFileIndexHigh == info2.nFileIndexHigh
6574 && info1.nFileIndexLow == info2.nFileIndexLow)
6575 use_tmp_file = TRUE;
6576 }
6577#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006578
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006579 if (use_tmp_file)
6580 {
6581 char tempname[MAXPATHL + 1];
6582
6583 /*
6584 * Find a name that doesn't exist and is in the same directory.
6585 * Rename "from" to "tempname" and then rename "tempname" to "to".
6586 */
6587 if (STRLEN(from) >= MAXPATHL - 5)
6588 return -1;
6589 STRCPY(tempname, from);
6590 for (n = 123; n < 99999; ++n)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006591 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006592 sprintf((char *)gettail((char_u *)tempname), "%d", n);
6593 if (mch_stat(tempname, &st) < 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006594 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006595 if (mch_rename((char *)from, tempname) == 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006596 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006597 if (mch_rename(tempname, (char *)to) == 0)
6598 return 0;
6599 /* Strange, the second step failed. Try moving the
6600 * file back and return failure. */
6601 mch_rename(tempname, (char *)from);
Bram Moolenaar3576da72008-12-30 15:15:57 +00006602 return -1;
6603 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006604 /* If it fails for one temp name it will most likely fail
6605 * for any temp name, give up. */
6606 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006607 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006608 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006609 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006610 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006611
Bram Moolenaar071d4272004-06-13 20:20:40 +00006612 /*
6613 * Delete the "to" file, this is required on some systems to make the
6614 * mch_rename() work, on other systems it makes sure that we don't have
6615 * two files when the mch_rename() fails.
6616 */
6617
6618#ifdef AMIGA
6619 /*
6620 * With MSDOS-compatible filesystems (crossdos, messydos) it is possible
6621 * that the name of the "to" file is the same as the "from" file, even
Bram Moolenaar7263a772007-05-10 17:35:54 +00006622 * though the names are different. To avoid the chance of accidentally
Bram Moolenaar071d4272004-06-13 20:20:40 +00006623 * deleting the "from" file (horror!) we lock it during the remove.
6624 *
6625 * When used for making a backup before writing the file: This should not
6626 * happen with ":w", because startscript() should detect this problem and
6627 * set buf->b_shortname, causing modname() to return a correct ".bak" file
6628 * name. This problem does exist with ":w filename", but then the
6629 * original file will be somewhere else so the backup isn't really
6630 * important. If autoscripting is off the rename may fail.
6631 */
6632 flock = Lock((UBYTE *)from, (long)ACCESS_READ);
6633#endif
6634 mch_remove(to);
6635#ifdef AMIGA
6636 if (flock)
6637 UnLock(flock);
6638#endif
6639
6640 /*
6641 * First try a normal rename, return if it works.
6642 */
6643 if (mch_rename((char *)from, (char *)to) == 0)
6644 return 0;
6645
6646 /*
6647 * Rename() failed, try copying the file.
6648 */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006649 perm = mch_getperm(from);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006650#ifdef HAVE_ACL
6651 /* For systems that support ACL: get the ACL from the original file. */
6652 acl = mch_get_acl(from);
6653#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006654 fd_in = mch_open((char *)from, O_RDONLY|O_EXTRA, 0);
6655 if (fd_in == -1)
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006656 {
6657#ifdef HAVE_ACL
6658 mch_free_acl(acl);
6659#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006660 return -1;
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006661 }
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006662
6663 /* Create the new file with same permissions as the original. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00006664 fd_out = mch_open((char *)to,
6665 O_CREAT|O_EXCL|O_WRONLY|O_EXTRA|O_NOFOLLOW, (int)perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006666 if (fd_out == -1)
6667 {
6668 close(fd_in);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006669#ifdef HAVE_ACL
6670 mch_free_acl(acl);
6671#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006672 return -1;
6673 }
6674
6675 buffer = (char *)alloc(BUFSIZE);
6676 if (buffer == NULL)
6677 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006678 close(fd_out);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006679 close(fd_in);
6680#ifdef HAVE_ACL
6681 mch_free_acl(acl);
6682#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006683 return -1;
6684 }
6685
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01006686 while ((n = read_eintr(fd_in, buffer, BUFSIZE)) > 0)
6687 if (write_eintr(fd_out, buffer, n) != n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006688 {
6689 errmsg = _("E208: Error writing to \"%s\"");
6690 break;
6691 }
6692
6693 vim_free(buffer);
6694 close(fd_in);
6695 if (close(fd_out) < 0)
6696 errmsg = _("E209: Error closing \"%s\"");
6697 if (n < 0)
6698 {
6699 errmsg = _("E210: Error reading \"%s\"");
6700 to = from;
6701 }
Bram Moolenaar7263a772007-05-10 17:35:54 +00006702#ifndef UNIX /* for Unix mch_open() already set the permission */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006703 mch_setperm(to, perm);
Bram Moolenaarc6039d82005-12-02 00:44:04 +00006704#endif
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006705#ifdef HAVE_ACL
6706 mch_set_acl(to, acl);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006707 mch_free_acl(acl);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006708#endif
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02006709#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaare8747442013-11-12 18:09:29 +01006710 mch_copy_sec(from, to);
Bram Moolenaar0671de32013-11-12 05:12:03 +01006711#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006712 if (errmsg != NULL)
6713 {
6714 EMSG2(errmsg, to);
6715 return -1;
6716 }
6717 mch_remove(from);
6718 return 0;
6719}
6720
6721static int already_warned = FALSE;
6722
6723/*
6724 * Check if any not hidden buffer has been changed.
6725 * Postpone the check if there are characters in the stuff buffer, a global
6726 * command is being executed, a mapping is being executed or an autocommand is
6727 * busy.
6728 * Returns TRUE if some message was written (screen should be redrawn and
6729 * cursor positioned).
6730 */
6731 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006732check_timestamps(
6733 int focus) /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006734{
6735 buf_T *buf;
6736 int didit = 0;
6737 int n;
6738
6739 /* Don't check timestamps while system() or another low-level function may
6740 * cause us to lose and gain focus. */
6741 if (no_check_timestamps > 0)
6742 return FALSE;
6743
6744 /* Avoid doing a check twice. The OK/Reload dialog can cause a focus
6745 * event and we would keep on checking if the file is steadily growing.
6746 * Do check again after typing something. */
6747 if (focus && did_check_timestamps)
6748 {
6749 need_check_timestamps = TRUE;
6750 return FALSE;
6751 }
6752
6753 if (!stuff_empty() || global_busy || !typebuf_typed()
6754#ifdef FEAT_AUTOCMD
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006755 || autocmd_busy || curbuf_lock > 0 || allbuf_lock > 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00006756#endif
6757 )
6758 need_check_timestamps = TRUE; /* check later */
6759 else
6760 {
6761 ++no_wait_return;
6762 did_check_timestamps = TRUE;
6763 already_warned = FALSE;
Bram Moolenaar29323592016-07-24 22:04:11 +02006764 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006765 {
6766 /* Only check buffers in a window. */
6767 if (buf->b_nwindows > 0)
6768 {
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006769 bufref_T bufref;
6770
6771 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006772 n = buf_check_timestamp(buf, focus);
6773 if (didit < n)
6774 didit = n;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006775 if (n > 0 && !bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006776 {
6777 /* Autocommands have removed the buffer, start at the
6778 * first one again. */
6779 buf = firstbuf;
6780 continue;
6781 }
6782 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006783 }
6784 --no_wait_return;
6785 need_check_timestamps = FALSE;
6786 if (need_wait_return && didit == 2)
6787 {
6788 /* make sure msg isn't overwritten */
6789 msg_puts((char_u *)"\n");
6790 out_flush();
6791 }
6792 }
6793 return didit;
6794}
6795
6796/*
6797 * Move all the lines from buffer "frombuf" to buffer "tobuf".
6798 * Return OK or FAIL. When FAIL "tobuf" is incomplete and/or "frombuf" is not
6799 * empty.
6800 */
6801 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006802move_lines(buf_T *frombuf, buf_T *tobuf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006803{
6804 buf_T *tbuf = curbuf;
6805 int retval = OK;
6806 linenr_T lnum;
6807 char_u *p;
6808
6809 /* Copy the lines in "frombuf" to "tobuf". */
6810 curbuf = tobuf;
6811 for (lnum = 1; lnum <= frombuf->b_ml.ml_line_count; ++lnum)
6812 {
6813 p = vim_strsave(ml_get_buf(frombuf, lnum, FALSE));
6814 if (p == NULL || ml_append(lnum - 1, p, 0, FALSE) == FAIL)
6815 {
6816 vim_free(p);
6817 retval = FAIL;
6818 break;
6819 }
6820 vim_free(p);
6821 }
6822
6823 /* Delete all the lines in "frombuf". */
6824 if (retval != FAIL)
6825 {
6826 curbuf = frombuf;
Bram Moolenaar9460b9d2007-01-09 14:37:01 +00006827 for (lnum = curbuf->b_ml.ml_line_count; lnum > 0; --lnum)
6828 if (ml_delete(lnum, FALSE) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006829 {
6830 /* Oops! We could try putting back the saved lines, but that
6831 * might fail again... */
6832 retval = FAIL;
6833 break;
6834 }
6835 }
6836
6837 curbuf = tbuf;
6838 return retval;
6839}
6840
6841/*
6842 * Check if buffer "buf" has been changed.
6843 * Also check if the file for a new buffer unexpectedly appeared.
6844 * return 1 if a changed buffer was found.
6845 * return 2 if a message has been displayed.
6846 * return 0 otherwise.
6847 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006848 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006849buf_check_timestamp(
6850 buf_T *buf,
6851 int focus UNUSED) /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006852{
Bram Moolenaar8767f522016-07-01 17:17:39 +02006853 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006854 int stat_res;
6855 int retval = 0;
6856 char_u *path;
6857 char_u *tbuf;
6858 char *mesg = NULL;
Bram Moolenaar44ecf652005-03-07 23:09:59 +00006859 char *mesg2 = "";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006860 int helpmesg = FALSE;
6861 int reload = FALSE;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006862 char *reason;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006863#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6864 int can_reload = FALSE;
6865#endif
Bram Moolenaar8767f522016-07-01 17:17:39 +02006866 off_T orig_size = buf->b_orig_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006867 int orig_mode = buf->b_orig_mode;
6868#ifdef FEAT_GUI
6869 int save_mouse_correct = need_mouse_correct;
6870#endif
6871#ifdef FEAT_AUTOCMD
6872 static int busy = FALSE;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006873 int n;
6874 char_u *s;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006875 bufref_T bufref;
6876
6877 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006878#endif
6879
6880 /* If there is no file name, the buffer is not loaded, 'buftype' is
6881 * set, we are in the middle of a save or being called recursively: ignore
6882 * this buffer. */
6883 if (buf->b_ffname == NULL
6884 || buf->b_ml.ml_mfp == NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00006885 || *buf->b_p_bt != NUL
Bram Moolenaar071d4272004-06-13 20:20:40 +00006886 || buf->b_saving
6887#ifdef FEAT_AUTOCMD
6888 || busy
6889#endif
Bram Moolenaar009b2592004-10-24 19:18:58 +00006890#ifdef FEAT_NETBEANS_INTG
6891 || isNetbeansBuffer(buf)
6892#endif
Bram Moolenaar8cad9302017-08-12 14:32:32 +02006893#ifdef FEAT_TERMINAL
6894 || buf->b_term != NULL
6895#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006896 )
6897 return 0;
6898
6899 if ( !(buf->b_flags & BF_NOTEDITED)
6900 && buf->b_mtime != 0
6901 && ((stat_res = mch_stat((char *)buf->b_ffname, &st)) < 0
6902 || time_differs((long)st.st_mtime, buf->b_mtime)
Bram Moolenaara7611f62014-05-02 15:46:14 +02006903 || st.st_size != buf->b_orig_size
Bram Moolenaar071d4272004-06-13 20:20:40 +00006904#ifdef HAVE_ST_MODE
6905 || (int)st.st_mode != buf->b_orig_mode
6906#else
6907 || mch_getperm(buf->b_ffname) != buf->b_orig_mode
6908#endif
6909 ))
6910 {
6911 retval = 1;
6912
Bram Moolenaar316059c2006-01-14 21:18:42 +00006913 /* set b_mtime to stop further warnings (e.g., when executing
6914 * FileChangedShell autocmd) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006915 if (stat_res < 0)
6916 {
6917 buf->b_mtime = 0;
6918 buf->b_orig_size = 0;
6919 buf->b_orig_mode = 0;
6920 }
6921 else
6922 buf_store_time(buf, &st, buf->b_ffname);
6923
6924 /* Don't do anything for a directory. Might contain the file
6925 * explorer. */
6926 if (mch_isdir(buf->b_fname))
6927 ;
6928
6929 /*
6930 * If 'autoread' is set, the buffer has no changes and the file still
6931 * exists, reload the buffer. Use the buffer-local option value if it
6932 * was set, the global option value otherwise.
6933 */
6934 else if ((buf->b_p_ar >= 0 ? buf->b_p_ar : p_ar)
6935 && !bufIsChanged(buf) && stat_res >= 0)
6936 reload = TRUE;
6937 else
6938 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006939 if (stat_res < 0)
6940 reason = "deleted";
6941 else if (bufIsChanged(buf))
6942 reason = "conflict";
6943 else if (orig_size != buf->b_orig_size || buf_contents_changed(buf))
6944 reason = "changed";
6945 else if (orig_mode != buf->b_orig_mode)
6946 reason = "mode";
6947 else
6948 reason = "time";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006949
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006950#ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006951 /*
6952 * Only give the warning if there are no FileChangedShell
6953 * autocommands.
6954 * Avoid being called recursively by setting "busy".
6955 */
6956 busy = TRUE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00006957# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006958 set_vim_var_string(VV_FCS_REASON, (char_u *)reason, -1);
6959 set_vim_var_string(VV_FCS_CHOICE, (char_u *)"", -1);
Bram Moolenaar1e015462005-09-25 22:16:38 +00006960# endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006961 ++allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006962 n = apply_autocmds(EVENT_FILECHANGEDSHELL,
6963 buf->b_fname, buf->b_fname, FALSE, buf);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006964 --allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006965 busy = FALSE;
6966 if (n)
6967 {
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006968 if (!bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006969 EMSG(_("E246: FileChangedShell autocommand deleted buffer"));
Bram Moolenaar1e015462005-09-25 22:16:38 +00006970# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006971 s = get_vim_var_str(VV_FCS_CHOICE);
6972 if (STRCMP(s, "reload") == 0 && *reason != 'd')
6973 reload = TRUE;
6974 else if (STRCMP(s, "ask") == 0)
6975 n = FALSE;
6976 else
Bram Moolenaar1e015462005-09-25 22:16:38 +00006977# endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006978 return 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006979 }
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006980 if (!n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006981#endif
6982 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006983 if (*reason == 'd')
6984 mesg = _("E211: File \"%s\" no longer available");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006985 else
6986 {
6987 helpmesg = TRUE;
6988#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6989 can_reload = TRUE;
6990#endif
6991 /*
6992 * Check if the file contents really changed to avoid
6993 * giving a warning when only the timestamp was set (e.g.,
6994 * checked out of CVS). Always warn when the buffer was
6995 * changed.
6996 */
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006997 if (reason[2] == 'n')
6998 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006999 mesg = _("W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007000 mesg2 = _("See \":help W12\" for more info.");
7001 }
7002 else if (reason[1] == 'h')
7003 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007004 mesg = _("W11: Warning: File \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007005 mesg2 = _("See \":help W11\" for more info.");
7006 }
7007 else if (*reason == 'm')
7008 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007009 mesg = _("W16: Warning: Mode of file \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007010 mesg2 = _("See \":help W16\" for more info.");
7011 }
Bram Moolenaar85388b52009-06-24 09:58:32 +00007012 else
7013 /* Only timestamp changed, store it to avoid a warning
7014 * in check_mtime() later. */
7015 buf->b_mtime_read = buf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007016 }
7017 }
7018 }
7019
7020 }
7021 else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W)
7022 && vim_fexists(buf->b_ffname))
7023 {
7024 retval = 1;
7025 mesg = _("W13: Warning: File \"%s\" has been created after editing started");
7026 buf->b_flags |= BF_NEW_W;
7027#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
7028 can_reload = TRUE;
7029#endif
7030 }
7031
7032 if (mesg != NULL)
7033 {
7034 path = home_replace_save(buf, buf->b_fname);
7035 if (path != NULL)
7036 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007037 if (!helpmesg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007038 mesg2 = "";
7039 tbuf = alloc((unsigned)(STRLEN(path) + STRLEN(mesg)
7040 + STRLEN(mesg2) + 2));
7041 sprintf((char *)tbuf, mesg, path);
Bram Moolenaar496c5262009-03-18 14:42:00 +00007042#ifdef FEAT_EVAL
7043 /* Set warningmsg here, before the unimportant and output-specific
7044 * mesg2 has been appended. */
7045 set_vim_var_string(VV_WARNINGMSG, tbuf, -1);
7046#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007047#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
7048 if (can_reload)
7049 {
7050 if (*mesg2 != NUL)
7051 {
7052 STRCAT(tbuf, "\n");
7053 STRCAT(tbuf, mesg2);
7054 }
7055 if (do_dialog(VIM_WARNING, (char_u *)_("Warning"), tbuf,
Bram Moolenaard2c340a2011-01-17 20:08:11 +01007056 (char_u *)_("&OK\n&Load File"), 1, NULL, TRUE) == 2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007057 reload = TRUE;
7058 }
7059 else
7060#endif
7061 if (State > NORMAL_BUSY || (State & CMDLINE) || already_warned)
7062 {
7063 if (*mesg2 != NUL)
7064 {
7065 STRCAT(tbuf, "; ");
7066 STRCAT(tbuf, mesg2);
7067 }
7068 EMSG(tbuf);
7069 retval = 2;
7070 }
7071 else
7072 {
Bram Moolenaared203462004-06-16 11:19:22 +00007073# ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00007074 if (!autocmd_busy)
Bram Moolenaared203462004-06-16 11:19:22 +00007075# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007076 {
7077 msg_start();
Bram Moolenaar8820b482017-03-16 17:23:31 +01007078 msg_puts_attr(tbuf, HL_ATTR(HLF_E) + MSG_HIST);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007079 if (*mesg2 != NUL)
7080 msg_puts_attr((char_u *)mesg2,
Bram Moolenaar8820b482017-03-16 17:23:31 +01007081 HL_ATTR(HLF_W) + MSG_HIST);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007082 msg_clr_eos();
7083 (void)msg_end();
7084 if (emsg_silent == 0)
7085 {
7086 out_flush();
Bram Moolenaared203462004-06-16 11:19:22 +00007087# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00007088 if (!focus)
Bram Moolenaared203462004-06-16 11:19:22 +00007089# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007090 /* give the user some time to think about it */
7091 ui_delay(1000L, TRUE);
7092
7093 /* don't redraw and erase the message */
7094 redraw_cmdline = FALSE;
7095 }
7096 }
7097 already_warned = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007098 }
7099
7100 vim_free(path);
7101 vim_free(tbuf);
7102 }
7103 }
7104
7105 if (reload)
Bram Moolenaar465748e2012-08-29 18:50:54 +02007106 {
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007107 /* Reload the buffer. */
Bram Moolenaar316059c2006-01-14 21:18:42 +00007108 buf_reload(buf, orig_mode);
Bram Moolenaar465748e2012-08-29 18:50:54 +02007109#ifdef FEAT_PERSISTENT_UNDO
7110 if (buf->b_p_udf && buf->b_ffname != NULL)
7111 {
7112 char_u hash[UNDO_HASH_SIZE];
7113 buf_T *save_curbuf = curbuf;
7114
7115 /* Any existing undo file is unusable, write it now. */
7116 curbuf = buf;
7117 u_compute_hash(hash);
7118 u_write_undo(NULL, FALSE, buf, hash);
7119 curbuf = save_curbuf;
7120 }
7121#endif
7122 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007123
Bram Moolenaar56718732006-03-15 22:53:57 +00007124#ifdef FEAT_AUTOCMD
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00007125 /* Trigger FileChangedShell when the file was changed in any way. */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007126 if (bufref_valid(&bufref) && retval != 0)
Bram Moolenaar56718732006-03-15 22:53:57 +00007127 (void)apply_autocmds(EVENT_FILECHANGEDSHELLPOST,
7128 buf->b_fname, buf->b_fname, FALSE, buf);
7129#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007130#ifdef FEAT_GUI
7131 /* restore this in case an autocommand has set it; it would break
7132 * 'mousefocus' */
7133 need_mouse_correct = save_mouse_correct;
7134#endif
7135
7136 return retval;
7137}
7138
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007139/*
7140 * Reload a buffer that is already loaded.
7141 * Used when the file was changed outside of Vim.
Bram Moolenaar316059c2006-01-14 21:18:42 +00007142 * "orig_mode" is buf->b_orig_mode before the need for reloading was detected.
7143 * buf->b_orig_mode may have been reset already.
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007144 */
7145 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007146buf_reload(buf_T *buf, int orig_mode)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007147{
7148 exarg_T ea;
7149 pos_T old_cursor;
7150 linenr_T old_topline;
7151 int old_ro = buf->b_p_ro;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007152 buf_T *savebuf;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007153 bufref_T bufref;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007154 int saved = OK;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007155 aco_save_T aco;
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007156 int flags = READ_NEW;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007157
7158 /* set curwin/curbuf for "buf" and save some things */
7159 aucmd_prepbuf(&aco, buf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007160
7161 /* We only want to read the text from the file, not reset the syntax
7162 * highlighting, clear marks, diff status, etc. Force the fileformat
7163 * and encoding to be the same. */
7164 if (prep_exarg(&ea, buf) == OK)
7165 {
7166 old_cursor = curwin->w_cursor;
7167 old_topline = curwin->w_topline;
7168
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007169 if (p_ur < 0 || curbuf->b_ml.ml_line_count <= p_ur)
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007170 {
7171 /* Save all the text, so that the reload can be undone.
7172 * Sync first so that this is a separate undo-able action. */
7173 u_sync(FALSE);
7174 saved = u_savecommon(0, curbuf->b_ml.ml_line_count + 1, 0, TRUE);
7175 flags |= READ_KEEP_UNDO;
7176 }
7177
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007178 /*
7179 * To behave like when a new file is edited (matters for
7180 * BufReadPost autocommands) we first need to delete the current
7181 * buffer contents. But if reading the file fails we should keep
7182 * the old contents. Can't use memory only, the file might be
7183 * too big. Use a hidden buffer to move the buffer contents to.
7184 */
Bram Moolenaarb5aedf32017-03-12 18:23:53 +01007185 if (BUFEMPTY() || saved == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007186 savebuf = NULL;
7187 else
7188 {
7189 /* Allocate a buffer without putting it in the buffer list. */
7190 savebuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007191 set_bufref(&bufref, savebuf);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007192 if (savebuf != NULL && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007193 {
7194 /* Open the memline. */
7195 curbuf = savebuf;
7196 curwin->w_buffer = savebuf;
Bram Moolenaar4770d092006-01-12 23:22:24 +00007197 saved = ml_open(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007198 curbuf = buf;
7199 curwin->w_buffer = buf;
7200 }
Bram Moolenaar8424a622006-04-19 21:23:36 +00007201 if (savebuf == NULL || saved == FAIL || buf != curbuf
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007202 || move_lines(buf, savebuf) == FAIL)
7203 {
7204 EMSG2(_("E462: Could not prepare for reloading \"%s\""),
7205 buf->b_fname);
7206 saved = FAIL;
7207 }
7208 }
7209
7210 if (saved == OK)
7211 {
7212 curbuf->b_flags |= BF_CHECK_RO; /* check for RO again */
7213#ifdef FEAT_AUTOCMD
7214 keep_filetype = TRUE; /* don't detect 'filetype' */
7215#endif
7216 if (readfile(buf->b_ffname, buf->b_fname, (linenr_T)0,
7217 (linenr_T)0,
Bram Moolenaare13b9af2017-01-13 22:01:02 +01007218 (linenr_T)MAXLNUM, &ea, flags) != OK)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007219 {
7220#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
7221 if (!aborting())
7222#endif
7223 EMSG2(_("E321: Could not reload \"%s\""), buf->b_fname);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007224 if (savebuf != NULL && bufref_valid(&bufref) && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007225 {
7226 /* Put the text back from the save buffer. First
7227 * delete any lines that readfile() added. */
Bram Moolenaarb5aedf32017-03-12 18:23:53 +01007228 while (!BUFEMPTY())
Bram Moolenaar8424a622006-04-19 21:23:36 +00007229 if (ml_delete(buf->b_ml.ml_line_count, FALSE) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007230 break;
7231 (void)move_lines(savebuf, buf);
7232 }
7233 }
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007234 else if (buf == curbuf) /* "buf" still valid */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007235 {
7236 /* Mark the buffer as unmodified and free undo info. */
7237 unchanged(buf, TRUE);
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007238 if ((flags & READ_KEEP_UNDO) == 0)
7239 {
7240 u_blockfree(buf);
7241 u_clearall(buf);
7242 }
7243 else
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007244 {
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007245 /* Mark all undo states as changed. */
7246 u_unchanged(curbuf);
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007247 }
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007248 }
7249 }
7250 vim_free(ea.cmd);
7251
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007252 if (savebuf != NULL && bufref_valid(&bufref))
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007253 wipe_buffer(savebuf, FALSE);
7254
7255#ifdef FEAT_DIFF
7256 /* Invalidate diff info if necessary. */
Bram Moolenaar8424a622006-04-19 21:23:36 +00007257 diff_invalidate(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007258#endif
7259
7260 /* Restore the topline and cursor position and check it (lines may
7261 * have been removed). */
7262 if (old_topline > curbuf->b_ml.ml_line_count)
7263 curwin->w_topline = curbuf->b_ml.ml_line_count;
7264 else
7265 curwin->w_topline = old_topline;
7266 curwin->w_cursor = old_cursor;
7267 check_cursor();
7268 update_topline();
7269#ifdef FEAT_AUTOCMD
7270 keep_filetype = FALSE;
7271#endif
7272#ifdef FEAT_FOLDING
7273 {
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007274 win_T *wp;
7275 tabpage_T *tp;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007276
7277 /* Update folds unless they are defined manually. */
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007278 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007279 if (wp->w_buffer == curwin->w_buffer
7280 && !foldmethodIsManual(wp))
7281 foldUpdateAll(wp);
7282 }
7283#endif
7284 /* If the mode didn't change and 'readonly' was set, keep the old
7285 * value; the user probably used the ":view" command. But don't
7286 * reset it, might have had a read error. */
7287 if (orig_mode == curbuf->b_orig_mode)
7288 curbuf->b_p_ro |= old_ro;
Bram Moolenaar52f85b72013-01-30 14:13:56 +01007289
7290 /* Modelines must override settings done by autocommands. */
7291 do_modelines(0);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007292 }
7293
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007294 /* restore curwin/curbuf and a few other things */
7295 aucmd_restbuf(&aco);
7296 /* Careful: autocommands may have made "buf" invalid! */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007297}
7298
Bram Moolenaar071d4272004-06-13 20:20:40 +00007299 void
Bram Moolenaar8767f522016-07-01 17:17:39 +02007300buf_store_time(buf_T *buf, stat_T *st, char_u *fname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007301{
7302 buf->b_mtime = (long)st->st_mtime;
Bram Moolenaar914703b2010-05-31 21:59:46 +02007303 buf->b_orig_size = st->st_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007304#ifdef HAVE_ST_MODE
7305 buf->b_orig_mode = (int)st->st_mode;
7306#else
7307 buf->b_orig_mode = mch_getperm(fname);
7308#endif
7309}
7310
7311/*
7312 * Adjust the line with missing eol, used for the next write.
7313 * Used for do_filter(), when the input lines for the filter are deleted.
7314 */
7315 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007316write_lnum_adjust(linenr_T offset)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007317{
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01007318 if (curbuf->b_no_eol_lnum != 0) /* only if there is a missing eol */
7319 curbuf->b_no_eol_lnum += offset;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007320}
7321
Bram Moolenaarda440d22016-01-16 21:27:23 +01007322#if defined(TEMPDIRNAMES) || defined(FEAT_EVAL) || defined(PROTO)
7323/*
7324 * Delete "name" and everything in it, recursively.
7325 * return 0 for succes, -1 if some file was not deleted.
7326 */
7327 int
7328delete_recursive(char_u *name)
7329{
7330 int result = 0;
7331 char_u **files;
7332 int file_count;
7333 int i;
7334 char_u *exp;
7335
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007336 /* A symbolic link to a directory itself is deleted, not the directory it
7337 * points to. */
7338 if (
Bram Moolenaar203258c2016-01-17 22:15:16 +01007339# if defined(UNIX) || defined(WIN32)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007340 mch_isrealdir(name)
Bram Moolenaar203258c2016-01-17 22:15:16 +01007341# else
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007342 mch_isdir(name)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007343# endif
7344 )
Bram Moolenaarda440d22016-01-16 21:27:23 +01007345 {
7346 vim_snprintf((char *)NameBuff, MAXPATHL, "%s/*", name);
7347 exp = vim_strsave(NameBuff);
7348 if (exp == NULL)
7349 return -1;
7350 if (gen_expand_wildcards(1, &exp, &file_count, &files,
Bram Moolenaar336bd622016-01-17 18:23:58 +01007351 EW_DIR|EW_FILE|EW_SILENT|EW_ALLLINKS|EW_DODOT|EW_EMPTYOK) == OK)
Bram Moolenaarda440d22016-01-16 21:27:23 +01007352 {
7353 for (i = 0; i < file_count; ++i)
7354 if (delete_recursive(files[i]) != 0)
7355 result = -1;
7356 FreeWild(file_count, files);
7357 }
7358 else
7359 result = -1;
7360 vim_free(exp);
7361 (void)mch_rmdir(name);
7362 }
7363 else
7364 result = mch_remove(name) == 0 ? 0 : -1;
7365
7366 return result;
7367}
7368#endif
7369
Bram Moolenaar071d4272004-06-13 20:20:40 +00007370#if defined(TEMPDIRNAMES) || defined(PROTO)
7371static long temp_count = 0; /* Temp filename counter. */
7372
7373/*
7374 * Delete the temp directory and all files it contains.
7375 */
7376 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007377vim_deltempdir(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007378{
Bram Moolenaar071d4272004-06-13 20:20:40 +00007379 if (vim_tempdir != NULL)
7380 {
Bram Moolenaarda440d22016-01-16 21:27:23 +01007381 /* remove the trailing path separator */
7382 gettail(vim_tempdir)[-1] = NUL;
7383 delete_recursive(vim_tempdir);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007384 vim_free(vim_tempdir);
7385 vim_tempdir = NULL;
7386 }
7387}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007388
7389/*
Bram Moolenaareaf03392009-11-17 11:08:52 +00007390 * Directory "tempdir" was created. Expand this name to a full path and put
7391 * it in "vim_tempdir". This avoids that using ":cd" would confuse us.
7392 * "tempdir" must be no longer than MAXPATHL.
7393 */
7394 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007395vim_settempdir(char_u *tempdir)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007396{
7397 char_u *buf;
7398
7399 buf = alloc((unsigned)MAXPATHL + 2);
7400 if (buf != NULL)
7401 {
7402 if (vim_FullName(tempdir, buf, MAXPATHL, FALSE) == FAIL)
7403 STRCPY(buf, tempdir);
Bram Moolenaara06ecab2016-07-16 14:47:36 +02007404 add_pathsep(buf);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007405 vim_tempdir = vim_strsave(buf);
7406 vim_free(buf);
7407 }
7408}
Bram Moolenaar4592dee2009-11-18 19:11:58 +00007409#endif
Bram Moolenaareaf03392009-11-17 11:08:52 +00007410
7411/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007412 * vim_tempname(): Return a unique name that can be used for a temp file.
7413 *
Bram Moolenaar76ae22f2016-06-13 20:00:29 +02007414 * The temp file is NOT guaranteed to be created. If "keep" is FALSE it is
7415 * guaranteed to NOT be created.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007416 *
7417 * The returned pointer is to allocated memory.
7418 * The returned pointer is NULL if no valid name was found.
7419 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007420 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007421vim_tempname(
7422 int extra_char UNUSED, /* char to use in the name instead of '?' */
7423 int keep UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007424{
7425#ifdef USE_TMPNAM
7426 char_u itmp[L_tmpnam]; /* use tmpnam() */
7427#else
7428 char_u itmp[TEMPNAMELEN];
7429#endif
7430
7431#ifdef TEMPDIRNAMES
7432 static char *(tempdirs[]) = {TEMPDIRNAMES};
7433 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007434# ifndef EEXIST
Bram Moolenaar8767f522016-07-01 17:17:39 +02007435 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007436# endif
7437
7438 /*
7439 * This will create a directory for private use by this instance of Vim.
7440 * This is done once, and the same directory is used for all temp files.
7441 * This method avoids security problems because of symlink attacks et al.
7442 * It's also a bit faster, because we only need to check for an existing
7443 * file when creating the directory and not for each temp file.
7444 */
7445 if (vim_tempdir == NULL)
7446 {
7447 /*
7448 * Try the entries in TEMPDIRNAMES to create the temp directory.
7449 */
Bram Moolenaar78a15312009-05-15 19:33:18 +00007450 for (i = 0; i < (int)(sizeof(tempdirs) / sizeof(char *)); ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007451 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007452# ifndef HAVE_MKDTEMP
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007453 size_t itmplen;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007454 long nr;
7455 long off;
7456# endif
7457
Bram Moolenaare1a61992015-12-03 21:02:27 +01007458 /* Expand $TMP, leave room for "/v1100000/999999999".
7459 * Skip the directory check if the expansion fails. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007460 expand_env((char_u *)tempdirs[i], itmp, TEMPNAMELEN - 20);
Bram Moolenaare1a61992015-12-03 21:02:27 +01007461 if (itmp[0] != '$' && mch_isdir(itmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007462 {
Bram Moolenaare1a61992015-12-03 21:02:27 +01007463 /* directory exists */
Bram Moolenaara06ecab2016-07-16 14:47:36 +02007464 add_pathsep(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007465
Bram Moolenaareaf03392009-11-17 11:08:52 +00007466# ifdef HAVE_MKDTEMP
Bram Moolenaar35d88f42016-06-04 14:52:00 +02007467 {
7468# if defined(UNIX) || defined(VMS)
7469 /* Make sure the umask doesn't remove the executable bit.
7470 * "repl" has been reported to use "177". */
7471 mode_t umask_save = umask(077);
7472# endif
7473 /* Leave room for filename */
7474 STRCAT(itmp, "vXXXXXX");
7475 if (mkdtemp((char *)itmp) != NULL)
7476 vim_settempdir(itmp);
7477# if defined(UNIX) || defined(VMS)
7478 (void)umask(umask_save);
7479# endif
7480 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007481# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007482 /* Get an arbitrary number of up to 6 digits. When it's
7483 * unlikely that it already exists it will be faster,
7484 * otherwise it doesn't matter. The use of mkdir() avoids any
7485 * security problems because of the predictable number. */
7486 nr = (mch_get_pid() + (long)time(NULL)) % 1000000L;
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007487 itmplen = STRLEN(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007488
7489 /* Try up to 10000 different values until we find a name that
7490 * doesn't exist. */
7491 for (off = 0; off < 10000L; ++off)
7492 {
7493 int r;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007494# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007495 mode_t umask_save;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007496# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007497
Bram Moolenaareaf03392009-11-17 11:08:52 +00007498 sprintf((char *)itmp + itmplen, "v%ld", nr + off);
7499# ifndef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007500 /* If mkdir() does not set errno to EEXIST, check for
7501 * existing file here. There is a race condition then,
7502 * although it's fail-safe. */
7503 if (mch_stat((char *)itmp, &st) >= 0)
7504 continue;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007505# endif
7506# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007507 /* Make sure the umask doesn't remove the executable bit.
7508 * "repl" has been reported to use "177". */
7509 umask_save = umask(077);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007510# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007511 r = vim_mkdir(itmp, 0700);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007512# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007513 (void)umask(umask_save);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007514# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007515 if (r == 0)
7516 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007517 vim_settempdir(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007518 break;
7519 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007520# ifdef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007521 /* If the mkdir() didn't fail because the file/dir exists,
7522 * we probably can't create any dir here, try another
7523 * place. */
7524 if (errno != EEXIST)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007525# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007526 break;
7527 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007528# endif /* HAVE_MKDTEMP */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007529 if (vim_tempdir != NULL)
7530 break;
7531 }
7532 }
7533 }
7534
7535 if (vim_tempdir != NULL)
7536 {
7537 /* There is no need to check if the file exists, because we own the
7538 * directory and nobody else creates a file in it. */
7539 sprintf((char *)itmp, "%s%ld", vim_tempdir, temp_count++);
7540 return vim_strsave(itmp);
7541 }
7542
7543 return NULL;
7544
7545#else /* TEMPDIRNAMES */
7546
7547# ifdef WIN3264
7548 char szTempFile[_MAX_PATH + 1];
7549 char buf4[4];
7550 char_u *retval;
7551 char_u *p;
7552
7553 STRCPY(itmp, "");
7554 if (GetTempPath(_MAX_PATH, szTempFile) == 0)
Bram Moolenaarb1891912011-02-09 14:47:03 +01007555 {
7556 szTempFile[0] = '.'; /* GetTempPath() failed, use current dir */
7557 szTempFile[1] = NUL;
7558 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007559 strcpy(buf4, "VIM");
7560 buf4[2] = extra_char; /* make it "VIa", "VIb", etc. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007561 if (GetTempFileName(szTempFile, buf4, 0, (LPSTR)itmp) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007562 return NULL;
Bram Moolenaare5c421c2015-03-31 13:33:08 +02007563 if (!keep)
7564 /* GetTempFileName() will create the file, we don't want that */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007565 (void)DeleteFile((LPSTR)itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007566
7567 /* Backslashes in a temp file name cause problems when filtering with
7568 * "sh". NOTE: This also checks 'shellcmdflag' to help those people who
7569 * didn't set 'shellslash'. */
7570 retval = vim_strsave(itmp);
7571 if (*p_shcf == '-' || p_ssl)
7572 for (p = retval; *p; ++p)
7573 if (*p == '\\')
7574 *p = '/';
7575 return retval;
7576
7577# else /* WIN3264 */
7578
7579# ifdef USE_TMPNAM
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007580 char_u *p;
7581
Bram Moolenaar071d4272004-06-13 20:20:40 +00007582 /* tmpnam() will make its own name */
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007583 p = tmpnam((char *)itmp);
7584 if (p == NULL || *p == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007585 return NULL;
7586# else
7587 char_u *p;
7588
7589# ifdef VMS_TEMPNAM
7590 /* mktemp() is not working on VMS. It seems to be
7591 * a do-nothing function. Therefore we use tempnam().
7592 */
7593 sprintf((char *)itmp, "VIM%c", extra_char);
7594 p = (char_u *)tempnam("tmp:", (char *)itmp);
7595 if (p != NULL)
7596 {
Bram Moolenaar206f0112014-03-12 16:51:55 +01007597 /* VMS will use '.LIS' if we don't explicitly specify an extension,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007598 * and VIM will then be unable to find the file later */
7599 STRCPY(itmp, p);
7600 STRCAT(itmp, ".txt");
7601 free(p);
7602 }
7603 else
7604 return NULL;
7605# else
7606 STRCPY(itmp, TEMPNAME);
7607 if ((p = vim_strchr(itmp, '?')) != NULL)
7608 *p = extra_char;
7609 if (mktemp((char *)itmp) == NULL)
7610 return NULL;
7611# endif
7612# endif
7613
7614 return vim_strsave(itmp);
7615# endif /* WIN3264 */
7616#endif /* TEMPDIRNAMES */
7617}
7618
7619#if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
7620/*
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02007621 * Convert all backslashes in fname to forward slashes in-place, unless when
7622 * it looks like a URL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007623 */
7624 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007625forward_slash(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007626{
7627 char_u *p;
7628
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02007629 if (path_with_url(fname))
7630 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007631 for (p = fname; *p != NUL; ++p)
7632# ifdef FEAT_MBYTE
7633 /* The Big5 encoding can have '\' in the trail byte. */
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00007634 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007635 ++p;
7636 else
7637# endif
7638 if (*p == '\\')
7639 *p = '/';
7640}
7641#endif
7642
7643
7644/*
7645 * Code for automatic commands.
7646 *
7647 * Only included when "FEAT_AUTOCMD" has been defined.
7648 */
7649
7650#if defined(FEAT_AUTOCMD) || defined(PROTO)
7651
7652/*
7653 * The autocommands are stored in a list for each event.
7654 * Autocommands for the same pattern, that are consecutive, are joined
7655 * together, to avoid having to match the pattern too often.
7656 * The result is an array of Autopat lists, which point to AutoCmd lists:
7657 *
7658 * first_autopat[0] --> Autopat.next --> Autopat.next --> NULL
7659 * Autopat.cmds Autopat.cmds
7660 * | |
7661 * V V
7662 * AutoCmd.next AutoCmd.next
7663 * | |
7664 * V V
7665 * AutoCmd.next NULL
7666 * |
7667 * V
7668 * NULL
7669 *
7670 * first_autopat[1] --> Autopat.next --> NULL
7671 * Autopat.cmds
7672 * |
7673 * V
7674 * AutoCmd.next
7675 * |
7676 * V
7677 * NULL
7678 * etc.
7679 *
7680 * The order of AutoCmds is important, this is the order in which they were
7681 * defined and will have to be executed.
7682 */
7683typedef struct AutoCmd
7684{
7685 char_u *cmd; /* The command to be executed (NULL
7686 when command has been removed) */
7687 char nested; /* If autocommands nest here */
7688 char last; /* last command in list */
7689#ifdef FEAT_EVAL
7690 scid_T scriptID; /* script ID where defined */
7691#endif
7692 struct AutoCmd *next; /* Next AutoCmd in list */
7693} AutoCmd;
7694
7695typedef struct AutoPat
7696{
Bram Moolenaar071d4272004-06-13 20:20:40 +00007697 char_u *pat; /* pattern as typed (NULL when pattern
7698 has been removed) */
Bram Moolenaar748bf032005-02-02 23:04:36 +00007699 regprog_T *reg_prog; /* compiled regprog for pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007700 AutoCmd *cmds; /* list of commands to do */
7701 struct AutoPat *next; /* next AutoPat in AutoPat list */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007702 int group; /* group ID */
7703 int patlen; /* strlen() of pat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007704 int buflocal_nr; /* !=0 for buffer-local AutoPat */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007705 char allow_dirs; /* Pattern may match whole path */
7706 char last; /* last pattern for apply_autocmds() */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007707} AutoPat;
7708
7709static struct event_name
7710{
7711 char *name; /* event name */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007712 event_T event; /* event number */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007713} event_names[] =
7714{
7715 {"BufAdd", EVENT_BUFADD},
7716 {"BufCreate", EVENT_BUFADD},
7717 {"BufDelete", EVENT_BUFDELETE},
7718 {"BufEnter", EVENT_BUFENTER},
7719 {"BufFilePost", EVENT_BUFFILEPOST},
7720 {"BufFilePre", EVENT_BUFFILEPRE},
7721 {"BufHidden", EVENT_BUFHIDDEN},
7722 {"BufLeave", EVENT_BUFLEAVE},
7723 {"BufNew", EVENT_BUFNEW},
7724 {"BufNewFile", EVENT_BUFNEWFILE},
7725 {"BufRead", EVENT_BUFREADPOST},
7726 {"BufReadCmd", EVENT_BUFREADCMD},
7727 {"BufReadPost", EVENT_BUFREADPOST},
7728 {"BufReadPre", EVENT_BUFREADPRE},
7729 {"BufUnload", EVENT_BUFUNLOAD},
7730 {"BufWinEnter", EVENT_BUFWINENTER},
7731 {"BufWinLeave", EVENT_BUFWINLEAVE},
7732 {"BufWipeout", EVENT_BUFWIPEOUT},
7733 {"BufWrite", EVENT_BUFWRITEPRE},
7734 {"BufWritePost", EVENT_BUFWRITEPOST},
7735 {"BufWritePre", EVENT_BUFWRITEPRE},
7736 {"BufWriteCmd", EVENT_BUFWRITECMD},
7737 {"CmdwinEnter", EVENT_CMDWINENTER},
7738 {"CmdwinLeave", EVENT_CMDWINLEAVE},
Bram Moolenaard5005162014-08-22 23:05:54 +02007739 {"CmdUndefined", EVENT_CMDUNDEFINED},
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007740 {"ColorScheme", EVENT_COLORSCHEME},
Bram Moolenaarcfa3cae2012-07-10 17:14:56 +02007741 {"CompleteDone", EVENT_COMPLETEDONE},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007742 {"CursorHold", EVENT_CURSORHOLD},
7743 {"CursorHoldI", EVENT_CURSORHOLDI},
7744 {"CursorMoved", EVENT_CURSORMOVED},
7745 {"CursorMovedI", EVENT_CURSORMOVEDI},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007746 {"EncodingChanged", EVENT_ENCODINGCHANGED},
7747 {"FileEncoding", EVENT_ENCODINGCHANGED},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007748 {"FileAppendPost", EVENT_FILEAPPENDPOST},
7749 {"FileAppendPre", EVENT_FILEAPPENDPRE},
7750 {"FileAppendCmd", EVENT_FILEAPPENDCMD},
7751 {"FileChangedShell",EVENT_FILECHANGEDSHELL},
Bram Moolenaar56718732006-03-15 22:53:57 +00007752 {"FileChangedShellPost",EVENT_FILECHANGEDSHELLPOST},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007753 {"FileChangedRO", EVENT_FILECHANGEDRO},
7754 {"FileReadPost", EVENT_FILEREADPOST},
7755 {"FileReadPre", EVENT_FILEREADPRE},
7756 {"FileReadCmd", EVENT_FILEREADCMD},
7757 {"FileType", EVENT_FILETYPE},
7758 {"FileWritePost", EVENT_FILEWRITEPOST},
7759 {"FileWritePre", EVENT_FILEWRITEPRE},
7760 {"FileWriteCmd", EVENT_FILEWRITECMD},
7761 {"FilterReadPost", EVENT_FILTERREADPOST},
7762 {"FilterReadPre", EVENT_FILTERREADPRE},
7763 {"FilterWritePost", EVENT_FILTERWRITEPOST},
7764 {"FilterWritePre", EVENT_FILTERWRITEPRE},
7765 {"FocusGained", EVENT_FOCUSGAINED},
7766 {"FocusLost", EVENT_FOCUSLOST},
7767 {"FuncUndefined", EVENT_FUNCUNDEFINED},
7768 {"GUIEnter", EVENT_GUIENTER},
Bram Moolenaar265e5072006-08-29 16:13:22 +00007769 {"GUIFailed", EVENT_GUIFAILED},
Bram Moolenaar843ee412004-06-30 16:16:41 +00007770 {"InsertChange", EVENT_INSERTCHANGE},
7771 {"InsertEnter", EVENT_INSERTENTER},
7772 {"InsertLeave", EVENT_INSERTLEAVE},
Bram Moolenaare659c952011-05-19 17:25:41 +02007773 {"InsertCharPre", EVENT_INSERTCHARPRE},
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00007774 {"MenuPopup", EVENT_MENUPOPUP},
Bram Moolenaar53744302015-07-17 17:38:22 +02007775 {"OptionSet", EVENT_OPTIONSET},
Bram Moolenaar7c626922005-02-07 22:01:03 +00007776 {"QuickFixCmdPost", EVENT_QUICKFIXCMDPOST},
7777 {"QuickFixCmdPre", EVENT_QUICKFIXCMDPRE},
Bram Moolenaar3b53dfb2012-06-06 18:03:07 +02007778 {"QuitPre", EVENT_QUITPRE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007779 {"RemoteReply", EVENT_REMOTEREPLY},
Bram Moolenaar9372a112005-12-06 19:59:18 +00007780 {"SessionLoadPost", EVENT_SESSIONLOADPOST},
Bram Moolenaar5c4bab02006-03-10 21:37:46 +00007781 {"ShellCmdPost", EVENT_SHELLCMDPOST},
7782 {"ShellFilterPost", EVENT_SHELLFILTERPOST},
Bram Moolenaara2031822006-03-07 22:29:51 +00007783 {"SourcePre", EVENT_SOURCEPRE},
Bram Moolenaar8dd1aa52007-01-16 20:33:19 +00007784 {"SourceCmd", EVENT_SOURCECMD},
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00007785 {"SpellFileMissing",EVENT_SPELLFILEMISSING},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007786 {"StdinReadPost", EVENT_STDINREADPOST},
7787 {"StdinReadPre", EVENT_STDINREADPRE},
Bram Moolenaarb815dac2005-12-07 20:59:24 +00007788 {"SwapExists", EVENT_SWAPEXISTS},
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00007789 {"Syntax", EVENT_SYNTAX},
Bram Moolenaarc917da42016-07-19 22:31:36 +02007790 {"TabNew", EVENT_TABNEW},
Bram Moolenaar12c11d52016-07-19 23:13:03 +02007791 {"TabClosed", EVENT_TABCLOSED},
Bram Moolenaar70836c82006-02-20 21:28:49 +00007792 {"TabEnter", EVENT_TABENTER},
7793 {"TabLeave", EVENT_TABLEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007794 {"TermChanged", EVENT_TERMCHANGED},
7795 {"TermResponse", EVENT_TERMRESPONSE},
Bram Moolenaar186628f2013-03-19 13:33:23 +01007796 {"TextChanged", EVENT_TEXTCHANGED},
7797 {"TextChangedI", EVENT_TEXTCHANGEDI},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007798 {"User", EVENT_USER},
7799 {"VimEnter", EVENT_VIMENTER},
7800 {"VimLeave", EVENT_VIMLEAVE},
7801 {"VimLeavePre", EVENT_VIMLEAVEPRE},
Bram Moolenaarc917da42016-07-19 22:31:36 +02007802 {"WinNew", EVENT_WINNEW},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007803 {"WinEnter", EVENT_WINENTER},
7804 {"WinLeave", EVENT_WINLEAVE},
Bram Moolenaar56718732006-03-15 22:53:57 +00007805 {"VimResized", EVENT_VIMRESIZED},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007806 {NULL, (event_T)0}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007807};
7808
7809static AutoPat *first_autopat[NUM_EVENTS] =
7810{
7811 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7812 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7813 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7814 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00007815 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaar53744302015-07-17 17:38:22 +02007816 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007817};
7818
7819/*
7820 * struct used to keep status while executing autocommands for an event.
7821 */
7822typedef struct AutoPatCmd
7823{
7824 AutoPat *curpat; /* next AutoPat to examine */
7825 AutoCmd *nextcmd; /* next AutoCmd to execute */
7826 int group; /* group being used */
7827 char_u *fname; /* fname to match with */
7828 char_u *sfname; /* sfname to match with */
7829 char_u *tail; /* tail of fname */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007830 event_T event; /* current event */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007831 int arg_bufnr; /* initially equal to <abuf>, set to zero when
7832 buf is deleted */
7833 struct AutoPatCmd *next; /* chain of active apc-s for auto-invalidation*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00007834} AutoPatCmd;
7835
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007836static AutoPatCmd *active_apc_list = NULL; /* stack of active autocommands */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007837
Bram Moolenaar071d4272004-06-13 20:20:40 +00007838/*
7839 * augroups stores a list of autocmd group names.
7840 */
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007841static garray_T augroups = {0, 0, sizeof(char_u *), 10, NULL};
Bram Moolenaar071d4272004-06-13 20:20:40 +00007842#define AUGROUP_NAME(i) (((char_u **)augroups.ga_data)[i])
Bram Moolenaarb62cc362016-09-03 16:43:53 +02007843/* use get_deleted_augroup() to get this */
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02007844static char_u *deleted_augroup = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007845
7846/*
7847 * The ID of the current group. Group 0 is the default one.
7848 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007849static int current_augroup = AUGROUP_DEFAULT;
7850
7851static int au_need_clean = FALSE; /* need to delete marked patterns */
7852
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007853static void show_autocmd(AutoPat *ap, event_T event);
7854static void au_remove_pat(AutoPat *ap);
7855static void au_remove_cmds(AutoPat *ap);
7856static void au_cleanup(void);
7857static int au_new_group(char_u *name);
7858static void au_del_group(char_u *name);
7859static event_T event_name2nr(char_u *start, char_u **end);
7860static char_u *event_nr2name(event_T event);
7861static char_u *find_end_event(char_u *arg, int have_group);
7862static int event_ignored(event_T event);
7863static int au_get_grouparg(char_u **argp);
7864static int do_autocmd_event(event_T event, char_u *pat, int nested, char_u *cmd, int forceit, int group);
7865static int apply_autocmds_group(event_T event, char_u *fname, char_u *fname_io, int force, int group, buf_T *buf, exarg_T *eap);
7866static void auto_next_pat(AutoPatCmd *apc, int stop_at_last);
Bram Moolenaardffa5b82014-11-19 16:38:07 +01007867#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN)
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007868static 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 +01007869#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007870
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007871
Bram Moolenaar754b5602006-02-09 23:53:20 +00007872static event_T last_event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007873static int last_group;
Bram Moolenaar78ab3312007-09-29 12:16:41 +00007874static int autocmd_blocked = 0; /* block all autocmds */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007875
Bram Moolenaarb62cc362016-09-03 16:43:53 +02007876 static char_u *
7877get_deleted_augroup(void)
7878{
7879 if (deleted_augroup == NULL)
7880 deleted_augroup = (char_u *)_("--Deleted--");
7881 return deleted_augroup;
7882}
7883
Bram Moolenaar071d4272004-06-13 20:20:40 +00007884/*
7885 * Show the autocommands for one AutoPat.
7886 */
7887 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007888show_autocmd(AutoPat *ap, event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007889{
7890 AutoCmd *ac;
7891
7892 /* Check for "got_int" (here and at various places below), which is set
7893 * when "q" has been hit for the "--more--" prompt */
7894 if (got_int)
7895 return;
7896 if (ap->pat == NULL) /* pattern has been removed */
7897 return;
7898
7899 msg_putchar('\n');
7900 if (got_int)
7901 return;
7902 if (event != last_event || ap->group != last_group)
7903 {
7904 if (ap->group != AUGROUP_DEFAULT)
7905 {
7906 if (AUGROUP_NAME(ap->group) == NULL)
Bram Moolenaar8820b482017-03-16 17:23:31 +01007907 msg_puts_attr(get_deleted_augroup(), HL_ATTR(HLF_E));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007908 else
Bram Moolenaar8820b482017-03-16 17:23:31 +01007909 msg_puts_attr(AUGROUP_NAME(ap->group), HL_ATTR(HLF_T));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007910 msg_puts((char_u *)" ");
7911 }
Bram Moolenaar8820b482017-03-16 17:23:31 +01007912 msg_puts_attr(event_nr2name(event), HL_ATTR(HLF_T));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007913 last_event = event;
7914 last_group = ap->group;
7915 msg_putchar('\n');
7916 if (got_int)
7917 return;
7918 }
7919 msg_col = 4;
7920 msg_outtrans(ap->pat);
7921
7922 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7923 {
7924 if (ac->cmd != NULL) /* skip removed commands */
7925 {
7926 if (msg_col >= 14)
7927 msg_putchar('\n');
7928 msg_col = 14;
7929 if (got_int)
7930 return;
7931 msg_outtrans(ac->cmd);
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00007932#ifdef FEAT_EVAL
7933 if (p_verbose > 0)
7934 last_set_msg(ac->scriptID);
7935#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007936 if (got_int)
7937 return;
7938 if (ac->next != NULL)
7939 {
7940 msg_putchar('\n');
7941 if (got_int)
7942 return;
7943 }
7944 }
7945 }
7946}
7947
7948/*
7949 * Mark an autocommand pattern for deletion.
7950 */
7951 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007952au_remove_pat(AutoPat *ap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007953{
7954 vim_free(ap->pat);
7955 ap->pat = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007956 ap->buflocal_nr = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007957 au_need_clean = TRUE;
7958}
7959
7960/*
7961 * Mark all commands for a pattern for deletion.
7962 */
7963 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007964au_remove_cmds(AutoPat *ap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007965{
7966 AutoCmd *ac;
7967
7968 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7969 {
7970 vim_free(ac->cmd);
7971 ac->cmd = NULL;
7972 }
7973 au_need_clean = TRUE;
7974}
7975
7976/*
7977 * Cleanup autocommands and patterns that have been deleted.
7978 * This is only done when not executing autocommands.
7979 */
7980 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007981au_cleanup(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007982{
7983 AutoPat *ap, **prev_ap;
7984 AutoCmd *ac, **prev_ac;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007985 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007986
7987 if (autocmd_busy || !au_need_clean)
7988 return;
7989
7990 /* loop over all events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007991 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7992 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007993 {
7994 /* loop over all autocommand patterns */
7995 prev_ap = &(first_autopat[(int)event]);
7996 for (ap = *prev_ap; ap != NULL; ap = *prev_ap)
7997 {
7998 /* loop over all commands for this pattern */
7999 prev_ac = &(ap->cmds);
8000 for (ac = *prev_ac; ac != NULL; ac = *prev_ac)
8001 {
8002 /* remove the command if the pattern is to be deleted or when
8003 * the command has been marked for deletion */
8004 if (ap->pat == NULL || ac->cmd == NULL)
8005 {
8006 *prev_ac = ac->next;
8007 vim_free(ac->cmd);
8008 vim_free(ac);
8009 }
8010 else
8011 prev_ac = &(ac->next);
8012 }
8013
8014 /* remove the pattern if it has been marked for deletion */
8015 if (ap->pat == NULL)
8016 {
8017 *prev_ap = ap->next;
Bram Moolenaar473de612013-06-08 18:19:48 +02008018 vim_regfree(ap->reg_prog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008019 vim_free(ap);
8020 }
8021 else
8022 prev_ap = &(ap->next);
8023 }
8024 }
8025
8026 au_need_clean = FALSE;
8027}
8028
8029/*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008030 * Called when buffer is freed, to remove/invalidate related buffer-local
8031 * autocmds.
8032 */
8033 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008034aubuflocal_remove(buf_T *buf)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008035{
8036 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008037 event_T event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008038 AutoPatCmd *apc;
8039
8040 /* invalidate currently executing autocommands */
8041 for (apc = active_apc_list; apc; apc = apc->next)
8042 if (buf->b_fnum == apc->arg_bufnr)
8043 apc->arg_bufnr = 0;
8044
8045 /* invalidate buflocals looping through events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008046 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8047 event = (event_T)((int)event + 1))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008048 /* loop over all autocommand patterns */
8049 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8050 if (ap->buflocal_nr == buf->b_fnum)
8051 {
8052 au_remove_pat(ap);
8053 if (p_verbose >= 6)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00008054 {
8055 verbose_enter();
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008056 smsg((char_u *)
8057 _("auto-removing autocommand: %s <buffer=%d>"),
8058 event_nr2name(event), buf->b_fnum);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00008059 verbose_leave();
8060 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008061 }
8062 au_cleanup();
8063}
8064
8065/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008066 * Add an autocmd group name.
8067 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
8068 */
8069 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008070au_new_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008071{
8072 int i;
8073
8074 i = au_find_group(name);
8075 if (i == AUGROUP_ERROR) /* the group doesn't exist yet, add it */
8076 {
8077 /* First try using a free entry. */
8078 for (i = 0; i < augroups.ga_len; ++i)
8079 if (AUGROUP_NAME(i) == NULL)
8080 break;
8081 if (i == augroups.ga_len && ga_grow(&augroups, 1) == FAIL)
8082 return AUGROUP_ERROR;
8083
8084 AUGROUP_NAME(i) = vim_strsave(name);
8085 if (AUGROUP_NAME(i) == NULL)
8086 return AUGROUP_ERROR;
8087 if (i == augroups.ga_len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008088 ++augroups.ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008089 }
8090
8091 return i;
8092}
8093
8094 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008095au_del_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008096{
8097 int i;
8098
8099 i = au_find_group(name);
8100 if (i == AUGROUP_ERROR) /* the group doesn't exist */
8101 EMSG2(_("E367: No such group: \"%s\""), name);
Bram Moolenaarde653f02016-09-03 16:59:06 +02008102 else if (i == current_augroup)
8103 EMSG(_("E936: Cannot delete the current group"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008104 else
8105 {
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008106 event_T event;
8107 AutoPat *ap;
8108 int in_use = FALSE;
8109
8110 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8111 event = (event_T)((int)event + 1))
8112 {
8113 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
Bram Moolenaar5c809082016-09-01 16:21:48 +02008114 if (ap->group == i && ap->pat != NULL)
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008115 {
8116 give_warning((char_u *)_("W19: Deleting augroup that is still in use"), TRUE);
8117 in_use = TRUE;
8118 event = NUM_EVENTS;
8119 break;
8120 }
8121 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008122 vim_free(AUGROUP_NAME(i));
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008123 if (in_use)
8124 {
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008125 AUGROUP_NAME(i) = get_deleted_augroup();
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008126 }
8127 else
8128 AUGROUP_NAME(i) = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008129 }
8130}
8131
8132/*
8133 * Find the ID of an autocmd group name.
8134 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
8135 */
8136 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008137au_find_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008138{
8139 int i;
8140
8141 for (i = 0; i < augroups.ga_len; ++i)
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008142 if (AUGROUP_NAME(i) != NULL && AUGROUP_NAME(i) != get_deleted_augroup()
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008143 && STRCMP(AUGROUP_NAME(i), name) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008144 return i;
8145 return AUGROUP_ERROR;
8146}
8147
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008148/*
8149 * Return TRUE if augroup "name" exists.
8150 */
8151 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008152au_has_group(char_u *name)
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008153{
8154 return au_find_group(name) != AUGROUP_ERROR;
8155}
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008156
Bram Moolenaar071d4272004-06-13 20:20:40 +00008157/*
8158 * ":augroup {name}".
8159 */
8160 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008161do_augroup(char_u *arg, int del_group)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008162{
8163 int i;
8164
8165 if (del_group)
8166 {
8167 if (*arg == NUL)
8168 EMSG(_(e_argreq));
8169 else
8170 au_del_group(arg);
8171 }
8172 else if (STRICMP(arg, "end") == 0) /* ":aug end": back to group 0 */
8173 current_augroup = AUGROUP_DEFAULT;
8174 else if (*arg) /* ":aug xxx": switch to group xxx */
8175 {
8176 i = au_new_group(arg);
8177 if (i != AUGROUP_ERROR)
8178 current_augroup = i;
8179 }
8180 else /* ":aug": list the group names */
8181 {
8182 msg_start();
8183 for (i = 0; i < augroups.ga_len; ++i)
8184 {
8185 if (AUGROUP_NAME(i) != NULL)
8186 {
8187 msg_puts(AUGROUP_NAME(i));
8188 msg_puts((char_u *)" ");
8189 }
8190 }
8191 msg_clr_eos();
8192 msg_end();
8193 }
8194}
8195
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008196#if defined(EXITFREE) || defined(PROTO)
8197 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008198free_all_autocmds(void)
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008199{
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008200 int i;
8201 char_u *s;
8202
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008203 for (current_augroup = -1; current_augroup < augroups.ga_len;
8204 ++current_augroup)
8205 do_autocmd((char_u *)"", TRUE);
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008206
8207 for (i = 0; i < augroups.ga_len; ++i)
8208 {
8209 s = ((char_u **)(augroups.ga_data))[i];
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008210 if (s != get_deleted_augroup())
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008211 vim_free(s);
8212 }
8213 ga_clear(&augroups);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008214}
8215#endif
8216
Bram Moolenaar071d4272004-06-13 20:20:40 +00008217/*
8218 * Return the event number for event name "start".
8219 * Return NUM_EVENTS if the event name was not found.
8220 * Return a pointer to the next event name in "end".
8221 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008222 static event_T
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008223event_name2nr(char_u *start, char_u **end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008224{
8225 char_u *p;
8226 int i;
8227 int len;
8228
Bram Moolenaare99e8442016-07-26 20:43:40 +02008229 /* the event name ends with end of line, '|', a blank or a comma */
Bram Moolenaar1c465442017-03-12 20:10:05 +01008230 for (p = start; *p && !VIM_ISWHITE(*p) && *p != ',' && *p != '|'; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008231 ;
8232 for (i = 0; event_names[i].name != NULL; ++i)
8233 {
8234 len = (int)STRLEN(event_names[i].name);
8235 if (len == p - start && STRNICMP(event_names[i].name, start, len) == 0)
8236 break;
8237 }
8238 if (*p == ',')
8239 ++p;
8240 *end = p;
8241 if (event_names[i].name == NULL)
8242 return NUM_EVENTS;
8243 return event_names[i].event;
8244}
8245
8246/*
8247 * Return the name for event "event".
8248 */
8249 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008250event_nr2name(event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008251{
8252 int i;
8253
8254 for (i = 0; event_names[i].name != NULL; ++i)
8255 if (event_names[i].event == event)
8256 return (char_u *)event_names[i].name;
8257 return (char_u *)"Unknown";
8258}
8259
8260/*
8261 * Scan over the events. "*" stands for all events.
8262 */
8263 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008264find_end_event(
8265 char_u *arg,
8266 int have_group) /* TRUE when group name was found */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008267{
8268 char_u *pat;
8269 char_u *p;
8270
8271 if (*arg == '*')
8272 {
Bram Moolenaar1c465442017-03-12 20:10:05 +01008273 if (arg[1] && !VIM_ISWHITE(arg[1]))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008274 {
8275 EMSG2(_("E215: Illegal character after *: %s"), arg);
8276 return NULL;
8277 }
8278 pat = arg + 1;
8279 }
8280 else
8281 {
Bram Moolenaar1c465442017-03-12 20:10:05 +01008282 for (pat = arg; *pat && *pat != '|' && !VIM_ISWHITE(*pat); pat = p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008283 {
8284 if ((int)event_name2nr(pat, &p) >= (int)NUM_EVENTS)
8285 {
8286 if (have_group)
8287 EMSG2(_("E216: No such event: %s"), pat);
8288 else
8289 EMSG2(_("E216: No such group or event: %s"), pat);
8290 return NULL;
8291 }
8292 }
8293 }
8294 return pat;
8295}
8296
8297/*
8298 * Return TRUE if "event" is included in 'eventignore'.
8299 */
8300 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008301event_ignored(event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008302{
8303 char_u *p = p_ei;
8304
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008305 while (*p != NUL)
8306 {
8307 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8308 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008309 if (event_name2nr(p, &p) == event)
8310 return TRUE;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008311 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008312
8313 return FALSE;
8314}
8315
8316/*
8317 * Return OK when the contents of p_ei is valid, FAIL otherwise.
8318 */
8319 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008320check_ei(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008321{
8322 char_u *p = p_ei;
8323
Bram Moolenaar071d4272004-06-13 20:20:40 +00008324 while (*p)
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008325 {
8326 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8327 {
8328 p += 3;
8329 if (*p == ',')
8330 ++p;
8331 }
8332 else if (event_name2nr(p, &p) == NUM_EVENTS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008333 return FAIL;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008334 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008335
8336 return OK;
8337}
8338
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008339# if defined(FEAT_SYN_HL) || defined(PROTO)
8340
8341/*
8342 * Add "what" to 'eventignore' to skip loading syntax highlighting for every
8343 * buffer loaded into the window. "what" must start with a comma.
8344 * Returns the old value of 'eventignore' in allocated memory.
8345 */
8346 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008347au_event_disable(char *what)
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008348{
8349 char_u *new_ei;
8350 char_u *save_ei;
8351
8352 save_ei = vim_strsave(p_ei);
8353 if (save_ei != NULL)
8354 {
Bram Moolenaara5792f52005-11-23 21:25:05 +00008355 new_ei = vim_strnsave(p_ei, (int)(STRLEN(p_ei) + STRLEN(what)));
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008356 if (new_ei != NULL)
8357 {
Bram Moolenaar8cac9fd2010-03-02 12:48:05 +01008358 if (*what == ',' && *p_ei == NUL)
8359 STRCPY(new_ei, what + 1);
8360 else
8361 STRCAT(new_ei, what);
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008362 set_string_option_direct((char_u *)"ei", -1, new_ei,
8363 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008364 vim_free(new_ei);
8365 }
8366 }
8367 return save_ei;
8368}
8369
8370 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008371au_event_restore(char_u *old_ei)
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008372{
8373 if (old_ei != NULL)
8374 {
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008375 set_string_option_direct((char_u *)"ei", -1, old_ei,
8376 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008377 vim_free(old_ei);
8378 }
8379}
8380# endif /* FEAT_SYN_HL */
8381
Bram Moolenaar071d4272004-06-13 20:20:40 +00008382/*
8383 * do_autocmd() -- implements the :autocmd command. Can be used in the
8384 * following ways:
8385 *
8386 * :autocmd <event> <pat> <cmd> Add <cmd> to the list of commands that
8387 * will be automatically executed for <event>
8388 * when editing a file matching <pat>, in
8389 * the current group.
8390 * :autocmd <event> <pat> Show the auto-commands associated with
8391 * <event> and <pat>.
8392 * :autocmd <event> Show the auto-commands associated with
8393 * <event>.
8394 * :autocmd Show all auto-commands.
8395 * :autocmd! <event> <pat> <cmd> Remove all auto-commands associated with
8396 * <event> and <pat>, and add the command
8397 * <cmd>, for the current group.
8398 * :autocmd! <event> <pat> Remove all auto-commands associated with
8399 * <event> and <pat> for the current group.
8400 * :autocmd! <event> Remove all auto-commands associated with
8401 * <event> for the current group.
8402 * :autocmd! Remove ALL auto-commands for the current
8403 * group.
8404 *
8405 * Multiple events and patterns may be given separated by commas. Here are
8406 * some examples:
8407 * :autocmd bufread,bufenter *.c,*.h set tw=0 smartindent noic
8408 * :autocmd bufleave * set tw=79 nosmartindent ic infercase
8409 *
8410 * :autocmd * *.c show all autocommands for *.c files.
Bram Moolenaard35f9712005-12-18 22:02:33 +00008411 *
8412 * Mostly a {group} argument can optionally appear before <event>.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008413 */
8414 void
Bram Moolenaare99e8442016-07-26 20:43:40 +02008415do_autocmd(char_u *arg_in, int forceit)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008416{
Bram Moolenaare99e8442016-07-26 20:43:40 +02008417 char_u *arg = arg_in;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008418 char_u *pat;
8419 char_u *envpat = NULL;
8420 char_u *cmd;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008421 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008422 int need_free = FALSE;
8423 int nested = FALSE;
8424 int group;
8425
Bram Moolenaare99e8442016-07-26 20:43:40 +02008426 if (*arg == '|')
8427 {
8428 arg = (char_u *)"";
8429 group = AUGROUP_ALL; /* no argument, use all groups */
8430 }
8431 else
8432 {
8433 /*
8434 * Check for a legal group name. If not, use AUGROUP_ALL.
8435 */
8436 group = au_get_grouparg(&arg);
8437 if (arg == NULL) /* out of memory */
8438 return;
8439 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008440
8441 /*
8442 * Scan over the events.
8443 * If we find an illegal name, return here, don't do anything.
8444 */
8445 pat = find_end_event(arg, group != AUGROUP_ALL);
8446 if (pat == NULL)
8447 return;
8448
Bram Moolenaar071d4272004-06-13 20:20:40 +00008449 pat = skipwhite(pat);
Bram Moolenaare99e8442016-07-26 20:43:40 +02008450 if (*pat == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008451 {
Bram Moolenaare99e8442016-07-26 20:43:40 +02008452 pat = (char_u *)"";
8453 cmd = (char_u *)"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00008454 }
Bram Moolenaare99e8442016-07-26 20:43:40 +02008455 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00008456 {
Bram Moolenaare99e8442016-07-26 20:43:40 +02008457 /*
8458 * Scan over the pattern. Put a NUL at the end.
8459 */
8460 cmd = pat;
Bram Moolenaar1c465442017-03-12 20:10:05 +01008461 while (*cmd && (!VIM_ISWHITE(*cmd) || cmd[-1] == '\\'))
Bram Moolenaare99e8442016-07-26 20:43:40 +02008462 cmd++;
8463 if (*cmd)
8464 *cmd++ = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008465
Bram Moolenaare99e8442016-07-26 20:43:40 +02008466 /* Expand environment variables in the pattern. Set 'shellslash', we want
8467 * forward slashes here. */
8468 if (vim_strchr(pat, '$') != NULL || vim_strchr(pat, '~') != NULL)
8469 {
8470#ifdef BACKSLASH_IN_FILENAME
8471 int p_ssl_save = p_ssl;
8472
8473 p_ssl = TRUE;
8474#endif
8475 envpat = expand_env_save(pat);
8476#ifdef BACKSLASH_IN_FILENAME
8477 p_ssl = p_ssl_save;
8478#endif
8479 if (envpat != NULL)
8480 pat = envpat;
8481 }
8482
8483 /*
8484 * Check for "nested" flag.
8485 */
8486 cmd = skipwhite(cmd);
Bram Moolenaar1c465442017-03-12 20:10:05 +01008487 if (*cmd != NUL && STRNCMP(cmd, "nested", 6) == 0 && VIM_ISWHITE(cmd[6]))
Bram Moolenaare99e8442016-07-26 20:43:40 +02008488 {
8489 nested = TRUE;
8490 cmd = skipwhite(cmd + 6);
8491 }
8492
8493 /*
8494 * Find the start of the commands.
8495 * Expand <sfile> in it.
8496 */
8497 if (*cmd != NUL)
8498 {
8499 cmd = expand_sfile(cmd);
8500 if (cmd == NULL) /* some error */
8501 return;
8502 need_free = TRUE;
8503 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008504 }
8505
8506 /*
8507 * Print header when showing autocommands.
8508 */
8509 if (!forceit && *cmd == NUL)
8510 {
8511 /* Highlight title */
8512 MSG_PUTS_TITLE(_("\n--- Auto-Commands ---"));
8513 }
8514
8515 /*
8516 * Loop over the events.
8517 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008518 last_event = (event_T)-1; /* for listing the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008519 last_group = AUGROUP_ERROR; /* for listing the group name */
Bram Moolenaare99e8442016-07-26 20:43:40 +02008520 if (*arg == '*' || *arg == NUL || *arg == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008521 {
Bram Moolenaar754b5602006-02-09 23:53:20 +00008522 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8523 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008524 if (do_autocmd_event(event, pat,
8525 nested, cmd, forceit, group) == FAIL)
8526 break;
8527 }
8528 else
8529 {
Bram Moolenaar1c465442017-03-12 20:10:05 +01008530 while (*arg && *arg != '|' && !VIM_ISWHITE(*arg))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008531 if (do_autocmd_event(event_name2nr(arg, &arg), pat,
8532 nested, cmd, forceit, group) == FAIL)
8533 break;
8534 }
8535
8536 if (need_free)
8537 vim_free(cmd);
8538 vim_free(envpat);
8539}
8540
8541/*
8542 * Find the group ID in a ":autocmd" or ":doautocmd" argument.
8543 * The "argp" argument is advanced to the following argument.
8544 *
8545 * Returns the group ID, AUGROUP_ERROR for error (out of memory).
8546 */
8547 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008548au_get_grouparg(char_u **argp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008549{
8550 char_u *group_name;
8551 char_u *p;
8552 char_u *arg = *argp;
8553 int group = AUGROUP_ALL;
8554
Bram Moolenaar1c465442017-03-12 20:10:05 +01008555 for (p = arg; *p && !VIM_ISWHITE(*p) && *p != '|'; ++p)
Bram Moolenaare99e8442016-07-26 20:43:40 +02008556 ;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008557 if (p > arg)
8558 {
8559 group_name = vim_strnsave(arg, (int)(p - arg));
8560 if (group_name == NULL) /* out of memory */
8561 return AUGROUP_ERROR;
8562 group = au_find_group(group_name);
8563 if (group == AUGROUP_ERROR)
8564 group = AUGROUP_ALL; /* no match, use all groups */
8565 else
8566 *argp = skipwhite(p); /* match, skip over group name */
8567 vim_free(group_name);
8568 }
8569 return group;
8570}
8571
8572/*
8573 * do_autocmd() for one event.
8574 * If *pat == NUL do for all patterns.
8575 * If *cmd == NUL show entries.
8576 * If forceit == TRUE delete entries.
8577 * If group is not AUGROUP_ALL, only use this group.
8578 */
8579 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008580do_autocmd_event(
8581 event_T event,
8582 char_u *pat,
8583 int nested,
8584 char_u *cmd,
8585 int forceit,
8586 int group)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008587{
8588 AutoPat *ap;
8589 AutoPat **prev_ap;
8590 AutoCmd *ac;
8591 AutoCmd **prev_ac;
8592 int brace_level;
8593 char_u *endpat;
8594 int findgroup;
8595 int allgroups;
8596 int patlen;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00008597 int is_buflocal;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008598 int buflocal_nr;
8599 char_u buflocal_pat[25]; /* for "<buffer=X>" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008600
8601 if (group == AUGROUP_ALL)
8602 findgroup = current_augroup;
8603 else
8604 findgroup = group;
8605 allgroups = (group == AUGROUP_ALL && !forceit && *cmd == NUL);
8606
8607 /*
8608 * Show or delete all patterns for an event.
8609 */
8610 if (*pat == NUL)
8611 {
8612 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8613 {
8614 if (forceit) /* delete the AutoPat, if it's in the current group */
8615 {
8616 if (ap->group == findgroup)
8617 au_remove_pat(ap);
8618 }
8619 else if (group == AUGROUP_ALL || ap->group == group)
8620 show_autocmd(ap, event);
8621 }
8622 }
8623
8624 /*
8625 * Loop through all the specified patterns.
8626 */
8627 for ( ; *pat; pat = (*endpat == ',' ? endpat + 1 : endpat))
8628 {
8629 /*
8630 * Find end of the pattern.
8631 * Watch out for a comma in braces, like "*.\{obj,o\}".
8632 */
8633 brace_level = 0;
8634 for (endpat = pat; *endpat && (*endpat != ',' || brace_level
Bram Moolenaar6b9be1b2015-07-28 13:33:45 +02008635 || (endpat > pat && endpat[-1] == '\\')); ++endpat)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008636 {
8637 if (*endpat == '{')
8638 brace_level++;
8639 else if (*endpat == '}')
8640 brace_level--;
8641 }
8642 if (pat == endpat) /* ignore single comma */
8643 continue;
8644 patlen = (int)(endpat - pat);
8645
8646 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008647 * detect special <buflocal[=X]> buffer-local patterns
8648 */
8649 is_buflocal = FALSE;
8650 buflocal_nr = 0;
8651
Bram Moolenaar1e997822015-02-17 16:04:57 +01008652 if (patlen >= 8 && STRNCMP(pat, "<buffer", 7) == 0
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008653 && pat[patlen - 1] == '>')
8654 {
Bram Moolenaar1e997822015-02-17 16:04:57 +01008655 /* "<buffer...>": Error will be printed only for addition.
8656 * printing and removing will proceed silently. */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008657 is_buflocal = TRUE;
8658 if (patlen == 8)
Bram Moolenaar1e997822015-02-17 16:04:57 +01008659 /* "<buffer>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008660 buflocal_nr = curbuf->b_fnum;
8661 else if (patlen > 9 && pat[7] == '=')
8662 {
Bram Moolenaar1e997822015-02-17 16:04:57 +01008663 if (patlen == 13 && STRNICMP(pat, "<buffer=abuf>", 13) == 0)
8664 /* "<buffer=abuf>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008665 buflocal_nr = autocmd_bufnr;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008666 else if (skipdigits(pat + 8) == pat + patlen - 1)
Bram Moolenaar1e997822015-02-17 16:04:57 +01008667 /* "<buffer=123>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008668 buflocal_nr = atoi((char *)pat + 8);
8669 }
8670 }
8671
8672 if (is_buflocal)
8673 {
8674 /* normalize pat into standard "<buffer>#N" form */
8675 sprintf((char *)buflocal_pat, "<buffer=%d>", buflocal_nr);
8676 pat = buflocal_pat; /* can modify pat and patlen */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008677 patlen = (int)STRLEN(buflocal_pat); /* but not endpat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008678 }
8679
8680 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008681 * Find AutoPat entries with this pattern.
8682 */
8683 prev_ap = &first_autopat[(int)event];
8684 while ((ap = *prev_ap) != NULL)
8685 {
8686 if (ap->pat != NULL)
8687 {
8688 /* Accept a pattern when:
8689 * - a group was specified and it's that group, or a group was
8690 * not specified and it's the current group, or a group was
8691 * not specified and we are listing
8692 * - the length of the pattern matches
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008693 * - the pattern matches.
8694 * For <buffer[=X]>, this condition works because we normalize
8695 * all buffer-local patterns.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008696 */
8697 if ((allgroups || ap->group == findgroup)
8698 && ap->patlen == patlen
8699 && STRNCMP(pat, ap->pat, patlen) == 0)
8700 {
8701 /*
8702 * Remove existing autocommands.
8703 * If adding any new autocmd's for this AutoPat, don't
8704 * delete the pattern from the autopat list, append to
8705 * this list.
8706 */
8707 if (forceit)
8708 {
8709 if (*cmd != NUL && ap->next == NULL)
8710 {
8711 au_remove_cmds(ap);
8712 break;
8713 }
8714 au_remove_pat(ap);
8715 }
8716
8717 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008718 * Show autocmd's for this autopat, or buflocals <buffer=X>
Bram Moolenaar071d4272004-06-13 20:20:40 +00008719 */
8720 else if (*cmd == NUL)
8721 show_autocmd(ap, event);
8722
8723 /*
8724 * Add autocmd to this autopat, if it's the last one.
8725 */
8726 else if (ap->next == NULL)
8727 break;
8728 }
8729 }
8730 prev_ap = &ap->next;
8731 }
8732
8733 /*
8734 * Add a new command.
8735 */
8736 if (*cmd != NUL)
8737 {
8738 /*
8739 * If the pattern we want to add a command to does appear at the
8740 * end of the list (or not is not in the list at all), add the
8741 * pattern at the end of the list.
8742 */
8743 if (ap == NULL)
8744 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008745 /* refuse to add buffer-local ap if buffer number is invalid */
8746 if (is_buflocal && (buflocal_nr == 0
8747 || buflist_findnr(buflocal_nr) == NULL))
8748 {
8749 EMSGN(_("E680: <buffer=%d>: invalid buffer number "),
8750 buflocal_nr);
8751 return FAIL;
8752 }
8753
Bram Moolenaar071d4272004-06-13 20:20:40 +00008754 ap = (AutoPat *)alloc((unsigned)sizeof(AutoPat));
8755 if (ap == NULL)
8756 return FAIL;
8757 ap->pat = vim_strnsave(pat, patlen);
8758 ap->patlen = patlen;
8759 if (ap->pat == NULL)
8760 {
8761 vim_free(ap);
8762 return FAIL;
8763 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008764
8765 if (is_buflocal)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008766 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008767 ap->buflocal_nr = buflocal_nr;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008768 ap->reg_prog = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008769 }
8770 else
8771 {
Bram Moolenaar748bf032005-02-02 23:04:36 +00008772 char_u *reg_pat;
8773
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008774 ap->buflocal_nr = 0;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008775 reg_pat = file_pat_to_reg_pat(pat, endpat,
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008776 &ap->allow_dirs, TRUE);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008777 if (reg_pat != NULL)
8778 ap->reg_prog = vim_regcomp(reg_pat, RE_MAGIC);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008779 vim_free(reg_pat);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008780 if (reg_pat == NULL || ap->reg_prog == NULL)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008781 {
8782 vim_free(ap->pat);
8783 vim_free(ap);
8784 return FAIL;
8785 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008786 }
8787 ap->cmds = NULL;
8788 *prev_ap = ap;
8789 ap->next = NULL;
8790 if (group == AUGROUP_ALL)
8791 ap->group = current_augroup;
8792 else
8793 ap->group = group;
8794 }
8795
8796 /*
8797 * Add the autocmd at the end of the AutoCmd list.
8798 */
8799 prev_ac = &(ap->cmds);
8800 while ((ac = *prev_ac) != NULL)
8801 prev_ac = &ac->next;
8802 ac = (AutoCmd *)alloc((unsigned)sizeof(AutoCmd));
8803 if (ac == NULL)
8804 return FAIL;
8805 ac->cmd = vim_strsave(cmd);
8806#ifdef FEAT_EVAL
8807 ac->scriptID = current_SID;
8808#endif
8809 if (ac->cmd == NULL)
8810 {
8811 vim_free(ac);
8812 return FAIL;
8813 }
8814 ac->next = NULL;
8815 *prev_ac = ac;
8816 ac->nested = nested;
8817 }
8818 }
8819
8820 au_cleanup(); /* may really delete removed patterns/commands now */
8821 return OK;
8822}
8823
8824/*
8825 * Implementation of ":doautocmd [group] event [fname]".
8826 * Return OK for success, FAIL for failure;
8827 */
8828 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008829do_doautocmd(
8830 char_u *arg,
Bram Moolenaar1610d052016-06-09 22:53:01 +02008831 int do_msg, /* give message for no matching autocmds? */
8832 int *did_something)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008833{
8834 char_u *fname;
8835 int nothing_done = TRUE;
8836 int group;
8837
Bram Moolenaar1610d052016-06-09 22:53:01 +02008838 if (did_something != NULL)
Bram Moolenaar76ae22f2016-06-13 20:00:29 +02008839 *did_something = FALSE;
Bram Moolenaar1610d052016-06-09 22:53:01 +02008840
Bram Moolenaar071d4272004-06-13 20:20:40 +00008841 /*
8842 * Check for a legal group name. If not, use AUGROUP_ALL.
8843 */
8844 group = au_get_grouparg(&arg);
8845 if (arg == NULL) /* out of memory */
8846 return FAIL;
8847
8848 if (*arg == '*')
8849 {
8850 EMSG(_("E217: Can't execute autocommands for ALL events"));
8851 return FAIL;
8852 }
8853
8854 /*
8855 * Scan over the events.
8856 * If we find an illegal name, return here, don't do anything.
8857 */
8858 fname = find_end_event(arg, group != AUGROUP_ALL);
8859 if (fname == NULL)
8860 return FAIL;
8861
8862 fname = skipwhite(fname);
8863
8864 /*
8865 * Loop over the events.
8866 */
Bram Moolenaarfaf29d72017-07-09 11:07:16 +02008867 while (*arg && !ends_excmd(*arg) && !VIM_ISWHITE(*arg))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008868 if (apply_autocmds_group(event_name2nr(arg, &arg),
8869 fname, NULL, TRUE, group, curbuf, NULL))
8870 nothing_done = FALSE;
8871
8872 if (nothing_done && do_msg)
8873 MSG(_("No matching autocommands"));
Bram Moolenaar1610d052016-06-09 22:53:01 +02008874 if (did_something != NULL)
8875 *did_something = !nothing_done;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008876
8877#ifdef FEAT_EVAL
8878 return aborting() ? FAIL : OK;
8879#else
8880 return OK;
8881#endif
8882}
8883
8884/*
8885 * ":doautoall": execute autocommands for each loaded buffer.
8886 */
8887 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008888ex_doautoall(exarg_T *eap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008889{
8890 int retval;
8891 aco_save_T aco;
8892 buf_T *buf;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008893 bufref_T bufref;
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008894 char_u *arg = eap->arg;
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008895 int call_do_modelines = check_nomodeline(&arg);
Bram Moolenaar1610d052016-06-09 22:53:01 +02008896 int did_aucmd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008897
8898 /*
8899 * This is a bit tricky: For some commands curwin->w_buffer needs to be
8900 * equal to curbuf, but for some buffers there may not be a window.
8901 * So we change the buffer for the current window for a moment. This
8902 * gives problems when the autocommands make changes to the list of
8903 * buffers or windows...
8904 */
Bram Moolenaar29323592016-07-24 22:04:11 +02008905 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008906 {
Bram Moolenaar3a847972008-07-08 09:36:58 +00008907 if (buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008908 {
8909 /* find a window for this buffer and save some values */
8910 aucmd_prepbuf(&aco, buf);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008911 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008912
8913 /* execute the autocommands for this buffer */
Bram Moolenaar1610d052016-06-09 22:53:01 +02008914 retval = do_doautocmd(arg, FALSE, &did_aucmd);
Bram Moolenaareeefcc72007-05-01 21:21:21 +00008915
Bram Moolenaar1610d052016-06-09 22:53:01 +02008916 if (call_do_modelines && did_aucmd)
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008917 {
8918 /* Execute the modeline settings, but don't set window-local
8919 * options if we are using the current window for another
8920 * buffer. */
8921 do_modelines(curwin == aucmd_win ? OPT_NOWIN : 0);
8922 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008923
8924 /* restore the current window */
8925 aucmd_restbuf(&aco);
8926
8927 /* stop if there is some error or buffer was deleted */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008928 if (retval == FAIL || !bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008929 break;
8930 }
8931 }
8932
8933 check_cursor(); /* just in case lines got deleted */
8934}
8935
8936/*
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008937 * Check *argp for <nomodeline>. When it is present return FALSE, otherwise
8938 * return TRUE and advance *argp to after it.
8939 * Thus return TRUE when do_modelines() should be called.
8940 */
8941 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008942check_nomodeline(char_u **argp)
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008943{
8944 if (STRNCMP(*argp, "<nomodeline>", 12) == 0)
8945 {
8946 *argp = skipwhite(*argp + 12);
8947 return FALSE;
8948 }
8949 return TRUE;
8950}
8951
8952/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008953 * Prepare for executing autocommands for (hidden) buffer "buf".
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008954 * Search for a visible window containing the current buffer. If there isn't
8955 * one then use "aucmd_win".
Bram Moolenaar071d4272004-06-13 20:20:40 +00008956 * Set "curbuf" and "curwin" to match "buf".
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00008957 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008958 */
8959 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008960aucmd_prepbuf(
8961 aco_save_T *aco, /* structure to save values in */
8962 buf_T *buf) /* new curbuf */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008963{
8964 win_T *win;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008965#ifdef FEAT_WINDOWS
8966 int save_ea;
8967#endif
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008968#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008969 int save_acd;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008970#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008971
8972 /* Find a window that is for the new buffer */
8973 if (buf == curbuf) /* be quick when buf is curbuf */
8974 win = curwin;
8975 else
8976#ifdef FEAT_WINDOWS
Bram Moolenaar29323592016-07-24 22:04:11 +02008977 FOR_ALL_WINDOWS(win)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008978 if (win->w_buffer == buf)
8979 break;
8980#else
8981 win = NULL;
8982#endif
8983
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008984 /* Allocate "aucmd_win" when needed. If this fails (out of memory) fall
8985 * back to using the current window. */
8986 if (win == NULL && aucmd_win == NULL)
8987 {
8988 win_alloc_aucmd_win();
8989 if (aucmd_win == NULL)
8990 win = curwin;
8991 }
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008992 if (win == NULL && aucmd_win_used)
8993 /* Strange recursive autocommand, fall back to using the current
8994 * window. Expect a few side effects... */
8995 win = curwin;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008996
8997 aco->save_curwin = curwin;
8998 aco->save_curbuf = curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008999 if (win != NULL)
9000 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009001 /* There is a window for "buf" in the current tab page, make it the
9002 * curwin. This is preferred, it has the least side effects (esp. if
9003 * "buf" is curbuf). */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009004 aco->use_aucmd_win = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009005 curwin = win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009006 }
9007 else
9008 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009009 /* There is no window for "buf", use "aucmd_win". To minimize the side
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02009010 * effects, insert it in the current tab page.
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009011 * Anything related to a window (e.g., setting folds) may have
9012 * unexpected results. */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009013 aco->use_aucmd_win = TRUE;
9014 aucmd_win_used = TRUE;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00009015 aucmd_win->w_buffer = buf;
Bram Moolenaarcdddaa42010-06-07 23:07:44 +02009016 aucmd_win->w_s = &buf->b_s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009017 ++buf->b_nwindows;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00009018 win_init_empty(aucmd_win); /* set cursor and topline to safe values */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009019
9020 /* Make sure w_localdir and globaldir are NULL to avoid a chdir() in
9021 * win_enter_ext(). */
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009022 vim_free(aucmd_win->w_localdir);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009023 aucmd_win->w_localdir = NULL;
9024 aco->globaldir = globaldir;
9025 globaldir = NULL;
9026
Bram Moolenaar071d4272004-06-13 20:20:40 +00009027
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009028#ifdef FEAT_WINDOWS
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00009029 /* Split the current window, put the aucmd_win in the upper half.
9030 * We don't want the BufEnter or WinEnter autocommands. */
9031 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009032 make_snapshot(SNAP_AUCMD_IDX);
9033 save_ea = p_ea;
9034 p_ea = FALSE;
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009035
Bram Moolenaar01c458e2013-08-05 22:02:20 +02009036# ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009037 /* Prevent chdir() call in win_enter_ext(), through do_autochdir(). */
9038 save_acd = p_acd;
9039 p_acd = FALSE;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02009040# endif
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009041
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009042 (void)win_split_ins(0, WSP_TOP, aucmd_win, 0);
9043 (void)win_comp_pos(); /* recompute window positions */
9044 p_ea = save_ea;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02009045# ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009046 p_acd = save_acd;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02009047# endif
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00009048 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009049#endif
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00009050 curwin = aucmd_win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009051 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009052 curbuf = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009053 aco->new_curwin = curwin;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009054 set_bufref(&aco->new_curbuf, curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009055}
9056
9057/*
9058 * Cleanup after executing autocommands for a (hidden) buffer.
9059 * Restore the window as it was (if possible).
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009060 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009061 */
9062 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009063aucmd_restbuf(
9064 aco_save_T *aco) /* structure holding saved values */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009065{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009066#ifdef FEAT_WINDOWS
9067 int dummy;
9068#endif
9069
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009070 if (aco->use_aucmd_win)
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009071 {
9072 --curbuf->b_nwindows;
9073#ifdef FEAT_WINDOWS
9074 /* Find "aucmd_win", it can't be closed, but it may be in another tab
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00009075 * page. Do not trigger autocommands here. */
9076 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009077 if (curwin != aucmd_win)
9078 {
9079 tabpage_T *tp;
9080 win_T *wp;
9081
9082 FOR_ALL_TAB_WINDOWS(tp, wp)
9083 {
9084 if (wp == aucmd_win)
9085 {
9086 if (tp != curtab)
Bram Moolenaar49e649f2013-05-06 04:50:35 +02009087 goto_tabpage_tp(tp, TRUE, TRUE);
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009088 win_goto(aucmd_win);
Bram Moolenaar28f29082012-02-11 23:45:37 +01009089 goto win_found;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009090 }
9091 }
9092 }
Bram Moolenaar28f29082012-02-11 23:45:37 +01009093win_found:
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009094
9095 /* Remove the window and frame from the tree of frames. */
9096 (void)winframe_remove(curwin, &dummy, NULL);
9097 win_remove(curwin, NULL);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009098 aucmd_win_used = FALSE;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009099 last_status(FALSE); /* may need to remove last status line */
Bram Moolenaar8c752bd2017-03-19 17:09:56 +01009100
9101 if (!valid_tabpage_win(curtab))
9102 /* no valid window in current tabpage */
9103 close_tabpage(curtab);
9104
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009105 restore_snapshot(SNAP_AUCMD_IDX, FALSE);
9106 (void)win_comp_pos(); /* recompute window positions */
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00009107 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009108
9109 if (win_valid(aco->save_curwin))
9110 curwin = aco->save_curwin;
9111 else
9112 /* Hmm, original window disappeared. Just use the first one. */
9113 curwin = firstwin;
9114# ifdef FEAT_EVAL
Bram Moolenaar429fa852013-04-15 12:27:36 +02009115 vars_clear(&aucmd_win->w_vars->dv_hashtab); /* free all w: variables */
9116 hash_init(&aucmd_win->w_vars->dv_hashtab); /* re-use the hashtab */
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009117# endif
9118#else
9119 curwin = aco->save_curwin;
9120#endif
9121 curbuf = curwin->w_buffer;
9122
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009123 vim_free(globaldir);
9124 globaldir = aco->globaldir;
9125
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009126 /* the buffer contents may have changed */
9127 check_cursor();
9128 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
9129 {
9130 curwin->w_topline = curbuf->b_ml.ml_line_count;
9131#ifdef FEAT_DIFF
9132 curwin->w_topfill = 0;
9133#endif
9134 }
9135#if defined(FEAT_GUI)
9136 /* Hide the scrollbars from the aucmd_win and update. */
9137 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_LEFT], FALSE);
9138 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_RIGHT], FALSE);
9139 gui_may_update_scrollbars();
9140#endif
9141 }
9142 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00009143 {
9144 /* restore curwin */
9145#ifdef FEAT_WINDOWS
9146 if (win_valid(aco->save_curwin))
9147#endif
9148 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009149 /* Restore the buffer which was previously edited by curwin, if
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009150 * it was changed, we are still the same window and the buffer is
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009151 * valid. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009152 if (curwin == aco->new_curwin
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009153 && curbuf != aco->new_curbuf.br_buf
9154 && bufref_valid(&aco->new_curbuf)
9155 && aco->new_curbuf.br_buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009156 {
Bram Moolenaar7da9c372012-04-30 17:04:52 +02009157# if defined(FEAT_SYN_HL) || defined(FEAT_SPELL)
9158 if (curwin->w_s == &curbuf->b_s)
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009159 curwin->w_s = &aco->new_curbuf.br_buf->b_s;
Bram Moolenaar7da9c372012-04-30 17:04:52 +02009160# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009161 --curbuf->b_nwindows;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009162 curbuf = aco->new_curbuf.br_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009163 curwin->w_buffer = curbuf;
9164 ++curbuf->b_nwindows;
9165 }
9166
9167 curwin = aco->save_curwin;
9168 curbuf = curwin->w_buffer;
Bram Moolenaar371932a2014-09-09 16:59:38 +02009169 /* In case the autocommand move the cursor to a position that that
9170 * not exist in curbuf. */
9171 check_cursor();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009172 }
9173 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009174}
9175
9176static int autocmd_nested = FALSE;
9177
9178/*
9179 * Execute autocommands for "event" and file name "fname".
9180 * Return TRUE if some commands were executed.
9181 */
9182 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009183apply_autocmds(
9184 event_T event,
9185 char_u *fname, /* NULL or empty means use actual file name */
9186 char_u *fname_io, /* fname to use for <afile> on cmdline */
9187 int force, /* when TRUE, ignore autocmd_busy */
9188 buf_T *buf) /* buffer for <abuf> */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009189{
9190 return apply_autocmds_group(event, fname, fname_io, force,
9191 AUGROUP_ALL, buf, NULL);
9192}
9193
9194/*
9195 * Like apply_autocmds(), but with extra "eap" argument. This takes care of
9196 * setting v:filearg.
9197 */
9198 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009199apply_autocmds_exarg(
9200 event_T event,
9201 char_u *fname,
9202 char_u *fname_io,
9203 int force,
9204 buf_T *buf,
9205 exarg_T *eap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009206{
9207 return apply_autocmds_group(event, fname, fname_io, force,
9208 AUGROUP_ALL, buf, eap);
9209}
9210
9211/*
9212 * Like apply_autocmds(), but handles the caller's retval. If the script
9213 * processing is being aborted or if retval is FAIL when inside a try
9214 * conditional, no autocommands are executed. If otherwise the autocommands
9215 * cause the script to be aborted, retval is set to FAIL.
9216 */
9217 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009218apply_autocmds_retval(
9219 event_T event,
9220 char_u *fname, /* NULL or empty means use actual file name */
9221 char_u *fname_io, /* fname to use for <afile> on cmdline */
9222 int force, /* when TRUE, ignore autocmd_busy */
9223 buf_T *buf, /* buffer for <abuf> */
9224 int *retval) /* pointer to caller's retval */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009225{
9226 int did_cmd;
9227
Bram Moolenaar1e015462005-09-25 22:16:38 +00009228#ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00009229 if (should_abort(*retval))
9230 return FALSE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00009231#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009232
9233 did_cmd = apply_autocmds_group(event, fname, fname_io, force,
9234 AUGROUP_ALL, buf, NULL);
Bram Moolenaar1e015462005-09-25 22:16:38 +00009235 if (did_cmd
9236#ifdef FEAT_EVAL
9237 && aborting()
9238#endif
9239 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00009240 *retval = FAIL;
9241 return did_cmd;
9242}
9243
Bram Moolenaard35f9712005-12-18 22:02:33 +00009244/*
9245 * Return TRUE when there is a CursorHold autocommand defined.
9246 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009247 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009248has_cursorhold(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009249{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009250 return (first_autopat[(int)(get_real_state() == NORMAL_BUSY
9251 ? EVENT_CURSORHOLD : EVENT_CURSORHOLDI)] != NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009252}
Bram Moolenaard35f9712005-12-18 22:02:33 +00009253
9254/*
9255 * Return TRUE if the CursorHold event can be triggered.
9256 */
9257 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009258trigger_cursorhold(void)
Bram Moolenaard35f9712005-12-18 22:02:33 +00009259{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009260 int state;
9261
Bram Moolenaar05334432011-07-20 18:29:39 +02009262 if (!did_cursorhold
9263 && has_cursorhold()
9264 && !Recording
9265 && typebuf.tb_len == 0
Bram Moolenaard29a9ee2006-09-14 09:07:34 +00009266#ifdef FEAT_INS_EXPAND
9267 && !ins_compl_active()
9268#endif
9269 )
Bram Moolenaar754b5602006-02-09 23:53:20 +00009270 {
9271 state = get_real_state();
9272 if (state == NORMAL_BUSY || (state & INSERT) != 0)
9273 return TRUE;
9274 }
9275 return FALSE;
Bram Moolenaard35f9712005-12-18 22:02:33 +00009276}
Bram Moolenaar754b5602006-02-09 23:53:20 +00009277
9278/*
9279 * Return TRUE when there is a CursorMoved autocommand defined.
9280 */
9281 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009282has_cursormoved(void)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009283{
9284 return (first_autopat[(int)EVENT_CURSORMOVED] != NULL);
9285}
9286
9287/*
9288 * Return TRUE when there is a CursorMovedI autocommand defined.
9289 */
9290 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009291has_cursormovedI(void)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009292{
9293 return (first_autopat[(int)EVENT_CURSORMOVEDI] != NULL);
9294}
Bram Moolenaar071d4272004-06-13 20:20:40 +00009295
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009296/*
Bram Moolenaar186628f2013-03-19 13:33:23 +01009297 * Return TRUE when there is a TextChanged autocommand defined.
9298 */
9299 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009300has_textchanged(void)
Bram Moolenaar186628f2013-03-19 13:33:23 +01009301{
9302 return (first_autopat[(int)EVENT_TEXTCHANGED] != NULL);
9303}
9304
9305/*
9306 * Return TRUE when there is a TextChangedI autocommand defined.
9307 */
9308 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009309has_textchangedI(void)
Bram Moolenaar186628f2013-03-19 13:33:23 +01009310{
9311 return (first_autopat[(int)EVENT_TEXTCHANGEDI] != NULL);
9312}
9313
9314/*
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009315 * Return TRUE when there is an InsertCharPre autocommand defined.
9316 */
9317 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009318has_insertcharpre(void)
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009319{
9320 return (first_autopat[(int)EVENT_INSERTCHARPRE] != NULL);
9321}
9322
Bram Moolenaard5005162014-08-22 23:05:54 +02009323/*
9324 * Return TRUE when there is an CmdUndefined autocommand defined.
9325 */
9326 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009327has_cmdundefined(void)
Bram Moolenaard5005162014-08-22 23:05:54 +02009328{
9329 return (first_autopat[(int)EVENT_CMDUNDEFINED] != NULL);
9330}
9331
9332/*
9333 * Return TRUE when there is an FuncUndefined autocommand defined.
9334 */
9335 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009336has_funcundefined(void)
Bram Moolenaard5005162014-08-22 23:05:54 +02009337{
9338 return (first_autopat[(int)EVENT_FUNCUNDEFINED] != NULL);
9339}
9340
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009341/*
9342 * Execute autocommands for "event" and file name "fname".
9343 * Return TRUE if some commands were executed.
9344 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009345 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009346apply_autocmds_group(
9347 event_T event,
9348 char_u *fname, /* NULL or empty means use actual file name */
9349 char_u *fname_io, /* fname to use for <afile> on cmdline, NULL means
Bram Moolenaar071d4272004-06-13 20:20:40 +00009350 use fname */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009351 int force, /* when TRUE, ignore autocmd_busy */
9352 int group, /* group ID, or AUGROUP_ALL */
9353 buf_T *buf, /* buffer for <abuf> */
9354 exarg_T *eap) /* command arguments */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009355{
9356 char_u *sfname = NULL; /* short file name */
9357 char_u *tail;
9358 int save_changed;
9359 buf_T *old_curbuf;
9360 int retval = FALSE;
9361 char_u *save_sourcing_name;
9362 linenr_T save_sourcing_lnum;
9363 char_u *save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009364 int save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009365 int save_autocmd_bufnr;
9366 char_u *save_autocmd_match;
9367 int save_autocmd_busy;
9368 int save_autocmd_nested;
9369 static int nesting = 0;
9370 AutoPatCmd patcmd;
9371 AutoPat *ap;
9372#ifdef FEAT_EVAL
9373 scid_T save_current_SID;
9374 void *save_funccalp;
9375 char_u *save_cmdarg;
9376 long save_cmdbang;
9377#endif
9378 static int filechangeshell_busy = FALSE;
Bram Moolenaar05159a02005-02-26 23:04:13 +00009379#ifdef FEAT_PROFILE
9380 proftime_T wait_time;
9381#endif
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009382 int did_save_redobuff = FALSE;
Bram Moolenaard4863aa2017-04-07 19:50:12 +02009383 save_redo_T save_redo;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009384
9385 /*
9386 * Quickly return if there are no autocommands for this event or
9387 * autocommands are blocked.
9388 */
Bram Moolenaarfaf29d72017-07-09 11:07:16 +02009389 if (event == NUM_EVENTS || first_autopat[(int)event] == NULL
9390 || autocmd_blocked > 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009391 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009392
9393 /*
9394 * When autocommands are busy, new autocommands are only executed when
9395 * explicitly enabled with the "nested" flag.
9396 */
9397 if (autocmd_busy && !(force || autocmd_nested))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009398 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009399
9400#ifdef FEAT_EVAL
9401 /*
Bram Moolenaar7263a772007-05-10 17:35:54 +00009402 * Quickly return when immediately aborting on error, or when an interrupt
Bram Moolenaar071d4272004-06-13 20:20:40 +00009403 * occurred or an exception was thrown but not caught.
9404 */
9405 if (aborting())
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009406 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009407#endif
9408
9409 /*
9410 * FileChangedShell never nests, because it can create an endless loop.
9411 */
Bram Moolenaar56718732006-03-15 22:53:57 +00009412 if (filechangeshell_busy && (event == EVENT_FILECHANGEDSHELL
9413 || event == EVENT_FILECHANGEDSHELLPOST))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009414 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009415
9416 /*
9417 * Ignore events in 'eventignore'.
9418 */
9419 if (event_ignored(event))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009420 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009421
9422 /*
9423 * Allow nesting of autocommands, but restrict the depth, because it's
9424 * possible to create an endless loop.
9425 */
9426 if (nesting == 10)
9427 {
9428 EMSG(_("E218: autocommand nesting too deep"));
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009429 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009430 }
9431
9432 /*
9433 * Check if these autocommands are disabled. Used when doing ":all" or
9434 * ":ball".
9435 */
9436 if ( (autocmd_no_enter
9437 && (event == EVENT_WINENTER || event == EVENT_BUFENTER))
9438 || (autocmd_no_leave
9439 && (event == EVENT_WINLEAVE || event == EVENT_BUFLEAVE)))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009440 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009441
9442 /*
9443 * Save the autocmd_* variables and info about the current buffer.
9444 */
9445 save_autocmd_fname = autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009446 save_autocmd_fname_full = autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009447 save_autocmd_bufnr = autocmd_bufnr;
9448 save_autocmd_match = autocmd_match;
9449 save_autocmd_busy = autocmd_busy;
9450 save_autocmd_nested = autocmd_nested;
9451 save_changed = curbuf->b_changed;
9452 old_curbuf = curbuf;
9453
9454 /*
9455 * Set the file name to be used for <afile>.
Bram Moolenaara0174af2008-01-02 20:08:25 +00009456 * Make a copy to avoid that changing a buffer name or directory makes it
9457 * invalid.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009458 */
9459 if (fname_io == NULL)
9460 {
Bram Moolenaar53744302015-07-17 17:38:22 +02009461 if (event == EVENT_COLORSCHEME || event == EVENT_OPTIONSET)
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009462 autocmd_fname = NULL;
Bram Moolenaarfaf29d72017-07-09 11:07:16 +02009463 else if (fname != NULL && !ends_excmd(*fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009464 autocmd_fname = fname;
9465 else if (buf != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009466 autocmd_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009467 else
9468 autocmd_fname = NULL;
9469 }
9470 else
9471 autocmd_fname = fname_io;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009472 if (autocmd_fname != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009473 autocmd_fname = vim_strsave(autocmd_fname);
9474 autocmd_fname_full = FALSE; /* call FullName_save() later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009475
9476 /*
9477 * Set the buffer number to be used for <abuf>.
9478 */
9479 if (buf == NULL)
9480 autocmd_bufnr = 0;
9481 else
9482 autocmd_bufnr = buf->b_fnum;
9483
9484 /*
9485 * When the file name is NULL or empty, use the file name of buffer "buf".
9486 * Always use the full path of the file name to match with, in case
9487 * "allow_dirs" is set.
9488 */
9489 if (fname == NULL || *fname == NUL)
9490 {
9491 if (buf == NULL)
9492 fname = NULL;
9493 else
9494 {
9495#ifdef FEAT_SYN_HL
9496 if (event == EVENT_SYNTAX)
9497 fname = buf->b_p_syn;
9498 else
9499#endif
9500 if (event == EVENT_FILETYPE)
9501 fname = buf->b_p_ft;
9502 else
9503 {
9504 if (buf->b_sfname != NULL)
9505 sfname = vim_strsave(buf->b_sfname);
9506 fname = buf->b_ffname;
9507 }
9508 }
9509 if (fname == NULL)
9510 fname = (char_u *)"";
9511 fname = vim_strsave(fname); /* make a copy, so we can change it */
9512 }
9513 else
9514 {
9515 sfname = vim_strsave(fname);
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009516 /* Don't try expanding FileType, Syntax, FuncUndefined, WindowID,
9517 * ColorScheme or QuickFixCmd* */
Bram Moolenaar7c626922005-02-07 22:01:03 +00009518 if (event == EVENT_FILETYPE
9519 || event == EVENT_SYNTAX
Bram Moolenaar5135d462009-04-29 16:03:38 +00009520 || event == EVENT_FUNCUNDEFINED
Bram Moolenaar7c626922005-02-07 22:01:03 +00009521 || event == EVENT_REMOTEREPLY
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00009522 || event == EVENT_SPELLFILEMISSING
Bram Moolenaar7c626922005-02-07 22:01:03 +00009523 || event == EVENT_QUICKFIXCMDPRE
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009524 || event == EVENT_COLORSCHEME
Bram Moolenaar53744302015-07-17 17:38:22 +02009525 || event == EVENT_OPTIONSET
Bram Moolenaar7c626922005-02-07 22:01:03 +00009526 || event == EVENT_QUICKFIXCMDPOST)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009527 fname = vim_strsave(fname);
9528 else
9529 fname = FullName_save(fname, FALSE);
9530 }
9531 if (fname == NULL) /* out of memory */
9532 {
9533 vim_free(sfname);
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009534 retval = FALSE;
9535 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009536 }
9537
9538#ifdef BACKSLASH_IN_FILENAME
9539 /*
9540 * Replace all backslashes with forward slashes. This makes the
9541 * autocommand patterns portable between Unix and MS-DOS.
9542 */
9543 if (sfname != NULL)
9544 forward_slash(sfname);
9545 forward_slash(fname);
9546#endif
9547
9548#ifdef VMS
9549 /* remove version for correct match */
9550 if (sfname != NULL)
9551 vms_remove_version(sfname);
9552 vms_remove_version(fname);
9553#endif
9554
9555 /*
9556 * Set the name to be used for <amatch>.
9557 */
9558 autocmd_match = fname;
9559
9560
9561 /* Don't redraw while doing auto commands. */
9562 ++RedrawingDisabled;
9563 save_sourcing_name = sourcing_name;
9564 sourcing_name = NULL; /* don't free this one */
9565 save_sourcing_lnum = sourcing_lnum;
9566 sourcing_lnum = 0; /* no line number here */
9567
9568#ifdef FEAT_EVAL
9569 save_current_SID = current_SID;
9570
Bram Moolenaar05159a02005-02-26 23:04:13 +00009571# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009572 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009573 prof_child_enter(&wait_time); /* doesn't count for the caller itself */
9574# endif
9575
Bram Moolenaar071d4272004-06-13 20:20:40 +00009576 /* Don't use local function variables, if called from a function */
9577 save_funccalp = save_funccal();
9578#endif
9579
9580 /*
9581 * When starting to execute autocommands, save the search patterns.
9582 */
9583 if (!autocmd_busy)
9584 {
9585 save_search_patterns();
Bram Moolenaar20ad69c2015-12-03 13:52:52 +01009586#ifdef FEAT_INS_EXPAND
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009587 if (!ins_compl_active())
Bram Moolenaar20ad69c2015-12-03 13:52:52 +01009588#endif
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009589 {
Bram Moolenaard4863aa2017-04-07 19:50:12 +02009590 saveRedobuff(&save_redo);
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009591 did_save_redobuff = TRUE;
9592 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009593 did_filetype = keep_filetype;
9594 }
9595
9596 /*
9597 * Note that we are applying autocmds. Some commands need to know.
9598 */
9599 autocmd_busy = TRUE;
9600 filechangeshell_busy = (event == EVENT_FILECHANGEDSHELL);
9601 ++nesting; /* see matching decrement below */
9602
9603 /* Remember that FileType was triggered. Used for did_filetype(). */
9604 if (event == EVENT_FILETYPE)
9605 did_filetype = TRUE;
9606
9607 tail = gettail(fname);
9608
9609 /* Find first autocommand that matches */
9610 patcmd.curpat = first_autopat[(int)event];
9611 patcmd.nextcmd = NULL;
9612 patcmd.group = group;
9613 patcmd.fname = fname;
9614 patcmd.sfname = sfname;
9615 patcmd.tail = tail;
9616 patcmd.event = event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009617 patcmd.arg_bufnr = autocmd_bufnr;
9618 patcmd.next = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009619 auto_next_pat(&patcmd, FALSE);
9620
9621 /* found one, start executing the autocommands */
9622 if (patcmd.curpat != NULL)
9623 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009624 /* add to active_apc_list */
9625 patcmd.next = active_apc_list;
9626 active_apc_list = &patcmd;
9627
Bram Moolenaar071d4272004-06-13 20:20:40 +00009628#ifdef FEAT_EVAL
9629 /* set v:cmdarg (only when there is a matching pattern) */
Bram Moolenaar22fcfad2016-07-01 18:17:26 +02009630 save_cmdbang = (long)get_vim_var_nr(VV_CMDBANG);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009631 if (eap != NULL)
9632 {
9633 save_cmdarg = set_cmdarg(eap, NULL);
9634 set_vim_var_nr(VV_CMDBANG, (long)eap->forceit);
9635 }
9636 else
9637 save_cmdarg = NULL; /* avoid gcc warning */
9638#endif
9639 retval = TRUE;
9640 /* mark the last pattern, to avoid an endless loop when more patterns
9641 * are added when executing autocommands */
9642 for (ap = patcmd.curpat; ap->next != NULL; ap = ap->next)
9643 ap->last = FALSE;
9644 ap->last = TRUE;
9645 check_lnums(TRUE); /* make sure cursor and topline are valid */
9646 do_cmdline(NULL, getnextac, (void *)&patcmd,
9647 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
9648#ifdef FEAT_EVAL
9649 if (eap != NULL)
9650 {
9651 (void)set_cmdarg(NULL, save_cmdarg);
9652 set_vim_var_nr(VV_CMDBANG, save_cmdbang);
9653 }
9654#endif
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009655 /* delete from active_apc_list */
9656 if (active_apc_list == &patcmd) /* just in case */
9657 active_apc_list = patcmd.next;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009658 }
9659
9660 --RedrawingDisabled;
9661 autocmd_busy = save_autocmd_busy;
9662 filechangeshell_busy = FALSE;
9663 autocmd_nested = save_autocmd_nested;
9664 vim_free(sourcing_name);
9665 sourcing_name = save_sourcing_name;
9666 sourcing_lnum = save_sourcing_lnum;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009667 vim_free(autocmd_fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009668 autocmd_fname = save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009669 autocmd_fname_full = save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009670 autocmd_bufnr = save_autocmd_bufnr;
9671 autocmd_match = save_autocmd_match;
9672#ifdef FEAT_EVAL
9673 current_SID = save_current_SID;
9674 restore_funccal(save_funccalp);
Bram Moolenaar05159a02005-02-26 23:04:13 +00009675# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009676 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009677 prof_child_exit(&wait_time);
9678# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009679#endif
9680 vim_free(fname);
9681 vim_free(sfname);
9682 --nesting; /* see matching increment above */
9683
9684 /*
9685 * When stopping to execute autocommands, restore the search patterns and
Bram Moolenaar3be85852014-06-12 14:01:31 +02009686 * the redo buffer. Free any buffers in the au_pending_free_buf list and
9687 * free any windows in the au_pending_free_win list.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009688 */
9689 if (!autocmd_busy)
9690 {
9691 restore_search_patterns();
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009692 if (did_save_redobuff)
Bram Moolenaard4863aa2017-04-07 19:50:12 +02009693 restoreRedobuff(&save_redo);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009694 did_filetype = FALSE;
Bram Moolenaar4c7ab1b2014-04-06 20:45:43 +02009695 while (au_pending_free_buf != NULL)
9696 {
9697 buf_T *b = au_pending_free_buf->b_next;
9698 vim_free(au_pending_free_buf);
9699 au_pending_free_buf = b;
9700 }
Bram Moolenaar3be85852014-06-12 14:01:31 +02009701 while (au_pending_free_win != NULL)
9702 {
9703 win_T *w = au_pending_free_win->w_next;
9704 vim_free(au_pending_free_win);
9705 au_pending_free_win = w;
9706 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009707 }
9708
9709 /*
9710 * Some events don't set or reset the Changed flag.
9711 * Check if still in the same buffer!
9712 */
9713 if (curbuf == old_curbuf
9714 && (event == EVENT_BUFREADPOST
9715 || event == EVENT_BUFWRITEPOST
9716 || event == EVENT_FILEAPPENDPOST
9717 || event == EVENT_VIMLEAVE
9718 || event == EVENT_VIMLEAVEPRE))
9719 {
9720#ifdef FEAT_TITLE
9721 if (curbuf->b_changed != save_changed)
9722 need_maketitle = TRUE;
9723#endif
9724 curbuf->b_changed = save_changed;
9725 }
9726
9727 au_cleanup(); /* may really delete removed patterns/commands now */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009728
9729BYPASS_AU:
9730 /* When wiping out a buffer make sure all its buffer-local autocommands
9731 * are deleted. */
9732 if (event == EVENT_BUFWIPEOUT && buf != NULL)
9733 aubuflocal_remove(buf);
9734
Bram Moolenaarc3691332016-04-20 12:49:49 +02009735 if (retval == OK && event == EVENT_FILETYPE)
9736 au_did_filetype = TRUE;
9737
Bram Moolenaar071d4272004-06-13 20:20:40 +00009738 return retval;
9739}
9740
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009741# ifdef FEAT_EVAL
9742static char_u *old_termresponse = NULL;
9743# endif
9744
9745/*
9746 * Block triggering autocommands until unblock_autocmd() is called.
9747 * Can be used recursively, so long as it's symmetric.
9748 */
9749 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009750block_autocmds(void)
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009751{
9752# ifdef FEAT_EVAL
9753 /* Remember the value of v:termresponse. */
9754 if (autocmd_blocked == 0)
9755 old_termresponse = get_vim_var_str(VV_TERMRESPONSE);
9756# endif
9757 ++autocmd_blocked;
9758}
9759
9760 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009761unblock_autocmds(void)
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009762{
9763 --autocmd_blocked;
9764
9765# ifdef FEAT_EVAL
9766 /* When v:termresponse was set while autocommands were blocked, trigger
9767 * the autocommands now. Esp. useful when executing a shell command
9768 * during startup (vimdiff). */
9769 if (autocmd_blocked == 0
9770 && get_vim_var_str(VV_TERMRESPONSE) != old_termresponse)
9771 apply_autocmds(EVENT_TERMRESPONSE, NULL, NULL, FALSE, curbuf);
9772# endif
9773}
9774
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009775 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009776is_autocmd_blocked(void)
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009777{
9778 return autocmd_blocked != 0;
9779}
9780
Bram Moolenaar071d4272004-06-13 20:20:40 +00009781/*
9782 * Find next autocommand pattern that matches.
9783 */
9784 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009785auto_next_pat(
9786 AutoPatCmd *apc,
9787 int stop_at_last) /* stop when 'last' flag is set */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009788{
9789 AutoPat *ap;
9790 AutoCmd *cp;
9791 char_u *name;
9792 char *s;
9793
9794 vim_free(sourcing_name);
9795 sourcing_name = NULL;
9796
9797 for (ap = apc->curpat; ap != NULL && !got_int; ap = ap->next)
9798 {
9799 apc->curpat = NULL;
9800
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009801 /* Only use a pattern when it has not been removed, has commands and
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009802 * the group matches. For buffer-local autocommands only check the
9803 * buffer number. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009804 if (ap->pat != NULL && ap->cmds != NULL
9805 && (apc->group == AUGROUP_ALL || apc->group == ap->group))
9806 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009807 /* execution-condition */
9808 if (ap->buflocal_nr == 0
Bram Moolenaardffa5b82014-11-19 16:38:07 +01009809 ? (match_file_pat(NULL, &ap->reg_prog, apc->fname,
Bram Moolenaar748bf032005-02-02 23:04:36 +00009810 apc->sfname, apc->tail, ap->allow_dirs))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009811 : ap->buflocal_nr == apc->arg_bufnr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009812 {
9813 name = event_nr2name(apc->event);
9814 s = _("%s Auto commands for \"%s\"");
9815 sourcing_name = alloc((unsigned)(STRLEN(s)
9816 + STRLEN(name) + ap->patlen + 1));
9817 if (sourcing_name != NULL)
9818 {
9819 sprintf((char *)sourcing_name, s,
9820 (char *)name, (char *)ap->pat);
9821 if (p_verbose >= 8)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009822 {
9823 verbose_enter();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009824 smsg((char_u *)_("Executing %s"), sourcing_name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009825 verbose_leave();
9826 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009827 }
9828
9829 apc->curpat = ap;
9830 apc->nextcmd = ap->cmds;
9831 /* mark last command */
9832 for (cp = ap->cmds; cp->next != NULL; cp = cp->next)
9833 cp->last = FALSE;
9834 cp->last = TRUE;
9835 }
9836 line_breakcheck();
9837 if (apc->curpat != NULL) /* found a match */
9838 break;
9839 }
9840 if (stop_at_last && ap->last)
9841 break;
9842 }
9843}
9844
9845/*
9846 * Get next autocommand command.
9847 * Called by do_cmdline() to get the next line for ":if".
9848 * Returns allocated string, or NULL for end of autocommands.
9849 */
Bram Moolenaar21691f82012-12-05 19:13:18 +01009850 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009851getnextac(int c UNUSED, void *cookie, int indent UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009852{
9853 AutoPatCmd *acp = (AutoPatCmd *)cookie;
9854 char_u *retval;
9855 AutoCmd *ac;
9856
9857 /* Can be called again after returning the last line. */
9858 if (acp->curpat == NULL)
9859 return NULL;
9860
9861 /* repeat until we find an autocommand to execute */
9862 for (;;)
9863 {
9864 /* skip removed commands */
9865 while (acp->nextcmd != NULL && acp->nextcmd->cmd == NULL)
9866 if (acp->nextcmd->last)
9867 acp->nextcmd = NULL;
9868 else
9869 acp->nextcmd = acp->nextcmd->next;
9870
9871 if (acp->nextcmd != NULL)
9872 break;
9873
9874 /* at end of commands, find next pattern that matches */
9875 if (acp->curpat->last)
9876 acp->curpat = NULL;
9877 else
9878 acp->curpat = acp->curpat->next;
9879 if (acp->curpat != NULL)
9880 auto_next_pat(acp, TRUE);
9881 if (acp->curpat == NULL)
9882 return NULL;
9883 }
9884
9885 ac = acp->nextcmd;
9886
9887 if (p_verbose >= 9)
9888 {
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009889 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009890 smsg((char_u *)_("autocommand %s"), ac->cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009891 msg_puts((char_u *)"\n"); /* don't overwrite this either */
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009892 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009893 }
9894 retval = vim_strsave(ac->cmd);
9895 autocmd_nested = ac->nested;
9896#ifdef FEAT_EVAL
9897 current_SID = ac->scriptID;
9898#endif
9899 if (ac->last)
9900 acp->nextcmd = NULL;
9901 else
9902 acp->nextcmd = ac->next;
9903 return retval;
9904}
9905
9906/*
9907 * Return TRUE if there is a matching autocommand for "fname".
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009908 * To account for buffer-local autocommands, function needs to know
9909 * in which buffer the file will be opened.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009910 */
9911 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009912has_autocmd(event_T event, char_u *sfname, buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009913{
9914 AutoPat *ap;
9915 char_u *fname;
9916 char_u *tail = gettail(sfname);
9917 int retval = FALSE;
9918
9919 fname = FullName_save(sfname, FALSE);
9920 if (fname == NULL)
9921 return FALSE;
9922
9923#ifdef BACKSLASH_IN_FILENAME
9924 /*
9925 * Replace all backslashes with forward slashes. This makes the
9926 * autocommand patterns portable between Unix and MS-DOS.
9927 */
9928 sfname = vim_strsave(sfname);
9929 if (sfname != NULL)
9930 forward_slash(sfname);
9931 forward_slash(fname);
9932#endif
9933
9934 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
9935 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009936 && (ap->buflocal_nr == 0
Bram Moolenaardffa5b82014-11-19 16:38:07 +01009937 ? match_file_pat(NULL, &ap->reg_prog,
Bram Moolenaar748bf032005-02-02 23:04:36 +00009938 fname, sfname, tail, ap->allow_dirs)
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009939 : buf != NULL && ap->buflocal_nr == buf->b_fnum
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009940 ))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009941 {
9942 retval = TRUE;
9943 break;
9944 }
9945
9946 vim_free(fname);
9947#ifdef BACKSLASH_IN_FILENAME
9948 vim_free(sfname);
9949#endif
9950
9951 return retval;
9952}
9953
9954#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
9955/*
9956 * Function given to ExpandGeneric() to obtain the list of autocommand group
9957 * names.
9958 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009959 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009960get_augroup_name(expand_T *xp UNUSED, int idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009961{
9962 if (idx == augroups.ga_len) /* add "END" add the end */
9963 return (char_u *)"END";
9964 if (idx >= augroups.ga_len) /* end of list */
9965 return NULL;
Bram Moolenaarb62cc362016-09-03 16:43:53 +02009966 if (AUGROUP_NAME(idx) == NULL || AUGROUP_NAME(idx) == get_deleted_augroup())
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02009967 /* skip deleted entries */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009968 return (char_u *)"";
9969 return AUGROUP_NAME(idx); /* return a name */
9970}
9971
9972static int include_groups = FALSE;
9973
9974 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009975set_context_in_autocmd(
9976 expand_T *xp,
9977 char_u *arg,
9978 int doautocmd) /* TRUE for :doauto*, FALSE for :autocmd */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009979{
9980 char_u *p;
9981 int group;
9982
9983 /* check for a group name, skip it if present */
9984 include_groups = FALSE;
9985 p = arg;
9986 group = au_get_grouparg(&arg);
9987 if (group == AUGROUP_ERROR)
9988 return NULL;
9989 /* If there only is a group name that's what we expand. */
Bram Moolenaar1c465442017-03-12 20:10:05 +01009990 if (*arg == NUL && group != AUGROUP_ALL && !VIM_ISWHITE(arg[-1]))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009991 {
9992 arg = p;
9993 group = AUGROUP_ALL;
9994 }
9995
9996 /* skip over event name */
Bram Moolenaar1c465442017-03-12 20:10:05 +01009997 for (p = arg; *p != NUL && !VIM_ISWHITE(*p); ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009998 if (*p == ',')
9999 arg = p + 1;
10000 if (*p == NUL)
10001 {
10002 if (group == AUGROUP_ALL)
10003 include_groups = TRUE;
10004 xp->xp_context = EXPAND_EVENTS; /* expand event name */
10005 xp->xp_pattern = arg;
10006 return NULL;
10007 }
10008
10009 /* skip over pattern */
10010 arg = skipwhite(p);
Bram Moolenaar1c465442017-03-12 20:10:05 +010010011 while (*arg && (!VIM_ISWHITE(*arg) || arg[-1] == '\\'))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010012 arg++;
10013 if (*arg)
10014 return arg; /* expand (next) command */
10015
10016 if (doautocmd)
10017 xp->xp_context = EXPAND_FILES; /* expand file names */
10018 else
10019 xp->xp_context = EXPAND_NOTHING; /* pattern is not expanded */
10020 return NULL;
10021}
10022
10023/*
10024 * Function given to ExpandGeneric() to obtain the list of event names.
10025 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010026 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010027get_event_name(expand_T *xp UNUSED, int idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010028{
10029 if (idx < augroups.ga_len) /* First list group names, if wanted */
10030 {
Bram Moolenaarf2c4c392016-07-29 20:50:24 +020010031 if (!include_groups || AUGROUP_NAME(idx) == NULL
Bram Moolenaarb62cc362016-09-03 16:43:53 +020010032 || AUGROUP_NAME(idx) == get_deleted_augroup())
Bram Moolenaar071d4272004-06-13 20:20:40 +000010033 return (char_u *)""; /* skip deleted entries */
10034 return AUGROUP_NAME(idx); /* return a name */
10035 }
10036 return (char_u *)event_names[idx - augroups.ga_len].name;
10037}
10038
10039#endif /* FEAT_CMDL_COMPL */
10040
10041/*
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010042 * Return TRUE if autocmd is supported.
10043 */
10044 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010045autocmd_supported(char_u *name)
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010046{
10047 char_u *p;
10048
10049 return (event_name2nr(name, &p) != NUM_EVENTS);
10050}
10051
10052/*
Bram Moolenaar195d6352005-12-19 22:08:24 +000010053 * Return TRUE if an autocommand is defined for a group, event and
10054 * pattern: The group can be omitted to accept any group. "event" and "pattern"
10055 * can be NULL to accept any event and pattern. "pattern" can be NULL to accept
10056 * any pattern. Buffer-local patterns <buffer> or <buffer=N> are accepted.
10057 * Used for:
10058 * exists("#Group") or
10059 * exists("#Group#Event") or
10060 * exists("#Group#Event#pat") or
10061 * exists("#Event") or
10062 * exists("#Event#pat")
Bram Moolenaar071d4272004-06-13 20:20:40 +000010063 */
10064 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010065au_exists(char_u *arg)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010066{
Bram Moolenaar195d6352005-12-19 22:08:24 +000010067 char_u *arg_save;
10068 char_u *pattern = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010069 char_u *event_name;
10070 char_u *p;
Bram Moolenaar754b5602006-02-09 23:53:20 +000010071 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010072 AutoPat *ap;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010073 buf_T *buflocal_buf = NULL;
Bram Moolenaar195d6352005-12-19 22:08:24 +000010074 int group;
10075 int retval = FALSE;
10076
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010077 /* Make a copy so that we can change the '#' chars to a NUL. */
Bram Moolenaar195d6352005-12-19 22:08:24 +000010078 arg_save = vim_strsave(arg);
10079 if (arg_save == NULL)
10080 return FALSE;
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010081 p = vim_strchr(arg_save, '#');
Bram Moolenaar195d6352005-12-19 22:08:24 +000010082 if (p != NULL)
10083 *p++ = NUL;
10084
10085 /* First, look for an autocmd group name */
10086 group = au_find_group(arg_save);
10087 if (group == AUGROUP_ERROR)
10088 {
10089 /* Didn't match a group name, assume the first argument is an event. */
10090 group = AUGROUP_ALL;
10091 event_name = arg_save;
10092 }
10093 else
10094 {
10095 if (p == NULL)
10096 {
10097 /* "Group": group name is present and it's recognized */
10098 retval = TRUE;
10099 goto theend;
10100 }
10101
10102 /* Must be "Group#Event" or "Group#Event#pat". */
10103 event_name = p;
10104 p = vim_strchr(event_name, '#');
10105 if (p != NULL)
10106 *p++ = NUL; /* "Group#Event#pat" */
10107 }
10108
10109 pattern = p; /* "pattern" is NULL when there is no pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010110
10111 /* find the index (enum) for the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010112 event = event_name2nr(event_name, &p);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010113
10114 /* return FALSE if the event name is not recognized */
Bram Moolenaar195d6352005-12-19 22:08:24 +000010115 if (event == NUM_EVENTS)
10116 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010117
10118 /* Find the first autocommand for this event.
10119 * If there isn't any, return FALSE;
10120 * If there is one and no pattern given, return TRUE; */
10121 ap = first_autopat[(int)event];
10122 if (ap == NULL)
Bram Moolenaar195d6352005-12-19 22:08:24 +000010123 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010124
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010125 /* if pattern is "<buffer>", special handling is needed which uses curbuf */
10126 /* for pattern "<buffer=N>, fnamecmp() will work fine */
Bram Moolenaar5b7880d2009-09-11 15:24:31 +000010127 if (pattern != NULL && STRICMP(pattern, "<buffer>") == 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010128 buflocal_buf = curbuf;
10129
Bram Moolenaar071d4272004-06-13 20:20:40 +000010130 /* Check if there is an autocommand with the given pattern. */
10131 for ( ; ap != NULL; ap = ap->next)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010132 /* only use a pattern when it has not been removed and has commands. */
10133 /* For buffer-local autocommands, fnamecmp() works fine. */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010134 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaar195d6352005-12-19 22:08:24 +000010135 && (group == AUGROUP_ALL || ap->group == group)
Bram Moolenaar5b7880d2009-09-11 15:24:31 +000010136 && (pattern == NULL
10137 || (buflocal_buf == NULL
10138 ? fnamecmp(ap->pat, pattern) == 0
10139 : ap->buflocal_nr == buflocal_buf->b_fnum)))
Bram Moolenaar195d6352005-12-19 22:08:24 +000010140 {
10141 retval = TRUE;
10142 break;
10143 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010144
Bram Moolenaar195d6352005-12-19 22:08:24 +000010145theend:
10146 vim_free(arg_save);
10147 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010148}
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010149
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010150#else /* FEAT_AUTOCMD */
10151
10152/*
10153 * Prepare for executing commands for (hidden) buffer "buf".
10154 * This is the non-autocommand version, it simply saves "curbuf" and sets
10155 * "curbuf" and "curwin" to match "buf".
10156 */
10157 void
Bram Moolenaard14e00e2016-01-31 17:30:51 +010010158aucmd_prepbuf(
10159 aco_save_T *aco, /* structure to save values in */
10160 buf_T *buf) /* new curbuf */
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010161{
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010162 aco->save_curbuf = curbuf;
10163 --curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010164 curbuf = buf;
10165 curwin->w_buffer = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010166 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010167}
10168
10169/*
10170 * Restore after executing commands for a (hidden) buffer.
10171 * This is the non-autocommand version.
10172 */
10173 void
Bram Moolenaard14e00e2016-01-31 17:30:51 +010010174aucmd_restbuf(
10175 aco_save_T *aco) /* structure holding saved values */
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010176{
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010177 --curbuf->b_nwindows;
10178 curbuf = aco->save_curbuf;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010179 curwin->w_buffer = curbuf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010180 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010181}
10182
Bram Moolenaar071d4272004-06-13 20:20:40 +000010183#endif /* FEAT_AUTOCMD */
10184
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010185
Bram Moolenaar071d4272004-06-13 20:20:40 +000010186#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN) || defined(PROTO)
10187/*
Bram Moolenaar748bf032005-02-02 23:04:36 +000010188 * Try matching a filename with a "pattern" ("prog" is NULL), or use the
10189 * precompiled regprog "prog" ("pattern" is NULL). That avoids calling
10190 * vim_regcomp() often.
Bram Moolenaar071d4272004-06-13 20:20:40 +000010191 * Used for autocommands and 'wildignore'.
10192 * Returns TRUE if there is a match, FALSE otherwise.
10193 */
Bram Moolenaardffa5b82014-11-19 16:38:07 +010010194 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010195match_file_pat(
10196 char_u *pattern, /* pattern to match with */
10197 regprog_T **prog, /* pre-compiled regprog or NULL */
10198 char_u *fname, /* full path of file name */
10199 char_u *sfname, /* short file name or NULL */
10200 char_u *tail, /* tail of path */
10201 int allow_dirs) /* allow matching with dir */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010202{
10203 regmatch_T regmatch;
10204 int result = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010205
Bram Moolenaar71afbfe2013-03-19 16:49:16 +010010206 regmatch.rm_ic = p_fic; /* ignore case if 'fileignorecase' is set */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010207 if (prog != NULL)
10208 regmatch.regprog = *prog;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010209 else
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010210 regmatch.regprog = vim_regcomp(pattern, RE_MAGIC);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010211
10212 /*
10213 * Try for a match with the pattern with:
10214 * 1. the full file name, when the pattern has a '/'.
10215 * 2. the short file name, when the pattern has a '/'.
10216 * 3. the tail of the file name, when the pattern has no '/'.
10217 */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010218 if (regmatch.regprog != NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +000010219 && ((allow_dirs
10220 && (vim_regexec(&regmatch, fname, (colnr_T)0)
10221 || (sfname != NULL
10222 && vim_regexec(&regmatch, sfname, (colnr_T)0))))
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010223 || (!allow_dirs && vim_regexec(&regmatch, tail, (colnr_T)0))))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010224 result = TRUE;
10225
Bram Moolenaardffa5b82014-11-19 16:38:07 +010010226 if (prog != NULL)
10227 *prog = regmatch.regprog;
10228 else
Bram Moolenaar473de612013-06-08 18:19:48 +020010229 vim_regfree(regmatch.regprog);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010230 return result;
10231}
10232#endif
10233
10234#if defined(FEAT_WILDIGN) || defined(PROTO)
10235/*
10236 * Return TRUE if a file matches with a pattern in "list".
10237 * "list" is a comma-separated list of patterns, like 'wildignore'.
10238 * "sfname" is the short file name or NULL, "ffname" the long file name.
10239 */
10240 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010241match_file_list(char_u *list, char_u *sfname, char_u *ffname)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010242{
10243 char_u buf[100];
10244 char_u *tail;
10245 char_u *regpat;
10246 char allow_dirs;
10247 int match;
10248 char_u *p;
10249
10250 tail = gettail(sfname);
10251
10252 /* try all patterns in 'wildignore' */
10253 p = list;
10254 while (*p)
10255 {
10256 copy_option_part(&p, buf, 100, ",");
10257 regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, FALSE);
10258 if (regpat == NULL)
10259 break;
Bram Moolenaar748bf032005-02-02 23:04:36 +000010260 match = match_file_pat(regpat, NULL, ffname, sfname,
10261 tail, (int)allow_dirs);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010262 vim_free(regpat);
10263 if (match)
10264 return TRUE;
10265 }
10266 return FALSE;
10267}
10268#endif
10269
10270/*
10271 * Convert the given pattern "pat" which has shell style wildcards in it, into
10272 * a regular expression, and return the result in allocated memory. If there
10273 * is a directory path separator to be matched, then TRUE is put in
10274 * allow_dirs, otherwise FALSE is put there -- webb.
10275 * Handle backslashes before special characters, like "\*" and "\ ".
10276 *
Bram Moolenaar071d4272004-06-13 20:20:40 +000010277 * Returns NULL when out of memory.
10278 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010279 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010280file_pat_to_reg_pat(
10281 char_u *pat,
10282 char_u *pat_end, /* first char after pattern or NULL */
10283 char *allow_dirs, /* Result passed back out in here */
10284 int no_bslash UNUSED) /* Don't use a backward slash as pathsep */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010285{
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010286 int size = 2; /* '^' at start, '$' at end */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010287 char_u *endp;
10288 char_u *reg_pat;
10289 char_u *p;
10290 int i;
10291 int nested = 0;
10292 int add_dollar = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010293
10294 if (allow_dirs != NULL)
10295 *allow_dirs = FALSE;
10296 if (pat_end == NULL)
10297 pat_end = pat + STRLEN(pat);
10298
Bram Moolenaar071d4272004-06-13 20:20:40 +000010299 for (p = pat; p < pat_end; p++)
10300 {
10301 switch (*p)
10302 {
10303 case '*':
10304 case '.':
10305 case ',':
10306 case '{':
10307 case '}':
10308 case '~':
10309 size += 2; /* extra backslash */
10310 break;
10311#ifdef BACKSLASH_IN_FILENAME
10312 case '\\':
10313 case '/':
10314 size += 4; /* could become "[\/]" */
10315 break;
10316#endif
10317 default:
10318 size++;
Bram Moolenaar2288afe2015-08-11 16:20:05 +020010319# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010320 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010321 {
10322 ++p;
10323 ++size;
10324 }
10325# endif
10326 break;
10327 }
10328 }
10329 reg_pat = alloc(size + 1);
10330 if (reg_pat == NULL)
10331 return NULL;
10332
Bram Moolenaar071d4272004-06-13 20:20:40 +000010333 i = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010334
10335 if (pat[0] == '*')
10336 while (pat[0] == '*' && pat < pat_end - 1)
10337 pat++;
10338 else
10339 reg_pat[i++] = '^';
10340 endp = pat_end - 1;
Bram Moolenaar8fee8782015-08-11 18:45:48 +020010341 if (endp >= pat && *endp == '*')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010342 {
10343 while (endp - pat > 0 && *endp == '*')
10344 endp--;
10345 add_dollar = FALSE;
10346 }
10347 for (p = pat; *p && nested >= 0 && p <= endp; p++)
10348 {
10349 switch (*p)
10350 {
10351 case '*':
10352 reg_pat[i++] = '.';
10353 reg_pat[i++] = '*';
Bram Moolenaar02743632005-07-25 20:42:36 +000010354 while (p[1] == '*') /* "**" matches like "*" */
10355 ++p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010356 break;
10357 case '.':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010358 case '~':
10359 reg_pat[i++] = '\\';
10360 reg_pat[i++] = *p;
10361 break;
10362 case '?':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010363 reg_pat[i++] = '.';
10364 break;
10365 case '\\':
10366 if (p[1] == NUL)
10367 break;
10368#ifdef BACKSLASH_IN_FILENAME
10369 if (!no_bslash)
10370 {
10371 /* translate:
10372 * "\x" to "\\x" e.g., "dir\file"
10373 * "\*" to "\\.*" e.g., "dir\*.c"
10374 * "\?" to "\\." e.g., "dir\??.c"
10375 * "\+" to "\+" e.g., "fileX\+.c"
10376 */
10377 if ((vim_isfilec(p[1]) || p[1] == '*' || p[1] == '?')
10378 && p[1] != '+')
10379 {
10380 reg_pat[i++] = '[';
10381 reg_pat[i++] = '\\';
10382 reg_pat[i++] = '/';
10383 reg_pat[i++] = ']';
10384 if (allow_dirs != NULL)
10385 *allow_dirs = TRUE;
10386 break;
10387 }
10388 }
10389#endif
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010390 /* Undo escaping from ExpandEscape():
10391 * foo\?bar -> foo?bar
10392 * foo\%bar -> foo%bar
10393 * foo\,bar -> foo,bar
10394 * foo\ bar -> foo bar
10395 * Don't unescape \, * and others that are also special in a
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010396 * regexp.
10397 * An escaped { must be unescaped since we use magic not
Bram Moolenaara946afe2013-08-02 15:22:39 +020010398 * verymagic. Use "\\\{n,m\}"" to get "\{n,m}".
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010399 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010400 if (*++p == '?'
10401#ifdef BACKSLASH_IN_FILENAME
10402 && no_bslash
10403#endif
10404 )
10405 reg_pat[i++] = '?';
10406 else
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010407 if (*p == ',' || *p == '%' || *p == '#'
Bram Moolenaar2288afe2015-08-11 16:20:05 +020010408 || vim_isspace(*p) || *p == '{' || *p == '}')
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010409 reg_pat[i++] = *p;
Bram Moolenaara946afe2013-08-02 15:22:39 +020010410 else if (*p == '\\' && p[1] == '\\' && p[2] == '{')
10411 {
10412 reg_pat[i++] = '\\';
10413 reg_pat[i++] = '{';
10414 p += 2;
10415 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010416 else
10417 {
10418 if (allow_dirs != NULL && vim_ispathsep(*p)
10419#ifdef BACKSLASH_IN_FILENAME
10420 && (!no_bslash || *p != '\\')
10421#endif
10422 )
10423 *allow_dirs = TRUE;
10424 reg_pat[i++] = '\\';
10425 reg_pat[i++] = *p;
10426 }
10427 break;
10428#ifdef BACKSLASH_IN_FILENAME
10429 case '/':
10430 reg_pat[i++] = '[';
10431 reg_pat[i++] = '\\';
10432 reg_pat[i++] = '/';
10433 reg_pat[i++] = ']';
10434 if (allow_dirs != NULL)
10435 *allow_dirs = TRUE;
10436 break;
10437#endif
10438 case '{':
10439 reg_pat[i++] = '\\';
10440 reg_pat[i++] = '(';
10441 nested++;
10442 break;
10443 case '}':
10444 reg_pat[i++] = '\\';
10445 reg_pat[i++] = ')';
10446 --nested;
10447 break;
10448 case ',':
10449 if (nested)
10450 {
10451 reg_pat[i++] = '\\';
10452 reg_pat[i++] = '|';
10453 }
10454 else
10455 reg_pat[i++] = ',';
10456 break;
10457 default:
10458# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010459 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010460 reg_pat[i++] = *p++;
10461 else
10462# endif
10463 if (allow_dirs != NULL && vim_ispathsep(*p))
10464 *allow_dirs = TRUE;
10465 reg_pat[i++] = *p;
10466 break;
10467 }
10468 }
10469 if (add_dollar)
10470 reg_pat[i++] = '$';
10471 reg_pat[i] = NUL;
10472 if (nested != 0)
10473 {
10474 if (nested < 0)
10475 EMSG(_("E219: Missing {."));
10476 else
10477 EMSG(_("E220: Missing }."));
10478 vim_free(reg_pat);
10479 reg_pat = NULL;
10480 }
10481 return reg_pat;
10482}
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010483
10484#if defined(EINTR) || defined(PROTO)
10485/*
10486 * Version of read() that retries when interrupted by EINTR (possibly
10487 * by a SIGWINCH).
10488 */
10489 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010490read_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010491{
10492 long ret;
10493
10494 for (;;)
10495 {
10496 ret = vim_read(fd, buf, bufsize);
10497 if (ret >= 0 || errno != EINTR)
10498 break;
10499 }
10500 return ret;
10501}
10502
10503/*
10504 * Version of write() that retries when interrupted by EINTR (possibly
10505 * by a SIGWINCH).
10506 */
10507 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010508write_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010509{
10510 long ret = 0;
10511 long wlen;
10512
10513 /* Repeat the write() so long it didn't fail, other than being interrupted
10514 * by a signal. */
10515 while (ret < (long)bufsize)
10516 {
Bram Moolenaar9c263032010-12-17 18:06:06 +010010517 wlen = vim_write(fd, (char *)buf + ret, bufsize - ret);
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010518 if (wlen < 0)
10519 {
10520 if (errno != EINTR)
10521 break;
10522 }
10523 else
10524 ret += wlen;
10525 }
10526 return ret;
10527}
10528#endif