blob: 39e356f88e4e09bf66c84a308266077cd47d8778 [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 {
2254 if (ptr[-1] == CAR) /* remove CR */
2255 {
2256 ptr[-1] = NUL;
2257 --len;
2258 }
2259 /*
2260 * Reading in Dos format, but no CR-LF found!
2261 * When 'fileformats' includes "unix", delete all
2262 * the lines read so far and start all over again.
2263 * Otherwise give an error message later.
2264 */
2265 else if (ff_error != EOL_DOS)
2266 {
2267 if ( try_unix
2268 && !read_stdin
2269 && (read_buffer
Bram Moolenaar8767f522016-07-01 17:17:39 +02002270 || vim_lseek(fd, (off_T)0L, SEEK_SET)
2271 == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002272 {
2273 fileformat = EOL_UNIX;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002274 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002275 set_fileformat(EOL_UNIX, OPT_LOCAL);
2276 file_rewind = TRUE;
2277 keep_fileformat = TRUE;
2278 goto retry;
2279 }
2280 ff_error = EOL_DOS;
2281 }
2282 }
2283 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2284 {
2285 error = TRUE;
2286 break;
2287 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002288#ifdef FEAT_PERSISTENT_UNDO
2289 if (read_undo_file)
2290 sha256_update(&sha_ctx, line_start, len);
2291#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002292 ++lnum;
2293 if (--read_count == 0)
2294 {
2295 error = TRUE; /* break loop */
2296 line_start = ptr; /* nothing left to write */
2297 break;
2298 }
2299 }
2300 else
2301 --skip_count;
2302 line_start = ptr + 1;
2303 }
2304 }
2305 }
2306 linerest = (long)(ptr - line_start);
2307 ui_breakcheck();
2308 }
2309
2310failed:
2311 /* not an error, max. number of lines reached */
2312 if (error && read_count == 0)
2313 error = FALSE;
2314
2315 /*
2316 * If we get EOF in the middle of a line, note the fact and
2317 * complete the line ourselves.
2318 * In Dos format ignore a trailing CTRL-Z, unless 'binary' set.
2319 */
2320 if (!error
2321 && !got_int
2322 && linerest != 0
2323 && !(!curbuf->b_p_bin
2324 && fileformat == EOL_DOS
2325 && *line_start == Ctrl_Z
2326 && ptr == line_start + 1))
2327 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002328 /* remember for when writing */
2329 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002330 curbuf->b_p_eol = FALSE;
2331 *ptr = NUL;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002332 len = (colnr_T)(ptr - line_start + 1);
2333 if (ml_append(lnum, line_start, len, newfile) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002334 error = TRUE;
2335 else
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002336 {
2337#ifdef FEAT_PERSISTENT_UNDO
2338 if (read_undo_file)
2339 sha256_update(&sha_ctx, line_start, len);
2340#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002341 read_no_eol_lnum = ++lnum;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002342 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002343 }
2344
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002345 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002346 save_file_ff(curbuf); /* remember the current file format */
2347
2348#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002349 if (curbuf->b_cryptstate != NULL)
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002350 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002351 crypt_free_state(curbuf->b_cryptstate);
2352 curbuf->b_cryptstate = NULL;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002353 }
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002354 if (cryptkey != NULL && cryptkey != curbuf->b_p_key)
2355 crypt_free_key(cryptkey);
2356 /* Don't set cryptkey to NULL, it's used below as a flag that
2357 * encryption was used. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002358#endif
2359
2360#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002361 /* If editing a new file: set 'fenc' for the current buffer.
2362 * Also for ":read ++edit file". */
2363 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002364 set_string_option_direct((char_u *)"fenc", -1, fenc,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00002365 OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002366 if (fenc_alloced)
2367 vim_free(fenc);
2368# ifdef USE_ICONV
2369 if (iconv_fd != (iconv_t)-1)
2370 {
2371 iconv_close(iconv_fd);
2372 iconv_fd = (iconv_t)-1;
2373 }
2374# endif
2375#endif
2376
2377 if (!read_buffer && !read_stdin)
2378 close(fd); /* errors are ignored */
Bram Moolenaarf05da212009-11-17 16:13:15 +00002379#ifdef HAVE_FD_CLOEXEC
2380 else
2381 {
2382 int fdflags = fcntl(fd, F_GETFD);
2383 if (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0)
Bram Moolenaarfbc4b4d2016-02-07 15:14:01 +01002384 (void)fcntl(fd, F_SETFD, fdflags | FD_CLOEXEC);
Bram Moolenaarf05da212009-11-17 16:13:15 +00002385 }
2386#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002387 vim_free(buffer);
2388
2389#ifdef HAVE_DUP
2390 if (read_stdin)
2391 {
2392 /* Use stderr for stdin, makes shell commands work. */
2393 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00002394 ignored = dup(2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002395 }
2396#endif
2397
2398#ifdef FEAT_MBYTE
2399 if (tmpname != NULL)
2400 {
2401 mch_remove(tmpname); /* delete converted file */
2402 vim_free(tmpname);
2403 }
2404#endif
2405 --no_wait_return; /* may wait for return now */
2406
2407 /*
2408 * In recovery mode everything but autocommands is skipped.
2409 */
2410 if (!recoverymode)
2411 {
2412 /* need to delete the last line, which comes from the empty buffer */
2413 if (newfile && wasempty && !(curbuf->b_ml.ml_flags & ML_EMPTY))
2414 {
2415#ifdef FEAT_NETBEANS_INTG
2416 netbeansFireChanges = 0;
2417#endif
2418 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
2419#ifdef FEAT_NETBEANS_INTG
2420 netbeansFireChanges = 1;
2421#endif
2422 --linecnt;
2423 }
2424 linecnt = curbuf->b_ml.ml_line_count - linecnt;
2425 if (filesize == 0)
2426 linecnt = 0;
2427 if (newfile || read_buffer)
Bram Moolenaar7263a772007-05-10 17:35:54 +00002428 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002429 redraw_curbuf_later(NOT_VALID);
Bram Moolenaar7263a772007-05-10 17:35:54 +00002430#ifdef FEAT_DIFF
2431 /* After reading the text into the buffer the diff info needs to
2432 * be updated. */
2433 diff_invalidate(curbuf);
2434#endif
2435#ifdef FEAT_FOLDING
2436 /* All folds in the window are invalid now. Mark them for update
2437 * before triggering autocommands. */
2438 foldUpdateAll(curwin);
2439#endif
2440 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002441 else if (linecnt) /* appended at least one line */
2442 appended_lines_mark(from, linecnt);
2443
Bram Moolenaar071d4272004-06-13 20:20:40 +00002444#ifndef ALWAYS_USE_GUI
2445 /*
2446 * If we were reading from the same terminal as where messages go,
2447 * the screen will have been messed up.
2448 * Switch on raw mode now and clear the screen.
2449 */
2450 if (read_stdin)
2451 {
2452 settmode(TMODE_RAW); /* set to raw mode */
2453 starttermcap();
2454 screenclear();
2455 }
2456#endif
2457
2458 if (got_int)
2459 {
2460 if (!(flags & READ_DUMMY))
2461 {
2462 filemess(curbuf, sfname, (char_u *)_(e_interr), 0);
2463 if (newfile)
2464 curbuf->b_p_ro = TRUE; /* must use "w!" now */
2465 }
2466 msg_scroll = msg_save;
2467#ifdef FEAT_VIMINFO
2468 check_marks_read();
2469#endif
2470 return OK; /* an interrupt isn't really an error */
2471 }
2472
2473 if (!filtering && !(flags & READ_DUMMY))
2474 {
2475 msg_add_fname(curbuf, sfname); /* fname in IObuff with quotes */
2476 c = FALSE;
2477
2478#ifdef UNIX
2479# ifdef S_ISFIFO
2480 if (S_ISFIFO(perm)) /* fifo or socket */
2481 {
2482 STRCAT(IObuff, _("[fifo/socket]"));
2483 c = TRUE;
2484 }
2485# else
2486# ifdef S_IFIFO
2487 if ((perm & S_IFMT) == S_IFIFO) /* fifo */
2488 {
2489 STRCAT(IObuff, _("[fifo]"));
2490 c = TRUE;
2491 }
2492# endif
2493# ifdef S_IFSOCK
2494 if ((perm & S_IFMT) == S_IFSOCK) /* or socket */
2495 {
2496 STRCAT(IObuff, _("[socket]"));
2497 c = TRUE;
2498 }
2499# endif
2500# endif
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002501# ifdef OPEN_CHR_FILES
2502 if (S_ISCHR(perm)) /* or character special */
2503 {
2504 STRCAT(IObuff, _("[character special]"));
2505 c = TRUE;
2506 }
2507# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002508#endif
2509 if (curbuf->b_p_ro)
2510 {
2511 STRCAT(IObuff, shortmess(SHM_RO) ? _("[RO]") : _("[readonly]"));
2512 c = TRUE;
2513 }
2514 if (read_no_eol_lnum)
2515 {
2516 msg_add_eol();
2517 c = TRUE;
2518 }
2519 if (ff_error == EOL_DOS)
2520 {
2521 STRCAT(IObuff, _("[CR missing]"));
2522 c = TRUE;
2523 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002524 if (split)
2525 {
2526 STRCAT(IObuff, _("[long lines split]"));
2527 c = TRUE;
2528 }
2529#ifdef FEAT_MBYTE
2530 if (notconverted)
2531 {
2532 STRCAT(IObuff, _("[NOT converted]"));
2533 c = TRUE;
2534 }
2535 else if (converted)
2536 {
2537 STRCAT(IObuff, _("[converted]"));
2538 c = TRUE;
2539 }
2540#endif
2541#ifdef FEAT_CRYPT
2542 if (cryptkey != NULL)
2543 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002544 crypt_append_msg(curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002545 c = TRUE;
2546 }
2547#endif
2548#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002549 if (conv_error != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002550 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002551 sprintf((char *)IObuff + STRLEN(IObuff),
2552 _("[CONVERSION ERROR in line %ld]"), (long)conv_error);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002553 c = TRUE;
2554 }
2555 else if (illegal_byte > 0)
2556 {
2557 sprintf((char *)IObuff + STRLEN(IObuff),
2558 _("[ILLEGAL BYTE in line %ld]"), (long)illegal_byte);
2559 c = TRUE;
2560 }
2561 else
2562#endif
2563 if (error)
2564 {
2565 STRCAT(IObuff, _("[READ ERRORS]"));
2566 c = TRUE;
2567 }
2568 if (msg_add_fileformat(fileformat))
2569 c = TRUE;
2570#ifdef FEAT_CRYPT
2571 if (cryptkey != NULL)
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002572 msg_add_lines(c, (long)linecnt, filesize
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002573 - crypt_get_header_len(crypt_get_method_nr(curbuf)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002574 else
2575#endif
2576 msg_add_lines(c, (long)linecnt, filesize);
2577
2578 vim_free(keep_msg);
2579 keep_msg = NULL;
2580 msg_scrolled_ign = TRUE;
2581#ifdef ALWAYS_USE_GUI
2582 /* Don't show the message when reading stdin, it would end up in a
2583 * message box (which might be shown when exiting!) */
2584 if (read_stdin || read_buffer)
2585 p = msg_may_trunc(FALSE, IObuff);
2586 else
2587#endif
2588 p = msg_trunc_attr(IObuff, FALSE, 0);
2589 if (read_stdin || read_buffer || restart_edit != 0
Bram Moolenaar1c7715d2005-10-03 22:02:18 +00002590 || (msg_scrolled != 0 && !need_wait_return))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002591 /* Need to repeat the message after redrawing when:
2592 * - When reading from stdin (the screen will be cleared next).
2593 * - When restart_edit is set (otherwise there will be a delay
2594 * before redrawing).
2595 * - When the screen was scrolled but there is no wait-return
2596 * prompt. */
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002597 set_keep_msg(p, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002598 msg_scrolled_ign = FALSE;
2599 }
2600
2601 /* with errors writing the file requires ":w!" */
2602 if (newfile && (error
2603#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002604 || conv_error != 0
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002605 || (illegal_byte > 0 && bad_char_behavior != BAD_KEEP)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002606#endif
2607 ))
2608 curbuf->b_p_ro = TRUE;
2609
2610 u_clearline(); /* cannot use "U" command after adding lines */
2611
2612 /*
2613 * In Ex mode: cursor at last new line.
2614 * Otherwise: cursor at first new line.
2615 */
2616 if (exmode_active)
2617 curwin->w_cursor.lnum = from + linecnt;
2618 else
2619 curwin->w_cursor.lnum = from + 1;
2620 check_cursor_lnum();
2621 beginline(BL_WHITE | BL_FIX); /* on first non-blank */
2622
2623 /*
2624 * Set '[ and '] marks to the newly read lines.
2625 */
2626 curbuf->b_op_start.lnum = from + 1;
2627 curbuf->b_op_start.col = 0;
2628 curbuf->b_op_end.lnum = from + linecnt;
2629 curbuf->b_op_end.col = 0;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002630
2631#ifdef WIN32
2632 /*
2633 * Work around a weird problem: When a file has two links (only
2634 * possible on NTFS) and we write through one link, then stat() it
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00002635 * through the other link, the timestamp information may be wrong.
Bram Moolenaar03f48552006-02-28 23:52:23 +00002636 * It's correct again after reading the file, thus reset the timestamp
2637 * here.
2638 */
2639 if (newfile && !read_stdin && !read_buffer
2640 && mch_stat((char *)fname, &st) >= 0)
2641 {
2642 buf_store_time(curbuf, &st, fname);
2643 curbuf->b_mtime_read = curbuf->b_mtime;
2644 }
2645#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002646 }
2647 msg_scroll = msg_save;
2648
2649#ifdef FEAT_VIMINFO
2650 /*
2651 * Get the marks before executing autocommands, so they can be used there.
2652 */
2653 check_marks_read();
2654#endif
2655
Bram Moolenaar071d4272004-06-13 20:20:40 +00002656 /*
Bram Moolenaar34d72d42015-07-17 14:18:08 +02002657 * We remember if the last line of the read didn't have
2658 * an eol even when 'binary' is off, to support turning 'fixeol' off,
2659 * or writing the read again with 'binary' on. The latter is required
2660 * for ":autocmd FileReadPost *.gz set bin|'[,']!gunzip" to work.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002661 */
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002662 curbuf->b_no_eol_lnum = read_no_eol_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002663
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02002664 /* When reloading a buffer put the cursor at the first line that is
2665 * different. */
2666 if (flags & READ_KEEP_UNDO)
2667 u_find_first_changed();
2668
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002669#ifdef FEAT_PERSISTENT_UNDO
2670 /*
2671 * When opening a new file locate undo info and read it.
2672 */
2673 if (read_undo_file)
2674 {
2675 char_u hash[UNDO_HASH_SIZE];
2676
2677 sha256_finish(&sha_ctx, hash);
Bram Moolenaar6ed8ed82010-05-30 20:40:11 +02002678 u_read_undo(NULL, hash, fname);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002679 }
2680#endif
2681
Bram Moolenaardf177f62005-02-22 08:39:57 +00002682#ifdef FEAT_AUTOCMD
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02002683 if (!read_stdin && !read_fifo && (!read_buffer || sfname != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002684 {
2685 int m = msg_scroll;
2686 int n = msg_scrolled;
2687
2688 /* Save the fileformat now, otherwise the buffer will be considered
2689 * modified if the format/encoding was automatically detected. */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002690 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002691 save_file_ff(curbuf);
2692
2693 /*
2694 * The output from the autocommands should not overwrite anything and
2695 * should not be overwritten: Set msg_scroll, restore its value if no
2696 * output was done.
2697 */
2698 msg_scroll = TRUE;
2699 if (filtering)
2700 apply_autocmds_exarg(EVENT_FILTERREADPOST, NULL, sfname,
2701 FALSE, curbuf, eap);
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02002702 else if (newfile || (read_buffer && sfname != NULL))
Bram Moolenaarc3691332016-04-20 12:49:49 +02002703 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002704 apply_autocmds_exarg(EVENT_BUFREADPOST, NULL, sfname,
2705 FALSE, curbuf, eap);
Bram Moolenaarc3691332016-04-20 12:49:49 +02002706 if (!au_did_filetype && *curbuf->b_p_ft != NUL)
2707 /*
2708 * EVENT_FILETYPE was not triggered but the buffer already has a
2709 * filetype. Trigger EVENT_FILETYPE using the existing filetype.
2710 */
2711 apply_autocmds(EVENT_FILETYPE, curbuf->b_p_ft, curbuf->b_fname,
2712 TRUE, curbuf);
2713 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002714 else
2715 apply_autocmds_exarg(EVENT_FILEREADPOST, sfname, sfname,
2716 FALSE, NULL, eap);
2717 if (msg_scrolled == n)
2718 msg_scroll = m;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002719# ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002720 if (aborting()) /* autocmds may abort script processing */
2721 return FAIL;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002722# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002723 }
2724#endif
2725
2726 if (recoverymode && error)
2727 return FAIL;
2728 return OK;
2729}
2730
Bram Moolenaarf04507d2016-08-20 15:05:39 +02002731#if defined(OPEN_CHR_FILES) || defined(PROTO)
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002732/*
2733 * Returns TRUE if the file name argument is of the form "/dev/fd/\d\+",
2734 * which is the name of files used for process substitution output by
2735 * some shells on some operating systems, e.g., bash on SunOS.
2736 * Do not accept "/dev/fd/[012]", opening these may hang Vim.
2737 */
Bram Moolenaarf04507d2016-08-20 15:05:39 +02002738 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002739is_dev_fd_file(char_u *fname)
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002740{
2741 return (STRNCMP(fname, "/dev/fd/", 8) == 0
2742 && VIM_ISDIGIT(fname[8])
2743 && *skipdigits(fname + 9) == NUL
2744 && (fname[9] != NUL
2745 || (fname[8] != '0' && fname[8] != '1' && fname[8] != '2')));
2746}
2747#endif
2748
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002749#ifdef FEAT_MBYTE
2750
2751/*
2752 * From the current line count and characters read after that, estimate the
2753 * line number where we are now.
2754 * Used for error messages that include a line number.
2755 */
2756 static linenr_T
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002757readfile_linenr(
2758 linenr_T linecnt, /* line count before reading more bytes */
2759 char_u *p, /* start of more bytes read */
2760 char_u *endp) /* end of more bytes read */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002761{
2762 char_u *s;
2763 linenr_T lnum;
2764
2765 lnum = curbuf->b_ml.ml_line_count - linecnt + 1;
2766 for (s = p; s < endp; ++s)
2767 if (*s == '\n')
2768 ++lnum;
2769 return lnum;
2770}
2771#endif
2772
Bram Moolenaar071d4272004-06-13 20:20:40 +00002773/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00002774 * Fill "*eap" to force the 'fileencoding', 'fileformat' and 'binary to be
2775 * equal to the buffer "buf". Used for calling readfile().
Bram Moolenaar071d4272004-06-13 20:20:40 +00002776 * Returns OK or FAIL.
2777 */
2778 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002779prep_exarg(exarg_T *eap, buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002780{
2781 eap->cmd = alloc((unsigned)(STRLEN(buf->b_p_ff)
2782#ifdef FEAT_MBYTE
2783 + STRLEN(buf->b_p_fenc)
2784#endif
2785 + 15));
2786 if (eap->cmd == NULL)
2787 return FAIL;
2788
2789#ifdef FEAT_MBYTE
2790 sprintf((char *)eap->cmd, "e ++ff=%s ++enc=%s", buf->b_p_ff, buf->b_p_fenc);
2791 eap->force_enc = 14 + (int)STRLEN(buf->b_p_ff);
Bram Moolenaar195d6352005-12-19 22:08:24 +00002792 eap->bad_char = buf->b_bad_char;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002793#else
2794 sprintf((char *)eap->cmd, "e ++ff=%s", buf->b_p_ff);
2795#endif
2796 eap->force_ff = 7;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002797
2798 eap->force_bin = buf->b_p_bin ? FORCE_BIN : FORCE_NOBIN;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002799 eap->read_edit = FALSE;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002800 eap->forceit = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002801 return OK;
2802}
2803
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002804/*
2805 * Set default or forced 'fileformat' and 'binary'.
2806 */
2807 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002808set_file_options(int set_options, exarg_T *eap)
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002809{
2810 /* set default 'fileformat' */
2811 if (set_options)
2812 {
2813 if (eap != NULL && eap->force_ff != 0)
2814 set_fileformat(get_fileformat_force(curbuf, eap), OPT_LOCAL);
2815 else if (*p_ffs != NUL)
2816 set_fileformat(default_fileformat(), OPT_LOCAL);
2817 }
2818
2819 /* set or reset 'binary' */
2820 if (eap != NULL && eap->force_bin != 0)
2821 {
2822 int oldval = curbuf->b_p_bin;
2823
2824 curbuf->b_p_bin = (eap->force_bin == FORCE_BIN);
2825 set_options_bin(oldval, curbuf->b_p_bin, OPT_LOCAL);
2826 }
2827}
2828
2829#if defined(FEAT_MBYTE) || defined(PROTO)
2830/*
2831 * Set forced 'fileencoding'.
2832 */
2833 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002834set_forced_fenc(exarg_T *eap)
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002835{
2836 if (eap->force_enc != 0)
2837 {
2838 char_u *fenc = enc_canonize(eap->cmd + eap->force_enc);
2839
2840 if (fenc != NULL)
2841 set_string_option_direct((char_u *)"fenc", -1,
2842 fenc, OPT_FREE|OPT_LOCAL, 0);
2843 vim_free(fenc);
2844 }
2845}
2846
Bram Moolenaar071d4272004-06-13 20:20:40 +00002847/*
2848 * Find next fileencoding to use from 'fileencodings'.
2849 * "pp" points to fenc_next. It's advanced to the next item.
2850 * When there are no more items, an empty string is returned and *pp is set to
2851 * NULL.
2852 * When *pp is not set to NULL, the result is in allocated memory.
2853 */
2854 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002855next_fenc(char_u **pp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002856{
2857 char_u *p;
2858 char_u *r;
2859
2860 if (**pp == NUL)
2861 {
2862 *pp = NULL;
2863 return (char_u *)"";
2864 }
2865 p = vim_strchr(*pp, ',');
2866 if (p == NULL)
2867 {
2868 r = enc_canonize(*pp);
2869 *pp += STRLEN(*pp);
2870 }
2871 else
2872 {
2873 r = vim_strnsave(*pp, (int)(p - *pp));
2874 *pp = p + 1;
2875 if (r != NULL)
2876 {
2877 p = enc_canonize(r);
2878 vim_free(r);
2879 r = p;
2880 }
2881 }
2882 if (r == NULL) /* out of memory */
2883 {
2884 r = (char_u *)"";
2885 *pp = NULL;
2886 }
2887 return r;
2888}
2889
2890# ifdef FEAT_EVAL
2891/*
2892 * Convert a file with the 'charconvert' expression.
2893 * This closes the file which is to be read, converts it and opens the
2894 * resulting file for reading.
2895 * Returns name of the resulting converted file (the caller should delete it
2896 * after reading it).
2897 * Returns NULL if the conversion failed ("*fdp" is not set) .
2898 */
2899 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002900readfile_charconvert(
2901 char_u *fname, /* name of input file */
2902 char_u *fenc, /* converted from */
2903 int *fdp) /* in/out: file descriptor of file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002904{
2905 char_u *tmpname;
2906 char_u *errmsg = NULL;
2907
Bram Moolenaare5c421c2015-03-31 13:33:08 +02002908 tmpname = vim_tempname('r', FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002909 if (tmpname == NULL)
2910 errmsg = (char_u *)_("Can't find temp file for conversion");
2911 else
2912 {
2913 close(*fdp); /* close the input file, ignore errors */
2914 *fdp = -1;
2915 if (eval_charconvert(fenc, enc_utf8 ? (char_u *)"utf-8" : p_enc,
2916 fname, tmpname) == FAIL)
2917 errmsg = (char_u *)_("Conversion with 'charconvert' failed");
2918 if (errmsg == NULL && (*fdp = mch_open((char *)tmpname,
2919 O_RDONLY | O_EXTRA, 0)) < 0)
2920 errmsg = (char_u *)_("can't read output of 'charconvert'");
2921 }
2922
2923 if (errmsg != NULL)
2924 {
2925 /* Don't use emsg(), it breaks mappings, the retry with
2926 * another type of conversion might still work. */
2927 MSG(errmsg);
2928 if (tmpname != NULL)
2929 {
2930 mch_remove(tmpname); /* delete converted file */
2931 vim_free(tmpname);
2932 tmpname = NULL;
2933 }
2934 }
2935
2936 /* If the input file is closed, open it (caller should check for error). */
2937 if (*fdp < 0)
2938 *fdp = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
2939
2940 return tmpname;
2941}
2942# endif
2943
2944#endif
2945
2946#ifdef FEAT_VIMINFO
2947/*
2948 * Read marks for the current buffer from the viminfo file, when we support
2949 * buffer marks and the buffer has a name.
2950 */
2951 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002952check_marks_read(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002953{
2954 if (!curbuf->b_marks_read && get_viminfo_parameter('\'') > 0
2955 && curbuf->b_ffname != NULL)
Bram Moolenaard812df62008-11-09 12:46:09 +00002956 read_viminfo(NULL, VIF_WANT_MARKS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002957
2958 /* Always set b_marks_read; needed when 'viminfo' is changed to include
2959 * the ' parameter after opening a buffer. */
2960 curbuf->b_marks_read = TRUE;
2961}
2962#endif
2963
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002964#if defined(FEAT_CRYPT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002965/*
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002966 * Check for magic number used for encryption. Applies to the current buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002967 * If found, the magic number is removed from ptr[*sizep] and *sizep and
2968 * *filesizep are updated.
2969 * Return the (new) encryption key, NULL for no encryption.
2970 */
2971 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002972check_for_cryptkey(
2973 char_u *cryptkey, /* previous encryption key or NULL */
2974 char_u *ptr, /* pointer to read bytes */
2975 long *sizep, /* length of read bytes */
Bram Moolenaar8767f522016-07-01 17:17:39 +02002976 off_T *filesizep, /* nr of bytes used from file */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002977 int newfile, /* editing a new buffer */
2978 char_u *fname, /* file name to display */
2979 int *did_ask) /* flag: whether already asked for key */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002980{
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002981 int method = crypt_method_nr_from_magic((char *)ptr, *sizep);
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02002982 int b_p_ro = curbuf->b_p_ro;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002983
2984 if (method >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002985 {
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02002986 /* Mark the buffer as read-only until the decryption has taken place.
2987 * Avoids accidentally overwriting the file with garbage. */
2988 curbuf->b_p_ro = TRUE;
2989
Bram Moolenaar2be79502014-08-13 21:58:28 +02002990 /* Set the cryptmethod local to the buffer. */
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002991 crypt_set_cm_option(curbuf, method);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002992 if (cryptkey == NULL && !*did_ask)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002993 {
2994 if (*curbuf->b_p_key)
2995 cryptkey = curbuf->b_p_key;
2996 else
2997 {
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002998 /* When newfile is TRUE, store the typed key in the 'key'
2999 * option and don't free it. bf needs hash of the key saved.
Bram Moolenaarf50a2532010-05-21 15:36:08 +02003000 * Don't ask for the key again when first time Enter was hit.
3001 * Happens when retrying to detect encoding. */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003002 smsg((char_u *)_(need_key_msg), fname);
3003 msg_scroll = TRUE;
Bram Moolenaar3a0c9082014-11-12 15:15:42 +01003004 crypt_check_method(method);
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003005 cryptkey = crypt_get_key(newfile, FALSE);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02003006 *did_ask = TRUE;
3007
Bram Moolenaar071d4272004-06-13 20:20:40 +00003008 /* check if empty key entered */
3009 if (cryptkey != NULL && *cryptkey == NUL)
3010 {
3011 if (cryptkey != curbuf->b_p_key)
3012 vim_free(cryptkey);
3013 cryptkey = NULL;
3014 }
3015 }
3016 }
3017
3018 if (cryptkey != NULL)
3019 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003020 int header_len;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003021
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003022 curbuf->b_cryptstate = crypt_create_from_header(
3023 method, cryptkey, ptr);
3024 crypt_set_cm_option(curbuf, method);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003025
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003026 /* Remove cryptmethod specific header from the text. */
3027 header_len = crypt_get_header_len(method);
Bram Moolenaar680e0152016-09-25 20:54:11 +02003028 if (*sizep <= header_len)
3029 /* invalid header, buffer can't be encrypted */
3030 return NULL;
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003031 *filesizep += header_len;
3032 *sizep -= header_len;
3033 mch_memmove(ptr, ptr + header_len, (size_t)*sizep);
3034
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02003035 /* Restore the read-only flag. */
3036 curbuf->b_p_ro = b_p_ro;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003037 }
3038 }
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003039 /* When starting to edit a new file which does not have encryption, clear
3040 * the 'key' option, except when starting up (called with -x argument) */
Bram Moolenaarfa0ff9a2010-07-25 16:05:19 +02003041 else if (newfile && *curbuf->b_p_key != NUL && !starting)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003042 set_option_value((char_u *)"key", 0L, (char_u *)"", OPT_LOCAL);
3043
3044 return cryptkey;
3045}
Bram Moolenaar80794b12010-06-13 05:20:42 +02003046#endif /* FEAT_CRYPT */
3047
Bram Moolenaar071d4272004-06-13 20:20:40 +00003048#ifdef UNIX
3049 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003050set_file_time(
3051 char_u *fname,
3052 time_t atime, /* access time */
3053 time_t mtime) /* modification time */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003054{
3055# if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
3056 struct utimbuf buf;
3057
3058 buf.actime = atime;
3059 buf.modtime = mtime;
3060 (void)utime((char *)fname, &buf);
3061# else
3062# if defined(HAVE_UTIMES)
3063 struct timeval tvp[2];
3064
3065 tvp[0].tv_sec = atime;
3066 tvp[0].tv_usec = 0;
3067 tvp[1].tv_sec = mtime;
3068 tvp[1].tv_usec = 0;
3069# ifdef NeXT
3070 (void)utimes((char *)fname, tvp);
3071# else
3072 (void)utimes((char *)fname, (const struct timeval *)&tvp);
3073# endif
3074# endif
3075# endif
3076}
3077#endif /* UNIX */
3078
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003079#if defined(VMS) && !defined(MIN)
3080/* Older DECC compiler for VAX doesn't define MIN() */
3081# define MIN(a, b) ((a) < (b) ? (a) : (b))
3082#endif
3083
Bram Moolenaar071d4272004-06-13 20:20:40 +00003084/*
Bram Moolenaar5386a122007-06-28 20:02:32 +00003085 * Return TRUE if a file appears to be read-only from the file permissions.
3086 */
3087 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003088check_file_readonly(
3089 char_u *fname, /* full path to file */
3090 int perm) /* known permissions on file */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003091{
3092#ifndef USE_MCH_ACCESS
3093 int fd = 0;
3094#endif
3095
3096 return (
3097#ifdef USE_MCH_ACCESS
3098# ifdef UNIX
3099 (perm & 0222) == 0 ||
3100# endif
3101 mch_access((char *)fname, W_OK)
3102#else
3103 (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0
3104 ? TRUE : (close(fd), FALSE)
3105#endif
3106 );
3107}
3108
3109
3110/*
Bram Moolenaar292ad192005-12-11 21:29:51 +00003111 * buf_write() - write to file "fname" lines "start" through "end"
Bram Moolenaar071d4272004-06-13 20:20:40 +00003112 *
3113 * We do our own buffering here because fwrite() is so slow.
3114 *
Bram Moolenaar292ad192005-12-11 21:29:51 +00003115 * If "forceit" is true, we don't care for errors when attempting backups.
3116 * In case of an error everything possible is done to restore the original
Bram Moolenaare37d50a2008-08-06 17:06:04 +00003117 * file. But when "forceit" is TRUE, we risk losing it.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003118 *
3119 * When "reset_changed" is TRUE and "append" == FALSE and "start" == 1 and
3120 * "end" == curbuf->b_ml.ml_line_count, reset curbuf->b_changed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003121 *
3122 * This function must NOT use NameBuff (because it's called by autowrite()).
3123 *
3124 * return FAIL for failure, OK otherwise
3125 */
3126 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003127buf_write(
3128 buf_T *buf,
3129 char_u *fname,
3130 char_u *sfname,
3131 linenr_T start,
3132 linenr_T end,
3133 exarg_T *eap, /* for forced 'ff' and 'fenc', can be
Bram Moolenaar071d4272004-06-13 20:20:40 +00003134 NULL! */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003135 int append, /* append to the file */
3136 int forceit,
3137 int reset_changed,
3138 int filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003139{
3140 int fd;
3141 char_u *backup = NULL;
3142 int backup_copy = FALSE; /* copy the original file? */
3143 int dobackup;
3144 char_u *ffname;
3145 char_u *wfname = NULL; /* name of file to write to */
3146 char_u *s;
3147 char_u *ptr;
3148 char_u c;
3149 int len;
3150 linenr_T lnum;
3151 long nchars;
3152 char_u *errmsg = NULL;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003153 int errmsg_allocated = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003154 char_u *errnum = NULL;
3155 char_u *buffer;
3156 char_u smallbuf[SMBUFSIZE];
3157 char_u *backup_ext;
3158 int bufsize;
3159 long perm; /* file permissions */
3160 int retval = OK;
3161 int newfile = FALSE; /* TRUE if file doesn't exist yet */
3162 int msg_save = msg_scroll;
3163 int overwriting; /* TRUE if writing over original */
3164 int no_eol = FALSE; /* no end-of-line written */
3165 int device = FALSE; /* writing to a device */
Bram Moolenaar8767f522016-07-01 17:17:39 +02003166 stat_T st_old;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003167 int prev_got_int = got_int;
3168 int file_readonly = FALSE; /* overwritten file is read-only */
3169 static char *err_readonly = "is read-only (cannot override: \"W\" in 'cpoptions')";
Bram Moolenaara06ecab2016-07-16 14:47:36 +02003170#if defined(UNIX) /*XXX fix me sometime? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003171 int made_writable = FALSE; /* 'w' bit has been set */
3172#endif
3173 /* writing everything */
3174 int whole = (start == 1 && end == buf->b_ml.ml_line_count);
3175#ifdef FEAT_AUTOCMD
3176 linenr_T old_line_count = buf->b_ml.ml_line_count;
3177#endif
3178 int attr;
3179 int fileformat;
3180 int write_bin;
3181 struct bw_info write_info; /* info for buf_write_bytes() */
3182#ifdef FEAT_MBYTE
3183 int converted = FALSE;
3184 int notconverted = FALSE;
3185 char_u *fenc; /* effective 'fileencoding' */
3186 char_u *fenc_tofree = NULL; /* allocated "fenc" */
3187#endif
3188#ifdef HAS_BW_FLAGS
3189 int wb_flags = 0;
3190#endif
3191#ifdef HAVE_ACL
3192 vim_acl_T acl = NULL; /* ACL copied from original file to
3193 backup or new file */
3194#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003195#ifdef FEAT_PERSISTENT_UNDO
3196 int write_undo_file = FALSE;
3197 context_sha256_T sha_ctx;
3198#endif
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003199 unsigned int bkc = get_bkc_value(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003200
3201 if (fname == NULL || *fname == NUL) /* safety check */
3202 return FAIL;
Bram Moolenaar70d60e92009-12-31 13:53:33 +00003203 if (buf->b_ml.ml_mfp == NULL)
3204 {
3205 /* This can happen during startup when there is a stray "w" in the
3206 * vimrc file. */
3207 EMSG(_(e_emptybuf));
3208 return FAIL;
3209 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003210
3211 /*
3212 * Disallow writing from .exrc and .vimrc in current directory for
3213 * security reasons.
3214 */
3215 if (check_secure())
3216 return FAIL;
3217
3218 /* Avoid a crash for a long name. */
3219 if (STRLEN(fname) >= MAXPATHL)
3220 {
3221 EMSG(_(e_longname));
3222 return FAIL;
3223 }
3224
3225#ifdef FEAT_MBYTE
3226 /* must init bw_conv_buf and bw_iconv_fd before jumping to "fail" */
3227 write_info.bw_conv_buf = NULL;
3228 write_info.bw_conv_error = FALSE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003229 write_info.bw_conv_error_lnum = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003230 write_info.bw_restlen = 0;
3231# ifdef USE_ICONV
3232 write_info.bw_iconv_fd = (iconv_t)-1;
3233# endif
3234#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003235#ifdef FEAT_CRYPT
3236 write_info.bw_buffer = buf;
3237#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003238
Bram Moolenaardf177f62005-02-22 08:39:57 +00003239 /* After writing a file changedtick changes but we don't want to display
3240 * the line. */
3241 ex_no_reprint = TRUE;
3242
Bram Moolenaar071d4272004-06-13 20:20:40 +00003243 /*
3244 * If there is no file name yet, use the one for the written file.
3245 * BF_NOTEDITED is set to reflect this (in case the write fails).
3246 * Don't do this when the write is for a filter command.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003247 * Don't do this when appending.
3248 * Only do this when 'cpoptions' contains the 'F' flag.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003249 */
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003250 if (buf->b_ffname == NULL
3251 && reset_changed
Bram Moolenaar071d4272004-06-13 20:20:40 +00003252 && whole
3253 && buf == curbuf
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00003254#ifdef FEAT_QUICKFIX
3255 && !bt_nofile(buf)
3256#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003257 && !filtering
Bram Moolenaar292ad192005-12-11 21:29:51 +00003258 && (!append || vim_strchr(p_cpo, CPO_FNAMEAPP) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003259 && vim_strchr(p_cpo, CPO_FNAMEW) != NULL)
3260 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003261 if (set_rw_fname(fname, sfname) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003262 return FAIL;
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003263 buf = curbuf; /* just in case autocmds made "buf" invalid */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003264 }
3265
3266 if (sfname == NULL)
3267 sfname = fname;
3268 /*
3269 * For Unix: Use the short file name whenever possible.
3270 * Avoids problems with networks and when directory names are changed.
3271 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
3272 * another directory, which we don't detect
3273 */
3274 ffname = fname; /* remember full fname */
3275#ifdef UNIX
3276 fname = sfname;
3277#endif
3278
3279 if (buf->b_ffname != NULL && fnamecmp(ffname, buf->b_ffname) == 0)
3280 overwriting = TRUE;
3281 else
3282 overwriting = FALSE;
3283
3284 if (exiting)
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003285 settmode(TMODE_COOK); /* when exiting allow typeahead now */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003286
3287 ++no_wait_return; /* don't wait for return yet */
3288
3289 /*
3290 * Set '[ and '] marks to the lines to be written.
3291 */
3292 buf->b_op_start.lnum = start;
3293 buf->b_op_start.col = 0;
3294 buf->b_op_end.lnum = end;
3295 buf->b_op_end.col = 0;
3296
3297#ifdef FEAT_AUTOCMD
3298 {
3299 aco_save_T aco;
3300 int buf_ffname = FALSE;
3301 int buf_sfname = FALSE;
3302 int buf_fname_f = FALSE;
3303 int buf_fname_s = FALSE;
3304 int did_cmd = FALSE;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003305 int nofile_err = FALSE;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003306 int empty_memline = (buf->b_ml.ml_mfp == NULL);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003307 bufref_T bufref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003308
3309 /*
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003310 * Apply PRE autocommands.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003311 * Set curbuf to the buffer to be written.
3312 * Careful: The autocommands may call buf_write() recursively!
3313 */
3314 if (ffname == buf->b_ffname)
3315 buf_ffname = TRUE;
3316 if (sfname == buf->b_sfname)
3317 buf_sfname = TRUE;
3318 if (fname == buf->b_ffname)
3319 buf_fname_f = TRUE;
3320 if (fname == buf->b_sfname)
3321 buf_fname_s = TRUE;
3322
3323 /* set curwin/curbuf to buf and save a few things */
3324 aucmd_prepbuf(&aco, buf);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003325 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003326
3327 if (append)
3328 {
3329 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD,
3330 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003331 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003332#ifdef FEAT_QUICKFIX
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00003333 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003334 nofile_err = TRUE;
3335 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003336#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003337 apply_autocmds_exarg(EVENT_FILEAPPENDPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003338 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003339 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003340 }
3341 else if (filtering)
3342 {
3343 apply_autocmds_exarg(EVENT_FILTERWRITEPRE,
3344 NULL, sfname, FALSE, curbuf, eap);
3345 }
3346 else if (reset_changed && whole)
3347 {
Bram Moolenaar39fc42e2011-09-02 11:56:20 +02003348 int was_changed = curbufIsChanged();
3349
3350 did_cmd = apply_autocmds_exarg(EVENT_BUFWRITECMD,
3351 sfname, sfname, FALSE, curbuf, eap);
3352 if (did_cmd)
3353 {
3354 if (was_changed && !curbufIsChanged())
3355 {
3356 /* Written everything correctly and BufWriteCmd has reset
3357 * 'modified': Correct the undo information so that an
3358 * undo now sets 'modified'. */
3359 u_unchanged(curbuf);
3360 u_update_save_nr(curbuf);
3361 }
3362 }
3363 else
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003364 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003365#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003366 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003367 nofile_err = TRUE;
3368 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003369#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003370 apply_autocmds_exarg(EVENT_BUFWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003371 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003372 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003373 }
3374 else
3375 {
3376 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD,
3377 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003378 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003379#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003380 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003381 nofile_err = TRUE;
3382 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003383#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003384 apply_autocmds_exarg(EVENT_FILEWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003385 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003386 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003387 }
3388
3389 /* restore curwin/curbuf and a few other things */
3390 aucmd_restbuf(&aco);
3391
3392 /*
3393 * In three situations we return here and don't write the file:
3394 * 1. the autocommands deleted or unloaded the buffer.
3395 * 2. The autocommands abort script processing.
3396 * 3. If one of the "Cmd" autocommands was executed.
3397 */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003398 if (!bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003399 buf = NULL;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003400 if (buf == NULL || (buf->b_ml.ml_mfp == NULL && !empty_memline)
Bram Moolenaar1e015462005-09-25 22:16:38 +00003401 || did_cmd || nofile_err
3402#ifdef FEAT_EVAL
3403 || aborting()
3404#endif
3405 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003406 {
3407 --no_wait_return;
3408 msg_scroll = msg_save;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003409 if (nofile_err)
3410 EMSG(_("E676: No matching autocommands for acwrite buffer"));
3411
Bram Moolenaar1e015462005-09-25 22:16:38 +00003412 if (nofile_err
3413#ifdef FEAT_EVAL
3414 || aborting()
3415#endif
3416 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003417 /* An aborting error, interrupt or exception in the
3418 * autocommands. */
3419 return FAIL;
3420 if (did_cmd)
3421 {
3422 if (buf == NULL)
3423 /* The buffer was deleted. We assume it was written
3424 * (can't retry anyway). */
3425 return OK;
3426 if (overwriting)
3427 {
3428 /* Assume the buffer was written, update the timestamp. */
3429 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00003430 if (append)
3431 buf->b_flags &= ~BF_NEW;
3432 else
3433 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003434 }
Bram Moolenaar292ad192005-12-11 21:29:51 +00003435 if (reset_changed && buf->b_changed && !append
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003436 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003437 /* Buffer still changed, the autocommands didn't work
3438 * properly. */
3439 return FAIL;
3440 return OK;
3441 }
3442#ifdef FEAT_EVAL
3443 if (!aborting())
3444#endif
3445 EMSG(_("E203: Autocommands deleted or unloaded buffer to be written"));
3446 return FAIL;
3447 }
3448
3449 /*
3450 * The autocommands may have changed the number of lines in the file.
3451 * When writing the whole file, adjust the end.
3452 * When writing part of the file, assume that the autocommands only
3453 * changed the number of lines that are to be written (tricky!).
3454 */
3455 if (buf->b_ml.ml_line_count != old_line_count)
3456 {
3457 if (whole) /* write all */
3458 end = buf->b_ml.ml_line_count;
3459 else if (buf->b_ml.ml_line_count > old_line_count) /* more lines */
3460 end += buf->b_ml.ml_line_count - old_line_count;
3461 else /* less lines */
3462 {
3463 end -= old_line_count - buf->b_ml.ml_line_count;
3464 if (end < start)
3465 {
3466 --no_wait_return;
3467 msg_scroll = msg_save;
3468 EMSG(_("E204: Autocommand changed number of lines in unexpected way"));
3469 return FAIL;
3470 }
3471 }
3472 }
3473
3474 /*
3475 * The autocommands may have changed the name of the buffer, which may
3476 * be kept in fname, ffname and sfname.
3477 */
3478 if (buf_ffname)
3479 ffname = buf->b_ffname;
3480 if (buf_sfname)
3481 sfname = buf->b_sfname;
3482 if (buf_fname_f)
3483 fname = buf->b_ffname;
3484 if (buf_fname_s)
3485 fname = buf->b_sfname;
3486 }
3487#endif
3488
3489#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003490 if (netbeans_active() && isNetbeansBuffer(buf))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003491 {
3492 if (whole)
3493 {
3494 /*
3495 * b_changed can be 0 after an undo, but we still need to write
3496 * the buffer to NetBeans.
3497 */
3498 if (buf->b_changed || isNetbeansModified(buf))
3499 {
Bram Moolenaar009b2592004-10-24 19:18:58 +00003500 --no_wait_return; /* may wait for return now */
3501 msg_scroll = msg_save;
3502 netbeans_save_buffer(buf); /* no error checking... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003503 return retval;
3504 }
3505 else
3506 {
3507 errnum = (char_u *)"E656: ";
Bram Moolenaared0e7452008-06-27 19:17:34 +00003508 errmsg = (char_u *)_("NetBeans disallows writes of unmodified buffers");
Bram Moolenaar071d4272004-06-13 20:20:40 +00003509 buffer = NULL;
3510 goto fail;
3511 }
3512 }
3513 else
3514 {
3515 errnum = (char_u *)"E657: ";
3516 errmsg = (char_u *)_("Partial writes disallowed for NetBeans buffers");
3517 buffer = NULL;
3518 goto fail;
3519 }
3520 }
3521#endif
3522
3523 if (shortmess(SHM_OVER) && !exiting)
3524 msg_scroll = FALSE; /* overwrite previous file message */
3525 else
3526 msg_scroll = TRUE; /* don't overwrite previous file message */
3527 if (!filtering)
3528 filemess(buf,
3529#ifndef UNIX
3530 sfname,
3531#else
3532 fname,
3533#endif
3534 (char_u *)"", 0); /* show that we are busy */
3535 msg_scroll = FALSE; /* always overwrite the file message now */
3536
3537 buffer = alloc(BUFSIZE);
3538 if (buffer == NULL) /* can't allocate big buffer, use small
3539 * one (to be able to write when out of
3540 * memory) */
3541 {
3542 buffer = smallbuf;
3543 bufsize = SMBUFSIZE;
3544 }
3545 else
3546 bufsize = BUFSIZE;
3547
3548 /*
3549 * Get information about original file (if there is one).
3550 */
Bram Moolenaar53076832015-12-31 19:53:21 +01003551#if defined(UNIX)
Bram Moolenaar6f192452007-11-08 19:49:02 +00003552 st_old.st_dev = 0;
3553 st_old.st_ino = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003554 perm = -1;
3555 if (mch_stat((char *)fname, &st_old) < 0)
3556 newfile = TRUE;
3557 else
3558 {
3559 perm = st_old.st_mode;
3560 if (!S_ISREG(st_old.st_mode)) /* not a file */
3561 {
3562 if (S_ISDIR(st_old.st_mode))
3563 {
3564 errnum = (char_u *)"E502: ";
3565 errmsg = (char_u *)_("is a directory");
3566 goto fail;
3567 }
3568 if (mch_nodetype(fname) != NODE_WRITABLE)
3569 {
3570 errnum = (char_u *)"E503: ";
3571 errmsg = (char_u *)_("is not a file or writable device");
3572 goto fail;
3573 }
3574 /* It's a device of some kind (or a fifo) which we can write to
3575 * but for which we can't make a backup. */
3576 device = TRUE;
3577 newfile = TRUE;
3578 perm = -1;
3579 }
3580 }
3581#else /* !UNIX */
3582 /*
3583 * Check for a writable device name.
3584 */
3585 c = mch_nodetype(fname);
3586 if (c == NODE_OTHER)
3587 {
3588 errnum = (char_u *)"E503: ";
3589 errmsg = (char_u *)_("is not a file or writable device");
3590 goto fail;
3591 }
3592 if (c == NODE_WRITABLE)
3593 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003594# if defined(MSWIN)
Bram Moolenaar043545e2006-10-10 16:44:07 +00003595 /* MS-Windows allows opening a device, but we will probably get stuck
3596 * trying to write to it. */
3597 if (!p_odev)
3598 {
3599 errnum = (char_u *)"E796: ";
3600 errmsg = (char_u *)_("writing to device disabled with 'opendevice' option");
3601 goto fail;
3602 }
3603# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003604 device = TRUE;
3605 newfile = TRUE;
3606 perm = -1;
3607 }
3608 else
3609 {
3610 perm = mch_getperm(fname);
3611 if (perm < 0)
3612 newfile = TRUE;
3613 else if (mch_isdir(fname))
3614 {
3615 errnum = (char_u *)"E502: ";
3616 errmsg = (char_u *)_("is a directory");
3617 goto fail;
3618 }
3619 if (overwriting)
3620 (void)mch_stat((char *)fname, &st_old);
3621 }
3622#endif /* !UNIX */
3623
3624 if (!device && !newfile)
3625 {
3626 /*
3627 * Check if the file is really writable (when renaming the file to
3628 * make a backup we won't discover it later).
3629 */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003630 file_readonly = check_file_readonly(fname, (int)perm);
3631
Bram Moolenaar071d4272004-06-13 20:20:40 +00003632 if (!forceit && file_readonly)
3633 {
3634 if (vim_strchr(p_cpo, CPO_FWRITE) != NULL)
3635 {
3636 errnum = (char_u *)"E504: ";
3637 errmsg = (char_u *)_(err_readonly);
3638 }
3639 else
3640 {
3641 errnum = (char_u *)"E505: ";
3642 errmsg = (char_u *)_("is read-only (add ! to override)");
3643 }
3644 goto fail;
3645 }
3646
3647 /*
3648 * Check if the timestamp hasn't changed since reading the file.
3649 */
3650 if (overwriting)
3651 {
3652 retval = check_mtime(buf, &st_old);
3653 if (retval == FAIL)
3654 goto fail;
3655 }
3656 }
3657
3658#ifdef HAVE_ACL
3659 /*
3660 * For systems that support ACL: get the ACL from the original file.
3661 */
3662 if (!newfile)
3663 acl = mch_get_acl(fname);
3664#endif
3665
3666 /*
3667 * If 'backupskip' is not empty, don't make a backup for some files.
3668 */
3669 dobackup = (p_wb || p_bk || *p_pm != NUL);
3670#ifdef FEAT_WILDIGN
3671 if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname))
3672 dobackup = FALSE;
3673#endif
3674
3675 /*
3676 * Save the value of got_int and reset it. We don't want a previous
3677 * interruption cancel writing, only hitting CTRL-C while writing should
3678 * abort it.
3679 */
3680 prev_got_int = got_int;
3681 got_int = FALSE;
3682
3683 /* Mark the buffer as 'being saved' to prevent changed buffer warnings */
3684 buf->b_saving = TRUE;
3685
3686 /*
3687 * If we are not appending or filtering, the file exists, and the
3688 * 'writebackup', 'backup' or 'patchmode' option is set, need a backup.
3689 * When 'patchmode' is set also make a backup when appending.
3690 *
3691 * Do not make any backup, if 'writebackup' and 'backup' are both switched
3692 * off. This helps when editing large files on almost-full disks.
3693 */
3694 if (!(append && *p_pm == NUL) && !filtering && perm >= 0 && dobackup)
3695 {
3696#if defined(UNIX) || defined(WIN32)
Bram Moolenaar8767f522016-07-01 17:17:39 +02003697 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003698#endif
3699
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003700 if ((bkc & BKC_YES) || append) /* "yes" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003701 backup_copy = TRUE;
3702#if defined(UNIX) || defined(WIN32)
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003703 else if ((bkc & BKC_AUTO)) /* "auto" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003704 {
3705 int i;
3706
3707# ifdef UNIX
3708 /*
3709 * Don't rename the file when:
3710 * - it's a hard link
3711 * - it's a symbolic link
3712 * - we don't have write permission in the directory
3713 * - we can't set the owner/group of the new file
3714 */
3715 if (st_old.st_nlink > 1
3716 || mch_lstat((char *)fname, &st) < 0
3717 || st.st_dev != st_old.st_dev
Bram Moolenaara5792f52005-11-23 21:25:05 +00003718 || st.st_ino != st_old.st_ino
3719# ifndef HAVE_FCHOWN
3720 || st.st_uid != st_old.st_uid
3721 || st.st_gid != st_old.st_gid
3722# endif
3723 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003724 backup_copy = TRUE;
3725 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003726# else
3727# ifdef WIN32
3728 /* On NTFS file systems hard links are possible. */
3729 if (mch_is_linked(fname))
3730 backup_copy = TRUE;
3731 else
3732# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003733# endif
3734 {
3735 /*
3736 * Check if we can create a file and set the owner/group to
3737 * the ones from the original file.
3738 * First find a file name that doesn't exist yet (use some
3739 * arbitrary numbers).
3740 */
3741 STRCPY(IObuff, fname);
3742 for (i = 4913; ; i += 123)
3743 {
3744 sprintf((char *)gettail(IObuff), "%d", i);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003745 if (mch_lstat((char *)IObuff, &st) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003746 break;
3747 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00003748 fd = mch_open((char *)IObuff,
3749 O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003750 if (fd < 0) /* can't write in directory */
3751 backup_copy = TRUE;
3752 else
3753 {
3754# ifdef UNIX
Bram Moolenaara5792f52005-11-23 21:25:05 +00003755# ifdef HAVE_FCHOWN
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00003756 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003757# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003758 if (mch_stat((char *)IObuff, &st) < 0
3759 || st.st_uid != st_old.st_uid
3760 || st.st_gid != st_old.st_gid
Bram Moolenaar78a15312009-05-15 19:33:18 +00003761 || (long)st.st_mode != perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003762 backup_copy = TRUE;
3763# endif
Bram Moolenaar98358622005-11-28 22:58:23 +00003764 /* Close the file before removing it, on MS-Windows we
3765 * can't delete an open file. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003766 close(fd);
Bram Moolenaar98358622005-11-28 22:58:23 +00003767 mch_remove(IObuff);
Bram Moolenaar3479c5d2010-08-08 18:46:06 +02003768# ifdef MSWIN
3769 /* MS-Windows may trigger a virus scanner to open the
3770 * file, we can't delete it then. Keep trying for half a
3771 * second. */
3772 {
3773 int try;
3774
3775 for (try = 0; try < 10; ++try)
3776 {
3777 if (mch_lstat((char *)IObuff, &st) < 0)
3778 break;
3779 ui_delay(50L, TRUE); /* wait 50 msec */
3780 mch_remove(IObuff);
3781 }
3782 }
3783# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003784 }
3785 }
3786 }
3787
Bram Moolenaar071d4272004-06-13 20:20:40 +00003788 /*
3789 * Break symlinks and/or hardlinks if we've been asked to.
3790 */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003791 if ((bkc & BKC_BREAKSYMLINK) || (bkc & BKC_BREAKHARDLINK))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003792 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003793# ifdef UNIX
Bram Moolenaar071d4272004-06-13 20:20:40 +00003794 int lstat_res;
3795
3796 lstat_res = mch_lstat((char *)fname, &st);
3797
3798 /* Symlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003799 if ((bkc & BKC_BREAKSYMLINK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003800 && lstat_res == 0
3801 && st.st_ino != st_old.st_ino)
3802 backup_copy = FALSE;
3803
3804 /* Hardlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003805 if ((bkc & BKC_BREAKHARDLINK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003806 && st_old.st_nlink > 1
3807 && (lstat_res != 0 || st.st_ino == st_old.st_ino))
3808 backup_copy = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003809# else
3810# if defined(WIN32)
3811 /* Symlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003812 if ((bkc & BKC_BREAKSYMLINK) && mch_is_symbolic_link(fname))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003813 backup_copy = FALSE;
3814
3815 /* Hardlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003816 if ((bkc & BKC_BREAKHARDLINK) && mch_is_hard_link(fname))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003817 backup_copy = FALSE;
3818# endif
3819# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003820 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003821
3822#endif
3823
3824 /* make sure we have a valid backup extension to use */
3825 if (*p_bex == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003826 backup_ext = (char_u *)".bak";
Bram Moolenaar071d4272004-06-13 20:20:40 +00003827 else
3828 backup_ext = p_bex;
3829
3830 if (backup_copy
3831 && (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) >= 0)
3832 {
3833 int bfd;
3834 char_u *copybuf, *wp;
3835 int some_error = FALSE;
Bram Moolenaar8767f522016-07-01 17:17:39 +02003836 stat_T st_new;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003837 char_u *dirp;
3838 char_u *rootname;
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003839#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003840 int did_set_shortname;
3841#endif
3842
3843 copybuf = alloc(BUFSIZE + 1);
3844 if (copybuf == NULL)
3845 {
3846 some_error = TRUE; /* out of memory */
3847 goto nobackup;
3848 }
3849
3850 /*
3851 * Try to make the backup in each directory in the 'bdir' option.
3852 *
3853 * Unix semantics has it, that we may have a writable file,
3854 * that cannot be recreated with a simple open(..., O_CREAT, ) e.g:
3855 * - the directory is not writable,
3856 * - the file may be a symbolic link,
3857 * - the file may belong to another user/group, etc.
3858 *
3859 * For these reasons, the existing writable file must be truncated
3860 * and reused. Creation of a backup COPY will be attempted.
3861 */
3862 dirp = p_bdir;
3863 while (*dirp)
3864 {
3865#ifdef UNIX
3866 st_new.st_ino = 0;
3867 st_new.st_dev = 0;
3868 st_new.st_gid = 0;
3869#endif
3870
3871 /*
3872 * Isolate one directory name, using an entry in 'bdir'.
3873 */
3874 (void)copy_option_part(&dirp, copybuf, BUFSIZE, ",");
3875 rootname = get_file_in_dir(fname, copybuf);
3876 if (rootname == NULL)
3877 {
3878 some_error = TRUE; /* out of memory */
3879 goto nobackup;
3880 }
3881
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003882#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003883 did_set_shortname = FALSE;
3884#endif
3885
3886 /*
3887 * May try twice if 'shortname' not set.
3888 */
3889 for (;;)
3890 {
3891 /*
3892 * Make backup file name.
3893 */
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003894 backup = buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003895 rootname, backup_ext, FALSE);
3896 if (backup == NULL)
3897 {
3898 vim_free(rootname);
3899 some_error = TRUE; /* out of memory */
3900 goto nobackup;
3901 }
3902
3903 /*
3904 * Check if backup file already exists.
3905 */
3906 if (mch_stat((char *)backup, &st_new) >= 0)
3907 {
3908#ifdef UNIX
3909 /*
3910 * Check if backup file is same as original file.
3911 * May happen when modname() gave the same file back.
3912 * E.g. silly link, or file name-length reached.
3913 * If we don't check here, we either ruin the file
3914 * when copying or erase it after writing. jw.
3915 */
3916 if (st_new.st_dev == st_old.st_dev
3917 && st_new.st_ino == st_old.st_ino)
3918 {
3919 vim_free(backup);
3920 backup = NULL; /* no backup file to delete */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003921 /*
3922 * may try again with 'shortname' set
3923 */
3924 if (!(buf->b_shortname || buf->b_p_sn))
3925 {
3926 buf->b_shortname = TRUE;
3927 did_set_shortname = TRUE;
3928 continue;
3929 }
3930 /* setting shortname didn't help */
3931 if (did_set_shortname)
3932 buf->b_shortname = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003933 break;
3934 }
3935#endif
3936
3937 /*
3938 * If we are not going to keep the backup file, don't
3939 * delete an existing one, try to use another name.
3940 * Change one character, just before the extension.
3941 */
3942 if (!p_bk)
3943 {
3944 wp = backup + STRLEN(backup) - 1
3945 - STRLEN(backup_ext);
3946 if (wp < backup) /* empty file name ??? */
3947 wp = backup;
3948 *wp = 'z';
3949 while (*wp > 'a'
3950 && mch_stat((char *)backup, &st_new) >= 0)
3951 --*wp;
3952 /* They all exist??? Must be something wrong. */
3953 if (*wp == 'a')
3954 {
3955 vim_free(backup);
3956 backup = NULL;
3957 }
3958 }
3959 }
3960 break;
3961 }
3962 vim_free(rootname);
3963
3964 /*
3965 * Try to create the backup file
3966 */
3967 if (backup != NULL)
3968 {
3969 /* remove old backup, if present */
3970 mch_remove(backup);
3971 /* Open with O_EXCL to avoid the file being created while
3972 * we were sleeping (symlink hacker attack?) */
3973 bfd = mch_open((char *)backup,
Bram Moolenaara5792f52005-11-23 21:25:05 +00003974 O_WRONLY|O_CREAT|O_EXTRA|O_EXCL|O_NOFOLLOW,
3975 perm & 0777);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003976 if (bfd < 0)
3977 {
3978 vim_free(backup);
3979 backup = NULL;
3980 }
3981 else
3982 {
3983 /* set file protection same as original file, but
3984 * strip s-bit */
3985 (void)mch_setperm(backup, perm & 0777);
3986
3987#ifdef UNIX
3988 /*
3989 * Try to set the group of the backup same as the
3990 * original file. If this fails, set the protection
3991 * bits for the group same as the protection bits for
3992 * others.
3993 */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003994 if (st_new.st_gid != st_old.st_gid
Bram Moolenaar071d4272004-06-13 20:20:40 +00003995# ifdef HAVE_FCHOWN /* sequent-ptx lacks fchown() */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003996 && fchown(bfd, (uid_t)-1, st_old.st_gid) != 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00003997# endif
3998 )
3999 mch_setperm(backup,
4000 (perm & 0707) | ((perm & 07) << 3));
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004001# if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004002 mch_copy_sec(fname, backup);
4003# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004004#endif
4005
4006 /*
4007 * copy the file.
4008 */
4009 write_info.bw_fd = bfd;
4010 write_info.bw_buf = copybuf;
4011#ifdef HAS_BW_FLAGS
4012 write_info.bw_flags = FIO_NOCONVERT;
4013#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004014 while ((write_info.bw_len = read_eintr(fd, copybuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004015 BUFSIZE)) > 0)
4016 {
4017 if (buf_write_bytes(&write_info) == FAIL)
4018 {
4019 errmsg = (char_u *)_("E506: Can't write to backup file (add ! to override)");
4020 break;
4021 }
4022 ui_breakcheck();
4023 if (got_int)
4024 {
4025 errmsg = (char_u *)_(e_interr);
4026 break;
4027 }
4028 }
4029
4030 if (close(bfd) < 0 && errmsg == NULL)
4031 errmsg = (char_u *)_("E507: Close error for backup file (add ! to override)");
4032 if (write_info.bw_len < 0)
4033 errmsg = (char_u *)_("E508: Can't read file for backup (add ! to override)");
4034#ifdef UNIX
4035 set_file_time(backup, st_old.st_atime, st_old.st_mtime);
4036#endif
4037#ifdef HAVE_ACL
4038 mch_set_acl(backup, acl);
4039#endif
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004040#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004041 mch_copy_sec(fname, backup);
4042#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004043 break;
4044 }
4045 }
4046 }
4047 nobackup:
4048 close(fd); /* ignore errors for closing read file */
4049 vim_free(copybuf);
4050
4051 if (backup == NULL && errmsg == NULL)
4052 errmsg = (char_u *)_("E509: Cannot create backup file (add ! to override)");
4053 /* ignore errors when forceit is TRUE */
4054 if ((some_error || errmsg != NULL) && !forceit)
4055 {
4056 retval = FAIL;
4057 goto fail;
4058 }
4059 errmsg = NULL;
4060 }
4061 else
4062 {
4063 char_u *dirp;
4064 char_u *p;
4065 char_u *rootname;
4066
4067 /*
4068 * Make a backup by renaming the original file.
4069 */
4070 /*
4071 * If 'cpoptions' includes the "W" flag, we don't want to
4072 * overwrite a read-only file. But rename may be possible
4073 * anyway, thus we need an extra check here.
4074 */
4075 if (file_readonly && vim_strchr(p_cpo, CPO_FWRITE) != NULL)
4076 {
4077 errnum = (char_u *)"E504: ";
4078 errmsg = (char_u *)_(err_readonly);
4079 goto fail;
4080 }
4081
4082 /*
4083 *
4084 * Form the backup file name - change path/fo.o.h to
4085 * path/fo.o.h.bak Try all directories in 'backupdir', first one
4086 * that works is used.
4087 */
4088 dirp = p_bdir;
4089 while (*dirp)
4090 {
4091 /*
4092 * Isolate one directory name and make the backup file name.
4093 */
4094 (void)copy_option_part(&dirp, IObuff, IOSIZE, ",");
4095 rootname = get_file_in_dir(fname, IObuff);
4096 if (rootname == NULL)
4097 backup = NULL;
4098 else
4099 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01004100 backup = buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00004101 rootname, backup_ext, FALSE);
4102 vim_free(rootname);
4103 }
4104
4105 if (backup != NULL)
4106 {
4107 /*
4108 * If we are not going to keep the backup file, don't
4109 * delete an existing one, try to use another name.
4110 * Change one character, just before the extension.
4111 */
4112 if (!p_bk && mch_getperm(backup) >= 0)
4113 {
4114 p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext);
4115 if (p < backup) /* empty file name ??? */
4116 p = backup;
4117 *p = 'z';
4118 while (*p > 'a' && mch_getperm(backup) >= 0)
4119 --*p;
4120 /* They all exist??? Must be something wrong! */
4121 if (*p == 'a')
4122 {
4123 vim_free(backup);
4124 backup = NULL;
4125 }
4126 }
4127 }
4128 if (backup != NULL)
4129 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004130 /*
Bram Moolenaarbfd8fc02005-09-20 23:22:24 +00004131 * Delete any existing backup and move the current version
4132 * to the backup. For safety, we don't remove the backup
4133 * until the write has finished successfully. And if the
4134 * 'backup' option is set, leave it around.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004135 */
4136 /*
4137 * If the renaming of the original file to the backup file
4138 * works, quit here.
4139 */
4140 if (vim_rename(fname, backup) == 0)
4141 break;
4142
4143 vim_free(backup); /* don't do the rename below */
4144 backup = NULL;
4145 }
4146 }
4147 if (backup == NULL && !forceit)
4148 {
4149 errmsg = (char_u *)_("E510: Can't make backup file (add ! to override)");
4150 goto fail;
4151 }
4152 }
4153 }
4154
Bram Moolenaar53076832015-12-31 19:53:21 +01004155#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004156 /* When using ":w!" and the file was read-only: make it writable */
4157 if (forceit && perm >= 0 && !(perm & 0200) && st_old.st_uid == getuid()
4158 && vim_strchr(p_cpo, CPO_FWRITE) == NULL)
4159 {
4160 perm |= 0200;
4161 (void)mch_setperm(fname, perm);
4162 made_writable = TRUE;
4163 }
4164#endif
4165
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004166 /* When using ":w!" and writing to the current file, 'readonly' makes no
Bram Moolenaar4399ef42005-02-12 14:29:27 +00004167 * sense, reset it, unless 'Z' appears in 'cpoptions'. */
4168 if (forceit && overwriting && vim_strchr(p_cpo, CPO_KEEPRO) == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004169 {
4170 buf->b_p_ro = FALSE;
4171#ifdef FEAT_TITLE
4172 need_maketitle = TRUE; /* set window title later */
4173#endif
4174#ifdef FEAT_WINDOWS
4175 status_redraw_all(); /* redraw status lines later */
4176#endif
4177 }
4178
4179 if (end > buf->b_ml.ml_line_count)
4180 end = buf->b_ml.ml_line_count;
4181 if (buf->b_ml.ml_flags & ML_EMPTY)
4182 start = end + 1;
4183
4184 /*
4185 * If the original file is being overwritten, there is a small chance that
4186 * we crash in the middle of writing. Therefore the file is preserved now.
4187 * This makes all block numbers positive so that recovery does not need
4188 * the original file.
4189 * Don't do this if there is a backup file and we are exiting.
4190 */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004191 if (reset_changed && !newfile && overwriting
Bram Moolenaar071d4272004-06-13 20:20:40 +00004192 && !(exiting && backup != NULL))
4193 {
4194 ml_preserve(buf, FALSE);
4195 if (got_int)
4196 {
4197 errmsg = (char_u *)_(e_interr);
4198 goto restore_backup;
4199 }
4200 }
4201
4202#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
4203 /*
4204 * Before risking to lose the original file verify if there's
4205 * a resource fork to preserve, and if cannot be done warn
4206 * the users. This happens when overwriting without backups.
4207 */
4208 if (backup == NULL && overwriting && !append)
4209 if (mch_has_resource_fork(fname))
4210 {
4211 errmsg = (char_u *)_("E460: The resource fork would be lost (add ! to override)");
4212 goto restore_backup;
4213 }
4214#endif
4215
4216#ifdef VMS
4217 vms_remove_version(fname); /* remove version */
4218#endif
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00004219 /* Default: write the file directly. May write to a temp file for
Bram Moolenaar071d4272004-06-13 20:20:40 +00004220 * multi-byte conversion. */
4221 wfname = fname;
4222
4223#ifdef FEAT_MBYTE
4224 /* Check for forced 'fileencoding' from "++opt=val" argument. */
4225 if (eap != NULL && eap->force_enc != 0)
4226 {
4227 fenc = eap->cmd + eap->force_enc;
4228 fenc = enc_canonize(fenc);
4229 fenc_tofree = fenc;
4230 }
4231 else
4232 fenc = buf->b_p_fenc;
4233
4234 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004235 * Check if the file needs to be converted.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004236 */
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004237 converted = need_conversion(fenc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004238
4239 /*
4240 * Check if UTF-8 to UCS-2/4 or Latin1 conversion needs to be done. Or
4241 * Latin1 to Unicode conversion. This is handled in buf_write_bytes().
4242 * Prepare the flags for it and allocate bw_conv_buf when needed.
4243 */
4244 if (converted && (enc_utf8 || STRCMP(p_enc, "latin1") == 0))
4245 {
4246 wb_flags = get_fio_flags(fenc);
4247 if (wb_flags & (FIO_UCS2 | FIO_UCS4 | FIO_UTF16 | FIO_UTF8))
4248 {
4249 /* Need to allocate a buffer to translate into. */
4250 if (wb_flags & (FIO_UCS2 | FIO_UTF16 | FIO_UTF8))
4251 write_info.bw_conv_buflen = bufsize * 2;
4252 else /* FIO_UCS4 */
4253 write_info.bw_conv_buflen = bufsize * 4;
4254 write_info.bw_conv_buf
4255 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4256 if (write_info.bw_conv_buf == NULL)
4257 end = 0;
4258 }
4259 }
4260
4261# ifdef WIN3264
4262 if (converted && wb_flags == 0 && (wb_flags = get_win_fio_flags(fenc)) != 0)
4263 {
4264 /* Convert UTF-8 -> UCS-2 and UCS-2 -> DBCS. Worst-case * 4: */
4265 write_info.bw_conv_buflen = bufsize * 4;
4266 write_info.bw_conv_buf
4267 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4268 if (write_info.bw_conv_buf == NULL)
4269 end = 0;
4270 }
4271# endif
4272
4273# ifdef MACOS_X
4274 if (converted && wb_flags == 0 && (wb_flags = get_mac_fio_flags(fenc)) != 0)
4275 {
4276 write_info.bw_conv_buflen = bufsize * 3;
4277 write_info.bw_conv_buf
4278 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4279 if (write_info.bw_conv_buf == NULL)
4280 end = 0;
4281 }
4282# endif
4283
4284# if defined(FEAT_EVAL) || defined(USE_ICONV)
4285 if (converted && wb_flags == 0)
4286 {
4287# ifdef USE_ICONV
4288 /*
4289 * Use iconv() conversion when conversion is needed and it's not done
4290 * internally.
4291 */
4292 write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc,
4293 enc_utf8 ? (char_u *)"utf-8" : p_enc);
4294 if (write_info.bw_iconv_fd != (iconv_t)-1)
4295 {
4296 /* We're going to use iconv(), allocate a buffer to convert in. */
4297 write_info.bw_conv_buflen = bufsize * ICONV_MULT;
4298 write_info.bw_conv_buf
4299 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4300 if (write_info.bw_conv_buf == NULL)
4301 end = 0;
4302 write_info.bw_first = TRUE;
4303 }
4304# ifdef FEAT_EVAL
4305 else
4306# endif
4307# endif
4308
4309# ifdef FEAT_EVAL
4310 /*
4311 * When the file needs to be converted with 'charconvert' after
4312 * writing, write to a temp file instead and let the conversion
4313 * overwrite the original file.
4314 */
4315 if (*p_ccv != NUL)
4316 {
Bram Moolenaare5c421c2015-03-31 13:33:08 +02004317 wfname = vim_tempname('w', FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004318 if (wfname == NULL) /* Can't write without a tempfile! */
4319 {
4320 errmsg = (char_u *)_("E214: Can't find temp file for writing");
4321 goto restore_backup;
4322 }
4323 }
4324# endif
4325 }
4326# endif
4327 if (converted && wb_flags == 0
4328# ifdef USE_ICONV
4329 && write_info.bw_iconv_fd == (iconv_t)-1
4330# endif
4331# ifdef FEAT_EVAL
4332 && wfname == fname
4333# endif
4334 )
4335 {
4336 if (!forceit)
4337 {
4338 errmsg = (char_u *)_("E213: Cannot convert (add ! to write without conversion)");
4339 goto restore_backup;
4340 }
4341 notconverted = TRUE;
4342 }
4343#endif
4344
4345 /*
4346 * Open the file "wfname" for writing.
4347 * We may try to open the file twice: If we can't write to the
4348 * file and forceit is TRUE we delete the existing file and try to create
4349 * a new one. If this still fails we may have lost the original file!
4350 * (this may happen when the user reached his quotum for number of files).
4351 * Appending will fail if the file does not exist and forceit is FALSE.
4352 */
4353 while ((fd = mch_open((char *)wfname, O_WRONLY | O_EXTRA | (append
4354 ? (forceit ? (O_APPEND | O_CREAT) : O_APPEND)
4355 : (O_CREAT | O_TRUNC))
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00004356 , perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004357 {
4358 /*
4359 * A forced write will try to create a new file if the old one is
4360 * still readonly. This may also happen when the directory is
4361 * read-only. In that case the mch_remove() will fail.
4362 */
4363 if (errmsg == NULL)
4364 {
4365#ifdef UNIX
Bram Moolenaar8767f522016-07-01 17:17:39 +02004366 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004367
4368 /* Don't delete the file when it's a hard or symbolic link. */
4369 if ((!newfile && st_old.st_nlink > 1)
4370 || (mch_lstat((char *)fname, &st) == 0
4371 && (st.st_dev != st_old.st_dev
4372 || st.st_ino != st_old.st_ino)))
4373 errmsg = (char_u *)_("E166: Can't open linked file for writing");
4374 else
4375#endif
4376 {
4377 errmsg = (char_u *)_("E212: Can't open file for writing");
4378 if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL
4379 && perm >= 0)
4380 {
4381#ifdef UNIX
4382 /* we write to the file, thus it should be marked
4383 writable after all */
4384 if (!(perm & 0200))
4385 made_writable = TRUE;
4386 perm |= 0200;
4387 if (st_old.st_uid != getuid() || st_old.st_gid != getgid())
4388 perm &= 0777;
4389#endif
4390 if (!append) /* don't remove when appending */
4391 mch_remove(wfname);
4392 continue;
4393 }
4394 }
4395 }
4396
4397restore_backup:
4398 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02004399 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004400
4401 /*
4402 * If we failed to open the file, we don't need a backup. Throw it
4403 * away. If we moved or removed the original file try to put the
4404 * backup in its place.
4405 */
4406 if (backup != NULL && wfname == fname)
4407 {
4408 if (backup_copy)
4409 {
4410 /*
4411 * There is a small chance that we removed the original,
4412 * try to move the copy in its place.
4413 * This may not work if the vim_rename() fails.
4414 * In that case we leave the copy around.
4415 */
4416 /* If file does not exist, put the copy in its place */
4417 if (mch_stat((char *)fname, &st) < 0)
4418 vim_rename(backup, fname);
4419 /* if original file does exist throw away the copy */
4420 if (mch_stat((char *)fname, &st) >= 0)
4421 mch_remove(backup);
4422 }
4423 else
4424 {
4425 /* try to put the original file back */
4426 vim_rename(backup, fname);
4427 }
4428 }
4429
4430 /* if original file no longer exists give an extra warning */
4431 if (!newfile && mch_stat((char *)fname, &st) < 0)
4432 end = 0;
4433 }
4434
4435#ifdef FEAT_MBYTE
4436 if (wfname != fname)
4437 vim_free(wfname);
4438#endif
4439 goto fail;
4440 }
4441 errmsg = NULL;
4442
4443#if defined(MACOS_CLASSIC) || defined(WIN3264)
4444 /* TODO: Is it need for MACOS_X? (Dany) */
4445 /*
4446 * On macintosh copy the original files attributes (i.e. the backup)
Bram Moolenaar7263a772007-05-10 17:35:54 +00004447 * This is done in order to preserve the resource fork and the
4448 * Finder attribute (label, comments, custom icons, file creator)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004449 */
4450 if (backup != NULL && overwriting && !append)
4451 {
4452 if (backup_copy)
4453 (void)mch_copy_file_attribute(wfname, backup);
4454 else
4455 (void)mch_copy_file_attribute(backup, wfname);
4456 }
4457
4458 if (!overwriting && !append)
4459 {
4460 if (buf->b_ffname != NULL)
4461 (void)mch_copy_file_attribute(buf->b_ffname, wfname);
Bram Moolenaar7263a772007-05-10 17:35:54 +00004462 /* Should copy resource fork */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004463 }
4464#endif
4465
4466 write_info.bw_fd = fd;
4467
4468#ifdef FEAT_CRYPT
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004469 if (*buf->b_p_key != NUL && !filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004470 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004471 char_u *header;
4472 int header_len;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004473
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004474 buf->b_cryptstate = crypt_create_for_writing(crypt_get_method_nr(buf),
4475 buf->b_p_key, &header, &header_len);
4476 if (buf->b_cryptstate == NULL || header == NULL)
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02004477 end = 0;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004478 else
4479 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004480 /* Write magic number, so that Vim knows how this file is
4481 * encrypted when reading it back. */
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02004482 write_info.bw_buf = header;
4483 write_info.bw_len = header_len;
4484 write_info.bw_flags = FIO_NOCONVERT;
4485 if (buf_write_bytes(&write_info) == FAIL)
4486 end = 0;
4487 wb_flags |= FIO_ENCRYPTED;
4488 vim_free(header);
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004489 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004490 }
4491#endif
4492
4493 write_info.bw_buf = buffer;
4494 nchars = 0;
4495
4496 /* use "++bin", "++nobin" or 'binary' */
4497 if (eap != NULL && eap->force_bin != 0)
4498 write_bin = (eap->force_bin == FORCE_BIN);
4499 else
4500 write_bin = buf->b_p_bin;
4501
4502#ifdef FEAT_MBYTE
4503 /*
4504 * The BOM is written just after the encryption magic number.
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004505 * Skip it when appending and the file already existed, the BOM only makes
4506 * sense at the start of the file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004507 */
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004508 if (buf->b_p_bomb && !write_bin && (!append || perm < 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004509 {
4510 write_info.bw_len = make_bom(buffer, fenc);
4511 if (write_info.bw_len > 0)
4512 {
4513 /* don't convert, do encryption */
4514 write_info.bw_flags = FIO_NOCONVERT | wb_flags;
4515 if (buf_write_bytes(&write_info) == FAIL)
4516 end = 0;
4517 else
4518 nchars += write_info.bw_len;
4519 }
4520 }
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004521 write_info.bw_start_lnum = start;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004522#endif
4523
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004524#ifdef FEAT_PERSISTENT_UNDO
4525 write_undo_file = (buf->b_p_udf && overwriting && !append
4526 && !filtering && reset_changed);
4527 if (write_undo_file)
4528 /* Prepare for computing the hash value of the text. */
4529 sha256_start(&sha_ctx);
4530#endif
4531
Bram Moolenaar071d4272004-06-13 20:20:40 +00004532 write_info.bw_len = bufsize;
4533#ifdef HAS_BW_FLAGS
4534 write_info.bw_flags = wb_flags;
4535#endif
4536 fileformat = get_fileformat_force(buf, eap);
4537 s = buffer;
4538 len = 0;
4539 for (lnum = start; lnum <= end; ++lnum)
4540 {
4541 /*
4542 * The next while loop is done once for each character written.
4543 * Keep it fast!
4544 */
4545 ptr = ml_get_buf(buf, lnum, FALSE) - 1;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004546#ifdef FEAT_PERSISTENT_UNDO
4547 if (write_undo_file)
Bram Moolenaar442b4222010-05-24 21:34:22 +02004548 sha256_update(&sha_ctx, ptr + 1, (UINT32_T)(STRLEN(ptr + 1) + 1));
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004549#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004550 while ((c = *++ptr) != NUL)
4551 {
4552 if (c == NL)
4553 *s = NUL; /* replace newlines with NULs */
4554 else if (c == CAR && fileformat == EOL_MAC)
4555 *s = NL; /* Mac: replace CRs with NLs */
4556 else
4557 *s = c;
4558 ++s;
4559 if (++len != bufsize)
4560 continue;
4561 if (buf_write_bytes(&write_info) == FAIL)
4562 {
4563 end = 0; /* write error: break loop */
4564 break;
4565 }
4566 nchars += bufsize;
4567 s = buffer;
4568 len = 0;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004569#ifdef FEAT_MBYTE
4570 write_info.bw_start_lnum = lnum;
4571#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004572 }
4573 /* write failed or last line has no EOL: stop here */
4574 if (end == 0
4575 || (lnum == end
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004576 && (write_bin || !buf->b_p_fixeol)
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004577 && (lnum == buf->b_no_eol_lnum
Bram Moolenaar071d4272004-06-13 20:20:40 +00004578 || (lnum == buf->b_ml.ml_line_count && !buf->b_p_eol))))
4579 {
4580 ++lnum; /* written the line, count it */
4581 no_eol = TRUE;
4582 break;
4583 }
4584 if (fileformat == EOL_UNIX)
4585 *s++ = NL;
4586 else
4587 {
4588 *s++ = CAR; /* EOL_MAC or EOL_DOS: write CR */
4589 if (fileformat == EOL_DOS) /* write CR-NL */
4590 {
4591 if (++len == bufsize)
4592 {
4593 if (buf_write_bytes(&write_info) == FAIL)
4594 {
4595 end = 0; /* write error: break loop */
4596 break;
4597 }
4598 nchars += bufsize;
4599 s = buffer;
4600 len = 0;
4601 }
4602 *s++ = NL;
4603 }
4604 }
4605 if (++len == bufsize && end)
4606 {
4607 if (buf_write_bytes(&write_info) == FAIL)
4608 {
4609 end = 0; /* write error: break loop */
4610 break;
4611 }
4612 nchars += bufsize;
4613 s = buffer;
4614 len = 0;
4615
4616 ui_breakcheck();
4617 if (got_int)
4618 {
4619 end = 0; /* Interrupted, break loop */
4620 break;
4621 }
4622 }
4623#ifdef VMS
4624 /*
4625 * On VMS there is a problem: newlines get added when writing blocks
4626 * at a time. Fix it by writing a line at a time.
4627 * This is much slower!
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004628 * Explanation: VAX/DECC RTL insists that records in some RMS
4629 * structures end with a newline (carriage return) character, and if
4630 * they don't it adds one.
4631 * With other RMS structures it works perfect without this fix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004632 */
Bram Moolenaarb52e2602007-10-29 21:38:54 +00004633 if (buf->b_fab_rfm == FAB$C_VFC
4634 || ((buf->b_fab_rat & (FAB$M_FTN | FAB$M_CR)) != 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004635 {
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004636 int b2write;
4637
4638 buf->b_fab_mrs = (buf->b_fab_mrs == 0
4639 ? MIN(4096, bufsize)
4640 : MIN(buf->b_fab_mrs, bufsize));
4641
4642 b2write = len;
4643 while (b2write > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004644 {
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004645 write_info.bw_len = MIN(b2write, buf->b_fab_mrs);
4646 if (buf_write_bytes(&write_info) == FAIL)
4647 {
4648 end = 0;
4649 break;
4650 }
4651 b2write -= MIN(b2write, buf->b_fab_mrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004652 }
4653 write_info.bw_len = bufsize;
4654 nchars += len;
4655 s = buffer;
4656 len = 0;
4657 }
4658#endif
4659 }
4660 if (len > 0 && end > 0)
4661 {
4662 write_info.bw_len = len;
4663 if (buf_write_bytes(&write_info) == FAIL)
4664 end = 0; /* write error */
4665 nchars += len;
4666 }
4667
4668#if defined(UNIX) && defined(HAVE_FSYNC)
4669 /* On many journalling file systems there is a bug that causes both the
4670 * original and the backup file to be lost when halting the system right
4671 * after writing the file. That's because only the meta-data is
4672 * journalled. Syncing the file slows down the system, but assures it has
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004673 * been written to disk and we don't lose it.
4674 * For a device do try the fsync() but don't complain if it does not work
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00004675 * (could be a pipe).
4676 * If the 'fsync' option is FALSE, don't fsync(). Useful for laptops. */
4677 if (p_fs && fsync(fd) != 0 && !device)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004678 {
4679 errmsg = (char_u *)_("E667: Fsync failed");
4680 end = 0;
4681 }
4682#endif
4683
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004684#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004685 /* Probably need to set the security context. */
4686 if (!backup_copy)
4687 mch_copy_sec(backup, wfname);
4688#endif
4689
Bram Moolenaara5792f52005-11-23 21:25:05 +00004690#ifdef UNIX
4691 /* When creating a new file, set its owner/group to that of the original
4692 * file. Get the new device and inode number. */
4693 if (backup != NULL && !backup_copy)
4694 {
4695# ifdef HAVE_FCHOWN
Bram Moolenaar8767f522016-07-01 17:17:39 +02004696 stat_T st;
Bram Moolenaara5792f52005-11-23 21:25:05 +00004697
4698 /* don't change the owner when it's already OK, some systems remove
4699 * permission or ACL stuff */
4700 if (mch_stat((char *)wfname, &st) < 0
4701 || st.st_uid != st_old.st_uid
4702 || st.st_gid != st_old.st_gid)
4703 {
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004704 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004705 if (perm >= 0) /* set permission again, may have changed */
4706 (void)mch_setperm(wfname, perm);
4707 }
4708# endif
4709 buf_setino(buf);
4710 }
Bram Moolenaarf1726cc2009-05-13 18:48:16 +00004711 else if (!buf->b_dev_valid)
Bram Moolenaar8fa04452005-12-23 22:13:51 +00004712 /* Set the inode when creating a new file. */
4713 buf_setino(buf);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004714#endif
4715
Bram Moolenaar071d4272004-06-13 20:20:40 +00004716 if (close(fd) != 0)
4717 {
4718 errmsg = (char_u *)_("E512: Close failed");
4719 end = 0;
4720 }
4721
4722#ifdef UNIX
4723 if (made_writable)
4724 perm &= ~0200; /* reset 'w' bit for security reasons */
4725#endif
4726 if (perm >= 0) /* set perm. of new file same as old file */
4727 (void)mch_setperm(wfname, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004728#ifdef HAVE_ACL
Bram Moolenaarda412772016-07-14 20:37:07 +02004729 /*
4730 * Probably need to set the ACL before changing the user (can't set the
4731 * ACL on a file the user doesn't own).
4732 * On Solaris, with ZFS and the aclmode property set to "discard" (the
4733 * default), chmod() discards all part of a file's ACL that don't represent
4734 * the mode of the file. It's non-trivial for us to discover whether we're
4735 * in that situation, so we simply always re-set the ACL.
4736 */
4737# ifndef HAVE_SOLARIS_ZFS_ACL
Bram Moolenaar071d4272004-06-13 20:20:40 +00004738 if (!backup_copy)
Bram Moolenaarda412772016-07-14 20:37:07 +02004739# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004740 mch_set_acl(wfname, acl);
4741#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004742#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004743 if (buf->b_cryptstate != NULL)
4744 {
4745 crypt_free_state(buf->b_cryptstate);
4746 buf->b_cryptstate = NULL;
4747 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004748#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004749
Bram Moolenaar071d4272004-06-13 20:20:40 +00004750#if defined(FEAT_MBYTE) && defined(FEAT_EVAL)
4751 if (wfname != fname)
4752 {
4753 /*
4754 * The file was written to a temp file, now it needs to be converted
4755 * with 'charconvert' to (overwrite) the output file.
4756 */
4757 if (end != 0)
4758 {
4759 if (eval_charconvert(enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc,
4760 wfname, fname) == FAIL)
4761 {
4762 write_info.bw_conv_error = TRUE;
4763 end = 0;
4764 }
4765 }
4766 mch_remove(wfname);
4767 vim_free(wfname);
4768 }
4769#endif
4770
4771 if (end == 0)
4772 {
4773 if (errmsg == NULL)
4774 {
4775#ifdef FEAT_MBYTE
4776 if (write_info.bw_conv_error)
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004777 {
4778 if (write_info.bw_conv_error_lnum == 0)
4779 errmsg = (char_u *)_("E513: write error, conversion failed (make 'fenc' empty to override)");
4780 else
4781 {
4782 errmsg_allocated = TRUE;
4783 errmsg = alloc(300);
4784 vim_snprintf((char *)errmsg, 300, _("E513: write error, conversion failed in line %ld (make 'fenc' empty to override)"),
4785 (long)write_info.bw_conv_error_lnum);
4786 }
4787 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004788 else
4789#endif
4790 if (got_int)
4791 errmsg = (char_u *)_(e_interr);
4792 else
4793 errmsg = (char_u *)_("E514: write error (file system full?)");
4794 }
4795
4796 /*
4797 * If we have a backup file, try to put it in place of the new file,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004798 * because the new file is probably corrupt. This avoids losing the
Bram Moolenaar071d4272004-06-13 20:20:40 +00004799 * original file when trying to make a backup when writing the file a
4800 * second time.
4801 * When "backup_copy" is set we need to copy the backup over the new
4802 * file. Otherwise rename the backup file.
4803 * If this is OK, don't give the extra warning message.
4804 */
4805 if (backup != NULL)
4806 {
4807 if (backup_copy)
4808 {
4809 /* This may take a while, if we were interrupted let the user
4810 * know we got the message. */
4811 if (got_int)
4812 {
4813 MSG(_(e_interr));
4814 out_flush();
4815 }
4816 if ((fd = mch_open((char *)backup, O_RDONLY | O_EXTRA, 0)) >= 0)
4817 {
4818 if ((write_info.bw_fd = mch_open((char *)fname,
Bram Moolenaar9be038d2005-03-08 22:34:32 +00004819 O_WRONLY | O_CREAT | O_TRUNC | O_EXTRA,
4820 perm & 0777)) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004821 {
4822 /* copy the file. */
4823 write_info.bw_buf = smallbuf;
4824#ifdef HAS_BW_FLAGS
4825 write_info.bw_flags = FIO_NOCONVERT;
4826#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004827 while ((write_info.bw_len = read_eintr(fd, smallbuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004828 SMBUFSIZE)) > 0)
4829 if (buf_write_bytes(&write_info) == FAIL)
4830 break;
4831
4832 if (close(write_info.bw_fd) >= 0
4833 && write_info.bw_len == 0)
4834 end = 1; /* success */
4835 }
4836 close(fd); /* ignore errors for closing read file */
4837 }
4838 }
4839 else
4840 {
4841 if (vim_rename(backup, fname) == 0)
4842 end = 1;
4843 }
4844 }
4845 goto fail;
4846 }
4847
4848 lnum -= start; /* compute number of written lines */
4849 --no_wait_return; /* may wait for return now */
4850
4851#if !(defined(UNIX) || defined(VMS))
4852 fname = sfname; /* use shortname now, for the messages */
4853#endif
4854 if (!filtering)
4855 {
4856 msg_add_fname(buf, fname); /* put fname in IObuff with quotes */
4857 c = FALSE;
4858#ifdef FEAT_MBYTE
4859 if (write_info.bw_conv_error)
4860 {
4861 STRCAT(IObuff, _(" CONVERSION ERROR"));
4862 c = TRUE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004863 if (write_info.bw_conv_error_lnum != 0)
Bram Moolenaara800b422010-06-27 01:15:55 +02004864 vim_snprintf_add((char *)IObuff, IOSIZE, _(" in line %ld;"),
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004865 (long)write_info.bw_conv_error_lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004866 }
4867 else if (notconverted)
4868 {
4869 STRCAT(IObuff, _("[NOT converted]"));
4870 c = TRUE;
4871 }
4872 else if (converted)
4873 {
4874 STRCAT(IObuff, _("[converted]"));
4875 c = TRUE;
4876 }
4877#endif
4878 if (device)
4879 {
4880 STRCAT(IObuff, _("[Device]"));
4881 c = TRUE;
4882 }
4883 else if (newfile)
4884 {
4885 STRCAT(IObuff, shortmess(SHM_NEW) ? _("[New]") : _("[New File]"));
4886 c = TRUE;
4887 }
4888 if (no_eol)
4889 {
4890 msg_add_eol();
4891 c = TRUE;
4892 }
4893 /* may add [unix/dos/mac] */
4894 if (msg_add_fileformat(fileformat))
4895 c = TRUE;
4896#ifdef FEAT_CRYPT
4897 if (wb_flags & FIO_ENCRYPTED)
4898 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004899 crypt_append_msg(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004900 c = TRUE;
4901 }
4902#endif
4903 msg_add_lines(c, (long)lnum, nchars); /* add line/char count */
4904 if (!shortmess(SHM_WRITE))
4905 {
4906 if (append)
4907 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended"));
4908 else
4909 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written"));
4910 }
4911
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00004912 set_keep_msg(msg_trunc_attr(IObuff, FALSE, 0), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004913 }
4914
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004915 /* When written everything correctly: reset 'modified'. Unless not
4916 * writing to the original file and '+' is not in 'cpoptions'. */
Bram Moolenaar292ad192005-12-11 21:29:51 +00004917 if (reset_changed && whole && !append
Bram Moolenaar071d4272004-06-13 20:20:40 +00004918#ifdef FEAT_MBYTE
4919 && !write_info.bw_conv_error
4920#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004921 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL)
4922 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004923 {
4924 unchanged(buf, TRUE);
Bram Moolenaar086329d2014-10-31 19:51:36 +01004925#ifdef FEAT_AUTOCMD
4926 /* buf->b_changedtick is always incremented in unchanged() but that
4927 * should not trigger a TextChanged event. */
4928 if (last_changedtick + 1 == buf->b_changedtick
4929 && last_changedtick_buf == buf)
4930 last_changedtick = buf->b_changedtick;
4931#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004932 u_unchanged(buf);
Bram Moolenaar730cde92010-06-27 05:18:54 +02004933 u_update_save_nr(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004934 }
4935
4936 /*
4937 * If written to the current file, update the timestamp of the swap file
4938 * and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
4939 */
4940 if (overwriting)
4941 {
4942 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00004943 if (append)
4944 buf->b_flags &= ~BF_NEW;
4945 else
4946 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004947 }
4948
4949 /*
4950 * If we kept a backup until now, and we are in patch mode, then we make
4951 * the backup file our 'original' file.
4952 */
4953 if (*p_pm && dobackup)
4954 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01004955 char *org = (char *)buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00004956 fname, p_pm, FALSE);
4957
4958 if (backup != NULL)
4959 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02004960 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004961
4962 /*
4963 * If the original file does not exist yet
4964 * the current backup file becomes the original file
4965 */
4966 if (org == NULL)
4967 EMSG(_("E205: Patchmode: can't save original file"));
4968 else if (mch_stat(org, &st) < 0)
4969 {
4970 vim_rename(backup, (char_u *)org);
4971 vim_free(backup); /* don't delete the file */
4972 backup = NULL;
4973#ifdef UNIX
4974 set_file_time((char_u *)org, st_old.st_atime, st_old.st_mtime);
4975#endif
4976 }
4977 }
4978 /*
4979 * If there is no backup file, remember that a (new) file was
4980 * created.
4981 */
4982 else
4983 {
4984 int empty_fd;
4985
4986 if (org == NULL
Bram Moolenaara5792f52005-11-23 21:25:05 +00004987 || (empty_fd = mch_open(org,
4988 O_CREAT | O_EXTRA | O_EXCL | O_NOFOLLOW,
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00004989 perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004990 EMSG(_("E206: patchmode: can't touch empty original file"));
4991 else
4992 close(empty_fd);
4993 }
4994 if (org != NULL)
4995 {
4996 mch_setperm((char_u *)org, mch_getperm(fname) & 0777);
4997 vim_free(org);
4998 }
4999 }
5000
5001 /*
5002 * Remove the backup unless 'backup' option is set
5003 */
5004 if (!p_bk && backup != NULL && mch_remove(backup) != 0)
5005 EMSG(_("E207: Can't delete backup file"));
5006
5007#ifdef FEAT_SUN_WORKSHOP
5008 if (usingSunWorkShop)
5009 workshop_file_saved((char *) ffname);
5010#endif
5011
5012 goto nofail;
5013
5014 /*
5015 * Finish up. We get here either after failure or success.
5016 */
5017fail:
5018 --no_wait_return; /* may wait for return now */
5019nofail:
5020
5021 /* Done saving, we accept changed buffer warnings again */
5022 buf->b_saving = FALSE;
5023
5024 vim_free(backup);
5025 if (buffer != smallbuf)
5026 vim_free(buffer);
5027#ifdef FEAT_MBYTE
5028 vim_free(fenc_tofree);
5029 vim_free(write_info.bw_conv_buf);
5030# ifdef USE_ICONV
5031 if (write_info.bw_iconv_fd != (iconv_t)-1)
5032 {
5033 iconv_close(write_info.bw_iconv_fd);
5034 write_info.bw_iconv_fd = (iconv_t)-1;
5035 }
5036# endif
5037#endif
5038#ifdef HAVE_ACL
5039 mch_free_acl(acl);
5040#endif
5041
5042 if (errmsg != NULL)
5043 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005044 int numlen = errnum != NULL ? (int)STRLEN(errnum) : 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005045
5046 attr = hl_attr(HLF_E); /* set highlight for error messages */
5047 msg_add_fname(buf,
5048#ifndef UNIX
5049 sfname
5050#else
5051 fname
5052#endif
5053 ); /* put file name in IObuff with quotes */
5054 if (STRLEN(IObuff) + STRLEN(errmsg) + numlen >= IOSIZE)
5055 IObuff[IOSIZE - STRLEN(errmsg) - numlen - 1] = NUL;
5056 /* If the error message has the form "is ...", put the error number in
5057 * front of the file name. */
5058 if (errnum != NULL)
5059 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00005060 STRMOVE(IObuff + numlen, IObuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005061 mch_memmove(IObuff, errnum, (size_t)numlen);
5062 }
5063 STRCAT(IObuff, errmsg);
5064 emsg(IObuff);
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005065 if (errmsg_allocated)
5066 vim_free(errmsg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005067
5068 retval = FAIL;
5069 if (end == 0)
5070 {
5071 MSG_PUTS_ATTR(_("\nWARNING: Original file may be lost or damaged\n"),
5072 attr | MSG_HIST);
5073 MSG_PUTS_ATTR(_("don't quit the editor until the file is successfully written!"),
5074 attr | MSG_HIST);
5075
5076 /* Update the timestamp to avoid an "overwrite changed file"
5077 * prompt when writing again. */
5078 if (mch_stat((char *)fname, &st_old) >= 0)
5079 {
5080 buf_store_time(buf, &st_old, fname);
5081 buf->b_mtime_read = buf->b_mtime;
5082 }
5083 }
5084 }
5085 msg_scroll = msg_save;
5086
Bram Moolenaar55debbe2010-05-23 23:34:36 +02005087#ifdef FEAT_PERSISTENT_UNDO
5088 /*
5089 * When writing the whole file and 'undofile' is set, also write the undo
5090 * file.
5091 */
5092 if (retval == OK && write_undo_file)
5093 {
5094 char_u hash[UNDO_HASH_SIZE];
5095
5096 sha256_finish(&sha_ctx, hash);
5097 u_write_undo(NULL, FALSE, buf, hash);
5098 }
5099#endif
5100
Bram Moolenaar071d4272004-06-13 20:20:40 +00005101#ifdef FEAT_AUTOCMD
5102#ifdef FEAT_EVAL
5103 if (!should_abort(retval))
5104#else
5105 if (!got_int)
5106#endif
5107 {
5108 aco_save_T aco;
5109
Bram Moolenaar68a33fc2012-04-25 16:50:48 +02005110 curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */
5111
Bram Moolenaar071d4272004-06-13 20:20:40 +00005112 /*
5113 * Apply POST autocommands.
5114 * Careful: The autocommands may call buf_write() recursively!
5115 */
5116 aucmd_prepbuf(&aco, buf);
5117
5118 if (append)
5119 apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname,
5120 FALSE, curbuf, eap);
5121 else if (filtering)
5122 apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname,
5123 FALSE, curbuf, eap);
5124 else if (reset_changed && whole)
5125 apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname,
5126 FALSE, curbuf, eap);
5127 else
5128 apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname,
5129 FALSE, curbuf, eap);
5130
5131 /* restore curwin/curbuf and a few other things */
5132 aucmd_restbuf(&aco);
5133
5134#ifdef FEAT_EVAL
5135 if (aborting()) /* autocmds may abort script processing */
5136 retval = FALSE;
5137#endif
5138 }
5139#endif
5140
5141 got_int |= prev_got_int;
5142
5143#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
5144 /* Update machine specific information. */
5145 mch_post_buffer_write(buf);
5146#endif
5147 return retval;
5148}
5149
5150/*
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005151 * Set the name of the current buffer. Use when the buffer doesn't have a
5152 * name and a ":r" or ":w" command with a file name is used.
5153 */
5154 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005155set_rw_fname(char_u *fname, char_u *sfname)
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005156{
5157#ifdef FEAT_AUTOCMD
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005158 buf_T *buf = curbuf;
5159
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005160 /* It's like the unnamed buffer is deleted.... */
5161 if (curbuf->b_p_bl)
5162 apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
5163 apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf);
5164# ifdef FEAT_EVAL
5165 if (aborting()) /* autocmds may abort script processing */
5166 return FAIL;
5167# endif
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005168 if (curbuf != buf)
5169 {
5170 /* We are in another buffer now, don't do the renaming. */
5171 EMSG(_(e_auchangedbuf));
5172 return FAIL;
5173 }
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005174#endif
5175
5176 if (setfname(curbuf, fname, sfname, FALSE) == OK)
5177 curbuf->b_flags |= BF_NOTEDITED;
5178
5179#ifdef FEAT_AUTOCMD
5180 /* ....and a new named one is created */
5181 apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, curbuf);
5182 if (curbuf->b_p_bl)
5183 apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf);
5184# ifdef FEAT_EVAL
5185 if (aborting()) /* autocmds may abort script processing */
5186 return FAIL;
5187# endif
5188
5189 /* Do filetype detection now if 'filetype' is empty. */
5190 if (*curbuf->b_p_ft == NUL)
5191 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005192 if (au_has_group((char_u *)"filetypedetect"))
Bram Moolenaar1610d052016-06-09 22:53:01 +02005193 (void)do_doautocmd((char_u *)"filetypedetect BufRead", FALSE, NULL);
Bram Moolenaara3227e22006-03-08 21:32:40 +00005194 do_modelines(0);
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005195 }
5196#endif
5197
5198 return OK;
5199}
5200
5201/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00005202 * Put file name into IObuff with quotes.
5203 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005204 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005205msg_add_fname(buf_T *buf, char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005206{
5207 if (fname == NULL)
5208 fname = (char_u *)"-stdin-";
5209 home_replace(buf, fname, IObuff + 1, IOSIZE - 4, TRUE);
5210 IObuff[0] = '"';
5211 STRCAT(IObuff, "\" ");
5212}
5213
5214/*
5215 * Append message for text mode to IObuff.
5216 * Return TRUE if something appended.
5217 */
5218 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005219msg_add_fileformat(int eol_type)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005220{
5221#ifndef USE_CRNL
5222 if (eol_type == EOL_DOS)
5223 {
5224 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[dos]") : _("[dos format]"));
5225 return TRUE;
5226 }
5227#endif
5228#ifndef USE_CR
5229 if (eol_type == EOL_MAC)
5230 {
5231 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[mac]") : _("[mac format]"));
5232 return TRUE;
5233 }
5234#endif
5235#if defined(USE_CRNL) || defined(USE_CR)
5236 if (eol_type == EOL_UNIX)
5237 {
5238 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[unix]") : _("[unix format]"));
5239 return TRUE;
5240 }
5241#endif
5242 return FALSE;
5243}
5244
5245/*
5246 * Append line and character count to IObuff.
5247 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005248 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005249msg_add_lines(
5250 int insert_space,
5251 long lnum,
Bram Moolenaar8767f522016-07-01 17:17:39 +02005252 off_T nchars)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005253{
5254 char_u *p;
5255
5256 p = IObuff + STRLEN(IObuff);
5257
5258 if (insert_space)
5259 *p++ = ' ';
5260 if (shortmess(SHM_LINES))
Bram Moolenaarbde98102016-07-01 20:03:42 +02005261 vim_snprintf((char *)p, IOSIZE - (p - IObuff),
5262 "%ldL, %lldC", lnum, (varnumber_T)nchars);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005263 else
5264 {
5265 if (lnum == 1)
5266 STRCPY(p, _("1 line, "));
5267 else
5268 sprintf((char *)p, _("%ld lines, "), lnum);
5269 p += STRLEN(p);
5270 if (nchars == 1)
5271 STRCPY(p, _("1 character"));
5272 else
Bram Moolenaarbde98102016-07-01 20:03:42 +02005273 vim_snprintf((char *)p, IOSIZE - (p - IObuff),
5274 _("%lld characters"), (varnumber_T)nchars);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005275 }
5276}
5277
5278/*
5279 * Append message for missing line separator to IObuff.
5280 */
5281 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005282msg_add_eol(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005283{
5284 STRCAT(IObuff, shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]"));
5285}
5286
5287/*
5288 * Check modification time of file, before writing to it.
5289 * The size isn't checked, because using a tool like "gzip" takes care of
5290 * using the same timestamp but can't set the size.
5291 */
5292 static int
Bram Moolenaar8767f522016-07-01 17:17:39 +02005293check_mtime(buf_T *buf, stat_T *st)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005294{
5295 if (buf->b_mtime_read != 0
5296 && time_differs((long)st->st_mtime, buf->b_mtime_read))
5297 {
5298 msg_scroll = TRUE; /* don't overwrite messages here */
5299 msg_silent = 0; /* must give this prompt */
5300 /* don't use emsg() here, don't want to flush the buffers */
5301 MSG_ATTR(_("WARNING: The file has been changed since reading it!!!"),
5302 hl_attr(HLF_E));
5303 if (ask_yesno((char_u *)_("Do you really want to write to it"),
5304 TRUE) == 'n')
5305 return FAIL;
5306 msg_scroll = FALSE; /* always overwrite the file message now */
5307 }
5308 return OK;
5309}
5310
5311 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005312time_differs(long t1, long t2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005313{
Bram Moolenaar48e330a2016-02-23 14:53:34 +01005314#if defined(__linux__) || defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005315 /* On a FAT filesystem, esp. under Linux, there are only 5 bits to store
5316 * the seconds. Since the roundoff is done when flushing the inode, the
5317 * time may change unexpectedly by one second!!! */
5318 return (t1 - t2 > 1 || t2 - t1 > 1);
5319#else
5320 return (t1 != t2);
5321#endif
5322}
5323
5324/*
5325 * Call write() to write a number of bytes to the file.
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005326 * Handles encryption and 'encoding' conversion.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005327 *
5328 * Return FAIL for failure, OK otherwise.
5329 */
5330 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005331buf_write_bytes(struct bw_info *ip)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005332{
5333 int wlen;
5334 char_u *buf = ip->bw_buf; /* data to write */
5335 int len = ip->bw_len; /* length of data */
5336#ifdef HAS_BW_FLAGS
5337 int flags = ip->bw_flags; /* extra flags */
5338#endif
5339
5340#ifdef FEAT_MBYTE
5341 /*
5342 * Skip conversion when writing the crypt magic number or the BOM.
5343 */
5344 if (!(flags & FIO_NOCONVERT))
5345 {
5346 char_u *p;
5347 unsigned c;
5348 int n;
5349
5350 if (flags & FIO_UTF8)
5351 {
5352 /*
5353 * Convert latin1 in the buffer to UTF-8 in the file.
5354 */
5355 p = ip->bw_conv_buf; /* translate to buffer */
5356 for (wlen = 0; wlen < len; ++wlen)
5357 p += utf_char2bytes(buf[wlen], p);
5358 buf = ip->bw_conv_buf;
5359 len = (int)(p - ip->bw_conv_buf);
5360 }
5361 else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1))
5362 {
5363 /*
5364 * Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
5365 * Latin1 chars in the file.
5366 */
5367 if (flags & FIO_LATIN1)
5368 p = buf; /* translate in-place (can only get shorter) */
5369 else
5370 p = ip->bw_conv_buf; /* translate to buffer */
5371 for (wlen = 0; wlen < len; wlen += n)
5372 {
5373 if (wlen == 0 && ip->bw_restlen != 0)
5374 {
5375 int l;
5376
5377 /* Use remainder of previous call. Append the start of
5378 * buf[] to get a full sequence. Might still be too
5379 * short! */
5380 l = CONV_RESTLEN - ip->bw_restlen;
5381 if (l > len)
5382 l = len;
5383 mch_memmove(ip->bw_rest + ip->bw_restlen, buf, (size_t)l);
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005384 n = utf_ptr2len_len(ip->bw_rest, ip->bw_restlen + l);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005385 if (n > ip->bw_restlen + len)
5386 {
5387 /* We have an incomplete byte sequence at the end to
5388 * be written. We can't convert it without the
5389 * remaining bytes. Keep them for the next call. */
5390 if (ip->bw_restlen + len > CONV_RESTLEN)
5391 return FAIL;
5392 ip->bw_restlen += len;
5393 break;
5394 }
5395 if (n > 1)
5396 c = utf_ptr2char(ip->bw_rest);
5397 else
5398 c = ip->bw_rest[0];
5399 if (n >= ip->bw_restlen)
5400 {
5401 n -= ip->bw_restlen;
5402 ip->bw_restlen = 0;
5403 }
5404 else
5405 {
5406 ip->bw_restlen -= n;
5407 mch_memmove(ip->bw_rest, ip->bw_rest + n,
5408 (size_t)ip->bw_restlen);
5409 n = 0;
5410 }
5411 }
5412 else
5413 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005414 n = utf_ptr2len_len(buf + wlen, len - wlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005415 if (n > len - wlen)
5416 {
5417 /* We have an incomplete byte sequence at the end to
5418 * be written. We can't convert it without the
5419 * remaining bytes. Keep them for the next call. */
5420 if (len - wlen > CONV_RESTLEN)
5421 return FAIL;
5422 ip->bw_restlen = len - wlen;
5423 mch_memmove(ip->bw_rest, buf + wlen,
5424 (size_t)ip->bw_restlen);
5425 break;
5426 }
5427 if (n > 1)
5428 c = utf_ptr2char(buf + wlen);
5429 else
5430 c = buf[wlen];
5431 }
5432
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005433 if (ucs2bytes(c, &p, flags) && !ip->bw_conv_error)
5434 {
5435 ip->bw_conv_error = TRUE;
5436 ip->bw_conv_error_lnum = ip->bw_start_lnum;
5437 }
5438 if (c == NL)
5439 ++ip->bw_start_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005440 }
5441 if (flags & FIO_LATIN1)
5442 len = (int)(p - buf);
5443 else
5444 {
5445 buf = ip->bw_conv_buf;
5446 len = (int)(p - ip->bw_conv_buf);
5447 }
5448 }
5449
5450# ifdef WIN3264
5451 else if (flags & FIO_CODEPAGE)
5452 {
5453 /*
5454 * Convert UTF-8 or codepage to UCS-2 and then to MS-Windows
5455 * codepage.
5456 */
5457 char_u *from;
5458 size_t fromlen;
5459 char_u *to;
5460 int u8c;
5461 BOOL bad = FALSE;
5462 int needed;
5463
5464 if (ip->bw_restlen > 0)
5465 {
5466 /* Need to concatenate the remainder of the previous call and
5467 * the bytes of the current call. Use the end of the
5468 * conversion buffer for this. */
5469 fromlen = len + ip->bw_restlen;
5470 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5471 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5472 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5473 }
5474 else
5475 {
5476 from = buf;
5477 fromlen = len;
5478 }
5479
5480 to = ip->bw_conv_buf;
5481 if (enc_utf8)
5482 {
5483 /* Convert from UTF-8 to UCS-2, to the start of the buffer.
5484 * The buffer has been allocated to be big enough. */
5485 while (fromlen > 0)
5486 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005487 n = (int)utf_ptr2len_len(from, (int)fromlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005488 if (n > (int)fromlen) /* incomplete byte sequence */
5489 break;
5490 u8c = utf_ptr2char(from);
5491 *to++ = (u8c & 0xff);
5492 *to++ = (u8c >> 8);
5493 fromlen -= n;
5494 from += n;
5495 }
5496
5497 /* Copy remainder to ip->bw_rest[] to be used for the next
5498 * call. */
5499 if (fromlen > CONV_RESTLEN)
5500 {
5501 /* weird overlong sequence */
5502 ip->bw_conv_error = TRUE;
5503 return FAIL;
5504 }
5505 mch_memmove(ip->bw_rest, from, fromlen);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005506 ip->bw_restlen = (int)fromlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005507 }
5508 else
5509 {
5510 /* Convert from enc_codepage to UCS-2, to the start of the
5511 * buffer. The buffer has been allocated to be big enough. */
5512 ip->bw_restlen = 0;
5513 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005514 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005515 NULL, 0);
5516 if (needed == 0)
5517 {
5518 /* When conversion fails there may be a trailing byte. */
5519 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005520 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen - 1,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005521 NULL, 0);
5522 if (needed == 0)
5523 {
5524 /* Conversion doesn't work. */
5525 ip->bw_conv_error = TRUE;
5526 return FAIL;
5527 }
5528 /* Save the trailing byte for the next call. */
5529 ip->bw_rest[0] = from[fromlen - 1];
5530 ip->bw_restlen = 1;
5531 }
5532 needed = MultiByteToWideChar(enc_codepage, MB_ERR_INVALID_CHARS,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005533 (LPCSTR)from, (int)(fromlen - ip->bw_restlen),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005534 (LPWSTR)to, needed);
5535 if (needed == 0)
5536 {
5537 /* Safety check: Conversion doesn't work. */
5538 ip->bw_conv_error = TRUE;
5539 return FAIL;
5540 }
5541 to += needed * 2;
5542 }
5543
5544 fromlen = to - ip->bw_conv_buf;
5545 buf = to;
5546# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5547 if (FIO_GET_CP(flags) == CP_UTF8)
5548 {
5549 /* Convert from UCS-2 to UTF-8, using the remainder of the
5550 * conversion buffer. Fails when out of space. */
5551 for (from = ip->bw_conv_buf; fromlen > 1; fromlen -= 2)
5552 {
5553 u8c = *from++;
5554 u8c += (*from++ << 8);
5555 to += utf_char2bytes(u8c, to);
5556 if (to + 6 >= ip->bw_conv_buf + ip->bw_conv_buflen)
5557 {
5558 ip->bw_conv_error = TRUE;
5559 return FAIL;
5560 }
5561 }
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005562 len = (int)(to - buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005563 }
5564 else
5565#endif
5566 {
5567 /* Convert from UCS-2 to the codepage, using the remainder of
5568 * the conversion buffer. If the conversion uses the default
5569 * character "0", the data doesn't fit in this encoding, so
5570 * fail. */
5571 len = WideCharToMultiByte(FIO_GET_CP(flags), 0,
5572 (LPCWSTR)ip->bw_conv_buf, (int)fromlen / sizeof(WCHAR),
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005573 (LPSTR)to, (int)(ip->bw_conv_buflen - fromlen), 0,
5574 &bad);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005575 if (bad)
5576 {
5577 ip->bw_conv_error = TRUE;
5578 return FAIL;
5579 }
5580 }
5581 }
5582# endif
5583
Bram Moolenaar56718732006-03-15 22:53:57 +00005584# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00005585 else if (flags & FIO_MACROMAN)
5586 {
5587 /*
5588 * Convert UTF-8 or latin1 to Apple MacRoman.
5589 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005590 char_u *from;
5591 size_t fromlen;
5592
5593 if (ip->bw_restlen > 0)
5594 {
5595 /* Need to concatenate the remainder of the previous call and
5596 * the bytes of the current call. Use the end of the
5597 * conversion buffer for this. */
5598 fromlen = len + ip->bw_restlen;
5599 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5600 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5601 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5602 }
5603 else
5604 {
5605 from = buf;
5606 fromlen = len;
5607 }
5608
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00005609 if (enc2macroman(from, fromlen,
5610 ip->bw_conv_buf, &len, ip->bw_conv_buflen,
5611 ip->bw_rest, &ip->bw_restlen) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005612 {
5613 ip->bw_conv_error = TRUE;
5614 return FAIL;
5615 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005616 buf = ip->bw_conv_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005617 }
5618# endif
5619
5620# ifdef USE_ICONV
5621 if (ip->bw_iconv_fd != (iconv_t)-1)
5622 {
5623 const char *from;
5624 size_t fromlen;
5625 char *to;
5626 size_t tolen;
5627
5628 /* Convert with iconv(). */
5629 if (ip->bw_restlen > 0)
5630 {
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005631 char *fp;
5632
Bram Moolenaar071d4272004-06-13 20:20:40 +00005633 /* Need to concatenate the remainder of the previous call and
5634 * the bytes of the current call. Use the end of the
5635 * conversion buffer for this. */
5636 fromlen = len + ip->bw_restlen;
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005637 fp = (char *)ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5638 mch_memmove(fp, ip->bw_rest, (size_t)ip->bw_restlen);
5639 mch_memmove(fp + ip->bw_restlen, buf, (size_t)len);
5640 from = fp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005641 tolen = ip->bw_conv_buflen - fromlen;
5642 }
5643 else
5644 {
5645 from = (const char *)buf;
5646 fromlen = len;
5647 tolen = ip->bw_conv_buflen;
5648 }
5649 to = (char *)ip->bw_conv_buf;
5650
5651 if (ip->bw_first)
5652 {
5653 size_t save_len = tolen;
5654
5655 /* output the initial shift state sequence */
5656 (void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen);
5657
5658 /* There is a bug in iconv() on Linux (which appears to be
5659 * wide-spread) which sets "to" to NULL and messes up "tolen".
5660 */
5661 if (to == NULL)
5662 {
5663 to = (char *)ip->bw_conv_buf;
5664 tolen = save_len;
5665 }
5666 ip->bw_first = FALSE;
5667 }
5668
5669 /*
5670 * If iconv() has an error or there is not enough room, fail.
5671 */
5672 if ((iconv(ip->bw_iconv_fd, (void *)&from, &fromlen, &to, &tolen)
5673 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
5674 || fromlen > CONV_RESTLEN)
5675 {
5676 ip->bw_conv_error = TRUE;
5677 return FAIL;
5678 }
5679
5680 /* copy remainder to ip->bw_rest[] to be used for the next call. */
5681 if (fromlen > 0)
5682 mch_memmove(ip->bw_rest, (void *)from, fromlen);
5683 ip->bw_restlen = (int)fromlen;
5684
5685 buf = ip->bw_conv_buf;
5686 len = (int)((char_u *)to - ip->bw_conv_buf);
5687 }
5688# endif
5689 }
5690#endif /* FEAT_MBYTE */
5691
5692#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02005693 if (flags & FIO_ENCRYPTED)
5694 {
5695 /* Encrypt the data. Do it in-place if possible, otherwise use an
5696 * allocated buffer. */
5697 if (crypt_works_inplace(ip->bw_buffer->b_cryptstate))
5698 {
5699 crypt_encode_inplace(ip->bw_buffer->b_cryptstate, buf, len);
5700 }
5701 else
5702 {
5703 char_u *outbuf;
5704
5705 len = crypt_encode_alloc(curbuf->b_cryptstate, buf, len, &outbuf);
5706 if (len == 0)
5707 return OK; /* Crypt layer is buffering, will flush later. */
5708 wlen = write_eintr(ip->bw_fd, outbuf, len);
5709 vim_free(outbuf);
5710 return (wlen < len) ? FAIL : OK;
5711 }
5712 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005713#endif
5714
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005715 wlen = write_eintr(ip->bw_fd, buf, len);
5716 return (wlen < len) ? FAIL : OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005717}
5718
5719#ifdef FEAT_MBYTE
5720/*
5721 * Convert a Unicode character to bytes.
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005722 * Return TRUE for an error, FALSE when it's OK.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005723 */
5724 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005725ucs2bytes(
5726 unsigned c, /* in: character */
5727 char_u **pp, /* in/out: pointer to result */
5728 int flags) /* FIO_ flags */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005729{
5730 char_u *p = *pp;
5731 int error = FALSE;
5732 int cc;
5733
5734
5735 if (flags & FIO_UCS4)
5736 {
5737 if (flags & FIO_ENDIAN_L)
5738 {
5739 *p++ = c;
5740 *p++ = (c >> 8);
5741 *p++ = (c >> 16);
5742 *p++ = (c >> 24);
5743 }
5744 else
5745 {
5746 *p++ = (c >> 24);
5747 *p++ = (c >> 16);
5748 *p++ = (c >> 8);
5749 *p++ = c;
5750 }
5751 }
5752 else if (flags & (FIO_UCS2 | FIO_UTF16))
5753 {
5754 if (c >= 0x10000)
5755 {
5756 if (flags & FIO_UTF16)
5757 {
5758 /* Make two words, ten bits of the character in each. First
5759 * word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff */
5760 c -= 0x10000;
5761 if (c >= 0x100000)
5762 error = TRUE;
5763 cc = ((c >> 10) & 0x3ff) + 0xd800;
5764 if (flags & FIO_ENDIAN_L)
5765 {
5766 *p++ = cc;
5767 *p++ = ((unsigned)cc >> 8);
5768 }
5769 else
5770 {
5771 *p++ = ((unsigned)cc >> 8);
5772 *p++ = cc;
5773 }
5774 c = (c & 0x3ff) + 0xdc00;
5775 }
5776 else
5777 error = TRUE;
5778 }
5779 if (flags & FIO_ENDIAN_L)
5780 {
5781 *p++ = c;
5782 *p++ = (c >> 8);
5783 }
5784 else
5785 {
5786 *p++ = (c >> 8);
5787 *p++ = c;
5788 }
5789 }
5790 else /* Latin1 */
5791 {
5792 if (c >= 0x100)
5793 {
5794 error = TRUE;
5795 *p++ = 0xBF;
5796 }
5797 else
5798 *p++ = c;
5799 }
5800
5801 *pp = p;
5802 return error;
5803}
5804
5805/*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005806 * Return TRUE if file encoding "fenc" requires conversion from or to
5807 * 'encoding'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005808 */
5809 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005810need_conversion(char_u *fenc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005811{
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005812 int same_encoding;
5813 int enc_flags;
5814 int fenc_flags;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005815
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005816 if (*fenc == NUL || STRCMP(p_enc, fenc) == 0)
Bram Moolenaar442b4222010-05-24 21:34:22 +02005817 {
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005818 same_encoding = TRUE;
Bram Moolenaar442b4222010-05-24 21:34:22 +02005819 fenc_flags = 0;
5820 }
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005821 else
5822 {
5823 /* Ignore difference between "ansi" and "latin1", "ucs-4" and
5824 * "ucs-4be", etc. */
5825 enc_flags = get_fio_flags(p_enc);
5826 fenc_flags = get_fio_flags(fenc);
5827 same_encoding = (enc_flags != 0 && fenc_flags == enc_flags);
5828 }
5829 if (same_encoding)
5830 {
5831 /* Specified encoding matches with 'encoding'. This requires
5832 * conversion when 'encoding' is Unicode but not UTF-8. */
5833 return enc_unicode != 0;
5834 }
5835
5836 /* Encodings differ. However, conversion is not needed when 'enc' is any
5837 * Unicode encoding and the file is UTF-8. */
5838 return !(enc_utf8 && fenc_flags == FIO_UTF8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005839}
5840
5841/*
5842 * Check "ptr" for a unicode encoding and return the FIO_ flags needed for the
5843 * internal conversion.
5844 * if "ptr" is an empty string, use 'encoding'.
5845 */
5846 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005847get_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005848{
5849 int prop;
5850
5851 if (*ptr == NUL)
5852 ptr = p_enc;
5853
5854 prop = enc_canon_props(ptr);
5855 if (prop & ENC_UNICODE)
5856 {
5857 if (prop & ENC_2BYTE)
5858 {
5859 if (prop & ENC_ENDIAN_L)
5860 return FIO_UCS2 | FIO_ENDIAN_L;
5861 return FIO_UCS2;
5862 }
5863 if (prop & ENC_4BYTE)
5864 {
5865 if (prop & ENC_ENDIAN_L)
5866 return FIO_UCS4 | FIO_ENDIAN_L;
5867 return FIO_UCS4;
5868 }
5869 if (prop & ENC_2WORD)
5870 {
5871 if (prop & ENC_ENDIAN_L)
5872 return FIO_UTF16 | FIO_ENDIAN_L;
5873 return FIO_UTF16;
5874 }
5875 return FIO_UTF8;
5876 }
5877 if (prop & ENC_LATIN1)
5878 return FIO_LATIN1;
5879 /* must be ENC_DBCS, requires iconv() */
5880 return 0;
5881}
5882
5883#ifdef WIN3264
5884/*
5885 * Check "ptr" for a MS-Windows codepage name and return the FIO_ flags needed
5886 * for the conversion MS-Windows can do for us. Also accept "utf-8".
5887 * Used for conversion between 'encoding' and 'fileencoding'.
5888 */
5889 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005890get_win_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005891{
5892 int cp;
5893
5894 /* Cannot do this when 'encoding' is not utf-8 and not a codepage. */
5895 if (!enc_utf8 && enc_codepage <= 0)
5896 return 0;
5897
5898 cp = encname2codepage(ptr);
5899 if (cp == 0)
5900 {
5901# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5902 if (STRCMP(ptr, "utf-8") == 0)
5903 cp = CP_UTF8;
5904 else
5905# endif
5906 return 0;
5907 }
5908 return FIO_PUT_CP(cp) | FIO_CODEPAGE;
5909}
5910#endif
5911
5912#ifdef MACOS_X
5913/*
5914 * Check "ptr" for a Carbon supported encoding and return the FIO_ flags
5915 * needed for the internal conversion to/from utf-8 or latin1.
5916 */
5917 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005918get_mac_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005919{
5920 if ((enc_utf8 || STRCMP(p_enc, "latin1") == 0)
5921 && (enc_canon_props(ptr) & ENC_MACROMAN))
5922 return FIO_MACROMAN;
5923 return 0;
5924}
5925#endif
5926
5927/*
5928 * Check for a Unicode BOM (Byte Order Mark) at the start of p[size].
5929 * "size" must be at least 2.
5930 * Return the name of the encoding and set "*lenp" to the length.
5931 * Returns NULL when no BOM found.
5932 */
5933 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005934check_for_bom(
5935 char_u *p,
5936 long size,
5937 int *lenp,
5938 int flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005939{
5940 char *name = NULL;
5941 int len = 2;
5942
5943 if (p[0] == 0xef && p[1] == 0xbb && size >= 3 && p[2] == 0xbf
Bram Moolenaaree0f5a62008-07-24 20:09:16 +00005944 && (flags == FIO_ALL || flags == FIO_UTF8 || flags == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005945 {
5946 name = "utf-8"; /* EF BB BF */
5947 len = 3;
5948 }
5949 else if (p[0] == 0xff && p[1] == 0xfe)
5950 {
5951 if (size >= 4 && p[2] == 0 && p[3] == 0
5952 && (flags == FIO_ALL || flags == (FIO_UCS4 | FIO_ENDIAN_L)))
5953 {
5954 name = "ucs-4le"; /* FF FE 00 00 */
5955 len = 4;
5956 }
Bram Moolenaar223a1892008-11-11 20:57:11 +00005957 else if (flags == (FIO_UCS2 | FIO_ENDIAN_L))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005958 name = "ucs-2le"; /* FF FE */
Bram Moolenaar223a1892008-11-11 20:57:11 +00005959 else if (flags == FIO_ALL || flags == (FIO_UTF16 | FIO_ENDIAN_L))
5960 /* utf-16le is preferred, it also works for ucs-2le text */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005961 name = "utf-16le"; /* FF FE */
5962 }
5963 else if (p[0] == 0xfe && p[1] == 0xff
5964 && (flags == FIO_ALL || flags == FIO_UCS2 || flags == FIO_UTF16))
5965 {
Bram Moolenaarffd82c52008-02-20 17:15:26 +00005966 /* Default to utf-16, it works also for ucs-2 text. */
5967 if (flags == FIO_UCS2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005968 name = "ucs-2"; /* FE FF */
Bram Moolenaarffd82c52008-02-20 17:15:26 +00005969 else
5970 name = "utf-16"; /* FE FF */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005971 }
5972 else if (size >= 4 && p[0] == 0 && p[1] == 0 && p[2] == 0xfe
5973 && p[3] == 0xff && (flags == FIO_ALL || flags == FIO_UCS4))
5974 {
5975 name = "ucs-4"; /* 00 00 FE FF */
5976 len = 4;
5977 }
5978
5979 *lenp = len;
5980 return (char_u *)name;
5981}
5982
5983/*
5984 * Generate a BOM in "buf[4]" for encoding "name".
5985 * Return the length of the BOM (zero when no BOM).
5986 */
5987 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005988make_bom(char_u *buf, char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005989{
5990 int flags;
5991 char_u *p;
5992
5993 flags = get_fio_flags(name);
5994
5995 /* Can't put a BOM in a non-Unicode file. */
5996 if (flags == FIO_LATIN1 || flags == 0)
5997 return 0;
5998
5999 if (flags == FIO_UTF8) /* UTF-8 */
6000 {
6001 buf[0] = 0xef;
6002 buf[1] = 0xbb;
6003 buf[2] = 0xbf;
6004 return 3;
6005 }
6006 p = buf;
6007 (void)ucs2bytes(0xfeff, &p, flags);
6008 return (int)(p - buf);
6009}
6010#endif
6011
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00006012#if defined(FEAT_VIMINFO) || defined(FEAT_BROWSE) || \
Bram Moolenaara0174af2008-01-02 20:08:25 +00006013 defined(FEAT_QUICKFIX) || defined(FEAT_AUTOCMD) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006014/*
6015 * Try to find a shortname by comparing the fullname with the current
6016 * directory.
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006017 * Returns "full_path" or pointer into "full_path" if shortened.
6018 */
6019 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006020shorten_fname1(char_u *full_path)
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006021{
Bram Moolenaard9462e32011-04-11 21:35:11 +02006022 char_u *dirname;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006023 char_u *p = full_path;
6024
Bram Moolenaard9462e32011-04-11 21:35:11 +02006025 dirname = alloc(MAXPATHL);
6026 if (dirname == NULL)
6027 return full_path;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006028 if (mch_dirname(dirname, MAXPATHL) == OK)
6029 {
6030 p = shorten_fname(full_path, dirname);
6031 if (p == NULL || *p == NUL)
6032 p = full_path;
6033 }
Bram Moolenaard9462e32011-04-11 21:35:11 +02006034 vim_free(dirname);
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006035 return p;
6036}
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00006037#endif
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006038
6039/*
6040 * Try to find a shortname by comparing the fullname with the current
6041 * directory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006042 * Returns NULL if not shorter name possible, pointer into "full_path"
6043 * otherwise.
6044 */
6045 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006046shorten_fname(char_u *full_path, char_u *dir_name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006047{
6048 int len;
6049 char_u *p;
6050
6051 if (full_path == NULL)
6052 return NULL;
6053 len = (int)STRLEN(dir_name);
6054 if (fnamencmp(dir_name, full_path, len) == 0)
6055 {
6056 p = full_path + len;
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006057#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006058 /*
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006059 * MSWIN: when a file is in the root directory, dir_name will end in a
Bram Moolenaar071d4272004-06-13 20:20:40 +00006060 * slash, since C: by itself does not define a specific dir. In this
6061 * case p may already be correct. <negri>
6062 */
6063 if (!((len > 2) && (*(p - 2) == ':')))
6064#endif
6065 {
6066 if (vim_ispathsep(*p))
6067 ++p;
6068#ifndef VMS /* the path separator is always part of the path */
6069 else
6070 p = NULL;
6071#endif
6072 }
6073 }
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006074#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006075 /*
6076 * When using a file in the current drive, remove the drive name:
6077 * "A:\dir\file" -> "\dir\file". This helps when moving a session file on
6078 * a floppy from "A:\dir" to "B:\dir".
6079 */
6080 else if (len > 3
6081 && TOUPPER_LOC(full_path[0]) == TOUPPER_LOC(dir_name[0])
6082 && full_path[1] == ':'
6083 && vim_ispathsep(full_path[2]))
6084 p = full_path + 2;
6085#endif
6086 else
6087 p = NULL;
6088 return p;
6089}
6090
6091/*
6092 * Shorten filenames for all buffers.
6093 * When "force" is TRUE: Use full path from now on for files currently being
6094 * edited, both for file name and swap file name. Try to shorten the file
6095 * names a bit, if safe to do so.
6096 * When "force" is FALSE: Only try to shorten absolute file names.
6097 * For buffers that have buftype "nofile" or "scratch": never change the file
6098 * name.
6099 */
6100 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006101shorten_fnames(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006102{
6103 char_u dirname[MAXPATHL];
6104 buf_T *buf;
6105 char_u *p;
6106
6107 mch_dirname(dirname, MAXPATHL);
Bram Moolenaar29323592016-07-24 22:04:11 +02006108 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006109 {
6110 if (buf->b_fname != NULL
6111#ifdef FEAT_QUICKFIX
6112 && !bt_nofile(buf)
6113#endif
6114 && !path_with_url(buf->b_fname)
6115 && (force
6116 || buf->b_sfname == NULL
6117 || mch_isFullName(buf->b_sfname)))
6118 {
6119 vim_free(buf->b_sfname);
6120 buf->b_sfname = NULL;
6121 p = shorten_fname(buf->b_ffname, dirname);
6122 if (p != NULL)
6123 {
6124 buf->b_sfname = vim_strsave(p);
6125 buf->b_fname = buf->b_sfname;
6126 }
6127 if (p == NULL || buf->b_fname == NULL)
6128 buf->b_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006129 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00006130
6131 /* Always make the swap file name a full path, a "nofile" buffer may
6132 * also have a swap file. */
6133 mf_fullname(buf->b_ml.ml_mfp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006134 }
6135#ifdef FEAT_WINDOWS
6136 status_redraw_all();
Bram Moolenaar49d7bf12006-02-17 21:45:41 +00006137 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006138#endif
6139}
6140
6141#if (defined(FEAT_DND) && defined(FEAT_GUI_GTK)) \
6142 || defined(FEAT_GUI_MSWIN) \
6143 || defined(FEAT_GUI_MAC) \
6144 || defined(PROTO)
6145/*
6146 * Shorten all filenames in "fnames[count]" by current directory.
6147 */
6148 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006149shorten_filenames(char_u **fnames, int count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006150{
6151 int i;
6152 char_u dirname[MAXPATHL];
6153 char_u *p;
6154
6155 if (fnames == NULL || count < 1)
6156 return;
6157 mch_dirname(dirname, sizeof(dirname));
6158 for (i = 0; i < count; ++i)
6159 {
6160 if ((p = shorten_fname(fnames[i], dirname)) != NULL)
6161 {
6162 /* shorten_fname() returns pointer in given "fnames[i]". If free
6163 * "fnames[i]" first, "p" becomes invalid. So we need to copy
6164 * "p" first then free fnames[i]. */
6165 p = vim_strsave(p);
6166 vim_free(fnames[i]);
6167 fnames[i] = p;
6168 }
6169 }
6170}
6171#endif
6172
6173/*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006174 * add extension to file name - change path/fo.o.h to path/fo.o.h.ext or
Bram Moolenaar071d4272004-06-13 20:20:40 +00006175 * fo_o_h.ext for MSDOS or when shortname option set.
6176 *
6177 * Assumed that fname is a valid name found in the filesystem we assure that
6178 * the return value is a different name and ends in 'ext'.
6179 * "ext" MUST be at most 4 characters long if it starts with a dot, 3
6180 * characters otherwise.
6181 * Space for the returned name is allocated, must be freed later.
6182 * Returns NULL when out of memory.
6183 */
6184 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006185modname(
6186 char_u *fname,
6187 char_u *ext,
6188 int prepend_dot) /* may prepend a '.' to file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006189{
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006190 return buf_modname((curbuf->b_p_sn || curbuf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00006191 fname, ext, prepend_dot);
6192}
6193
6194 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006195buf_modname(
6196 int shortname, /* use 8.3 file name */
6197 char_u *fname,
6198 char_u *ext,
6199 int prepend_dot) /* may prepend a '.' to file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006200{
6201 char_u *retval;
6202 char_u *s;
6203 char_u *e;
6204 char_u *ptr;
6205 int fnamelen, extlen;
6206
6207 extlen = (int)STRLEN(ext);
6208
6209 /*
6210 * If there is no file name we must get the name of the current directory
6211 * (we need the full path in case :cd is used).
6212 */
6213 if (fname == NULL || *fname == NUL)
6214 {
6215 retval = alloc((unsigned)(MAXPATHL + extlen + 3));
6216 if (retval == NULL)
6217 return NULL;
6218 if (mch_dirname(retval, MAXPATHL) == FAIL ||
6219 (fnamelen = (int)STRLEN(retval)) == 0)
6220 {
6221 vim_free(retval);
6222 return NULL;
6223 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006224 if (!after_pathsep(retval, retval + fnamelen))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006225 {
6226 retval[fnamelen++] = PATHSEP;
6227 retval[fnamelen] = NUL;
6228 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006229 prepend_dot = FALSE; /* nothing to prepend a dot to */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006230 }
6231 else
6232 {
6233 fnamelen = (int)STRLEN(fname);
6234 retval = alloc((unsigned)(fnamelen + extlen + 3));
6235 if (retval == NULL)
6236 return NULL;
6237 STRCPY(retval, fname);
6238#ifdef VMS
6239 vms_remove_version(retval); /* we do not need versions here */
6240#endif
6241 }
6242
6243 /*
6244 * search backwards until we hit a '/', '\' or ':' replacing all '.'
6245 * by '_' for MSDOS or when shortname option set and ext starts with a dot.
6246 * Then truncate what is after the '/', '\' or ':' to 8 characters for
6247 * MSDOS and 26 characters for AMIGA, a lot more for UNIX.
6248 */
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006249 for (ptr = retval + fnamelen; ptr > retval; mb_ptr_back(retval, ptr))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006250 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006251 if (*ext == '.'
Bram Moolenaare60acc12011-05-10 16:41:25 +02006252#ifdef USE_LONG_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00006253 && (!USE_LONG_FNAME || shortname)
Bram Moolenaare60acc12011-05-10 16:41:25 +02006254#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006255 && shortname
Bram Moolenaare60acc12011-05-10 16:41:25 +02006256#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006257 )
6258 if (*ptr == '.') /* replace '.' by '_' */
6259 *ptr = '_';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006260 if (vim_ispathsep(*ptr))
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006261 {
6262 ++ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006263 break;
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006264 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006265 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006266
6267 /* the file name has at most BASENAMELEN characters. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006268 if (STRLEN(ptr) > (unsigned)BASENAMELEN)
6269 ptr[BASENAMELEN] = '\0';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006270
6271 s = ptr + STRLEN(ptr);
6272
6273 /*
6274 * For 8.3 file names we may have to reduce the length.
6275 */
6276#ifdef USE_LONG_FNAME
6277 if (!USE_LONG_FNAME || shortname)
6278#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006279 if (shortname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006280#endif
6281 {
6282 /*
6283 * If there is no file name, or the file name ends in '/', and the
6284 * extension starts with '.', put a '_' before the dot, because just
6285 * ".ext" is invalid.
6286 */
6287 if (fname == NULL || *fname == NUL
6288 || vim_ispathsep(fname[STRLEN(fname) - 1]))
6289 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006290 if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006291 *s++ = '_';
6292 }
6293 /*
6294 * If the extension starts with '.', truncate the base name at 8
6295 * characters
6296 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006297 else if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006298 {
Bram Moolenaar78a15312009-05-15 19:33:18 +00006299 if ((size_t)(s - ptr) > (size_t)8)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006300 {
6301 s = ptr + 8;
6302 *s = '\0';
6303 }
6304 }
6305 /*
6306 * If the extension doesn't start with '.', and the file name
6307 * doesn't have an extension yet, append a '.'
6308 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006309 else if ((e = vim_strchr(ptr, '.')) == NULL)
6310 *s++ = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006311 /*
6312 * If the extension doesn't start with '.', and there already is an
Bram Moolenaar7263a772007-05-10 17:35:54 +00006313 * extension, it may need to be truncated
Bram Moolenaar071d4272004-06-13 20:20:40 +00006314 */
6315 else if ((int)STRLEN(e) + extlen > 4)
6316 s = e + 4 - extlen;
6317 }
Bram Moolenaare7fedb62015-12-31 19:07:19 +01006318#if defined(USE_LONG_FNAME) || defined(WIN3264)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006319 /*
6320 * If there is no file name, and the extension starts with '.', put a
6321 * '_' before the dot, because just ".ext" may be invalid if it's on a
6322 * FAT partition, and on HPFS it doesn't matter.
6323 */
6324 else if ((fname == NULL || *fname == NUL) && *ext == '.')
6325 *s++ = '_';
6326#endif
6327
6328 /*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006329 * Append the extension.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006330 * ext can start with '.' and cannot exceed 3 more characters.
6331 */
6332 STRCPY(s, ext);
6333
Bram Moolenaar071d4272004-06-13 20:20:40 +00006334 /*
6335 * Prepend the dot.
6336 */
Bram Moolenaare60acc12011-05-10 16:41:25 +02006337 if (prepend_dot && !shortname && *(e = gettail(retval)) != '.'
Bram Moolenaar071d4272004-06-13 20:20:40 +00006338#ifdef USE_LONG_FNAME
6339 && USE_LONG_FNAME
6340#endif
6341 )
6342 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006343 STRMOVE(e + 1, e);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006344 *e = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006345 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006346
6347 /*
6348 * Check that, after appending the extension, the file name is really
6349 * different.
6350 */
6351 if (fname != NULL && STRCMP(fname, retval) == 0)
6352 {
6353 /* we search for a character that can be replaced by '_' */
6354 while (--s >= ptr)
6355 {
6356 if (*s != '_')
6357 {
6358 *s = '_';
6359 break;
6360 }
6361 }
6362 if (s < ptr) /* fname was "________.<ext>", how tricky! */
6363 *ptr = 'v';
6364 }
6365 return retval;
6366}
6367
6368/*
6369 * Like fgets(), but if the file line is too long, it is truncated and the
6370 * rest of the line is thrown away. Returns TRUE for end-of-file.
6371 */
6372 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006373vim_fgets(char_u *buf, int size, FILE *fp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006374{
6375 char *eof;
6376#define FGETS_SIZE 200
6377 char tbuf[FGETS_SIZE];
6378
6379 buf[size - 2] = NUL;
6380#ifdef USE_CR
6381 eof = fgets_cr((char *)buf, size, fp);
6382#else
6383 eof = fgets((char *)buf, size, fp);
6384#endif
6385 if (buf[size - 2] != NUL && buf[size - 2] != '\n')
6386 {
6387 buf[size - 1] = NUL; /* Truncate the line */
6388
6389 /* Now throw away the rest of the line: */
6390 do
6391 {
6392 tbuf[FGETS_SIZE - 2] = NUL;
6393#ifdef USE_CR
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006394 ignoredp = fgets_cr((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006395#else
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006396 ignoredp = fgets((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006397#endif
6398 } while (tbuf[FGETS_SIZE - 2] != NUL && tbuf[FGETS_SIZE - 2] != '\n');
6399 }
6400 return (eof == NULL);
6401}
6402
6403#if defined(USE_CR) || defined(PROTO)
6404/*
6405 * Like vim_fgets(), but accept any line terminator: CR, CR-LF or LF.
6406 * Returns TRUE for end-of-file.
6407 * Only used for the Mac, because it's much slower than vim_fgets().
6408 */
6409 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006410tag_fgets(char_u *buf, int size, FILE *fp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006411{
6412 int i = 0;
6413 int c;
6414 int eof = FALSE;
6415
6416 for (;;)
6417 {
6418 c = fgetc(fp);
6419 if (c == EOF)
6420 {
6421 eof = TRUE;
6422 break;
6423 }
6424 if (c == '\r')
6425 {
6426 /* Always store a NL for end-of-line. */
6427 if (i < size - 1)
6428 buf[i++] = '\n';
6429 c = fgetc(fp);
6430 if (c != '\n') /* Macintosh format: single CR. */
6431 ungetc(c, fp);
6432 break;
6433 }
6434 if (i < size - 1)
6435 buf[i++] = c;
6436 if (c == '\n')
6437 break;
6438 }
6439 buf[i] = NUL;
6440 return eof;
6441}
6442#endif
6443
6444/*
6445 * rename() only works if both files are on the same file system, this
6446 * function will (attempts to?) copy the file across if rename fails -- webb
6447 * Return -1 for failure, 0 for success.
6448 */
6449 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006450vim_rename(char_u *from, char_u *to)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006451{
6452 int fd_in;
6453 int fd_out;
6454 int n;
6455 char *errmsg = NULL;
6456 char *buffer;
6457#ifdef AMIGA
6458 BPTR flock;
6459#endif
Bram Moolenaar8767f522016-07-01 17:17:39 +02006460 stat_T st;
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006461 long perm;
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006462#ifdef HAVE_ACL
6463 vim_acl_T acl; /* ACL from original file */
6464#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006465 int use_tmp_file = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006466
6467 /*
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006468 * When the names are identical, there is nothing to do. When they refer
6469 * to the same file (ignoring case and slash/backslash differences) but
6470 * the file name differs we need to go through a temp file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006471 */
6472 if (fnamecmp(from, to) == 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006473 {
Bram Moolenaar71afbfe2013-03-19 16:49:16 +01006474 if (p_fic && STRCMP(gettail(from), gettail(to)) != 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006475 use_tmp_file = TRUE;
6476 else
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006477 return 0;
6478 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006479
6480 /*
6481 * Fail if the "from" file doesn't exist. Avoids that "to" is deleted.
6482 */
6483 if (mch_stat((char *)from, &st) < 0)
6484 return -1;
6485
Bram Moolenaar3576da72008-12-30 15:15:57 +00006486#ifdef UNIX
6487 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02006488 stat_T st_to;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006489
6490 /* It's possible for the source and destination to be the same file.
6491 * This happens when "from" and "to" differ in case and are on a FAT32
6492 * filesystem. In that case go through a temp file name. */
6493 if (mch_stat((char *)to, &st_to) >= 0
6494 && st.st_dev == st_to.st_dev
6495 && st.st_ino == st_to.st_ino)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006496 use_tmp_file = TRUE;
6497 }
6498#endif
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02006499#ifdef WIN3264
6500 {
6501 BY_HANDLE_FILE_INFORMATION info1, info2;
6502
6503 /* It's possible for the source and destination to be the same file.
6504 * In that case go through a temp file name. This makes rename("foo",
6505 * "./foo") a no-op (in a complicated way). */
6506 if (win32_fileinfo(from, &info1) == FILEINFO_OK
6507 && win32_fileinfo(to, &info2) == FILEINFO_OK
6508 && info1.dwVolumeSerialNumber == info2.dwVolumeSerialNumber
6509 && info1.nFileIndexHigh == info2.nFileIndexHigh
6510 && info1.nFileIndexLow == info2.nFileIndexLow)
6511 use_tmp_file = TRUE;
6512 }
6513#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006514
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006515 if (use_tmp_file)
6516 {
6517 char tempname[MAXPATHL + 1];
6518
6519 /*
6520 * Find a name that doesn't exist and is in the same directory.
6521 * Rename "from" to "tempname" and then rename "tempname" to "to".
6522 */
6523 if (STRLEN(from) >= MAXPATHL - 5)
6524 return -1;
6525 STRCPY(tempname, from);
6526 for (n = 123; n < 99999; ++n)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006527 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006528 sprintf((char *)gettail((char_u *)tempname), "%d", n);
6529 if (mch_stat(tempname, &st) < 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006530 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006531 if (mch_rename((char *)from, tempname) == 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006532 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006533 if (mch_rename(tempname, (char *)to) == 0)
6534 return 0;
6535 /* Strange, the second step failed. Try moving the
6536 * file back and return failure. */
6537 mch_rename(tempname, (char *)from);
Bram Moolenaar3576da72008-12-30 15:15:57 +00006538 return -1;
6539 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006540 /* If it fails for one temp name it will most likely fail
6541 * for any temp name, give up. */
6542 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006543 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006544 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006545 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006546 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006547
Bram Moolenaar071d4272004-06-13 20:20:40 +00006548 /*
6549 * Delete the "to" file, this is required on some systems to make the
6550 * mch_rename() work, on other systems it makes sure that we don't have
6551 * two files when the mch_rename() fails.
6552 */
6553
6554#ifdef AMIGA
6555 /*
6556 * With MSDOS-compatible filesystems (crossdos, messydos) it is possible
6557 * that the name of the "to" file is the same as the "from" file, even
Bram Moolenaar7263a772007-05-10 17:35:54 +00006558 * though the names are different. To avoid the chance of accidentally
Bram Moolenaar071d4272004-06-13 20:20:40 +00006559 * deleting the "from" file (horror!) we lock it during the remove.
6560 *
6561 * When used for making a backup before writing the file: This should not
6562 * happen with ":w", because startscript() should detect this problem and
6563 * set buf->b_shortname, causing modname() to return a correct ".bak" file
6564 * name. This problem does exist with ":w filename", but then the
6565 * original file will be somewhere else so the backup isn't really
6566 * important. If autoscripting is off the rename may fail.
6567 */
6568 flock = Lock((UBYTE *)from, (long)ACCESS_READ);
6569#endif
6570 mch_remove(to);
6571#ifdef AMIGA
6572 if (flock)
6573 UnLock(flock);
6574#endif
6575
6576 /*
6577 * First try a normal rename, return if it works.
6578 */
6579 if (mch_rename((char *)from, (char *)to) == 0)
6580 return 0;
6581
6582 /*
6583 * Rename() failed, try copying the file.
6584 */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006585 perm = mch_getperm(from);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006586#ifdef HAVE_ACL
6587 /* For systems that support ACL: get the ACL from the original file. */
6588 acl = mch_get_acl(from);
6589#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006590 fd_in = mch_open((char *)from, O_RDONLY|O_EXTRA, 0);
6591 if (fd_in == -1)
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006592 {
6593#ifdef HAVE_ACL
6594 mch_free_acl(acl);
6595#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006596 return -1;
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006597 }
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006598
6599 /* Create the new file with same permissions as the original. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00006600 fd_out = mch_open((char *)to,
6601 O_CREAT|O_EXCL|O_WRONLY|O_EXTRA|O_NOFOLLOW, (int)perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006602 if (fd_out == -1)
6603 {
6604 close(fd_in);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006605#ifdef HAVE_ACL
6606 mch_free_acl(acl);
6607#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006608 return -1;
6609 }
6610
6611 buffer = (char *)alloc(BUFSIZE);
6612 if (buffer == NULL)
6613 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006614 close(fd_out);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006615 close(fd_in);
6616#ifdef HAVE_ACL
6617 mch_free_acl(acl);
6618#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006619 return -1;
6620 }
6621
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01006622 while ((n = read_eintr(fd_in, buffer, BUFSIZE)) > 0)
6623 if (write_eintr(fd_out, buffer, n) != n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006624 {
6625 errmsg = _("E208: Error writing to \"%s\"");
6626 break;
6627 }
6628
6629 vim_free(buffer);
6630 close(fd_in);
6631 if (close(fd_out) < 0)
6632 errmsg = _("E209: Error closing \"%s\"");
6633 if (n < 0)
6634 {
6635 errmsg = _("E210: Error reading \"%s\"");
6636 to = from;
6637 }
Bram Moolenaar7263a772007-05-10 17:35:54 +00006638#ifndef UNIX /* for Unix mch_open() already set the permission */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006639 mch_setperm(to, perm);
Bram Moolenaarc6039d82005-12-02 00:44:04 +00006640#endif
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006641#ifdef HAVE_ACL
6642 mch_set_acl(to, acl);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006643 mch_free_acl(acl);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006644#endif
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02006645#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaare8747442013-11-12 18:09:29 +01006646 mch_copy_sec(from, to);
Bram Moolenaar0671de32013-11-12 05:12:03 +01006647#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006648 if (errmsg != NULL)
6649 {
6650 EMSG2(errmsg, to);
6651 return -1;
6652 }
6653 mch_remove(from);
6654 return 0;
6655}
6656
6657static int already_warned = FALSE;
6658
6659/*
6660 * Check if any not hidden buffer has been changed.
6661 * Postpone the check if there are characters in the stuff buffer, a global
6662 * command is being executed, a mapping is being executed or an autocommand is
6663 * busy.
6664 * Returns TRUE if some message was written (screen should be redrawn and
6665 * cursor positioned).
6666 */
6667 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006668check_timestamps(
6669 int focus) /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006670{
6671 buf_T *buf;
6672 int didit = 0;
6673 int n;
6674
6675 /* Don't check timestamps while system() or another low-level function may
6676 * cause us to lose and gain focus. */
6677 if (no_check_timestamps > 0)
6678 return FALSE;
6679
6680 /* Avoid doing a check twice. The OK/Reload dialog can cause a focus
6681 * event and we would keep on checking if the file is steadily growing.
6682 * Do check again after typing something. */
6683 if (focus && did_check_timestamps)
6684 {
6685 need_check_timestamps = TRUE;
6686 return FALSE;
6687 }
6688
6689 if (!stuff_empty() || global_busy || !typebuf_typed()
6690#ifdef FEAT_AUTOCMD
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006691 || autocmd_busy || curbuf_lock > 0 || allbuf_lock > 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00006692#endif
6693 )
6694 need_check_timestamps = TRUE; /* check later */
6695 else
6696 {
6697 ++no_wait_return;
6698 did_check_timestamps = TRUE;
6699 already_warned = FALSE;
Bram Moolenaar29323592016-07-24 22:04:11 +02006700 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006701 {
6702 /* Only check buffers in a window. */
6703 if (buf->b_nwindows > 0)
6704 {
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006705 bufref_T bufref;
6706
6707 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006708 n = buf_check_timestamp(buf, focus);
6709 if (didit < n)
6710 didit = n;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006711 if (n > 0 && !bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006712 {
6713 /* Autocommands have removed the buffer, start at the
6714 * first one again. */
6715 buf = firstbuf;
6716 continue;
6717 }
6718 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006719 }
6720 --no_wait_return;
6721 need_check_timestamps = FALSE;
6722 if (need_wait_return && didit == 2)
6723 {
6724 /* make sure msg isn't overwritten */
6725 msg_puts((char_u *)"\n");
6726 out_flush();
6727 }
6728 }
6729 return didit;
6730}
6731
6732/*
6733 * Move all the lines from buffer "frombuf" to buffer "tobuf".
6734 * Return OK or FAIL. When FAIL "tobuf" is incomplete and/or "frombuf" is not
6735 * empty.
6736 */
6737 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006738move_lines(buf_T *frombuf, buf_T *tobuf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006739{
6740 buf_T *tbuf = curbuf;
6741 int retval = OK;
6742 linenr_T lnum;
6743 char_u *p;
6744
6745 /* Copy the lines in "frombuf" to "tobuf". */
6746 curbuf = tobuf;
6747 for (lnum = 1; lnum <= frombuf->b_ml.ml_line_count; ++lnum)
6748 {
6749 p = vim_strsave(ml_get_buf(frombuf, lnum, FALSE));
6750 if (p == NULL || ml_append(lnum - 1, p, 0, FALSE) == FAIL)
6751 {
6752 vim_free(p);
6753 retval = FAIL;
6754 break;
6755 }
6756 vim_free(p);
6757 }
6758
6759 /* Delete all the lines in "frombuf". */
6760 if (retval != FAIL)
6761 {
6762 curbuf = frombuf;
Bram Moolenaar9460b9d2007-01-09 14:37:01 +00006763 for (lnum = curbuf->b_ml.ml_line_count; lnum > 0; --lnum)
6764 if (ml_delete(lnum, FALSE) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006765 {
6766 /* Oops! We could try putting back the saved lines, but that
6767 * might fail again... */
6768 retval = FAIL;
6769 break;
6770 }
6771 }
6772
6773 curbuf = tbuf;
6774 return retval;
6775}
6776
6777/*
6778 * Check if buffer "buf" has been changed.
6779 * Also check if the file for a new buffer unexpectedly appeared.
6780 * return 1 if a changed buffer was found.
6781 * return 2 if a message has been displayed.
6782 * return 0 otherwise.
6783 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006784 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006785buf_check_timestamp(
6786 buf_T *buf,
6787 int focus UNUSED) /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006788{
Bram Moolenaar8767f522016-07-01 17:17:39 +02006789 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006790 int stat_res;
6791 int retval = 0;
6792 char_u *path;
6793 char_u *tbuf;
6794 char *mesg = NULL;
Bram Moolenaar44ecf652005-03-07 23:09:59 +00006795 char *mesg2 = "";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006796 int helpmesg = FALSE;
6797 int reload = FALSE;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006798 char *reason;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006799#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6800 int can_reload = FALSE;
6801#endif
Bram Moolenaar8767f522016-07-01 17:17:39 +02006802 off_T orig_size = buf->b_orig_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006803 int orig_mode = buf->b_orig_mode;
6804#ifdef FEAT_GUI
6805 int save_mouse_correct = need_mouse_correct;
6806#endif
6807#ifdef FEAT_AUTOCMD
6808 static int busy = FALSE;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006809 int n;
6810 char_u *s;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006811 bufref_T bufref;
6812
6813 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006814#endif
6815
6816 /* If there is no file name, the buffer is not loaded, 'buftype' is
6817 * set, we are in the middle of a save or being called recursively: ignore
6818 * this buffer. */
6819 if (buf->b_ffname == NULL
6820 || buf->b_ml.ml_mfp == NULL
6821#if defined(FEAT_QUICKFIX)
6822 || *buf->b_p_bt != NUL
6823#endif
6824 || buf->b_saving
6825#ifdef FEAT_AUTOCMD
6826 || busy
6827#endif
Bram Moolenaar009b2592004-10-24 19:18:58 +00006828#ifdef FEAT_NETBEANS_INTG
6829 || isNetbeansBuffer(buf)
6830#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006831 )
6832 return 0;
6833
6834 if ( !(buf->b_flags & BF_NOTEDITED)
6835 && buf->b_mtime != 0
6836 && ((stat_res = mch_stat((char *)buf->b_ffname, &st)) < 0
6837 || time_differs((long)st.st_mtime, buf->b_mtime)
Bram Moolenaara7611f62014-05-02 15:46:14 +02006838 || st.st_size != buf->b_orig_size
Bram Moolenaar071d4272004-06-13 20:20:40 +00006839#ifdef HAVE_ST_MODE
6840 || (int)st.st_mode != buf->b_orig_mode
6841#else
6842 || mch_getperm(buf->b_ffname) != buf->b_orig_mode
6843#endif
6844 ))
6845 {
6846 retval = 1;
6847
Bram Moolenaar316059c2006-01-14 21:18:42 +00006848 /* set b_mtime to stop further warnings (e.g., when executing
6849 * FileChangedShell autocmd) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006850 if (stat_res < 0)
6851 {
6852 buf->b_mtime = 0;
6853 buf->b_orig_size = 0;
6854 buf->b_orig_mode = 0;
6855 }
6856 else
6857 buf_store_time(buf, &st, buf->b_ffname);
6858
6859 /* Don't do anything for a directory. Might contain the file
6860 * explorer. */
6861 if (mch_isdir(buf->b_fname))
6862 ;
6863
6864 /*
6865 * If 'autoread' is set, the buffer has no changes and the file still
6866 * exists, reload the buffer. Use the buffer-local option value if it
6867 * was set, the global option value otherwise.
6868 */
6869 else if ((buf->b_p_ar >= 0 ? buf->b_p_ar : p_ar)
6870 && !bufIsChanged(buf) && stat_res >= 0)
6871 reload = TRUE;
6872 else
6873 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006874 if (stat_res < 0)
6875 reason = "deleted";
6876 else if (bufIsChanged(buf))
6877 reason = "conflict";
6878 else if (orig_size != buf->b_orig_size || buf_contents_changed(buf))
6879 reason = "changed";
6880 else if (orig_mode != buf->b_orig_mode)
6881 reason = "mode";
6882 else
6883 reason = "time";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006884
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006885#ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006886 /*
6887 * Only give the warning if there are no FileChangedShell
6888 * autocommands.
6889 * Avoid being called recursively by setting "busy".
6890 */
6891 busy = TRUE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00006892# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006893 set_vim_var_string(VV_FCS_REASON, (char_u *)reason, -1);
6894 set_vim_var_string(VV_FCS_CHOICE, (char_u *)"", -1);
Bram Moolenaar1e015462005-09-25 22:16:38 +00006895# endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006896 ++allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006897 n = apply_autocmds(EVENT_FILECHANGEDSHELL,
6898 buf->b_fname, buf->b_fname, FALSE, buf);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006899 --allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006900 busy = FALSE;
6901 if (n)
6902 {
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006903 if (!bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006904 EMSG(_("E246: FileChangedShell autocommand deleted buffer"));
Bram Moolenaar1e015462005-09-25 22:16:38 +00006905# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006906 s = get_vim_var_str(VV_FCS_CHOICE);
6907 if (STRCMP(s, "reload") == 0 && *reason != 'd')
6908 reload = TRUE;
6909 else if (STRCMP(s, "ask") == 0)
6910 n = FALSE;
6911 else
Bram Moolenaar1e015462005-09-25 22:16:38 +00006912# endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006913 return 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006914 }
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006915 if (!n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006916#endif
6917 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006918 if (*reason == 'd')
6919 mesg = _("E211: File \"%s\" no longer available");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006920 else
6921 {
6922 helpmesg = TRUE;
6923#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6924 can_reload = TRUE;
6925#endif
6926 /*
6927 * Check if the file contents really changed to avoid
6928 * giving a warning when only the timestamp was set (e.g.,
6929 * checked out of CVS). Always warn when the buffer was
6930 * changed.
6931 */
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006932 if (reason[2] == 'n')
6933 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006934 mesg = _("W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006935 mesg2 = _("See \":help W12\" for more info.");
6936 }
6937 else if (reason[1] == 'h')
6938 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006939 mesg = _("W11: Warning: File \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006940 mesg2 = _("See \":help W11\" for more info.");
6941 }
6942 else if (*reason == 'm')
6943 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006944 mesg = _("W16: Warning: Mode of file \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006945 mesg2 = _("See \":help W16\" for more info.");
6946 }
Bram Moolenaar85388b52009-06-24 09:58:32 +00006947 else
6948 /* Only timestamp changed, store it to avoid a warning
6949 * in check_mtime() later. */
6950 buf->b_mtime_read = buf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006951 }
6952 }
6953 }
6954
6955 }
6956 else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W)
6957 && vim_fexists(buf->b_ffname))
6958 {
6959 retval = 1;
6960 mesg = _("W13: Warning: File \"%s\" has been created after editing started");
6961 buf->b_flags |= BF_NEW_W;
6962#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6963 can_reload = TRUE;
6964#endif
6965 }
6966
6967 if (mesg != NULL)
6968 {
6969 path = home_replace_save(buf, buf->b_fname);
6970 if (path != NULL)
6971 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006972 if (!helpmesg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006973 mesg2 = "";
6974 tbuf = alloc((unsigned)(STRLEN(path) + STRLEN(mesg)
6975 + STRLEN(mesg2) + 2));
6976 sprintf((char *)tbuf, mesg, path);
Bram Moolenaar496c5262009-03-18 14:42:00 +00006977#ifdef FEAT_EVAL
6978 /* Set warningmsg here, before the unimportant and output-specific
6979 * mesg2 has been appended. */
6980 set_vim_var_string(VV_WARNINGMSG, tbuf, -1);
6981#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006982#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6983 if (can_reload)
6984 {
6985 if (*mesg2 != NUL)
6986 {
6987 STRCAT(tbuf, "\n");
6988 STRCAT(tbuf, mesg2);
6989 }
6990 if (do_dialog(VIM_WARNING, (char_u *)_("Warning"), tbuf,
Bram Moolenaard2c340a2011-01-17 20:08:11 +01006991 (char_u *)_("&OK\n&Load File"), 1, NULL, TRUE) == 2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006992 reload = TRUE;
6993 }
6994 else
6995#endif
6996 if (State > NORMAL_BUSY || (State & CMDLINE) || already_warned)
6997 {
6998 if (*mesg2 != NUL)
6999 {
7000 STRCAT(tbuf, "; ");
7001 STRCAT(tbuf, mesg2);
7002 }
7003 EMSG(tbuf);
7004 retval = 2;
7005 }
7006 else
7007 {
Bram Moolenaared203462004-06-16 11:19:22 +00007008# ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00007009 if (!autocmd_busy)
Bram Moolenaared203462004-06-16 11:19:22 +00007010# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007011 {
7012 msg_start();
7013 msg_puts_attr(tbuf, hl_attr(HLF_E) + MSG_HIST);
7014 if (*mesg2 != NUL)
7015 msg_puts_attr((char_u *)mesg2,
7016 hl_attr(HLF_W) + MSG_HIST);
7017 msg_clr_eos();
7018 (void)msg_end();
7019 if (emsg_silent == 0)
7020 {
7021 out_flush();
Bram Moolenaared203462004-06-16 11:19:22 +00007022# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00007023 if (!focus)
Bram Moolenaared203462004-06-16 11:19:22 +00007024# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007025 /* give the user some time to think about it */
7026 ui_delay(1000L, TRUE);
7027
7028 /* don't redraw and erase the message */
7029 redraw_cmdline = FALSE;
7030 }
7031 }
7032 already_warned = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007033 }
7034
7035 vim_free(path);
7036 vim_free(tbuf);
7037 }
7038 }
7039
7040 if (reload)
Bram Moolenaar465748e2012-08-29 18:50:54 +02007041 {
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007042 /* Reload the buffer. */
Bram Moolenaar316059c2006-01-14 21:18:42 +00007043 buf_reload(buf, orig_mode);
Bram Moolenaar465748e2012-08-29 18:50:54 +02007044#ifdef FEAT_PERSISTENT_UNDO
7045 if (buf->b_p_udf && buf->b_ffname != NULL)
7046 {
7047 char_u hash[UNDO_HASH_SIZE];
7048 buf_T *save_curbuf = curbuf;
7049
7050 /* Any existing undo file is unusable, write it now. */
7051 curbuf = buf;
7052 u_compute_hash(hash);
7053 u_write_undo(NULL, FALSE, buf, hash);
7054 curbuf = save_curbuf;
7055 }
7056#endif
7057 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007058
Bram Moolenaar56718732006-03-15 22:53:57 +00007059#ifdef FEAT_AUTOCMD
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00007060 /* Trigger FileChangedShell when the file was changed in any way. */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007061 if (bufref_valid(&bufref) && retval != 0)
Bram Moolenaar56718732006-03-15 22:53:57 +00007062 (void)apply_autocmds(EVENT_FILECHANGEDSHELLPOST,
7063 buf->b_fname, buf->b_fname, FALSE, buf);
7064#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007065#ifdef FEAT_GUI
7066 /* restore this in case an autocommand has set it; it would break
7067 * 'mousefocus' */
7068 need_mouse_correct = save_mouse_correct;
7069#endif
7070
7071 return retval;
7072}
7073
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007074/*
7075 * Reload a buffer that is already loaded.
7076 * Used when the file was changed outside of Vim.
Bram Moolenaar316059c2006-01-14 21:18:42 +00007077 * "orig_mode" is buf->b_orig_mode before the need for reloading was detected.
7078 * buf->b_orig_mode may have been reset already.
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007079 */
7080 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007081buf_reload(buf_T *buf, int orig_mode)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007082{
7083 exarg_T ea;
7084 pos_T old_cursor;
7085 linenr_T old_topline;
7086 int old_ro = buf->b_p_ro;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007087 buf_T *savebuf;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007088 bufref_T bufref;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007089 int saved = OK;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007090 aco_save_T aco;
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007091 int flags = READ_NEW;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007092
7093 /* set curwin/curbuf for "buf" and save some things */
7094 aucmd_prepbuf(&aco, buf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007095
7096 /* We only want to read the text from the file, not reset the syntax
7097 * highlighting, clear marks, diff status, etc. Force the fileformat
7098 * and encoding to be the same. */
7099 if (prep_exarg(&ea, buf) == OK)
7100 {
7101 old_cursor = curwin->w_cursor;
7102 old_topline = curwin->w_topline;
7103
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007104 if (p_ur < 0 || curbuf->b_ml.ml_line_count <= p_ur)
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007105 {
7106 /* Save all the text, so that the reload can be undone.
7107 * Sync first so that this is a separate undo-able action. */
7108 u_sync(FALSE);
7109 saved = u_savecommon(0, curbuf->b_ml.ml_line_count + 1, 0, TRUE);
7110 flags |= READ_KEEP_UNDO;
7111 }
7112
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007113 /*
7114 * To behave like when a new file is edited (matters for
7115 * BufReadPost autocommands) we first need to delete the current
7116 * buffer contents. But if reading the file fails we should keep
7117 * the old contents. Can't use memory only, the file might be
7118 * too big. Use a hidden buffer to move the buffer contents to.
7119 */
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007120 if (bufempty() || saved == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007121 savebuf = NULL;
7122 else
7123 {
7124 /* Allocate a buffer without putting it in the buffer list. */
7125 savebuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007126 set_bufref(&bufref, savebuf);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007127 if (savebuf != NULL && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007128 {
7129 /* Open the memline. */
7130 curbuf = savebuf;
7131 curwin->w_buffer = savebuf;
Bram Moolenaar4770d092006-01-12 23:22:24 +00007132 saved = ml_open(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007133 curbuf = buf;
7134 curwin->w_buffer = buf;
7135 }
Bram Moolenaar8424a622006-04-19 21:23:36 +00007136 if (savebuf == NULL || saved == FAIL || buf != curbuf
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007137 || move_lines(buf, savebuf) == FAIL)
7138 {
7139 EMSG2(_("E462: Could not prepare for reloading \"%s\""),
7140 buf->b_fname);
7141 saved = FAIL;
7142 }
7143 }
7144
7145 if (saved == OK)
7146 {
7147 curbuf->b_flags |= BF_CHECK_RO; /* check for RO again */
7148#ifdef FEAT_AUTOCMD
7149 keep_filetype = TRUE; /* don't detect 'filetype' */
7150#endif
7151 if (readfile(buf->b_ffname, buf->b_fname, (linenr_T)0,
7152 (linenr_T)0,
Bram Moolenaare13b9af2017-01-13 22:01:02 +01007153 (linenr_T)MAXLNUM, &ea, flags) != OK)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007154 {
7155#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
7156 if (!aborting())
7157#endif
7158 EMSG2(_("E321: Could not reload \"%s\""), buf->b_fname);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007159 if (savebuf != NULL && bufref_valid(&bufref) && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007160 {
7161 /* Put the text back from the save buffer. First
7162 * delete any lines that readfile() added. */
7163 while (!bufempty())
Bram Moolenaar8424a622006-04-19 21:23:36 +00007164 if (ml_delete(buf->b_ml.ml_line_count, FALSE) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007165 break;
7166 (void)move_lines(savebuf, buf);
7167 }
7168 }
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007169 else if (buf == curbuf) /* "buf" still valid */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007170 {
7171 /* Mark the buffer as unmodified and free undo info. */
7172 unchanged(buf, TRUE);
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007173 if ((flags & READ_KEEP_UNDO) == 0)
7174 {
7175 u_blockfree(buf);
7176 u_clearall(buf);
7177 }
7178 else
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007179 {
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007180 /* Mark all undo states as changed. */
7181 u_unchanged(curbuf);
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007182 }
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007183 }
7184 }
7185 vim_free(ea.cmd);
7186
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007187 if (savebuf != NULL && bufref_valid(&bufref))
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007188 wipe_buffer(savebuf, FALSE);
7189
7190#ifdef FEAT_DIFF
7191 /* Invalidate diff info if necessary. */
Bram Moolenaar8424a622006-04-19 21:23:36 +00007192 diff_invalidate(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007193#endif
7194
7195 /* Restore the topline and cursor position and check it (lines may
7196 * have been removed). */
7197 if (old_topline > curbuf->b_ml.ml_line_count)
7198 curwin->w_topline = curbuf->b_ml.ml_line_count;
7199 else
7200 curwin->w_topline = old_topline;
7201 curwin->w_cursor = old_cursor;
7202 check_cursor();
7203 update_topline();
7204#ifdef FEAT_AUTOCMD
7205 keep_filetype = FALSE;
7206#endif
7207#ifdef FEAT_FOLDING
7208 {
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007209 win_T *wp;
7210 tabpage_T *tp;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007211
7212 /* Update folds unless they are defined manually. */
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007213 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007214 if (wp->w_buffer == curwin->w_buffer
7215 && !foldmethodIsManual(wp))
7216 foldUpdateAll(wp);
7217 }
7218#endif
7219 /* If the mode didn't change and 'readonly' was set, keep the old
7220 * value; the user probably used the ":view" command. But don't
7221 * reset it, might have had a read error. */
7222 if (orig_mode == curbuf->b_orig_mode)
7223 curbuf->b_p_ro |= old_ro;
Bram Moolenaar52f85b72013-01-30 14:13:56 +01007224
7225 /* Modelines must override settings done by autocommands. */
7226 do_modelines(0);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007227 }
7228
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007229 /* restore curwin/curbuf and a few other things */
7230 aucmd_restbuf(&aco);
7231 /* Careful: autocommands may have made "buf" invalid! */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007232}
7233
Bram Moolenaar071d4272004-06-13 20:20:40 +00007234 void
Bram Moolenaar8767f522016-07-01 17:17:39 +02007235buf_store_time(buf_T *buf, stat_T *st, char_u *fname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007236{
7237 buf->b_mtime = (long)st->st_mtime;
Bram Moolenaar914703b2010-05-31 21:59:46 +02007238 buf->b_orig_size = st->st_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007239#ifdef HAVE_ST_MODE
7240 buf->b_orig_mode = (int)st->st_mode;
7241#else
7242 buf->b_orig_mode = mch_getperm(fname);
7243#endif
7244}
7245
7246/*
7247 * Adjust the line with missing eol, used for the next write.
7248 * Used for do_filter(), when the input lines for the filter are deleted.
7249 */
7250 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007251write_lnum_adjust(linenr_T offset)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007252{
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01007253 if (curbuf->b_no_eol_lnum != 0) /* only if there is a missing eol */
7254 curbuf->b_no_eol_lnum += offset;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007255}
7256
Bram Moolenaarda440d22016-01-16 21:27:23 +01007257#if defined(TEMPDIRNAMES) || defined(FEAT_EVAL) || defined(PROTO)
7258/*
7259 * Delete "name" and everything in it, recursively.
7260 * return 0 for succes, -1 if some file was not deleted.
7261 */
7262 int
7263delete_recursive(char_u *name)
7264{
7265 int result = 0;
7266 char_u **files;
7267 int file_count;
7268 int i;
7269 char_u *exp;
7270
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007271 /* A symbolic link to a directory itself is deleted, not the directory it
7272 * points to. */
7273 if (
Bram Moolenaar203258c2016-01-17 22:15:16 +01007274# if defined(UNIX) || defined(WIN32)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007275 mch_isrealdir(name)
Bram Moolenaar203258c2016-01-17 22:15:16 +01007276# else
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007277 mch_isdir(name)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007278# endif
7279 )
Bram Moolenaarda440d22016-01-16 21:27:23 +01007280 {
7281 vim_snprintf((char *)NameBuff, MAXPATHL, "%s/*", name);
7282 exp = vim_strsave(NameBuff);
7283 if (exp == NULL)
7284 return -1;
7285 if (gen_expand_wildcards(1, &exp, &file_count, &files,
Bram Moolenaar336bd622016-01-17 18:23:58 +01007286 EW_DIR|EW_FILE|EW_SILENT|EW_ALLLINKS|EW_DODOT|EW_EMPTYOK) == OK)
Bram Moolenaarda440d22016-01-16 21:27:23 +01007287 {
7288 for (i = 0; i < file_count; ++i)
7289 if (delete_recursive(files[i]) != 0)
7290 result = -1;
7291 FreeWild(file_count, files);
7292 }
7293 else
7294 result = -1;
7295 vim_free(exp);
7296 (void)mch_rmdir(name);
7297 }
7298 else
7299 result = mch_remove(name) == 0 ? 0 : -1;
7300
7301 return result;
7302}
7303#endif
7304
Bram Moolenaar071d4272004-06-13 20:20:40 +00007305#if defined(TEMPDIRNAMES) || defined(PROTO)
7306static long temp_count = 0; /* Temp filename counter. */
7307
7308/*
7309 * Delete the temp directory and all files it contains.
7310 */
7311 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007312vim_deltempdir(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007313{
Bram Moolenaar071d4272004-06-13 20:20:40 +00007314 if (vim_tempdir != NULL)
7315 {
Bram Moolenaarda440d22016-01-16 21:27:23 +01007316 /* remove the trailing path separator */
7317 gettail(vim_tempdir)[-1] = NUL;
7318 delete_recursive(vim_tempdir);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007319 vim_free(vim_tempdir);
7320 vim_tempdir = NULL;
7321 }
7322}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007323
7324/*
Bram Moolenaareaf03392009-11-17 11:08:52 +00007325 * Directory "tempdir" was created. Expand this name to a full path and put
7326 * it in "vim_tempdir". This avoids that using ":cd" would confuse us.
7327 * "tempdir" must be no longer than MAXPATHL.
7328 */
7329 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007330vim_settempdir(char_u *tempdir)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007331{
7332 char_u *buf;
7333
7334 buf = alloc((unsigned)MAXPATHL + 2);
7335 if (buf != NULL)
7336 {
7337 if (vim_FullName(tempdir, buf, MAXPATHL, FALSE) == FAIL)
7338 STRCPY(buf, tempdir);
Bram Moolenaara06ecab2016-07-16 14:47:36 +02007339 add_pathsep(buf);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007340 vim_tempdir = vim_strsave(buf);
7341 vim_free(buf);
7342 }
7343}
Bram Moolenaar4592dee2009-11-18 19:11:58 +00007344#endif
Bram Moolenaareaf03392009-11-17 11:08:52 +00007345
7346/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007347 * vim_tempname(): Return a unique name that can be used for a temp file.
7348 *
Bram Moolenaar76ae22f2016-06-13 20:00:29 +02007349 * The temp file is NOT guaranteed to be created. If "keep" is FALSE it is
7350 * guaranteed to NOT be created.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007351 *
7352 * The returned pointer is to allocated memory.
7353 * The returned pointer is NULL if no valid name was found.
7354 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007355 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007356vim_tempname(
7357 int extra_char UNUSED, /* char to use in the name instead of '?' */
7358 int keep UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007359{
7360#ifdef USE_TMPNAM
7361 char_u itmp[L_tmpnam]; /* use tmpnam() */
7362#else
7363 char_u itmp[TEMPNAMELEN];
7364#endif
7365
7366#ifdef TEMPDIRNAMES
7367 static char *(tempdirs[]) = {TEMPDIRNAMES};
7368 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007369# ifndef EEXIST
Bram Moolenaar8767f522016-07-01 17:17:39 +02007370 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007371# endif
7372
7373 /*
7374 * This will create a directory for private use by this instance of Vim.
7375 * This is done once, and the same directory is used for all temp files.
7376 * This method avoids security problems because of symlink attacks et al.
7377 * It's also a bit faster, because we only need to check for an existing
7378 * file when creating the directory and not for each temp file.
7379 */
7380 if (vim_tempdir == NULL)
7381 {
7382 /*
7383 * Try the entries in TEMPDIRNAMES to create the temp directory.
7384 */
Bram Moolenaar78a15312009-05-15 19:33:18 +00007385 for (i = 0; i < (int)(sizeof(tempdirs) / sizeof(char *)); ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007386 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007387# ifndef HAVE_MKDTEMP
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007388 size_t itmplen;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007389 long nr;
7390 long off;
7391# endif
7392
Bram Moolenaare1a61992015-12-03 21:02:27 +01007393 /* Expand $TMP, leave room for "/v1100000/999999999".
7394 * Skip the directory check if the expansion fails. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007395 expand_env((char_u *)tempdirs[i], itmp, TEMPNAMELEN - 20);
Bram Moolenaare1a61992015-12-03 21:02:27 +01007396 if (itmp[0] != '$' && mch_isdir(itmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007397 {
Bram Moolenaare1a61992015-12-03 21:02:27 +01007398 /* directory exists */
Bram Moolenaara06ecab2016-07-16 14:47:36 +02007399 add_pathsep(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007400
Bram Moolenaareaf03392009-11-17 11:08:52 +00007401# ifdef HAVE_MKDTEMP
Bram Moolenaar35d88f42016-06-04 14:52:00 +02007402 {
7403# if defined(UNIX) || defined(VMS)
7404 /* Make sure the umask doesn't remove the executable bit.
7405 * "repl" has been reported to use "177". */
7406 mode_t umask_save = umask(077);
7407# endif
7408 /* Leave room for filename */
7409 STRCAT(itmp, "vXXXXXX");
7410 if (mkdtemp((char *)itmp) != NULL)
7411 vim_settempdir(itmp);
7412# if defined(UNIX) || defined(VMS)
7413 (void)umask(umask_save);
7414# endif
7415 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007416# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007417 /* Get an arbitrary number of up to 6 digits. When it's
7418 * unlikely that it already exists it will be faster,
7419 * otherwise it doesn't matter. The use of mkdir() avoids any
7420 * security problems because of the predictable number. */
7421 nr = (mch_get_pid() + (long)time(NULL)) % 1000000L;
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007422 itmplen = STRLEN(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007423
7424 /* Try up to 10000 different values until we find a name that
7425 * doesn't exist. */
7426 for (off = 0; off < 10000L; ++off)
7427 {
7428 int r;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007429# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007430 mode_t umask_save;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007431# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007432
Bram Moolenaareaf03392009-11-17 11:08:52 +00007433 sprintf((char *)itmp + itmplen, "v%ld", nr + off);
7434# ifndef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007435 /* If mkdir() does not set errno to EEXIST, check for
7436 * existing file here. There is a race condition then,
7437 * although it's fail-safe. */
7438 if (mch_stat((char *)itmp, &st) >= 0)
7439 continue;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007440# endif
7441# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007442 /* Make sure the umask doesn't remove the executable bit.
7443 * "repl" has been reported to use "177". */
7444 umask_save = umask(077);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007445# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007446 r = vim_mkdir(itmp, 0700);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007447# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007448 (void)umask(umask_save);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007449# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007450 if (r == 0)
7451 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007452 vim_settempdir(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007453 break;
7454 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007455# ifdef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007456 /* If the mkdir() didn't fail because the file/dir exists,
7457 * we probably can't create any dir here, try another
7458 * place. */
7459 if (errno != EEXIST)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007460# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007461 break;
7462 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007463# endif /* HAVE_MKDTEMP */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007464 if (vim_tempdir != NULL)
7465 break;
7466 }
7467 }
7468 }
7469
7470 if (vim_tempdir != NULL)
7471 {
7472 /* There is no need to check if the file exists, because we own the
7473 * directory and nobody else creates a file in it. */
7474 sprintf((char *)itmp, "%s%ld", vim_tempdir, temp_count++);
7475 return vim_strsave(itmp);
7476 }
7477
7478 return NULL;
7479
7480#else /* TEMPDIRNAMES */
7481
7482# ifdef WIN3264
7483 char szTempFile[_MAX_PATH + 1];
7484 char buf4[4];
7485 char_u *retval;
7486 char_u *p;
7487
7488 STRCPY(itmp, "");
7489 if (GetTempPath(_MAX_PATH, szTempFile) == 0)
Bram Moolenaarb1891912011-02-09 14:47:03 +01007490 {
7491 szTempFile[0] = '.'; /* GetTempPath() failed, use current dir */
7492 szTempFile[1] = NUL;
7493 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007494 strcpy(buf4, "VIM");
7495 buf4[2] = extra_char; /* make it "VIa", "VIb", etc. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007496 if (GetTempFileName(szTempFile, buf4, 0, (LPSTR)itmp) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007497 return NULL;
Bram Moolenaare5c421c2015-03-31 13:33:08 +02007498 if (!keep)
7499 /* GetTempFileName() will create the file, we don't want that */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007500 (void)DeleteFile((LPSTR)itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007501
7502 /* Backslashes in a temp file name cause problems when filtering with
7503 * "sh". NOTE: This also checks 'shellcmdflag' to help those people who
7504 * didn't set 'shellslash'. */
7505 retval = vim_strsave(itmp);
7506 if (*p_shcf == '-' || p_ssl)
7507 for (p = retval; *p; ++p)
7508 if (*p == '\\')
7509 *p = '/';
7510 return retval;
7511
7512# else /* WIN3264 */
7513
7514# ifdef USE_TMPNAM
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007515 char_u *p;
7516
Bram Moolenaar071d4272004-06-13 20:20:40 +00007517 /* tmpnam() will make its own name */
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007518 p = tmpnam((char *)itmp);
7519 if (p == NULL || *p == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007520 return NULL;
7521# else
7522 char_u *p;
7523
7524# ifdef VMS_TEMPNAM
7525 /* mktemp() is not working on VMS. It seems to be
7526 * a do-nothing function. Therefore we use tempnam().
7527 */
7528 sprintf((char *)itmp, "VIM%c", extra_char);
7529 p = (char_u *)tempnam("tmp:", (char *)itmp);
7530 if (p != NULL)
7531 {
Bram Moolenaar206f0112014-03-12 16:51:55 +01007532 /* VMS will use '.LIS' if we don't explicitly specify an extension,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007533 * and VIM will then be unable to find the file later */
7534 STRCPY(itmp, p);
7535 STRCAT(itmp, ".txt");
7536 free(p);
7537 }
7538 else
7539 return NULL;
7540# else
7541 STRCPY(itmp, TEMPNAME);
7542 if ((p = vim_strchr(itmp, '?')) != NULL)
7543 *p = extra_char;
7544 if (mktemp((char *)itmp) == NULL)
7545 return NULL;
7546# endif
7547# endif
7548
7549 return vim_strsave(itmp);
7550# endif /* WIN3264 */
7551#endif /* TEMPDIRNAMES */
7552}
7553
7554#if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
7555/*
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02007556 * Convert all backslashes in fname to forward slashes in-place, unless when
7557 * it looks like a URL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007558 */
7559 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007560forward_slash(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007561{
7562 char_u *p;
7563
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02007564 if (path_with_url(fname))
7565 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007566 for (p = fname; *p != NUL; ++p)
7567# ifdef FEAT_MBYTE
7568 /* The Big5 encoding can have '\' in the trail byte. */
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00007569 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007570 ++p;
7571 else
7572# endif
7573 if (*p == '\\')
7574 *p = '/';
7575}
7576#endif
7577
7578
7579/*
7580 * Code for automatic commands.
7581 *
7582 * Only included when "FEAT_AUTOCMD" has been defined.
7583 */
7584
7585#if defined(FEAT_AUTOCMD) || defined(PROTO)
7586
7587/*
7588 * The autocommands are stored in a list for each event.
7589 * Autocommands for the same pattern, that are consecutive, are joined
7590 * together, to avoid having to match the pattern too often.
7591 * The result is an array of Autopat lists, which point to AutoCmd lists:
7592 *
7593 * first_autopat[0] --> Autopat.next --> Autopat.next --> NULL
7594 * Autopat.cmds Autopat.cmds
7595 * | |
7596 * V V
7597 * AutoCmd.next AutoCmd.next
7598 * | |
7599 * V V
7600 * AutoCmd.next NULL
7601 * |
7602 * V
7603 * NULL
7604 *
7605 * first_autopat[1] --> Autopat.next --> NULL
7606 * Autopat.cmds
7607 * |
7608 * V
7609 * AutoCmd.next
7610 * |
7611 * V
7612 * NULL
7613 * etc.
7614 *
7615 * The order of AutoCmds is important, this is the order in which they were
7616 * defined and will have to be executed.
7617 */
7618typedef struct AutoCmd
7619{
7620 char_u *cmd; /* The command to be executed (NULL
7621 when command has been removed) */
7622 char nested; /* If autocommands nest here */
7623 char last; /* last command in list */
7624#ifdef FEAT_EVAL
7625 scid_T scriptID; /* script ID where defined */
7626#endif
7627 struct AutoCmd *next; /* Next AutoCmd in list */
7628} AutoCmd;
7629
7630typedef struct AutoPat
7631{
Bram Moolenaar071d4272004-06-13 20:20:40 +00007632 char_u *pat; /* pattern as typed (NULL when pattern
7633 has been removed) */
Bram Moolenaar748bf032005-02-02 23:04:36 +00007634 regprog_T *reg_prog; /* compiled regprog for pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007635 AutoCmd *cmds; /* list of commands to do */
7636 struct AutoPat *next; /* next AutoPat in AutoPat list */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007637 int group; /* group ID */
7638 int patlen; /* strlen() of pat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007639 int buflocal_nr; /* !=0 for buffer-local AutoPat */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007640 char allow_dirs; /* Pattern may match whole path */
7641 char last; /* last pattern for apply_autocmds() */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007642} AutoPat;
7643
7644static struct event_name
7645{
7646 char *name; /* event name */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007647 event_T event; /* event number */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007648} event_names[] =
7649{
7650 {"BufAdd", EVENT_BUFADD},
7651 {"BufCreate", EVENT_BUFADD},
7652 {"BufDelete", EVENT_BUFDELETE},
7653 {"BufEnter", EVENT_BUFENTER},
7654 {"BufFilePost", EVENT_BUFFILEPOST},
7655 {"BufFilePre", EVENT_BUFFILEPRE},
7656 {"BufHidden", EVENT_BUFHIDDEN},
7657 {"BufLeave", EVENT_BUFLEAVE},
7658 {"BufNew", EVENT_BUFNEW},
7659 {"BufNewFile", EVENT_BUFNEWFILE},
7660 {"BufRead", EVENT_BUFREADPOST},
7661 {"BufReadCmd", EVENT_BUFREADCMD},
7662 {"BufReadPost", EVENT_BUFREADPOST},
7663 {"BufReadPre", EVENT_BUFREADPRE},
7664 {"BufUnload", EVENT_BUFUNLOAD},
7665 {"BufWinEnter", EVENT_BUFWINENTER},
7666 {"BufWinLeave", EVENT_BUFWINLEAVE},
7667 {"BufWipeout", EVENT_BUFWIPEOUT},
7668 {"BufWrite", EVENT_BUFWRITEPRE},
7669 {"BufWritePost", EVENT_BUFWRITEPOST},
7670 {"BufWritePre", EVENT_BUFWRITEPRE},
7671 {"BufWriteCmd", EVENT_BUFWRITECMD},
7672 {"CmdwinEnter", EVENT_CMDWINENTER},
7673 {"CmdwinLeave", EVENT_CMDWINLEAVE},
Bram Moolenaard5005162014-08-22 23:05:54 +02007674 {"CmdUndefined", EVENT_CMDUNDEFINED},
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007675 {"ColorScheme", EVENT_COLORSCHEME},
Bram Moolenaarcfa3cae2012-07-10 17:14:56 +02007676 {"CompleteDone", EVENT_COMPLETEDONE},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007677 {"CursorHold", EVENT_CURSORHOLD},
7678 {"CursorHoldI", EVENT_CURSORHOLDI},
7679 {"CursorMoved", EVENT_CURSORMOVED},
7680 {"CursorMovedI", EVENT_CURSORMOVEDI},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007681 {"EncodingChanged", EVENT_ENCODINGCHANGED},
7682 {"FileEncoding", EVENT_ENCODINGCHANGED},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007683 {"FileAppendPost", EVENT_FILEAPPENDPOST},
7684 {"FileAppendPre", EVENT_FILEAPPENDPRE},
7685 {"FileAppendCmd", EVENT_FILEAPPENDCMD},
7686 {"FileChangedShell",EVENT_FILECHANGEDSHELL},
Bram Moolenaar56718732006-03-15 22:53:57 +00007687 {"FileChangedShellPost",EVENT_FILECHANGEDSHELLPOST},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007688 {"FileChangedRO", EVENT_FILECHANGEDRO},
7689 {"FileReadPost", EVENT_FILEREADPOST},
7690 {"FileReadPre", EVENT_FILEREADPRE},
7691 {"FileReadCmd", EVENT_FILEREADCMD},
7692 {"FileType", EVENT_FILETYPE},
7693 {"FileWritePost", EVENT_FILEWRITEPOST},
7694 {"FileWritePre", EVENT_FILEWRITEPRE},
7695 {"FileWriteCmd", EVENT_FILEWRITECMD},
7696 {"FilterReadPost", EVENT_FILTERREADPOST},
7697 {"FilterReadPre", EVENT_FILTERREADPRE},
7698 {"FilterWritePost", EVENT_FILTERWRITEPOST},
7699 {"FilterWritePre", EVENT_FILTERWRITEPRE},
7700 {"FocusGained", EVENT_FOCUSGAINED},
7701 {"FocusLost", EVENT_FOCUSLOST},
7702 {"FuncUndefined", EVENT_FUNCUNDEFINED},
7703 {"GUIEnter", EVENT_GUIENTER},
Bram Moolenaar265e5072006-08-29 16:13:22 +00007704 {"GUIFailed", EVENT_GUIFAILED},
Bram Moolenaar843ee412004-06-30 16:16:41 +00007705 {"InsertChange", EVENT_INSERTCHANGE},
7706 {"InsertEnter", EVENT_INSERTENTER},
7707 {"InsertLeave", EVENT_INSERTLEAVE},
Bram Moolenaare659c952011-05-19 17:25:41 +02007708 {"InsertCharPre", EVENT_INSERTCHARPRE},
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00007709 {"MenuPopup", EVENT_MENUPOPUP},
Bram Moolenaar53744302015-07-17 17:38:22 +02007710 {"OptionSet", EVENT_OPTIONSET},
Bram Moolenaar7c626922005-02-07 22:01:03 +00007711 {"QuickFixCmdPost", EVENT_QUICKFIXCMDPOST},
7712 {"QuickFixCmdPre", EVENT_QUICKFIXCMDPRE},
Bram Moolenaar3b53dfb2012-06-06 18:03:07 +02007713 {"QuitPre", EVENT_QUITPRE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007714 {"RemoteReply", EVENT_REMOTEREPLY},
Bram Moolenaar9372a112005-12-06 19:59:18 +00007715 {"SessionLoadPost", EVENT_SESSIONLOADPOST},
Bram Moolenaar5c4bab02006-03-10 21:37:46 +00007716 {"ShellCmdPost", EVENT_SHELLCMDPOST},
7717 {"ShellFilterPost", EVENT_SHELLFILTERPOST},
Bram Moolenaara2031822006-03-07 22:29:51 +00007718 {"SourcePre", EVENT_SOURCEPRE},
Bram Moolenaar8dd1aa52007-01-16 20:33:19 +00007719 {"SourceCmd", EVENT_SOURCECMD},
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00007720 {"SpellFileMissing",EVENT_SPELLFILEMISSING},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007721 {"StdinReadPost", EVENT_STDINREADPOST},
7722 {"StdinReadPre", EVENT_STDINREADPRE},
Bram Moolenaarb815dac2005-12-07 20:59:24 +00007723 {"SwapExists", EVENT_SWAPEXISTS},
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00007724 {"Syntax", EVENT_SYNTAX},
Bram Moolenaarc917da42016-07-19 22:31:36 +02007725 {"TabNew", EVENT_TABNEW},
Bram Moolenaar12c11d52016-07-19 23:13:03 +02007726 {"TabClosed", EVENT_TABCLOSED},
Bram Moolenaar70836c82006-02-20 21:28:49 +00007727 {"TabEnter", EVENT_TABENTER},
7728 {"TabLeave", EVENT_TABLEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007729 {"TermChanged", EVENT_TERMCHANGED},
7730 {"TermResponse", EVENT_TERMRESPONSE},
Bram Moolenaar186628f2013-03-19 13:33:23 +01007731 {"TextChanged", EVENT_TEXTCHANGED},
7732 {"TextChangedI", EVENT_TEXTCHANGEDI},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007733 {"User", EVENT_USER},
7734 {"VimEnter", EVENT_VIMENTER},
7735 {"VimLeave", EVENT_VIMLEAVE},
7736 {"VimLeavePre", EVENT_VIMLEAVEPRE},
Bram Moolenaarc917da42016-07-19 22:31:36 +02007737 {"WinNew", EVENT_WINNEW},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007738 {"WinEnter", EVENT_WINENTER},
7739 {"WinLeave", EVENT_WINLEAVE},
Bram Moolenaar56718732006-03-15 22:53:57 +00007740 {"VimResized", EVENT_VIMRESIZED},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007741 {NULL, (event_T)0}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007742};
7743
7744static AutoPat *first_autopat[NUM_EVENTS] =
7745{
7746 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7747 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7748 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7749 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00007750 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaar53744302015-07-17 17:38:22 +02007751 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007752};
7753
7754/*
7755 * struct used to keep status while executing autocommands for an event.
7756 */
7757typedef struct AutoPatCmd
7758{
7759 AutoPat *curpat; /* next AutoPat to examine */
7760 AutoCmd *nextcmd; /* next AutoCmd to execute */
7761 int group; /* group being used */
7762 char_u *fname; /* fname to match with */
7763 char_u *sfname; /* sfname to match with */
7764 char_u *tail; /* tail of fname */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007765 event_T event; /* current event */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007766 int arg_bufnr; /* initially equal to <abuf>, set to zero when
7767 buf is deleted */
7768 struct AutoPatCmd *next; /* chain of active apc-s for auto-invalidation*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00007769} AutoPatCmd;
7770
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007771static AutoPatCmd *active_apc_list = NULL; /* stack of active autocommands */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007772
Bram Moolenaar071d4272004-06-13 20:20:40 +00007773/*
7774 * augroups stores a list of autocmd group names.
7775 */
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007776static garray_T augroups = {0, 0, sizeof(char_u *), 10, NULL};
Bram Moolenaar071d4272004-06-13 20:20:40 +00007777#define AUGROUP_NAME(i) (((char_u **)augroups.ga_data)[i])
Bram Moolenaarb62cc362016-09-03 16:43:53 +02007778/* use get_deleted_augroup() to get this */
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02007779static char_u *deleted_augroup = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007780
7781/*
7782 * The ID of the current group. Group 0 is the default one.
7783 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007784static int current_augroup = AUGROUP_DEFAULT;
7785
7786static int au_need_clean = FALSE; /* need to delete marked patterns */
7787
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007788static void show_autocmd(AutoPat *ap, event_T event);
7789static void au_remove_pat(AutoPat *ap);
7790static void au_remove_cmds(AutoPat *ap);
7791static void au_cleanup(void);
7792static int au_new_group(char_u *name);
7793static void au_del_group(char_u *name);
7794static event_T event_name2nr(char_u *start, char_u **end);
7795static char_u *event_nr2name(event_T event);
7796static char_u *find_end_event(char_u *arg, int have_group);
7797static int event_ignored(event_T event);
7798static int au_get_grouparg(char_u **argp);
7799static int do_autocmd_event(event_T event, char_u *pat, int nested, char_u *cmd, int forceit, int group);
7800static int apply_autocmds_group(event_T event, char_u *fname, char_u *fname_io, int force, int group, buf_T *buf, exarg_T *eap);
7801static void auto_next_pat(AutoPatCmd *apc, int stop_at_last);
Bram Moolenaardffa5b82014-11-19 16:38:07 +01007802#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN)
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007803static 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 +01007804#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007805
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007806
Bram Moolenaar754b5602006-02-09 23:53:20 +00007807static event_T last_event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007808static int last_group;
Bram Moolenaar78ab3312007-09-29 12:16:41 +00007809static int autocmd_blocked = 0; /* block all autocmds */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007810
Bram Moolenaarb62cc362016-09-03 16:43:53 +02007811 static char_u *
7812get_deleted_augroup(void)
7813{
7814 if (deleted_augroup == NULL)
7815 deleted_augroup = (char_u *)_("--Deleted--");
7816 return deleted_augroup;
7817}
7818
Bram Moolenaar071d4272004-06-13 20:20:40 +00007819/*
7820 * Show the autocommands for one AutoPat.
7821 */
7822 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007823show_autocmd(AutoPat *ap, event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007824{
7825 AutoCmd *ac;
7826
7827 /* Check for "got_int" (here and at various places below), which is set
7828 * when "q" has been hit for the "--more--" prompt */
7829 if (got_int)
7830 return;
7831 if (ap->pat == NULL) /* pattern has been removed */
7832 return;
7833
7834 msg_putchar('\n');
7835 if (got_int)
7836 return;
7837 if (event != last_event || ap->group != last_group)
7838 {
7839 if (ap->group != AUGROUP_DEFAULT)
7840 {
7841 if (AUGROUP_NAME(ap->group) == NULL)
Bram Moolenaarb62cc362016-09-03 16:43:53 +02007842 msg_puts_attr(get_deleted_augroup(), hl_attr(HLF_E));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007843 else
7844 msg_puts_attr(AUGROUP_NAME(ap->group), hl_attr(HLF_T));
7845 msg_puts((char_u *)" ");
7846 }
7847 msg_puts_attr(event_nr2name(event), hl_attr(HLF_T));
7848 last_event = event;
7849 last_group = ap->group;
7850 msg_putchar('\n');
7851 if (got_int)
7852 return;
7853 }
7854 msg_col = 4;
7855 msg_outtrans(ap->pat);
7856
7857 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7858 {
7859 if (ac->cmd != NULL) /* skip removed commands */
7860 {
7861 if (msg_col >= 14)
7862 msg_putchar('\n');
7863 msg_col = 14;
7864 if (got_int)
7865 return;
7866 msg_outtrans(ac->cmd);
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00007867#ifdef FEAT_EVAL
7868 if (p_verbose > 0)
7869 last_set_msg(ac->scriptID);
7870#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007871 if (got_int)
7872 return;
7873 if (ac->next != NULL)
7874 {
7875 msg_putchar('\n');
7876 if (got_int)
7877 return;
7878 }
7879 }
7880 }
7881}
7882
7883/*
7884 * Mark an autocommand pattern for deletion.
7885 */
7886 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007887au_remove_pat(AutoPat *ap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007888{
7889 vim_free(ap->pat);
7890 ap->pat = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007891 ap->buflocal_nr = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007892 au_need_clean = TRUE;
7893}
7894
7895/*
7896 * Mark all commands for a pattern for deletion.
7897 */
7898 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007899au_remove_cmds(AutoPat *ap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007900{
7901 AutoCmd *ac;
7902
7903 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7904 {
7905 vim_free(ac->cmd);
7906 ac->cmd = NULL;
7907 }
7908 au_need_clean = TRUE;
7909}
7910
7911/*
7912 * Cleanup autocommands and patterns that have been deleted.
7913 * This is only done when not executing autocommands.
7914 */
7915 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007916au_cleanup(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007917{
7918 AutoPat *ap, **prev_ap;
7919 AutoCmd *ac, **prev_ac;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007920 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007921
7922 if (autocmd_busy || !au_need_clean)
7923 return;
7924
7925 /* loop over all events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007926 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7927 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007928 {
7929 /* loop over all autocommand patterns */
7930 prev_ap = &(first_autopat[(int)event]);
7931 for (ap = *prev_ap; ap != NULL; ap = *prev_ap)
7932 {
7933 /* loop over all commands for this pattern */
7934 prev_ac = &(ap->cmds);
7935 for (ac = *prev_ac; ac != NULL; ac = *prev_ac)
7936 {
7937 /* remove the command if the pattern is to be deleted or when
7938 * the command has been marked for deletion */
7939 if (ap->pat == NULL || ac->cmd == NULL)
7940 {
7941 *prev_ac = ac->next;
7942 vim_free(ac->cmd);
7943 vim_free(ac);
7944 }
7945 else
7946 prev_ac = &(ac->next);
7947 }
7948
7949 /* remove the pattern if it has been marked for deletion */
7950 if (ap->pat == NULL)
7951 {
7952 *prev_ap = ap->next;
Bram Moolenaar473de612013-06-08 18:19:48 +02007953 vim_regfree(ap->reg_prog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007954 vim_free(ap);
7955 }
7956 else
7957 prev_ap = &(ap->next);
7958 }
7959 }
7960
7961 au_need_clean = FALSE;
7962}
7963
7964/*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007965 * Called when buffer is freed, to remove/invalidate related buffer-local
7966 * autocmds.
7967 */
7968 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007969aubuflocal_remove(buf_T *buf)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007970{
7971 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007972 event_T event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007973 AutoPatCmd *apc;
7974
7975 /* invalidate currently executing autocommands */
7976 for (apc = active_apc_list; apc; apc = apc->next)
7977 if (buf->b_fnum == apc->arg_bufnr)
7978 apc->arg_bufnr = 0;
7979
7980 /* invalidate buflocals looping through events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007981 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7982 event = (event_T)((int)event + 1))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007983 /* loop over all autocommand patterns */
7984 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
7985 if (ap->buflocal_nr == buf->b_fnum)
7986 {
7987 au_remove_pat(ap);
7988 if (p_verbose >= 6)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007989 {
7990 verbose_enter();
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007991 smsg((char_u *)
7992 _("auto-removing autocommand: %s <buffer=%d>"),
7993 event_nr2name(event), buf->b_fnum);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007994 verbose_leave();
7995 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007996 }
7997 au_cleanup();
7998}
7999
8000/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008001 * Add an autocmd group name.
8002 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
8003 */
8004 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008005au_new_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008006{
8007 int i;
8008
8009 i = au_find_group(name);
8010 if (i == AUGROUP_ERROR) /* the group doesn't exist yet, add it */
8011 {
8012 /* First try using a free entry. */
8013 for (i = 0; i < augroups.ga_len; ++i)
8014 if (AUGROUP_NAME(i) == NULL)
8015 break;
8016 if (i == augroups.ga_len && ga_grow(&augroups, 1) == FAIL)
8017 return AUGROUP_ERROR;
8018
8019 AUGROUP_NAME(i) = vim_strsave(name);
8020 if (AUGROUP_NAME(i) == NULL)
8021 return AUGROUP_ERROR;
8022 if (i == augroups.ga_len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008023 ++augroups.ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008024 }
8025
8026 return i;
8027}
8028
8029 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008030au_del_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008031{
8032 int i;
8033
8034 i = au_find_group(name);
8035 if (i == AUGROUP_ERROR) /* the group doesn't exist */
8036 EMSG2(_("E367: No such group: \"%s\""), name);
Bram Moolenaarde653f02016-09-03 16:59:06 +02008037 else if (i == current_augroup)
8038 EMSG(_("E936: Cannot delete the current group"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008039 else
8040 {
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008041 event_T event;
8042 AutoPat *ap;
8043 int in_use = FALSE;
8044
8045 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8046 event = (event_T)((int)event + 1))
8047 {
8048 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
Bram Moolenaar5c809082016-09-01 16:21:48 +02008049 if (ap->group == i && ap->pat != NULL)
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008050 {
8051 give_warning((char_u *)_("W19: Deleting augroup that is still in use"), TRUE);
8052 in_use = TRUE;
8053 event = NUM_EVENTS;
8054 break;
8055 }
8056 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008057 vim_free(AUGROUP_NAME(i));
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008058 if (in_use)
8059 {
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008060 AUGROUP_NAME(i) = get_deleted_augroup();
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008061 }
8062 else
8063 AUGROUP_NAME(i) = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008064 }
8065}
8066
8067/*
8068 * Find the ID of an autocmd group name.
8069 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
8070 */
8071 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008072au_find_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008073{
8074 int i;
8075
8076 for (i = 0; i < augroups.ga_len; ++i)
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008077 if (AUGROUP_NAME(i) != NULL && AUGROUP_NAME(i) != get_deleted_augroup()
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008078 && STRCMP(AUGROUP_NAME(i), name) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008079 return i;
8080 return AUGROUP_ERROR;
8081}
8082
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008083/*
8084 * Return TRUE if augroup "name" exists.
8085 */
8086 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008087au_has_group(char_u *name)
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008088{
8089 return au_find_group(name) != AUGROUP_ERROR;
8090}
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008091
Bram Moolenaar071d4272004-06-13 20:20:40 +00008092/*
8093 * ":augroup {name}".
8094 */
8095 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008096do_augroup(char_u *arg, int del_group)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008097{
8098 int i;
8099
8100 if (del_group)
8101 {
8102 if (*arg == NUL)
8103 EMSG(_(e_argreq));
8104 else
8105 au_del_group(arg);
8106 }
8107 else if (STRICMP(arg, "end") == 0) /* ":aug end": back to group 0 */
8108 current_augroup = AUGROUP_DEFAULT;
8109 else if (*arg) /* ":aug xxx": switch to group xxx */
8110 {
8111 i = au_new_group(arg);
8112 if (i != AUGROUP_ERROR)
8113 current_augroup = i;
8114 }
8115 else /* ":aug": list the group names */
8116 {
8117 msg_start();
8118 for (i = 0; i < augroups.ga_len; ++i)
8119 {
8120 if (AUGROUP_NAME(i) != NULL)
8121 {
8122 msg_puts(AUGROUP_NAME(i));
8123 msg_puts((char_u *)" ");
8124 }
8125 }
8126 msg_clr_eos();
8127 msg_end();
8128 }
8129}
8130
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008131#if defined(EXITFREE) || defined(PROTO)
8132 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008133free_all_autocmds(void)
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008134{
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008135 int i;
8136 char_u *s;
8137
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008138 for (current_augroup = -1; current_augroup < augroups.ga_len;
8139 ++current_augroup)
8140 do_autocmd((char_u *)"", TRUE);
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008141
8142 for (i = 0; i < augroups.ga_len; ++i)
8143 {
8144 s = ((char_u **)(augroups.ga_data))[i];
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008145 if (s != get_deleted_augroup())
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008146 vim_free(s);
8147 }
8148 ga_clear(&augroups);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008149}
8150#endif
8151
Bram Moolenaar071d4272004-06-13 20:20:40 +00008152/*
8153 * Return the event number for event name "start".
8154 * Return NUM_EVENTS if the event name was not found.
8155 * Return a pointer to the next event name in "end".
8156 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008157 static event_T
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008158event_name2nr(char_u *start, char_u **end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008159{
8160 char_u *p;
8161 int i;
8162 int len;
8163
Bram Moolenaare99e8442016-07-26 20:43:40 +02008164 /* the event name ends with end of line, '|', a blank or a comma */
8165 for (p = start; *p && !vim_iswhite(*p) && *p != ',' && *p != '|'; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008166 ;
8167 for (i = 0; event_names[i].name != NULL; ++i)
8168 {
8169 len = (int)STRLEN(event_names[i].name);
8170 if (len == p - start && STRNICMP(event_names[i].name, start, len) == 0)
8171 break;
8172 }
8173 if (*p == ',')
8174 ++p;
8175 *end = p;
8176 if (event_names[i].name == NULL)
8177 return NUM_EVENTS;
8178 return event_names[i].event;
8179}
8180
8181/*
8182 * Return the name for event "event".
8183 */
8184 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008185event_nr2name(event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008186{
8187 int i;
8188
8189 for (i = 0; event_names[i].name != NULL; ++i)
8190 if (event_names[i].event == event)
8191 return (char_u *)event_names[i].name;
8192 return (char_u *)"Unknown";
8193}
8194
8195/*
8196 * Scan over the events. "*" stands for all events.
8197 */
8198 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008199find_end_event(
8200 char_u *arg,
8201 int have_group) /* TRUE when group name was found */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008202{
8203 char_u *pat;
8204 char_u *p;
8205
8206 if (*arg == '*')
8207 {
8208 if (arg[1] && !vim_iswhite(arg[1]))
8209 {
8210 EMSG2(_("E215: Illegal character after *: %s"), arg);
8211 return NULL;
8212 }
8213 pat = arg + 1;
8214 }
8215 else
8216 {
Bram Moolenaare99e8442016-07-26 20:43:40 +02008217 for (pat = arg; *pat && *pat != '|' && !vim_iswhite(*pat); pat = p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008218 {
8219 if ((int)event_name2nr(pat, &p) >= (int)NUM_EVENTS)
8220 {
8221 if (have_group)
8222 EMSG2(_("E216: No such event: %s"), pat);
8223 else
8224 EMSG2(_("E216: No such group or event: %s"), pat);
8225 return NULL;
8226 }
8227 }
8228 }
8229 return pat;
8230}
8231
8232/*
8233 * Return TRUE if "event" is included in 'eventignore'.
8234 */
8235 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008236event_ignored(event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008237{
8238 char_u *p = p_ei;
8239
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008240 while (*p != NUL)
8241 {
8242 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8243 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008244 if (event_name2nr(p, &p) == event)
8245 return TRUE;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008246 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008247
8248 return FALSE;
8249}
8250
8251/*
8252 * Return OK when the contents of p_ei is valid, FAIL otherwise.
8253 */
8254 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008255check_ei(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008256{
8257 char_u *p = p_ei;
8258
Bram Moolenaar071d4272004-06-13 20:20:40 +00008259 while (*p)
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008260 {
8261 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8262 {
8263 p += 3;
8264 if (*p == ',')
8265 ++p;
8266 }
8267 else if (event_name2nr(p, &p) == NUM_EVENTS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008268 return FAIL;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008269 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008270
8271 return OK;
8272}
8273
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008274# if defined(FEAT_SYN_HL) || defined(PROTO)
8275
8276/*
8277 * Add "what" to 'eventignore' to skip loading syntax highlighting for every
8278 * buffer loaded into the window. "what" must start with a comma.
8279 * Returns the old value of 'eventignore' in allocated memory.
8280 */
8281 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008282au_event_disable(char *what)
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008283{
8284 char_u *new_ei;
8285 char_u *save_ei;
8286
8287 save_ei = vim_strsave(p_ei);
8288 if (save_ei != NULL)
8289 {
Bram Moolenaara5792f52005-11-23 21:25:05 +00008290 new_ei = vim_strnsave(p_ei, (int)(STRLEN(p_ei) + STRLEN(what)));
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008291 if (new_ei != NULL)
8292 {
Bram Moolenaar8cac9fd2010-03-02 12:48:05 +01008293 if (*what == ',' && *p_ei == NUL)
8294 STRCPY(new_ei, what + 1);
8295 else
8296 STRCAT(new_ei, what);
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008297 set_string_option_direct((char_u *)"ei", -1, new_ei,
8298 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008299 vim_free(new_ei);
8300 }
8301 }
8302 return save_ei;
8303}
8304
8305 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008306au_event_restore(char_u *old_ei)
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008307{
8308 if (old_ei != NULL)
8309 {
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008310 set_string_option_direct((char_u *)"ei", -1, old_ei,
8311 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008312 vim_free(old_ei);
8313 }
8314}
8315# endif /* FEAT_SYN_HL */
8316
Bram Moolenaar071d4272004-06-13 20:20:40 +00008317/*
8318 * do_autocmd() -- implements the :autocmd command. Can be used in the
8319 * following ways:
8320 *
8321 * :autocmd <event> <pat> <cmd> Add <cmd> to the list of commands that
8322 * will be automatically executed for <event>
8323 * when editing a file matching <pat>, in
8324 * the current group.
8325 * :autocmd <event> <pat> Show the auto-commands associated with
8326 * <event> and <pat>.
8327 * :autocmd <event> Show the auto-commands associated with
8328 * <event>.
8329 * :autocmd Show all auto-commands.
8330 * :autocmd! <event> <pat> <cmd> Remove all auto-commands associated with
8331 * <event> and <pat>, and add the command
8332 * <cmd>, for the current group.
8333 * :autocmd! <event> <pat> Remove all auto-commands associated with
8334 * <event> and <pat> for the current group.
8335 * :autocmd! <event> Remove all auto-commands associated with
8336 * <event> for the current group.
8337 * :autocmd! Remove ALL auto-commands for the current
8338 * group.
8339 *
8340 * Multiple events and patterns may be given separated by commas. Here are
8341 * some examples:
8342 * :autocmd bufread,bufenter *.c,*.h set tw=0 smartindent noic
8343 * :autocmd bufleave * set tw=79 nosmartindent ic infercase
8344 *
8345 * :autocmd * *.c show all autocommands for *.c files.
Bram Moolenaard35f9712005-12-18 22:02:33 +00008346 *
8347 * Mostly a {group} argument can optionally appear before <event>.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008348 */
8349 void
Bram Moolenaare99e8442016-07-26 20:43:40 +02008350do_autocmd(char_u *arg_in, int forceit)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008351{
Bram Moolenaare99e8442016-07-26 20:43:40 +02008352 char_u *arg = arg_in;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008353 char_u *pat;
8354 char_u *envpat = NULL;
8355 char_u *cmd;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008356 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008357 int need_free = FALSE;
8358 int nested = FALSE;
8359 int group;
8360
Bram Moolenaare99e8442016-07-26 20:43:40 +02008361 if (*arg == '|')
8362 {
8363 arg = (char_u *)"";
8364 group = AUGROUP_ALL; /* no argument, use all groups */
8365 }
8366 else
8367 {
8368 /*
8369 * Check for a legal group name. If not, use AUGROUP_ALL.
8370 */
8371 group = au_get_grouparg(&arg);
8372 if (arg == NULL) /* out of memory */
8373 return;
8374 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008375
8376 /*
8377 * Scan over the events.
8378 * If we find an illegal name, return here, don't do anything.
8379 */
8380 pat = find_end_event(arg, group != AUGROUP_ALL);
8381 if (pat == NULL)
8382 return;
8383
Bram Moolenaar071d4272004-06-13 20:20:40 +00008384 pat = skipwhite(pat);
Bram Moolenaare99e8442016-07-26 20:43:40 +02008385 if (*pat == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008386 {
Bram Moolenaare99e8442016-07-26 20:43:40 +02008387 pat = (char_u *)"";
8388 cmd = (char_u *)"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00008389 }
Bram Moolenaare99e8442016-07-26 20:43:40 +02008390 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00008391 {
Bram Moolenaare99e8442016-07-26 20:43:40 +02008392 /*
8393 * Scan over the pattern. Put a NUL at the end.
8394 */
8395 cmd = pat;
8396 while (*cmd && (!vim_iswhite(*cmd) || cmd[-1] == '\\'))
8397 cmd++;
8398 if (*cmd)
8399 *cmd++ = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008400
Bram Moolenaare99e8442016-07-26 20:43:40 +02008401 /* Expand environment variables in the pattern. Set 'shellslash', we want
8402 * forward slashes here. */
8403 if (vim_strchr(pat, '$') != NULL || vim_strchr(pat, '~') != NULL)
8404 {
8405#ifdef BACKSLASH_IN_FILENAME
8406 int p_ssl_save = p_ssl;
8407
8408 p_ssl = TRUE;
8409#endif
8410 envpat = expand_env_save(pat);
8411#ifdef BACKSLASH_IN_FILENAME
8412 p_ssl = p_ssl_save;
8413#endif
8414 if (envpat != NULL)
8415 pat = envpat;
8416 }
8417
8418 /*
8419 * Check for "nested" flag.
8420 */
8421 cmd = skipwhite(cmd);
8422 if (*cmd != NUL && STRNCMP(cmd, "nested", 6) == 0 && vim_iswhite(cmd[6]))
8423 {
8424 nested = TRUE;
8425 cmd = skipwhite(cmd + 6);
8426 }
8427
8428 /*
8429 * Find the start of the commands.
8430 * Expand <sfile> in it.
8431 */
8432 if (*cmd != NUL)
8433 {
8434 cmd = expand_sfile(cmd);
8435 if (cmd == NULL) /* some error */
8436 return;
8437 need_free = TRUE;
8438 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008439 }
8440
8441 /*
8442 * Print header when showing autocommands.
8443 */
8444 if (!forceit && *cmd == NUL)
8445 {
8446 /* Highlight title */
8447 MSG_PUTS_TITLE(_("\n--- Auto-Commands ---"));
8448 }
8449
8450 /*
8451 * Loop over the events.
8452 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008453 last_event = (event_T)-1; /* for listing the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008454 last_group = AUGROUP_ERROR; /* for listing the group name */
Bram Moolenaare99e8442016-07-26 20:43:40 +02008455 if (*arg == '*' || *arg == NUL || *arg == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008456 {
Bram Moolenaar754b5602006-02-09 23:53:20 +00008457 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8458 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008459 if (do_autocmd_event(event, pat,
8460 nested, cmd, forceit, group) == FAIL)
8461 break;
8462 }
8463 else
8464 {
Bram Moolenaare99e8442016-07-26 20:43:40 +02008465 while (*arg && *arg != '|' && !vim_iswhite(*arg))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008466 if (do_autocmd_event(event_name2nr(arg, &arg), pat,
8467 nested, cmd, forceit, group) == FAIL)
8468 break;
8469 }
8470
8471 if (need_free)
8472 vim_free(cmd);
8473 vim_free(envpat);
8474}
8475
8476/*
8477 * Find the group ID in a ":autocmd" or ":doautocmd" argument.
8478 * The "argp" argument is advanced to the following argument.
8479 *
8480 * Returns the group ID, AUGROUP_ERROR for error (out of memory).
8481 */
8482 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008483au_get_grouparg(char_u **argp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008484{
8485 char_u *group_name;
8486 char_u *p;
8487 char_u *arg = *argp;
8488 int group = AUGROUP_ALL;
8489
Bram Moolenaare99e8442016-07-26 20:43:40 +02008490 for (p = arg; *p && !vim_iswhite(*p) && *p != '|'; ++p)
8491 ;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008492 if (p > arg)
8493 {
8494 group_name = vim_strnsave(arg, (int)(p - arg));
8495 if (group_name == NULL) /* out of memory */
8496 return AUGROUP_ERROR;
8497 group = au_find_group(group_name);
8498 if (group == AUGROUP_ERROR)
8499 group = AUGROUP_ALL; /* no match, use all groups */
8500 else
8501 *argp = skipwhite(p); /* match, skip over group name */
8502 vim_free(group_name);
8503 }
8504 return group;
8505}
8506
8507/*
8508 * do_autocmd() for one event.
8509 * If *pat == NUL do for all patterns.
8510 * If *cmd == NUL show entries.
8511 * If forceit == TRUE delete entries.
8512 * If group is not AUGROUP_ALL, only use this group.
8513 */
8514 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008515do_autocmd_event(
8516 event_T event,
8517 char_u *pat,
8518 int nested,
8519 char_u *cmd,
8520 int forceit,
8521 int group)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008522{
8523 AutoPat *ap;
8524 AutoPat **prev_ap;
8525 AutoCmd *ac;
8526 AutoCmd **prev_ac;
8527 int brace_level;
8528 char_u *endpat;
8529 int findgroup;
8530 int allgroups;
8531 int patlen;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00008532 int is_buflocal;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008533 int buflocal_nr;
8534 char_u buflocal_pat[25]; /* for "<buffer=X>" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008535
8536 if (group == AUGROUP_ALL)
8537 findgroup = current_augroup;
8538 else
8539 findgroup = group;
8540 allgroups = (group == AUGROUP_ALL && !forceit && *cmd == NUL);
8541
8542 /*
8543 * Show or delete all patterns for an event.
8544 */
8545 if (*pat == NUL)
8546 {
8547 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8548 {
8549 if (forceit) /* delete the AutoPat, if it's in the current group */
8550 {
8551 if (ap->group == findgroup)
8552 au_remove_pat(ap);
8553 }
8554 else if (group == AUGROUP_ALL || ap->group == group)
8555 show_autocmd(ap, event);
8556 }
8557 }
8558
8559 /*
8560 * Loop through all the specified patterns.
8561 */
8562 for ( ; *pat; pat = (*endpat == ',' ? endpat + 1 : endpat))
8563 {
8564 /*
8565 * Find end of the pattern.
8566 * Watch out for a comma in braces, like "*.\{obj,o\}".
8567 */
8568 brace_level = 0;
8569 for (endpat = pat; *endpat && (*endpat != ',' || brace_level
Bram Moolenaar6b9be1b2015-07-28 13:33:45 +02008570 || (endpat > pat && endpat[-1] == '\\')); ++endpat)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008571 {
8572 if (*endpat == '{')
8573 brace_level++;
8574 else if (*endpat == '}')
8575 brace_level--;
8576 }
8577 if (pat == endpat) /* ignore single comma */
8578 continue;
8579 patlen = (int)(endpat - pat);
8580
8581 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008582 * detect special <buflocal[=X]> buffer-local patterns
8583 */
8584 is_buflocal = FALSE;
8585 buflocal_nr = 0;
8586
Bram Moolenaar1e997822015-02-17 16:04:57 +01008587 if (patlen >= 8 && STRNCMP(pat, "<buffer", 7) == 0
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008588 && pat[patlen - 1] == '>')
8589 {
Bram Moolenaar1e997822015-02-17 16:04:57 +01008590 /* "<buffer...>": Error will be printed only for addition.
8591 * printing and removing will proceed silently. */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008592 is_buflocal = TRUE;
8593 if (patlen == 8)
Bram Moolenaar1e997822015-02-17 16:04:57 +01008594 /* "<buffer>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008595 buflocal_nr = curbuf->b_fnum;
8596 else if (patlen > 9 && pat[7] == '=')
8597 {
Bram Moolenaar1e997822015-02-17 16:04:57 +01008598 if (patlen == 13 && STRNICMP(pat, "<buffer=abuf>", 13) == 0)
8599 /* "<buffer=abuf>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008600 buflocal_nr = autocmd_bufnr;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008601 else if (skipdigits(pat + 8) == pat + patlen - 1)
Bram Moolenaar1e997822015-02-17 16:04:57 +01008602 /* "<buffer=123>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008603 buflocal_nr = atoi((char *)pat + 8);
8604 }
8605 }
8606
8607 if (is_buflocal)
8608 {
8609 /* normalize pat into standard "<buffer>#N" form */
8610 sprintf((char *)buflocal_pat, "<buffer=%d>", buflocal_nr);
8611 pat = buflocal_pat; /* can modify pat and patlen */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008612 patlen = (int)STRLEN(buflocal_pat); /* but not endpat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008613 }
8614
8615 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008616 * Find AutoPat entries with this pattern.
8617 */
8618 prev_ap = &first_autopat[(int)event];
8619 while ((ap = *prev_ap) != NULL)
8620 {
8621 if (ap->pat != NULL)
8622 {
8623 /* Accept a pattern when:
8624 * - a group was specified and it's that group, or a group was
8625 * not specified and it's the current group, or a group was
8626 * not specified and we are listing
8627 * - the length of the pattern matches
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008628 * - the pattern matches.
8629 * For <buffer[=X]>, this condition works because we normalize
8630 * all buffer-local patterns.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008631 */
8632 if ((allgroups || ap->group == findgroup)
8633 && ap->patlen == patlen
8634 && STRNCMP(pat, ap->pat, patlen) == 0)
8635 {
8636 /*
8637 * Remove existing autocommands.
8638 * If adding any new autocmd's for this AutoPat, don't
8639 * delete the pattern from the autopat list, append to
8640 * this list.
8641 */
8642 if (forceit)
8643 {
8644 if (*cmd != NUL && ap->next == NULL)
8645 {
8646 au_remove_cmds(ap);
8647 break;
8648 }
8649 au_remove_pat(ap);
8650 }
8651
8652 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008653 * Show autocmd's for this autopat, or buflocals <buffer=X>
Bram Moolenaar071d4272004-06-13 20:20:40 +00008654 */
8655 else if (*cmd == NUL)
8656 show_autocmd(ap, event);
8657
8658 /*
8659 * Add autocmd to this autopat, if it's the last one.
8660 */
8661 else if (ap->next == NULL)
8662 break;
8663 }
8664 }
8665 prev_ap = &ap->next;
8666 }
8667
8668 /*
8669 * Add a new command.
8670 */
8671 if (*cmd != NUL)
8672 {
8673 /*
8674 * If the pattern we want to add a command to does appear at the
8675 * end of the list (or not is not in the list at all), add the
8676 * pattern at the end of the list.
8677 */
8678 if (ap == NULL)
8679 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008680 /* refuse to add buffer-local ap if buffer number is invalid */
8681 if (is_buflocal && (buflocal_nr == 0
8682 || buflist_findnr(buflocal_nr) == NULL))
8683 {
8684 EMSGN(_("E680: <buffer=%d>: invalid buffer number "),
8685 buflocal_nr);
8686 return FAIL;
8687 }
8688
Bram Moolenaar071d4272004-06-13 20:20:40 +00008689 ap = (AutoPat *)alloc((unsigned)sizeof(AutoPat));
8690 if (ap == NULL)
8691 return FAIL;
8692 ap->pat = vim_strnsave(pat, patlen);
8693 ap->patlen = patlen;
8694 if (ap->pat == NULL)
8695 {
8696 vim_free(ap);
8697 return FAIL;
8698 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008699
8700 if (is_buflocal)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008701 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008702 ap->buflocal_nr = buflocal_nr;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008703 ap->reg_prog = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008704 }
8705 else
8706 {
Bram Moolenaar748bf032005-02-02 23:04:36 +00008707 char_u *reg_pat;
8708
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008709 ap->buflocal_nr = 0;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008710 reg_pat = file_pat_to_reg_pat(pat, endpat,
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008711 &ap->allow_dirs, TRUE);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008712 if (reg_pat != NULL)
8713 ap->reg_prog = vim_regcomp(reg_pat, RE_MAGIC);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008714 vim_free(reg_pat);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008715 if (reg_pat == NULL || ap->reg_prog == NULL)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008716 {
8717 vim_free(ap->pat);
8718 vim_free(ap);
8719 return FAIL;
8720 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008721 }
8722 ap->cmds = NULL;
8723 *prev_ap = ap;
8724 ap->next = NULL;
8725 if (group == AUGROUP_ALL)
8726 ap->group = current_augroup;
8727 else
8728 ap->group = group;
8729 }
8730
8731 /*
8732 * Add the autocmd at the end of the AutoCmd list.
8733 */
8734 prev_ac = &(ap->cmds);
8735 while ((ac = *prev_ac) != NULL)
8736 prev_ac = &ac->next;
8737 ac = (AutoCmd *)alloc((unsigned)sizeof(AutoCmd));
8738 if (ac == NULL)
8739 return FAIL;
8740 ac->cmd = vim_strsave(cmd);
8741#ifdef FEAT_EVAL
8742 ac->scriptID = current_SID;
8743#endif
8744 if (ac->cmd == NULL)
8745 {
8746 vim_free(ac);
8747 return FAIL;
8748 }
8749 ac->next = NULL;
8750 *prev_ac = ac;
8751 ac->nested = nested;
8752 }
8753 }
8754
8755 au_cleanup(); /* may really delete removed patterns/commands now */
8756 return OK;
8757}
8758
8759/*
8760 * Implementation of ":doautocmd [group] event [fname]".
8761 * Return OK for success, FAIL for failure;
8762 */
8763 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008764do_doautocmd(
8765 char_u *arg,
Bram Moolenaar1610d052016-06-09 22:53:01 +02008766 int do_msg, /* give message for no matching autocmds? */
8767 int *did_something)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008768{
8769 char_u *fname;
8770 int nothing_done = TRUE;
8771 int group;
8772
Bram Moolenaar1610d052016-06-09 22:53:01 +02008773 if (did_something != NULL)
Bram Moolenaar76ae22f2016-06-13 20:00:29 +02008774 *did_something = FALSE;
Bram Moolenaar1610d052016-06-09 22:53:01 +02008775
Bram Moolenaar071d4272004-06-13 20:20:40 +00008776 /*
8777 * Check for a legal group name. If not, use AUGROUP_ALL.
8778 */
8779 group = au_get_grouparg(&arg);
8780 if (arg == NULL) /* out of memory */
8781 return FAIL;
8782
8783 if (*arg == '*')
8784 {
8785 EMSG(_("E217: Can't execute autocommands for ALL events"));
8786 return FAIL;
8787 }
8788
8789 /*
8790 * Scan over the events.
8791 * If we find an illegal name, return here, don't do anything.
8792 */
8793 fname = find_end_event(arg, group != AUGROUP_ALL);
8794 if (fname == NULL)
8795 return FAIL;
8796
8797 fname = skipwhite(fname);
8798
8799 /*
8800 * Loop over the events.
8801 */
8802 while (*arg && !vim_iswhite(*arg))
8803 if (apply_autocmds_group(event_name2nr(arg, &arg),
8804 fname, NULL, TRUE, group, curbuf, NULL))
8805 nothing_done = FALSE;
8806
8807 if (nothing_done && do_msg)
8808 MSG(_("No matching autocommands"));
Bram Moolenaar1610d052016-06-09 22:53:01 +02008809 if (did_something != NULL)
8810 *did_something = !nothing_done;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008811
8812#ifdef FEAT_EVAL
8813 return aborting() ? FAIL : OK;
8814#else
8815 return OK;
8816#endif
8817}
8818
8819/*
8820 * ":doautoall": execute autocommands for each loaded buffer.
8821 */
8822 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008823ex_doautoall(exarg_T *eap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008824{
8825 int retval;
8826 aco_save_T aco;
8827 buf_T *buf;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008828 bufref_T bufref;
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008829 char_u *arg = eap->arg;
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008830 int call_do_modelines = check_nomodeline(&arg);
Bram Moolenaar1610d052016-06-09 22:53:01 +02008831 int did_aucmd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008832
8833 /*
8834 * This is a bit tricky: For some commands curwin->w_buffer needs to be
8835 * equal to curbuf, but for some buffers there may not be a window.
8836 * So we change the buffer for the current window for a moment. This
8837 * gives problems when the autocommands make changes to the list of
8838 * buffers or windows...
8839 */
Bram Moolenaar29323592016-07-24 22:04:11 +02008840 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008841 {
Bram Moolenaar3a847972008-07-08 09:36:58 +00008842 if (buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008843 {
8844 /* find a window for this buffer and save some values */
8845 aucmd_prepbuf(&aco, buf);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008846 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008847
8848 /* execute the autocommands for this buffer */
Bram Moolenaar1610d052016-06-09 22:53:01 +02008849 retval = do_doautocmd(arg, FALSE, &did_aucmd);
Bram Moolenaareeefcc72007-05-01 21:21:21 +00008850
Bram Moolenaar1610d052016-06-09 22:53:01 +02008851 if (call_do_modelines && did_aucmd)
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008852 {
8853 /* Execute the modeline settings, but don't set window-local
8854 * options if we are using the current window for another
8855 * buffer. */
8856 do_modelines(curwin == aucmd_win ? OPT_NOWIN : 0);
8857 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008858
8859 /* restore the current window */
8860 aucmd_restbuf(&aco);
8861
8862 /* stop if there is some error or buffer was deleted */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008863 if (retval == FAIL || !bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008864 break;
8865 }
8866 }
8867
8868 check_cursor(); /* just in case lines got deleted */
8869}
8870
8871/*
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008872 * Check *argp for <nomodeline>. When it is present return FALSE, otherwise
8873 * return TRUE and advance *argp to after it.
8874 * Thus return TRUE when do_modelines() should be called.
8875 */
8876 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008877check_nomodeline(char_u **argp)
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008878{
8879 if (STRNCMP(*argp, "<nomodeline>", 12) == 0)
8880 {
8881 *argp = skipwhite(*argp + 12);
8882 return FALSE;
8883 }
8884 return TRUE;
8885}
8886
8887/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008888 * Prepare for executing autocommands for (hidden) buffer "buf".
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008889 * Search for a visible window containing the current buffer. If there isn't
8890 * one then use "aucmd_win".
Bram Moolenaar071d4272004-06-13 20:20:40 +00008891 * Set "curbuf" and "curwin" to match "buf".
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00008892 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008893 */
8894 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008895aucmd_prepbuf(
8896 aco_save_T *aco, /* structure to save values in */
8897 buf_T *buf) /* new curbuf */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008898{
8899 win_T *win;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008900#ifdef FEAT_WINDOWS
8901 int save_ea;
8902#endif
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008903#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008904 int save_acd;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008905#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008906
8907 /* Find a window that is for the new buffer */
8908 if (buf == curbuf) /* be quick when buf is curbuf */
8909 win = curwin;
8910 else
8911#ifdef FEAT_WINDOWS
Bram Moolenaar29323592016-07-24 22:04:11 +02008912 FOR_ALL_WINDOWS(win)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008913 if (win->w_buffer == buf)
8914 break;
8915#else
8916 win = NULL;
8917#endif
8918
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008919 /* Allocate "aucmd_win" when needed. If this fails (out of memory) fall
8920 * back to using the current window. */
8921 if (win == NULL && aucmd_win == NULL)
8922 {
8923 win_alloc_aucmd_win();
8924 if (aucmd_win == NULL)
8925 win = curwin;
8926 }
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008927 if (win == NULL && aucmd_win_used)
8928 /* Strange recursive autocommand, fall back to using the current
8929 * window. Expect a few side effects... */
8930 win = curwin;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008931
8932 aco->save_curwin = curwin;
8933 aco->save_curbuf = curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008934 if (win != NULL)
8935 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008936 /* There is a window for "buf" in the current tab page, make it the
8937 * curwin. This is preferred, it has the least side effects (esp. if
8938 * "buf" is curbuf). */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008939 aco->use_aucmd_win = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008940 curwin = win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008941 }
8942 else
8943 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008944 /* There is no window for "buf", use "aucmd_win". To minimize the side
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02008945 * effects, insert it in the current tab page.
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008946 * Anything related to a window (e.g., setting folds) may have
8947 * unexpected results. */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008948 aco->use_aucmd_win = TRUE;
8949 aucmd_win_used = TRUE;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008950 aucmd_win->w_buffer = buf;
Bram Moolenaarcdddaa42010-06-07 23:07:44 +02008951 aucmd_win->w_s = &buf->b_s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008952 ++buf->b_nwindows;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008953 win_init_empty(aucmd_win); /* set cursor and topline to safe values */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008954
8955 /* Make sure w_localdir and globaldir are NULL to avoid a chdir() in
8956 * win_enter_ext(). */
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008957 vim_free(aucmd_win->w_localdir);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008958 aucmd_win->w_localdir = NULL;
8959 aco->globaldir = globaldir;
8960 globaldir = NULL;
8961
Bram Moolenaar071d4272004-06-13 20:20:40 +00008962
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008963#ifdef FEAT_WINDOWS
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008964 /* Split the current window, put the aucmd_win in the upper half.
8965 * We don't want the BufEnter or WinEnter autocommands. */
8966 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008967 make_snapshot(SNAP_AUCMD_IDX);
8968 save_ea = p_ea;
8969 p_ea = FALSE;
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008970
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008971# ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008972 /* Prevent chdir() call in win_enter_ext(), through do_autochdir(). */
8973 save_acd = p_acd;
8974 p_acd = FALSE;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008975# endif
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008976
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008977 (void)win_split_ins(0, WSP_TOP, aucmd_win, 0);
8978 (void)win_comp_pos(); /* recompute window positions */
8979 p_ea = save_ea;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008980# ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008981 p_acd = save_acd;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008982# endif
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008983 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008984#endif
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008985 curwin = aucmd_win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008986 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008987 curbuf = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008988 aco->new_curwin = curwin;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008989 set_bufref(&aco->new_curbuf, curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008990}
8991
8992/*
8993 * Cleanup after executing autocommands for a (hidden) buffer.
8994 * Restore the window as it was (if possible).
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00008995 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008996 */
8997 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008998aucmd_restbuf(
8999 aco_save_T *aco) /* structure holding saved values */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009000{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009001#ifdef FEAT_WINDOWS
9002 int dummy;
9003#endif
9004
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009005 if (aco->use_aucmd_win)
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009006 {
9007 --curbuf->b_nwindows;
9008#ifdef FEAT_WINDOWS
9009 /* Find "aucmd_win", it can't be closed, but it may be in another tab
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00009010 * page. Do not trigger autocommands here. */
9011 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009012 if (curwin != aucmd_win)
9013 {
9014 tabpage_T *tp;
9015 win_T *wp;
9016
9017 FOR_ALL_TAB_WINDOWS(tp, wp)
9018 {
9019 if (wp == aucmd_win)
9020 {
9021 if (tp != curtab)
Bram Moolenaar49e649f2013-05-06 04:50:35 +02009022 goto_tabpage_tp(tp, TRUE, TRUE);
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009023 win_goto(aucmd_win);
Bram Moolenaar28f29082012-02-11 23:45:37 +01009024 goto win_found;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009025 }
9026 }
9027 }
Bram Moolenaar28f29082012-02-11 23:45:37 +01009028win_found:
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009029
9030 /* Remove the window and frame from the tree of frames. */
9031 (void)winframe_remove(curwin, &dummy, NULL);
9032 win_remove(curwin, NULL);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009033 aucmd_win_used = FALSE;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009034 last_status(FALSE); /* may need to remove last status line */
9035 restore_snapshot(SNAP_AUCMD_IDX, FALSE);
9036 (void)win_comp_pos(); /* recompute window positions */
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00009037 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009038
9039 if (win_valid(aco->save_curwin))
9040 curwin = aco->save_curwin;
9041 else
9042 /* Hmm, original window disappeared. Just use the first one. */
9043 curwin = firstwin;
9044# ifdef FEAT_EVAL
Bram Moolenaar429fa852013-04-15 12:27:36 +02009045 vars_clear(&aucmd_win->w_vars->dv_hashtab); /* free all w: variables */
9046 hash_init(&aucmd_win->w_vars->dv_hashtab); /* re-use the hashtab */
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009047# endif
9048#else
9049 curwin = aco->save_curwin;
9050#endif
9051 curbuf = curwin->w_buffer;
9052
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009053 vim_free(globaldir);
9054 globaldir = aco->globaldir;
9055
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009056 /* the buffer contents may have changed */
9057 check_cursor();
9058 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
9059 {
9060 curwin->w_topline = curbuf->b_ml.ml_line_count;
9061#ifdef FEAT_DIFF
9062 curwin->w_topfill = 0;
9063#endif
9064 }
9065#if defined(FEAT_GUI)
9066 /* Hide the scrollbars from the aucmd_win and update. */
9067 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_LEFT], FALSE);
9068 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_RIGHT], FALSE);
9069 gui_may_update_scrollbars();
9070#endif
9071 }
9072 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00009073 {
9074 /* restore curwin */
9075#ifdef FEAT_WINDOWS
9076 if (win_valid(aco->save_curwin))
9077#endif
9078 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009079 /* Restore the buffer which was previously edited by curwin, if
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009080 * it was changed, we are still the same window and the buffer is
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009081 * valid. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009082 if (curwin == aco->new_curwin
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009083 && curbuf != aco->new_curbuf.br_buf
9084 && bufref_valid(&aco->new_curbuf)
9085 && aco->new_curbuf.br_buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009086 {
Bram Moolenaar7da9c372012-04-30 17:04:52 +02009087# if defined(FEAT_SYN_HL) || defined(FEAT_SPELL)
9088 if (curwin->w_s == &curbuf->b_s)
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009089 curwin->w_s = &aco->new_curbuf.br_buf->b_s;
Bram Moolenaar7da9c372012-04-30 17:04:52 +02009090# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009091 --curbuf->b_nwindows;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009092 curbuf = aco->new_curbuf.br_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009093 curwin->w_buffer = curbuf;
9094 ++curbuf->b_nwindows;
9095 }
9096
9097 curwin = aco->save_curwin;
9098 curbuf = curwin->w_buffer;
Bram Moolenaar371932a2014-09-09 16:59:38 +02009099 /* In case the autocommand move the cursor to a position that that
9100 * not exist in curbuf. */
9101 check_cursor();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009102 }
9103 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009104}
9105
9106static int autocmd_nested = FALSE;
9107
9108/*
9109 * Execute autocommands for "event" and file name "fname".
9110 * Return TRUE if some commands were executed.
9111 */
9112 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009113apply_autocmds(
9114 event_T event,
9115 char_u *fname, /* NULL or empty means use actual file name */
9116 char_u *fname_io, /* fname to use for <afile> on cmdline */
9117 int force, /* when TRUE, ignore autocmd_busy */
9118 buf_T *buf) /* buffer for <abuf> */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009119{
9120 return apply_autocmds_group(event, fname, fname_io, force,
9121 AUGROUP_ALL, buf, NULL);
9122}
9123
9124/*
9125 * Like apply_autocmds(), but with extra "eap" argument. This takes care of
9126 * setting v:filearg.
9127 */
9128 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009129apply_autocmds_exarg(
9130 event_T event,
9131 char_u *fname,
9132 char_u *fname_io,
9133 int force,
9134 buf_T *buf,
9135 exarg_T *eap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009136{
9137 return apply_autocmds_group(event, fname, fname_io, force,
9138 AUGROUP_ALL, buf, eap);
9139}
9140
9141/*
9142 * Like apply_autocmds(), but handles the caller's retval. If the script
9143 * processing is being aborted or if retval is FAIL when inside a try
9144 * conditional, no autocommands are executed. If otherwise the autocommands
9145 * cause the script to be aborted, retval is set to FAIL.
9146 */
9147 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009148apply_autocmds_retval(
9149 event_T event,
9150 char_u *fname, /* NULL or empty means use actual file name */
9151 char_u *fname_io, /* fname to use for <afile> on cmdline */
9152 int force, /* when TRUE, ignore autocmd_busy */
9153 buf_T *buf, /* buffer for <abuf> */
9154 int *retval) /* pointer to caller's retval */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009155{
9156 int did_cmd;
9157
Bram Moolenaar1e015462005-09-25 22:16:38 +00009158#ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00009159 if (should_abort(*retval))
9160 return FALSE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00009161#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009162
9163 did_cmd = apply_autocmds_group(event, fname, fname_io, force,
9164 AUGROUP_ALL, buf, NULL);
Bram Moolenaar1e015462005-09-25 22:16:38 +00009165 if (did_cmd
9166#ifdef FEAT_EVAL
9167 && aborting()
9168#endif
9169 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00009170 *retval = FAIL;
9171 return did_cmd;
9172}
9173
Bram Moolenaard35f9712005-12-18 22:02:33 +00009174/*
9175 * Return TRUE when there is a CursorHold autocommand defined.
9176 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009177 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009178has_cursorhold(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009179{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009180 return (first_autopat[(int)(get_real_state() == NORMAL_BUSY
9181 ? EVENT_CURSORHOLD : EVENT_CURSORHOLDI)] != NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009182}
Bram Moolenaard35f9712005-12-18 22:02:33 +00009183
9184/*
9185 * Return TRUE if the CursorHold event can be triggered.
9186 */
9187 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009188trigger_cursorhold(void)
Bram Moolenaard35f9712005-12-18 22:02:33 +00009189{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009190 int state;
9191
Bram Moolenaar05334432011-07-20 18:29:39 +02009192 if (!did_cursorhold
9193 && has_cursorhold()
9194 && !Recording
9195 && typebuf.tb_len == 0
Bram Moolenaard29a9ee2006-09-14 09:07:34 +00009196#ifdef FEAT_INS_EXPAND
9197 && !ins_compl_active()
9198#endif
9199 )
Bram Moolenaar754b5602006-02-09 23:53:20 +00009200 {
9201 state = get_real_state();
9202 if (state == NORMAL_BUSY || (state & INSERT) != 0)
9203 return TRUE;
9204 }
9205 return FALSE;
Bram Moolenaard35f9712005-12-18 22:02:33 +00009206}
Bram Moolenaar754b5602006-02-09 23:53:20 +00009207
9208/*
9209 * Return TRUE when there is a CursorMoved autocommand defined.
9210 */
9211 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009212has_cursormoved(void)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009213{
9214 return (first_autopat[(int)EVENT_CURSORMOVED] != NULL);
9215}
9216
9217/*
9218 * Return TRUE when there is a CursorMovedI autocommand defined.
9219 */
9220 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009221has_cursormovedI(void)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009222{
9223 return (first_autopat[(int)EVENT_CURSORMOVEDI] != NULL);
9224}
Bram Moolenaar071d4272004-06-13 20:20:40 +00009225
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009226/*
Bram Moolenaar186628f2013-03-19 13:33:23 +01009227 * Return TRUE when there is a TextChanged autocommand defined.
9228 */
9229 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009230has_textchanged(void)
Bram Moolenaar186628f2013-03-19 13:33:23 +01009231{
9232 return (first_autopat[(int)EVENT_TEXTCHANGED] != NULL);
9233}
9234
9235/*
9236 * Return TRUE when there is a TextChangedI autocommand defined.
9237 */
9238 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009239has_textchangedI(void)
Bram Moolenaar186628f2013-03-19 13:33:23 +01009240{
9241 return (first_autopat[(int)EVENT_TEXTCHANGEDI] != NULL);
9242}
9243
9244/*
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009245 * Return TRUE when there is an InsertCharPre autocommand defined.
9246 */
9247 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009248has_insertcharpre(void)
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009249{
9250 return (first_autopat[(int)EVENT_INSERTCHARPRE] != NULL);
9251}
9252
Bram Moolenaard5005162014-08-22 23:05:54 +02009253/*
9254 * Return TRUE when there is an CmdUndefined autocommand defined.
9255 */
9256 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009257has_cmdundefined(void)
Bram Moolenaard5005162014-08-22 23:05:54 +02009258{
9259 return (first_autopat[(int)EVENT_CMDUNDEFINED] != NULL);
9260}
9261
9262/*
9263 * Return TRUE when there is an FuncUndefined autocommand defined.
9264 */
9265 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009266has_funcundefined(void)
Bram Moolenaard5005162014-08-22 23:05:54 +02009267{
9268 return (first_autopat[(int)EVENT_FUNCUNDEFINED] != NULL);
9269}
9270
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009271/*
9272 * Execute autocommands for "event" and file name "fname".
9273 * Return TRUE if some commands were executed.
9274 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009275 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009276apply_autocmds_group(
9277 event_T event,
9278 char_u *fname, /* NULL or empty means use actual file name */
9279 char_u *fname_io, /* fname to use for <afile> on cmdline, NULL means
Bram Moolenaar071d4272004-06-13 20:20:40 +00009280 use fname */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009281 int force, /* when TRUE, ignore autocmd_busy */
9282 int group, /* group ID, or AUGROUP_ALL */
9283 buf_T *buf, /* buffer for <abuf> */
9284 exarg_T *eap) /* command arguments */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009285{
9286 char_u *sfname = NULL; /* short file name */
9287 char_u *tail;
9288 int save_changed;
9289 buf_T *old_curbuf;
9290 int retval = FALSE;
9291 char_u *save_sourcing_name;
9292 linenr_T save_sourcing_lnum;
9293 char_u *save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009294 int save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009295 int save_autocmd_bufnr;
9296 char_u *save_autocmd_match;
9297 int save_autocmd_busy;
9298 int save_autocmd_nested;
9299 static int nesting = 0;
9300 AutoPatCmd patcmd;
9301 AutoPat *ap;
9302#ifdef FEAT_EVAL
9303 scid_T save_current_SID;
9304 void *save_funccalp;
9305 char_u *save_cmdarg;
9306 long save_cmdbang;
9307#endif
9308 static int filechangeshell_busy = FALSE;
Bram Moolenaar05159a02005-02-26 23:04:13 +00009309#ifdef FEAT_PROFILE
9310 proftime_T wait_time;
9311#endif
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009312 int did_save_redobuff = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009313
9314 /*
9315 * Quickly return if there are no autocommands for this event or
9316 * autocommands are blocked.
9317 */
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009318 if (first_autopat[(int)event] == NULL || autocmd_blocked > 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009319 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009320
9321 /*
9322 * When autocommands are busy, new autocommands are only executed when
9323 * explicitly enabled with the "nested" flag.
9324 */
9325 if (autocmd_busy && !(force || autocmd_nested))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009326 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009327
9328#ifdef FEAT_EVAL
9329 /*
Bram Moolenaar7263a772007-05-10 17:35:54 +00009330 * Quickly return when immediately aborting on error, or when an interrupt
Bram Moolenaar071d4272004-06-13 20:20:40 +00009331 * occurred or an exception was thrown but not caught.
9332 */
9333 if (aborting())
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009334 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009335#endif
9336
9337 /*
9338 * FileChangedShell never nests, because it can create an endless loop.
9339 */
Bram Moolenaar56718732006-03-15 22:53:57 +00009340 if (filechangeshell_busy && (event == EVENT_FILECHANGEDSHELL
9341 || event == EVENT_FILECHANGEDSHELLPOST))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009342 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009343
9344 /*
9345 * Ignore events in 'eventignore'.
9346 */
9347 if (event_ignored(event))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009348 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009349
9350 /*
9351 * Allow nesting of autocommands, but restrict the depth, because it's
9352 * possible to create an endless loop.
9353 */
9354 if (nesting == 10)
9355 {
9356 EMSG(_("E218: autocommand nesting too deep"));
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009357 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009358 }
9359
9360 /*
9361 * Check if these autocommands are disabled. Used when doing ":all" or
9362 * ":ball".
9363 */
9364 if ( (autocmd_no_enter
9365 && (event == EVENT_WINENTER || event == EVENT_BUFENTER))
9366 || (autocmd_no_leave
9367 && (event == EVENT_WINLEAVE || event == EVENT_BUFLEAVE)))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009368 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009369
9370 /*
9371 * Save the autocmd_* variables and info about the current buffer.
9372 */
9373 save_autocmd_fname = autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009374 save_autocmd_fname_full = autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009375 save_autocmd_bufnr = autocmd_bufnr;
9376 save_autocmd_match = autocmd_match;
9377 save_autocmd_busy = autocmd_busy;
9378 save_autocmd_nested = autocmd_nested;
9379 save_changed = curbuf->b_changed;
9380 old_curbuf = curbuf;
9381
9382 /*
9383 * Set the file name to be used for <afile>.
Bram Moolenaara0174af2008-01-02 20:08:25 +00009384 * Make a copy to avoid that changing a buffer name or directory makes it
9385 * invalid.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009386 */
9387 if (fname_io == NULL)
9388 {
Bram Moolenaar53744302015-07-17 17:38:22 +02009389 if (event == EVENT_COLORSCHEME || event == EVENT_OPTIONSET)
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009390 autocmd_fname = NULL;
9391 else if (fname != NULL && *fname != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009392 autocmd_fname = fname;
9393 else if (buf != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009394 autocmd_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009395 else
9396 autocmd_fname = NULL;
9397 }
9398 else
9399 autocmd_fname = fname_io;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009400 if (autocmd_fname != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009401 autocmd_fname = vim_strsave(autocmd_fname);
9402 autocmd_fname_full = FALSE; /* call FullName_save() later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009403
9404 /*
9405 * Set the buffer number to be used for <abuf>.
9406 */
9407 if (buf == NULL)
9408 autocmd_bufnr = 0;
9409 else
9410 autocmd_bufnr = buf->b_fnum;
9411
9412 /*
9413 * When the file name is NULL or empty, use the file name of buffer "buf".
9414 * Always use the full path of the file name to match with, in case
9415 * "allow_dirs" is set.
9416 */
9417 if (fname == NULL || *fname == NUL)
9418 {
9419 if (buf == NULL)
9420 fname = NULL;
9421 else
9422 {
9423#ifdef FEAT_SYN_HL
9424 if (event == EVENT_SYNTAX)
9425 fname = buf->b_p_syn;
9426 else
9427#endif
9428 if (event == EVENT_FILETYPE)
9429 fname = buf->b_p_ft;
9430 else
9431 {
9432 if (buf->b_sfname != NULL)
9433 sfname = vim_strsave(buf->b_sfname);
9434 fname = buf->b_ffname;
9435 }
9436 }
9437 if (fname == NULL)
9438 fname = (char_u *)"";
9439 fname = vim_strsave(fname); /* make a copy, so we can change it */
9440 }
9441 else
9442 {
9443 sfname = vim_strsave(fname);
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009444 /* Don't try expanding FileType, Syntax, FuncUndefined, WindowID,
9445 * ColorScheme or QuickFixCmd* */
Bram Moolenaar7c626922005-02-07 22:01:03 +00009446 if (event == EVENT_FILETYPE
9447 || event == EVENT_SYNTAX
Bram Moolenaar5135d462009-04-29 16:03:38 +00009448 || event == EVENT_FUNCUNDEFINED
Bram Moolenaar7c626922005-02-07 22:01:03 +00009449 || event == EVENT_REMOTEREPLY
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00009450 || event == EVENT_SPELLFILEMISSING
Bram Moolenaar7c626922005-02-07 22:01:03 +00009451 || event == EVENT_QUICKFIXCMDPRE
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009452 || event == EVENT_COLORSCHEME
Bram Moolenaar53744302015-07-17 17:38:22 +02009453 || event == EVENT_OPTIONSET
Bram Moolenaar7c626922005-02-07 22:01:03 +00009454 || event == EVENT_QUICKFIXCMDPOST)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009455 fname = vim_strsave(fname);
9456 else
9457 fname = FullName_save(fname, FALSE);
9458 }
9459 if (fname == NULL) /* out of memory */
9460 {
9461 vim_free(sfname);
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009462 retval = FALSE;
9463 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009464 }
9465
9466#ifdef BACKSLASH_IN_FILENAME
9467 /*
9468 * Replace all backslashes with forward slashes. This makes the
9469 * autocommand patterns portable between Unix and MS-DOS.
9470 */
9471 if (sfname != NULL)
9472 forward_slash(sfname);
9473 forward_slash(fname);
9474#endif
9475
9476#ifdef VMS
9477 /* remove version for correct match */
9478 if (sfname != NULL)
9479 vms_remove_version(sfname);
9480 vms_remove_version(fname);
9481#endif
9482
9483 /*
9484 * Set the name to be used for <amatch>.
9485 */
9486 autocmd_match = fname;
9487
9488
9489 /* Don't redraw while doing auto commands. */
9490 ++RedrawingDisabled;
9491 save_sourcing_name = sourcing_name;
9492 sourcing_name = NULL; /* don't free this one */
9493 save_sourcing_lnum = sourcing_lnum;
9494 sourcing_lnum = 0; /* no line number here */
9495
9496#ifdef FEAT_EVAL
9497 save_current_SID = current_SID;
9498
Bram Moolenaar05159a02005-02-26 23:04:13 +00009499# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009500 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009501 prof_child_enter(&wait_time); /* doesn't count for the caller itself */
9502# endif
9503
Bram Moolenaar071d4272004-06-13 20:20:40 +00009504 /* Don't use local function variables, if called from a function */
9505 save_funccalp = save_funccal();
9506#endif
9507
9508 /*
9509 * When starting to execute autocommands, save the search patterns.
9510 */
9511 if (!autocmd_busy)
9512 {
9513 save_search_patterns();
Bram Moolenaar20ad69c2015-12-03 13:52:52 +01009514#ifdef FEAT_INS_EXPAND
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009515 if (!ins_compl_active())
Bram Moolenaar20ad69c2015-12-03 13:52:52 +01009516#endif
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009517 {
9518 saveRedobuff();
9519 did_save_redobuff = TRUE;
9520 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009521 did_filetype = keep_filetype;
9522 }
9523
9524 /*
9525 * Note that we are applying autocmds. Some commands need to know.
9526 */
9527 autocmd_busy = TRUE;
9528 filechangeshell_busy = (event == EVENT_FILECHANGEDSHELL);
9529 ++nesting; /* see matching decrement below */
9530
9531 /* Remember that FileType was triggered. Used for did_filetype(). */
9532 if (event == EVENT_FILETYPE)
9533 did_filetype = TRUE;
9534
9535 tail = gettail(fname);
9536
9537 /* Find first autocommand that matches */
9538 patcmd.curpat = first_autopat[(int)event];
9539 patcmd.nextcmd = NULL;
9540 patcmd.group = group;
9541 patcmd.fname = fname;
9542 patcmd.sfname = sfname;
9543 patcmd.tail = tail;
9544 patcmd.event = event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009545 patcmd.arg_bufnr = autocmd_bufnr;
9546 patcmd.next = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009547 auto_next_pat(&patcmd, FALSE);
9548
9549 /* found one, start executing the autocommands */
9550 if (patcmd.curpat != NULL)
9551 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009552 /* add to active_apc_list */
9553 patcmd.next = active_apc_list;
9554 active_apc_list = &patcmd;
9555
Bram Moolenaar071d4272004-06-13 20:20:40 +00009556#ifdef FEAT_EVAL
9557 /* set v:cmdarg (only when there is a matching pattern) */
Bram Moolenaar22fcfad2016-07-01 18:17:26 +02009558 save_cmdbang = (long)get_vim_var_nr(VV_CMDBANG);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009559 if (eap != NULL)
9560 {
9561 save_cmdarg = set_cmdarg(eap, NULL);
9562 set_vim_var_nr(VV_CMDBANG, (long)eap->forceit);
9563 }
9564 else
9565 save_cmdarg = NULL; /* avoid gcc warning */
9566#endif
9567 retval = TRUE;
9568 /* mark the last pattern, to avoid an endless loop when more patterns
9569 * are added when executing autocommands */
9570 for (ap = patcmd.curpat; ap->next != NULL; ap = ap->next)
9571 ap->last = FALSE;
9572 ap->last = TRUE;
9573 check_lnums(TRUE); /* make sure cursor and topline are valid */
9574 do_cmdline(NULL, getnextac, (void *)&patcmd,
9575 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
9576#ifdef FEAT_EVAL
9577 if (eap != NULL)
9578 {
9579 (void)set_cmdarg(NULL, save_cmdarg);
9580 set_vim_var_nr(VV_CMDBANG, save_cmdbang);
9581 }
9582#endif
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009583 /* delete from active_apc_list */
9584 if (active_apc_list == &patcmd) /* just in case */
9585 active_apc_list = patcmd.next;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009586 }
9587
9588 --RedrawingDisabled;
9589 autocmd_busy = save_autocmd_busy;
9590 filechangeshell_busy = FALSE;
9591 autocmd_nested = save_autocmd_nested;
9592 vim_free(sourcing_name);
9593 sourcing_name = save_sourcing_name;
9594 sourcing_lnum = save_sourcing_lnum;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009595 vim_free(autocmd_fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009596 autocmd_fname = save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009597 autocmd_fname_full = save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009598 autocmd_bufnr = save_autocmd_bufnr;
9599 autocmd_match = save_autocmd_match;
9600#ifdef FEAT_EVAL
9601 current_SID = save_current_SID;
9602 restore_funccal(save_funccalp);
Bram Moolenaar05159a02005-02-26 23:04:13 +00009603# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009604 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009605 prof_child_exit(&wait_time);
9606# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009607#endif
9608 vim_free(fname);
9609 vim_free(sfname);
9610 --nesting; /* see matching increment above */
9611
9612 /*
9613 * When stopping to execute autocommands, restore the search patterns and
Bram Moolenaar3be85852014-06-12 14:01:31 +02009614 * the redo buffer. Free any buffers in the au_pending_free_buf list and
9615 * free any windows in the au_pending_free_win list.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009616 */
9617 if (!autocmd_busy)
9618 {
9619 restore_search_patterns();
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009620 if (did_save_redobuff)
9621 restoreRedobuff();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009622 did_filetype = FALSE;
Bram Moolenaar4c7ab1b2014-04-06 20:45:43 +02009623 while (au_pending_free_buf != NULL)
9624 {
9625 buf_T *b = au_pending_free_buf->b_next;
9626 vim_free(au_pending_free_buf);
9627 au_pending_free_buf = b;
9628 }
Bram Moolenaar3be85852014-06-12 14:01:31 +02009629 while (au_pending_free_win != NULL)
9630 {
9631 win_T *w = au_pending_free_win->w_next;
9632 vim_free(au_pending_free_win);
9633 au_pending_free_win = w;
9634 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009635 }
9636
9637 /*
9638 * Some events don't set or reset the Changed flag.
9639 * Check if still in the same buffer!
9640 */
9641 if (curbuf == old_curbuf
9642 && (event == EVENT_BUFREADPOST
9643 || event == EVENT_BUFWRITEPOST
9644 || event == EVENT_FILEAPPENDPOST
9645 || event == EVENT_VIMLEAVE
9646 || event == EVENT_VIMLEAVEPRE))
9647 {
9648#ifdef FEAT_TITLE
9649 if (curbuf->b_changed != save_changed)
9650 need_maketitle = TRUE;
9651#endif
9652 curbuf->b_changed = save_changed;
9653 }
9654
9655 au_cleanup(); /* may really delete removed patterns/commands now */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009656
9657BYPASS_AU:
9658 /* When wiping out a buffer make sure all its buffer-local autocommands
9659 * are deleted. */
9660 if (event == EVENT_BUFWIPEOUT && buf != NULL)
9661 aubuflocal_remove(buf);
9662
Bram Moolenaarc3691332016-04-20 12:49:49 +02009663 if (retval == OK && event == EVENT_FILETYPE)
9664 au_did_filetype = TRUE;
9665
Bram Moolenaar071d4272004-06-13 20:20:40 +00009666 return retval;
9667}
9668
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009669# ifdef FEAT_EVAL
9670static char_u *old_termresponse = NULL;
9671# endif
9672
9673/*
9674 * Block triggering autocommands until unblock_autocmd() is called.
9675 * Can be used recursively, so long as it's symmetric.
9676 */
9677 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009678block_autocmds(void)
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009679{
9680# ifdef FEAT_EVAL
9681 /* Remember the value of v:termresponse. */
9682 if (autocmd_blocked == 0)
9683 old_termresponse = get_vim_var_str(VV_TERMRESPONSE);
9684# endif
9685 ++autocmd_blocked;
9686}
9687
9688 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009689unblock_autocmds(void)
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009690{
9691 --autocmd_blocked;
9692
9693# ifdef FEAT_EVAL
9694 /* When v:termresponse was set while autocommands were blocked, trigger
9695 * the autocommands now. Esp. useful when executing a shell command
9696 * during startup (vimdiff). */
9697 if (autocmd_blocked == 0
9698 && get_vim_var_str(VV_TERMRESPONSE) != old_termresponse)
9699 apply_autocmds(EVENT_TERMRESPONSE, NULL, NULL, FALSE, curbuf);
9700# endif
9701}
9702
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009703 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009704is_autocmd_blocked(void)
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009705{
9706 return autocmd_blocked != 0;
9707}
9708
Bram Moolenaar071d4272004-06-13 20:20:40 +00009709/*
9710 * Find next autocommand pattern that matches.
9711 */
9712 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009713auto_next_pat(
9714 AutoPatCmd *apc,
9715 int stop_at_last) /* stop when 'last' flag is set */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009716{
9717 AutoPat *ap;
9718 AutoCmd *cp;
9719 char_u *name;
9720 char *s;
9721
9722 vim_free(sourcing_name);
9723 sourcing_name = NULL;
9724
9725 for (ap = apc->curpat; ap != NULL && !got_int; ap = ap->next)
9726 {
9727 apc->curpat = NULL;
9728
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009729 /* Only use a pattern when it has not been removed, has commands and
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009730 * the group matches. For buffer-local autocommands only check the
9731 * buffer number. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009732 if (ap->pat != NULL && ap->cmds != NULL
9733 && (apc->group == AUGROUP_ALL || apc->group == ap->group))
9734 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009735 /* execution-condition */
9736 if (ap->buflocal_nr == 0
Bram Moolenaardffa5b82014-11-19 16:38:07 +01009737 ? (match_file_pat(NULL, &ap->reg_prog, apc->fname,
Bram Moolenaar748bf032005-02-02 23:04:36 +00009738 apc->sfname, apc->tail, ap->allow_dirs))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009739 : ap->buflocal_nr == apc->arg_bufnr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009740 {
9741 name = event_nr2name(apc->event);
9742 s = _("%s Auto commands for \"%s\"");
9743 sourcing_name = alloc((unsigned)(STRLEN(s)
9744 + STRLEN(name) + ap->patlen + 1));
9745 if (sourcing_name != NULL)
9746 {
9747 sprintf((char *)sourcing_name, s,
9748 (char *)name, (char *)ap->pat);
9749 if (p_verbose >= 8)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009750 {
9751 verbose_enter();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009752 smsg((char_u *)_("Executing %s"), sourcing_name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009753 verbose_leave();
9754 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009755 }
9756
9757 apc->curpat = ap;
9758 apc->nextcmd = ap->cmds;
9759 /* mark last command */
9760 for (cp = ap->cmds; cp->next != NULL; cp = cp->next)
9761 cp->last = FALSE;
9762 cp->last = TRUE;
9763 }
9764 line_breakcheck();
9765 if (apc->curpat != NULL) /* found a match */
9766 break;
9767 }
9768 if (stop_at_last && ap->last)
9769 break;
9770 }
9771}
9772
9773/*
9774 * Get next autocommand command.
9775 * Called by do_cmdline() to get the next line for ":if".
9776 * Returns allocated string, or NULL for end of autocommands.
9777 */
Bram Moolenaar21691f82012-12-05 19:13:18 +01009778 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009779getnextac(int c UNUSED, void *cookie, int indent UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009780{
9781 AutoPatCmd *acp = (AutoPatCmd *)cookie;
9782 char_u *retval;
9783 AutoCmd *ac;
9784
9785 /* Can be called again after returning the last line. */
9786 if (acp->curpat == NULL)
9787 return NULL;
9788
9789 /* repeat until we find an autocommand to execute */
9790 for (;;)
9791 {
9792 /* skip removed commands */
9793 while (acp->nextcmd != NULL && acp->nextcmd->cmd == NULL)
9794 if (acp->nextcmd->last)
9795 acp->nextcmd = NULL;
9796 else
9797 acp->nextcmd = acp->nextcmd->next;
9798
9799 if (acp->nextcmd != NULL)
9800 break;
9801
9802 /* at end of commands, find next pattern that matches */
9803 if (acp->curpat->last)
9804 acp->curpat = NULL;
9805 else
9806 acp->curpat = acp->curpat->next;
9807 if (acp->curpat != NULL)
9808 auto_next_pat(acp, TRUE);
9809 if (acp->curpat == NULL)
9810 return NULL;
9811 }
9812
9813 ac = acp->nextcmd;
9814
9815 if (p_verbose >= 9)
9816 {
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009817 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009818 smsg((char_u *)_("autocommand %s"), ac->cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009819 msg_puts((char_u *)"\n"); /* don't overwrite this either */
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009820 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009821 }
9822 retval = vim_strsave(ac->cmd);
9823 autocmd_nested = ac->nested;
9824#ifdef FEAT_EVAL
9825 current_SID = ac->scriptID;
9826#endif
9827 if (ac->last)
9828 acp->nextcmd = NULL;
9829 else
9830 acp->nextcmd = ac->next;
9831 return retval;
9832}
9833
9834/*
9835 * Return TRUE if there is a matching autocommand for "fname".
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009836 * To account for buffer-local autocommands, function needs to know
9837 * in which buffer the file will be opened.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009838 */
9839 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009840has_autocmd(event_T event, char_u *sfname, buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009841{
9842 AutoPat *ap;
9843 char_u *fname;
9844 char_u *tail = gettail(sfname);
9845 int retval = FALSE;
9846
9847 fname = FullName_save(sfname, FALSE);
9848 if (fname == NULL)
9849 return FALSE;
9850
9851#ifdef BACKSLASH_IN_FILENAME
9852 /*
9853 * Replace all backslashes with forward slashes. This makes the
9854 * autocommand patterns portable between Unix and MS-DOS.
9855 */
9856 sfname = vim_strsave(sfname);
9857 if (sfname != NULL)
9858 forward_slash(sfname);
9859 forward_slash(fname);
9860#endif
9861
9862 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
9863 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009864 && (ap->buflocal_nr == 0
Bram Moolenaardffa5b82014-11-19 16:38:07 +01009865 ? match_file_pat(NULL, &ap->reg_prog,
Bram Moolenaar748bf032005-02-02 23:04:36 +00009866 fname, sfname, tail, ap->allow_dirs)
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009867 : buf != NULL && ap->buflocal_nr == buf->b_fnum
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009868 ))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009869 {
9870 retval = TRUE;
9871 break;
9872 }
9873
9874 vim_free(fname);
9875#ifdef BACKSLASH_IN_FILENAME
9876 vim_free(sfname);
9877#endif
9878
9879 return retval;
9880}
9881
9882#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
9883/*
9884 * Function given to ExpandGeneric() to obtain the list of autocommand group
9885 * names.
9886 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009887 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009888get_augroup_name(expand_T *xp UNUSED, int idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009889{
9890 if (idx == augroups.ga_len) /* add "END" add the end */
9891 return (char_u *)"END";
9892 if (idx >= augroups.ga_len) /* end of list */
9893 return NULL;
Bram Moolenaarb62cc362016-09-03 16:43:53 +02009894 if (AUGROUP_NAME(idx) == NULL || AUGROUP_NAME(idx) == get_deleted_augroup())
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02009895 /* skip deleted entries */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009896 return (char_u *)"";
9897 return AUGROUP_NAME(idx); /* return a name */
9898}
9899
9900static int include_groups = FALSE;
9901
9902 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009903set_context_in_autocmd(
9904 expand_T *xp,
9905 char_u *arg,
9906 int doautocmd) /* TRUE for :doauto*, FALSE for :autocmd */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009907{
9908 char_u *p;
9909 int group;
9910
9911 /* check for a group name, skip it if present */
9912 include_groups = FALSE;
9913 p = arg;
9914 group = au_get_grouparg(&arg);
9915 if (group == AUGROUP_ERROR)
9916 return NULL;
9917 /* If there only is a group name that's what we expand. */
9918 if (*arg == NUL && group != AUGROUP_ALL && !vim_iswhite(arg[-1]))
9919 {
9920 arg = p;
9921 group = AUGROUP_ALL;
9922 }
9923
9924 /* skip over event name */
9925 for (p = arg; *p != NUL && !vim_iswhite(*p); ++p)
9926 if (*p == ',')
9927 arg = p + 1;
9928 if (*p == NUL)
9929 {
9930 if (group == AUGROUP_ALL)
9931 include_groups = TRUE;
9932 xp->xp_context = EXPAND_EVENTS; /* expand event name */
9933 xp->xp_pattern = arg;
9934 return NULL;
9935 }
9936
9937 /* skip over pattern */
9938 arg = skipwhite(p);
9939 while (*arg && (!vim_iswhite(*arg) || arg[-1] == '\\'))
9940 arg++;
9941 if (*arg)
9942 return arg; /* expand (next) command */
9943
9944 if (doautocmd)
9945 xp->xp_context = EXPAND_FILES; /* expand file names */
9946 else
9947 xp->xp_context = EXPAND_NOTHING; /* pattern is not expanded */
9948 return NULL;
9949}
9950
9951/*
9952 * Function given to ExpandGeneric() to obtain the list of event names.
9953 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009954 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009955get_event_name(expand_T *xp UNUSED, int idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009956{
9957 if (idx < augroups.ga_len) /* First list group names, if wanted */
9958 {
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02009959 if (!include_groups || AUGROUP_NAME(idx) == NULL
Bram Moolenaarb62cc362016-09-03 16:43:53 +02009960 || AUGROUP_NAME(idx) == get_deleted_augroup())
Bram Moolenaar071d4272004-06-13 20:20:40 +00009961 return (char_u *)""; /* skip deleted entries */
9962 return AUGROUP_NAME(idx); /* return a name */
9963 }
9964 return (char_u *)event_names[idx - augroups.ga_len].name;
9965}
9966
9967#endif /* FEAT_CMDL_COMPL */
9968
9969/*
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009970 * Return TRUE if autocmd is supported.
9971 */
9972 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009973autocmd_supported(char_u *name)
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009974{
9975 char_u *p;
9976
9977 return (event_name2nr(name, &p) != NUM_EVENTS);
9978}
9979
9980/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00009981 * Return TRUE if an autocommand is defined for a group, event and
9982 * pattern: The group can be omitted to accept any group. "event" and "pattern"
9983 * can be NULL to accept any event and pattern. "pattern" can be NULL to accept
9984 * any pattern. Buffer-local patterns <buffer> or <buffer=N> are accepted.
9985 * Used for:
9986 * exists("#Group") or
9987 * exists("#Group#Event") or
9988 * exists("#Group#Event#pat") or
9989 * exists("#Event") or
9990 * exists("#Event#pat")
Bram Moolenaar071d4272004-06-13 20:20:40 +00009991 */
9992 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009993au_exists(char_u *arg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009994{
Bram Moolenaar195d6352005-12-19 22:08:24 +00009995 char_u *arg_save;
9996 char_u *pattern = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009997 char_u *event_name;
9998 char_u *p;
Bram Moolenaar754b5602006-02-09 23:53:20 +00009999 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010000 AutoPat *ap;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010001 buf_T *buflocal_buf = NULL;
Bram Moolenaar195d6352005-12-19 22:08:24 +000010002 int group;
10003 int retval = FALSE;
10004
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010005 /* Make a copy so that we can change the '#' chars to a NUL. */
Bram Moolenaar195d6352005-12-19 22:08:24 +000010006 arg_save = vim_strsave(arg);
10007 if (arg_save == NULL)
10008 return FALSE;
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010009 p = vim_strchr(arg_save, '#');
Bram Moolenaar195d6352005-12-19 22:08:24 +000010010 if (p != NULL)
10011 *p++ = NUL;
10012
10013 /* First, look for an autocmd group name */
10014 group = au_find_group(arg_save);
10015 if (group == AUGROUP_ERROR)
10016 {
10017 /* Didn't match a group name, assume the first argument is an event. */
10018 group = AUGROUP_ALL;
10019 event_name = arg_save;
10020 }
10021 else
10022 {
10023 if (p == NULL)
10024 {
10025 /* "Group": group name is present and it's recognized */
10026 retval = TRUE;
10027 goto theend;
10028 }
10029
10030 /* Must be "Group#Event" or "Group#Event#pat". */
10031 event_name = p;
10032 p = vim_strchr(event_name, '#');
10033 if (p != NULL)
10034 *p++ = NUL; /* "Group#Event#pat" */
10035 }
10036
10037 pattern = p; /* "pattern" is NULL when there is no pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010038
10039 /* find the index (enum) for the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010040 event = event_name2nr(event_name, &p);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010041
10042 /* return FALSE if the event name is not recognized */
Bram Moolenaar195d6352005-12-19 22:08:24 +000010043 if (event == NUM_EVENTS)
10044 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010045
10046 /* Find the first autocommand for this event.
10047 * If there isn't any, return FALSE;
10048 * If there is one and no pattern given, return TRUE; */
10049 ap = first_autopat[(int)event];
10050 if (ap == NULL)
Bram Moolenaar195d6352005-12-19 22:08:24 +000010051 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010052
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010053 /* if pattern is "<buffer>", special handling is needed which uses curbuf */
10054 /* for pattern "<buffer=N>, fnamecmp() will work fine */
Bram Moolenaar5b7880d2009-09-11 15:24:31 +000010055 if (pattern != NULL && STRICMP(pattern, "<buffer>") == 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010056 buflocal_buf = curbuf;
10057
Bram Moolenaar071d4272004-06-13 20:20:40 +000010058 /* Check if there is an autocommand with the given pattern. */
10059 for ( ; ap != NULL; ap = ap->next)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010060 /* only use a pattern when it has not been removed and has commands. */
10061 /* For buffer-local autocommands, fnamecmp() works fine. */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010062 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaar195d6352005-12-19 22:08:24 +000010063 && (group == AUGROUP_ALL || ap->group == group)
Bram Moolenaar5b7880d2009-09-11 15:24:31 +000010064 && (pattern == NULL
10065 || (buflocal_buf == NULL
10066 ? fnamecmp(ap->pat, pattern) == 0
10067 : ap->buflocal_nr == buflocal_buf->b_fnum)))
Bram Moolenaar195d6352005-12-19 22:08:24 +000010068 {
10069 retval = TRUE;
10070 break;
10071 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010072
Bram Moolenaar195d6352005-12-19 22:08:24 +000010073theend:
10074 vim_free(arg_save);
10075 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010076}
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010077
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010078#else /* FEAT_AUTOCMD */
10079
10080/*
10081 * Prepare for executing commands for (hidden) buffer "buf".
10082 * This is the non-autocommand version, it simply saves "curbuf" and sets
10083 * "curbuf" and "curwin" to match "buf".
10084 */
10085 void
Bram Moolenaard14e00e2016-01-31 17:30:51 +010010086aucmd_prepbuf(
10087 aco_save_T *aco, /* structure to save values in */
10088 buf_T *buf) /* new curbuf */
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010089{
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010090 aco->save_curbuf = curbuf;
10091 --curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010092 curbuf = buf;
10093 curwin->w_buffer = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010094 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010095}
10096
10097/*
10098 * Restore after executing commands for a (hidden) buffer.
10099 * This is the non-autocommand version.
10100 */
10101 void
Bram Moolenaard14e00e2016-01-31 17:30:51 +010010102aucmd_restbuf(
10103 aco_save_T *aco) /* structure holding saved values */
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010104{
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010105 --curbuf->b_nwindows;
10106 curbuf = aco->save_curbuf;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010107 curwin->w_buffer = curbuf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010108 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010109}
10110
Bram Moolenaar071d4272004-06-13 20:20:40 +000010111#endif /* FEAT_AUTOCMD */
10112
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010113
Bram Moolenaar071d4272004-06-13 20:20:40 +000010114#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN) || defined(PROTO)
10115/*
Bram Moolenaar748bf032005-02-02 23:04:36 +000010116 * Try matching a filename with a "pattern" ("prog" is NULL), or use the
10117 * precompiled regprog "prog" ("pattern" is NULL). That avoids calling
10118 * vim_regcomp() often.
Bram Moolenaar071d4272004-06-13 20:20:40 +000010119 * Used for autocommands and 'wildignore'.
10120 * Returns TRUE if there is a match, FALSE otherwise.
10121 */
Bram Moolenaardffa5b82014-11-19 16:38:07 +010010122 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010123match_file_pat(
10124 char_u *pattern, /* pattern to match with */
10125 regprog_T **prog, /* pre-compiled regprog or NULL */
10126 char_u *fname, /* full path of file name */
10127 char_u *sfname, /* short file name or NULL */
10128 char_u *tail, /* tail of path */
10129 int allow_dirs) /* allow matching with dir */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010130{
10131 regmatch_T regmatch;
10132 int result = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010133
Bram Moolenaar71afbfe2013-03-19 16:49:16 +010010134 regmatch.rm_ic = p_fic; /* ignore case if 'fileignorecase' is set */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010135 if (prog != NULL)
10136 regmatch.regprog = *prog;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010137 else
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010138 regmatch.regprog = vim_regcomp(pattern, RE_MAGIC);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010139
10140 /*
10141 * Try for a match with the pattern with:
10142 * 1. the full file name, when the pattern has a '/'.
10143 * 2. the short file name, when the pattern has a '/'.
10144 * 3. the tail of the file name, when the pattern has no '/'.
10145 */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010146 if (regmatch.regprog != NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +000010147 && ((allow_dirs
10148 && (vim_regexec(&regmatch, fname, (colnr_T)0)
10149 || (sfname != NULL
10150 && vim_regexec(&regmatch, sfname, (colnr_T)0))))
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010151 || (!allow_dirs && vim_regexec(&regmatch, tail, (colnr_T)0))))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010152 result = TRUE;
10153
Bram Moolenaardffa5b82014-11-19 16:38:07 +010010154 if (prog != NULL)
10155 *prog = regmatch.regprog;
10156 else
Bram Moolenaar473de612013-06-08 18:19:48 +020010157 vim_regfree(regmatch.regprog);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010158 return result;
10159}
10160#endif
10161
10162#if defined(FEAT_WILDIGN) || defined(PROTO)
10163/*
10164 * Return TRUE if a file matches with a pattern in "list".
10165 * "list" is a comma-separated list of patterns, like 'wildignore'.
10166 * "sfname" is the short file name or NULL, "ffname" the long file name.
10167 */
10168 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010169match_file_list(char_u *list, char_u *sfname, char_u *ffname)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010170{
10171 char_u buf[100];
10172 char_u *tail;
10173 char_u *regpat;
10174 char allow_dirs;
10175 int match;
10176 char_u *p;
10177
10178 tail = gettail(sfname);
10179
10180 /* try all patterns in 'wildignore' */
10181 p = list;
10182 while (*p)
10183 {
10184 copy_option_part(&p, buf, 100, ",");
10185 regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, FALSE);
10186 if (regpat == NULL)
10187 break;
Bram Moolenaar748bf032005-02-02 23:04:36 +000010188 match = match_file_pat(regpat, NULL, ffname, sfname,
10189 tail, (int)allow_dirs);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010190 vim_free(regpat);
10191 if (match)
10192 return TRUE;
10193 }
10194 return FALSE;
10195}
10196#endif
10197
10198/*
10199 * Convert the given pattern "pat" which has shell style wildcards in it, into
10200 * a regular expression, and return the result in allocated memory. If there
10201 * is a directory path separator to be matched, then TRUE is put in
10202 * allow_dirs, otherwise FALSE is put there -- webb.
10203 * Handle backslashes before special characters, like "\*" and "\ ".
10204 *
Bram Moolenaar071d4272004-06-13 20:20:40 +000010205 * Returns NULL when out of memory.
10206 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010207 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010208file_pat_to_reg_pat(
10209 char_u *pat,
10210 char_u *pat_end, /* first char after pattern or NULL */
10211 char *allow_dirs, /* Result passed back out in here */
10212 int no_bslash UNUSED) /* Don't use a backward slash as pathsep */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010213{
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010214 int size = 2; /* '^' at start, '$' at end */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010215 char_u *endp;
10216 char_u *reg_pat;
10217 char_u *p;
10218 int i;
10219 int nested = 0;
10220 int add_dollar = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010221
10222 if (allow_dirs != NULL)
10223 *allow_dirs = FALSE;
10224 if (pat_end == NULL)
10225 pat_end = pat + STRLEN(pat);
10226
Bram Moolenaar071d4272004-06-13 20:20:40 +000010227 for (p = pat; p < pat_end; p++)
10228 {
10229 switch (*p)
10230 {
10231 case '*':
10232 case '.':
10233 case ',':
10234 case '{':
10235 case '}':
10236 case '~':
10237 size += 2; /* extra backslash */
10238 break;
10239#ifdef BACKSLASH_IN_FILENAME
10240 case '\\':
10241 case '/':
10242 size += 4; /* could become "[\/]" */
10243 break;
10244#endif
10245 default:
10246 size++;
Bram Moolenaar2288afe2015-08-11 16:20:05 +020010247# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010248 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010249 {
10250 ++p;
10251 ++size;
10252 }
10253# endif
10254 break;
10255 }
10256 }
10257 reg_pat = alloc(size + 1);
10258 if (reg_pat == NULL)
10259 return NULL;
10260
Bram Moolenaar071d4272004-06-13 20:20:40 +000010261 i = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010262
10263 if (pat[0] == '*')
10264 while (pat[0] == '*' && pat < pat_end - 1)
10265 pat++;
10266 else
10267 reg_pat[i++] = '^';
10268 endp = pat_end - 1;
Bram Moolenaar8fee8782015-08-11 18:45:48 +020010269 if (endp >= pat && *endp == '*')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010270 {
10271 while (endp - pat > 0 && *endp == '*')
10272 endp--;
10273 add_dollar = FALSE;
10274 }
10275 for (p = pat; *p && nested >= 0 && p <= endp; p++)
10276 {
10277 switch (*p)
10278 {
10279 case '*':
10280 reg_pat[i++] = '.';
10281 reg_pat[i++] = '*';
Bram Moolenaar02743632005-07-25 20:42:36 +000010282 while (p[1] == '*') /* "**" matches like "*" */
10283 ++p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010284 break;
10285 case '.':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010286 case '~':
10287 reg_pat[i++] = '\\';
10288 reg_pat[i++] = *p;
10289 break;
10290 case '?':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010291 reg_pat[i++] = '.';
10292 break;
10293 case '\\':
10294 if (p[1] == NUL)
10295 break;
10296#ifdef BACKSLASH_IN_FILENAME
10297 if (!no_bslash)
10298 {
10299 /* translate:
10300 * "\x" to "\\x" e.g., "dir\file"
10301 * "\*" to "\\.*" e.g., "dir\*.c"
10302 * "\?" to "\\." e.g., "dir\??.c"
10303 * "\+" to "\+" e.g., "fileX\+.c"
10304 */
10305 if ((vim_isfilec(p[1]) || p[1] == '*' || p[1] == '?')
10306 && p[1] != '+')
10307 {
10308 reg_pat[i++] = '[';
10309 reg_pat[i++] = '\\';
10310 reg_pat[i++] = '/';
10311 reg_pat[i++] = ']';
10312 if (allow_dirs != NULL)
10313 *allow_dirs = TRUE;
10314 break;
10315 }
10316 }
10317#endif
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010318 /* Undo escaping from ExpandEscape():
10319 * foo\?bar -> foo?bar
10320 * foo\%bar -> foo%bar
10321 * foo\,bar -> foo,bar
10322 * foo\ bar -> foo bar
10323 * Don't unescape \, * and others that are also special in a
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010324 * regexp.
10325 * An escaped { must be unescaped since we use magic not
Bram Moolenaara946afe2013-08-02 15:22:39 +020010326 * verymagic. Use "\\\{n,m\}"" to get "\{n,m}".
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010327 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010328 if (*++p == '?'
10329#ifdef BACKSLASH_IN_FILENAME
10330 && no_bslash
10331#endif
10332 )
10333 reg_pat[i++] = '?';
10334 else
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010335 if (*p == ',' || *p == '%' || *p == '#'
Bram Moolenaar2288afe2015-08-11 16:20:05 +020010336 || vim_isspace(*p) || *p == '{' || *p == '}')
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010337 reg_pat[i++] = *p;
Bram Moolenaara946afe2013-08-02 15:22:39 +020010338 else if (*p == '\\' && p[1] == '\\' && p[2] == '{')
10339 {
10340 reg_pat[i++] = '\\';
10341 reg_pat[i++] = '{';
10342 p += 2;
10343 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010344 else
10345 {
10346 if (allow_dirs != NULL && vim_ispathsep(*p)
10347#ifdef BACKSLASH_IN_FILENAME
10348 && (!no_bslash || *p != '\\')
10349#endif
10350 )
10351 *allow_dirs = TRUE;
10352 reg_pat[i++] = '\\';
10353 reg_pat[i++] = *p;
10354 }
10355 break;
10356#ifdef BACKSLASH_IN_FILENAME
10357 case '/':
10358 reg_pat[i++] = '[';
10359 reg_pat[i++] = '\\';
10360 reg_pat[i++] = '/';
10361 reg_pat[i++] = ']';
10362 if (allow_dirs != NULL)
10363 *allow_dirs = TRUE;
10364 break;
10365#endif
10366 case '{':
10367 reg_pat[i++] = '\\';
10368 reg_pat[i++] = '(';
10369 nested++;
10370 break;
10371 case '}':
10372 reg_pat[i++] = '\\';
10373 reg_pat[i++] = ')';
10374 --nested;
10375 break;
10376 case ',':
10377 if (nested)
10378 {
10379 reg_pat[i++] = '\\';
10380 reg_pat[i++] = '|';
10381 }
10382 else
10383 reg_pat[i++] = ',';
10384 break;
10385 default:
10386# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010387 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010388 reg_pat[i++] = *p++;
10389 else
10390# endif
10391 if (allow_dirs != NULL && vim_ispathsep(*p))
10392 *allow_dirs = TRUE;
10393 reg_pat[i++] = *p;
10394 break;
10395 }
10396 }
10397 if (add_dollar)
10398 reg_pat[i++] = '$';
10399 reg_pat[i] = NUL;
10400 if (nested != 0)
10401 {
10402 if (nested < 0)
10403 EMSG(_("E219: Missing {."));
10404 else
10405 EMSG(_("E220: Missing }."));
10406 vim_free(reg_pat);
10407 reg_pat = NULL;
10408 }
10409 return reg_pat;
10410}
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010411
10412#if defined(EINTR) || defined(PROTO)
10413/*
10414 * Version of read() that retries when interrupted by EINTR (possibly
10415 * by a SIGWINCH).
10416 */
10417 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010418read_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010419{
10420 long ret;
10421
10422 for (;;)
10423 {
10424 ret = vim_read(fd, buf, bufsize);
10425 if (ret >= 0 || errno != EINTR)
10426 break;
10427 }
10428 return ret;
10429}
10430
10431/*
10432 * Version of write() that retries when interrupted by EINTR (possibly
10433 * by a SIGWINCH).
10434 */
10435 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010436write_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010437{
10438 long ret = 0;
10439 long wlen;
10440
10441 /* Repeat the write() so long it didn't fail, other than being interrupted
10442 * by a signal. */
10443 while (ret < (long)bufsize)
10444 {
Bram Moolenaar9c263032010-12-17 18:06:06 +010010445 wlen = vim_write(fd, (char *)buf + ret, bufsize - ret);
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010446 if (wlen < 0)
10447 {
10448 if (errno != EINTR)
10449 break;
10450 }
10451 else
10452 ret += wlen;
10453 }
10454 return ret;
10455}
10456#endif