blob: aeb53b593d14a3d95bf88afa622454d352036b30 [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 */
277 int try_mac = (vim_strchr(p_ffs, 'm') != NULL);
278 int try_dos = (vim_strchr(p_ffs, 'd') != NULL);
279 int try_unix = (vim_strchr(p_ffs, 'x') != NULL);
280 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
741#ifdef FEAT_AUTOCMD
742 if (!read_buffer)
743 {
744 int m = msg_scroll;
745 int n = msg_scrolled;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000746
747 /*
748 * The file must be closed again, the autocommands may want to change
749 * the file before reading it.
750 */
751 if (!read_stdin)
752 close(fd); /* ignore errors */
753
754 /*
755 * The output from the autocommands should not overwrite anything and
756 * should not be overwritten: Set msg_scroll, restore its value if no
757 * output was done.
758 */
759 msg_scroll = TRUE;
760 if (filtering)
761 apply_autocmds_exarg(EVENT_FILTERREADPRE, NULL, sfname,
762 FALSE, curbuf, eap);
763 else if (read_stdin)
764 apply_autocmds_exarg(EVENT_STDINREADPRE, NULL, sfname,
765 FALSE, curbuf, eap);
766 else if (newfile)
767 apply_autocmds_exarg(EVENT_BUFREADPRE, NULL, sfname,
768 FALSE, curbuf, eap);
769 else
770 apply_autocmds_exarg(EVENT_FILEREADPRE, sfname, sfname,
771 FALSE, NULL, eap);
772 if (msg_scrolled == n)
773 msg_scroll = m;
774
775#ifdef FEAT_EVAL
776 if (aborting()) /* autocmds may abort script processing */
777 {
778 --no_wait_return;
779 msg_scroll = msg_save;
780 curbuf->b_p_ro = TRUE; /* must use "w!" now */
781 return FAIL;
782 }
783#endif
784 /*
785 * Don't allow the autocommands to change the current buffer.
786 * Try to re-open the file.
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000787 *
788 * Don't allow the autocommands to change the buffer name either
789 * (cd for example) if it invalidates fname or sfname.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000790 */
791 if (!read_stdin && (curbuf != old_curbuf
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000792 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
793 || (using_b_fname && (old_b_fname != curbuf->b_fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000794 || (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) < 0))
795 {
796 --no_wait_return;
797 msg_scroll = msg_save;
798 if (fd < 0)
799 EMSG(_("E200: *ReadPre autocommands made the file unreadable"));
800 else
801 EMSG(_("E201: *ReadPre autocommands must not change current buffer"));
802 curbuf->b_p_ro = TRUE; /* must use "w!" now */
803 return FAIL;
804 }
805 }
806#endif /* FEAT_AUTOCMD */
807
808 /* Autocommands may add lines to the file, need to check if it is empty */
809 wasempty = (curbuf->b_ml.ml_flags & ML_EMPTY);
810
811 if (!recoverymode && !filtering && !(flags & READ_DUMMY))
812 {
813 /*
814 * Show the user that we are busy reading the input. Sometimes this
815 * may take a while. When reading from stdin another program may
816 * still be running, don't move the cursor to the last line, unless
817 * always using the GUI.
818 */
819 if (read_stdin)
820 {
821#ifndef ALWAYS_USE_GUI
822 mch_msg(_("Vim: Reading from stdin...\n"));
823#endif
824#ifdef FEAT_GUI
825 /* Also write a message in the GUI window, if there is one. */
826 if (gui.in_use && !gui.dying && !gui.starting)
827 {
828 p = (char_u *)_("Reading from stdin...");
829 gui_write(p, (int)STRLEN(p));
830 }
831#endif
832 }
833 else if (!read_buffer)
834 filemess(curbuf, sfname, (char_u *)"", 0);
835 }
836
837 msg_scroll = FALSE; /* overwrite the file message */
838
839 /*
840 * Set linecnt now, before the "retry" caused by a wrong guess for
841 * fileformat, and after the autocommands, which may change them.
842 */
843 linecnt = curbuf->b_ml.ml_line_count;
844
845#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000846 /* "++bad=" argument. */
847 if (eap != NULL && eap->bad_char != 0)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000848 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000849 bad_char_behavior = eap->bad_char;
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000850 if (set_options)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000851 curbuf->b_bad_char = eap->bad_char;
852 }
853 else
854 curbuf->b_bad_char = 0;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000855
Bram Moolenaar071d4272004-06-13 20:20:40 +0000856 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000857 * Decide which 'encoding' to use or use first.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000858 */
859 if (eap != NULL && eap->force_enc != 0)
860 {
861 fenc = enc_canonize(eap->cmd + eap->force_enc);
862 fenc_alloced = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000863 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000864 }
865 else if (curbuf->b_p_bin)
866 {
867 fenc = (char_u *)""; /* binary: don't convert */
868 fenc_alloced = FALSE;
869 }
870 else if (curbuf->b_help)
871 {
872 char_u firstline[80];
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000873 int fc;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000874
875 /* Help files are either utf-8 or latin1. Try utf-8 first, if this
876 * fails it must be latin1.
877 * Always do this when 'encoding' is "utf-8". Otherwise only do
878 * this when needed to avoid [converted] remarks all the time.
879 * It is needed when the first line contains non-ASCII characters.
880 * That is only in *.??x files. */
881 fenc = (char_u *)"latin1";
882 c = enc_utf8;
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000883 if (!c && !read_stdin)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000884 {
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000885 fc = fname[STRLEN(fname) - 1];
886 if (TOLOWER_ASC(fc) == 'x')
887 {
888 /* Read the first line (and a bit more). Immediately rewind to
889 * the start of the file. If the read() fails "len" is -1. */
Bram Moolenaar540fc6f2010-12-17 16:27:16 +0100890 len = read_eintr(fd, firstline, 80);
Bram Moolenaar8767f522016-07-01 17:17:39 +0200891 vim_lseek(fd, (off_T)0L, SEEK_SET);
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000892 for (p = firstline; p < firstline + len; ++p)
893 if (*p >= 0x80)
894 {
895 c = TRUE;
896 break;
897 }
898 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000899 }
900
901 if (c)
902 {
903 fenc_next = fenc;
904 fenc = (char_u *)"utf-8";
905
906 /* When the file is utf-8 but a character doesn't fit in
907 * 'encoding' don't retry. In help text editing utf-8 bytes
908 * doesn't make sense. */
Bram Moolenaarf193fff2006-04-27 00:02:13 +0000909 if (!enc_utf8)
910 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000911 }
912 fenc_alloced = FALSE;
913 }
914 else if (*p_fencs == NUL)
915 {
916 fenc = curbuf->b_p_fenc; /* use format from buffer */
917 fenc_alloced = FALSE;
918 }
919 else
920 {
921 fenc_next = p_fencs; /* try items in 'fileencodings' */
922 fenc = next_fenc(&fenc_next);
923 fenc_alloced = TRUE;
924 }
925#endif
926
927 /*
928 * Jump back here to retry reading the file in different ways.
929 * Reasons to retry:
930 * - encoding conversion failed: try another one from "fenc_next"
931 * - BOM detected and fenc was set, need to setup conversion
932 * - "fileformat" check failed: try another
933 *
934 * Variables set for special retry actions:
935 * "file_rewind" Rewind the file to start reading it again.
936 * "advance_fenc" Advance "fenc" using "fenc_next".
937 * "skip_read" Re-use already read bytes (BOM detected).
938 * "did_iconv" iconv() conversion failed, try 'charconvert'.
939 * "keep_fileformat" Don't reset "fileformat".
940 *
941 * Other status indicators:
942 * "tmpname" When != NULL did conversion with 'charconvert'.
943 * Output file has to be deleted afterwards.
944 * "iconv_fd" When != -1 did conversion with iconv().
945 */
946retry:
947
948 if (file_rewind)
949 {
950 if (read_buffer)
951 {
952 read_buf_lnum = 1;
953 read_buf_col = 0;
954 }
Bram Moolenaar8767f522016-07-01 17:17:39 +0200955 else if (read_stdin || vim_lseek(fd, (off_T)0L, SEEK_SET) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000956 {
957 /* Can't rewind the file, give up. */
958 error = TRUE;
959 goto failed;
960 }
961 /* Delete the previously read lines. */
962 while (lnum > from)
963 ml_delete(lnum--, FALSE);
964 file_rewind = FALSE;
965#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000966 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000967 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000968 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000969 curbuf->b_start_bomb = FALSE;
970 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000971 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000972#endif
973 }
974
975 /*
976 * When retrying with another "fenc" and the first time "fileformat"
977 * will be reset.
978 */
979 if (keep_fileformat)
980 keep_fileformat = FALSE;
981 else
982 {
983 if (eap != NULL && eap->force_ff != 0)
Bram Moolenaar1c860362008-11-12 15:05:21 +0000984 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000985 fileformat = get_fileformat_force(curbuf, eap);
Bram Moolenaar1c860362008-11-12 15:05:21 +0000986 try_unix = try_dos = try_mac = FALSE;
987 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000988 else if (curbuf->b_p_bin)
989 fileformat = EOL_UNIX; /* binary: use Unix format */
990 else if (*p_ffs == NUL)
991 fileformat = get_fileformat(curbuf);/* use format from buffer */
992 else
993 fileformat = EOL_UNKNOWN; /* detect from file */
994 }
995
996#ifdef FEAT_MBYTE
997# ifdef USE_ICONV
998 if (iconv_fd != (iconv_t)-1)
999 {
1000 /* aborted conversion with iconv(), close the descriptor */
1001 iconv_close(iconv_fd);
1002 iconv_fd = (iconv_t)-1;
1003 }
1004# endif
1005
1006 if (advance_fenc)
1007 {
1008 /*
1009 * Try the next entry in 'fileencodings'.
1010 */
1011 advance_fenc = FALSE;
1012
1013 if (eap != NULL && eap->force_enc != 0)
1014 {
1015 /* Conversion given with "++cc=" wasn't possible, read
1016 * without conversion. */
1017 notconverted = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001018 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001019 if (fenc_alloced)
1020 vim_free(fenc);
1021 fenc = (char_u *)"";
1022 fenc_alloced = FALSE;
1023 }
1024 else
1025 {
1026 if (fenc_alloced)
1027 vim_free(fenc);
1028 if (fenc_next != NULL)
1029 {
1030 fenc = next_fenc(&fenc_next);
1031 fenc_alloced = (fenc_next != NULL);
1032 }
1033 else
1034 {
1035 fenc = (char_u *)"";
1036 fenc_alloced = FALSE;
1037 }
1038 }
1039 if (tmpname != NULL)
1040 {
1041 mch_remove(tmpname); /* delete converted file */
1042 vim_free(tmpname);
1043 tmpname = NULL;
1044 }
1045 }
1046
1047 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001048 * Conversion may be required when the encoding of the file is different
1049 * from 'encoding' or 'encoding' is UTF-16, UCS-2 or UCS-4.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001050 */
1051 fio_flags = 0;
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001052 converted = need_conversion(fenc);
1053 if (converted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001054 {
1055
1056 /* "ucs-bom" means we need to check the first bytes of the file
1057 * for a BOM. */
1058 if (STRCMP(fenc, ENC_UCSBOM) == 0)
1059 fio_flags = FIO_UCSBOM;
1060
1061 /*
1062 * Check if UCS-2/4 or Latin1 to UTF-8 conversion needs to be
1063 * done. This is handled below after read(). Prepare the
1064 * fio_flags to avoid having to parse the string each time.
1065 * Also check for Unicode to Latin1 conversion, because iconv()
1066 * appears not to handle this correctly. This works just like
1067 * conversion to UTF-8 except how the resulting character is put in
1068 * the buffer.
1069 */
1070 else if (enc_utf8 || STRCMP(p_enc, "latin1") == 0)
1071 fio_flags = get_fio_flags(fenc);
1072
1073# ifdef WIN3264
1074 /*
1075 * Conversion from an MS-Windows codepage to UTF-8 or another codepage
1076 * is handled with MultiByteToWideChar().
1077 */
1078 if (fio_flags == 0)
1079 fio_flags = get_win_fio_flags(fenc);
1080# endif
1081
1082# ifdef MACOS_X
1083 /* Conversion from Apple MacRoman to latin1 or UTF-8 */
1084 if (fio_flags == 0)
1085 fio_flags = get_mac_fio_flags(fenc);
1086# endif
1087
1088# ifdef USE_ICONV
1089 /*
1090 * Try using iconv() if we can't convert internally.
1091 */
1092 if (fio_flags == 0
1093# ifdef FEAT_EVAL
1094 && !did_iconv
1095# endif
1096 )
1097 iconv_fd = (iconv_t)my_iconv_open(
1098 enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc);
1099# endif
1100
1101# ifdef FEAT_EVAL
1102 /*
1103 * Use the 'charconvert' expression when conversion is required
1104 * and we can't do it internally or with iconv().
1105 */
1106 if (fio_flags == 0 && !read_stdin && !read_buffer && *p_ccv != NUL
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02001107 && !read_fifo
Bram Moolenaar071d4272004-06-13 20:20:40 +00001108# ifdef USE_ICONV
1109 && iconv_fd == (iconv_t)-1
1110# endif
1111 )
1112 {
1113# ifdef USE_ICONV
1114 did_iconv = FALSE;
1115# endif
1116 /* Skip conversion when it's already done (retry for wrong
1117 * "fileformat"). */
1118 if (tmpname == NULL)
1119 {
1120 tmpname = readfile_charconvert(fname, fenc, &fd);
1121 if (tmpname == NULL)
1122 {
1123 /* Conversion failed. Try another one. */
1124 advance_fenc = TRUE;
1125 if (fd < 0)
1126 {
1127 /* Re-opening the original file failed! */
1128 EMSG(_("E202: Conversion made file unreadable!"));
1129 error = TRUE;
1130 goto failed;
1131 }
1132 goto retry;
1133 }
1134 }
1135 }
1136 else
1137# endif
1138 {
1139 if (fio_flags == 0
1140# ifdef USE_ICONV
1141 && iconv_fd == (iconv_t)-1
1142# endif
1143 )
1144 {
1145 /* Conversion wanted but we can't.
1146 * Try the next conversion in 'fileencodings' */
1147 advance_fenc = TRUE;
1148 goto retry;
1149 }
1150 }
1151 }
1152
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001153 /* Set "can_retry" when it's possible to rewind the file and try with
Bram Moolenaar071d4272004-06-13 20:20:40 +00001154 * another "fenc" value. It's FALSE when no other "fenc" to try, reading
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001155 * stdin or fixed at a specific encoding. */
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02001156 can_retry = (*fenc != NUL && !read_stdin && !read_fifo && !keep_dest_enc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001157#endif
1158
1159 if (!skip_read)
1160 {
1161 linerest = 0;
1162 filesize = 0;
1163 skip_count = lines_to_skip;
1164 read_count = lines_to_read;
1165#ifdef FEAT_MBYTE
1166 conv_restlen = 0;
1167#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001168#ifdef FEAT_PERSISTENT_UNDO
Bram Moolenaar59f931e2010-07-24 20:27:03 +02001169 read_undo_file = (newfile && (flags & READ_KEEP_UNDO) == 0
1170 && curbuf->b_ffname != NULL
1171 && curbuf->b_p_udf
1172 && !filtering
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02001173 && !read_fifo
Bram Moolenaar59f931e2010-07-24 20:27:03 +02001174 && !read_stdin
1175 && !read_buffer);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001176 if (read_undo_file)
1177 sha256_start(&sha_ctx);
1178#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001179#ifdef FEAT_CRYPT
1180 if (curbuf->b_cryptstate != NULL)
1181 {
1182 /* Need to free the state, but keep the key, don't want to ask for
1183 * it again. */
1184 crypt_free_state(curbuf->b_cryptstate);
1185 curbuf->b_cryptstate = NULL;
1186 }
1187#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001188 }
1189
1190 while (!error && !got_int)
1191 {
1192 /*
1193 * We allocate as much space for the file as we can get, plus
1194 * space for the old line plus room for one terminating NUL.
1195 * The amount is limited by the fact that read() only can read
1196 * upto max_unsigned characters (and other things).
1197 */
Bram Moolenaara2aa31a2014-02-23 22:52:40 +01001198#if VIM_SIZEOF_INT <= 2
Bram Moolenaar071d4272004-06-13 20:20:40 +00001199 if (linerest >= 0x7ff0)
1200 {
1201 ++split;
1202 *ptr = NL; /* split line by inserting a NL */
1203 size = 1;
1204 }
1205 else
1206#endif
1207 {
1208 if (!skip_read)
1209 {
Bram Moolenaara2aa31a2014-02-23 22:52:40 +01001210#if VIM_SIZEOF_INT > 2
Bram Moolenaar311d9822007-02-27 15:48:28 +00001211# if defined(SSIZE_MAX) && (SSIZE_MAX < 0x10000L)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001212 size = SSIZE_MAX; /* use max I/O size, 52K */
1213# else
1214 size = 0x10000L; /* use buffer >= 64K */
1215# endif
1216#else
1217 size = 0x7ff0L - linerest; /* limit buffer to 32K */
1218#endif
1219
Bram Moolenaarc1e37902006-04-18 21:55:01 +00001220 for ( ; size >= 10; size = (long)((long_u)size >> 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001221 {
1222 if ((new_buffer = lalloc((long_u)(size + linerest + 1),
1223 FALSE)) != NULL)
1224 break;
1225 }
1226 if (new_buffer == NULL)
1227 {
1228 do_outofmem_msg((long_u)(size * 2 + linerest + 1));
1229 error = TRUE;
1230 break;
1231 }
1232 if (linerest) /* copy characters from the previous buffer */
1233 mch_memmove(new_buffer, ptr - linerest, (size_t)linerest);
1234 vim_free(buffer);
1235 buffer = new_buffer;
1236 ptr = buffer + linerest;
1237 line_start = buffer;
1238
1239#ifdef FEAT_MBYTE
1240 /* May need room to translate into.
1241 * For iconv() we don't really know the required space, use a
1242 * factor ICONV_MULT.
1243 * latin1 to utf-8: 1 byte becomes up to 2 bytes
1244 * utf-16 to utf-8: 2 bytes become up to 3 bytes, 4 bytes
1245 * become up to 4 bytes, size must be multiple of 2
1246 * ucs-2 to utf-8: 2 bytes become up to 3 bytes, size must be
1247 * multiple of 2
1248 * ucs-4 to utf-8: 4 bytes become up to 6 bytes, size must be
1249 * multiple of 4 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001250 real_size = (int)size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001251# ifdef USE_ICONV
1252 if (iconv_fd != (iconv_t)-1)
1253 size = size / ICONV_MULT;
1254 else
1255# endif
1256 if (fio_flags & FIO_LATIN1)
1257 size = size / 2;
1258 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1259 size = (size * 2 / 3) & ~1;
1260 else if (fio_flags & FIO_UCS4)
1261 size = (size * 2 / 3) & ~3;
1262 else if (fio_flags == FIO_UCSBOM)
1263 size = size / ICONV_MULT; /* worst case */
1264# ifdef WIN3264
1265 else if (fio_flags & FIO_CODEPAGE)
1266 size = size / ICONV_MULT; /* also worst case */
1267# endif
1268# ifdef MACOS_X
1269 else if (fio_flags & FIO_MACROMAN)
1270 size = size / ICONV_MULT; /* also worst case */
1271# endif
1272#endif
1273
1274#ifdef FEAT_MBYTE
1275 if (conv_restlen > 0)
1276 {
1277 /* Insert unconverted bytes from previous line. */
1278 mch_memmove(ptr, conv_rest, conv_restlen);
1279 ptr += conv_restlen;
1280 size -= conv_restlen;
1281 }
1282#endif
1283
1284 if (read_buffer)
1285 {
1286 /*
1287 * Read bytes from curbuf. Used for converting text read
1288 * from stdin.
1289 */
1290 if (read_buf_lnum > from)
1291 size = 0;
1292 else
1293 {
1294 int n, ni;
1295 long tlen;
1296
1297 tlen = 0;
1298 for (;;)
1299 {
1300 p = ml_get(read_buf_lnum) + read_buf_col;
1301 n = (int)STRLEN(p);
1302 if ((int)tlen + n + 1 > size)
1303 {
1304 /* Filled up to "size", append partial line.
1305 * Change NL to NUL to reverse the effect done
1306 * below. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001307 n = (int)(size - tlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001308 for (ni = 0; ni < n; ++ni)
1309 {
1310 if (p[ni] == NL)
1311 ptr[tlen++] = NUL;
1312 else
1313 ptr[tlen++] = p[ni];
1314 }
1315 read_buf_col += n;
1316 break;
1317 }
1318 else
1319 {
1320 /* Append whole line and new-line. Change NL
1321 * to NUL to reverse the effect done below. */
1322 for (ni = 0; ni < n; ++ni)
1323 {
1324 if (p[ni] == NL)
1325 ptr[tlen++] = NUL;
1326 else
1327 ptr[tlen++] = p[ni];
1328 }
1329 ptr[tlen++] = NL;
1330 read_buf_col = 0;
1331 if (++read_buf_lnum > from)
1332 {
1333 /* When the last line didn't have an
1334 * end-of-line don't add it now either. */
1335 if (!curbuf->b_p_eol)
1336 --tlen;
1337 size = tlen;
1338 break;
1339 }
1340 }
1341 }
1342 }
1343 }
1344 else
1345 {
1346 /*
1347 * Read bytes from the file.
1348 */
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01001349 size = read_eintr(fd, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001350 }
1351
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001352#ifdef FEAT_CRYPT
1353 /*
1354 * At start of file: Check for magic number of encryption.
1355 */
1356 if (filesize == 0 && size > 0)
1357 cryptkey = check_for_cryptkey(cryptkey, ptr, &size,
1358 &filesize, newfile, sfname,
1359 &did_ask_for_key);
1360 /*
1361 * Decrypt the read bytes. This is done before checking for
1362 * EOF because the crypt layer may be buffering.
1363 */
1364 if (cryptkey != NULL && size > 0)
1365 {
1366 if (crypt_works_inplace(curbuf->b_cryptstate))
1367 {
1368 crypt_decode_inplace(curbuf->b_cryptstate, ptr, size);
1369 }
1370 else
1371 {
1372 char_u *newptr = NULL;
1373 int decrypted_size;
1374
1375 decrypted_size = crypt_decode_alloc(
1376 curbuf->b_cryptstate, ptr, size, &newptr);
1377
1378 /* If the crypt layer is buffering, not producing
1379 * anything yet, need to read more. */
1380 if (size > 0 && decrypted_size == 0)
1381 continue;
1382
1383 if (linerest == 0)
1384 {
1385 /* Simple case: reuse returned buffer (may be
1386 * NULL, checked later). */
1387 new_buffer = newptr;
1388 }
1389 else
1390 {
1391 long_u new_size;
1392
1393 /* Need new buffer to add bytes carried over. */
1394 new_size = (long_u)(decrypted_size + linerest + 1);
1395 new_buffer = lalloc(new_size, FALSE);
1396 if (new_buffer == NULL)
1397 {
1398 do_outofmem_msg(new_size);
1399 error = TRUE;
1400 break;
1401 }
1402
1403 mch_memmove(new_buffer, buffer, linerest);
1404 if (newptr != NULL)
1405 mch_memmove(new_buffer + linerest, newptr,
1406 decrypted_size);
1407 }
1408
1409 if (new_buffer != NULL)
1410 {
1411 vim_free(buffer);
1412 buffer = new_buffer;
1413 new_buffer = NULL;
1414 line_start = buffer;
1415 ptr = buffer + linerest;
1416 }
1417 size = decrypted_size;
1418 }
1419 }
1420#endif
1421
Bram Moolenaar071d4272004-06-13 20:20:40 +00001422 if (size <= 0)
1423 {
1424 if (size < 0) /* read error */
1425 error = TRUE;
1426#ifdef FEAT_MBYTE
1427 else if (conv_restlen > 0)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001428 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001429 /*
1430 * Reached end-of-file but some trailing bytes could
1431 * not be converted. Truncated file?
1432 */
1433
1434 /* When we did a conversion report an error. */
1435 if (fio_flags != 0
1436# ifdef USE_ICONV
1437 || iconv_fd != (iconv_t)-1
1438# endif
1439 )
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001440 {
Bram Moolenaare8d95302013-04-24 16:34:02 +02001441 if (can_retry)
1442 goto rewind_retry;
Bram Moolenaarf453d352008-06-04 17:37:34 +00001443 if (conv_error == 0)
1444 conv_error = curbuf->b_ml.ml_line_count
1445 - linecnt + 1;
1446 }
1447 /* Remember the first linenr with an illegal byte */
1448 else if (illegal_byte == 0)
1449 illegal_byte = curbuf->b_ml.ml_line_count
1450 - linecnt + 1;
1451 if (bad_char_behavior == BAD_DROP)
1452 {
1453 *(ptr - conv_restlen) = NUL;
1454 conv_restlen = 0;
1455 }
1456 else
1457 {
1458 /* Replace the trailing bytes with the replacement
1459 * character if we were converting; if we weren't,
1460 * leave the UTF8 checking code to do it, as it
1461 * works slightly differently. */
1462 if (bad_char_behavior != BAD_KEEP && (fio_flags != 0
1463# ifdef USE_ICONV
1464 || iconv_fd != (iconv_t)-1
1465# endif
1466 ))
1467 {
1468 while (conv_restlen > 0)
1469 {
1470 *(--ptr) = bad_char_behavior;
1471 --conv_restlen;
1472 }
1473 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001474 fio_flags = 0; /* don't convert this */
Bram Moolenaarb21e5842006-04-16 18:30:08 +00001475# ifdef USE_ICONV
1476 if (iconv_fd != (iconv_t)-1)
1477 {
1478 iconv_close(iconv_fd);
1479 iconv_fd = (iconv_t)-1;
1480 }
1481# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001482 }
1483 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001484#endif
1485 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001486 }
1487 skip_read = FALSE;
1488
1489#ifdef FEAT_MBYTE
1490 /*
1491 * At start of file (or after crypt magic number): Check for BOM.
1492 * Also check for a BOM for other Unicode encodings, but not after
1493 * converting with 'charconvert' or when a BOM has already been
1494 * found.
1495 */
1496 if ((filesize == 0
1497# ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001498 || (cryptkey != NULL
1499 && filesize == crypt_get_header_len(
1500 crypt_get_method_nr(curbuf)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001501# endif
1502 )
1503 && (fio_flags == FIO_UCSBOM
1504 || (!curbuf->b_p_bomb
1505 && tmpname == NULL
1506 && (*fenc == 'u' || (*fenc == NUL && enc_utf8)))))
1507 {
1508 char_u *ccname;
1509 int blen;
1510
1511 /* no BOM detection in a short file or in binary mode */
1512 if (size < 2 || curbuf->b_p_bin)
1513 ccname = NULL;
1514 else
1515 ccname = check_for_bom(ptr, size, &blen,
1516 fio_flags == FIO_UCSBOM ? FIO_ALL : get_fio_flags(fenc));
1517 if (ccname != NULL)
1518 {
1519 /* Remove BOM from the text */
1520 filesize += blen;
1521 size -= blen;
1522 mch_memmove(ptr, ptr + blen, (size_t)size);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00001523 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001524 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001525 curbuf->b_p_bomb = TRUE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001526 curbuf->b_start_bomb = TRUE;
1527 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001528 }
1529
1530 if (fio_flags == FIO_UCSBOM)
1531 {
1532 if (ccname == NULL)
1533 {
1534 /* No BOM detected: retry with next encoding. */
1535 advance_fenc = TRUE;
1536 }
1537 else
1538 {
1539 /* BOM detected: set "fenc" and jump back */
1540 if (fenc_alloced)
1541 vim_free(fenc);
1542 fenc = ccname;
1543 fenc_alloced = FALSE;
1544 }
1545 /* retry reading without getting new bytes or rewinding */
1546 skip_read = TRUE;
1547 goto retry;
1548 }
1549 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001550
1551 /* Include not converted bytes. */
1552 ptr -= conv_restlen;
1553 size += conv_restlen;
1554 conv_restlen = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001555#endif
1556 /*
1557 * Break here for a read error or end-of-file.
1558 */
1559 if (size <= 0)
1560 break;
1561
1562#ifdef FEAT_MBYTE
1563
Bram Moolenaar071d4272004-06-13 20:20:40 +00001564# ifdef USE_ICONV
1565 if (iconv_fd != (iconv_t)-1)
1566 {
1567 /*
1568 * Attempt conversion of the read bytes to 'encoding' using
1569 * iconv().
1570 */
1571 const char *fromp;
1572 char *top;
1573 size_t from_size;
1574 size_t to_size;
1575
1576 fromp = (char *)ptr;
1577 from_size = size;
1578 ptr += size;
1579 top = (char *)ptr;
1580 to_size = real_size - size;
1581
1582 /*
1583 * If there is conversion error or not enough room try using
Bram Moolenaar19a09a12005-03-04 23:39:37 +00001584 * another conversion. Except for when there is no
1585 * alternative (help files).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001586 */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001587 while ((iconv(iconv_fd, (void *)&fromp, &from_size,
1588 &top, &to_size)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001589 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
1590 || from_size > CONV_RESTLEN)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001591 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001592 if (can_retry)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001593 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001594 if (conv_error == 0)
1595 conv_error = readfile_linenr(linecnt,
1596 ptr, (char_u *)top);
Bram Moolenaar42eeac32005-06-29 22:40:58 +00001597
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001598 /* Deal with a bad byte and continue with the next. */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001599 ++fromp;
1600 --from_size;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001601 if (bad_char_behavior == BAD_KEEP)
1602 {
1603 *top++ = *(fromp - 1);
1604 --to_size;
1605 }
1606 else if (bad_char_behavior != BAD_DROP)
1607 {
1608 *top++ = bad_char_behavior;
1609 --to_size;
1610 }
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001611 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001612
1613 if (from_size > 0)
1614 {
1615 /* Some remaining characters, keep them for the next
1616 * round. */
1617 mch_memmove(conv_rest, (char_u *)fromp, from_size);
1618 conv_restlen = (int)from_size;
1619 }
1620
1621 /* move the linerest to before the converted characters */
1622 line_start = ptr - linerest;
1623 mch_memmove(line_start, buffer, (size_t)linerest);
1624 size = (long)((char_u *)top - ptr);
1625 }
1626# endif
1627
1628# ifdef WIN3264
1629 if (fio_flags & FIO_CODEPAGE)
1630 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001631 char_u *src, *dst;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001632 WCHAR ucs2buf[3];
1633 int ucs2len;
1634 int codepage = FIO_GET_CP(fio_flags);
1635 int bytelen;
1636 int found_bad;
1637 char replstr[2];
1638
Bram Moolenaar071d4272004-06-13 20:20:40 +00001639 /*
1640 * Conversion from an MS-Windows codepage or UTF-8 to UTF-8 or
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001641 * a codepage, using standard MS-Windows functions. This
1642 * requires two steps:
1643 * 1. convert from 'fileencoding' to ucs-2
1644 * 2. convert from ucs-2 to 'encoding'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001645 *
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001646 * Because there may be illegal bytes AND an incomplete byte
1647 * sequence at the end, we may have to do the conversion one
1648 * character at a time to get it right.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001649 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001650
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001651 /* Replacement string for WideCharToMultiByte(). */
1652 if (bad_char_behavior > 0)
1653 replstr[0] = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001654 else
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001655 replstr[0] = '?';
1656 replstr[1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001657
1658 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001659 * Move the bytes to the end of the buffer, so that we have
1660 * room to put the result at the start.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001661 */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001662 src = ptr + real_size - size;
1663 mch_memmove(src, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001664
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001665 /*
1666 * Do the conversion.
1667 */
1668 dst = ptr;
1669 size = size;
1670 while (size > 0)
1671 {
1672 found_bad = FALSE;
1673
1674# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
1675 if (codepage == CP_UTF8)
1676 {
1677 /* Handle CP_UTF8 input ourselves to be able to handle
1678 * trailing bytes properly.
1679 * Get one UTF-8 character from src. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001680 bytelen = (int)utf_ptr2len_len(src, size);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001681 if (bytelen > size)
1682 {
1683 /* Only got some bytes of a character. Normally
1684 * it's put in "conv_rest", but if it's too long
1685 * deal with it as if they were illegal bytes. */
1686 if (bytelen <= CONV_RESTLEN)
1687 break;
1688
1689 /* weird overlong byte sequence */
1690 bytelen = size;
1691 found_bad = TRUE;
1692 }
1693 else
1694 {
Bram Moolenaarc01140a2006-03-24 22:21:52 +00001695 int u8c = utf_ptr2char(src);
1696
Bram Moolenaar86e01082005-12-29 22:45:34 +00001697 if (u8c > 0xffff || (*src >= 0x80 && bytelen == 1))
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001698 found_bad = TRUE;
1699 ucs2buf[0] = u8c;
1700 ucs2len = 1;
1701 }
1702 }
1703 else
1704# endif
1705 {
1706 /* We don't know how long the byte sequence is, try
1707 * from one to three bytes. */
1708 for (bytelen = 1; bytelen <= size && bytelen <= 3;
1709 ++bytelen)
1710 {
1711 ucs2len = MultiByteToWideChar(codepage,
1712 MB_ERR_INVALID_CHARS,
1713 (LPCSTR)src, bytelen,
1714 ucs2buf, 3);
1715 if (ucs2len > 0)
1716 break;
1717 }
1718 if (ucs2len == 0)
1719 {
1720 /* If we have only one byte then it's probably an
1721 * incomplete byte sequence. Otherwise discard
1722 * one byte as a bad character. */
1723 if (size == 1)
1724 break;
1725 found_bad = TRUE;
1726 bytelen = 1;
1727 }
1728 }
1729
1730 if (!found_bad)
1731 {
1732 int i;
1733
1734 /* Convert "ucs2buf[ucs2len]" to 'enc' in "dst". */
1735 if (enc_utf8)
1736 {
1737 /* From UCS-2 to UTF-8. Cannot fail. */
1738 for (i = 0; i < ucs2len; ++i)
1739 dst += utf_char2bytes(ucs2buf[i], dst);
1740 }
1741 else
1742 {
1743 BOOL bad = FALSE;
1744 int dstlen;
1745
1746 /* From UCS-2 to "enc_codepage". If the
1747 * conversion uses the default character "?",
1748 * the data doesn't fit in this encoding. */
1749 dstlen = WideCharToMultiByte(enc_codepage, 0,
1750 (LPCWSTR)ucs2buf, ucs2len,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001751 (LPSTR)dst, (int)(src - dst),
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001752 replstr, &bad);
1753 if (bad)
1754 found_bad = TRUE;
1755 else
1756 dst += dstlen;
1757 }
1758 }
1759
1760 if (found_bad)
1761 {
1762 /* Deal with bytes we can't convert. */
1763 if (can_retry)
1764 goto rewind_retry;
1765 if (conv_error == 0)
1766 conv_error = readfile_linenr(linecnt, ptr, dst);
1767 if (bad_char_behavior != BAD_DROP)
1768 {
1769 if (bad_char_behavior == BAD_KEEP)
1770 {
1771 mch_memmove(dst, src, bytelen);
1772 dst += bytelen;
1773 }
1774 else
1775 *dst++ = bad_char_behavior;
1776 }
1777 }
1778
1779 src += bytelen;
1780 size -= bytelen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001781 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001782
1783 if (size > 0)
1784 {
1785 /* An incomplete byte sequence remaining. */
1786 mch_memmove(conv_rest, src, size);
1787 conv_restlen = size;
1788 }
1789
1790 /* The new size is equal to how much "dst" was advanced. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001791 size = (long)(dst - ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001792 }
1793 else
1794# endif
Bram Moolenaar56718732006-03-15 22:53:57 +00001795# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001796 if (fio_flags & FIO_MACROMAN)
1797 {
1798 /*
1799 * Conversion from Apple MacRoman char encoding to UTF-8 or
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001800 * latin1. This is in os_mac_conv.c.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001801 */
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001802 if (macroman2enc(ptr, &size, real_size) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001803 goto rewind_retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001804 }
1805 else
1806# endif
1807 if (fio_flags != 0)
1808 {
1809 int u8c;
1810 char_u *dest;
1811 char_u *tail = NULL;
1812
1813 /*
1814 * "enc_utf8" set: Convert Unicode or Latin1 to UTF-8.
1815 * "enc_utf8" not set: Convert Unicode to Latin1.
1816 * Go from end to start through the buffer, because the number
1817 * of bytes may increase.
1818 * "dest" points to after where the UTF-8 bytes go, "p" points
1819 * to after the next character to convert.
1820 */
1821 dest = ptr + real_size;
1822 if (fio_flags == FIO_LATIN1 || fio_flags == FIO_UTF8)
1823 {
1824 p = ptr + size;
1825 if (fio_flags == FIO_UTF8)
1826 {
1827 /* Check for a trailing incomplete UTF-8 sequence */
1828 tail = ptr + size - 1;
1829 while (tail > ptr && (*tail & 0xc0) == 0x80)
1830 --tail;
1831 if (tail + utf_byte2len(*tail) <= ptr + size)
1832 tail = NULL;
1833 else
1834 p = tail;
1835 }
1836 }
1837 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1838 {
1839 /* Check for a trailing byte */
1840 p = ptr + (size & ~1);
1841 if (size & 1)
1842 tail = p;
1843 if ((fio_flags & FIO_UTF16) && p > ptr)
1844 {
1845 /* Check for a trailing leading word */
1846 if (fio_flags & FIO_ENDIAN_L)
1847 {
1848 u8c = (*--p << 8);
1849 u8c += *--p;
1850 }
1851 else
1852 {
1853 u8c = *--p;
1854 u8c += (*--p << 8);
1855 }
1856 if (u8c >= 0xd800 && u8c <= 0xdbff)
1857 tail = p;
1858 else
1859 p += 2;
1860 }
1861 }
1862 else /* FIO_UCS4 */
1863 {
1864 /* Check for trailing 1, 2 or 3 bytes */
1865 p = ptr + (size & ~3);
1866 if (size & 3)
1867 tail = p;
1868 }
1869
1870 /* If there is a trailing incomplete sequence move it to
1871 * conv_rest[]. */
1872 if (tail != NULL)
1873 {
1874 conv_restlen = (int)((ptr + size) - tail);
1875 mch_memmove(conv_rest, (char_u *)tail, conv_restlen);
1876 size -= conv_restlen;
1877 }
1878
1879
1880 while (p > ptr)
1881 {
1882 if (fio_flags & FIO_LATIN1)
1883 u8c = *--p;
1884 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1885 {
1886 if (fio_flags & FIO_ENDIAN_L)
1887 {
1888 u8c = (*--p << 8);
1889 u8c += *--p;
1890 }
1891 else
1892 {
1893 u8c = *--p;
1894 u8c += (*--p << 8);
1895 }
1896 if ((fio_flags & FIO_UTF16)
1897 && u8c >= 0xdc00 && u8c <= 0xdfff)
1898 {
1899 int u16c;
1900
1901 if (p == ptr)
1902 {
1903 /* Missing leading word. */
1904 if (can_retry)
1905 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001906 if (conv_error == 0)
1907 conv_error = readfile_linenr(linecnt,
1908 ptr, p);
1909 if (bad_char_behavior == BAD_DROP)
1910 continue;
1911 if (bad_char_behavior != BAD_KEEP)
1912 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001913 }
1914
1915 /* found second word of double-word, get the first
1916 * word and compute the resulting character */
1917 if (fio_flags & FIO_ENDIAN_L)
1918 {
1919 u16c = (*--p << 8);
1920 u16c += *--p;
1921 }
1922 else
1923 {
1924 u16c = *--p;
1925 u16c += (*--p << 8);
1926 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001927 u8c = 0x10000 + ((u16c & 0x3ff) << 10)
1928 + (u8c & 0x3ff);
1929
Bram Moolenaar071d4272004-06-13 20:20:40 +00001930 /* Check if the word is indeed a leading word. */
1931 if (u16c < 0xd800 || u16c > 0xdbff)
1932 {
1933 if (can_retry)
1934 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001935 if (conv_error == 0)
1936 conv_error = readfile_linenr(linecnt,
1937 ptr, p);
1938 if (bad_char_behavior == BAD_DROP)
1939 continue;
1940 if (bad_char_behavior != BAD_KEEP)
1941 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001942 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001943 }
1944 }
1945 else if (fio_flags & FIO_UCS4)
1946 {
1947 if (fio_flags & FIO_ENDIAN_L)
1948 {
1949 u8c = (*--p << 24);
1950 u8c += (*--p << 16);
1951 u8c += (*--p << 8);
1952 u8c += *--p;
1953 }
1954 else /* big endian */
1955 {
1956 u8c = *--p;
1957 u8c += (*--p << 8);
1958 u8c += (*--p << 16);
1959 u8c += (*--p << 24);
1960 }
1961 }
1962 else /* UTF-8 */
1963 {
1964 if (*--p < 0x80)
1965 u8c = *p;
1966 else
1967 {
1968 len = utf_head_off(ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001969 p -= len;
1970 u8c = utf_ptr2char(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001971 if (len == 0)
1972 {
1973 /* Not a valid UTF-8 character, retry with
1974 * another fenc when possible, otherwise just
1975 * report the error. */
1976 if (can_retry)
1977 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001978 if (conv_error == 0)
1979 conv_error = readfile_linenr(linecnt,
1980 ptr, p);
1981 if (bad_char_behavior == BAD_DROP)
1982 continue;
1983 if (bad_char_behavior != BAD_KEEP)
1984 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001985 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001986 }
1987 }
1988 if (enc_utf8) /* produce UTF-8 */
1989 {
1990 dest -= utf_char2len(u8c);
1991 (void)utf_char2bytes(u8c, dest);
1992 }
1993 else /* produce Latin1 */
1994 {
1995 --dest;
1996 if (u8c >= 0x100)
1997 {
1998 /* character doesn't fit in latin1, retry with
1999 * another fenc when possible, otherwise just
2000 * report the error. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002001 if (can_retry)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002002 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002003 if (conv_error == 0)
2004 conv_error = readfile_linenr(linecnt, ptr, p);
2005 if (bad_char_behavior == BAD_DROP)
2006 ++dest;
2007 else if (bad_char_behavior == BAD_KEEP)
2008 *dest = u8c;
2009 else if (eap != NULL && eap->bad_char != 0)
2010 *dest = bad_char_behavior;
2011 else
2012 *dest = 0xBF;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002013 }
2014 else
2015 *dest = u8c;
2016 }
2017 }
2018
2019 /* move the linerest to before the converted characters */
2020 line_start = dest - linerest;
2021 mch_memmove(line_start, buffer, (size_t)linerest);
2022 size = (long)((ptr + real_size) - dest);
2023 ptr = dest;
2024 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002025 else if (enc_utf8 && !curbuf->b_p_bin)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002026 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002027 int incomplete_tail = FALSE;
2028
2029 /* Reading UTF-8: Check if the bytes are valid UTF-8. */
2030 for (p = ptr; ; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002031 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002032 int todo = (int)((ptr + size) - p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002033 int l;
2034
2035 if (todo <= 0)
2036 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002037 if (*p >= 0x80)
2038 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002039 /* A length of 1 means it's an illegal byte. Accept
2040 * an incomplete character at the end though, the next
2041 * read() will get the next bytes, we'll check it
2042 * then. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002043 l = utf_ptr2len_len(p, todo);
Bram Moolenaarf453d352008-06-04 17:37:34 +00002044 if (l > todo && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002045 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002046 /* Avoid retrying with a different encoding when
2047 * a truncated file is more likely, or attempting
2048 * to read the rest of an incomplete sequence when
2049 * we have already done so. */
2050 if (p > ptr || filesize > 0)
2051 incomplete_tail = TRUE;
2052 /* Incomplete byte sequence, move it to conv_rest[]
2053 * and try to read the rest of it, unless we've
2054 * already done so. */
2055 if (p > ptr)
2056 {
2057 conv_restlen = todo;
2058 mch_memmove(conv_rest, p, conv_restlen);
2059 size -= conv_restlen;
2060 break;
2061 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002062 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002063 if (l == 1 || l > todo)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002064 {
2065 /* Illegal byte. If we can try another encoding
Bram Moolenaarf453d352008-06-04 17:37:34 +00002066 * do that, unless at EOF where a truncated
2067 * file is more likely than a conversion error. */
2068 if (can_retry && !incomplete_tail)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002069 break;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002070# ifdef USE_ICONV
2071 /* When we did a conversion report an error. */
2072 if (iconv_fd != (iconv_t)-1 && conv_error == 0)
2073 conv_error = readfile_linenr(linecnt, ptr, p);
2074# endif
Bram Moolenaarf453d352008-06-04 17:37:34 +00002075 /* Remember the first linenr with an illegal byte */
2076 if (conv_error == 0 && illegal_byte == 0)
2077 illegal_byte = readfile_linenr(linecnt, ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002078
2079 /* Drop, keep or replace the bad byte. */
2080 if (bad_char_behavior == BAD_DROP)
2081 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002082 mch_memmove(p, p + 1, todo - 1);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002083 --p;
2084 --size;
2085 }
2086 else if (bad_char_behavior != BAD_KEEP)
2087 *p = bad_char_behavior;
2088 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002089 else
2090 p += l - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002091 }
2092 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002093 if (p < ptr + size && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002094 {
2095 /* Detected a UTF-8 error. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002096rewind_retry:
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002097 /* Retry reading with another conversion. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002098# if defined(FEAT_EVAL) && defined(USE_ICONV)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002099 if (*p_ccv != NUL && iconv_fd != (iconv_t)-1)
2100 /* iconv() failed, try 'charconvert' */
2101 did_iconv = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002102 else
2103# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002104 /* use next item from 'fileencodings' */
2105 advance_fenc = TRUE;
2106 file_rewind = TRUE;
2107 goto retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002108 }
2109 }
2110#endif
2111
2112 /* count the number of characters (after conversion!) */
2113 filesize += size;
2114
2115 /*
2116 * when reading the first part of a file: guess EOL type
2117 */
2118 if (fileformat == EOL_UNKNOWN)
2119 {
2120 /* First try finding a NL, for Dos and Unix */
2121 if (try_dos || try_unix)
2122 {
Bram Moolenaarc6b72172015-02-27 17:48:09 +01002123 /* Reset the carriage return counter. */
2124 if (try_mac)
2125 try_mac = 1;
2126
Bram Moolenaar071d4272004-06-13 20:20:40 +00002127 for (p = ptr; p < ptr + size; ++p)
2128 {
2129 if (*p == NL)
2130 {
2131 if (!try_unix
2132 || (try_dos && p > ptr && p[-1] == CAR))
2133 fileformat = EOL_DOS;
2134 else
2135 fileformat = EOL_UNIX;
2136 break;
2137 }
Bram Moolenaar05eb6122015-02-17 14:15:19 +01002138 else if (*p == CAR && try_mac)
2139 try_mac++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002140 }
2141
2142 /* Don't give in to EOL_UNIX if EOL_MAC is more likely */
2143 if (fileformat == EOL_UNIX && try_mac)
2144 {
2145 /* Need to reset the counters when retrying fenc. */
2146 try_mac = 1;
2147 try_unix = 1;
2148 for (; p >= ptr && *p != CAR; p--)
2149 ;
2150 if (p >= ptr)
2151 {
2152 for (p = ptr; p < ptr + size; ++p)
2153 {
2154 if (*p == NL)
2155 try_unix++;
2156 else if (*p == CAR)
2157 try_mac++;
2158 }
2159 if (try_mac > try_unix)
2160 fileformat = EOL_MAC;
2161 }
2162 }
Bram Moolenaar05eb6122015-02-17 14:15:19 +01002163 else if (fileformat == EOL_UNKNOWN && try_mac == 1)
2164 /* Looking for CR but found no end-of-line markers at
2165 * all: use the default format. */
2166 fileformat = default_fileformat();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002167 }
2168
2169 /* No NL found: may use Mac format */
2170 if (fileformat == EOL_UNKNOWN && try_mac)
2171 fileformat = EOL_MAC;
2172
2173 /* Still nothing found? Use first format in 'ffs' */
2174 if (fileformat == EOL_UNKNOWN)
2175 fileformat = default_fileformat();
2176
2177 /* if editing a new file: may set p_tx and p_ff */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002178 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002179 set_fileformat(fileformat, OPT_LOCAL);
2180 }
2181 }
2182
2183 /*
2184 * This loop is executed once for every character read.
2185 * Keep it fast!
2186 */
2187 if (fileformat == EOL_MAC)
2188 {
2189 --ptr;
2190 while (++ptr, --size >= 0)
2191 {
2192 /* catch most common case first */
2193 if ((c = *ptr) != NUL && c != CAR && c != NL)
2194 continue;
2195 if (c == NUL)
2196 *ptr = NL; /* NULs are replaced by newlines! */
2197 else if (c == NL)
2198 *ptr = CAR; /* NLs are replaced by CRs! */
2199 else
2200 {
2201 if (skip_count == 0)
2202 {
2203 *ptr = NUL; /* end of line */
2204 len = (colnr_T) (ptr - line_start + 1);
2205 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2206 {
2207 error = TRUE;
2208 break;
2209 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002210#ifdef FEAT_PERSISTENT_UNDO
2211 if (read_undo_file)
2212 sha256_update(&sha_ctx, line_start, len);
2213#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002214 ++lnum;
2215 if (--read_count == 0)
2216 {
2217 error = TRUE; /* break loop */
2218 line_start = ptr; /* nothing left to write */
2219 break;
2220 }
2221 }
2222 else
2223 --skip_count;
2224 line_start = ptr + 1;
2225 }
2226 }
2227 }
2228 else
2229 {
2230 --ptr;
2231 while (++ptr, --size >= 0)
2232 {
2233 if ((c = *ptr) != NUL && c != NL) /* catch most common case */
2234 continue;
2235 if (c == NUL)
2236 *ptr = NL; /* NULs are replaced by newlines! */
2237 else
2238 {
2239 if (skip_count == 0)
2240 {
2241 *ptr = NUL; /* end of line */
2242 len = (colnr_T)(ptr - line_start + 1);
2243 if (fileformat == EOL_DOS)
2244 {
2245 if (ptr[-1] == CAR) /* remove CR */
2246 {
2247 ptr[-1] = NUL;
2248 --len;
2249 }
2250 /*
2251 * Reading in Dos format, but no CR-LF found!
2252 * When 'fileformats' includes "unix", delete all
2253 * the lines read so far and start all over again.
2254 * Otherwise give an error message later.
2255 */
2256 else if (ff_error != EOL_DOS)
2257 {
2258 if ( try_unix
2259 && !read_stdin
2260 && (read_buffer
Bram Moolenaar8767f522016-07-01 17:17:39 +02002261 || vim_lseek(fd, (off_T)0L, SEEK_SET)
2262 == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002263 {
2264 fileformat = EOL_UNIX;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002265 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002266 set_fileformat(EOL_UNIX, OPT_LOCAL);
2267 file_rewind = TRUE;
2268 keep_fileformat = TRUE;
2269 goto retry;
2270 }
2271 ff_error = EOL_DOS;
2272 }
2273 }
2274 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2275 {
2276 error = TRUE;
2277 break;
2278 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002279#ifdef FEAT_PERSISTENT_UNDO
2280 if (read_undo_file)
2281 sha256_update(&sha_ctx, line_start, len);
2282#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002283 ++lnum;
2284 if (--read_count == 0)
2285 {
2286 error = TRUE; /* break loop */
2287 line_start = ptr; /* nothing left to write */
2288 break;
2289 }
2290 }
2291 else
2292 --skip_count;
2293 line_start = ptr + 1;
2294 }
2295 }
2296 }
2297 linerest = (long)(ptr - line_start);
2298 ui_breakcheck();
2299 }
2300
2301failed:
2302 /* not an error, max. number of lines reached */
2303 if (error && read_count == 0)
2304 error = FALSE;
2305
2306 /*
2307 * If we get EOF in the middle of a line, note the fact and
2308 * complete the line ourselves.
2309 * In Dos format ignore a trailing CTRL-Z, unless 'binary' set.
2310 */
2311 if (!error
2312 && !got_int
2313 && linerest != 0
2314 && !(!curbuf->b_p_bin
2315 && fileformat == EOL_DOS
2316 && *line_start == Ctrl_Z
2317 && ptr == line_start + 1))
2318 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002319 /* remember for when writing */
2320 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002321 curbuf->b_p_eol = FALSE;
2322 *ptr = NUL;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002323 len = (colnr_T)(ptr - line_start + 1);
2324 if (ml_append(lnum, line_start, len, newfile) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002325 error = TRUE;
2326 else
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002327 {
2328#ifdef FEAT_PERSISTENT_UNDO
2329 if (read_undo_file)
2330 sha256_update(&sha_ctx, line_start, len);
2331#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002332 read_no_eol_lnum = ++lnum;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002333 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002334 }
2335
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002336 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002337 save_file_ff(curbuf); /* remember the current file format */
2338
2339#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002340 if (curbuf->b_cryptstate != NULL)
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002341 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002342 crypt_free_state(curbuf->b_cryptstate);
2343 curbuf->b_cryptstate = NULL;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002344 }
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002345 if (cryptkey != NULL && cryptkey != curbuf->b_p_key)
2346 crypt_free_key(cryptkey);
2347 /* Don't set cryptkey to NULL, it's used below as a flag that
2348 * encryption was used. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002349#endif
2350
2351#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002352 /* If editing a new file: set 'fenc' for the current buffer.
2353 * Also for ":read ++edit file". */
2354 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002355 set_string_option_direct((char_u *)"fenc", -1, fenc,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00002356 OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002357 if (fenc_alloced)
2358 vim_free(fenc);
2359# ifdef USE_ICONV
2360 if (iconv_fd != (iconv_t)-1)
2361 {
2362 iconv_close(iconv_fd);
2363 iconv_fd = (iconv_t)-1;
2364 }
2365# endif
2366#endif
2367
2368 if (!read_buffer && !read_stdin)
2369 close(fd); /* errors are ignored */
Bram Moolenaarf05da212009-11-17 16:13:15 +00002370#ifdef HAVE_FD_CLOEXEC
2371 else
2372 {
2373 int fdflags = fcntl(fd, F_GETFD);
2374 if (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0)
Bram Moolenaarfbc4b4d2016-02-07 15:14:01 +01002375 (void)fcntl(fd, F_SETFD, fdflags | FD_CLOEXEC);
Bram Moolenaarf05da212009-11-17 16:13:15 +00002376 }
2377#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002378 vim_free(buffer);
2379
2380#ifdef HAVE_DUP
2381 if (read_stdin)
2382 {
2383 /* Use stderr for stdin, makes shell commands work. */
2384 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00002385 ignored = dup(2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002386 }
2387#endif
2388
2389#ifdef FEAT_MBYTE
2390 if (tmpname != NULL)
2391 {
2392 mch_remove(tmpname); /* delete converted file */
2393 vim_free(tmpname);
2394 }
2395#endif
2396 --no_wait_return; /* may wait for return now */
2397
2398 /*
2399 * In recovery mode everything but autocommands is skipped.
2400 */
2401 if (!recoverymode)
2402 {
2403 /* need to delete the last line, which comes from the empty buffer */
2404 if (newfile && wasempty && !(curbuf->b_ml.ml_flags & ML_EMPTY))
2405 {
2406#ifdef FEAT_NETBEANS_INTG
2407 netbeansFireChanges = 0;
2408#endif
2409 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
2410#ifdef FEAT_NETBEANS_INTG
2411 netbeansFireChanges = 1;
2412#endif
2413 --linecnt;
2414 }
2415 linecnt = curbuf->b_ml.ml_line_count - linecnt;
2416 if (filesize == 0)
2417 linecnt = 0;
2418 if (newfile || read_buffer)
Bram Moolenaar7263a772007-05-10 17:35:54 +00002419 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002420 redraw_curbuf_later(NOT_VALID);
Bram Moolenaar7263a772007-05-10 17:35:54 +00002421#ifdef FEAT_DIFF
2422 /* After reading the text into the buffer the diff info needs to
2423 * be updated. */
2424 diff_invalidate(curbuf);
2425#endif
2426#ifdef FEAT_FOLDING
2427 /* All folds in the window are invalid now. Mark them for update
2428 * before triggering autocommands. */
2429 foldUpdateAll(curwin);
2430#endif
2431 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002432 else if (linecnt) /* appended at least one line */
2433 appended_lines_mark(from, linecnt);
2434
Bram Moolenaar071d4272004-06-13 20:20:40 +00002435#ifndef ALWAYS_USE_GUI
2436 /*
2437 * If we were reading from the same terminal as where messages go,
2438 * the screen will have been messed up.
2439 * Switch on raw mode now and clear the screen.
2440 */
2441 if (read_stdin)
2442 {
2443 settmode(TMODE_RAW); /* set to raw mode */
2444 starttermcap();
2445 screenclear();
2446 }
2447#endif
2448
2449 if (got_int)
2450 {
2451 if (!(flags & READ_DUMMY))
2452 {
2453 filemess(curbuf, sfname, (char_u *)_(e_interr), 0);
2454 if (newfile)
2455 curbuf->b_p_ro = TRUE; /* must use "w!" now */
2456 }
2457 msg_scroll = msg_save;
2458#ifdef FEAT_VIMINFO
2459 check_marks_read();
2460#endif
2461 return OK; /* an interrupt isn't really an error */
2462 }
2463
2464 if (!filtering && !(flags & READ_DUMMY))
2465 {
2466 msg_add_fname(curbuf, sfname); /* fname in IObuff with quotes */
2467 c = FALSE;
2468
2469#ifdef UNIX
2470# ifdef S_ISFIFO
2471 if (S_ISFIFO(perm)) /* fifo or socket */
2472 {
2473 STRCAT(IObuff, _("[fifo/socket]"));
2474 c = TRUE;
2475 }
2476# else
2477# ifdef S_IFIFO
2478 if ((perm & S_IFMT) == S_IFIFO) /* fifo */
2479 {
2480 STRCAT(IObuff, _("[fifo]"));
2481 c = TRUE;
2482 }
2483# endif
2484# ifdef S_IFSOCK
2485 if ((perm & S_IFMT) == S_IFSOCK) /* or socket */
2486 {
2487 STRCAT(IObuff, _("[socket]"));
2488 c = TRUE;
2489 }
2490# endif
2491# endif
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002492# ifdef OPEN_CHR_FILES
2493 if (S_ISCHR(perm)) /* or character special */
2494 {
2495 STRCAT(IObuff, _("[character special]"));
2496 c = TRUE;
2497 }
2498# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002499#endif
2500 if (curbuf->b_p_ro)
2501 {
2502 STRCAT(IObuff, shortmess(SHM_RO) ? _("[RO]") : _("[readonly]"));
2503 c = TRUE;
2504 }
2505 if (read_no_eol_lnum)
2506 {
2507 msg_add_eol();
2508 c = TRUE;
2509 }
2510 if (ff_error == EOL_DOS)
2511 {
2512 STRCAT(IObuff, _("[CR missing]"));
2513 c = TRUE;
2514 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002515 if (split)
2516 {
2517 STRCAT(IObuff, _("[long lines split]"));
2518 c = TRUE;
2519 }
2520#ifdef FEAT_MBYTE
2521 if (notconverted)
2522 {
2523 STRCAT(IObuff, _("[NOT converted]"));
2524 c = TRUE;
2525 }
2526 else if (converted)
2527 {
2528 STRCAT(IObuff, _("[converted]"));
2529 c = TRUE;
2530 }
2531#endif
2532#ifdef FEAT_CRYPT
2533 if (cryptkey != NULL)
2534 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002535 crypt_append_msg(curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002536 c = TRUE;
2537 }
2538#endif
2539#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002540 if (conv_error != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002541 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002542 sprintf((char *)IObuff + STRLEN(IObuff),
2543 _("[CONVERSION ERROR in line %ld]"), (long)conv_error);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002544 c = TRUE;
2545 }
2546 else if (illegal_byte > 0)
2547 {
2548 sprintf((char *)IObuff + STRLEN(IObuff),
2549 _("[ILLEGAL BYTE in line %ld]"), (long)illegal_byte);
2550 c = TRUE;
2551 }
2552 else
2553#endif
2554 if (error)
2555 {
2556 STRCAT(IObuff, _("[READ ERRORS]"));
2557 c = TRUE;
2558 }
2559 if (msg_add_fileformat(fileformat))
2560 c = TRUE;
2561#ifdef FEAT_CRYPT
2562 if (cryptkey != NULL)
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002563 msg_add_lines(c, (long)linecnt, filesize
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002564 - crypt_get_header_len(crypt_get_method_nr(curbuf)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002565 else
2566#endif
2567 msg_add_lines(c, (long)linecnt, filesize);
2568
2569 vim_free(keep_msg);
2570 keep_msg = NULL;
2571 msg_scrolled_ign = TRUE;
2572#ifdef ALWAYS_USE_GUI
2573 /* Don't show the message when reading stdin, it would end up in a
2574 * message box (which might be shown when exiting!) */
2575 if (read_stdin || read_buffer)
2576 p = msg_may_trunc(FALSE, IObuff);
2577 else
2578#endif
2579 p = msg_trunc_attr(IObuff, FALSE, 0);
2580 if (read_stdin || read_buffer || restart_edit != 0
Bram Moolenaar1c7715d2005-10-03 22:02:18 +00002581 || (msg_scrolled != 0 && !need_wait_return))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002582 /* Need to repeat the message after redrawing when:
2583 * - When reading from stdin (the screen will be cleared next).
2584 * - When restart_edit is set (otherwise there will be a delay
2585 * before redrawing).
2586 * - When the screen was scrolled but there is no wait-return
2587 * prompt. */
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002588 set_keep_msg(p, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002589 msg_scrolled_ign = FALSE;
2590 }
2591
2592 /* with errors writing the file requires ":w!" */
2593 if (newfile && (error
2594#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002595 || conv_error != 0
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002596 || (illegal_byte > 0 && bad_char_behavior != BAD_KEEP)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002597#endif
2598 ))
2599 curbuf->b_p_ro = TRUE;
2600
2601 u_clearline(); /* cannot use "U" command after adding lines */
2602
2603 /*
2604 * In Ex mode: cursor at last new line.
2605 * Otherwise: cursor at first new line.
2606 */
2607 if (exmode_active)
2608 curwin->w_cursor.lnum = from + linecnt;
2609 else
2610 curwin->w_cursor.lnum = from + 1;
2611 check_cursor_lnum();
2612 beginline(BL_WHITE | BL_FIX); /* on first non-blank */
2613
2614 /*
2615 * Set '[ and '] marks to the newly read lines.
2616 */
2617 curbuf->b_op_start.lnum = from + 1;
2618 curbuf->b_op_start.col = 0;
2619 curbuf->b_op_end.lnum = from + linecnt;
2620 curbuf->b_op_end.col = 0;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002621
2622#ifdef WIN32
2623 /*
2624 * Work around a weird problem: When a file has two links (only
2625 * possible on NTFS) and we write through one link, then stat() it
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00002626 * through the other link, the timestamp information may be wrong.
Bram Moolenaar03f48552006-02-28 23:52:23 +00002627 * It's correct again after reading the file, thus reset the timestamp
2628 * here.
2629 */
2630 if (newfile && !read_stdin && !read_buffer
2631 && mch_stat((char *)fname, &st) >= 0)
2632 {
2633 buf_store_time(curbuf, &st, fname);
2634 curbuf->b_mtime_read = curbuf->b_mtime;
2635 }
2636#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002637 }
2638 msg_scroll = msg_save;
2639
2640#ifdef FEAT_VIMINFO
2641 /*
2642 * Get the marks before executing autocommands, so they can be used there.
2643 */
2644 check_marks_read();
2645#endif
2646
Bram Moolenaar071d4272004-06-13 20:20:40 +00002647 /*
Bram Moolenaar34d72d42015-07-17 14:18:08 +02002648 * We remember if the last line of the read didn't have
2649 * an eol even when 'binary' is off, to support turning 'fixeol' off,
2650 * or writing the read again with 'binary' on. The latter is required
2651 * for ":autocmd FileReadPost *.gz set bin|'[,']!gunzip" to work.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002652 */
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002653 curbuf->b_no_eol_lnum = read_no_eol_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002654
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02002655 /* When reloading a buffer put the cursor at the first line that is
2656 * different. */
2657 if (flags & READ_KEEP_UNDO)
2658 u_find_first_changed();
2659
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002660#ifdef FEAT_PERSISTENT_UNDO
2661 /*
2662 * When opening a new file locate undo info and read it.
2663 */
2664 if (read_undo_file)
2665 {
2666 char_u hash[UNDO_HASH_SIZE];
2667
2668 sha256_finish(&sha_ctx, hash);
Bram Moolenaar6ed8ed82010-05-30 20:40:11 +02002669 u_read_undo(NULL, hash, fname);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002670 }
2671#endif
2672
Bram Moolenaardf177f62005-02-22 08:39:57 +00002673#ifdef FEAT_AUTOCMD
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02002674 if (!read_stdin && !read_fifo && (!read_buffer || sfname != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002675 {
2676 int m = msg_scroll;
2677 int n = msg_scrolled;
2678
2679 /* Save the fileformat now, otherwise the buffer will be considered
2680 * modified if the format/encoding was automatically detected. */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002681 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002682 save_file_ff(curbuf);
2683
2684 /*
2685 * The output from the autocommands should not overwrite anything and
2686 * should not be overwritten: Set msg_scroll, restore its value if no
2687 * output was done.
2688 */
2689 msg_scroll = TRUE;
2690 if (filtering)
2691 apply_autocmds_exarg(EVENT_FILTERREADPOST, NULL, sfname,
2692 FALSE, curbuf, eap);
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02002693 else if (newfile || (read_buffer && sfname != NULL))
Bram Moolenaarc3691332016-04-20 12:49:49 +02002694 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002695 apply_autocmds_exarg(EVENT_BUFREADPOST, NULL, sfname,
2696 FALSE, curbuf, eap);
Bram Moolenaarc3691332016-04-20 12:49:49 +02002697 if (!au_did_filetype && *curbuf->b_p_ft != NUL)
2698 /*
2699 * EVENT_FILETYPE was not triggered but the buffer already has a
2700 * filetype. Trigger EVENT_FILETYPE using the existing filetype.
2701 */
2702 apply_autocmds(EVENT_FILETYPE, curbuf->b_p_ft, curbuf->b_fname,
2703 TRUE, curbuf);
2704 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002705 else
2706 apply_autocmds_exarg(EVENT_FILEREADPOST, sfname, sfname,
2707 FALSE, NULL, eap);
2708 if (msg_scrolled == n)
2709 msg_scroll = m;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002710# ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002711 if (aborting()) /* autocmds may abort script processing */
2712 return FAIL;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002713# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002714 }
2715#endif
2716
2717 if (recoverymode && error)
2718 return FAIL;
2719 return OK;
2720}
2721
Bram Moolenaarf04507d2016-08-20 15:05:39 +02002722#if defined(OPEN_CHR_FILES) || defined(PROTO)
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002723/*
2724 * Returns TRUE if the file name argument is of the form "/dev/fd/\d\+",
2725 * which is the name of files used for process substitution output by
2726 * some shells on some operating systems, e.g., bash on SunOS.
2727 * Do not accept "/dev/fd/[012]", opening these may hang Vim.
2728 */
Bram Moolenaarf04507d2016-08-20 15:05:39 +02002729 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002730is_dev_fd_file(char_u *fname)
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002731{
2732 return (STRNCMP(fname, "/dev/fd/", 8) == 0
2733 && VIM_ISDIGIT(fname[8])
2734 && *skipdigits(fname + 9) == NUL
2735 && (fname[9] != NUL
2736 || (fname[8] != '0' && fname[8] != '1' && fname[8] != '2')));
2737}
2738#endif
2739
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002740#ifdef FEAT_MBYTE
2741
2742/*
2743 * From the current line count and characters read after that, estimate the
2744 * line number where we are now.
2745 * Used for error messages that include a line number.
2746 */
2747 static linenr_T
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002748readfile_linenr(
2749 linenr_T linecnt, /* line count before reading more bytes */
2750 char_u *p, /* start of more bytes read */
2751 char_u *endp) /* end of more bytes read */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002752{
2753 char_u *s;
2754 linenr_T lnum;
2755
2756 lnum = curbuf->b_ml.ml_line_count - linecnt + 1;
2757 for (s = p; s < endp; ++s)
2758 if (*s == '\n')
2759 ++lnum;
2760 return lnum;
2761}
2762#endif
2763
Bram Moolenaar071d4272004-06-13 20:20:40 +00002764/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00002765 * Fill "*eap" to force the 'fileencoding', 'fileformat' and 'binary to be
2766 * equal to the buffer "buf". Used for calling readfile().
Bram Moolenaar071d4272004-06-13 20:20:40 +00002767 * Returns OK or FAIL.
2768 */
2769 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002770prep_exarg(exarg_T *eap, buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002771{
2772 eap->cmd = alloc((unsigned)(STRLEN(buf->b_p_ff)
2773#ifdef FEAT_MBYTE
2774 + STRLEN(buf->b_p_fenc)
2775#endif
2776 + 15));
2777 if (eap->cmd == NULL)
2778 return FAIL;
2779
2780#ifdef FEAT_MBYTE
2781 sprintf((char *)eap->cmd, "e ++ff=%s ++enc=%s", buf->b_p_ff, buf->b_p_fenc);
2782 eap->force_enc = 14 + (int)STRLEN(buf->b_p_ff);
Bram Moolenaar195d6352005-12-19 22:08:24 +00002783 eap->bad_char = buf->b_bad_char;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002784#else
2785 sprintf((char *)eap->cmd, "e ++ff=%s", buf->b_p_ff);
2786#endif
2787 eap->force_ff = 7;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002788
2789 eap->force_bin = buf->b_p_bin ? FORCE_BIN : FORCE_NOBIN;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002790 eap->read_edit = FALSE;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002791 eap->forceit = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002792 return OK;
2793}
2794
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002795/*
2796 * Set default or forced 'fileformat' and 'binary'.
2797 */
2798 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002799set_file_options(int set_options, exarg_T *eap)
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002800{
2801 /* set default 'fileformat' */
2802 if (set_options)
2803 {
2804 if (eap != NULL && eap->force_ff != 0)
2805 set_fileformat(get_fileformat_force(curbuf, eap), OPT_LOCAL);
2806 else if (*p_ffs != NUL)
2807 set_fileformat(default_fileformat(), OPT_LOCAL);
2808 }
2809
2810 /* set or reset 'binary' */
2811 if (eap != NULL && eap->force_bin != 0)
2812 {
2813 int oldval = curbuf->b_p_bin;
2814
2815 curbuf->b_p_bin = (eap->force_bin == FORCE_BIN);
2816 set_options_bin(oldval, curbuf->b_p_bin, OPT_LOCAL);
2817 }
2818}
2819
2820#if defined(FEAT_MBYTE) || defined(PROTO)
2821/*
2822 * Set forced 'fileencoding'.
2823 */
2824 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002825set_forced_fenc(exarg_T *eap)
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002826{
2827 if (eap->force_enc != 0)
2828 {
2829 char_u *fenc = enc_canonize(eap->cmd + eap->force_enc);
2830
2831 if (fenc != NULL)
2832 set_string_option_direct((char_u *)"fenc", -1,
2833 fenc, OPT_FREE|OPT_LOCAL, 0);
2834 vim_free(fenc);
2835 }
2836}
2837
Bram Moolenaar071d4272004-06-13 20:20:40 +00002838/*
2839 * Find next fileencoding to use from 'fileencodings'.
2840 * "pp" points to fenc_next. It's advanced to the next item.
2841 * When there are no more items, an empty string is returned and *pp is set to
2842 * NULL.
2843 * When *pp is not set to NULL, the result is in allocated memory.
2844 */
2845 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002846next_fenc(char_u **pp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002847{
2848 char_u *p;
2849 char_u *r;
2850
2851 if (**pp == NUL)
2852 {
2853 *pp = NULL;
2854 return (char_u *)"";
2855 }
2856 p = vim_strchr(*pp, ',');
2857 if (p == NULL)
2858 {
2859 r = enc_canonize(*pp);
2860 *pp += STRLEN(*pp);
2861 }
2862 else
2863 {
2864 r = vim_strnsave(*pp, (int)(p - *pp));
2865 *pp = p + 1;
2866 if (r != NULL)
2867 {
2868 p = enc_canonize(r);
2869 vim_free(r);
2870 r = p;
2871 }
2872 }
2873 if (r == NULL) /* out of memory */
2874 {
2875 r = (char_u *)"";
2876 *pp = NULL;
2877 }
2878 return r;
2879}
2880
2881# ifdef FEAT_EVAL
2882/*
2883 * Convert a file with the 'charconvert' expression.
2884 * This closes the file which is to be read, converts it and opens the
2885 * resulting file for reading.
2886 * Returns name of the resulting converted file (the caller should delete it
2887 * after reading it).
2888 * Returns NULL if the conversion failed ("*fdp" is not set) .
2889 */
2890 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002891readfile_charconvert(
2892 char_u *fname, /* name of input file */
2893 char_u *fenc, /* converted from */
2894 int *fdp) /* in/out: file descriptor of file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002895{
2896 char_u *tmpname;
2897 char_u *errmsg = NULL;
2898
Bram Moolenaare5c421c2015-03-31 13:33:08 +02002899 tmpname = vim_tempname('r', FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002900 if (tmpname == NULL)
2901 errmsg = (char_u *)_("Can't find temp file for conversion");
2902 else
2903 {
2904 close(*fdp); /* close the input file, ignore errors */
2905 *fdp = -1;
2906 if (eval_charconvert(fenc, enc_utf8 ? (char_u *)"utf-8" : p_enc,
2907 fname, tmpname) == FAIL)
2908 errmsg = (char_u *)_("Conversion with 'charconvert' failed");
2909 if (errmsg == NULL && (*fdp = mch_open((char *)tmpname,
2910 O_RDONLY | O_EXTRA, 0)) < 0)
2911 errmsg = (char_u *)_("can't read output of 'charconvert'");
2912 }
2913
2914 if (errmsg != NULL)
2915 {
2916 /* Don't use emsg(), it breaks mappings, the retry with
2917 * another type of conversion might still work. */
2918 MSG(errmsg);
2919 if (tmpname != NULL)
2920 {
2921 mch_remove(tmpname); /* delete converted file */
2922 vim_free(tmpname);
2923 tmpname = NULL;
2924 }
2925 }
2926
2927 /* If the input file is closed, open it (caller should check for error). */
2928 if (*fdp < 0)
2929 *fdp = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
2930
2931 return tmpname;
2932}
2933# endif
2934
2935#endif
2936
2937#ifdef FEAT_VIMINFO
2938/*
2939 * Read marks for the current buffer from the viminfo file, when we support
2940 * buffer marks and the buffer has a name.
2941 */
2942 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002943check_marks_read(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002944{
2945 if (!curbuf->b_marks_read && get_viminfo_parameter('\'') > 0
2946 && curbuf->b_ffname != NULL)
Bram Moolenaard812df62008-11-09 12:46:09 +00002947 read_viminfo(NULL, VIF_WANT_MARKS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002948
2949 /* Always set b_marks_read; needed when 'viminfo' is changed to include
2950 * the ' parameter after opening a buffer. */
2951 curbuf->b_marks_read = TRUE;
2952}
2953#endif
2954
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002955#if defined(FEAT_CRYPT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002956/*
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002957 * Check for magic number used for encryption. Applies to the current buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002958 * If found, the magic number is removed from ptr[*sizep] and *sizep and
2959 * *filesizep are updated.
2960 * Return the (new) encryption key, NULL for no encryption.
2961 */
2962 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002963check_for_cryptkey(
2964 char_u *cryptkey, /* previous encryption key or NULL */
2965 char_u *ptr, /* pointer to read bytes */
2966 long *sizep, /* length of read bytes */
Bram Moolenaar8767f522016-07-01 17:17:39 +02002967 off_T *filesizep, /* nr of bytes used from file */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002968 int newfile, /* editing a new buffer */
2969 char_u *fname, /* file name to display */
2970 int *did_ask) /* flag: whether already asked for key */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002971{
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002972 int method = crypt_method_nr_from_magic((char *)ptr, *sizep);
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02002973 int b_p_ro = curbuf->b_p_ro;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002974
2975 if (method >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002976 {
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02002977 /* Mark the buffer as read-only until the decryption has taken place.
2978 * Avoids accidentally overwriting the file with garbage. */
2979 curbuf->b_p_ro = TRUE;
2980
Bram Moolenaar2be79502014-08-13 21:58:28 +02002981 /* Set the cryptmethod local to the buffer. */
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002982 crypt_set_cm_option(curbuf, method);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002983 if (cryptkey == NULL && !*did_ask)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002984 {
2985 if (*curbuf->b_p_key)
2986 cryptkey = curbuf->b_p_key;
2987 else
2988 {
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002989 /* When newfile is TRUE, store the typed key in the 'key'
2990 * option and don't free it. bf needs hash of the key saved.
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002991 * Don't ask for the key again when first time Enter was hit.
2992 * Happens when retrying to detect encoding. */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002993 smsg((char_u *)_(need_key_msg), fname);
2994 msg_scroll = TRUE;
Bram Moolenaar3a0c9082014-11-12 15:15:42 +01002995 crypt_check_method(method);
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002996 cryptkey = crypt_get_key(newfile, FALSE);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002997 *did_ask = TRUE;
2998
Bram Moolenaar071d4272004-06-13 20:20:40 +00002999 /* check if empty key entered */
3000 if (cryptkey != NULL && *cryptkey == NUL)
3001 {
3002 if (cryptkey != curbuf->b_p_key)
3003 vim_free(cryptkey);
3004 cryptkey = NULL;
3005 }
3006 }
3007 }
3008
3009 if (cryptkey != NULL)
3010 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003011 int header_len;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003012
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003013 curbuf->b_cryptstate = crypt_create_from_header(
3014 method, cryptkey, ptr);
3015 crypt_set_cm_option(curbuf, method);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003016
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003017 /* Remove cryptmethod specific header from the text. */
3018 header_len = crypt_get_header_len(method);
Bram Moolenaar680e0152016-09-25 20:54:11 +02003019 if (*sizep <= header_len)
3020 /* invalid header, buffer can't be encrypted */
3021 return NULL;
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003022 *filesizep += header_len;
3023 *sizep -= header_len;
3024 mch_memmove(ptr, ptr + header_len, (size_t)*sizep);
3025
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02003026 /* Restore the read-only flag. */
3027 curbuf->b_p_ro = b_p_ro;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003028 }
3029 }
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003030 /* When starting to edit a new file which does not have encryption, clear
3031 * the 'key' option, except when starting up (called with -x argument) */
Bram Moolenaarfa0ff9a2010-07-25 16:05:19 +02003032 else if (newfile && *curbuf->b_p_key != NUL && !starting)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003033 set_option_value((char_u *)"key", 0L, (char_u *)"", OPT_LOCAL);
3034
3035 return cryptkey;
3036}
Bram Moolenaar80794b12010-06-13 05:20:42 +02003037#endif /* FEAT_CRYPT */
3038
Bram Moolenaar071d4272004-06-13 20:20:40 +00003039#ifdef UNIX
3040 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003041set_file_time(
3042 char_u *fname,
3043 time_t atime, /* access time */
3044 time_t mtime) /* modification time */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003045{
3046# if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
3047 struct utimbuf buf;
3048
3049 buf.actime = atime;
3050 buf.modtime = mtime;
3051 (void)utime((char *)fname, &buf);
3052# else
3053# if defined(HAVE_UTIMES)
3054 struct timeval tvp[2];
3055
3056 tvp[0].tv_sec = atime;
3057 tvp[0].tv_usec = 0;
3058 tvp[1].tv_sec = mtime;
3059 tvp[1].tv_usec = 0;
3060# ifdef NeXT
3061 (void)utimes((char *)fname, tvp);
3062# else
3063 (void)utimes((char *)fname, (const struct timeval *)&tvp);
3064# endif
3065# endif
3066# endif
3067}
3068#endif /* UNIX */
3069
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003070#if defined(VMS) && !defined(MIN)
3071/* Older DECC compiler for VAX doesn't define MIN() */
3072# define MIN(a, b) ((a) < (b) ? (a) : (b))
3073#endif
3074
Bram Moolenaar071d4272004-06-13 20:20:40 +00003075/*
Bram Moolenaar5386a122007-06-28 20:02:32 +00003076 * Return TRUE if a file appears to be read-only from the file permissions.
3077 */
3078 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003079check_file_readonly(
3080 char_u *fname, /* full path to file */
3081 int perm) /* known permissions on file */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003082{
3083#ifndef USE_MCH_ACCESS
3084 int fd = 0;
3085#endif
3086
3087 return (
3088#ifdef USE_MCH_ACCESS
3089# ifdef UNIX
3090 (perm & 0222) == 0 ||
3091# endif
3092 mch_access((char *)fname, W_OK)
3093#else
3094 (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0
3095 ? TRUE : (close(fd), FALSE)
3096#endif
3097 );
3098}
3099
3100
3101/*
Bram Moolenaar292ad192005-12-11 21:29:51 +00003102 * buf_write() - write to file "fname" lines "start" through "end"
Bram Moolenaar071d4272004-06-13 20:20:40 +00003103 *
3104 * We do our own buffering here because fwrite() is so slow.
3105 *
Bram Moolenaar292ad192005-12-11 21:29:51 +00003106 * If "forceit" is true, we don't care for errors when attempting backups.
3107 * In case of an error everything possible is done to restore the original
Bram Moolenaare37d50a2008-08-06 17:06:04 +00003108 * file. But when "forceit" is TRUE, we risk losing it.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003109 *
3110 * When "reset_changed" is TRUE and "append" == FALSE and "start" == 1 and
3111 * "end" == curbuf->b_ml.ml_line_count, reset curbuf->b_changed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003112 *
3113 * This function must NOT use NameBuff (because it's called by autowrite()).
3114 *
3115 * return FAIL for failure, OK otherwise
3116 */
3117 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003118buf_write(
3119 buf_T *buf,
3120 char_u *fname,
3121 char_u *sfname,
3122 linenr_T start,
3123 linenr_T end,
3124 exarg_T *eap, /* for forced 'ff' and 'fenc', can be
Bram Moolenaar071d4272004-06-13 20:20:40 +00003125 NULL! */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003126 int append, /* append to the file */
3127 int forceit,
3128 int reset_changed,
3129 int filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003130{
3131 int fd;
3132 char_u *backup = NULL;
3133 int backup_copy = FALSE; /* copy the original file? */
3134 int dobackup;
3135 char_u *ffname;
3136 char_u *wfname = NULL; /* name of file to write to */
3137 char_u *s;
3138 char_u *ptr;
3139 char_u c;
3140 int len;
3141 linenr_T lnum;
3142 long nchars;
3143 char_u *errmsg = NULL;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003144 int errmsg_allocated = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003145 char_u *errnum = NULL;
3146 char_u *buffer;
3147 char_u smallbuf[SMBUFSIZE];
3148 char_u *backup_ext;
3149 int bufsize;
3150 long perm; /* file permissions */
3151 int retval = OK;
3152 int newfile = FALSE; /* TRUE if file doesn't exist yet */
3153 int msg_save = msg_scroll;
3154 int overwriting; /* TRUE if writing over original */
3155 int no_eol = FALSE; /* no end-of-line written */
3156 int device = FALSE; /* writing to a device */
Bram Moolenaar8767f522016-07-01 17:17:39 +02003157 stat_T st_old;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003158 int prev_got_int = got_int;
3159 int file_readonly = FALSE; /* overwritten file is read-only */
3160 static char *err_readonly = "is read-only (cannot override: \"W\" in 'cpoptions')";
Bram Moolenaara06ecab2016-07-16 14:47:36 +02003161#if defined(UNIX) /*XXX fix me sometime? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003162 int made_writable = FALSE; /* 'w' bit has been set */
3163#endif
3164 /* writing everything */
3165 int whole = (start == 1 && end == buf->b_ml.ml_line_count);
3166#ifdef FEAT_AUTOCMD
3167 linenr_T old_line_count = buf->b_ml.ml_line_count;
3168#endif
3169 int attr;
3170 int fileformat;
3171 int write_bin;
3172 struct bw_info write_info; /* info for buf_write_bytes() */
3173#ifdef FEAT_MBYTE
3174 int converted = FALSE;
3175 int notconverted = FALSE;
3176 char_u *fenc; /* effective 'fileencoding' */
3177 char_u *fenc_tofree = NULL; /* allocated "fenc" */
3178#endif
3179#ifdef HAS_BW_FLAGS
3180 int wb_flags = 0;
3181#endif
3182#ifdef HAVE_ACL
3183 vim_acl_T acl = NULL; /* ACL copied from original file to
3184 backup or new file */
3185#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003186#ifdef FEAT_PERSISTENT_UNDO
3187 int write_undo_file = FALSE;
3188 context_sha256_T sha_ctx;
3189#endif
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003190 unsigned int bkc = get_bkc_value(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003191
3192 if (fname == NULL || *fname == NUL) /* safety check */
3193 return FAIL;
Bram Moolenaar70d60e92009-12-31 13:53:33 +00003194 if (buf->b_ml.ml_mfp == NULL)
3195 {
3196 /* This can happen during startup when there is a stray "w" in the
3197 * vimrc file. */
3198 EMSG(_(e_emptybuf));
3199 return FAIL;
3200 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003201
3202 /*
3203 * Disallow writing from .exrc and .vimrc in current directory for
3204 * security reasons.
3205 */
3206 if (check_secure())
3207 return FAIL;
3208
3209 /* Avoid a crash for a long name. */
3210 if (STRLEN(fname) >= MAXPATHL)
3211 {
3212 EMSG(_(e_longname));
3213 return FAIL;
3214 }
3215
3216#ifdef FEAT_MBYTE
3217 /* must init bw_conv_buf and bw_iconv_fd before jumping to "fail" */
3218 write_info.bw_conv_buf = NULL;
3219 write_info.bw_conv_error = FALSE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003220 write_info.bw_conv_error_lnum = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003221 write_info.bw_restlen = 0;
3222# ifdef USE_ICONV
3223 write_info.bw_iconv_fd = (iconv_t)-1;
3224# endif
3225#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003226#ifdef FEAT_CRYPT
3227 write_info.bw_buffer = buf;
3228#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003229
Bram Moolenaardf177f62005-02-22 08:39:57 +00003230 /* After writing a file changedtick changes but we don't want to display
3231 * the line. */
3232 ex_no_reprint = TRUE;
3233
Bram Moolenaar071d4272004-06-13 20:20:40 +00003234 /*
3235 * If there is no file name yet, use the one for the written file.
3236 * BF_NOTEDITED is set to reflect this (in case the write fails).
3237 * Don't do this when the write is for a filter command.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003238 * Don't do this when appending.
3239 * Only do this when 'cpoptions' contains the 'F' flag.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003240 */
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003241 if (buf->b_ffname == NULL
3242 && reset_changed
Bram Moolenaar071d4272004-06-13 20:20:40 +00003243 && whole
3244 && buf == curbuf
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00003245#ifdef FEAT_QUICKFIX
3246 && !bt_nofile(buf)
3247#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003248 && !filtering
Bram Moolenaar292ad192005-12-11 21:29:51 +00003249 && (!append || vim_strchr(p_cpo, CPO_FNAMEAPP) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003250 && vim_strchr(p_cpo, CPO_FNAMEW) != NULL)
3251 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003252 if (set_rw_fname(fname, sfname) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003253 return FAIL;
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003254 buf = curbuf; /* just in case autocmds made "buf" invalid */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003255 }
3256
3257 if (sfname == NULL)
3258 sfname = fname;
3259 /*
3260 * For Unix: Use the short file name whenever possible.
3261 * Avoids problems with networks and when directory names are changed.
3262 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
3263 * another directory, which we don't detect
3264 */
3265 ffname = fname; /* remember full fname */
3266#ifdef UNIX
3267 fname = sfname;
3268#endif
3269
3270 if (buf->b_ffname != NULL && fnamecmp(ffname, buf->b_ffname) == 0)
3271 overwriting = TRUE;
3272 else
3273 overwriting = FALSE;
3274
3275 if (exiting)
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003276 settmode(TMODE_COOK); /* when exiting allow typeahead now */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003277
3278 ++no_wait_return; /* don't wait for return yet */
3279
3280 /*
3281 * Set '[ and '] marks to the lines to be written.
3282 */
3283 buf->b_op_start.lnum = start;
3284 buf->b_op_start.col = 0;
3285 buf->b_op_end.lnum = end;
3286 buf->b_op_end.col = 0;
3287
3288#ifdef FEAT_AUTOCMD
3289 {
3290 aco_save_T aco;
3291 int buf_ffname = FALSE;
3292 int buf_sfname = FALSE;
3293 int buf_fname_f = FALSE;
3294 int buf_fname_s = FALSE;
3295 int did_cmd = FALSE;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003296 int nofile_err = FALSE;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003297 int empty_memline = (buf->b_ml.ml_mfp == NULL);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003298 bufref_T bufref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003299
3300 /*
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003301 * Apply PRE autocommands.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003302 * Set curbuf to the buffer to be written.
3303 * Careful: The autocommands may call buf_write() recursively!
3304 */
3305 if (ffname == buf->b_ffname)
3306 buf_ffname = TRUE;
3307 if (sfname == buf->b_sfname)
3308 buf_sfname = TRUE;
3309 if (fname == buf->b_ffname)
3310 buf_fname_f = TRUE;
3311 if (fname == buf->b_sfname)
3312 buf_fname_s = TRUE;
3313
3314 /* set curwin/curbuf to buf and save a few things */
3315 aucmd_prepbuf(&aco, buf);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003316 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003317
3318 if (append)
3319 {
3320 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD,
3321 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003322 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003323#ifdef FEAT_QUICKFIX
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00003324 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003325 nofile_err = TRUE;
3326 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003327#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003328 apply_autocmds_exarg(EVENT_FILEAPPENDPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003329 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003330 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003331 }
3332 else if (filtering)
3333 {
3334 apply_autocmds_exarg(EVENT_FILTERWRITEPRE,
3335 NULL, sfname, FALSE, curbuf, eap);
3336 }
3337 else if (reset_changed && whole)
3338 {
Bram Moolenaar39fc42e2011-09-02 11:56:20 +02003339 int was_changed = curbufIsChanged();
3340
3341 did_cmd = apply_autocmds_exarg(EVENT_BUFWRITECMD,
3342 sfname, sfname, FALSE, curbuf, eap);
3343 if (did_cmd)
3344 {
3345 if (was_changed && !curbufIsChanged())
3346 {
3347 /* Written everything correctly and BufWriteCmd has reset
3348 * 'modified': Correct the undo information so that an
3349 * undo now sets 'modified'. */
3350 u_unchanged(curbuf);
3351 u_update_save_nr(curbuf);
3352 }
3353 }
3354 else
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003355 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003356#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003357 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003358 nofile_err = TRUE;
3359 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003360#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003361 apply_autocmds_exarg(EVENT_BUFWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003362 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003363 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003364 }
3365 else
3366 {
3367 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD,
3368 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003369 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003370#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003371 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003372 nofile_err = TRUE;
3373 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003374#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003375 apply_autocmds_exarg(EVENT_FILEWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003376 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003377 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003378 }
3379
3380 /* restore curwin/curbuf and a few other things */
3381 aucmd_restbuf(&aco);
3382
3383 /*
3384 * In three situations we return here and don't write the file:
3385 * 1. the autocommands deleted or unloaded the buffer.
3386 * 2. The autocommands abort script processing.
3387 * 3. If one of the "Cmd" autocommands was executed.
3388 */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003389 if (!bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003390 buf = NULL;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003391 if (buf == NULL || (buf->b_ml.ml_mfp == NULL && !empty_memline)
Bram Moolenaar1e015462005-09-25 22:16:38 +00003392 || did_cmd || nofile_err
3393#ifdef FEAT_EVAL
3394 || aborting()
3395#endif
3396 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003397 {
3398 --no_wait_return;
3399 msg_scroll = msg_save;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003400 if (nofile_err)
3401 EMSG(_("E676: No matching autocommands for acwrite buffer"));
3402
Bram Moolenaar1e015462005-09-25 22:16:38 +00003403 if (nofile_err
3404#ifdef FEAT_EVAL
3405 || aborting()
3406#endif
3407 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003408 /* An aborting error, interrupt or exception in the
3409 * autocommands. */
3410 return FAIL;
3411 if (did_cmd)
3412 {
3413 if (buf == NULL)
3414 /* The buffer was deleted. We assume it was written
3415 * (can't retry anyway). */
3416 return OK;
3417 if (overwriting)
3418 {
3419 /* Assume the buffer was written, update the timestamp. */
3420 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00003421 if (append)
3422 buf->b_flags &= ~BF_NEW;
3423 else
3424 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003425 }
Bram Moolenaar292ad192005-12-11 21:29:51 +00003426 if (reset_changed && buf->b_changed && !append
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003427 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003428 /* Buffer still changed, the autocommands didn't work
3429 * properly. */
3430 return FAIL;
3431 return OK;
3432 }
3433#ifdef FEAT_EVAL
3434 if (!aborting())
3435#endif
3436 EMSG(_("E203: Autocommands deleted or unloaded buffer to be written"));
3437 return FAIL;
3438 }
3439
3440 /*
3441 * The autocommands may have changed the number of lines in the file.
3442 * When writing the whole file, adjust the end.
3443 * When writing part of the file, assume that the autocommands only
3444 * changed the number of lines that are to be written (tricky!).
3445 */
3446 if (buf->b_ml.ml_line_count != old_line_count)
3447 {
3448 if (whole) /* write all */
3449 end = buf->b_ml.ml_line_count;
3450 else if (buf->b_ml.ml_line_count > old_line_count) /* more lines */
3451 end += buf->b_ml.ml_line_count - old_line_count;
3452 else /* less lines */
3453 {
3454 end -= old_line_count - buf->b_ml.ml_line_count;
3455 if (end < start)
3456 {
3457 --no_wait_return;
3458 msg_scroll = msg_save;
3459 EMSG(_("E204: Autocommand changed number of lines in unexpected way"));
3460 return FAIL;
3461 }
3462 }
3463 }
3464
3465 /*
3466 * The autocommands may have changed the name of the buffer, which may
3467 * be kept in fname, ffname and sfname.
3468 */
3469 if (buf_ffname)
3470 ffname = buf->b_ffname;
3471 if (buf_sfname)
3472 sfname = buf->b_sfname;
3473 if (buf_fname_f)
3474 fname = buf->b_ffname;
3475 if (buf_fname_s)
3476 fname = buf->b_sfname;
3477 }
3478#endif
3479
3480#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003481 if (netbeans_active() && isNetbeansBuffer(buf))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003482 {
3483 if (whole)
3484 {
3485 /*
3486 * b_changed can be 0 after an undo, but we still need to write
3487 * the buffer to NetBeans.
3488 */
3489 if (buf->b_changed || isNetbeansModified(buf))
3490 {
Bram Moolenaar009b2592004-10-24 19:18:58 +00003491 --no_wait_return; /* may wait for return now */
3492 msg_scroll = msg_save;
3493 netbeans_save_buffer(buf); /* no error checking... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003494 return retval;
3495 }
3496 else
3497 {
3498 errnum = (char_u *)"E656: ";
Bram Moolenaared0e7452008-06-27 19:17:34 +00003499 errmsg = (char_u *)_("NetBeans disallows writes of unmodified buffers");
Bram Moolenaar071d4272004-06-13 20:20:40 +00003500 buffer = NULL;
3501 goto fail;
3502 }
3503 }
3504 else
3505 {
3506 errnum = (char_u *)"E657: ";
3507 errmsg = (char_u *)_("Partial writes disallowed for NetBeans buffers");
3508 buffer = NULL;
3509 goto fail;
3510 }
3511 }
3512#endif
3513
3514 if (shortmess(SHM_OVER) && !exiting)
3515 msg_scroll = FALSE; /* overwrite previous file message */
3516 else
3517 msg_scroll = TRUE; /* don't overwrite previous file message */
3518 if (!filtering)
3519 filemess(buf,
3520#ifndef UNIX
3521 sfname,
3522#else
3523 fname,
3524#endif
3525 (char_u *)"", 0); /* show that we are busy */
3526 msg_scroll = FALSE; /* always overwrite the file message now */
3527
3528 buffer = alloc(BUFSIZE);
3529 if (buffer == NULL) /* can't allocate big buffer, use small
3530 * one (to be able to write when out of
3531 * memory) */
3532 {
3533 buffer = smallbuf;
3534 bufsize = SMBUFSIZE;
3535 }
3536 else
3537 bufsize = BUFSIZE;
3538
3539 /*
3540 * Get information about original file (if there is one).
3541 */
Bram Moolenaar53076832015-12-31 19:53:21 +01003542#if defined(UNIX)
Bram Moolenaar6f192452007-11-08 19:49:02 +00003543 st_old.st_dev = 0;
3544 st_old.st_ino = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003545 perm = -1;
3546 if (mch_stat((char *)fname, &st_old) < 0)
3547 newfile = TRUE;
3548 else
3549 {
3550 perm = st_old.st_mode;
3551 if (!S_ISREG(st_old.st_mode)) /* not a file */
3552 {
3553 if (S_ISDIR(st_old.st_mode))
3554 {
3555 errnum = (char_u *)"E502: ";
3556 errmsg = (char_u *)_("is a directory");
3557 goto fail;
3558 }
3559 if (mch_nodetype(fname) != NODE_WRITABLE)
3560 {
3561 errnum = (char_u *)"E503: ";
3562 errmsg = (char_u *)_("is not a file or writable device");
3563 goto fail;
3564 }
3565 /* It's a device of some kind (or a fifo) which we can write to
3566 * but for which we can't make a backup. */
3567 device = TRUE;
3568 newfile = TRUE;
3569 perm = -1;
3570 }
3571 }
3572#else /* !UNIX */
3573 /*
3574 * Check for a writable device name.
3575 */
3576 c = mch_nodetype(fname);
3577 if (c == NODE_OTHER)
3578 {
3579 errnum = (char_u *)"E503: ";
3580 errmsg = (char_u *)_("is not a file or writable device");
3581 goto fail;
3582 }
3583 if (c == NODE_WRITABLE)
3584 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003585# if defined(MSWIN)
Bram Moolenaar043545e2006-10-10 16:44:07 +00003586 /* MS-Windows allows opening a device, but we will probably get stuck
3587 * trying to write to it. */
3588 if (!p_odev)
3589 {
3590 errnum = (char_u *)"E796: ";
3591 errmsg = (char_u *)_("writing to device disabled with 'opendevice' option");
3592 goto fail;
3593 }
3594# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003595 device = TRUE;
3596 newfile = TRUE;
3597 perm = -1;
3598 }
3599 else
3600 {
3601 perm = mch_getperm(fname);
3602 if (perm < 0)
3603 newfile = TRUE;
3604 else if (mch_isdir(fname))
3605 {
3606 errnum = (char_u *)"E502: ";
3607 errmsg = (char_u *)_("is a directory");
3608 goto fail;
3609 }
3610 if (overwriting)
3611 (void)mch_stat((char *)fname, &st_old);
3612 }
3613#endif /* !UNIX */
3614
3615 if (!device && !newfile)
3616 {
3617 /*
3618 * Check if the file is really writable (when renaming the file to
3619 * make a backup we won't discover it later).
3620 */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003621 file_readonly = check_file_readonly(fname, (int)perm);
3622
Bram Moolenaar071d4272004-06-13 20:20:40 +00003623 if (!forceit && file_readonly)
3624 {
3625 if (vim_strchr(p_cpo, CPO_FWRITE) != NULL)
3626 {
3627 errnum = (char_u *)"E504: ";
3628 errmsg = (char_u *)_(err_readonly);
3629 }
3630 else
3631 {
3632 errnum = (char_u *)"E505: ";
3633 errmsg = (char_u *)_("is read-only (add ! to override)");
3634 }
3635 goto fail;
3636 }
3637
3638 /*
3639 * Check if the timestamp hasn't changed since reading the file.
3640 */
3641 if (overwriting)
3642 {
3643 retval = check_mtime(buf, &st_old);
3644 if (retval == FAIL)
3645 goto fail;
3646 }
3647 }
3648
3649#ifdef HAVE_ACL
3650 /*
3651 * For systems that support ACL: get the ACL from the original file.
3652 */
3653 if (!newfile)
3654 acl = mch_get_acl(fname);
3655#endif
3656
3657 /*
3658 * If 'backupskip' is not empty, don't make a backup for some files.
3659 */
3660 dobackup = (p_wb || p_bk || *p_pm != NUL);
3661#ifdef FEAT_WILDIGN
3662 if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname))
3663 dobackup = FALSE;
3664#endif
3665
3666 /*
3667 * Save the value of got_int and reset it. We don't want a previous
3668 * interruption cancel writing, only hitting CTRL-C while writing should
3669 * abort it.
3670 */
3671 prev_got_int = got_int;
3672 got_int = FALSE;
3673
3674 /* Mark the buffer as 'being saved' to prevent changed buffer warnings */
3675 buf->b_saving = TRUE;
3676
3677 /*
3678 * If we are not appending or filtering, the file exists, and the
3679 * 'writebackup', 'backup' or 'patchmode' option is set, need a backup.
3680 * When 'patchmode' is set also make a backup when appending.
3681 *
3682 * Do not make any backup, if 'writebackup' and 'backup' are both switched
3683 * off. This helps when editing large files on almost-full disks.
3684 */
3685 if (!(append && *p_pm == NUL) && !filtering && perm >= 0 && dobackup)
3686 {
3687#if defined(UNIX) || defined(WIN32)
Bram Moolenaar8767f522016-07-01 17:17:39 +02003688 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003689#endif
3690
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003691 if ((bkc & BKC_YES) || append) /* "yes" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003692 backup_copy = TRUE;
3693#if defined(UNIX) || defined(WIN32)
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003694 else if ((bkc & BKC_AUTO)) /* "auto" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003695 {
3696 int i;
3697
3698# ifdef UNIX
3699 /*
3700 * Don't rename the file when:
3701 * - it's a hard link
3702 * - it's a symbolic link
3703 * - we don't have write permission in the directory
3704 * - we can't set the owner/group of the new file
3705 */
3706 if (st_old.st_nlink > 1
3707 || mch_lstat((char *)fname, &st) < 0
3708 || st.st_dev != st_old.st_dev
Bram Moolenaara5792f52005-11-23 21:25:05 +00003709 || st.st_ino != st_old.st_ino
3710# ifndef HAVE_FCHOWN
3711 || st.st_uid != st_old.st_uid
3712 || st.st_gid != st_old.st_gid
3713# endif
3714 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003715 backup_copy = TRUE;
3716 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003717# else
3718# ifdef WIN32
3719 /* On NTFS file systems hard links are possible. */
3720 if (mch_is_linked(fname))
3721 backup_copy = TRUE;
3722 else
3723# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003724# endif
3725 {
3726 /*
3727 * Check if we can create a file and set the owner/group to
3728 * the ones from the original file.
3729 * First find a file name that doesn't exist yet (use some
3730 * arbitrary numbers).
3731 */
3732 STRCPY(IObuff, fname);
3733 for (i = 4913; ; i += 123)
3734 {
3735 sprintf((char *)gettail(IObuff), "%d", i);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003736 if (mch_lstat((char *)IObuff, &st) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003737 break;
3738 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00003739 fd = mch_open((char *)IObuff,
3740 O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003741 if (fd < 0) /* can't write in directory */
3742 backup_copy = TRUE;
3743 else
3744 {
3745# ifdef UNIX
Bram Moolenaara5792f52005-11-23 21:25:05 +00003746# ifdef HAVE_FCHOWN
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00003747 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003748# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003749 if (mch_stat((char *)IObuff, &st) < 0
3750 || st.st_uid != st_old.st_uid
3751 || st.st_gid != st_old.st_gid
Bram Moolenaar78a15312009-05-15 19:33:18 +00003752 || (long)st.st_mode != perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003753 backup_copy = TRUE;
3754# endif
Bram Moolenaar98358622005-11-28 22:58:23 +00003755 /* Close the file before removing it, on MS-Windows we
3756 * can't delete an open file. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003757 close(fd);
Bram Moolenaar98358622005-11-28 22:58:23 +00003758 mch_remove(IObuff);
Bram Moolenaar3479c5d2010-08-08 18:46:06 +02003759# ifdef MSWIN
3760 /* MS-Windows may trigger a virus scanner to open the
3761 * file, we can't delete it then. Keep trying for half a
3762 * second. */
3763 {
3764 int try;
3765
3766 for (try = 0; try < 10; ++try)
3767 {
3768 if (mch_lstat((char *)IObuff, &st) < 0)
3769 break;
3770 ui_delay(50L, TRUE); /* wait 50 msec */
3771 mch_remove(IObuff);
3772 }
3773 }
3774# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003775 }
3776 }
3777 }
3778
Bram Moolenaar071d4272004-06-13 20:20:40 +00003779 /*
3780 * Break symlinks and/or hardlinks if we've been asked to.
3781 */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003782 if ((bkc & BKC_BREAKSYMLINK) || (bkc & BKC_BREAKHARDLINK))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003783 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003784# ifdef UNIX
Bram Moolenaar071d4272004-06-13 20:20:40 +00003785 int lstat_res;
3786
3787 lstat_res = mch_lstat((char *)fname, &st);
3788
3789 /* Symlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003790 if ((bkc & BKC_BREAKSYMLINK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003791 && lstat_res == 0
3792 && st.st_ino != st_old.st_ino)
3793 backup_copy = FALSE;
3794
3795 /* Hardlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003796 if ((bkc & BKC_BREAKHARDLINK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003797 && st_old.st_nlink > 1
3798 && (lstat_res != 0 || st.st_ino == st_old.st_ino))
3799 backup_copy = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003800# else
3801# if defined(WIN32)
3802 /* Symlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003803 if ((bkc & BKC_BREAKSYMLINK) && mch_is_symbolic_link(fname))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003804 backup_copy = FALSE;
3805
3806 /* Hardlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003807 if ((bkc & BKC_BREAKHARDLINK) && mch_is_hard_link(fname))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003808 backup_copy = FALSE;
3809# endif
3810# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003811 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003812
3813#endif
3814
3815 /* make sure we have a valid backup extension to use */
3816 if (*p_bex == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003817 backup_ext = (char_u *)".bak";
Bram Moolenaar071d4272004-06-13 20:20:40 +00003818 else
3819 backup_ext = p_bex;
3820
3821 if (backup_copy
3822 && (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) >= 0)
3823 {
3824 int bfd;
3825 char_u *copybuf, *wp;
3826 int some_error = FALSE;
Bram Moolenaar8767f522016-07-01 17:17:39 +02003827 stat_T st_new;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003828 char_u *dirp;
3829 char_u *rootname;
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003830#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003831 int did_set_shortname;
3832#endif
3833
3834 copybuf = alloc(BUFSIZE + 1);
3835 if (copybuf == NULL)
3836 {
3837 some_error = TRUE; /* out of memory */
3838 goto nobackup;
3839 }
3840
3841 /*
3842 * Try to make the backup in each directory in the 'bdir' option.
3843 *
3844 * Unix semantics has it, that we may have a writable file,
3845 * that cannot be recreated with a simple open(..., O_CREAT, ) e.g:
3846 * - the directory is not writable,
3847 * - the file may be a symbolic link,
3848 * - the file may belong to another user/group, etc.
3849 *
3850 * For these reasons, the existing writable file must be truncated
3851 * and reused. Creation of a backup COPY will be attempted.
3852 */
3853 dirp = p_bdir;
3854 while (*dirp)
3855 {
3856#ifdef UNIX
3857 st_new.st_ino = 0;
3858 st_new.st_dev = 0;
3859 st_new.st_gid = 0;
3860#endif
3861
3862 /*
3863 * Isolate one directory name, using an entry in 'bdir'.
3864 */
3865 (void)copy_option_part(&dirp, copybuf, BUFSIZE, ",");
3866 rootname = get_file_in_dir(fname, copybuf);
3867 if (rootname == NULL)
3868 {
3869 some_error = TRUE; /* out of memory */
3870 goto nobackup;
3871 }
3872
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003873#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003874 did_set_shortname = FALSE;
3875#endif
3876
3877 /*
3878 * May try twice if 'shortname' not set.
3879 */
3880 for (;;)
3881 {
3882 /*
3883 * Make backup file name.
3884 */
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003885 backup = buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003886 rootname, backup_ext, FALSE);
3887 if (backup == NULL)
3888 {
3889 vim_free(rootname);
3890 some_error = TRUE; /* out of memory */
3891 goto nobackup;
3892 }
3893
3894 /*
3895 * Check if backup file already exists.
3896 */
3897 if (mch_stat((char *)backup, &st_new) >= 0)
3898 {
3899#ifdef UNIX
3900 /*
3901 * Check if backup file is same as original file.
3902 * May happen when modname() gave the same file back.
3903 * E.g. silly link, or file name-length reached.
3904 * If we don't check here, we either ruin the file
3905 * when copying or erase it after writing. jw.
3906 */
3907 if (st_new.st_dev == st_old.st_dev
3908 && st_new.st_ino == st_old.st_ino)
3909 {
3910 vim_free(backup);
3911 backup = NULL; /* no backup file to delete */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003912 /*
3913 * may try again with 'shortname' set
3914 */
3915 if (!(buf->b_shortname || buf->b_p_sn))
3916 {
3917 buf->b_shortname = TRUE;
3918 did_set_shortname = TRUE;
3919 continue;
3920 }
3921 /* setting shortname didn't help */
3922 if (did_set_shortname)
3923 buf->b_shortname = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003924 break;
3925 }
3926#endif
3927
3928 /*
3929 * If we are not going to keep the backup file, don't
3930 * delete an existing one, try to use another name.
3931 * Change one character, just before the extension.
3932 */
3933 if (!p_bk)
3934 {
3935 wp = backup + STRLEN(backup) - 1
3936 - STRLEN(backup_ext);
3937 if (wp < backup) /* empty file name ??? */
3938 wp = backup;
3939 *wp = 'z';
3940 while (*wp > 'a'
3941 && mch_stat((char *)backup, &st_new) >= 0)
3942 --*wp;
3943 /* They all exist??? Must be something wrong. */
3944 if (*wp == 'a')
3945 {
3946 vim_free(backup);
3947 backup = NULL;
3948 }
3949 }
3950 }
3951 break;
3952 }
3953 vim_free(rootname);
3954
3955 /*
3956 * Try to create the backup file
3957 */
3958 if (backup != NULL)
3959 {
3960 /* remove old backup, if present */
3961 mch_remove(backup);
3962 /* Open with O_EXCL to avoid the file being created while
3963 * we were sleeping (symlink hacker attack?) */
3964 bfd = mch_open((char *)backup,
Bram Moolenaara5792f52005-11-23 21:25:05 +00003965 O_WRONLY|O_CREAT|O_EXTRA|O_EXCL|O_NOFOLLOW,
3966 perm & 0777);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003967 if (bfd < 0)
3968 {
3969 vim_free(backup);
3970 backup = NULL;
3971 }
3972 else
3973 {
3974 /* set file protection same as original file, but
3975 * strip s-bit */
3976 (void)mch_setperm(backup, perm & 0777);
3977
3978#ifdef UNIX
3979 /*
3980 * Try to set the group of the backup same as the
3981 * original file. If this fails, set the protection
3982 * bits for the group same as the protection bits for
3983 * others.
3984 */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003985 if (st_new.st_gid != st_old.st_gid
Bram Moolenaar071d4272004-06-13 20:20:40 +00003986# ifdef HAVE_FCHOWN /* sequent-ptx lacks fchown() */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003987 && fchown(bfd, (uid_t)-1, st_old.st_gid) != 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00003988# endif
3989 )
3990 mch_setperm(backup,
3991 (perm & 0707) | ((perm & 07) << 3));
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02003992# if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00003993 mch_copy_sec(fname, backup);
3994# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003995#endif
3996
3997 /*
3998 * copy the file.
3999 */
4000 write_info.bw_fd = bfd;
4001 write_info.bw_buf = copybuf;
4002#ifdef HAS_BW_FLAGS
4003 write_info.bw_flags = FIO_NOCONVERT;
4004#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004005 while ((write_info.bw_len = read_eintr(fd, copybuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004006 BUFSIZE)) > 0)
4007 {
4008 if (buf_write_bytes(&write_info) == FAIL)
4009 {
4010 errmsg = (char_u *)_("E506: Can't write to backup file (add ! to override)");
4011 break;
4012 }
4013 ui_breakcheck();
4014 if (got_int)
4015 {
4016 errmsg = (char_u *)_(e_interr);
4017 break;
4018 }
4019 }
4020
4021 if (close(bfd) < 0 && errmsg == NULL)
4022 errmsg = (char_u *)_("E507: Close error for backup file (add ! to override)");
4023 if (write_info.bw_len < 0)
4024 errmsg = (char_u *)_("E508: Can't read file for backup (add ! to override)");
4025#ifdef UNIX
4026 set_file_time(backup, st_old.st_atime, st_old.st_mtime);
4027#endif
4028#ifdef HAVE_ACL
4029 mch_set_acl(backup, acl);
4030#endif
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004031#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004032 mch_copy_sec(fname, backup);
4033#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004034 break;
4035 }
4036 }
4037 }
4038 nobackup:
4039 close(fd); /* ignore errors for closing read file */
4040 vim_free(copybuf);
4041
4042 if (backup == NULL && errmsg == NULL)
4043 errmsg = (char_u *)_("E509: Cannot create backup file (add ! to override)");
4044 /* ignore errors when forceit is TRUE */
4045 if ((some_error || errmsg != NULL) && !forceit)
4046 {
4047 retval = FAIL;
4048 goto fail;
4049 }
4050 errmsg = NULL;
4051 }
4052 else
4053 {
4054 char_u *dirp;
4055 char_u *p;
4056 char_u *rootname;
4057
4058 /*
4059 * Make a backup by renaming the original file.
4060 */
4061 /*
4062 * If 'cpoptions' includes the "W" flag, we don't want to
4063 * overwrite a read-only file. But rename may be possible
4064 * anyway, thus we need an extra check here.
4065 */
4066 if (file_readonly && vim_strchr(p_cpo, CPO_FWRITE) != NULL)
4067 {
4068 errnum = (char_u *)"E504: ";
4069 errmsg = (char_u *)_(err_readonly);
4070 goto fail;
4071 }
4072
4073 /*
4074 *
4075 * Form the backup file name - change path/fo.o.h to
4076 * path/fo.o.h.bak Try all directories in 'backupdir', first one
4077 * that works is used.
4078 */
4079 dirp = p_bdir;
4080 while (*dirp)
4081 {
4082 /*
4083 * Isolate one directory name and make the backup file name.
4084 */
4085 (void)copy_option_part(&dirp, IObuff, IOSIZE, ",");
4086 rootname = get_file_in_dir(fname, IObuff);
4087 if (rootname == NULL)
4088 backup = NULL;
4089 else
4090 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01004091 backup = buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00004092 rootname, backup_ext, FALSE);
4093 vim_free(rootname);
4094 }
4095
4096 if (backup != NULL)
4097 {
4098 /*
4099 * If we are not going to keep the backup file, don't
4100 * delete an existing one, try to use another name.
4101 * Change one character, just before the extension.
4102 */
4103 if (!p_bk && mch_getperm(backup) >= 0)
4104 {
4105 p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext);
4106 if (p < backup) /* empty file name ??? */
4107 p = backup;
4108 *p = 'z';
4109 while (*p > 'a' && mch_getperm(backup) >= 0)
4110 --*p;
4111 /* They all exist??? Must be something wrong! */
4112 if (*p == 'a')
4113 {
4114 vim_free(backup);
4115 backup = NULL;
4116 }
4117 }
4118 }
4119 if (backup != NULL)
4120 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004121 /*
Bram Moolenaarbfd8fc02005-09-20 23:22:24 +00004122 * Delete any existing backup and move the current version
4123 * to the backup. For safety, we don't remove the backup
4124 * until the write has finished successfully. And if the
4125 * 'backup' option is set, leave it around.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004126 */
4127 /*
4128 * If the renaming of the original file to the backup file
4129 * works, quit here.
4130 */
4131 if (vim_rename(fname, backup) == 0)
4132 break;
4133
4134 vim_free(backup); /* don't do the rename below */
4135 backup = NULL;
4136 }
4137 }
4138 if (backup == NULL && !forceit)
4139 {
4140 errmsg = (char_u *)_("E510: Can't make backup file (add ! to override)");
4141 goto fail;
4142 }
4143 }
4144 }
4145
Bram Moolenaar53076832015-12-31 19:53:21 +01004146#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004147 /* When using ":w!" and the file was read-only: make it writable */
4148 if (forceit && perm >= 0 && !(perm & 0200) && st_old.st_uid == getuid()
4149 && vim_strchr(p_cpo, CPO_FWRITE) == NULL)
4150 {
4151 perm |= 0200;
4152 (void)mch_setperm(fname, perm);
4153 made_writable = TRUE;
4154 }
4155#endif
4156
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004157 /* When using ":w!" and writing to the current file, 'readonly' makes no
Bram Moolenaar4399ef42005-02-12 14:29:27 +00004158 * sense, reset it, unless 'Z' appears in 'cpoptions'. */
4159 if (forceit && overwriting && vim_strchr(p_cpo, CPO_KEEPRO) == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004160 {
4161 buf->b_p_ro = FALSE;
4162#ifdef FEAT_TITLE
4163 need_maketitle = TRUE; /* set window title later */
4164#endif
4165#ifdef FEAT_WINDOWS
4166 status_redraw_all(); /* redraw status lines later */
4167#endif
4168 }
4169
4170 if (end > buf->b_ml.ml_line_count)
4171 end = buf->b_ml.ml_line_count;
4172 if (buf->b_ml.ml_flags & ML_EMPTY)
4173 start = end + 1;
4174
4175 /*
4176 * If the original file is being overwritten, there is a small chance that
4177 * we crash in the middle of writing. Therefore the file is preserved now.
4178 * This makes all block numbers positive so that recovery does not need
4179 * the original file.
4180 * Don't do this if there is a backup file and we are exiting.
4181 */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004182 if (reset_changed && !newfile && overwriting
Bram Moolenaar071d4272004-06-13 20:20:40 +00004183 && !(exiting && backup != NULL))
4184 {
4185 ml_preserve(buf, FALSE);
4186 if (got_int)
4187 {
4188 errmsg = (char_u *)_(e_interr);
4189 goto restore_backup;
4190 }
4191 }
4192
4193#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
4194 /*
4195 * Before risking to lose the original file verify if there's
4196 * a resource fork to preserve, and if cannot be done warn
4197 * the users. This happens when overwriting without backups.
4198 */
4199 if (backup == NULL && overwriting && !append)
4200 if (mch_has_resource_fork(fname))
4201 {
4202 errmsg = (char_u *)_("E460: The resource fork would be lost (add ! to override)");
4203 goto restore_backup;
4204 }
4205#endif
4206
4207#ifdef VMS
4208 vms_remove_version(fname); /* remove version */
4209#endif
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00004210 /* Default: write the file directly. May write to a temp file for
Bram Moolenaar071d4272004-06-13 20:20:40 +00004211 * multi-byte conversion. */
4212 wfname = fname;
4213
4214#ifdef FEAT_MBYTE
4215 /* Check for forced 'fileencoding' from "++opt=val" argument. */
4216 if (eap != NULL && eap->force_enc != 0)
4217 {
4218 fenc = eap->cmd + eap->force_enc;
4219 fenc = enc_canonize(fenc);
4220 fenc_tofree = fenc;
4221 }
4222 else
4223 fenc = buf->b_p_fenc;
4224
4225 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004226 * Check if the file needs to be converted.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004227 */
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004228 converted = need_conversion(fenc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004229
4230 /*
4231 * Check if UTF-8 to UCS-2/4 or Latin1 conversion needs to be done. Or
4232 * Latin1 to Unicode conversion. This is handled in buf_write_bytes().
4233 * Prepare the flags for it and allocate bw_conv_buf when needed.
4234 */
4235 if (converted && (enc_utf8 || STRCMP(p_enc, "latin1") == 0))
4236 {
4237 wb_flags = get_fio_flags(fenc);
4238 if (wb_flags & (FIO_UCS2 | FIO_UCS4 | FIO_UTF16 | FIO_UTF8))
4239 {
4240 /* Need to allocate a buffer to translate into. */
4241 if (wb_flags & (FIO_UCS2 | FIO_UTF16 | FIO_UTF8))
4242 write_info.bw_conv_buflen = bufsize * 2;
4243 else /* FIO_UCS4 */
4244 write_info.bw_conv_buflen = bufsize * 4;
4245 write_info.bw_conv_buf
4246 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4247 if (write_info.bw_conv_buf == NULL)
4248 end = 0;
4249 }
4250 }
4251
4252# ifdef WIN3264
4253 if (converted && wb_flags == 0 && (wb_flags = get_win_fio_flags(fenc)) != 0)
4254 {
4255 /* Convert UTF-8 -> UCS-2 and UCS-2 -> DBCS. Worst-case * 4: */
4256 write_info.bw_conv_buflen = bufsize * 4;
4257 write_info.bw_conv_buf
4258 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4259 if (write_info.bw_conv_buf == NULL)
4260 end = 0;
4261 }
4262# endif
4263
4264# ifdef MACOS_X
4265 if (converted && wb_flags == 0 && (wb_flags = get_mac_fio_flags(fenc)) != 0)
4266 {
4267 write_info.bw_conv_buflen = bufsize * 3;
4268 write_info.bw_conv_buf
4269 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4270 if (write_info.bw_conv_buf == NULL)
4271 end = 0;
4272 }
4273# endif
4274
4275# if defined(FEAT_EVAL) || defined(USE_ICONV)
4276 if (converted && wb_flags == 0)
4277 {
4278# ifdef USE_ICONV
4279 /*
4280 * Use iconv() conversion when conversion is needed and it's not done
4281 * internally.
4282 */
4283 write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc,
4284 enc_utf8 ? (char_u *)"utf-8" : p_enc);
4285 if (write_info.bw_iconv_fd != (iconv_t)-1)
4286 {
4287 /* We're going to use iconv(), allocate a buffer to convert in. */
4288 write_info.bw_conv_buflen = bufsize * ICONV_MULT;
4289 write_info.bw_conv_buf
4290 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4291 if (write_info.bw_conv_buf == NULL)
4292 end = 0;
4293 write_info.bw_first = TRUE;
4294 }
4295# ifdef FEAT_EVAL
4296 else
4297# endif
4298# endif
4299
4300# ifdef FEAT_EVAL
4301 /*
4302 * When the file needs to be converted with 'charconvert' after
4303 * writing, write to a temp file instead and let the conversion
4304 * overwrite the original file.
4305 */
4306 if (*p_ccv != NUL)
4307 {
Bram Moolenaare5c421c2015-03-31 13:33:08 +02004308 wfname = vim_tempname('w', FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004309 if (wfname == NULL) /* Can't write without a tempfile! */
4310 {
4311 errmsg = (char_u *)_("E214: Can't find temp file for writing");
4312 goto restore_backup;
4313 }
4314 }
4315# endif
4316 }
4317# endif
4318 if (converted && wb_flags == 0
4319# ifdef USE_ICONV
4320 && write_info.bw_iconv_fd == (iconv_t)-1
4321# endif
4322# ifdef FEAT_EVAL
4323 && wfname == fname
4324# endif
4325 )
4326 {
4327 if (!forceit)
4328 {
4329 errmsg = (char_u *)_("E213: Cannot convert (add ! to write without conversion)");
4330 goto restore_backup;
4331 }
4332 notconverted = TRUE;
4333 }
4334#endif
4335
4336 /*
4337 * Open the file "wfname" for writing.
4338 * We may try to open the file twice: If we can't write to the
4339 * file and forceit is TRUE we delete the existing file and try to create
4340 * a new one. If this still fails we may have lost the original file!
4341 * (this may happen when the user reached his quotum for number of files).
4342 * Appending will fail if the file does not exist and forceit is FALSE.
4343 */
4344 while ((fd = mch_open((char *)wfname, O_WRONLY | O_EXTRA | (append
4345 ? (forceit ? (O_APPEND | O_CREAT) : O_APPEND)
4346 : (O_CREAT | O_TRUNC))
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00004347 , perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004348 {
4349 /*
4350 * A forced write will try to create a new file if the old one is
4351 * still readonly. This may also happen when the directory is
4352 * read-only. In that case the mch_remove() will fail.
4353 */
4354 if (errmsg == NULL)
4355 {
4356#ifdef UNIX
Bram Moolenaar8767f522016-07-01 17:17:39 +02004357 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004358
4359 /* Don't delete the file when it's a hard or symbolic link. */
4360 if ((!newfile && st_old.st_nlink > 1)
4361 || (mch_lstat((char *)fname, &st) == 0
4362 && (st.st_dev != st_old.st_dev
4363 || st.st_ino != st_old.st_ino)))
4364 errmsg = (char_u *)_("E166: Can't open linked file for writing");
4365 else
4366#endif
4367 {
4368 errmsg = (char_u *)_("E212: Can't open file for writing");
4369 if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL
4370 && perm >= 0)
4371 {
4372#ifdef UNIX
4373 /* we write to the file, thus it should be marked
4374 writable after all */
4375 if (!(perm & 0200))
4376 made_writable = TRUE;
4377 perm |= 0200;
4378 if (st_old.st_uid != getuid() || st_old.st_gid != getgid())
4379 perm &= 0777;
4380#endif
4381 if (!append) /* don't remove when appending */
4382 mch_remove(wfname);
4383 continue;
4384 }
4385 }
4386 }
4387
4388restore_backup:
4389 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02004390 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004391
4392 /*
4393 * If we failed to open the file, we don't need a backup. Throw it
4394 * away. If we moved or removed the original file try to put the
4395 * backup in its place.
4396 */
4397 if (backup != NULL && wfname == fname)
4398 {
4399 if (backup_copy)
4400 {
4401 /*
4402 * There is a small chance that we removed the original,
4403 * try to move the copy in its place.
4404 * This may not work if the vim_rename() fails.
4405 * In that case we leave the copy around.
4406 */
4407 /* If file does not exist, put the copy in its place */
4408 if (mch_stat((char *)fname, &st) < 0)
4409 vim_rename(backup, fname);
4410 /* if original file does exist throw away the copy */
4411 if (mch_stat((char *)fname, &st) >= 0)
4412 mch_remove(backup);
4413 }
4414 else
4415 {
4416 /* try to put the original file back */
4417 vim_rename(backup, fname);
4418 }
4419 }
4420
4421 /* if original file no longer exists give an extra warning */
4422 if (!newfile && mch_stat((char *)fname, &st) < 0)
4423 end = 0;
4424 }
4425
4426#ifdef FEAT_MBYTE
4427 if (wfname != fname)
4428 vim_free(wfname);
4429#endif
4430 goto fail;
4431 }
4432 errmsg = NULL;
4433
4434#if defined(MACOS_CLASSIC) || defined(WIN3264)
4435 /* TODO: Is it need for MACOS_X? (Dany) */
4436 /*
4437 * On macintosh copy the original files attributes (i.e. the backup)
Bram Moolenaar7263a772007-05-10 17:35:54 +00004438 * This is done in order to preserve the resource fork and the
4439 * Finder attribute (label, comments, custom icons, file creator)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004440 */
4441 if (backup != NULL && overwriting && !append)
4442 {
4443 if (backup_copy)
4444 (void)mch_copy_file_attribute(wfname, backup);
4445 else
4446 (void)mch_copy_file_attribute(backup, wfname);
4447 }
4448
4449 if (!overwriting && !append)
4450 {
4451 if (buf->b_ffname != NULL)
4452 (void)mch_copy_file_attribute(buf->b_ffname, wfname);
Bram Moolenaar7263a772007-05-10 17:35:54 +00004453 /* Should copy resource fork */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004454 }
4455#endif
4456
4457 write_info.bw_fd = fd;
4458
4459#ifdef FEAT_CRYPT
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004460 if (*buf->b_p_key != NUL && !filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004461 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004462 char_u *header;
4463 int header_len;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004464
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004465 buf->b_cryptstate = crypt_create_for_writing(crypt_get_method_nr(buf),
4466 buf->b_p_key, &header, &header_len);
4467 if (buf->b_cryptstate == NULL || header == NULL)
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02004468 end = 0;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004469 else
4470 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004471 /* Write magic number, so that Vim knows how this file is
4472 * encrypted when reading it back. */
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02004473 write_info.bw_buf = header;
4474 write_info.bw_len = header_len;
4475 write_info.bw_flags = FIO_NOCONVERT;
4476 if (buf_write_bytes(&write_info) == FAIL)
4477 end = 0;
4478 wb_flags |= FIO_ENCRYPTED;
4479 vim_free(header);
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004480 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004481 }
4482#endif
4483
4484 write_info.bw_buf = buffer;
4485 nchars = 0;
4486
4487 /* use "++bin", "++nobin" or 'binary' */
4488 if (eap != NULL && eap->force_bin != 0)
4489 write_bin = (eap->force_bin == FORCE_BIN);
4490 else
4491 write_bin = buf->b_p_bin;
4492
4493#ifdef FEAT_MBYTE
4494 /*
4495 * The BOM is written just after the encryption magic number.
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004496 * Skip it when appending and the file already existed, the BOM only makes
4497 * sense at the start of the file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004498 */
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004499 if (buf->b_p_bomb && !write_bin && (!append || perm < 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004500 {
4501 write_info.bw_len = make_bom(buffer, fenc);
4502 if (write_info.bw_len > 0)
4503 {
4504 /* don't convert, do encryption */
4505 write_info.bw_flags = FIO_NOCONVERT | wb_flags;
4506 if (buf_write_bytes(&write_info) == FAIL)
4507 end = 0;
4508 else
4509 nchars += write_info.bw_len;
4510 }
4511 }
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004512 write_info.bw_start_lnum = start;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004513#endif
4514
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004515#ifdef FEAT_PERSISTENT_UNDO
4516 write_undo_file = (buf->b_p_udf && overwriting && !append
4517 && !filtering && reset_changed);
4518 if (write_undo_file)
4519 /* Prepare for computing the hash value of the text. */
4520 sha256_start(&sha_ctx);
4521#endif
4522
Bram Moolenaar071d4272004-06-13 20:20:40 +00004523 write_info.bw_len = bufsize;
4524#ifdef HAS_BW_FLAGS
4525 write_info.bw_flags = wb_flags;
4526#endif
4527 fileformat = get_fileformat_force(buf, eap);
4528 s = buffer;
4529 len = 0;
4530 for (lnum = start; lnum <= end; ++lnum)
4531 {
4532 /*
4533 * The next while loop is done once for each character written.
4534 * Keep it fast!
4535 */
4536 ptr = ml_get_buf(buf, lnum, FALSE) - 1;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004537#ifdef FEAT_PERSISTENT_UNDO
4538 if (write_undo_file)
Bram Moolenaar442b4222010-05-24 21:34:22 +02004539 sha256_update(&sha_ctx, ptr + 1, (UINT32_T)(STRLEN(ptr + 1) + 1));
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004540#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004541 while ((c = *++ptr) != NUL)
4542 {
4543 if (c == NL)
4544 *s = NUL; /* replace newlines with NULs */
4545 else if (c == CAR && fileformat == EOL_MAC)
4546 *s = NL; /* Mac: replace CRs with NLs */
4547 else
4548 *s = c;
4549 ++s;
4550 if (++len != bufsize)
4551 continue;
4552 if (buf_write_bytes(&write_info) == FAIL)
4553 {
4554 end = 0; /* write error: break loop */
4555 break;
4556 }
4557 nchars += bufsize;
4558 s = buffer;
4559 len = 0;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004560#ifdef FEAT_MBYTE
4561 write_info.bw_start_lnum = lnum;
4562#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004563 }
4564 /* write failed or last line has no EOL: stop here */
4565 if (end == 0
4566 || (lnum == end
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004567 && (write_bin || !buf->b_p_fixeol)
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004568 && (lnum == buf->b_no_eol_lnum
Bram Moolenaar071d4272004-06-13 20:20:40 +00004569 || (lnum == buf->b_ml.ml_line_count && !buf->b_p_eol))))
4570 {
4571 ++lnum; /* written the line, count it */
4572 no_eol = TRUE;
4573 break;
4574 }
4575 if (fileformat == EOL_UNIX)
4576 *s++ = NL;
4577 else
4578 {
4579 *s++ = CAR; /* EOL_MAC or EOL_DOS: write CR */
4580 if (fileformat == EOL_DOS) /* write CR-NL */
4581 {
4582 if (++len == bufsize)
4583 {
4584 if (buf_write_bytes(&write_info) == FAIL)
4585 {
4586 end = 0; /* write error: break loop */
4587 break;
4588 }
4589 nchars += bufsize;
4590 s = buffer;
4591 len = 0;
4592 }
4593 *s++ = NL;
4594 }
4595 }
4596 if (++len == bufsize && end)
4597 {
4598 if (buf_write_bytes(&write_info) == FAIL)
4599 {
4600 end = 0; /* write error: break loop */
4601 break;
4602 }
4603 nchars += bufsize;
4604 s = buffer;
4605 len = 0;
4606
4607 ui_breakcheck();
4608 if (got_int)
4609 {
4610 end = 0; /* Interrupted, break loop */
4611 break;
4612 }
4613 }
4614#ifdef VMS
4615 /*
4616 * On VMS there is a problem: newlines get added when writing blocks
4617 * at a time. Fix it by writing a line at a time.
4618 * This is much slower!
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004619 * Explanation: VAX/DECC RTL insists that records in some RMS
4620 * structures end with a newline (carriage return) character, and if
4621 * they don't it adds one.
4622 * With other RMS structures it works perfect without this fix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004623 */
Bram Moolenaarb52e2602007-10-29 21:38:54 +00004624 if (buf->b_fab_rfm == FAB$C_VFC
4625 || ((buf->b_fab_rat & (FAB$M_FTN | FAB$M_CR)) != 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004626 {
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004627 int b2write;
4628
4629 buf->b_fab_mrs = (buf->b_fab_mrs == 0
4630 ? MIN(4096, bufsize)
4631 : MIN(buf->b_fab_mrs, bufsize));
4632
4633 b2write = len;
4634 while (b2write > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004635 {
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004636 write_info.bw_len = MIN(b2write, buf->b_fab_mrs);
4637 if (buf_write_bytes(&write_info) == FAIL)
4638 {
4639 end = 0;
4640 break;
4641 }
4642 b2write -= MIN(b2write, buf->b_fab_mrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004643 }
4644 write_info.bw_len = bufsize;
4645 nchars += len;
4646 s = buffer;
4647 len = 0;
4648 }
4649#endif
4650 }
4651 if (len > 0 && end > 0)
4652 {
4653 write_info.bw_len = len;
4654 if (buf_write_bytes(&write_info) == FAIL)
4655 end = 0; /* write error */
4656 nchars += len;
4657 }
4658
4659#if defined(UNIX) && defined(HAVE_FSYNC)
4660 /* On many journalling file systems there is a bug that causes both the
4661 * original and the backup file to be lost when halting the system right
4662 * after writing the file. That's because only the meta-data is
4663 * journalled. Syncing the file slows down the system, but assures it has
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004664 * been written to disk and we don't lose it.
4665 * For a device do try the fsync() but don't complain if it does not work
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00004666 * (could be a pipe).
4667 * If the 'fsync' option is FALSE, don't fsync(). Useful for laptops. */
4668 if (p_fs && fsync(fd) != 0 && !device)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004669 {
4670 errmsg = (char_u *)_("E667: Fsync failed");
4671 end = 0;
4672 }
4673#endif
4674
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004675#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004676 /* Probably need to set the security context. */
4677 if (!backup_copy)
4678 mch_copy_sec(backup, wfname);
4679#endif
4680
Bram Moolenaara5792f52005-11-23 21:25:05 +00004681#ifdef UNIX
4682 /* When creating a new file, set its owner/group to that of the original
4683 * file. Get the new device and inode number. */
4684 if (backup != NULL && !backup_copy)
4685 {
4686# ifdef HAVE_FCHOWN
Bram Moolenaar8767f522016-07-01 17:17:39 +02004687 stat_T st;
Bram Moolenaara5792f52005-11-23 21:25:05 +00004688
4689 /* don't change the owner when it's already OK, some systems remove
4690 * permission or ACL stuff */
4691 if (mch_stat((char *)wfname, &st) < 0
4692 || st.st_uid != st_old.st_uid
4693 || st.st_gid != st_old.st_gid)
4694 {
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004695 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004696 if (perm >= 0) /* set permission again, may have changed */
4697 (void)mch_setperm(wfname, perm);
4698 }
4699# endif
4700 buf_setino(buf);
4701 }
Bram Moolenaarf1726cc2009-05-13 18:48:16 +00004702 else if (!buf->b_dev_valid)
Bram Moolenaar8fa04452005-12-23 22:13:51 +00004703 /* Set the inode when creating a new file. */
4704 buf_setino(buf);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004705#endif
4706
Bram Moolenaar071d4272004-06-13 20:20:40 +00004707 if (close(fd) != 0)
4708 {
4709 errmsg = (char_u *)_("E512: Close failed");
4710 end = 0;
4711 }
4712
4713#ifdef UNIX
4714 if (made_writable)
4715 perm &= ~0200; /* reset 'w' bit for security reasons */
4716#endif
4717 if (perm >= 0) /* set perm. of new file same as old file */
4718 (void)mch_setperm(wfname, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004719#ifdef HAVE_ACL
Bram Moolenaarda412772016-07-14 20:37:07 +02004720 /*
4721 * Probably need to set the ACL before changing the user (can't set the
4722 * ACL on a file the user doesn't own).
4723 * On Solaris, with ZFS and the aclmode property set to "discard" (the
4724 * default), chmod() discards all part of a file's ACL that don't represent
4725 * the mode of the file. It's non-trivial for us to discover whether we're
4726 * in that situation, so we simply always re-set the ACL.
4727 */
4728# ifndef HAVE_SOLARIS_ZFS_ACL
Bram Moolenaar071d4272004-06-13 20:20:40 +00004729 if (!backup_copy)
Bram Moolenaarda412772016-07-14 20:37:07 +02004730# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004731 mch_set_acl(wfname, acl);
4732#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004733#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004734 if (buf->b_cryptstate != NULL)
4735 {
4736 crypt_free_state(buf->b_cryptstate);
4737 buf->b_cryptstate = NULL;
4738 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004739#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004740
Bram Moolenaar071d4272004-06-13 20:20:40 +00004741#if defined(FEAT_MBYTE) && defined(FEAT_EVAL)
4742 if (wfname != fname)
4743 {
4744 /*
4745 * The file was written to a temp file, now it needs to be converted
4746 * with 'charconvert' to (overwrite) the output file.
4747 */
4748 if (end != 0)
4749 {
4750 if (eval_charconvert(enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc,
4751 wfname, fname) == FAIL)
4752 {
4753 write_info.bw_conv_error = TRUE;
4754 end = 0;
4755 }
4756 }
4757 mch_remove(wfname);
4758 vim_free(wfname);
4759 }
4760#endif
4761
4762 if (end == 0)
4763 {
4764 if (errmsg == NULL)
4765 {
4766#ifdef FEAT_MBYTE
4767 if (write_info.bw_conv_error)
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004768 {
4769 if (write_info.bw_conv_error_lnum == 0)
4770 errmsg = (char_u *)_("E513: write error, conversion failed (make 'fenc' empty to override)");
4771 else
4772 {
4773 errmsg_allocated = TRUE;
4774 errmsg = alloc(300);
4775 vim_snprintf((char *)errmsg, 300, _("E513: write error, conversion failed in line %ld (make 'fenc' empty to override)"),
4776 (long)write_info.bw_conv_error_lnum);
4777 }
4778 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004779 else
4780#endif
4781 if (got_int)
4782 errmsg = (char_u *)_(e_interr);
4783 else
4784 errmsg = (char_u *)_("E514: write error (file system full?)");
4785 }
4786
4787 /*
4788 * If we have a backup file, try to put it in place of the new file,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004789 * because the new file is probably corrupt. This avoids losing the
Bram Moolenaar071d4272004-06-13 20:20:40 +00004790 * original file when trying to make a backup when writing the file a
4791 * second time.
4792 * When "backup_copy" is set we need to copy the backup over the new
4793 * file. Otherwise rename the backup file.
4794 * If this is OK, don't give the extra warning message.
4795 */
4796 if (backup != NULL)
4797 {
4798 if (backup_copy)
4799 {
4800 /* This may take a while, if we were interrupted let the user
4801 * know we got the message. */
4802 if (got_int)
4803 {
4804 MSG(_(e_interr));
4805 out_flush();
4806 }
4807 if ((fd = mch_open((char *)backup, O_RDONLY | O_EXTRA, 0)) >= 0)
4808 {
4809 if ((write_info.bw_fd = mch_open((char *)fname,
Bram Moolenaar9be038d2005-03-08 22:34:32 +00004810 O_WRONLY | O_CREAT | O_TRUNC | O_EXTRA,
4811 perm & 0777)) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004812 {
4813 /* copy the file. */
4814 write_info.bw_buf = smallbuf;
4815#ifdef HAS_BW_FLAGS
4816 write_info.bw_flags = FIO_NOCONVERT;
4817#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004818 while ((write_info.bw_len = read_eintr(fd, smallbuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004819 SMBUFSIZE)) > 0)
4820 if (buf_write_bytes(&write_info) == FAIL)
4821 break;
4822
4823 if (close(write_info.bw_fd) >= 0
4824 && write_info.bw_len == 0)
4825 end = 1; /* success */
4826 }
4827 close(fd); /* ignore errors for closing read file */
4828 }
4829 }
4830 else
4831 {
4832 if (vim_rename(backup, fname) == 0)
4833 end = 1;
4834 }
4835 }
4836 goto fail;
4837 }
4838
4839 lnum -= start; /* compute number of written lines */
4840 --no_wait_return; /* may wait for return now */
4841
4842#if !(defined(UNIX) || defined(VMS))
4843 fname = sfname; /* use shortname now, for the messages */
4844#endif
4845 if (!filtering)
4846 {
4847 msg_add_fname(buf, fname); /* put fname in IObuff with quotes */
4848 c = FALSE;
4849#ifdef FEAT_MBYTE
4850 if (write_info.bw_conv_error)
4851 {
4852 STRCAT(IObuff, _(" CONVERSION ERROR"));
4853 c = TRUE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004854 if (write_info.bw_conv_error_lnum != 0)
Bram Moolenaara800b422010-06-27 01:15:55 +02004855 vim_snprintf_add((char *)IObuff, IOSIZE, _(" in line %ld;"),
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004856 (long)write_info.bw_conv_error_lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004857 }
4858 else if (notconverted)
4859 {
4860 STRCAT(IObuff, _("[NOT converted]"));
4861 c = TRUE;
4862 }
4863 else if (converted)
4864 {
4865 STRCAT(IObuff, _("[converted]"));
4866 c = TRUE;
4867 }
4868#endif
4869 if (device)
4870 {
4871 STRCAT(IObuff, _("[Device]"));
4872 c = TRUE;
4873 }
4874 else if (newfile)
4875 {
4876 STRCAT(IObuff, shortmess(SHM_NEW) ? _("[New]") : _("[New File]"));
4877 c = TRUE;
4878 }
4879 if (no_eol)
4880 {
4881 msg_add_eol();
4882 c = TRUE;
4883 }
4884 /* may add [unix/dos/mac] */
4885 if (msg_add_fileformat(fileformat))
4886 c = TRUE;
4887#ifdef FEAT_CRYPT
4888 if (wb_flags & FIO_ENCRYPTED)
4889 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004890 crypt_append_msg(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004891 c = TRUE;
4892 }
4893#endif
4894 msg_add_lines(c, (long)lnum, nchars); /* add line/char count */
4895 if (!shortmess(SHM_WRITE))
4896 {
4897 if (append)
4898 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended"));
4899 else
4900 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written"));
4901 }
4902
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00004903 set_keep_msg(msg_trunc_attr(IObuff, FALSE, 0), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004904 }
4905
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004906 /* When written everything correctly: reset 'modified'. Unless not
4907 * writing to the original file and '+' is not in 'cpoptions'. */
Bram Moolenaar292ad192005-12-11 21:29:51 +00004908 if (reset_changed && whole && !append
Bram Moolenaar071d4272004-06-13 20:20:40 +00004909#ifdef FEAT_MBYTE
4910 && !write_info.bw_conv_error
4911#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004912 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL)
4913 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004914 {
4915 unchanged(buf, TRUE);
Bram Moolenaar086329d2014-10-31 19:51:36 +01004916#ifdef FEAT_AUTOCMD
4917 /* buf->b_changedtick is always incremented in unchanged() but that
4918 * should not trigger a TextChanged event. */
4919 if (last_changedtick + 1 == buf->b_changedtick
4920 && last_changedtick_buf == buf)
4921 last_changedtick = buf->b_changedtick;
4922#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004923 u_unchanged(buf);
Bram Moolenaar730cde92010-06-27 05:18:54 +02004924 u_update_save_nr(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004925 }
4926
4927 /*
4928 * If written to the current file, update the timestamp of the swap file
4929 * and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
4930 */
4931 if (overwriting)
4932 {
4933 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00004934 if (append)
4935 buf->b_flags &= ~BF_NEW;
4936 else
4937 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004938 }
4939
4940 /*
4941 * If we kept a backup until now, and we are in patch mode, then we make
4942 * the backup file our 'original' file.
4943 */
4944 if (*p_pm && dobackup)
4945 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01004946 char *org = (char *)buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00004947 fname, p_pm, FALSE);
4948
4949 if (backup != NULL)
4950 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02004951 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004952
4953 /*
4954 * If the original file does not exist yet
4955 * the current backup file becomes the original file
4956 */
4957 if (org == NULL)
4958 EMSG(_("E205: Patchmode: can't save original file"));
4959 else if (mch_stat(org, &st) < 0)
4960 {
4961 vim_rename(backup, (char_u *)org);
4962 vim_free(backup); /* don't delete the file */
4963 backup = NULL;
4964#ifdef UNIX
4965 set_file_time((char_u *)org, st_old.st_atime, st_old.st_mtime);
4966#endif
4967 }
4968 }
4969 /*
4970 * If there is no backup file, remember that a (new) file was
4971 * created.
4972 */
4973 else
4974 {
4975 int empty_fd;
4976
4977 if (org == NULL
Bram Moolenaara5792f52005-11-23 21:25:05 +00004978 || (empty_fd = mch_open(org,
4979 O_CREAT | O_EXTRA | O_EXCL | O_NOFOLLOW,
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00004980 perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004981 EMSG(_("E206: patchmode: can't touch empty original file"));
4982 else
4983 close(empty_fd);
4984 }
4985 if (org != NULL)
4986 {
4987 mch_setperm((char_u *)org, mch_getperm(fname) & 0777);
4988 vim_free(org);
4989 }
4990 }
4991
4992 /*
4993 * Remove the backup unless 'backup' option is set
4994 */
4995 if (!p_bk && backup != NULL && mch_remove(backup) != 0)
4996 EMSG(_("E207: Can't delete backup file"));
4997
4998#ifdef FEAT_SUN_WORKSHOP
4999 if (usingSunWorkShop)
5000 workshop_file_saved((char *) ffname);
5001#endif
5002
5003 goto nofail;
5004
5005 /*
5006 * Finish up. We get here either after failure or success.
5007 */
5008fail:
5009 --no_wait_return; /* may wait for return now */
5010nofail:
5011
5012 /* Done saving, we accept changed buffer warnings again */
5013 buf->b_saving = FALSE;
5014
5015 vim_free(backup);
5016 if (buffer != smallbuf)
5017 vim_free(buffer);
5018#ifdef FEAT_MBYTE
5019 vim_free(fenc_tofree);
5020 vim_free(write_info.bw_conv_buf);
5021# ifdef USE_ICONV
5022 if (write_info.bw_iconv_fd != (iconv_t)-1)
5023 {
5024 iconv_close(write_info.bw_iconv_fd);
5025 write_info.bw_iconv_fd = (iconv_t)-1;
5026 }
5027# endif
5028#endif
5029#ifdef HAVE_ACL
5030 mch_free_acl(acl);
5031#endif
5032
5033 if (errmsg != NULL)
5034 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005035 int numlen = errnum != NULL ? (int)STRLEN(errnum) : 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005036
5037 attr = hl_attr(HLF_E); /* set highlight for error messages */
5038 msg_add_fname(buf,
5039#ifndef UNIX
5040 sfname
5041#else
5042 fname
5043#endif
5044 ); /* put file name in IObuff with quotes */
5045 if (STRLEN(IObuff) + STRLEN(errmsg) + numlen >= IOSIZE)
5046 IObuff[IOSIZE - STRLEN(errmsg) - numlen - 1] = NUL;
5047 /* If the error message has the form "is ...", put the error number in
5048 * front of the file name. */
5049 if (errnum != NULL)
5050 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00005051 STRMOVE(IObuff + numlen, IObuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005052 mch_memmove(IObuff, errnum, (size_t)numlen);
5053 }
5054 STRCAT(IObuff, errmsg);
5055 emsg(IObuff);
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005056 if (errmsg_allocated)
5057 vim_free(errmsg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005058
5059 retval = FAIL;
5060 if (end == 0)
5061 {
5062 MSG_PUTS_ATTR(_("\nWARNING: Original file may be lost or damaged\n"),
5063 attr | MSG_HIST);
5064 MSG_PUTS_ATTR(_("don't quit the editor until the file is successfully written!"),
5065 attr | MSG_HIST);
5066
5067 /* Update the timestamp to avoid an "overwrite changed file"
5068 * prompt when writing again. */
5069 if (mch_stat((char *)fname, &st_old) >= 0)
5070 {
5071 buf_store_time(buf, &st_old, fname);
5072 buf->b_mtime_read = buf->b_mtime;
5073 }
5074 }
5075 }
5076 msg_scroll = msg_save;
5077
Bram Moolenaar55debbe2010-05-23 23:34:36 +02005078#ifdef FEAT_PERSISTENT_UNDO
5079 /*
5080 * When writing the whole file and 'undofile' is set, also write the undo
5081 * file.
5082 */
5083 if (retval == OK && write_undo_file)
5084 {
5085 char_u hash[UNDO_HASH_SIZE];
5086
5087 sha256_finish(&sha_ctx, hash);
5088 u_write_undo(NULL, FALSE, buf, hash);
5089 }
5090#endif
5091
Bram Moolenaar071d4272004-06-13 20:20:40 +00005092#ifdef FEAT_AUTOCMD
5093#ifdef FEAT_EVAL
5094 if (!should_abort(retval))
5095#else
5096 if (!got_int)
5097#endif
5098 {
5099 aco_save_T aco;
5100
Bram Moolenaar68a33fc2012-04-25 16:50:48 +02005101 curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */
5102
Bram Moolenaar071d4272004-06-13 20:20:40 +00005103 /*
5104 * Apply POST autocommands.
5105 * Careful: The autocommands may call buf_write() recursively!
5106 */
5107 aucmd_prepbuf(&aco, buf);
5108
5109 if (append)
5110 apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname,
5111 FALSE, curbuf, eap);
5112 else if (filtering)
5113 apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname,
5114 FALSE, curbuf, eap);
5115 else if (reset_changed && whole)
5116 apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname,
5117 FALSE, curbuf, eap);
5118 else
5119 apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname,
5120 FALSE, curbuf, eap);
5121
5122 /* restore curwin/curbuf and a few other things */
5123 aucmd_restbuf(&aco);
5124
5125#ifdef FEAT_EVAL
5126 if (aborting()) /* autocmds may abort script processing */
5127 retval = FALSE;
5128#endif
5129 }
5130#endif
5131
5132 got_int |= prev_got_int;
5133
5134#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
5135 /* Update machine specific information. */
5136 mch_post_buffer_write(buf);
5137#endif
5138 return retval;
5139}
5140
5141/*
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005142 * Set the name of the current buffer. Use when the buffer doesn't have a
5143 * name and a ":r" or ":w" command with a file name is used.
5144 */
5145 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005146set_rw_fname(char_u *fname, char_u *sfname)
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005147{
5148#ifdef FEAT_AUTOCMD
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005149 buf_T *buf = curbuf;
5150
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005151 /* It's like the unnamed buffer is deleted.... */
5152 if (curbuf->b_p_bl)
5153 apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
5154 apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf);
5155# ifdef FEAT_EVAL
5156 if (aborting()) /* autocmds may abort script processing */
5157 return FAIL;
5158# endif
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005159 if (curbuf != buf)
5160 {
5161 /* We are in another buffer now, don't do the renaming. */
5162 EMSG(_(e_auchangedbuf));
5163 return FAIL;
5164 }
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005165#endif
5166
5167 if (setfname(curbuf, fname, sfname, FALSE) == OK)
5168 curbuf->b_flags |= BF_NOTEDITED;
5169
5170#ifdef FEAT_AUTOCMD
5171 /* ....and a new named one is created */
5172 apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, curbuf);
5173 if (curbuf->b_p_bl)
5174 apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf);
5175# ifdef FEAT_EVAL
5176 if (aborting()) /* autocmds may abort script processing */
5177 return FAIL;
5178# endif
5179
5180 /* Do filetype detection now if 'filetype' is empty. */
5181 if (*curbuf->b_p_ft == NUL)
5182 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005183 if (au_has_group((char_u *)"filetypedetect"))
Bram Moolenaar1610d052016-06-09 22:53:01 +02005184 (void)do_doautocmd((char_u *)"filetypedetect BufRead", FALSE, NULL);
Bram Moolenaara3227e22006-03-08 21:32:40 +00005185 do_modelines(0);
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005186 }
5187#endif
5188
5189 return OK;
5190}
5191
5192/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00005193 * Put file name into IObuff with quotes.
5194 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005195 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005196msg_add_fname(buf_T *buf, char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005197{
5198 if (fname == NULL)
5199 fname = (char_u *)"-stdin-";
5200 home_replace(buf, fname, IObuff + 1, IOSIZE - 4, TRUE);
5201 IObuff[0] = '"';
5202 STRCAT(IObuff, "\" ");
5203}
5204
5205/*
5206 * Append message for text mode to IObuff.
5207 * Return TRUE if something appended.
5208 */
5209 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005210msg_add_fileformat(int eol_type)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005211{
5212#ifndef USE_CRNL
5213 if (eol_type == EOL_DOS)
5214 {
5215 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[dos]") : _("[dos format]"));
5216 return TRUE;
5217 }
5218#endif
5219#ifndef USE_CR
5220 if (eol_type == EOL_MAC)
5221 {
5222 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[mac]") : _("[mac format]"));
5223 return TRUE;
5224 }
5225#endif
5226#if defined(USE_CRNL) || defined(USE_CR)
5227 if (eol_type == EOL_UNIX)
5228 {
5229 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[unix]") : _("[unix format]"));
5230 return TRUE;
5231 }
5232#endif
5233 return FALSE;
5234}
5235
5236/*
5237 * Append line and character count to IObuff.
5238 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005239 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005240msg_add_lines(
5241 int insert_space,
5242 long lnum,
Bram Moolenaar8767f522016-07-01 17:17:39 +02005243 off_T nchars)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005244{
5245 char_u *p;
5246
5247 p = IObuff + STRLEN(IObuff);
5248
5249 if (insert_space)
5250 *p++ = ' ';
5251 if (shortmess(SHM_LINES))
Bram Moolenaarbde98102016-07-01 20:03:42 +02005252 vim_snprintf((char *)p, IOSIZE - (p - IObuff),
5253 "%ldL, %lldC", lnum, (varnumber_T)nchars);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005254 else
5255 {
5256 if (lnum == 1)
5257 STRCPY(p, _("1 line, "));
5258 else
5259 sprintf((char *)p, _("%ld lines, "), lnum);
5260 p += STRLEN(p);
5261 if (nchars == 1)
5262 STRCPY(p, _("1 character"));
5263 else
Bram Moolenaarbde98102016-07-01 20:03:42 +02005264 vim_snprintf((char *)p, IOSIZE - (p - IObuff),
5265 _("%lld characters"), (varnumber_T)nchars);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005266 }
5267}
5268
5269/*
5270 * Append message for missing line separator to IObuff.
5271 */
5272 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005273msg_add_eol(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005274{
5275 STRCAT(IObuff, shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]"));
5276}
5277
5278/*
5279 * Check modification time of file, before writing to it.
5280 * The size isn't checked, because using a tool like "gzip" takes care of
5281 * using the same timestamp but can't set the size.
5282 */
5283 static int
Bram Moolenaar8767f522016-07-01 17:17:39 +02005284check_mtime(buf_T *buf, stat_T *st)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005285{
5286 if (buf->b_mtime_read != 0
5287 && time_differs((long)st->st_mtime, buf->b_mtime_read))
5288 {
5289 msg_scroll = TRUE; /* don't overwrite messages here */
5290 msg_silent = 0; /* must give this prompt */
5291 /* don't use emsg() here, don't want to flush the buffers */
5292 MSG_ATTR(_("WARNING: The file has been changed since reading it!!!"),
5293 hl_attr(HLF_E));
5294 if (ask_yesno((char_u *)_("Do you really want to write to it"),
5295 TRUE) == 'n')
5296 return FAIL;
5297 msg_scroll = FALSE; /* always overwrite the file message now */
5298 }
5299 return OK;
5300}
5301
5302 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005303time_differs(long t1, long t2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005304{
Bram Moolenaar48e330a2016-02-23 14:53:34 +01005305#if defined(__linux__) || defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005306 /* On a FAT filesystem, esp. under Linux, there are only 5 bits to store
5307 * the seconds. Since the roundoff is done when flushing the inode, the
5308 * time may change unexpectedly by one second!!! */
5309 return (t1 - t2 > 1 || t2 - t1 > 1);
5310#else
5311 return (t1 != t2);
5312#endif
5313}
5314
5315/*
5316 * Call write() to write a number of bytes to the file.
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005317 * Handles encryption and 'encoding' conversion.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005318 *
5319 * Return FAIL for failure, OK otherwise.
5320 */
5321 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005322buf_write_bytes(struct bw_info *ip)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005323{
5324 int wlen;
5325 char_u *buf = ip->bw_buf; /* data to write */
5326 int len = ip->bw_len; /* length of data */
5327#ifdef HAS_BW_FLAGS
5328 int flags = ip->bw_flags; /* extra flags */
5329#endif
5330
5331#ifdef FEAT_MBYTE
5332 /*
5333 * Skip conversion when writing the crypt magic number or the BOM.
5334 */
5335 if (!(flags & FIO_NOCONVERT))
5336 {
5337 char_u *p;
5338 unsigned c;
5339 int n;
5340
5341 if (flags & FIO_UTF8)
5342 {
5343 /*
5344 * Convert latin1 in the buffer to UTF-8 in the file.
5345 */
5346 p = ip->bw_conv_buf; /* translate to buffer */
5347 for (wlen = 0; wlen < len; ++wlen)
5348 p += utf_char2bytes(buf[wlen], p);
5349 buf = ip->bw_conv_buf;
5350 len = (int)(p - ip->bw_conv_buf);
5351 }
5352 else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1))
5353 {
5354 /*
5355 * Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
5356 * Latin1 chars in the file.
5357 */
5358 if (flags & FIO_LATIN1)
5359 p = buf; /* translate in-place (can only get shorter) */
5360 else
5361 p = ip->bw_conv_buf; /* translate to buffer */
5362 for (wlen = 0; wlen < len; wlen += n)
5363 {
5364 if (wlen == 0 && ip->bw_restlen != 0)
5365 {
5366 int l;
5367
5368 /* Use remainder of previous call. Append the start of
5369 * buf[] to get a full sequence. Might still be too
5370 * short! */
5371 l = CONV_RESTLEN - ip->bw_restlen;
5372 if (l > len)
5373 l = len;
5374 mch_memmove(ip->bw_rest + ip->bw_restlen, buf, (size_t)l);
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005375 n = utf_ptr2len_len(ip->bw_rest, ip->bw_restlen + l);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005376 if (n > ip->bw_restlen + len)
5377 {
5378 /* We have an incomplete byte sequence at the end to
5379 * be written. We can't convert it without the
5380 * remaining bytes. Keep them for the next call. */
5381 if (ip->bw_restlen + len > CONV_RESTLEN)
5382 return FAIL;
5383 ip->bw_restlen += len;
5384 break;
5385 }
5386 if (n > 1)
5387 c = utf_ptr2char(ip->bw_rest);
5388 else
5389 c = ip->bw_rest[0];
5390 if (n >= ip->bw_restlen)
5391 {
5392 n -= ip->bw_restlen;
5393 ip->bw_restlen = 0;
5394 }
5395 else
5396 {
5397 ip->bw_restlen -= n;
5398 mch_memmove(ip->bw_rest, ip->bw_rest + n,
5399 (size_t)ip->bw_restlen);
5400 n = 0;
5401 }
5402 }
5403 else
5404 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005405 n = utf_ptr2len_len(buf + wlen, len - wlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005406 if (n > len - wlen)
5407 {
5408 /* We have an incomplete byte sequence at the end to
5409 * be written. We can't convert it without the
5410 * remaining bytes. Keep them for the next call. */
5411 if (len - wlen > CONV_RESTLEN)
5412 return FAIL;
5413 ip->bw_restlen = len - wlen;
5414 mch_memmove(ip->bw_rest, buf + wlen,
5415 (size_t)ip->bw_restlen);
5416 break;
5417 }
5418 if (n > 1)
5419 c = utf_ptr2char(buf + wlen);
5420 else
5421 c = buf[wlen];
5422 }
5423
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005424 if (ucs2bytes(c, &p, flags) && !ip->bw_conv_error)
5425 {
5426 ip->bw_conv_error = TRUE;
5427 ip->bw_conv_error_lnum = ip->bw_start_lnum;
5428 }
5429 if (c == NL)
5430 ++ip->bw_start_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005431 }
5432 if (flags & FIO_LATIN1)
5433 len = (int)(p - buf);
5434 else
5435 {
5436 buf = ip->bw_conv_buf;
5437 len = (int)(p - ip->bw_conv_buf);
5438 }
5439 }
5440
5441# ifdef WIN3264
5442 else if (flags & FIO_CODEPAGE)
5443 {
5444 /*
5445 * Convert UTF-8 or codepage to UCS-2 and then to MS-Windows
5446 * codepage.
5447 */
5448 char_u *from;
5449 size_t fromlen;
5450 char_u *to;
5451 int u8c;
5452 BOOL bad = FALSE;
5453 int needed;
5454
5455 if (ip->bw_restlen > 0)
5456 {
5457 /* Need to concatenate the remainder of the previous call and
5458 * the bytes of the current call. Use the end of the
5459 * conversion buffer for this. */
5460 fromlen = len + ip->bw_restlen;
5461 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5462 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5463 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5464 }
5465 else
5466 {
5467 from = buf;
5468 fromlen = len;
5469 }
5470
5471 to = ip->bw_conv_buf;
5472 if (enc_utf8)
5473 {
5474 /* Convert from UTF-8 to UCS-2, to the start of the buffer.
5475 * The buffer has been allocated to be big enough. */
5476 while (fromlen > 0)
5477 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005478 n = (int)utf_ptr2len_len(from, (int)fromlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005479 if (n > (int)fromlen) /* incomplete byte sequence */
5480 break;
5481 u8c = utf_ptr2char(from);
5482 *to++ = (u8c & 0xff);
5483 *to++ = (u8c >> 8);
5484 fromlen -= n;
5485 from += n;
5486 }
5487
5488 /* Copy remainder to ip->bw_rest[] to be used for the next
5489 * call. */
5490 if (fromlen > CONV_RESTLEN)
5491 {
5492 /* weird overlong sequence */
5493 ip->bw_conv_error = TRUE;
5494 return FAIL;
5495 }
5496 mch_memmove(ip->bw_rest, from, fromlen);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005497 ip->bw_restlen = (int)fromlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005498 }
5499 else
5500 {
5501 /* Convert from enc_codepage to UCS-2, to the start of the
5502 * buffer. The buffer has been allocated to be big enough. */
5503 ip->bw_restlen = 0;
5504 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005505 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005506 NULL, 0);
5507 if (needed == 0)
5508 {
5509 /* When conversion fails there may be a trailing byte. */
5510 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005511 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen - 1,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005512 NULL, 0);
5513 if (needed == 0)
5514 {
5515 /* Conversion doesn't work. */
5516 ip->bw_conv_error = TRUE;
5517 return FAIL;
5518 }
5519 /* Save the trailing byte for the next call. */
5520 ip->bw_rest[0] = from[fromlen - 1];
5521 ip->bw_restlen = 1;
5522 }
5523 needed = MultiByteToWideChar(enc_codepage, MB_ERR_INVALID_CHARS,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005524 (LPCSTR)from, (int)(fromlen - ip->bw_restlen),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005525 (LPWSTR)to, needed);
5526 if (needed == 0)
5527 {
5528 /* Safety check: Conversion doesn't work. */
5529 ip->bw_conv_error = TRUE;
5530 return FAIL;
5531 }
5532 to += needed * 2;
5533 }
5534
5535 fromlen = to - ip->bw_conv_buf;
5536 buf = to;
5537# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5538 if (FIO_GET_CP(flags) == CP_UTF8)
5539 {
5540 /* Convert from UCS-2 to UTF-8, using the remainder of the
5541 * conversion buffer. Fails when out of space. */
5542 for (from = ip->bw_conv_buf; fromlen > 1; fromlen -= 2)
5543 {
5544 u8c = *from++;
5545 u8c += (*from++ << 8);
5546 to += utf_char2bytes(u8c, to);
5547 if (to + 6 >= ip->bw_conv_buf + ip->bw_conv_buflen)
5548 {
5549 ip->bw_conv_error = TRUE;
5550 return FAIL;
5551 }
5552 }
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005553 len = (int)(to - buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005554 }
5555 else
5556#endif
5557 {
5558 /* Convert from UCS-2 to the codepage, using the remainder of
5559 * the conversion buffer. If the conversion uses the default
5560 * character "0", the data doesn't fit in this encoding, so
5561 * fail. */
5562 len = WideCharToMultiByte(FIO_GET_CP(flags), 0,
5563 (LPCWSTR)ip->bw_conv_buf, (int)fromlen / sizeof(WCHAR),
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005564 (LPSTR)to, (int)(ip->bw_conv_buflen - fromlen), 0,
5565 &bad);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005566 if (bad)
5567 {
5568 ip->bw_conv_error = TRUE;
5569 return FAIL;
5570 }
5571 }
5572 }
5573# endif
5574
Bram Moolenaar56718732006-03-15 22:53:57 +00005575# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00005576 else if (flags & FIO_MACROMAN)
5577 {
5578 /*
5579 * Convert UTF-8 or latin1 to Apple MacRoman.
5580 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005581 char_u *from;
5582 size_t fromlen;
5583
5584 if (ip->bw_restlen > 0)
5585 {
5586 /* Need to concatenate the remainder of the previous call and
5587 * the bytes of the current call. Use the end of the
5588 * conversion buffer for this. */
5589 fromlen = len + ip->bw_restlen;
5590 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5591 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5592 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5593 }
5594 else
5595 {
5596 from = buf;
5597 fromlen = len;
5598 }
5599
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00005600 if (enc2macroman(from, fromlen,
5601 ip->bw_conv_buf, &len, ip->bw_conv_buflen,
5602 ip->bw_rest, &ip->bw_restlen) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005603 {
5604 ip->bw_conv_error = TRUE;
5605 return FAIL;
5606 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005607 buf = ip->bw_conv_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005608 }
5609# endif
5610
5611# ifdef USE_ICONV
5612 if (ip->bw_iconv_fd != (iconv_t)-1)
5613 {
5614 const char *from;
5615 size_t fromlen;
5616 char *to;
5617 size_t tolen;
5618
5619 /* Convert with iconv(). */
5620 if (ip->bw_restlen > 0)
5621 {
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005622 char *fp;
5623
Bram Moolenaar071d4272004-06-13 20:20:40 +00005624 /* Need to concatenate the remainder of the previous call and
5625 * the bytes of the current call. Use the end of the
5626 * conversion buffer for this. */
5627 fromlen = len + ip->bw_restlen;
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005628 fp = (char *)ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5629 mch_memmove(fp, ip->bw_rest, (size_t)ip->bw_restlen);
5630 mch_memmove(fp + ip->bw_restlen, buf, (size_t)len);
5631 from = fp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005632 tolen = ip->bw_conv_buflen - fromlen;
5633 }
5634 else
5635 {
5636 from = (const char *)buf;
5637 fromlen = len;
5638 tolen = ip->bw_conv_buflen;
5639 }
5640 to = (char *)ip->bw_conv_buf;
5641
5642 if (ip->bw_first)
5643 {
5644 size_t save_len = tolen;
5645
5646 /* output the initial shift state sequence */
5647 (void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen);
5648
5649 /* There is a bug in iconv() on Linux (which appears to be
5650 * wide-spread) which sets "to" to NULL and messes up "tolen".
5651 */
5652 if (to == NULL)
5653 {
5654 to = (char *)ip->bw_conv_buf;
5655 tolen = save_len;
5656 }
5657 ip->bw_first = FALSE;
5658 }
5659
5660 /*
5661 * If iconv() has an error or there is not enough room, fail.
5662 */
5663 if ((iconv(ip->bw_iconv_fd, (void *)&from, &fromlen, &to, &tolen)
5664 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
5665 || fromlen > CONV_RESTLEN)
5666 {
5667 ip->bw_conv_error = TRUE;
5668 return FAIL;
5669 }
5670
5671 /* copy remainder to ip->bw_rest[] to be used for the next call. */
5672 if (fromlen > 0)
5673 mch_memmove(ip->bw_rest, (void *)from, fromlen);
5674 ip->bw_restlen = (int)fromlen;
5675
5676 buf = ip->bw_conv_buf;
5677 len = (int)((char_u *)to - ip->bw_conv_buf);
5678 }
5679# endif
5680 }
5681#endif /* FEAT_MBYTE */
5682
5683#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02005684 if (flags & FIO_ENCRYPTED)
5685 {
5686 /* Encrypt the data. Do it in-place if possible, otherwise use an
5687 * allocated buffer. */
5688 if (crypt_works_inplace(ip->bw_buffer->b_cryptstate))
5689 {
5690 crypt_encode_inplace(ip->bw_buffer->b_cryptstate, buf, len);
5691 }
5692 else
5693 {
5694 char_u *outbuf;
5695
5696 len = crypt_encode_alloc(curbuf->b_cryptstate, buf, len, &outbuf);
5697 if (len == 0)
5698 return OK; /* Crypt layer is buffering, will flush later. */
5699 wlen = write_eintr(ip->bw_fd, outbuf, len);
5700 vim_free(outbuf);
5701 return (wlen < len) ? FAIL : OK;
5702 }
5703 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005704#endif
5705
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005706 wlen = write_eintr(ip->bw_fd, buf, len);
5707 return (wlen < len) ? FAIL : OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005708}
5709
5710#ifdef FEAT_MBYTE
5711/*
5712 * Convert a Unicode character to bytes.
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005713 * Return TRUE for an error, FALSE when it's OK.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005714 */
5715 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005716ucs2bytes(
5717 unsigned c, /* in: character */
5718 char_u **pp, /* in/out: pointer to result */
5719 int flags) /* FIO_ flags */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005720{
5721 char_u *p = *pp;
5722 int error = FALSE;
5723 int cc;
5724
5725
5726 if (flags & FIO_UCS4)
5727 {
5728 if (flags & FIO_ENDIAN_L)
5729 {
5730 *p++ = c;
5731 *p++ = (c >> 8);
5732 *p++ = (c >> 16);
5733 *p++ = (c >> 24);
5734 }
5735 else
5736 {
5737 *p++ = (c >> 24);
5738 *p++ = (c >> 16);
5739 *p++ = (c >> 8);
5740 *p++ = c;
5741 }
5742 }
5743 else if (flags & (FIO_UCS2 | FIO_UTF16))
5744 {
5745 if (c >= 0x10000)
5746 {
5747 if (flags & FIO_UTF16)
5748 {
5749 /* Make two words, ten bits of the character in each. First
5750 * word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff */
5751 c -= 0x10000;
5752 if (c >= 0x100000)
5753 error = TRUE;
5754 cc = ((c >> 10) & 0x3ff) + 0xd800;
5755 if (flags & FIO_ENDIAN_L)
5756 {
5757 *p++ = cc;
5758 *p++ = ((unsigned)cc >> 8);
5759 }
5760 else
5761 {
5762 *p++ = ((unsigned)cc >> 8);
5763 *p++ = cc;
5764 }
5765 c = (c & 0x3ff) + 0xdc00;
5766 }
5767 else
5768 error = TRUE;
5769 }
5770 if (flags & FIO_ENDIAN_L)
5771 {
5772 *p++ = c;
5773 *p++ = (c >> 8);
5774 }
5775 else
5776 {
5777 *p++ = (c >> 8);
5778 *p++ = c;
5779 }
5780 }
5781 else /* Latin1 */
5782 {
5783 if (c >= 0x100)
5784 {
5785 error = TRUE;
5786 *p++ = 0xBF;
5787 }
5788 else
5789 *p++ = c;
5790 }
5791
5792 *pp = p;
5793 return error;
5794}
5795
5796/*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005797 * Return TRUE if file encoding "fenc" requires conversion from or to
5798 * 'encoding'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005799 */
5800 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005801need_conversion(char_u *fenc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005802{
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005803 int same_encoding;
5804 int enc_flags;
5805 int fenc_flags;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005806
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005807 if (*fenc == NUL || STRCMP(p_enc, fenc) == 0)
Bram Moolenaar442b4222010-05-24 21:34:22 +02005808 {
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005809 same_encoding = TRUE;
Bram Moolenaar442b4222010-05-24 21:34:22 +02005810 fenc_flags = 0;
5811 }
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005812 else
5813 {
5814 /* Ignore difference between "ansi" and "latin1", "ucs-4" and
5815 * "ucs-4be", etc. */
5816 enc_flags = get_fio_flags(p_enc);
5817 fenc_flags = get_fio_flags(fenc);
5818 same_encoding = (enc_flags != 0 && fenc_flags == enc_flags);
5819 }
5820 if (same_encoding)
5821 {
5822 /* Specified encoding matches with 'encoding'. This requires
5823 * conversion when 'encoding' is Unicode but not UTF-8. */
5824 return enc_unicode != 0;
5825 }
5826
5827 /* Encodings differ. However, conversion is not needed when 'enc' is any
5828 * Unicode encoding and the file is UTF-8. */
5829 return !(enc_utf8 && fenc_flags == FIO_UTF8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005830}
5831
5832/*
5833 * Check "ptr" for a unicode encoding and return the FIO_ flags needed for the
5834 * internal conversion.
5835 * if "ptr" is an empty string, use 'encoding'.
5836 */
5837 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005838get_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005839{
5840 int prop;
5841
5842 if (*ptr == NUL)
5843 ptr = p_enc;
5844
5845 prop = enc_canon_props(ptr);
5846 if (prop & ENC_UNICODE)
5847 {
5848 if (prop & ENC_2BYTE)
5849 {
5850 if (prop & ENC_ENDIAN_L)
5851 return FIO_UCS2 | FIO_ENDIAN_L;
5852 return FIO_UCS2;
5853 }
5854 if (prop & ENC_4BYTE)
5855 {
5856 if (prop & ENC_ENDIAN_L)
5857 return FIO_UCS4 | FIO_ENDIAN_L;
5858 return FIO_UCS4;
5859 }
5860 if (prop & ENC_2WORD)
5861 {
5862 if (prop & ENC_ENDIAN_L)
5863 return FIO_UTF16 | FIO_ENDIAN_L;
5864 return FIO_UTF16;
5865 }
5866 return FIO_UTF8;
5867 }
5868 if (prop & ENC_LATIN1)
5869 return FIO_LATIN1;
5870 /* must be ENC_DBCS, requires iconv() */
5871 return 0;
5872}
5873
5874#ifdef WIN3264
5875/*
5876 * Check "ptr" for a MS-Windows codepage name and return the FIO_ flags needed
5877 * for the conversion MS-Windows can do for us. Also accept "utf-8".
5878 * Used for conversion between 'encoding' and 'fileencoding'.
5879 */
5880 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005881get_win_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005882{
5883 int cp;
5884
5885 /* Cannot do this when 'encoding' is not utf-8 and not a codepage. */
5886 if (!enc_utf8 && enc_codepage <= 0)
5887 return 0;
5888
5889 cp = encname2codepage(ptr);
5890 if (cp == 0)
5891 {
5892# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5893 if (STRCMP(ptr, "utf-8") == 0)
5894 cp = CP_UTF8;
5895 else
5896# endif
5897 return 0;
5898 }
5899 return FIO_PUT_CP(cp) | FIO_CODEPAGE;
5900}
5901#endif
5902
5903#ifdef MACOS_X
5904/*
5905 * Check "ptr" for a Carbon supported encoding and return the FIO_ flags
5906 * needed for the internal conversion to/from utf-8 or latin1.
5907 */
5908 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005909get_mac_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005910{
5911 if ((enc_utf8 || STRCMP(p_enc, "latin1") == 0)
5912 && (enc_canon_props(ptr) & ENC_MACROMAN))
5913 return FIO_MACROMAN;
5914 return 0;
5915}
5916#endif
5917
5918/*
5919 * Check for a Unicode BOM (Byte Order Mark) at the start of p[size].
5920 * "size" must be at least 2.
5921 * Return the name of the encoding and set "*lenp" to the length.
5922 * Returns NULL when no BOM found.
5923 */
5924 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005925check_for_bom(
5926 char_u *p,
5927 long size,
5928 int *lenp,
5929 int flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005930{
5931 char *name = NULL;
5932 int len = 2;
5933
5934 if (p[0] == 0xef && p[1] == 0xbb && size >= 3 && p[2] == 0xbf
Bram Moolenaaree0f5a62008-07-24 20:09:16 +00005935 && (flags == FIO_ALL || flags == FIO_UTF8 || flags == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005936 {
5937 name = "utf-8"; /* EF BB BF */
5938 len = 3;
5939 }
5940 else if (p[0] == 0xff && p[1] == 0xfe)
5941 {
5942 if (size >= 4 && p[2] == 0 && p[3] == 0
5943 && (flags == FIO_ALL || flags == (FIO_UCS4 | FIO_ENDIAN_L)))
5944 {
5945 name = "ucs-4le"; /* FF FE 00 00 */
5946 len = 4;
5947 }
Bram Moolenaar223a1892008-11-11 20:57:11 +00005948 else if (flags == (FIO_UCS2 | FIO_ENDIAN_L))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005949 name = "ucs-2le"; /* FF FE */
Bram Moolenaar223a1892008-11-11 20:57:11 +00005950 else if (flags == FIO_ALL || flags == (FIO_UTF16 | FIO_ENDIAN_L))
5951 /* utf-16le is preferred, it also works for ucs-2le text */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005952 name = "utf-16le"; /* FF FE */
5953 }
5954 else if (p[0] == 0xfe && p[1] == 0xff
5955 && (flags == FIO_ALL || flags == FIO_UCS2 || flags == FIO_UTF16))
5956 {
Bram Moolenaarffd82c52008-02-20 17:15:26 +00005957 /* Default to utf-16, it works also for ucs-2 text. */
5958 if (flags == FIO_UCS2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005959 name = "ucs-2"; /* FE FF */
Bram Moolenaarffd82c52008-02-20 17:15:26 +00005960 else
5961 name = "utf-16"; /* FE FF */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005962 }
5963 else if (size >= 4 && p[0] == 0 && p[1] == 0 && p[2] == 0xfe
5964 && p[3] == 0xff && (flags == FIO_ALL || flags == FIO_UCS4))
5965 {
5966 name = "ucs-4"; /* 00 00 FE FF */
5967 len = 4;
5968 }
5969
5970 *lenp = len;
5971 return (char_u *)name;
5972}
5973
5974/*
5975 * Generate a BOM in "buf[4]" for encoding "name".
5976 * Return the length of the BOM (zero when no BOM).
5977 */
5978 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005979make_bom(char_u *buf, char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005980{
5981 int flags;
5982 char_u *p;
5983
5984 flags = get_fio_flags(name);
5985
5986 /* Can't put a BOM in a non-Unicode file. */
5987 if (flags == FIO_LATIN1 || flags == 0)
5988 return 0;
5989
5990 if (flags == FIO_UTF8) /* UTF-8 */
5991 {
5992 buf[0] = 0xef;
5993 buf[1] = 0xbb;
5994 buf[2] = 0xbf;
5995 return 3;
5996 }
5997 p = buf;
5998 (void)ucs2bytes(0xfeff, &p, flags);
5999 return (int)(p - buf);
6000}
6001#endif
6002
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00006003#if defined(FEAT_VIMINFO) || defined(FEAT_BROWSE) || \
Bram Moolenaara0174af2008-01-02 20:08:25 +00006004 defined(FEAT_QUICKFIX) || defined(FEAT_AUTOCMD) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006005/*
6006 * Try to find a shortname by comparing the fullname with the current
6007 * directory.
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006008 * Returns "full_path" or pointer into "full_path" if shortened.
6009 */
6010 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006011shorten_fname1(char_u *full_path)
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006012{
Bram Moolenaard9462e32011-04-11 21:35:11 +02006013 char_u *dirname;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006014 char_u *p = full_path;
6015
Bram Moolenaard9462e32011-04-11 21:35:11 +02006016 dirname = alloc(MAXPATHL);
6017 if (dirname == NULL)
6018 return full_path;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006019 if (mch_dirname(dirname, MAXPATHL) == OK)
6020 {
6021 p = shorten_fname(full_path, dirname);
6022 if (p == NULL || *p == NUL)
6023 p = full_path;
6024 }
Bram Moolenaard9462e32011-04-11 21:35:11 +02006025 vim_free(dirname);
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006026 return p;
6027}
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00006028#endif
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006029
6030/*
6031 * Try to find a shortname by comparing the fullname with the current
6032 * directory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006033 * Returns NULL if not shorter name possible, pointer into "full_path"
6034 * otherwise.
6035 */
6036 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006037shorten_fname(char_u *full_path, char_u *dir_name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006038{
6039 int len;
6040 char_u *p;
6041
6042 if (full_path == NULL)
6043 return NULL;
6044 len = (int)STRLEN(dir_name);
6045 if (fnamencmp(dir_name, full_path, len) == 0)
6046 {
6047 p = full_path + len;
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006048#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006049 /*
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006050 * MSWIN: when a file is in the root directory, dir_name will end in a
Bram Moolenaar071d4272004-06-13 20:20:40 +00006051 * slash, since C: by itself does not define a specific dir. In this
6052 * case p may already be correct. <negri>
6053 */
6054 if (!((len > 2) && (*(p - 2) == ':')))
6055#endif
6056 {
6057 if (vim_ispathsep(*p))
6058 ++p;
6059#ifndef VMS /* the path separator is always part of the path */
6060 else
6061 p = NULL;
6062#endif
6063 }
6064 }
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006065#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006066 /*
6067 * When using a file in the current drive, remove the drive name:
6068 * "A:\dir\file" -> "\dir\file". This helps when moving a session file on
6069 * a floppy from "A:\dir" to "B:\dir".
6070 */
6071 else if (len > 3
6072 && TOUPPER_LOC(full_path[0]) == TOUPPER_LOC(dir_name[0])
6073 && full_path[1] == ':'
6074 && vim_ispathsep(full_path[2]))
6075 p = full_path + 2;
6076#endif
6077 else
6078 p = NULL;
6079 return p;
6080}
6081
6082/*
6083 * Shorten filenames for all buffers.
6084 * When "force" is TRUE: Use full path from now on for files currently being
6085 * edited, both for file name and swap file name. Try to shorten the file
6086 * names a bit, if safe to do so.
6087 * When "force" is FALSE: Only try to shorten absolute file names.
6088 * For buffers that have buftype "nofile" or "scratch": never change the file
6089 * name.
6090 */
6091 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006092shorten_fnames(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006093{
6094 char_u dirname[MAXPATHL];
6095 buf_T *buf;
6096 char_u *p;
6097
6098 mch_dirname(dirname, MAXPATHL);
Bram Moolenaar29323592016-07-24 22:04:11 +02006099 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006100 {
6101 if (buf->b_fname != NULL
6102#ifdef FEAT_QUICKFIX
6103 && !bt_nofile(buf)
6104#endif
6105 && !path_with_url(buf->b_fname)
6106 && (force
6107 || buf->b_sfname == NULL
6108 || mch_isFullName(buf->b_sfname)))
6109 {
6110 vim_free(buf->b_sfname);
6111 buf->b_sfname = NULL;
6112 p = shorten_fname(buf->b_ffname, dirname);
6113 if (p != NULL)
6114 {
6115 buf->b_sfname = vim_strsave(p);
6116 buf->b_fname = buf->b_sfname;
6117 }
6118 if (p == NULL || buf->b_fname == NULL)
6119 buf->b_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006120 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00006121
6122 /* Always make the swap file name a full path, a "nofile" buffer may
6123 * also have a swap file. */
6124 mf_fullname(buf->b_ml.ml_mfp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006125 }
6126#ifdef FEAT_WINDOWS
6127 status_redraw_all();
Bram Moolenaar49d7bf12006-02-17 21:45:41 +00006128 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006129#endif
6130}
6131
6132#if (defined(FEAT_DND) && defined(FEAT_GUI_GTK)) \
6133 || defined(FEAT_GUI_MSWIN) \
6134 || defined(FEAT_GUI_MAC) \
6135 || defined(PROTO)
6136/*
6137 * Shorten all filenames in "fnames[count]" by current directory.
6138 */
6139 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006140shorten_filenames(char_u **fnames, int count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006141{
6142 int i;
6143 char_u dirname[MAXPATHL];
6144 char_u *p;
6145
6146 if (fnames == NULL || count < 1)
6147 return;
6148 mch_dirname(dirname, sizeof(dirname));
6149 for (i = 0; i < count; ++i)
6150 {
6151 if ((p = shorten_fname(fnames[i], dirname)) != NULL)
6152 {
6153 /* shorten_fname() returns pointer in given "fnames[i]". If free
6154 * "fnames[i]" first, "p" becomes invalid. So we need to copy
6155 * "p" first then free fnames[i]. */
6156 p = vim_strsave(p);
6157 vim_free(fnames[i]);
6158 fnames[i] = p;
6159 }
6160 }
6161}
6162#endif
6163
6164/*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006165 * add extension to file name - change path/fo.o.h to path/fo.o.h.ext or
Bram Moolenaar071d4272004-06-13 20:20:40 +00006166 * fo_o_h.ext for MSDOS or when shortname option set.
6167 *
6168 * Assumed that fname is a valid name found in the filesystem we assure that
6169 * the return value is a different name and ends in 'ext'.
6170 * "ext" MUST be at most 4 characters long if it starts with a dot, 3
6171 * characters otherwise.
6172 * Space for the returned name is allocated, must be freed later.
6173 * Returns NULL when out of memory.
6174 */
6175 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006176modname(
6177 char_u *fname,
6178 char_u *ext,
6179 int prepend_dot) /* may prepend a '.' to file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006180{
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006181 return buf_modname((curbuf->b_p_sn || curbuf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00006182 fname, ext, prepend_dot);
6183}
6184
6185 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006186buf_modname(
6187 int shortname, /* use 8.3 file name */
6188 char_u *fname,
6189 char_u *ext,
6190 int prepend_dot) /* may prepend a '.' to file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006191{
6192 char_u *retval;
6193 char_u *s;
6194 char_u *e;
6195 char_u *ptr;
6196 int fnamelen, extlen;
6197
6198 extlen = (int)STRLEN(ext);
6199
6200 /*
6201 * If there is no file name we must get the name of the current directory
6202 * (we need the full path in case :cd is used).
6203 */
6204 if (fname == NULL || *fname == NUL)
6205 {
6206 retval = alloc((unsigned)(MAXPATHL + extlen + 3));
6207 if (retval == NULL)
6208 return NULL;
6209 if (mch_dirname(retval, MAXPATHL) == FAIL ||
6210 (fnamelen = (int)STRLEN(retval)) == 0)
6211 {
6212 vim_free(retval);
6213 return NULL;
6214 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006215 if (!after_pathsep(retval, retval + fnamelen))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006216 {
6217 retval[fnamelen++] = PATHSEP;
6218 retval[fnamelen] = NUL;
6219 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006220 prepend_dot = FALSE; /* nothing to prepend a dot to */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006221 }
6222 else
6223 {
6224 fnamelen = (int)STRLEN(fname);
6225 retval = alloc((unsigned)(fnamelen + extlen + 3));
6226 if (retval == NULL)
6227 return NULL;
6228 STRCPY(retval, fname);
6229#ifdef VMS
6230 vms_remove_version(retval); /* we do not need versions here */
6231#endif
6232 }
6233
6234 /*
6235 * search backwards until we hit a '/', '\' or ':' replacing all '.'
6236 * by '_' for MSDOS or when shortname option set and ext starts with a dot.
6237 * Then truncate what is after the '/', '\' or ':' to 8 characters for
6238 * MSDOS and 26 characters for AMIGA, a lot more for UNIX.
6239 */
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006240 for (ptr = retval + fnamelen; ptr > retval; mb_ptr_back(retval, ptr))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006241 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006242 if (*ext == '.'
Bram Moolenaare60acc12011-05-10 16:41:25 +02006243#ifdef USE_LONG_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00006244 && (!USE_LONG_FNAME || shortname)
Bram Moolenaare60acc12011-05-10 16:41:25 +02006245#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006246 && shortname
Bram Moolenaare60acc12011-05-10 16:41:25 +02006247#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006248 )
6249 if (*ptr == '.') /* replace '.' by '_' */
6250 *ptr = '_';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006251 if (vim_ispathsep(*ptr))
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006252 {
6253 ++ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006254 break;
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006255 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006256 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006257
6258 /* the file name has at most BASENAMELEN characters. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006259 if (STRLEN(ptr) > (unsigned)BASENAMELEN)
6260 ptr[BASENAMELEN] = '\0';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006261
6262 s = ptr + STRLEN(ptr);
6263
6264 /*
6265 * For 8.3 file names we may have to reduce the length.
6266 */
6267#ifdef USE_LONG_FNAME
6268 if (!USE_LONG_FNAME || shortname)
6269#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006270 if (shortname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006271#endif
6272 {
6273 /*
6274 * If there is no file name, or the file name ends in '/', and the
6275 * extension starts with '.', put a '_' before the dot, because just
6276 * ".ext" is invalid.
6277 */
6278 if (fname == NULL || *fname == NUL
6279 || vim_ispathsep(fname[STRLEN(fname) - 1]))
6280 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006281 if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006282 *s++ = '_';
6283 }
6284 /*
6285 * If the extension starts with '.', truncate the base name at 8
6286 * characters
6287 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006288 else if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006289 {
Bram Moolenaar78a15312009-05-15 19:33:18 +00006290 if ((size_t)(s - ptr) > (size_t)8)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006291 {
6292 s = ptr + 8;
6293 *s = '\0';
6294 }
6295 }
6296 /*
6297 * If the extension doesn't start with '.', and the file name
6298 * doesn't have an extension yet, append a '.'
6299 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006300 else if ((e = vim_strchr(ptr, '.')) == NULL)
6301 *s++ = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006302 /*
6303 * If the extension doesn't start with '.', and there already is an
Bram Moolenaar7263a772007-05-10 17:35:54 +00006304 * extension, it may need to be truncated
Bram Moolenaar071d4272004-06-13 20:20:40 +00006305 */
6306 else if ((int)STRLEN(e) + extlen > 4)
6307 s = e + 4 - extlen;
6308 }
Bram Moolenaare7fedb62015-12-31 19:07:19 +01006309#if defined(USE_LONG_FNAME) || defined(WIN3264)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006310 /*
6311 * If there is no file name, and the extension starts with '.', put a
6312 * '_' before the dot, because just ".ext" may be invalid if it's on a
6313 * FAT partition, and on HPFS it doesn't matter.
6314 */
6315 else if ((fname == NULL || *fname == NUL) && *ext == '.')
6316 *s++ = '_';
6317#endif
6318
6319 /*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006320 * Append the extension.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006321 * ext can start with '.' and cannot exceed 3 more characters.
6322 */
6323 STRCPY(s, ext);
6324
Bram Moolenaar071d4272004-06-13 20:20:40 +00006325 /*
6326 * Prepend the dot.
6327 */
Bram Moolenaare60acc12011-05-10 16:41:25 +02006328 if (prepend_dot && !shortname && *(e = gettail(retval)) != '.'
Bram Moolenaar071d4272004-06-13 20:20:40 +00006329#ifdef USE_LONG_FNAME
6330 && USE_LONG_FNAME
6331#endif
6332 )
6333 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006334 STRMOVE(e + 1, e);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006335 *e = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006336 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006337
6338 /*
6339 * Check that, after appending the extension, the file name is really
6340 * different.
6341 */
6342 if (fname != NULL && STRCMP(fname, retval) == 0)
6343 {
6344 /* we search for a character that can be replaced by '_' */
6345 while (--s >= ptr)
6346 {
6347 if (*s != '_')
6348 {
6349 *s = '_';
6350 break;
6351 }
6352 }
6353 if (s < ptr) /* fname was "________.<ext>", how tricky! */
6354 *ptr = 'v';
6355 }
6356 return retval;
6357}
6358
6359/*
6360 * Like fgets(), but if the file line is too long, it is truncated and the
6361 * rest of the line is thrown away. Returns TRUE for end-of-file.
6362 */
6363 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006364vim_fgets(char_u *buf, int size, FILE *fp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006365{
6366 char *eof;
6367#define FGETS_SIZE 200
6368 char tbuf[FGETS_SIZE];
6369
6370 buf[size - 2] = NUL;
6371#ifdef USE_CR
6372 eof = fgets_cr((char *)buf, size, fp);
6373#else
6374 eof = fgets((char *)buf, size, fp);
6375#endif
6376 if (buf[size - 2] != NUL && buf[size - 2] != '\n')
6377 {
6378 buf[size - 1] = NUL; /* Truncate the line */
6379
6380 /* Now throw away the rest of the line: */
6381 do
6382 {
6383 tbuf[FGETS_SIZE - 2] = NUL;
6384#ifdef USE_CR
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006385 ignoredp = fgets_cr((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006386#else
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006387 ignoredp = fgets((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006388#endif
6389 } while (tbuf[FGETS_SIZE - 2] != NUL && tbuf[FGETS_SIZE - 2] != '\n');
6390 }
6391 return (eof == NULL);
6392}
6393
6394#if defined(USE_CR) || defined(PROTO)
6395/*
6396 * Like vim_fgets(), but accept any line terminator: CR, CR-LF or LF.
6397 * Returns TRUE for end-of-file.
6398 * Only used for the Mac, because it's much slower than vim_fgets().
6399 */
6400 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006401tag_fgets(char_u *buf, int size, FILE *fp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006402{
6403 int i = 0;
6404 int c;
6405 int eof = FALSE;
6406
6407 for (;;)
6408 {
6409 c = fgetc(fp);
6410 if (c == EOF)
6411 {
6412 eof = TRUE;
6413 break;
6414 }
6415 if (c == '\r')
6416 {
6417 /* Always store a NL for end-of-line. */
6418 if (i < size - 1)
6419 buf[i++] = '\n';
6420 c = fgetc(fp);
6421 if (c != '\n') /* Macintosh format: single CR. */
6422 ungetc(c, fp);
6423 break;
6424 }
6425 if (i < size - 1)
6426 buf[i++] = c;
6427 if (c == '\n')
6428 break;
6429 }
6430 buf[i] = NUL;
6431 return eof;
6432}
6433#endif
6434
6435/*
6436 * rename() only works if both files are on the same file system, this
6437 * function will (attempts to?) copy the file across if rename fails -- webb
6438 * Return -1 for failure, 0 for success.
6439 */
6440 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006441vim_rename(char_u *from, char_u *to)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006442{
6443 int fd_in;
6444 int fd_out;
6445 int n;
6446 char *errmsg = NULL;
6447 char *buffer;
6448#ifdef AMIGA
6449 BPTR flock;
6450#endif
Bram Moolenaar8767f522016-07-01 17:17:39 +02006451 stat_T st;
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006452 long perm;
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006453#ifdef HAVE_ACL
6454 vim_acl_T acl; /* ACL from original file */
6455#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006456 int use_tmp_file = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006457
6458 /*
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006459 * When the names are identical, there is nothing to do. When they refer
6460 * to the same file (ignoring case and slash/backslash differences) but
6461 * the file name differs we need to go through a temp file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006462 */
6463 if (fnamecmp(from, to) == 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006464 {
Bram Moolenaar71afbfe2013-03-19 16:49:16 +01006465 if (p_fic && STRCMP(gettail(from), gettail(to)) != 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006466 use_tmp_file = TRUE;
6467 else
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006468 return 0;
6469 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006470
6471 /*
6472 * Fail if the "from" file doesn't exist. Avoids that "to" is deleted.
6473 */
6474 if (mch_stat((char *)from, &st) < 0)
6475 return -1;
6476
Bram Moolenaar3576da72008-12-30 15:15:57 +00006477#ifdef UNIX
6478 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02006479 stat_T st_to;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006480
6481 /* It's possible for the source and destination to be the same file.
6482 * This happens when "from" and "to" differ in case and are on a FAT32
6483 * filesystem. In that case go through a temp file name. */
6484 if (mch_stat((char *)to, &st_to) >= 0
6485 && st.st_dev == st_to.st_dev
6486 && st.st_ino == st_to.st_ino)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006487 use_tmp_file = TRUE;
6488 }
6489#endif
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02006490#ifdef WIN3264
6491 {
6492 BY_HANDLE_FILE_INFORMATION info1, info2;
6493
6494 /* It's possible for the source and destination to be the same file.
6495 * In that case go through a temp file name. This makes rename("foo",
6496 * "./foo") a no-op (in a complicated way). */
6497 if (win32_fileinfo(from, &info1) == FILEINFO_OK
6498 && win32_fileinfo(to, &info2) == FILEINFO_OK
6499 && info1.dwVolumeSerialNumber == info2.dwVolumeSerialNumber
6500 && info1.nFileIndexHigh == info2.nFileIndexHigh
6501 && info1.nFileIndexLow == info2.nFileIndexLow)
6502 use_tmp_file = TRUE;
6503 }
6504#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006505
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006506 if (use_tmp_file)
6507 {
6508 char tempname[MAXPATHL + 1];
6509
6510 /*
6511 * Find a name that doesn't exist and is in the same directory.
6512 * Rename "from" to "tempname" and then rename "tempname" to "to".
6513 */
6514 if (STRLEN(from) >= MAXPATHL - 5)
6515 return -1;
6516 STRCPY(tempname, from);
6517 for (n = 123; n < 99999; ++n)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006518 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006519 sprintf((char *)gettail((char_u *)tempname), "%d", n);
6520 if (mch_stat(tempname, &st) < 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006521 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006522 if (mch_rename((char *)from, tempname) == 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006523 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006524 if (mch_rename(tempname, (char *)to) == 0)
6525 return 0;
6526 /* Strange, the second step failed. Try moving the
6527 * file back and return failure. */
6528 mch_rename(tempname, (char *)from);
Bram Moolenaar3576da72008-12-30 15:15:57 +00006529 return -1;
6530 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006531 /* If it fails for one temp name it will most likely fail
6532 * for any temp name, give up. */
6533 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006534 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006535 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006536 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006537 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006538
Bram Moolenaar071d4272004-06-13 20:20:40 +00006539 /*
6540 * Delete the "to" file, this is required on some systems to make the
6541 * mch_rename() work, on other systems it makes sure that we don't have
6542 * two files when the mch_rename() fails.
6543 */
6544
6545#ifdef AMIGA
6546 /*
6547 * With MSDOS-compatible filesystems (crossdos, messydos) it is possible
6548 * that the name of the "to" file is the same as the "from" file, even
Bram Moolenaar7263a772007-05-10 17:35:54 +00006549 * though the names are different. To avoid the chance of accidentally
Bram Moolenaar071d4272004-06-13 20:20:40 +00006550 * deleting the "from" file (horror!) we lock it during the remove.
6551 *
6552 * When used for making a backup before writing the file: This should not
6553 * happen with ":w", because startscript() should detect this problem and
6554 * set buf->b_shortname, causing modname() to return a correct ".bak" file
6555 * name. This problem does exist with ":w filename", but then the
6556 * original file will be somewhere else so the backup isn't really
6557 * important. If autoscripting is off the rename may fail.
6558 */
6559 flock = Lock((UBYTE *)from, (long)ACCESS_READ);
6560#endif
6561 mch_remove(to);
6562#ifdef AMIGA
6563 if (flock)
6564 UnLock(flock);
6565#endif
6566
6567 /*
6568 * First try a normal rename, return if it works.
6569 */
6570 if (mch_rename((char *)from, (char *)to) == 0)
6571 return 0;
6572
6573 /*
6574 * Rename() failed, try copying the file.
6575 */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006576 perm = mch_getperm(from);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006577#ifdef HAVE_ACL
6578 /* For systems that support ACL: get the ACL from the original file. */
6579 acl = mch_get_acl(from);
6580#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006581 fd_in = mch_open((char *)from, O_RDONLY|O_EXTRA, 0);
6582 if (fd_in == -1)
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006583 {
6584#ifdef HAVE_ACL
6585 mch_free_acl(acl);
6586#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006587 return -1;
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006588 }
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006589
6590 /* Create the new file with same permissions as the original. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00006591 fd_out = mch_open((char *)to,
6592 O_CREAT|O_EXCL|O_WRONLY|O_EXTRA|O_NOFOLLOW, (int)perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006593 if (fd_out == -1)
6594 {
6595 close(fd_in);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006596#ifdef HAVE_ACL
6597 mch_free_acl(acl);
6598#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006599 return -1;
6600 }
6601
6602 buffer = (char *)alloc(BUFSIZE);
6603 if (buffer == NULL)
6604 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006605 close(fd_out);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006606 close(fd_in);
6607#ifdef HAVE_ACL
6608 mch_free_acl(acl);
6609#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006610 return -1;
6611 }
6612
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01006613 while ((n = read_eintr(fd_in, buffer, BUFSIZE)) > 0)
6614 if (write_eintr(fd_out, buffer, n) != n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006615 {
6616 errmsg = _("E208: Error writing to \"%s\"");
6617 break;
6618 }
6619
6620 vim_free(buffer);
6621 close(fd_in);
6622 if (close(fd_out) < 0)
6623 errmsg = _("E209: Error closing \"%s\"");
6624 if (n < 0)
6625 {
6626 errmsg = _("E210: Error reading \"%s\"");
6627 to = from;
6628 }
Bram Moolenaar7263a772007-05-10 17:35:54 +00006629#ifndef UNIX /* for Unix mch_open() already set the permission */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006630 mch_setperm(to, perm);
Bram Moolenaarc6039d82005-12-02 00:44:04 +00006631#endif
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006632#ifdef HAVE_ACL
6633 mch_set_acl(to, acl);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006634 mch_free_acl(acl);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006635#endif
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02006636#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaare8747442013-11-12 18:09:29 +01006637 mch_copy_sec(from, to);
Bram Moolenaar0671de32013-11-12 05:12:03 +01006638#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006639 if (errmsg != NULL)
6640 {
6641 EMSG2(errmsg, to);
6642 return -1;
6643 }
6644 mch_remove(from);
6645 return 0;
6646}
6647
6648static int already_warned = FALSE;
6649
6650/*
6651 * Check if any not hidden buffer has been changed.
6652 * Postpone the check if there are characters in the stuff buffer, a global
6653 * command is being executed, a mapping is being executed or an autocommand is
6654 * busy.
6655 * Returns TRUE if some message was written (screen should be redrawn and
6656 * cursor positioned).
6657 */
6658 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006659check_timestamps(
6660 int focus) /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006661{
6662 buf_T *buf;
6663 int didit = 0;
6664 int n;
6665
6666 /* Don't check timestamps while system() or another low-level function may
6667 * cause us to lose and gain focus. */
6668 if (no_check_timestamps > 0)
6669 return FALSE;
6670
6671 /* Avoid doing a check twice. The OK/Reload dialog can cause a focus
6672 * event and we would keep on checking if the file is steadily growing.
6673 * Do check again after typing something. */
6674 if (focus && did_check_timestamps)
6675 {
6676 need_check_timestamps = TRUE;
6677 return FALSE;
6678 }
6679
6680 if (!stuff_empty() || global_busy || !typebuf_typed()
6681#ifdef FEAT_AUTOCMD
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006682 || autocmd_busy || curbuf_lock > 0 || allbuf_lock > 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00006683#endif
6684 )
6685 need_check_timestamps = TRUE; /* check later */
6686 else
6687 {
6688 ++no_wait_return;
6689 did_check_timestamps = TRUE;
6690 already_warned = FALSE;
Bram Moolenaar29323592016-07-24 22:04:11 +02006691 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006692 {
6693 /* Only check buffers in a window. */
6694 if (buf->b_nwindows > 0)
6695 {
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006696 bufref_T bufref;
6697
6698 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006699 n = buf_check_timestamp(buf, focus);
6700 if (didit < n)
6701 didit = n;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006702 if (n > 0 && !bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006703 {
6704 /* Autocommands have removed the buffer, start at the
6705 * first one again. */
6706 buf = firstbuf;
6707 continue;
6708 }
6709 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006710 }
6711 --no_wait_return;
6712 need_check_timestamps = FALSE;
6713 if (need_wait_return && didit == 2)
6714 {
6715 /* make sure msg isn't overwritten */
6716 msg_puts((char_u *)"\n");
6717 out_flush();
6718 }
6719 }
6720 return didit;
6721}
6722
6723/*
6724 * Move all the lines from buffer "frombuf" to buffer "tobuf".
6725 * Return OK or FAIL. When FAIL "tobuf" is incomplete and/or "frombuf" is not
6726 * empty.
6727 */
6728 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006729move_lines(buf_T *frombuf, buf_T *tobuf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006730{
6731 buf_T *tbuf = curbuf;
6732 int retval = OK;
6733 linenr_T lnum;
6734 char_u *p;
6735
6736 /* Copy the lines in "frombuf" to "tobuf". */
6737 curbuf = tobuf;
6738 for (lnum = 1; lnum <= frombuf->b_ml.ml_line_count; ++lnum)
6739 {
6740 p = vim_strsave(ml_get_buf(frombuf, lnum, FALSE));
6741 if (p == NULL || ml_append(lnum - 1, p, 0, FALSE) == FAIL)
6742 {
6743 vim_free(p);
6744 retval = FAIL;
6745 break;
6746 }
6747 vim_free(p);
6748 }
6749
6750 /* Delete all the lines in "frombuf". */
6751 if (retval != FAIL)
6752 {
6753 curbuf = frombuf;
Bram Moolenaar9460b9d2007-01-09 14:37:01 +00006754 for (lnum = curbuf->b_ml.ml_line_count; lnum > 0; --lnum)
6755 if (ml_delete(lnum, FALSE) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006756 {
6757 /* Oops! We could try putting back the saved lines, but that
6758 * might fail again... */
6759 retval = FAIL;
6760 break;
6761 }
6762 }
6763
6764 curbuf = tbuf;
6765 return retval;
6766}
6767
6768/*
6769 * Check if buffer "buf" has been changed.
6770 * Also check if the file for a new buffer unexpectedly appeared.
6771 * return 1 if a changed buffer was found.
6772 * return 2 if a message has been displayed.
6773 * return 0 otherwise.
6774 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006775 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006776buf_check_timestamp(
6777 buf_T *buf,
6778 int focus UNUSED) /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006779{
Bram Moolenaar8767f522016-07-01 17:17:39 +02006780 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006781 int stat_res;
6782 int retval = 0;
6783 char_u *path;
6784 char_u *tbuf;
6785 char *mesg = NULL;
Bram Moolenaar44ecf652005-03-07 23:09:59 +00006786 char *mesg2 = "";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006787 int helpmesg = FALSE;
6788 int reload = FALSE;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006789 char *reason;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006790#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6791 int can_reload = FALSE;
6792#endif
Bram Moolenaar8767f522016-07-01 17:17:39 +02006793 off_T orig_size = buf->b_orig_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006794 int orig_mode = buf->b_orig_mode;
6795#ifdef FEAT_GUI
6796 int save_mouse_correct = need_mouse_correct;
6797#endif
6798#ifdef FEAT_AUTOCMD
6799 static int busy = FALSE;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006800 int n;
6801 char_u *s;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006802 bufref_T bufref;
6803
6804 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006805#endif
6806
6807 /* If there is no file name, the buffer is not loaded, 'buftype' is
6808 * set, we are in the middle of a save or being called recursively: ignore
6809 * this buffer. */
6810 if (buf->b_ffname == NULL
6811 || buf->b_ml.ml_mfp == NULL
6812#if defined(FEAT_QUICKFIX)
6813 || *buf->b_p_bt != NUL
6814#endif
6815 || buf->b_saving
6816#ifdef FEAT_AUTOCMD
6817 || busy
6818#endif
Bram Moolenaar009b2592004-10-24 19:18:58 +00006819#ifdef FEAT_NETBEANS_INTG
6820 || isNetbeansBuffer(buf)
6821#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006822 )
6823 return 0;
6824
6825 if ( !(buf->b_flags & BF_NOTEDITED)
6826 && buf->b_mtime != 0
6827 && ((stat_res = mch_stat((char *)buf->b_ffname, &st)) < 0
6828 || time_differs((long)st.st_mtime, buf->b_mtime)
Bram Moolenaara7611f62014-05-02 15:46:14 +02006829 || st.st_size != buf->b_orig_size
Bram Moolenaar071d4272004-06-13 20:20:40 +00006830#ifdef HAVE_ST_MODE
6831 || (int)st.st_mode != buf->b_orig_mode
6832#else
6833 || mch_getperm(buf->b_ffname) != buf->b_orig_mode
6834#endif
6835 ))
6836 {
6837 retval = 1;
6838
Bram Moolenaar316059c2006-01-14 21:18:42 +00006839 /* set b_mtime to stop further warnings (e.g., when executing
6840 * FileChangedShell autocmd) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006841 if (stat_res < 0)
6842 {
6843 buf->b_mtime = 0;
6844 buf->b_orig_size = 0;
6845 buf->b_orig_mode = 0;
6846 }
6847 else
6848 buf_store_time(buf, &st, buf->b_ffname);
6849
6850 /* Don't do anything for a directory. Might contain the file
6851 * explorer. */
6852 if (mch_isdir(buf->b_fname))
6853 ;
6854
6855 /*
6856 * If 'autoread' is set, the buffer has no changes and the file still
6857 * exists, reload the buffer. Use the buffer-local option value if it
6858 * was set, the global option value otherwise.
6859 */
6860 else if ((buf->b_p_ar >= 0 ? buf->b_p_ar : p_ar)
6861 && !bufIsChanged(buf) && stat_res >= 0)
6862 reload = TRUE;
6863 else
6864 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006865 if (stat_res < 0)
6866 reason = "deleted";
6867 else if (bufIsChanged(buf))
6868 reason = "conflict";
6869 else if (orig_size != buf->b_orig_size || buf_contents_changed(buf))
6870 reason = "changed";
6871 else if (orig_mode != buf->b_orig_mode)
6872 reason = "mode";
6873 else
6874 reason = "time";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006875
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006876#ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006877 /*
6878 * Only give the warning if there are no FileChangedShell
6879 * autocommands.
6880 * Avoid being called recursively by setting "busy".
6881 */
6882 busy = TRUE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00006883# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006884 set_vim_var_string(VV_FCS_REASON, (char_u *)reason, -1);
6885 set_vim_var_string(VV_FCS_CHOICE, (char_u *)"", -1);
Bram Moolenaar1e015462005-09-25 22:16:38 +00006886# endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006887 ++allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006888 n = apply_autocmds(EVENT_FILECHANGEDSHELL,
6889 buf->b_fname, buf->b_fname, FALSE, buf);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006890 --allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006891 busy = FALSE;
6892 if (n)
6893 {
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006894 if (!bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006895 EMSG(_("E246: FileChangedShell autocommand deleted buffer"));
Bram Moolenaar1e015462005-09-25 22:16:38 +00006896# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006897 s = get_vim_var_str(VV_FCS_CHOICE);
6898 if (STRCMP(s, "reload") == 0 && *reason != 'd')
6899 reload = TRUE;
6900 else if (STRCMP(s, "ask") == 0)
6901 n = FALSE;
6902 else
Bram Moolenaar1e015462005-09-25 22:16:38 +00006903# endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006904 return 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006905 }
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006906 if (!n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006907#endif
6908 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006909 if (*reason == 'd')
6910 mesg = _("E211: File \"%s\" no longer available");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006911 else
6912 {
6913 helpmesg = TRUE;
6914#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6915 can_reload = TRUE;
6916#endif
6917 /*
6918 * Check if the file contents really changed to avoid
6919 * giving a warning when only the timestamp was set (e.g.,
6920 * checked out of CVS). Always warn when the buffer was
6921 * changed.
6922 */
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006923 if (reason[2] == 'n')
6924 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006925 mesg = _("W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006926 mesg2 = _("See \":help W12\" for more info.");
6927 }
6928 else if (reason[1] == 'h')
6929 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006930 mesg = _("W11: Warning: File \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006931 mesg2 = _("See \":help W11\" for more info.");
6932 }
6933 else if (*reason == 'm')
6934 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006935 mesg = _("W16: Warning: Mode of file \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006936 mesg2 = _("See \":help W16\" for more info.");
6937 }
Bram Moolenaar85388b52009-06-24 09:58:32 +00006938 else
6939 /* Only timestamp changed, store it to avoid a warning
6940 * in check_mtime() later. */
6941 buf->b_mtime_read = buf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006942 }
6943 }
6944 }
6945
6946 }
6947 else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W)
6948 && vim_fexists(buf->b_ffname))
6949 {
6950 retval = 1;
6951 mesg = _("W13: Warning: File \"%s\" has been created after editing started");
6952 buf->b_flags |= BF_NEW_W;
6953#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6954 can_reload = TRUE;
6955#endif
6956 }
6957
6958 if (mesg != NULL)
6959 {
6960 path = home_replace_save(buf, buf->b_fname);
6961 if (path != NULL)
6962 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006963 if (!helpmesg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006964 mesg2 = "";
6965 tbuf = alloc((unsigned)(STRLEN(path) + STRLEN(mesg)
6966 + STRLEN(mesg2) + 2));
6967 sprintf((char *)tbuf, mesg, path);
Bram Moolenaar496c5262009-03-18 14:42:00 +00006968#ifdef FEAT_EVAL
6969 /* Set warningmsg here, before the unimportant and output-specific
6970 * mesg2 has been appended. */
6971 set_vim_var_string(VV_WARNINGMSG, tbuf, -1);
6972#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006973#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6974 if (can_reload)
6975 {
6976 if (*mesg2 != NUL)
6977 {
6978 STRCAT(tbuf, "\n");
6979 STRCAT(tbuf, mesg2);
6980 }
6981 if (do_dialog(VIM_WARNING, (char_u *)_("Warning"), tbuf,
Bram Moolenaard2c340a2011-01-17 20:08:11 +01006982 (char_u *)_("&OK\n&Load File"), 1, NULL, TRUE) == 2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006983 reload = TRUE;
6984 }
6985 else
6986#endif
6987 if (State > NORMAL_BUSY || (State & CMDLINE) || already_warned)
6988 {
6989 if (*mesg2 != NUL)
6990 {
6991 STRCAT(tbuf, "; ");
6992 STRCAT(tbuf, mesg2);
6993 }
6994 EMSG(tbuf);
6995 retval = 2;
6996 }
6997 else
6998 {
Bram Moolenaared203462004-06-16 11:19:22 +00006999# ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00007000 if (!autocmd_busy)
Bram Moolenaared203462004-06-16 11:19:22 +00007001# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007002 {
7003 msg_start();
7004 msg_puts_attr(tbuf, hl_attr(HLF_E) + MSG_HIST);
7005 if (*mesg2 != NUL)
7006 msg_puts_attr((char_u *)mesg2,
7007 hl_attr(HLF_W) + MSG_HIST);
7008 msg_clr_eos();
7009 (void)msg_end();
7010 if (emsg_silent == 0)
7011 {
7012 out_flush();
Bram Moolenaared203462004-06-16 11:19:22 +00007013# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00007014 if (!focus)
Bram Moolenaared203462004-06-16 11:19:22 +00007015# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007016 /* give the user some time to think about it */
7017 ui_delay(1000L, TRUE);
7018
7019 /* don't redraw and erase the message */
7020 redraw_cmdline = FALSE;
7021 }
7022 }
7023 already_warned = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007024 }
7025
7026 vim_free(path);
7027 vim_free(tbuf);
7028 }
7029 }
7030
7031 if (reload)
Bram Moolenaar465748e2012-08-29 18:50:54 +02007032 {
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007033 /* Reload the buffer. */
Bram Moolenaar316059c2006-01-14 21:18:42 +00007034 buf_reload(buf, orig_mode);
Bram Moolenaar465748e2012-08-29 18:50:54 +02007035#ifdef FEAT_PERSISTENT_UNDO
7036 if (buf->b_p_udf && buf->b_ffname != NULL)
7037 {
7038 char_u hash[UNDO_HASH_SIZE];
7039 buf_T *save_curbuf = curbuf;
7040
7041 /* Any existing undo file is unusable, write it now. */
7042 curbuf = buf;
7043 u_compute_hash(hash);
7044 u_write_undo(NULL, FALSE, buf, hash);
7045 curbuf = save_curbuf;
7046 }
7047#endif
7048 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007049
Bram Moolenaar56718732006-03-15 22:53:57 +00007050#ifdef FEAT_AUTOCMD
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00007051 /* Trigger FileChangedShell when the file was changed in any way. */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007052 if (bufref_valid(&bufref) && retval != 0)
Bram Moolenaar56718732006-03-15 22:53:57 +00007053 (void)apply_autocmds(EVENT_FILECHANGEDSHELLPOST,
7054 buf->b_fname, buf->b_fname, FALSE, buf);
7055#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007056#ifdef FEAT_GUI
7057 /* restore this in case an autocommand has set it; it would break
7058 * 'mousefocus' */
7059 need_mouse_correct = save_mouse_correct;
7060#endif
7061
7062 return retval;
7063}
7064
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007065/*
7066 * Reload a buffer that is already loaded.
7067 * Used when the file was changed outside of Vim.
Bram Moolenaar316059c2006-01-14 21:18:42 +00007068 * "orig_mode" is buf->b_orig_mode before the need for reloading was detected.
7069 * buf->b_orig_mode may have been reset already.
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007070 */
7071 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007072buf_reload(buf_T *buf, int orig_mode)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007073{
7074 exarg_T ea;
7075 pos_T old_cursor;
7076 linenr_T old_topline;
7077 int old_ro = buf->b_p_ro;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007078 buf_T *savebuf;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007079 bufref_T bufref;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007080 int saved = OK;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007081 aco_save_T aco;
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007082 int flags = READ_NEW;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007083
7084 /* set curwin/curbuf for "buf" and save some things */
7085 aucmd_prepbuf(&aco, buf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007086
7087 /* We only want to read the text from the file, not reset the syntax
7088 * highlighting, clear marks, diff status, etc. Force the fileformat
7089 * and encoding to be the same. */
7090 if (prep_exarg(&ea, buf) == OK)
7091 {
7092 old_cursor = curwin->w_cursor;
7093 old_topline = curwin->w_topline;
7094
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007095 if (p_ur < 0 || curbuf->b_ml.ml_line_count <= p_ur)
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007096 {
7097 /* Save all the text, so that the reload can be undone.
7098 * Sync first so that this is a separate undo-able action. */
7099 u_sync(FALSE);
7100 saved = u_savecommon(0, curbuf->b_ml.ml_line_count + 1, 0, TRUE);
7101 flags |= READ_KEEP_UNDO;
7102 }
7103
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007104 /*
7105 * To behave like when a new file is edited (matters for
7106 * BufReadPost autocommands) we first need to delete the current
7107 * buffer contents. But if reading the file fails we should keep
7108 * the old contents. Can't use memory only, the file might be
7109 * too big. Use a hidden buffer to move the buffer contents to.
7110 */
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007111 if (bufempty() || saved == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007112 savebuf = NULL;
7113 else
7114 {
7115 /* Allocate a buffer without putting it in the buffer list. */
7116 savebuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007117 set_bufref(&bufref, savebuf);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007118 if (savebuf != NULL && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007119 {
7120 /* Open the memline. */
7121 curbuf = savebuf;
7122 curwin->w_buffer = savebuf;
Bram Moolenaar4770d092006-01-12 23:22:24 +00007123 saved = ml_open(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007124 curbuf = buf;
7125 curwin->w_buffer = buf;
7126 }
Bram Moolenaar8424a622006-04-19 21:23:36 +00007127 if (savebuf == NULL || saved == FAIL || buf != curbuf
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007128 || move_lines(buf, savebuf) == FAIL)
7129 {
7130 EMSG2(_("E462: Could not prepare for reloading \"%s\""),
7131 buf->b_fname);
7132 saved = FAIL;
7133 }
7134 }
7135
7136 if (saved == OK)
7137 {
7138 curbuf->b_flags |= BF_CHECK_RO; /* check for RO again */
7139#ifdef FEAT_AUTOCMD
7140 keep_filetype = TRUE; /* don't detect 'filetype' */
7141#endif
7142 if (readfile(buf->b_ffname, buf->b_fname, (linenr_T)0,
7143 (linenr_T)0,
Bram Moolenaare13b9af2017-01-13 22:01:02 +01007144 (linenr_T)MAXLNUM, &ea, flags) != OK)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007145 {
7146#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
7147 if (!aborting())
7148#endif
7149 EMSG2(_("E321: Could not reload \"%s\""), buf->b_fname);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007150 if (savebuf != NULL && bufref_valid(&bufref) && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007151 {
7152 /* Put the text back from the save buffer. First
7153 * delete any lines that readfile() added. */
7154 while (!bufempty())
Bram Moolenaar8424a622006-04-19 21:23:36 +00007155 if (ml_delete(buf->b_ml.ml_line_count, FALSE) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007156 break;
7157 (void)move_lines(savebuf, buf);
7158 }
7159 }
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007160 else if (buf == curbuf) /* "buf" still valid */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007161 {
7162 /* Mark the buffer as unmodified and free undo info. */
7163 unchanged(buf, TRUE);
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007164 if ((flags & READ_KEEP_UNDO) == 0)
7165 {
7166 u_blockfree(buf);
7167 u_clearall(buf);
7168 }
7169 else
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007170 {
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007171 /* Mark all undo states as changed. */
7172 u_unchanged(curbuf);
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007173 }
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007174 }
7175 }
7176 vim_free(ea.cmd);
7177
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007178 if (savebuf != NULL && bufref_valid(&bufref))
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007179 wipe_buffer(savebuf, FALSE);
7180
7181#ifdef FEAT_DIFF
7182 /* Invalidate diff info if necessary. */
Bram Moolenaar8424a622006-04-19 21:23:36 +00007183 diff_invalidate(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007184#endif
7185
7186 /* Restore the topline and cursor position and check it (lines may
7187 * have been removed). */
7188 if (old_topline > curbuf->b_ml.ml_line_count)
7189 curwin->w_topline = curbuf->b_ml.ml_line_count;
7190 else
7191 curwin->w_topline = old_topline;
7192 curwin->w_cursor = old_cursor;
7193 check_cursor();
7194 update_topline();
7195#ifdef FEAT_AUTOCMD
7196 keep_filetype = FALSE;
7197#endif
7198#ifdef FEAT_FOLDING
7199 {
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007200 win_T *wp;
7201 tabpage_T *tp;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007202
7203 /* Update folds unless they are defined manually. */
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007204 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007205 if (wp->w_buffer == curwin->w_buffer
7206 && !foldmethodIsManual(wp))
7207 foldUpdateAll(wp);
7208 }
7209#endif
7210 /* If the mode didn't change and 'readonly' was set, keep the old
7211 * value; the user probably used the ":view" command. But don't
7212 * reset it, might have had a read error. */
7213 if (orig_mode == curbuf->b_orig_mode)
7214 curbuf->b_p_ro |= old_ro;
Bram Moolenaar52f85b72013-01-30 14:13:56 +01007215
7216 /* Modelines must override settings done by autocommands. */
7217 do_modelines(0);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007218 }
7219
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007220 /* restore curwin/curbuf and a few other things */
7221 aucmd_restbuf(&aco);
7222 /* Careful: autocommands may have made "buf" invalid! */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007223}
7224
Bram Moolenaar071d4272004-06-13 20:20:40 +00007225 void
Bram Moolenaar8767f522016-07-01 17:17:39 +02007226buf_store_time(buf_T *buf, stat_T *st, char_u *fname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007227{
7228 buf->b_mtime = (long)st->st_mtime;
Bram Moolenaar914703b2010-05-31 21:59:46 +02007229 buf->b_orig_size = st->st_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007230#ifdef HAVE_ST_MODE
7231 buf->b_orig_mode = (int)st->st_mode;
7232#else
7233 buf->b_orig_mode = mch_getperm(fname);
7234#endif
7235}
7236
7237/*
7238 * Adjust the line with missing eol, used for the next write.
7239 * Used for do_filter(), when the input lines for the filter are deleted.
7240 */
7241 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007242write_lnum_adjust(linenr_T offset)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007243{
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01007244 if (curbuf->b_no_eol_lnum != 0) /* only if there is a missing eol */
7245 curbuf->b_no_eol_lnum += offset;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007246}
7247
Bram Moolenaarda440d22016-01-16 21:27:23 +01007248#if defined(TEMPDIRNAMES) || defined(FEAT_EVAL) || defined(PROTO)
7249/*
7250 * Delete "name" and everything in it, recursively.
7251 * return 0 for succes, -1 if some file was not deleted.
7252 */
7253 int
7254delete_recursive(char_u *name)
7255{
7256 int result = 0;
7257 char_u **files;
7258 int file_count;
7259 int i;
7260 char_u *exp;
7261
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007262 /* A symbolic link to a directory itself is deleted, not the directory it
7263 * points to. */
7264 if (
Bram Moolenaar203258c2016-01-17 22:15:16 +01007265# if defined(UNIX) || defined(WIN32)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007266 mch_isrealdir(name)
Bram Moolenaar203258c2016-01-17 22:15:16 +01007267# else
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007268 mch_isdir(name)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007269# endif
7270 )
Bram Moolenaarda440d22016-01-16 21:27:23 +01007271 {
7272 vim_snprintf((char *)NameBuff, MAXPATHL, "%s/*", name);
7273 exp = vim_strsave(NameBuff);
7274 if (exp == NULL)
7275 return -1;
7276 if (gen_expand_wildcards(1, &exp, &file_count, &files,
Bram Moolenaar336bd622016-01-17 18:23:58 +01007277 EW_DIR|EW_FILE|EW_SILENT|EW_ALLLINKS|EW_DODOT|EW_EMPTYOK) == OK)
Bram Moolenaarda440d22016-01-16 21:27:23 +01007278 {
7279 for (i = 0; i < file_count; ++i)
7280 if (delete_recursive(files[i]) != 0)
7281 result = -1;
7282 FreeWild(file_count, files);
7283 }
7284 else
7285 result = -1;
7286 vim_free(exp);
7287 (void)mch_rmdir(name);
7288 }
7289 else
7290 result = mch_remove(name) == 0 ? 0 : -1;
7291
7292 return result;
7293}
7294#endif
7295
Bram Moolenaar071d4272004-06-13 20:20:40 +00007296#if defined(TEMPDIRNAMES) || defined(PROTO)
7297static long temp_count = 0; /* Temp filename counter. */
7298
7299/*
7300 * Delete the temp directory and all files it contains.
7301 */
7302 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007303vim_deltempdir(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007304{
Bram Moolenaar071d4272004-06-13 20:20:40 +00007305 if (vim_tempdir != NULL)
7306 {
Bram Moolenaarda440d22016-01-16 21:27:23 +01007307 /* remove the trailing path separator */
7308 gettail(vim_tempdir)[-1] = NUL;
7309 delete_recursive(vim_tempdir);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007310 vim_free(vim_tempdir);
7311 vim_tempdir = NULL;
7312 }
7313}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007314
7315/*
Bram Moolenaareaf03392009-11-17 11:08:52 +00007316 * Directory "tempdir" was created. Expand this name to a full path and put
7317 * it in "vim_tempdir". This avoids that using ":cd" would confuse us.
7318 * "tempdir" must be no longer than MAXPATHL.
7319 */
7320 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007321vim_settempdir(char_u *tempdir)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007322{
7323 char_u *buf;
7324
7325 buf = alloc((unsigned)MAXPATHL + 2);
7326 if (buf != NULL)
7327 {
7328 if (vim_FullName(tempdir, buf, MAXPATHL, FALSE) == FAIL)
7329 STRCPY(buf, tempdir);
Bram Moolenaara06ecab2016-07-16 14:47:36 +02007330 add_pathsep(buf);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007331 vim_tempdir = vim_strsave(buf);
7332 vim_free(buf);
7333 }
7334}
Bram Moolenaar4592dee2009-11-18 19:11:58 +00007335#endif
Bram Moolenaareaf03392009-11-17 11:08:52 +00007336
7337/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007338 * vim_tempname(): Return a unique name that can be used for a temp file.
7339 *
Bram Moolenaar76ae22f2016-06-13 20:00:29 +02007340 * The temp file is NOT guaranteed to be created. If "keep" is FALSE it is
7341 * guaranteed to NOT be created.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007342 *
7343 * The returned pointer is to allocated memory.
7344 * The returned pointer is NULL if no valid name was found.
7345 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007346 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007347vim_tempname(
7348 int extra_char UNUSED, /* char to use in the name instead of '?' */
7349 int keep UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007350{
7351#ifdef USE_TMPNAM
7352 char_u itmp[L_tmpnam]; /* use tmpnam() */
7353#else
7354 char_u itmp[TEMPNAMELEN];
7355#endif
7356
7357#ifdef TEMPDIRNAMES
7358 static char *(tempdirs[]) = {TEMPDIRNAMES};
7359 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007360# ifndef EEXIST
Bram Moolenaar8767f522016-07-01 17:17:39 +02007361 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007362# endif
7363
7364 /*
7365 * This will create a directory for private use by this instance of Vim.
7366 * This is done once, and the same directory is used for all temp files.
7367 * This method avoids security problems because of symlink attacks et al.
7368 * It's also a bit faster, because we only need to check for an existing
7369 * file when creating the directory and not for each temp file.
7370 */
7371 if (vim_tempdir == NULL)
7372 {
7373 /*
7374 * Try the entries in TEMPDIRNAMES to create the temp directory.
7375 */
Bram Moolenaar78a15312009-05-15 19:33:18 +00007376 for (i = 0; i < (int)(sizeof(tempdirs) / sizeof(char *)); ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007377 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007378# ifndef HAVE_MKDTEMP
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007379 size_t itmplen;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007380 long nr;
7381 long off;
7382# endif
7383
Bram Moolenaare1a61992015-12-03 21:02:27 +01007384 /* Expand $TMP, leave room for "/v1100000/999999999".
7385 * Skip the directory check if the expansion fails. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007386 expand_env((char_u *)tempdirs[i], itmp, TEMPNAMELEN - 20);
Bram Moolenaare1a61992015-12-03 21:02:27 +01007387 if (itmp[0] != '$' && mch_isdir(itmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007388 {
Bram Moolenaare1a61992015-12-03 21:02:27 +01007389 /* directory exists */
Bram Moolenaara06ecab2016-07-16 14:47:36 +02007390 add_pathsep(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007391
Bram Moolenaareaf03392009-11-17 11:08:52 +00007392# ifdef HAVE_MKDTEMP
Bram Moolenaar35d88f42016-06-04 14:52:00 +02007393 {
7394# if defined(UNIX) || defined(VMS)
7395 /* Make sure the umask doesn't remove the executable bit.
7396 * "repl" has been reported to use "177". */
7397 mode_t umask_save = umask(077);
7398# endif
7399 /* Leave room for filename */
7400 STRCAT(itmp, "vXXXXXX");
7401 if (mkdtemp((char *)itmp) != NULL)
7402 vim_settempdir(itmp);
7403# if defined(UNIX) || defined(VMS)
7404 (void)umask(umask_save);
7405# endif
7406 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007407# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007408 /* Get an arbitrary number of up to 6 digits. When it's
7409 * unlikely that it already exists it will be faster,
7410 * otherwise it doesn't matter. The use of mkdir() avoids any
7411 * security problems because of the predictable number. */
7412 nr = (mch_get_pid() + (long)time(NULL)) % 1000000L;
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007413 itmplen = STRLEN(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007414
7415 /* Try up to 10000 different values until we find a name that
7416 * doesn't exist. */
7417 for (off = 0; off < 10000L; ++off)
7418 {
7419 int r;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007420# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007421 mode_t umask_save;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007422# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007423
Bram Moolenaareaf03392009-11-17 11:08:52 +00007424 sprintf((char *)itmp + itmplen, "v%ld", nr + off);
7425# ifndef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007426 /* If mkdir() does not set errno to EEXIST, check for
7427 * existing file here. There is a race condition then,
7428 * although it's fail-safe. */
7429 if (mch_stat((char *)itmp, &st) >= 0)
7430 continue;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007431# endif
7432# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007433 /* Make sure the umask doesn't remove the executable bit.
7434 * "repl" has been reported to use "177". */
7435 umask_save = umask(077);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007436# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007437 r = vim_mkdir(itmp, 0700);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007438# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007439 (void)umask(umask_save);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007440# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007441 if (r == 0)
7442 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007443 vim_settempdir(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007444 break;
7445 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007446# ifdef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007447 /* If the mkdir() didn't fail because the file/dir exists,
7448 * we probably can't create any dir here, try another
7449 * place. */
7450 if (errno != EEXIST)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007451# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007452 break;
7453 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007454# endif /* HAVE_MKDTEMP */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007455 if (vim_tempdir != NULL)
7456 break;
7457 }
7458 }
7459 }
7460
7461 if (vim_tempdir != NULL)
7462 {
7463 /* There is no need to check if the file exists, because we own the
7464 * directory and nobody else creates a file in it. */
7465 sprintf((char *)itmp, "%s%ld", vim_tempdir, temp_count++);
7466 return vim_strsave(itmp);
7467 }
7468
7469 return NULL;
7470
7471#else /* TEMPDIRNAMES */
7472
7473# ifdef WIN3264
7474 char szTempFile[_MAX_PATH + 1];
7475 char buf4[4];
7476 char_u *retval;
7477 char_u *p;
7478
7479 STRCPY(itmp, "");
7480 if (GetTempPath(_MAX_PATH, szTempFile) == 0)
Bram Moolenaarb1891912011-02-09 14:47:03 +01007481 {
7482 szTempFile[0] = '.'; /* GetTempPath() failed, use current dir */
7483 szTempFile[1] = NUL;
7484 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007485 strcpy(buf4, "VIM");
7486 buf4[2] = extra_char; /* make it "VIa", "VIb", etc. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007487 if (GetTempFileName(szTempFile, buf4, 0, (LPSTR)itmp) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007488 return NULL;
Bram Moolenaare5c421c2015-03-31 13:33:08 +02007489 if (!keep)
7490 /* GetTempFileName() will create the file, we don't want that */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007491 (void)DeleteFile((LPSTR)itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007492
7493 /* Backslashes in a temp file name cause problems when filtering with
7494 * "sh". NOTE: This also checks 'shellcmdflag' to help those people who
7495 * didn't set 'shellslash'. */
7496 retval = vim_strsave(itmp);
7497 if (*p_shcf == '-' || p_ssl)
7498 for (p = retval; *p; ++p)
7499 if (*p == '\\')
7500 *p = '/';
7501 return retval;
7502
7503# else /* WIN3264 */
7504
7505# ifdef USE_TMPNAM
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007506 char_u *p;
7507
Bram Moolenaar071d4272004-06-13 20:20:40 +00007508 /* tmpnam() will make its own name */
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007509 p = tmpnam((char *)itmp);
7510 if (p == NULL || *p == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007511 return NULL;
7512# else
7513 char_u *p;
7514
7515# ifdef VMS_TEMPNAM
7516 /* mktemp() is not working on VMS. It seems to be
7517 * a do-nothing function. Therefore we use tempnam().
7518 */
7519 sprintf((char *)itmp, "VIM%c", extra_char);
7520 p = (char_u *)tempnam("tmp:", (char *)itmp);
7521 if (p != NULL)
7522 {
Bram Moolenaar206f0112014-03-12 16:51:55 +01007523 /* VMS will use '.LIS' if we don't explicitly specify an extension,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007524 * and VIM will then be unable to find the file later */
7525 STRCPY(itmp, p);
7526 STRCAT(itmp, ".txt");
7527 free(p);
7528 }
7529 else
7530 return NULL;
7531# else
7532 STRCPY(itmp, TEMPNAME);
7533 if ((p = vim_strchr(itmp, '?')) != NULL)
7534 *p = extra_char;
7535 if (mktemp((char *)itmp) == NULL)
7536 return NULL;
7537# endif
7538# endif
7539
7540 return vim_strsave(itmp);
7541# endif /* WIN3264 */
7542#endif /* TEMPDIRNAMES */
7543}
7544
7545#if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
7546/*
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02007547 * Convert all backslashes in fname to forward slashes in-place, unless when
7548 * it looks like a URL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007549 */
7550 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007551forward_slash(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007552{
7553 char_u *p;
7554
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02007555 if (path_with_url(fname))
7556 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007557 for (p = fname; *p != NUL; ++p)
7558# ifdef FEAT_MBYTE
7559 /* The Big5 encoding can have '\' in the trail byte. */
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00007560 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007561 ++p;
7562 else
7563# endif
7564 if (*p == '\\')
7565 *p = '/';
7566}
7567#endif
7568
7569
7570/*
7571 * Code for automatic commands.
7572 *
7573 * Only included when "FEAT_AUTOCMD" has been defined.
7574 */
7575
7576#if defined(FEAT_AUTOCMD) || defined(PROTO)
7577
7578/*
7579 * The autocommands are stored in a list for each event.
7580 * Autocommands for the same pattern, that are consecutive, are joined
7581 * together, to avoid having to match the pattern too often.
7582 * The result is an array of Autopat lists, which point to AutoCmd lists:
7583 *
7584 * first_autopat[0] --> Autopat.next --> Autopat.next --> NULL
7585 * Autopat.cmds Autopat.cmds
7586 * | |
7587 * V V
7588 * AutoCmd.next AutoCmd.next
7589 * | |
7590 * V V
7591 * AutoCmd.next NULL
7592 * |
7593 * V
7594 * NULL
7595 *
7596 * first_autopat[1] --> Autopat.next --> NULL
7597 * Autopat.cmds
7598 * |
7599 * V
7600 * AutoCmd.next
7601 * |
7602 * V
7603 * NULL
7604 * etc.
7605 *
7606 * The order of AutoCmds is important, this is the order in which they were
7607 * defined and will have to be executed.
7608 */
7609typedef struct AutoCmd
7610{
7611 char_u *cmd; /* The command to be executed (NULL
7612 when command has been removed) */
7613 char nested; /* If autocommands nest here */
7614 char last; /* last command in list */
7615#ifdef FEAT_EVAL
7616 scid_T scriptID; /* script ID where defined */
7617#endif
7618 struct AutoCmd *next; /* Next AutoCmd in list */
7619} AutoCmd;
7620
7621typedef struct AutoPat
7622{
Bram Moolenaar071d4272004-06-13 20:20:40 +00007623 char_u *pat; /* pattern as typed (NULL when pattern
7624 has been removed) */
Bram Moolenaar748bf032005-02-02 23:04:36 +00007625 regprog_T *reg_prog; /* compiled regprog for pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007626 AutoCmd *cmds; /* list of commands to do */
7627 struct AutoPat *next; /* next AutoPat in AutoPat list */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007628 int group; /* group ID */
7629 int patlen; /* strlen() of pat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007630 int buflocal_nr; /* !=0 for buffer-local AutoPat */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007631 char allow_dirs; /* Pattern may match whole path */
7632 char last; /* last pattern for apply_autocmds() */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007633} AutoPat;
7634
7635static struct event_name
7636{
7637 char *name; /* event name */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007638 event_T event; /* event number */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007639} event_names[] =
7640{
7641 {"BufAdd", EVENT_BUFADD},
7642 {"BufCreate", EVENT_BUFADD},
7643 {"BufDelete", EVENT_BUFDELETE},
7644 {"BufEnter", EVENT_BUFENTER},
7645 {"BufFilePost", EVENT_BUFFILEPOST},
7646 {"BufFilePre", EVENT_BUFFILEPRE},
7647 {"BufHidden", EVENT_BUFHIDDEN},
7648 {"BufLeave", EVENT_BUFLEAVE},
7649 {"BufNew", EVENT_BUFNEW},
7650 {"BufNewFile", EVENT_BUFNEWFILE},
7651 {"BufRead", EVENT_BUFREADPOST},
7652 {"BufReadCmd", EVENT_BUFREADCMD},
7653 {"BufReadPost", EVENT_BUFREADPOST},
7654 {"BufReadPre", EVENT_BUFREADPRE},
7655 {"BufUnload", EVENT_BUFUNLOAD},
7656 {"BufWinEnter", EVENT_BUFWINENTER},
7657 {"BufWinLeave", EVENT_BUFWINLEAVE},
7658 {"BufWipeout", EVENT_BUFWIPEOUT},
7659 {"BufWrite", EVENT_BUFWRITEPRE},
7660 {"BufWritePost", EVENT_BUFWRITEPOST},
7661 {"BufWritePre", EVENT_BUFWRITEPRE},
7662 {"BufWriteCmd", EVENT_BUFWRITECMD},
7663 {"CmdwinEnter", EVENT_CMDWINENTER},
7664 {"CmdwinLeave", EVENT_CMDWINLEAVE},
Bram Moolenaard5005162014-08-22 23:05:54 +02007665 {"CmdUndefined", EVENT_CMDUNDEFINED},
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007666 {"ColorScheme", EVENT_COLORSCHEME},
Bram Moolenaarcfa3cae2012-07-10 17:14:56 +02007667 {"CompleteDone", EVENT_COMPLETEDONE},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007668 {"CursorHold", EVENT_CURSORHOLD},
7669 {"CursorHoldI", EVENT_CURSORHOLDI},
7670 {"CursorMoved", EVENT_CURSORMOVED},
7671 {"CursorMovedI", EVENT_CURSORMOVEDI},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007672 {"EncodingChanged", EVENT_ENCODINGCHANGED},
7673 {"FileEncoding", EVENT_ENCODINGCHANGED},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007674 {"FileAppendPost", EVENT_FILEAPPENDPOST},
7675 {"FileAppendPre", EVENT_FILEAPPENDPRE},
7676 {"FileAppendCmd", EVENT_FILEAPPENDCMD},
7677 {"FileChangedShell",EVENT_FILECHANGEDSHELL},
Bram Moolenaar56718732006-03-15 22:53:57 +00007678 {"FileChangedShellPost",EVENT_FILECHANGEDSHELLPOST},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007679 {"FileChangedRO", EVENT_FILECHANGEDRO},
7680 {"FileReadPost", EVENT_FILEREADPOST},
7681 {"FileReadPre", EVENT_FILEREADPRE},
7682 {"FileReadCmd", EVENT_FILEREADCMD},
7683 {"FileType", EVENT_FILETYPE},
7684 {"FileWritePost", EVENT_FILEWRITEPOST},
7685 {"FileWritePre", EVENT_FILEWRITEPRE},
7686 {"FileWriteCmd", EVENT_FILEWRITECMD},
7687 {"FilterReadPost", EVENT_FILTERREADPOST},
7688 {"FilterReadPre", EVENT_FILTERREADPRE},
7689 {"FilterWritePost", EVENT_FILTERWRITEPOST},
7690 {"FilterWritePre", EVENT_FILTERWRITEPRE},
7691 {"FocusGained", EVENT_FOCUSGAINED},
7692 {"FocusLost", EVENT_FOCUSLOST},
7693 {"FuncUndefined", EVENT_FUNCUNDEFINED},
7694 {"GUIEnter", EVENT_GUIENTER},
Bram Moolenaar265e5072006-08-29 16:13:22 +00007695 {"GUIFailed", EVENT_GUIFAILED},
Bram Moolenaar843ee412004-06-30 16:16:41 +00007696 {"InsertChange", EVENT_INSERTCHANGE},
7697 {"InsertEnter", EVENT_INSERTENTER},
7698 {"InsertLeave", EVENT_INSERTLEAVE},
Bram Moolenaare659c952011-05-19 17:25:41 +02007699 {"InsertCharPre", EVENT_INSERTCHARPRE},
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00007700 {"MenuPopup", EVENT_MENUPOPUP},
Bram Moolenaar53744302015-07-17 17:38:22 +02007701 {"OptionSet", EVENT_OPTIONSET},
Bram Moolenaar7c626922005-02-07 22:01:03 +00007702 {"QuickFixCmdPost", EVENT_QUICKFIXCMDPOST},
7703 {"QuickFixCmdPre", EVENT_QUICKFIXCMDPRE},
Bram Moolenaar3b53dfb2012-06-06 18:03:07 +02007704 {"QuitPre", EVENT_QUITPRE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007705 {"RemoteReply", EVENT_REMOTEREPLY},
Bram Moolenaar9372a112005-12-06 19:59:18 +00007706 {"SessionLoadPost", EVENT_SESSIONLOADPOST},
Bram Moolenaar5c4bab02006-03-10 21:37:46 +00007707 {"ShellCmdPost", EVENT_SHELLCMDPOST},
7708 {"ShellFilterPost", EVENT_SHELLFILTERPOST},
Bram Moolenaara2031822006-03-07 22:29:51 +00007709 {"SourcePre", EVENT_SOURCEPRE},
Bram Moolenaar8dd1aa52007-01-16 20:33:19 +00007710 {"SourceCmd", EVENT_SOURCECMD},
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00007711 {"SpellFileMissing",EVENT_SPELLFILEMISSING},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007712 {"StdinReadPost", EVENT_STDINREADPOST},
7713 {"StdinReadPre", EVENT_STDINREADPRE},
Bram Moolenaarb815dac2005-12-07 20:59:24 +00007714 {"SwapExists", EVENT_SWAPEXISTS},
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00007715 {"Syntax", EVENT_SYNTAX},
Bram Moolenaarc917da42016-07-19 22:31:36 +02007716 {"TabNew", EVENT_TABNEW},
Bram Moolenaar12c11d52016-07-19 23:13:03 +02007717 {"TabClosed", EVENT_TABCLOSED},
Bram Moolenaar70836c82006-02-20 21:28:49 +00007718 {"TabEnter", EVENT_TABENTER},
7719 {"TabLeave", EVENT_TABLEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007720 {"TermChanged", EVENT_TERMCHANGED},
7721 {"TermResponse", EVENT_TERMRESPONSE},
Bram Moolenaar186628f2013-03-19 13:33:23 +01007722 {"TextChanged", EVENT_TEXTCHANGED},
7723 {"TextChangedI", EVENT_TEXTCHANGEDI},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007724 {"User", EVENT_USER},
7725 {"VimEnter", EVENT_VIMENTER},
7726 {"VimLeave", EVENT_VIMLEAVE},
7727 {"VimLeavePre", EVENT_VIMLEAVEPRE},
Bram Moolenaarc917da42016-07-19 22:31:36 +02007728 {"WinNew", EVENT_WINNEW},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007729 {"WinEnter", EVENT_WINENTER},
7730 {"WinLeave", EVENT_WINLEAVE},
Bram Moolenaar56718732006-03-15 22:53:57 +00007731 {"VimResized", EVENT_VIMRESIZED},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007732 {NULL, (event_T)0}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007733};
7734
7735static AutoPat *first_autopat[NUM_EVENTS] =
7736{
7737 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7738 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7739 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7740 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00007741 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaar53744302015-07-17 17:38:22 +02007742 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007743};
7744
7745/*
7746 * struct used to keep status while executing autocommands for an event.
7747 */
7748typedef struct AutoPatCmd
7749{
7750 AutoPat *curpat; /* next AutoPat to examine */
7751 AutoCmd *nextcmd; /* next AutoCmd to execute */
7752 int group; /* group being used */
7753 char_u *fname; /* fname to match with */
7754 char_u *sfname; /* sfname to match with */
7755 char_u *tail; /* tail of fname */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007756 event_T event; /* current event */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007757 int arg_bufnr; /* initially equal to <abuf>, set to zero when
7758 buf is deleted */
7759 struct AutoPatCmd *next; /* chain of active apc-s for auto-invalidation*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00007760} AutoPatCmd;
7761
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007762static AutoPatCmd *active_apc_list = NULL; /* stack of active autocommands */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007763
Bram Moolenaar071d4272004-06-13 20:20:40 +00007764/*
7765 * augroups stores a list of autocmd group names.
7766 */
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007767static garray_T augroups = {0, 0, sizeof(char_u *), 10, NULL};
Bram Moolenaar071d4272004-06-13 20:20:40 +00007768#define AUGROUP_NAME(i) (((char_u **)augroups.ga_data)[i])
Bram Moolenaarb62cc362016-09-03 16:43:53 +02007769/* use get_deleted_augroup() to get this */
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02007770static char_u *deleted_augroup = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007771
7772/*
7773 * The ID of the current group. Group 0 is the default one.
7774 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007775static int current_augroup = AUGROUP_DEFAULT;
7776
7777static int au_need_clean = FALSE; /* need to delete marked patterns */
7778
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007779static void show_autocmd(AutoPat *ap, event_T event);
7780static void au_remove_pat(AutoPat *ap);
7781static void au_remove_cmds(AutoPat *ap);
7782static void au_cleanup(void);
7783static int au_new_group(char_u *name);
7784static void au_del_group(char_u *name);
7785static event_T event_name2nr(char_u *start, char_u **end);
7786static char_u *event_nr2name(event_T event);
7787static char_u *find_end_event(char_u *arg, int have_group);
7788static int event_ignored(event_T event);
7789static int au_get_grouparg(char_u **argp);
7790static int do_autocmd_event(event_T event, char_u *pat, int nested, char_u *cmd, int forceit, int group);
7791static int apply_autocmds_group(event_T event, char_u *fname, char_u *fname_io, int force, int group, buf_T *buf, exarg_T *eap);
7792static void auto_next_pat(AutoPatCmd *apc, int stop_at_last);
Bram Moolenaardffa5b82014-11-19 16:38:07 +01007793#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN)
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007794static 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 +01007795#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007796
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007797
Bram Moolenaar754b5602006-02-09 23:53:20 +00007798static event_T last_event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007799static int last_group;
Bram Moolenaar78ab3312007-09-29 12:16:41 +00007800static int autocmd_blocked = 0; /* block all autocmds */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007801
Bram Moolenaarb62cc362016-09-03 16:43:53 +02007802 static char_u *
7803get_deleted_augroup(void)
7804{
7805 if (deleted_augroup == NULL)
7806 deleted_augroup = (char_u *)_("--Deleted--");
7807 return deleted_augroup;
7808}
7809
Bram Moolenaar071d4272004-06-13 20:20:40 +00007810/*
7811 * Show the autocommands for one AutoPat.
7812 */
7813 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007814show_autocmd(AutoPat *ap, event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007815{
7816 AutoCmd *ac;
7817
7818 /* Check for "got_int" (here and at various places below), which is set
7819 * when "q" has been hit for the "--more--" prompt */
7820 if (got_int)
7821 return;
7822 if (ap->pat == NULL) /* pattern has been removed */
7823 return;
7824
7825 msg_putchar('\n');
7826 if (got_int)
7827 return;
7828 if (event != last_event || ap->group != last_group)
7829 {
7830 if (ap->group != AUGROUP_DEFAULT)
7831 {
7832 if (AUGROUP_NAME(ap->group) == NULL)
Bram Moolenaarb62cc362016-09-03 16:43:53 +02007833 msg_puts_attr(get_deleted_augroup(), hl_attr(HLF_E));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007834 else
7835 msg_puts_attr(AUGROUP_NAME(ap->group), hl_attr(HLF_T));
7836 msg_puts((char_u *)" ");
7837 }
7838 msg_puts_attr(event_nr2name(event), hl_attr(HLF_T));
7839 last_event = event;
7840 last_group = ap->group;
7841 msg_putchar('\n');
7842 if (got_int)
7843 return;
7844 }
7845 msg_col = 4;
7846 msg_outtrans(ap->pat);
7847
7848 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7849 {
7850 if (ac->cmd != NULL) /* skip removed commands */
7851 {
7852 if (msg_col >= 14)
7853 msg_putchar('\n');
7854 msg_col = 14;
7855 if (got_int)
7856 return;
7857 msg_outtrans(ac->cmd);
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00007858#ifdef FEAT_EVAL
7859 if (p_verbose > 0)
7860 last_set_msg(ac->scriptID);
7861#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007862 if (got_int)
7863 return;
7864 if (ac->next != NULL)
7865 {
7866 msg_putchar('\n');
7867 if (got_int)
7868 return;
7869 }
7870 }
7871 }
7872}
7873
7874/*
7875 * Mark an autocommand pattern for deletion.
7876 */
7877 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007878au_remove_pat(AutoPat *ap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007879{
7880 vim_free(ap->pat);
7881 ap->pat = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007882 ap->buflocal_nr = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007883 au_need_clean = TRUE;
7884}
7885
7886/*
7887 * Mark all commands for a pattern for deletion.
7888 */
7889 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007890au_remove_cmds(AutoPat *ap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007891{
7892 AutoCmd *ac;
7893
7894 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7895 {
7896 vim_free(ac->cmd);
7897 ac->cmd = NULL;
7898 }
7899 au_need_clean = TRUE;
7900}
7901
7902/*
7903 * Cleanup autocommands and patterns that have been deleted.
7904 * This is only done when not executing autocommands.
7905 */
7906 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007907au_cleanup(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007908{
7909 AutoPat *ap, **prev_ap;
7910 AutoCmd *ac, **prev_ac;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007911 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007912
7913 if (autocmd_busy || !au_need_clean)
7914 return;
7915
7916 /* loop over all events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007917 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7918 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007919 {
7920 /* loop over all autocommand patterns */
7921 prev_ap = &(first_autopat[(int)event]);
7922 for (ap = *prev_ap; ap != NULL; ap = *prev_ap)
7923 {
7924 /* loop over all commands for this pattern */
7925 prev_ac = &(ap->cmds);
7926 for (ac = *prev_ac; ac != NULL; ac = *prev_ac)
7927 {
7928 /* remove the command if the pattern is to be deleted or when
7929 * the command has been marked for deletion */
7930 if (ap->pat == NULL || ac->cmd == NULL)
7931 {
7932 *prev_ac = ac->next;
7933 vim_free(ac->cmd);
7934 vim_free(ac);
7935 }
7936 else
7937 prev_ac = &(ac->next);
7938 }
7939
7940 /* remove the pattern if it has been marked for deletion */
7941 if (ap->pat == NULL)
7942 {
7943 *prev_ap = ap->next;
Bram Moolenaar473de612013-06-08 18:19:48 +02007944 vim_regfree(ap->reg_prog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007945 vim_free(ap);
7946 }
7947 else
7948 prev_ap = &(ap->next);
7949 }
7950 }
7951
7952 au_need_clean = FALSE;
7953}
7954
7955/*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007956 * Called when buffer is freed, to remove/invalidate related buffer-local
7957 * autocmds.
7958 */
7959 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007960aubuflocal_remove(buf_T *buf)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007961{
7962 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007963 event_T event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007964 AutoPatCmd *apc;
7965
7966 /* invalidate currently executing autocommands */
7967 for (apc = active_apc_list; apc; apc = apc->next)
7968 if (buf->b_fnum == apc->arg_bufnr)
7969 apc->arg_bufnr = 0;
7970
7971 /* invalidate buflocals looping through events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007972 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7973 event = (event_T)((int)event + 1))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007974 /* loop over all autocommand patterns */
7975 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
7976 if (ap->buflocal_nr == buf->b_fnum)
7977 {
7978 au_remove_pat(ap);
7979 if (p_verbose >= 6)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007980 {
7981 verbose_enter();
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007982 smsg((char_u *)
7983 _("auto-removing autocommand: %s <buffer=%d>"),
7984 event_nr2name(event), buf->b_fnum);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007985 verbose_leave();
7986 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007987 }
7988 au_cleanup();
7989}
7990
7991/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007992 * Add an autocmd group name.
7993 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
7994 */
7995 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007996au_new_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007997{
7998 int i;
7999
8000 i = au_find_group(name);
8001 if (i == AUGROUP_ERROR) /* the group doesn't exist yet, add it */
8002 {
8003 /* First try using a free entry. */
8004 for (i = 0; i < augroups.ga_len; ++i)
8005 if (AUGROUP_NAME(i) == NULL)
8006 break;
8007 if (i == augroups.ga_len && ga_grow(&augroups, 1) == FAIL)
8008 return AUGROUP_ERROR;
8009
8010 AUGROUP_NAME(i) = vim_strsave(name);
8011 if (AUGROUP_NAME(i) == NULL)
8012 return AUGROUP_ERROR;
8013 if (i == augroups.ga_len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008014 ++augroups.ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008015 }
8016
8017 return i;
8018}
8019
8020 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008021au_del_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008022{
8023 int i;
8024
8025 i = au_find_group(name);
8026 if (i == AUGROUP_ERROR) /* the group doesn't exist */
8027 EMSG2(_("E367: No such group: \"%s\""), name);
Bram Moolenaarde653f02016-09-03 16:59:06 +02008028 else if (i == current_augroup)
8029 EMSG(_("E936: Cannot delete the current group"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008030 else
8031 {
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008032 event_T event;
8033 AutoPat *ap;
8034 int in_use = FALSE;
8035
8036 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8037 event = (event_T)((int)event + 1))
8038 {
8039 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
Bram Moolenaar5c809082016-09-01 16:21:48 +02008040 if (ap->group == i && ap->pat != NULL)
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008041 {
8042 give_warning((char_u *)_("W19: Deleting augroup that is still in use"), TRUE);
8043 in_use = TRUE;
8044 event = NUM_EVENTS;
8045 break;
8046 }
8047 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008048 vim_free(AUGROUP_NAME(i));
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008049 if (in_use)
8050 {
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008051 AUGROUP_NAME(i) = get_deleted_augroup();
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008052 }
8053 else
8054 AUGROUP_NAME(i) = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008055 }
8056}
8057
8058/*
8059 * Find the ID of an autocmd group name.
8060 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
8061 */
8062 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008063au_find_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008064{
8065 int i;
8066
8067 for (i = 0; i < augroups.ga_len; ++i)
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008068 if (AUGROUP_NAME(i) != NULL && AUGROUP_NAME(i) != get_deleted_augroup()
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008069 && STRCMP(AUGROUP_NAME(i), name) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008070 return i;
8071 return AUGROUP_ERROR;
8072}
8073
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008074/*
8075 * Return TRUE if augroup "name" exists.
8076 */
8077 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008078au_has_group(char_u *name)
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008079{
8080 return au_find_group(name) != AUGROUP_ERROR;
8081}
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008082
Bram Moolenaar071d4272004-06-13 20:20:40 +00008083/*
8084 * ":augroup {name}".
8085 */
8086 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008087do_augroup(char_u *arg, int del_group)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008088{
8089 int i;
8090
8091 if (del_group)
8092 {
8093 if (*arg == NUL)
8094 EMSG(_(e_argreq));
8095 else
8096 au_del_group(arg);
8097 }
8098 else if (STRICMP(arg, "end") == 0) /* ":aug end": back to group 0 */
8099 current_augroup = AUGROUP_DEFAULT;
8100 else if (*arg) /* ":aug xxx": switch to group xxx */
8101 {
8102 i = au_new_group(arg);
8103 if (i != AUGROUP_ERROR)
8104 current_augroup = i;
8105 }
8106 else /* ":aug": list the group names */
8107 {
8108 msg_start();
8109 for (i = 0; i < augroups.ga_len; ++i)
8110 {
8111 if (AUGROUP_NAME(i) != NULL)
8112 {
8113 msg_puts(AUGROUP_NAME(i));
8114 msg_puts((char_u *)" ");
8115 }
8116 }
8117 msg_clr_eos();
8118 msg_end();
8119 }
8120}
8121
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008122#if defined(EXITFREE) || defined(PROTO)
8123 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008124free_all_autocmds(void)
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008125{
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008126 int i;
8127 char_u *s;
8128
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008129 for (current_augroup = -1; current_augroup < augroups.ga_len;
8130 ++current_augroup)
8131 do_autocmd((char_u *)"", TRUE);
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008132
8133 for (i = 0; i < augroups.ga_len; ++i)
8134 {
8135 s = ((char_u **)(augroups.ga_data))[i];
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008136 if (s != get_deleted_augroup())
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008137 vim_free(s);
8138 }
8139 ga_clear(&augroups);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008140}
8141#endif
8142
Bram Moolenaar071d4272004-06-13 20:20:40 +00008143/*
8144 * Return the event number for event name "start".
8145 * Return NUM_EVENTS if the event name was not found.
8146 * Return a pointer to the next event name in "end".
8147 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008148 static event_T
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008149event_name2nr(char_u *start, char_u **end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008150{
8151 char_u *p;
8152 int i;
8153 int len;
8154
Bram Moolenaare99e8442016-07-26 20:43:40 +02008155 /* the event name ends with end of line, '|', a blank or a comma */
8156 for (p = start; *p && !vim_iswhite(*p) && *p != ',' && *p != '|'; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008157 ;
8158 for (i = 0; event_names[i].name != NULL; ++i)
8159 {
8160 len = (int)STRLEN(event_names[i].name);
8161 if (len == p - start && STRNICMP(event_names[i].name, start, len) == 0)
8162 break;
8163 }
8164 if (*p == ',')
8165 ++p;
8166 *end = p;
8167 if (event_names[i].name == NULL)
8168 return NUM_EVENTS;
8169 return event_names[i].event;
8170}
8171
8172/*
8173 * Return the name for event "event".
8174 */
8175 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008176event_nr2name(event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008177{
8178 int i;
8179
8180 for (i = 0; event_names[i].name != NULL; ++i)
8181 if (event_names[i].event == event)
8182 return (char_u *)event_names[i].name;
8183 return (char_u *)"Unknown";
8184}
8185
8186/*
8187 * Scan over the events. "*" stands for all events.
8188 */
8189 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008190find_end_event(
8191 char_u *arg,
8192 int have_group) /* TRUE when group name was found */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008193{
8194 char_u *pat;
8195 char_u *p;
8196
8197 if (*arg == '*')
8198 {
8199 if (arg[1] && !vim_iswhite(arg[1]))
8200 {
8201 EMSG2(_("E215: Illegal character after *: %s"), arg);
8202 return NULL;
8203 }
8204 pat = arg + 1;
8205 }
8206 else
8207 {
Bram Moolenaare99e8442016-07-26 20:43:40 +02008208 for (pat = arg; *pat && *pat != '|' && !vim_iswhite(*pat); pat = p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008209 {
8210 if ((int)event_name2nr(pat, &p) >= (int)NUM_EVENTS)
8211 {
8212 if (have_group)
8213 EMSG2(_("E216: No such event: %s"), pat);
8214 else
8215 EMSG2(_("E216: No such group or event: %s"), pat);
8216 return NULL;
8217 }
8218 }
8219 }
8220 return pat;
8221}
8222
8223/*
8224 * Return TRUE if "event" is included in 'eventignore'.
8225 */
8226 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008227event_ignored(event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008228{
8229 char_u *p = p_ei;
8230
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008231 while (*p != NUL)
8232 {
8233 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8234 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008235 if (event_name2nr(p, &p) == event)
8236 return TRUE;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008237 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008238
8239 return FALSE;
8240}
8241
8242/*
8243 * Return OK when the contents of p_ei is valid, FAIL otherwise.
8244 */
8245 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008246check_ei(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008247{
8248 char_u *p = p_ei;
8249
Bram Moolenaar071d4272004-06-13 20:20:40 +00008250 while (*p)
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008251 {
8252 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8253 {
8254 p += 3;
8255 if (*p == ',')
8256 ++p;
8257 }
8258 else if (event_name2nr(p, &p) == NUM_EVENTS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008259 return FAIL;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008260 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008261
8262 return OK;
8263}
8264
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008265# if defined(FEAT_SYN_HL) || defined(PROTO)
8266
8267/*
8268 * Add "what" to 'eventignore' to skip loading syntax highlighting for every
8269 * buffer loaded into the window. "what" must start with a comma.
8270 * Returns the old value of 'eventignore' in allocated memory.
8271 */
8272 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008273au_event_disable(char *what)
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008274{
8275 char_u *new_ei;
8276 char_u *save_ei;
8277
8278 save_ei = vim_strsave(p_ei);
8279 if (save_ei != NULL)
8280 {
Bram Moolenaara5792f52005-11-23 21:25:05 +00008281 new_ei = vim_strnsave(p_ei, (int)(STRLEN(p_ei) + STRLEN(what)));
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008282 if (new_ei != NULL)
8283 {
Bram Moolenaar8cac9fd2010-03-02 12:48:05 +01008284 if (*what == ',' && *p_ei == NUL)
8285 STRCPY(new_ei, what + 1);
8286 else
8287 STRCAT(new_ei, what);
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008288 set_string_option_direct((char_u *)"ei", -1, new_ei,
8289 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008290 vim_free(new_ei);
8291 }
8292 }
8293 return save_ei;
8294}
8295
8296 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008297au_event_restore(char_u *old_ei)
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008298{
8299 if (old_ei != NULL)
8300 {
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008301 set_string_option_direct((char_u *)"ei", -1, old_ei,
8302 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008303 vim_free(old_ei);
8304 }
8305}
8306# endif /* FEAT_SYN_HL */
8307
Bram Moolenaar071d4272004-06-13 20:20:40 +00008308/*
8309 * do_autocmd() -- implements the :autocmd command. Can be used in the
8310 * following ways:
8311 *
8312 * :autocmd <event> <pat> <cmd> Add <cmd> to the list of commands that
8313 * will be automatically executed for <event>
8314 * when editing a file matching <pat>, in
8315 * the current group.
8316 * :autocmd <event> <pat> Show the auto-commands associated with
8317 * <event> and <pat>.
8318 * :autocmd <event> Show the auto-commands associated with
8319 * <event>.
8320 * :autocmd Show all auto-commands.
8321 * :autocmd! <event> <pat> <cmd> Remove all auto-commands associated with
8322 * <event> and <pat>, and add the command
8323 * <cmd>, for the current group.
8324 * :autocmd! <event> <pat> Remove all auto-commands associated with
8325 * <event> and <pat> for the current group.
8326 * :autocmd! <event> Remove all auto-commands associated with
8327 * <event> for the current group.
8328 * :autocmd! Remove ALL auto-commands for the current
8329 * group.
8330 *
8331 * Multiple events and patterns may be given separated by commas. Here are
8332 * some examples:
8333 * :autocmd bufread,bufenter *.c,*.h set tw=0 smartindent noic
8334 * :autocmd bufleave * set tw=79 nosmartindent ic infercase
8335 *
8336 * :autocmd * *.c show all autocommands for *.c files.
Bram Moolenaard35f9712005-12-18 22:02:33 +00008337 *
8338 * Mostly a {group} argument can optionally appear before <event>.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008339 */
8340 void
Bram Moolenaare99e8442016-07-26 20:43:40 +02008341do_autocmd(char_u *arg_in, int forceit)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008342{
Bram Moolenaare99e8442016-07-26 20:43:40 +02008343 char_u *arg = arg_in;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008344 char_u *pat;
8345 char_u *envpat = NULL;
8346 char_u *cmd;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008347 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008348 int need_free = FALSE;
8349 int nested = FALSE;
8350 int group;
8351
Bram Moolenaare99e8442016-07-26 20:43:40 +02008352 if (*arg == '|')
8353 {
8354 arg = (char_u *)"";
8355 group = AUGROUP_ALL; /* no argument, use all groups */
8356 }
8357 else
8358 {
8359 /*
8360 * Check for a legal group name. If not, use AUGROUP_ALL.
8361 */
8362 group = au_get_grouparg(&arg);
8363 if (arg == NULL) /* out of memory */
8364 return;
8365 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008366
8367 /*
8368 * Scan over the events.
8369 * If we find an illegal name, return here, don't do anything.
8370 */
8371 pat = find_end_event(arg, group != AUGROUP_ALL);
8372 if (pat == NULL)
8373 return;
8374
Bram Moolenaar071d4272004-06-13 20:20:40 +00008375 pat = skipwhite(pat);
Bram Moolenaare99e8442016-07-26 20:43:40 +02008376 if (*pat == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008377 {
Bram Moolenaare99e8442016-07-26 20:43:40 +02008378 pat = (char_u *)"";
8379 cmd = (char_u *)"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00008380 }
Bram Moolenaare99e8442016-07-26 20:43:40 +02008381 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00008382 {
Bram Moolenaare99e8442016-07-26 20:43:40 +02008383 /*
8384 * Scan over the pattern. Put a NUL at the end.
8385 */
8386 cmd = pat;
8387 while (*cmd && (!vim_iswhite(*cmd) || cmd[-1] == '\\'))
8388 cmd++;
8389 if (*cmd)
8390 *cmd++ = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008391
Bram Moolenaare99e8442016-07-26 20:43:40 +02008392 /* Expand environment variables in the pattern. Set 'shellslash', we want
8393 * forward slashes here. */
8394 if (vim_strchr(pat, '$') != NULL || vim_strchr(pat, '~') != NULL)
8395 {
8396#ifdef BACKSLASH_IN_FILENAME
8397 int p_ssl_save = p_ssl;
8398
8399 p_ssl = TRUE;
8400#endif
8401 envpat = expand_env_save(pat);
8402#ifdef BACKSLASH_IN_FILENAME
8403 p_ssl = p_ssl_save;
8404#endif
8405 if (envpat != NULL)
8406 pat = envpat;
8407 }
8408
8409 /*
8410 * Check for "nested" flag.
8411 */
8412 cmd = skipwhite(cmd);
8413 if (*cmd != NUL && STRNCMP(cmd, "nested", 6) == 0 && vim_iswhite(cmd[6]))
8414 {
8415 nested = TRUE;
8416 cmd = skipwhite(cmd + 6);
8417 }
8418
8419 /*
8420 * Find the start of the commands.
8421 * Expand <sfile> in it.
8422 */
8423 if (*cmd != NUL)
8424 {
8425 cmd = expand_sfile(cmd);
8426 if (cmd == NULL) /* some error */
8427 return;
8428 need_free = TRUE;
8429 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008430 }
8431
8432 /*
8433 * Print header when showing autocommands.
8434 */
8435 if (!forceit && *cmd == NUL)
8436 {
8437 /* Highlight title */
8438 MSG_PUTS_TITLE(_("\n--- Auto-Commands ---"));
8439 }
8440
8441 /*
8442 * Loop over the events.
8443 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008444 last_event = (event_T)-1; /* for listing the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008445 last_group = AUGROUP_ERROR; /* for listing the group name */
Bram Moolenaare99e8442016-07-26 20:43:40 +02008446 if (*arg == '*' || *arg == NUL || *arg == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008447 {
Bram Moolenaar754b5602006-02-09 23:53:20 +00008448 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8449 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008450 if (do_autocmd_event(event, pat,
8451 nested, cmd, forceit, group) == FAIL)
8452 break;
8453 }
8454 else
8455 {
Bram Moolenaare99e8442016-07-26 20:43:40 +02008456 while (*arg && *arg != '|' && !vim_iswhite(*arg))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008457 if (do_autocmd_event(event_name2nr(arg, &arg), pat,
8458 nested, cmd, forceit, group) == FAIL)
8459 break;
8460 }
8461
8462 if (need_free)
8463 vim_free(cmd);
8464 vim_free(envpat);
8465}
8466
8467/*
8468 * Find the group ID in a ":autocmd" or ":doautocmd" argument.
8469 * The "argp" argument is advanced to the following argument.
8470 *
8471 * Returns the group ID, AUGROUP_ERROR for error (out of memory).
8472 */
8473 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008474au_get_grouparg(char_u **argp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008475{
8476 char_u *group_name;
8477 char_u *p;
8478 char_u *arg = *argp;
8479 int group = AUGROUP_ALL;
8480
Bram Moolenaare99e8442016-07-26 20:43:40 +02008481 for (p = arg; *p && !vim_iswhite(*p) && *p != '|'; ++p)
8482 ;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008483 if (p > arg)
8484 {
8485 group_name = vim_strnsave(arg, (int)(p - arg));
8486 if (group_name == NULL) /* out of memory */
8487 return AUGROUP_ERROR;
8488 group = au_find_group(group_name);
8489 if (group == AUGROUP_ERROR)
8490 group = AUGROUP_ALL; /* no match, use all groups */
8491 else
8492 *argp = skipwhite(p); /* match, skip over group name */
8493 vim_free(group_name);
8494 }
8495 return group;
8496}
8497
8498/*
8499 * do_autocmd() for one event.
8500 * If *pat == NUL do for all patterns.
8501 * If *cmd == NUL show entries.
8502 * If forceit == TRUE delete entries.
8503 * If group is not AUGROUP_ALL, only use this group.
8504 */
8505 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008506do_autocmd_event(
8507 event_T event,
8508 char_u *pat,
8509 int nested,
8510 char_u *cmd,
8511 int forceit,
8512 int group)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008513{
8514 AutoPat *ap;
8515 AutoPat **prev_ap;
8516 AutoCmd *ac;
8517 AutoCmd **prev_ac;
8518 int brace_level;
8519 char_u *endpat;
8520 int findgroup;
8521 int allgroups;
8522 int patlen;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00008523 int is_buflocal;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008524 int buflocal_nr;
8525 char_u buflocal_pat[25]; /* for "<buffer=X>" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008526
8527 if (group == AUGROUP_ALL)
8528 findgroup = current_augroup;
8529 else
8530 findgroup = group;
8531 allgroups = (group == AUGROUP_ALL && !forceit && *cmd == NUL);
8532
8533 /*
8534 * Show or delete all patterns for an event.
8535 */
8536 if (*pat == NUL)
8537 {
8538 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8539 {
8540 if (forceit) /* delete the AutoPat, if it's in the current group */
8541 {
8542 if (ap->group == findgroup)
8543 au_remove_pat(ap);
8544 }
8545 else if (group == AUGROUP_ALL || ap->group == group)
8546 show_autocmd(ap, event);
8547 }
8548 }
8549
8550 /*
8551 * Loop through all the specified patterns.
8552 */
8553 for ( ; *pat; pat = (*endpat == ',' ? endpat + 1 : endpat))
8554 {
8555 /*
8556 * Find end of the pattern.
8557 * Watch out for a comma in braces, like "*.\{obj,o\}".
8558 */
8559 brace_level = 0;
8560 for (endpat = pat; *endpat && (*endpat != ',' || brace_level
Bram Moolenaar6b9be1b2015-07-28 13:33:45 +02008561 || (endpat > pat && endpat[-1] == '\\')); ++endpat)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008562 {
8563 if (*endpat == '{')
8564 brace_level++;
8565 else if (*endpat == '}')
8566 brace_level--;
8567 }
8568 if (pat == endpat) /* ignore single comma */
8569 continue;
8570 patlen = (int)(endpat - pat);
8571
8572 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008573 * detect special <buflocal[=X]> buffer-local patterns
8574 */
8575 is_buflocal = FALSE;
8576 buflocal_nr = 0;
8577
Bram Moolenaar1e997822015-02-17 16:04:57 +01008578 if (patlen >= 8 && STRNCMP(pat, "<buffer", 7) == 0
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008579 && pat[patlen - 1] == '>')
8580 {
Bram Moolenaar1e997822015-02-17 16:04:57 +01008581 /* "<buffer...>": Error will be printed only for addition.
8582 * printing and removing will proceed silently. */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008583 is_buflocal = TRUE;
8584 if (patlen == 8)
Bram Moolenaar1e997822015-02-17 16:04:57 +01008585 /* "<buffer>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008586 buflocal_nr = curbuf->b_fnum;
8587 else if (patlen > 9 && pat[7] == '=')
8588 {
Bram Moolenaar1e997822015-02-17 16:04:57 +01008589 if (patlen == 13 && STRNICMP(pat, "<buffer=abuf>", 13) == 0)
8590 /* "<buffer=abuf>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008591 buflocal_nr = autocmd_bufnr;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008592 else if (skipdigits(pat + 8) == pat + patlen - 1)
Bram Moolenaar1e997822015-02-17 16:04:57 +01008593 /* "<buffer=123>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008594 buflocal_nr = atoi((char *)pat + 8);
8595 }
8596 }
8597
8598 if (is_buflocal)
8599 {
8600 /* normalize pat into standard "<buffer>#N" form */
8601 sprintf((char *)buflocal_pat, "<buffer=%d>", buflocal_nr);
8602 pat = buflocal_pat; /* can modify pat and patlen */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008603 patlen = (int)STRLEN(buflocal_pat); /* but not endpat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008604 }
8605
8606 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008607 * Find AutoPat entries with this pattern.
8608 */
8609 prev_ap = &first_autopat[(int)event];
8610 while ((ap = *prev_ap) != NULL)
8611 {
8612 if (ap->pat != NULL)
8613 {
8614 /* Accept a pattern when:
8615 * - a group was specified and it's that group, or a group was
8616 * not specified and it's the current group, or a group was
8617 * not specified and we are listing
8618 * - the length of the pattern matches
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008619 * - the pattern matches.
8620 * For <buffer[=X]>, this condition works because we normalize
8621 * all buffer-local patterns.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008622 */
8623 if ((allgroups || ap->group == findgroup)
8624 && ap->patlen == patlen
8625 && STRNCMP(pat, ap->pat, patlen) == 0)
8626 {
8627 /*
8628 * Remove existing autocommands.
8629 * If adding any new autocmd's for this AutoPat, don't
8630 * delete the pattern from the autopat list, append to
8631 * this list.
8632 */
8633 if (forceit)
8634 {
8635 if (*cmd != NUL && ap->next == NULL)
8636 {
8637 au_remove_cmds(ap);
8638 break;
8639 }
8640 au_remove_pat(ap);
8641 }
8642
8643 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008644 * Show autocmd's for this autopat, or buflocals <buffer=X>
Bram Moolenaar071d4272004-06-13 20:20:40 +00008645 */
8646 else if (*cmd == NUL)
8647 show_autocmd(ap, event);
8648
8649 /*
8650 * Add autocmd to this autopat, if it's the last one.
8651 */
8652 else if (ap->next == NULL)
8653 break;
8654 }
8655 }
8656 prev_ap = &ap->next;
8657 }
8658
8659 /*
8660 * Add a new command.
8661 */
8662 if (*cmd != NUL)
8663 {
8664 /*
8665 * If the pattern we want to add a command to does appear at the
8666 * end of the list (or not is not in the list at all), add the
8667 * pattern at the end of the list.
8668 */
8669 if (ap == NULL)
8670 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008671 /* refuse to add buffer-local ap if buffer number is invalid */
8672 if (is_buflocal && (buflocal_nr == 0
8673 || buflist_findnr(buflocal_nr) == NULL))
8674 {
8675 EMSGN(_("E680: <buffer=%d>: invalid buffer number "),
8676 buflocal_nr);
8677 return FAIL;
8678 }
8679
Bram Moolenaar071d4272004-06-13 20:20:40 +00008680 ap = (AutoPat *)alloc((unsigned)sizeof(AutoPat));
8681 if (ap == NULL)
8682 return FAIL;
8683 ap->pat = vim_strnsave(pat, patlen);
8684 ap->patlen = patlen;
8685 if (ap->pat == NULL)
8686 {
8687 vim_free(ap);
8688 return FAIL;
8689 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008690
8691 if (is_buflocal)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008692 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008693 ap->buflocal_nr = buflocal_nr;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008694 ap->reg_prog = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008695 }
8696 else
8697 {
Bram Moolenaar748bf032005-02-02 23:04:36 +00008698 char_u *reg_pat;
8699
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008700 ap->buflocal_nr = 0;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008701 reg_pat = file_pat_to_reg_pat(pat, endpat,
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008702 &ap->allow_dirs, TRUE);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008703 if (reg_pat != NULL)
8704 ap->reg_prog = vim_regcomp(reg_pat, RE_MAGIC);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008705 vim_free(reg_pat);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008706 if (reg_pat == NULL || ap->reg_prog == NULL)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008707 {
8708 vim_free(ap->pat);
8709 vim_free(ap);
8710 return FAIL;
8711 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008712 }
8713 ap->cmds = NULL;
8714 *prev_ap = ap;
8715 ap->next = NULL;
8716 if (group == AUGROUP_ALL)
8717 ap->group = current_augroup;
8718 else
8719 ap->group = group;
8720 }
8721
8722 /*
8723 * Add the autocmd at the end of the AutoCmd list.
8724 */
8725 prev_ac = &(ap->cmds);
8726 while ((ac = *prev_ac) != NULL)
8727 prev_ac = &ac->next;
8728 ac = (AutoCmd *)alloc((unsigned)sizeof(AutoCmd));
8729 if (ac == NULL)
8730 return FAIL;
8731 ac->cmd = vim_strsave(cmd);
8732#ifdef FEAT_EVAL
8733 ac->scriptID = current_SID;
8734#endif
8735 if (ac->cmd == NULL)
8736 {
8737 vim_free(ac);
8738 return FAIL;
8739 }
8740 ac->next = NULL;
8741 *prev_ac = ac;
8742 ac->nested = nested;
8743 }
8744 }
8745
8746 au_cleanup(); /* may really delete removed patterns/commands now */
8747 return OK;
8748}
8749
8750/*
8751 * Implementation of ":doautocmd [group] event [fname]".
8752 * Return OK for success, FAIL for failure;
8753 */
8754 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008755do_doautocmd(
8756 char_u *arg,
Bram Moolenaar1610d052016-06-09 22:53:01 +02008757 int do_msg, /* give message for no matching autocmds? */
8758 int *did_something)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008759{
8760 char_u *fname;
8761 int nothing_done = TRUE;
8762 int group;
8763
Bram Moolenaar1610d052016-06-09 22:53:01 +02008764 if (did_something != NULL)
Bram Moolenaar76ae22f2016-06-13 20:00:29 +02008765 *did_something = FALSE;
Bram Moolenaar1610d052016-06-09 22:53:01 +02008766
Bram Moolenaar071d4272004-06-13 20:20:40 +00008767 /*
8768 * Check for a legal group name. If not, use AUGROUP_ALL.
8769 */
8770 group = au_get_grouparg(&arg);
8771 if (arg == NULL) /* out of memory */
8772 return FAIL;
8773
8774 if (*arg == '*')
8775 {
8776 EMSG(_("E217: Can't execute autocommands for ALL events"));
8777 return FAIL;
8778 }
8779
8780 /*
8781 * Scan over the events.
8782 * If we find an illegal name, return here, don't do anything.
8783 */
8784 fname = find_end_event(arg, group != AUGROUP_ALL);
8785 if (fname == NULL)
8786 return FAIL;
8787
8788 fname = skipwhite(fname);
8789
8790 /*
8791 * Loop over the events.
8792 */
8793 while (*arg && !vim_iswhite(*arg))
8794 if (apply_autocmds_group(event_name2nr(arg, &arg),
8795 fname, NULL, TRUE, group, curbuf, NULL))
8796 nothing_done = FALSE;
8797
8798 if (nothing_done && do_msg)
8799 MSG(_("No matching autocommands"));
Bram Moolenaar1610d052016-06-09 22:53:01 +02008800 if (did_something != NULL)
8801 *did_something = !nothing_done;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008802
8803#ifdef FEAT_EVAL
8804 return aborting() ? FAIL : OK;
8805#else
8806 return OK;
8807#endif
8808}
8809
8810/*
8811 * ":doautoall": execute autocommands for each loaded buffer.
8812 */
8813 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008814ex_doautoall(exarg_T *eap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008815{
8816 int retval;
8817 aco_save_T aco;
8818 buf_T *buf;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008819 bufref_T bufref;
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008820 char_u *arg = eap->arg;
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008821 int call_do_modelines = check_nomodeline(&arg);
Bram Moolenaar1610d052016-06-09 22:53:01 +02008822 int did_aucmd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008823
8824 /*
8825 * This is a bit tricky: For some commands curwin->w_buffer needs to be
8826 * equal to curbuf, but for some buffers there may not be a window.
8827 * So we change the buffer for the current window for a moment. This
8828 * gives problems when the autocommands make changes to the list of
8829 * buffers or windows...
8830 */
Bram Moolenaar29323592016-07-24 22:04:11 +02008831 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008832 {
Bram Moolenaar3a847972008-07-08 09:36:58 +00008833 if (buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008834 {
8835 /* find a window for this buffer and save some values */
8836 aucmd_prepbuf(&aco, buf);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008837 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008838
8839 /* execute the autocommands for this buffer */
Bram Moolenaar1610d052016-06-09 22:53:01 +02008840 retval = do_doautocmd(arg, FALSE, &did_aucmd);
Bram Moolenaareeefcc72007-05-01 21:21:21 +00008841
Bram Moolenaar1610d052016-06-09 22:53:01 +02008842 if (call_do_modelines && did_aucmd)
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008843 {
8844 /* Execute the modeline settings, but don't set window-local
8845 * options if we are using the current window for another
8846 * buffer. */
8847 do_modelines(curwin == aucmd_win ? OPT_NOWIN : 0);
8848 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008849
8850 /* restore the current window */
8851 aucmd_restbuf(&aco);
8852
8853 /* stop if there is some error or buffer was deleted */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008854 if (retval == FAIL || !bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008855 break;
8856 }
8857 }
8858
8859 check_cursor(); /* just in case lines got deleted */
8860}
8861
8862/*
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008863 * Check *argp for <nomodeline>. When it is present return FALSE, otherwise
8864 * return TRUE and advance *argp to after it.
8865 * Thus return TRUE when do_modelines() should be called.
8866 */
8867 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008868check_nomodeline(char_u **argp)
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008869{
8870 if (STRNCMP(*argp, "<nomodeline>", 12) == 0)
8871 {
8872 *argp = skipwhite(*argp + 12);
8873 return FALSE;
8874 }
8875 return TRUE;
8876}
8877
8878/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008879 * Prepare for executing autocommands for (hidden) buffer "buf".
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008880 * Search for a visible window containing the current buffer. If there isn't
8881 * one then use "aucmd_win".
Bram Moolenaar071d4272004-06-13 20:20:40 +00008882 * Set "curbuf" and "curwin" to match "buf".
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00008883 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008884 */
8885 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008886aucmd_prepbuf(
8887 aco_save_T *aco, /* structure to save values in */
8888 buf_T *buf) /* new curbuf */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008889{
8890 win_T *win;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008891#ifdef FEAT_WINDOWS
8892 int save_ea;
8893#endif
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008894#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008895 int save_acd;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008896#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008897
8898 /* Find a window that is for the new buffer */
8899 if (buf == curbuf) /* be quick when buf is curbuf */
8900 win = curwin;
8901 else
8902#ifdef FEAT_WINDOWS
Bram Moolenaar29323592016-07-24 22:04:11 +02008903 FOR_ALL_WINDOWS(win)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008904 if (win->w_buffer == buf)
8905 break;
8906#else
8907 win = NULL;
8908#endif
8909
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008910 /* Allocate "aucmd_win" when needed. If this fails (out of memory) fall
8911 * back to using the current window. */
8912 if (win == NULL && aucmd_win == NULL)
8913 {
8914 win_alloc_aucmd_win();
8915 if (aucmd_win == NULL)
8916 win = curwin;
8917 }
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008918 if (win == NULL && aucmd_win_used)
8919 /* Strange recursive autocommand, fall back to using the current
8920 * window. Expect a few side effects... */
8921 win = curwin;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008922
8923 aco->save_curwin = curwin;
8924 aco->save_curbuf = curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008925 if (win != NULL)
8926 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008927 /* There is a window for "buf" in the current tab page, make it the
8928 * curwin. This is preferred, it has the least side effects (esp. if
8929 * "buf" is curbuf). */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008930 aco->use_aucmd_win = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008931 curwin = win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008932 }
8933 else
8934 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008935 /* There is no window for "buf", use "aucmd_win". To minimize the side
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02008936 * effects, insert it in the current tab page.
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008937 * Anything related to a window (e.g., setting folds) may have
8938 * unexpected results. */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008939 aco->use_aucmd_win = TRUE;
8940 aucmd_win_used = TRUE;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008941 aucmd_win->w_buffer = buf;
Bram Moolenaarcdddaa42010-06-07 23:07:44 +02008942 aucmd_win->w_s = &buf->b_s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008943 ++buf->b_nwindows;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008944 win_init_empty(aucmd_win); /* set cursor and topline to safe values */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008945
8946 /* Make sure w_localdir and globaldir are NULL to avoid a chdir() in
8947 * win_enter_ext(). */
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008948 vim_free(aucmd_win->w_localdir);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008949 aucmd_win->w_localdir = NULL;
8950 aco->globaldir = globaldir;
8951 globaldir = NULL;
8952
Bram Moolenaar071d4272004-06-13 20:20:40 +00008953
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008954#ifdef FEAT_WINDOWS
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008955 /* Split the current window, put the aucmd_win in the upper half.
8956 * We don't want the BufEnter or WinEnter autocommands. */
8957 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008958 make_snapshot(SNAP_AUCMD_IDX);
8959 save_ea = p_ea;
8960 p_ea = FALSE;
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008961
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008962# ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008963 /* Prevent chdir() call in win_enter_ext(), through do_autochdir(). */
8964 save_acd = p_acd;
8965 p_acd = FALSE;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008966# endif
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008967
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008968 (void)win_split_ins(0, WSP_TOP, aucmd_win, 0);
8969 (void)win_comp_pos(); /* recompute window positions */
8970 p_ea = save_ea;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008971# ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008972 p_acd = save_acd;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008973# endif
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008974 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008975#endif
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008976 curwin = aucmd_win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008977 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008978 curbuf = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008979 aco->new_curwin = curwin;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008980 set_bufref(&aco->new_curbuf, curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008981}
8982
8983/*
8984 * Cleanup after executing autocommands for a (hidden) buffer.
8985 * Restore the window as it was (if possible).
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00008986 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008987 */
8988 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008989aucmd_restbuf(
8990 aco_save_T *aco) /* structure holding saved values */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008991{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008992#ifdef FEAT_WINDOWS
8993 int dummy;
8994#endif
8995
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008996 if (aco->use_aucmd_win)
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008997 {
8998 --curbuf->b_nwindows;
8999#ifdef FEAT_WINDOWS
9000 /* Find "aucmd_win", it can't be closed, but it may be in another tab
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00009001 * page. Do not trigger autocommands here. */
9002 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009003 if (curwin != aucmd_win)
9004 {
9005 tabpage_T *tp;
9006 win_T *wp;
9007
9008 FOR_ALL_TAB_WINDOWS(tp, wp)
9009 {
9010 if (wp == aucmd_win)
9011 {
9012 if (tp != curtab)
Bram Moolenaar49e649f2013-05-06 04:50:35 +02009013 goto_tabpage_tp(tp, TRUE, TRUE);
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009014 win_goto(aucmd_win);
Bram Moolenaar28f29082012-02-11 23:45:37 +01009015 goto win_found;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009016 }
9017 }
9018 }
Bram Moolenaar28f29082012-02-11 23:45:37 +01009019win_found:
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009020
9021 /* Remove the window and frame from the tree of frames. */
9022 (void)winframe_remove(curwin, &dummy, NULL);
9023 win_remove(curwin, NULL);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009024 aucmd_win_used = FALSE;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009025 last_status(FALSE); /* may need to remove last status line */
9026 restore_snapshot(SNAP_AUCMD_IDX, FALSE);
9027 (void)win_comp_pos(); /* recompute window positions */
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00009028 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009029
9030 if (win_valid(aco->save_curwin))
9031 curwin = aco->save_curwin;
9032 else
9033 /* Hmm, original window disappeared. Just use the first one. */
9034 curwin = firstwin;
9035# ifdef FEAT_EVAL
Bram Moolenaar429fa852013-04-15 12:27:36 +02009036 vars_clear(&aucmd_win->w_vars->dv_hashtab); /* free all w: variables */
9037 hash_init(&aucmd_win->w_vars->dv_hashtab); /* re-use the hashtab */
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009038# endif
9039#else
9040 curwin = aco->save_curwin;
9041#endif
9042 curbuf = curwin->w_buffer;
9043
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009044 vim_free(globaldir);
9045 globaldir = aco->globaldir;
9046
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009047 /* the buffer contents may have changed */
9048 check_cursor();
9049 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
9050 {
9051 curwin->w_topline = curbuf->b_ml.ml_line_count;
9052#ifdef FEAT_DIFF
9053 curwin->w_topfill = 0;
9054#endif
9055 }
9056#if defined(FEAT_GUI)
9057 /* Hide the scrollbars from the aucmd_win and update. */
9058 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_LEFT], FALSE);
9059 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_RIGHT], FALSE);
9060 gui_may_update_scrollbars();
9061#endif
9062 }
9063 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00009064 {
9065 /* restore curwin */
9066#ifdef FEAT_WINDOWS
9067 if (win_valid(aco->save_curwin))
9068#endif
9069 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009070 /* Restore the buffer which was previously edited by curwin, if
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009071 * it was changed, we are still the same window and the buffer is
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009072 * valid. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009073 if (curwin == aco->new_curwin
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009074 && curbuf != aco->new_curbuf.br_buf
9075 && bufref_valid(&aco->new_curbuf)
9076 && aco->new_curbuf.br_buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009077 {
Bram Moolenaar7da9c372012-04-30 17:04:52 +02009078# if defined(FEAT_SYN_HL) || defined(FEAT_SPELL)
9079 if (curwin->w_s == &curbuf->b_s)
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009080 curwin->w_s = &aco->new_curbuf.br_buf->b_s;
Bram Moolenaar7da9c372012-04-30 17:04:52 +02009081# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009082 --curbuf->b_nwindows;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009083 curbuf = aco->new_curbuf.br_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009084 curwin->w_buffer = curbuf;
9085 ++curbuf->b_nwindows;
9086 }
9087
9088 curwin = aco->save_curwin;
9089 curbuf = curwin->w_buffer;
Bram Moolenaar371932a2014-09-09 16:59:38 +02009090 /* In case the autocommand move the cursor to a position that that
9091 * not exist in curbuf. */
9092 check_cursor();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009093 }
9094 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009095}
9096
9097static int autocmd_nested = FALSE;
9098
9099/*
9100 * Execute autocommands for "event" and file name "fname".
9101 * Return TRUE if some commands were executed.
9102 */
9103 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009104apply_autocmds(
9105 event_T event,
9106 char_u *fname, /* NULL or empty means use actual file name */
9107 char_u *fname_io, /* fname to use for <afile> on cmdline */
9108 int force, /* when TRUE, ignore autocmd_busy */
9109 buf_T *buf) /* buffer for <abuf> */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009110{
9111 return apply_autocmds_group(event, fname, fname_io, force,
9112 AUGROUP_ALL, buf, NULL);
9113}
9114
9115/*
9116 * Like apply_autocmds(), but with extra "eap" argument. This takes care of
9117 * setting v:filearg.
9118 */
9119 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009120apply_autocmds_exarg(
9121 event_T event,
9122 char_u *fname,
9123 char_u *fname_io,
9124 int force,
9125 buf_T *buf,
9126 exarg_T *eap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009127{
9128 return apply_autocmds_group(event, fname, fname_io, force,
9129 AUGROUP_ALL, buf, eap);
9130}
9131
9132/*
9133 * Like apply_autocmds(), but handles the caller's retval. If the script
9134 * processing is being aborted or if retval is FAIL when inside a try
9135 * conditional, no autocommands are executed. If otherwise the autocommands
9136 * cause the script to be aborted, retval is set to FAIL.
9137 */
9138 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009139apply_autocmds_retval(
9140 event_T event,
9141 char_u *fname, /* NULL or empty means use actual file name */
9142 char_u *fname_io, /* fname to use for <afile> on cmdline */
9143 int force, /* when TRUE, ignore autocmd_busy */
9144 buf_T *buf, /* buffer for <abuf> */
9145 int *retval) /* pointer to caller's retval */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009146{
9147 int did_cmd;
9148
Bram Moolenaar1e015462005-09-25 22:16:38 +00009149#ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00009150 if (should_abort(*retval))
9151 return FALSE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00009152#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009153
9154 did_cmd = apply_autocmds_group(event, fname, fname_io, force,
9155 AUGROUP_ALL, buf, NULL);
Bram Moolenaar1e015462005-09-25 22:16:38 +00009156 if (did_cmd
9157#ifdef FEAT_EVAL
9158 && aborting()
9159#endif
9160 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00009161 *retval = FAIL;
9162 return did_cmd;
9163}
9164
Bram Moolenaard35f9712005-12-18 22:02:33 +00009165/*
9166 * Return TRUE when there is a CursorHold autocommand defined.
9167 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009168 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009169has_cursorhold(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009170{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009171 return (first_autopat[(int)(get_real_state() == NORMAL_BUSY
9172 ? EVENT_CURSORHOLD : EVENT_CURSORHOLDI)] != NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009173}
Bram Moolenaard35f9712005-12-18 22:02:33 +00009174
9175/*
9176 * Return TRUE if the CursorHold event can be triggered.
9177 */
9178 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009179trigger_cursorhold(void)
Bram Moolenaard35f9712005-12-18 22:02:33 +00009180{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009181 int state;
9182
Bram Moolenaar05334432011-07-20 18:29:39 +02009183 if (!did_cursorhold
9184 && has_cursorhold()
9185 && !Recording
9186 && typebuf.tb_len == 0
Bram Moolenaard29a9ee2006-09-14 09:07:34 +00009187#ifdef FEAT_INS_EXPAND
9188 && !ins_compl_active()
9189#endif
9190 )
Bram Moolenaar754b5602006-02-09 23:53:20 +00009191 {
9192 state = get_real_state();
9193 if (state == NORMAL_BUSY || (state & INSERT) != 0)
9194 return TRUE;
9195 }
9196 return FALSE;
Bram Moolenaard35f9712005-12-18 22:02:33 +00009197}
Bram Moolenaar754b5602006-02-09 23:53:20 +00009198
9199/*
9200 * Return TRUE when there is a CursorMoved autocommand defined.
9201 */
9202 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009203has_cursormoved(void)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009204{
9205 return (first_autopat[(int)EVENT_CURSORMOVED] != NULL);
9206}
9207
9208/*
9209 * Return TRUE when there is a CursorMovedI autocommand defined.
9210 */
9211 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009212has_cursormovedI(void)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009213{
9214 return (first_autopat[(int)EVENT_CURSORMOVEDI] != NULL);
9215}
Bram Moolenaar071d4272004-06-13 20:20:40 +00009216
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009217/*
Bram Moolenaar186628f2013-03-19 13:33:23 +01009218 * Return TRUE when there is a TextChanged autocommand defined.
9219 */
9220 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009221has_textchanged(void)
Bram Moolenaar186628f2013-03-19 13:33:23 +01009222{
9223 return (first_autopat[(int)EVENT_TEXTCHANGED] != NULL);
9224}
9225
9226/*
9227 * Return TRUE when there is a TextChangedI autocommand defined.
9228 */
9229 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009230has_textchangedI(void)
Bram Moolenaar186628f2013-03-19 13:33:23 +01009231{
9232 return (first_autopat[(int)EVENT_TEXTCHANGEDI] != NULL);
9233}
9234
9235/*
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009236 * Return TRUE when there is an InsertCharPre autocommand defined.
9237 */
9238 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009239has_insertcharpre(void)
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009240{
9241 return (first_autopat[(int)EVENT_INSERTCHARPRE] != NULL);
9242}
9243
Bram Moolenaard5005162014-08-22 23:05:54 +02009244/*
9245 * Return TRUE when there is an CmdUndefined autocommand defined.
9246 */
9247 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009248has_cmdundefined(void)
Bram Moolenaard5005162014-08-22 23:05:54 +02009249{
9250 return (first_autopat[(int)EVENT_CMDUNDEFINED] != NULL);
9251}
9252
9253/*
9254 * Return TRUE when there is an FuncUndefined autocommand defined.
9255 */
9256 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009257has_funcundefined(void)
Bram Moolenaard5005162014-08-22 23:05:54 +02009258{
9259 return (first_autopat[(int)EVENT_FUNCUNDEFINED] != NULL);
9260}
9261
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009262/*
9263 * Execute autocommands for "event" and file name "fname".
9264 * Return TRUE if some commands were executed.
9265 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009266 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009267apply_autocmds_group(
9268 event_T event,
9269 char_u *fname, /* NULL or empty means use actual file name */
9270 char_u *fname_io, /* fname to use for <afile> on cmdline, NULL means
Bram Moolenaar071d4272004-06-13 20:20:40 +00009271 use fname */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009272 int force, /* when TRUE, ignore autocmd_busy */
9273 int group, /* group ID, or AUGROUP_ALL */
9274 buf_T *buf, /* buffer for <abuf> */
9275 exarg_T *eap) /* command arguments */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009276{
9277 char_u *sfname = NULL; /* short file name */
9278 char_u *tail;
9279 int save_changed;
9280 buf_T *old_curbuf;
9281 int retval = FALSE;
9282 char_u *save_sourcing_name;
9283 linenr_T save_sourcing_lnum;
9284 char_u *save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009285 int save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009286 int save_autocmd_bufnr;
9287 char_u *save_autocmd_match;
9288 int save_autocmd_busy;
9289 int save_autocmd_nested;
9290 static int nesting = 0;
9291 AutoPatCmd patcmd;
9292 AutoPat *ap;
9293#ifdef FEAT_EVAL
9294 scid_T save_current_SID;
9295 void *save_funccalp;
9296 char_u *save_cmdarg;
9297 long save_cmdbang;
9298#endif
9299 static int filechangeshell_busy = FALSE;
Bram Moolenaar05159a02005-02-26 23:04:13 +00009300#ifdef FEAT_PROFILE
9301 proftime_T wait_time;
9302#endif
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009303 int did_save_redobuff = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009304
9305 /*
9306 * Quickly return if there are no autocommands for this event or
9307 * autocommands are blocked.
9308 */
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009309 if (first_autopat[(int)event] == NULL || autocmd_blocked > 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009310 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009311
9312 /*
9313 * When autocommands are busy, new autocommands are only executed when
9314 * explicitly enabled with the "nested" flag.
9315 */
9316 if (autocmd_busy && !(force || autocmd_nested))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009317 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009318
9319#ifdef FEAT_EVAL
9320 /*
Bram Moolenaar7263a772007-05-10 17:35:54 +00009321 * Quickly return when immediately aborting on error, or when an interrupt
Bram Moolenaar071d4272004-06-13 20:20:40 +00009322 * occurred or an exception was thrown but not caught.
9323 */
9324 if (aborting())
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009325 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009326#endif
9327
9328 /*
9329 * FileChangedShell never nests, because it can create an endless loop.
9330 */
Bram Moolenaar56718732006-03-15 22:53:57 +00009331 if (filechangeshell_busy && (event == EVENT_FILECHANGEDSHELL
9332 || event == EVENT_FILECHANGEDSHELLPOST))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009333 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009334
9335 /*
9336 * Ignore events in 'eventignore'.
9337 */
9338 if (event_ignored(event))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009339 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009340
9341 /*
9342 * Allow nesting of autocommands, but restrict the depth, because it's
9343 * possible to create an endless loop.
9344 */
9345 if (nesting == 10)
9346 {
9347 EMSG(_("E218: autocommand nesting too deep"));
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009348 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009349 }
9350
9351 /*
9352 * Check if these autocommands are disabled. Used when doing ":all" or
9353 * ":ball".
9354 */
9355 if ( (autocmd_no_enter
9356 && (event == EVENT_WINENTER || event == EVENT_BUFENTER))
9357 || (autocmd_no_leave
9358 && (event == EVENT_WINLEAVE || event == EVENT_BUFLEAVE)))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009359 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009360
9361 /*
9362 * Save the autocmd_* variables and info about the current buffer.
9363 */
9364 save_autocmd_fname = autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009365 save_autocmd_fname_full = autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009366 save_autocmd_bufnr = autocmd_bufnr;
9367 save_autocmd_match = autocmd_match;
9368 save_autocmd_busy = autocmd_busy;
9369 save_autocmd_nested = autocmd_nested;
9370 save_changed = curbuf->b_changed;
9371 old_curbuf = curbuf;
9372
9373 /*
9374 * Set the file name to be used for <afile>.
Bram Moolenaara0174af2008-01-02 20:08:25 +00009375 * Make a copy to avoid that changing a buffer name or directory makes it
9376 * invalid.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009377 */
9378 if (fname_io == NULL)
9379 {
Bram Moolenaar53744302015-07-17 17:38:22 +02009380 if (event == EVENT_COLORSCHEME || event == EVENT_OPTIONSET)
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009381 autocmd_fname = NULL;
9382 else if (fname != NULL && *fname != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009383 autocmd_fname = fname;
9384 else if (buf != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009385 autocmd_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009386 else
9387 autocmd_fname = NULL;
9388 }
9389 else
9390 autocmd_fname = fname_io;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009391 if (autocmd_fname != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009392 autocmd_fname = vim_strsave(autocmd_fname);
9393 autocmd_fname_full = FALSE; /* call FullName_save() later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009394
9395 /*
9396 * Set the buffer number to be used for <abuf>.
9397 */
9398 if (buf == NULL)
9399 autocmd_bufnr = 0;
9400 else
9401 autocmd_bufnr = buf->b_fnum;
9402
9403 /*
9404 * When the file name is NULL or empty, use the file name of buffer "buf".
9405 * Always use the full path of the file name to match with, in case
9406 * "allow_dirs" is set.
9407 */
9408 if (fname == NULL || *fname == NUL)
9409 {
9410 if (buf == NULL)
9411 fname = NULL;
9412 else
9413 {
9414#ifdef FEAT_SYN_HL
9415 if (event == EVENT_SYNTAX)
9416 fname = buf->b_p_syn;
9417 else
9418#endif
9419 if (event == EVENT_FILETYPE)
9420 fname = buf->b_p_ft;
9421 else
9422 {
9423 if (buf->b_sfname != NULL)
9424 sfname = vim_strsave(buf->b_sfname);
9425 fname = buf->b_ffname;
9426 }
9427 }
9428 if (fname == NULL)
9429 fname = (char_u *)"";
9430 fname = vim_strsave(fname); /* make a copy, so we can change it */
9431 }
9432 else
9433 {
9434 sfname = vim_strsave(fname);
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009435 /* Don't try expanding FileType, Syntax, FuncUndefined, WindowID,
9436 * ColorScheme or QuickFixCmd* */
Bram Moolenaar7c626922005-02-07 22:01:03 +00009437 if (event == EVENT_FILETYPE
9438 || event == EVENT_SYNTAX
Bram Moolenaar5135d462009-04-29 16:03:38 +00009439 || event == EVENT_FUNCUNDEFINED
Bram Moolenaar7c626922005-02-07 22:01:03 +00009440 || event == EVENT_REMOTEREPLY
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00009441 || event == EVENT_SPELLFILEMISSING
Bram Moolenaar7c626922005-02-07 22:01:03 +00009442 || event == EVENT_QUICKFIXCMDPRE
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009443 || event == EVENT_COLORSCHEME
Bram Moolenaar53744302015-07-17 17:38:22 +02009444 || event == EVENT_OPTIONSET
Bram Moolenaar7c626922005-02-07 22:01:03 +00009445 || event == EVENT_QUICKFIXCMDPOST)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009446 fname = vim_strsave(fname);
9447 else
9448 fname = FullName_save(fname, FALSE);
9449 }
9450 if (fname == NULL) /* out of memory */
9451 {
9452 vim_free(sfname);
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009453 retval = FALSE;
9454 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009455 }
9456
9457#ifdef BACKSLASH_IN_FILENAME
9458 /*
9459 * Replace all backslashes with forward slashes. This makes the
9460 * autocommand patterns portable between Unix and MS-DOS.
9461 */
9462 if (sfname != NULL)
9463 forward_slash(sfname);
9464 forward_slash(fname);
9465#endif
9466
9467#ifdef VMS
9468 /* remove version for correct match */
9469 if (sfname != NULL)
9470 vms_remove_version(sfname);
9471 vms_remove_version(fname);
9472#endif
9473
9474 /*
9475 * Set the name to be used for <amatch>.
9476 */
9477 autocmd_match = fname;
9478
9479
9480 /* Don't redraw while doing auto commands. */
9481 ++RedrawingDisabled;
9482 save_sourcing_name = sourcing_name;
9483 sourcing_name = NULL; /* don't free this one */
9484 save_sourcing_lnum = sourcing_lnum;
9485 sourcing_lnum = 0; /* no line number here */
9486
9487#ifdef FEAT_EVAL
9488 save_current_SID = current_SID;
9489
Bram Moolenaar05159a02005-02-26 23:04:13 +00009490# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009491 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009492 prof_child_enter(&wait_time); /* doesn't count for the caller itself */
9493# endif
9494
Bram Moolenaar071d4272004-06-13 20:20:40 +00009495 /* Don't use local function variables, if called from a function */
9496 save_funccalp = save_funccal();
9497#endif
9498
9499 /*
9500 * When starting to execute autocommands, save the search patterns.
9501 */
9502 if (!autocmd_busy)
9503 {
9504 save_search_patterns();
Bram Moolenaar20ad69c2015-12-03 13:52:52 +01009505#ifdef FEAT_INS_EXPAND
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009506 if (!ins_compl_active())
Bram Moolenaar20ad69c2015-12-03 13:52:52 +01009507#endif
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009508 {
9509 saveRedobuff();
9510 did_save_redobuff = TRUE;
9511 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009512 did_filetype = keep_filetype;
9513 }
9514
9515 /*
9516 * Note that we are applying autocmds. Some commands need to know.
9517 */
9518 autocmd_busy = TRUE;
9519 filechangeshell_busy = (event == EVENT_FILECHANGEDSHELL);
9520 ++nesting; /* see matching decrement below */
9521
9522 /* Remember that FileType was triggered. Used for did_filetype(). */
9523 if (event == EVENT_FILETYPE)
9524 did_filetype = TRUE;
9525
9526 tail = gettail(fname);
9527
9528 /* Find first autocommand that matches */
9529 patcmd.curpat = first_autopat[(int)event];
9530 patcmd.nextcmd = NULL;
9531 patcmd.group = group;
9532 patcmd.fname = fname;
9533 patcmd.sfname = sfname;
9534 patcmd.tail = tail;
9535 patcmd.event = event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009536 patcmd.arg_bufnr = autocmd_bufnr;
9537 patcmd.next = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009538 auto_next_pat(&patcmd, FALSE);
9539
9540 /* found one, start executing the autocommands */
9541 if (patcmd.curpat != NULL)
9542 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009543 /* add to active_apc_list */
9544 patcmd.next = active_apc_list;
9545 active_apc_list = &patcmd;
9546
Bram Moolenaar071d4272004-06-13 20:20:40 +00009547#ifdef FEAT_EVAL
9548 /* set v:cmdarg (only when there is a matching pattern) */
Bram Moolenaar22fcfad2016-07-01 18:17:26 +02009549 save_cmdbang = (long)get_vim_var_nr(VV_CMDBANG);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009550 if (eap != NULL)
9551 {
9552 save_cmdarg = set_cmdarg(eap, NULL);
9553 set_vim_var_nr(VV_CMDBANG, (long)eap->forceit);
9554 }
9555 else
9556 save_cmdarg = NULL; /* avoid gcc warning */
9557#endif
9558 retval = TRUE;
9559 /* mark the last pattern, to avoid an endless loop when more patterns
9560 * are added when executing autocommands */
9561 for (ap = patcmd.curpat; ap->next != NULL; ap = ap->next)
9562 ap->last = FALSE;
9563 ap->last = TRUE;
9564 check_lnums(TRUE); /* make sure cursor and topline are valid */
9565 do_cmdline(NULL, getnextac, (void *)&patcmd,
9566 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
9567#ifdef FEAT_EVAL
9568 if (eap != NULL)
9569 {
9570 (void)set_cmdarg(NULL, save_cmdarg);
9571 set_vim_var_nr(VV_CMDBANG, save_cmdbang);
9572 }
9573#endif
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009574 /* delete from active_apc_list */
9575 if (active_apc_list == &patcmd) /* just in case */
9576 active_apc_list = patcmd.next;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009577 }
9578
9579 --RedrawingDisabled;
9580 autocmd_busy = save_autocmd_busy;
9581 filechangeshell_busy = FALSE;
9582 autocmd_nested = save_autocmd_nested;
9583 vim_free(sourcing_name);
9584 sourcing_name = save_sourcing_name;
9585 sourcing_lnum = save_sourcing_lnum;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009586 vim_free(autocmd_fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009587 autocmd_fname = save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009588 autocmd_fname_full = save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009589 autocmd_bufnr = save_autocmd_bufnr;
9590 autocmd_match = save_autocmd_match;
9591#ifdef FEAT_EVAL
9592 current_SID = save_current_SID;
9593 restore_funccal(save_funccalp);
Bram Moolenaar05159a02005-02-26 23:04:13 +00009594# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009595 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009596 prof_child_exit(&wait_time);
9597# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009598#endif
9599 vim_free(fname);
9600 vim_free(sfname);
9601 --nesting; /* see matching increment above */
9602
9603 /*
9604 * When stopping to execute autocommands, restore the search patterns and
Bram Moolenaar3be85852014-06-12 14:01:31 +02009605 * the redo buffer. Free any buffers in the au_pending_free_buf list and
9606 * free any windows in the au_pending_free_win list.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009607 */
9608 if (!autocmd_busy)
9609 {
9610 restore_search_patterns();
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009611 if (did_save_redobuff)
9612 restoreRedobuff();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009613 did_filetype = FALSE;
Bram Moolenaar4c7ab1b2014-04-06 20:45:43 +02009614 while (au_pending_free_buf != NULL)
9615 {
9616 buf_T *b = au_pending_free_buf->b_next;
9617 vim_free(au_pending_free_buf);
9618 au_pending_free_buf = b;
9619 }
Bram Moolenaar3be85852014-06-12 14:01:31 +02009620 while (au_pending_free_win != NULL)
9621 {
9622 win_T *w = au_pending_free_win->w_next;
9623 vim_free(au_pending_free_win);
9624 au_pending_free_win = w;
9625 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009626 }
9627
9628 /*
9629 * Some events don't set or reset the Changed flag.
9630 * Check if still in the same buffer!
9631 */
9632 if (curbuf == old_curbuf
9633 && (event == EVENT_BUFREADPOST
9634 || event == EVENT_BUFWRITEPOST
9635 || event == EVENT_FILEAPPENDPOST
9636 || event == EVENT_VIMLEAVE
9637 || event == EVENT_VIMLEAVEPRE))
9638 {
9639#ifdef FEAT_TITLE
9640 if (curbuf->b_changed != save_changed)
9641 need_maketitle = TRUE;
9642#endif
9643 curbuf->b_changed = save_changed;
9644 }
9645
9646 au_cleanup(); /* may really delete removed patterns/commands now */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009647
9648BYPASS_AU:
9649 /* When wiping out a buffer make sure all its buffer-local autocommands
9650 * are deleted. */
9651 if (event == EVENT_BUFWIPEOUT && buf != NULL)
9652 aubuflocal_remove(buf);
9653
Bram Moolenaarc3691332016-04-20 12:49:49 +02009654 if (retval == OK && event == EVENT_FILETYPE)
9655 au_did_filetype = TRUE;
9656
Bram Moolenaar071d4272004-06-13 20:20:40 +00009657 return retval;
9658}
9659
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009660# ifdef FEAT_EVAL
9661static char_u *old_termresponse = NULL;
9662# endif
9663
9664/*
9665 * Block triggering autocommands until unblock_autocmd() is called.
9666 * Can be used recursively, so long as it's symmetric.
9667 */
9668 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009669block_autocmds(void)
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009670{
9671# ifdef FEAT_EVAL
9672 /* Remember the value of v:termresponse. */
9673 if (autocmd_blocked == 0)
9674 old_termresponse = get_vim_var_str(VV_TERMRESPONSE);
9675# endif
9676 ++autocmd_blocked;
9677}
9678
9679 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009680unblock_autocmds(void)
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009681{
9682 --autocmd_blocked;
9683
9684# ifdef FEAT_EVAL
9685 /* When v:termresponse was set while autocommands were blocked, trigger
9686 * the autocommands now. Esp. useful when executing a shell command
9687 * during startup (vimdiff). */
9688 if (autocmd_blocked == 0
9689 && get_vim_var_str(VV_TERMRESPONSE) != old_termresponse)
9690 apply_autocmds(EVENT_TERMRESPONSE, NULL, NULL, FALSE, curbuf);
9691# endif
9692}
9693
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009694 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009695is_autocmd_blocked(void)
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009696{
9697 return autocmd_blocked != 0;
9698}
9699
Bram Moolenaar071d4272004-06-13 20:20:40 +00009700/*
9701 * Find next autocommand pattern that matches.
9702 */
9703 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009704auto_next_pat(
9705 AutoPatCmd *apc,
9706 int stop_at_last) /* stop when 'last' flag is set */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009707{
9708 AutoPat *ap;
9709 AutoCmd *cp;
9710 char_u *name;
9711 char *s;
9712
9713 vim_free(sourcing_name);
9714 sourcing_name = NULL;
9715
9716 for (ap = apc->curpat; ap != NULL && !got_int; ap = ap->next)
9717 {
9718 apc->curpat = NULL;
9719
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009720 /* Only use a pattern when it has not been removed, has commands and
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009721 * the group matches. For buffer-local autocommands only check the
9722 * buffer number. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009723 if (ap->pat != NULL && ap->cmds != NULL
9724 && (apc->group == AUGROUP_ALL || apc->group == ap->group))
9725 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009726 /* execution-condition */
9727 if (ap->buflocal_nr == 0
Bram Moolenaardffa5b82014-11-19 16:38:07 +01009728 ? (match_file_pat(NULL, &ap->reg_prog, apc->fname,
Bram Moolenaar748bf032005-02-02 23:04:36 +00009729 apc->sfname, apc->tail, ap->allow_dirs))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009730 : ap->buflocal_nr == apc->arg_bufnr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009731 {
9732 name = event_nr2name(apc->event);
9733 s = _("%s Auto commands for \"%s\"");
9734 sourcing_name = alloc((unsigned)(STRLEN(s)
9735 + STRLEN(name) + ap->patlen + 1));
9736 if (sourcing_name != NULL)
9737 {
9738 sprintf((char *)sourcing_name, s,
9739 (char *)name, (char *)ap->pat);
9740 if (p_verbose >= 8)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009741 {
9742 verbose_enter();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009743 smsg((char_u *)_("Executing %s"), sourcing_name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009744 verbose_leave();
9745 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009746 }
9747
9748 apc->curpat = ap;
9749 apc->nextcmd = ap->cmds;
9750 /* mark last command */
9751 for (cp = ap->cmds; cp->next != NULL; cp = cp->next)
9752 cp->last = FALSE;
9753 cp->last = TRUE;
9754 }
9755 line_breakcheck();
9756 if (apc->curpat != NULL) /* found a match */
9757 break;
9758 }
9759 if (stop_at_last && ap->last)
9760 break;
9761 }
9762}
9763
9764/*
9765 * Get next autocommand command.
9766 * Called by do_cmdline() to get the next line for ":if".
9767 * Returns allocated string, or NULL for end of autocommands.
9768 */
Bram Moolenaar21691f82012-12-05 19:13:18 +01009769 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009770getnextac(int c UNUSED, void *cookie, int indent UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009771{
9772 AutoPatCmd *acp = (AutoPatCmd *)cookie;
9773 char_u *retval;
9774 AutoCmd *ac;
9775
9776 /* Can be called again after returning the last line. */
9777 if (acp->curpat == NULL)
9778 return NULL;
9779
9780 /* repeat until we find an autocommand to execute */
9781 for (;;)
9782 {
9783 /* skip removed commands */
9784 while (acp->nextcmd != NULL && acp->nextcmd->cmd == NULL)
9785 if (acp->nextcmd->last)
9786 acp->nextcmd = NULL;
9787 else
9788 acp->nextcmd = acp->nextcmd->next;
9789
9790 if (acp->nextcmd != NULL)
9791 break;
9792
9793 /* at end of commands, find next pattern that matches */
9794 if (acp->curpat->last)
9795 acp->curpat = NULL;
9796 else
9797 acp->curpat = acp->curpat->next;
9798 if (acp->curpat != NULL)
9799 auto_next_pat(acp, TRUE);
9800 if (acp->curpat == NULL)
9801 return NULL;
9802 }
9803
9804 ac = acp->nextcmd;
9805
9806 if (p_verbose >= 9)
9807 {
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009808 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009809 smsg((char_u *)_("autocommand %s"), ac->cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009810 msg_puts((char_u *)"\n"); /* don't overwrite this either */
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009811 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009812 }
9813 retval = vim_strsave(ac->cmd);
9814 autocmd_nested = ac->nested;
9815#ifdef FEAT_EVAL
9816 current_SID = ac->scriptID;
9817#endif
9818 if (ac->last)
9819 acp->nextcmd = NULL;
9820 else
9821 acp->nextcmd = ac->next;
9822 return retval;
9823}
9824
9825/*
9826 * Return TRUE if there is a matching autocommand for "fname".
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009827 * To account for buffer-local autocommands, function needs to know
9828 * in which buffer the file will be opened.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009829 */
9830 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009831has_autocmd(event_T event, char_u *sfname, buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009832{
9833 AutoPat *ap;
9834 char_u *fname;
9835 char_u *tail = gettail(sfname);
9836 int retval = FALSE;
9837
9838 fname = FullName_save(sfname, FALSE);
9839 if (fname == NULL)
9840 return FALSE;
9841
9842#ifdef BACKSLASH_IN_FILENAME
9843 /*
9844 * Replace all backslashes with forward slashes. This makes the
9845 * autocommand patterns portable between Unix and MS-DOS.
9846 */
9847 sfname = vim_strsave(sfname);
9848 if (sfname != NULL)
9849 forward_slash(sfname);
9850 forward_slash(fname);
9851#endif
9852
9853 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
9854 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009855 && (ap->buflocal_nr == 0
Bram Moolenaardffa5b82014-11-19 16:38:07 +01009856 ? match_file_pat(NULL, &ap->reg_prog,
Bram Moolenaar748bf032005-02-02 23:04:36 +00009857 fname, sfname, tail, ap->allow_dirs)
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009858 : buf != NULL && ap->buflocal_nr == buf->b_fnum
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009859 ))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009860 {
9861 retval = TRUE;
9862 break;
9863 }
9864
9865 vim_free(fname);
9866#ifdef BACKSLASH_IN_FILENAME
9867 vim_free(sfname);
9868#endif
9869
9870 return retval;
9871}
9872
9873#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
9874/*
9875 * Function given to ExpandGeneric() to obtain the list of autocommand group
9876 * names.
9877 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009878 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009879get_augroup_name(expand_T *xp UNUSED, int idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009880{
9881 if (idx == augroups.ga_len) /* add "END" add the end */
9882 return (char_u *)"END";
9883 if (idx >= augroups.ga_len) /* end of list */
9884 return NULL;
Bram Moolenaarb62cc362016-09-03 16:43:53 +02009885 if (AUGROUP_NAME(idx) == NULL || AUGROUP_NAME(idx) == get_deleted_augroup())
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02009886 /* skip deleted entries */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009887 return (char_u *)"";
9888 return AUGROUP_NAME(idx); /* return a name */
9889}
9890
9891static int include_groups = FALSE;
9892
9893 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009894set_context_in_autocmd(
9895 expand_T *xp,
9896 char_u *arg,
9897 int doautocmd) /* TRUE for :doauto*, FALSE for :autocmd */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009898{
9899 char_u *p;
9900 int group;
9901
9902 /* check for a group name, skip it if present */
9903 include_groups = FALSE;
9904 p = arg;
9905 group = au_get_grouparg(&arg);
9906 if (group == AUGROUP_ERROR)
9907 return NULL;
9908 /* If there only is a group name that's what we expand. */
9909 if (*arg == NUL && group != AUGROUP_ALL && !vim_iswhite(arg[-1]))
9910 {
9911 arg = p;
9912 group = AUGROUP_ALL;
9913 }
9914
9915 /* skip over event name */
9916 for (p = arg; *p != NUL && !vim_iswhite(*p); ++p)
9917 if (*p == ',')
9918 arg = p + 1;
9919 if (*p == NUL)
9920 {
9921 if (group == AUGROUP_ALL)
9922 include_groups = TRUE;
9923 xp->xp_context = EXPAND_EVENTS; /* expand event name */
9924 xp->xp_pattern = arg;
9925 return NULL;
9926 }
9927
9928 /* skip over pattern */
9929 arg = skipwhite(p);
9930 while (*arg && (!vim_iswhite(*arg) || arg[-1] == '\\'))
9931 arg++;
9932 if (*arg)
9933 return arg; /* expand (next) command */
9934
9935 if (doautocmd)
9936 xp->xp_context = EXPAND_FILES; /* expand file names */
9937 else
9938 xp->xp_context = EXPAND_NOTHING; /* pattern is not expanded */
9939 return NULL;
9940}
9941
9942/*
9943 * Function given to ExpandGeneric() to obtain the list of event names.
9944 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009945 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009946get_event_name(expand_T *xp UNUSED, int idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009947{
9948 if (idx < augroups.ga_len) /* First list group names, if wanted */
9949 {
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02009950 if (!include_groups || AUGROUP_NAME(idx) == NULL
Bram Moolenaarb62cc362016-09-03 16:43:53 +02009951 || AUGROUP_NAME(idx) == get_deleted_augroup())
Bram Moolenaar071d4272004-06-13 20:20:40 +00009952 return (char_u *)""; /* skip deleted entries */
9953 return AUGROUP_NAME(idx); /* return a name */
9954 }
9955 return (char_u *)event_names[idx - augroups.ga_len].name;
9956}
9957
9958#endif /* FEAT_CMDL_COMPL */
9959
9960/*
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009961 * Return TRUE if autocmd is supported.
9962 */
9963 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009964autocmd_supported(char_u *name)
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009965{
9966 char_u *p;
9967
9968 return (event_name2nr(name, &p) != NUM_EVENTS);
9969}
9970
9971/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00009972 * Return TRUE if an autocommand is defined for a group, event and
9973 * pattern: The group can be omitted to accept any group. "event" and "pattern"
9974 * can be NULL to accept any event and pattern. "pattern" can be NULL to accept
9975 * any pattern. Buffer-local patterns <buffer> or <buffer=N> are accepted.
9976 * Used for:
9977 * exists("#Group") or
9978 * exists("#Group#Event") or
9979 * exists("#Group#Event#pat") or
9980 * exists("#Event") or
9981 * exists("#Event#pat")
Bram Moolenaar071d4272004-06-13 20:20:40 +00009982 */
9983 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009984au_exists(char_u *arg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009985{
Bram Moolenaar195d6352005-12-19 22:08:24 +00009986 char_u *arg_save;
9987 char_u *pattern = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009988 char_u *event_name;
9989 char_u *p;
Bram Moolenaar754b5602006-02-09 23:53:20 +00009990 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009991 AutoPat *ap;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009992 buf_T *buflocal_buf = NULL;
Bram Moolenaar195d6352005-12-19 22:08:24 +00009993 int group;
9994 int retval = FALSE;
9995
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009996 /* Make a copy so that we can change the '#' chars to a NUL. */
Bram Moolenaar195d6352005-12-19 22:08:24 +00009997 arg_save = vim_strsave(arg);
9998 if (arg_save == NULL)
9999 return FALSE;
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010000 p = vim_strchr(arg_save, '#');
Bram Moolenaar195d6352005-12-19 22:08:24 +000010001 if (p != NULL)
10002 *p++ = NUL;
10003
10004 /* First, look for an autocmd group name */
10005 group = au_find_group(arg_save);
10006 if (group == AUGROUP_ERROR)
10007 {
10008 /* Didn't match a group name, assume the first argument is an event. */
10009 group = AUGROUP_ALL;
10010 event_name = arg_save;
10011 }
10012 else
10013 {
10014 if (p == NULL)
10015 {
10016 /* "Group": group name is present and it's recognized */
10017 retval = TRUE;
10018 goto theend;
10019 }
10020
10021 /* Must be "Group#Event" or "Group#Event#pat". */
10022 event_name = p;
10023 p = vim_strchr(event_name, '#');
10024 if (p != NULL)
10025 *p++ = NUL; /* "Group#Event#pat" */
10026 }
10027
10028 pattern = p; /* "pattern" is NULL when there is no pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010029
10030 /* find the index (enum) for the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010031 event = event_name2nr(event_name, &p);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010032
10033 /* return FALSE if the event name is not recognized */
Bram Moolenaar195d6352005-12-19 22:08:24 +000010034 if (event == NUM_EVENTS)
10035 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010036
10037 /* Find the first autocommand for this event.
10038 * If there isn't any, return FALSE;
10039 * If there is one and no pattern given, return TRUE; */
10040 ap = first_autopat[(int)event];
10041 if (ap == NULL)
Bram Moolenaar195d6352005-12-19 22:08:24 +000010042 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010043
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010044 /* if pattern is "<buffer>", special handling is needed which uses curbuf */
10045 /* for pattern "<buffer=N>, fnamecmp() will work fine */
Bram Moolenaar5b7880d2009-09-11 15:24:31 +000010046 if (pattern != NULL && STRICMP(pattern, "<buffer>") == 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010047 buflocal_buf = curbuf;
10048
Bram Moolenaar071d4272004-06-13 20:20:40 +000010049 /* Check if there is an autocommand with the given pattern. */
10050 for ( ; ap != NULL; ap = ap->next)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010051 /* only use a pattern when it has not been removed and has commands. */
10052 /* For buffer-local autocommands, fnamecmp() works fine. */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010053 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaar195d6352005-12-19 22:08:24 +000010054 && (group == AUGROUP_ALL || ap->group == group)
Bram Moolenaar5b7880d2009-09-11 15:24:31 +000010055 && (pattern == NULL
10056 || (buflocal_buf == NULL
10057 ? fnamecmp(ap->pat, pattern) == 0
10058 : ap->buflocal_nr == buflocal_buf->b_fnum)))
Bram Moolenaar195d6352005-12-19 22:08:24 +000010059 {
10060 retval = TRUE;
10061 break;
10062 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010063
Bram Moolenaar195d6352005-12-19 22:08:24 +000010064theend:
10065 vim_free(arg_save);
10066 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010067}
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010068
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010069#else /* FEAT_AUTOCMD */
10070
10071/*
10072 * Prepare for executing commands for (hidden) buffer "buf".
10073 * This is the non-autocommand version, it simply saves "curbuf" and sets
10074 * "curbuf" and "curwin" to match "buf".
10075 */
10076 void
Bram Moolenaard14e00e2016-01-31 17:30:51 +010010077aucmd_prepbuf(
10078 aco_save_T *aco, /* structure to save values in */
10079 buf_T *buf) /* new curbuf */
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010080{
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010081 aco->save_curbuf = curbuf;
10082 --curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010083 curbuf = buf;
10084 curwin->w_buffer = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010085 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010086}
10087
10088/*
10089 * Restore after executing commands for a (hidden) buffer.
10090 * This is the non-autocommand version.
10091 */
10092 void
Bram Moolenaard14e00e2016-01-31 17:30:51 +010010093aucmd_restbuf(
10094 aco_save_T *aco) /* structure holding saved values */
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010095{
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010096 --curbuf->b_nwindows;
10097 curbuf = aco->save_curbuf;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010098 curwin->w_buffer = curbuf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010099 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010100}
10101
Bram Moolenaar071d4272004-06-13 20:20:40 +000010102#endif /* FEAT_AUTOCMD */
10103
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010104
Bram Moolenaar071d4272004-06-13 20:20:40 +000010105#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN) || defined(PROTO)
10106/*
Bram Moolenaar748bf032005-02-02 23:04:36 +000010107 * Try matching a filename with a "pattern" ("prog" is NULL), or use the
10108 * precompiled regprog "prog" ("pattern" is NULL). That avoids calling
10109 * vim_regcomp() often.
Bram Moolenaar071d4272004-06-13 20:20:40 +000010110 * Used for autocommands and 'wildignore'.
10111 * Returns TRUE if there is a match, FALSE otherwise.
10112 */
Bram Moolenaardffa5b82014-11-19 16:38:07 +010010113 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010114match_file_pat(
10115 char_u *pattern, /* pattern to match with */
10116 regprog_T **prog, /* pre-compiled regprog or NULL */
10117 char_u *fname, /* full path of file name */
10118 char_u *sfname, /* short file name or NULL */
10119 char_u *tail, /* tail of path */
10120 int allow_dirs) /* allow matching with dir */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010121{
10122 regmatch_T regmatch;
10123 int result = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010124
Bram Moolenaar71afbfe2013-03-19 16:49:16 +010010125 regmatch.rm_ic = p_fic; /* ignore case if 'fileignorecase' is set */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010126 if (prog != NULL)
10127 regmatch.regprog = *prog;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010128 else
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010129 regmatch.regprog = vim_regcomp(pattern, RE_MAGIC);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010130
10131 /*
10132 * Try for a match with the pattern with:
10133 * 1. the full file name, when the pattern has a '/'.
10134 * 2. the short file name, when the pattern has a '/'.
10135 * 3. the tail of the file name, when the pattern has no '/'.
10136 */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010137 if (regmatch.regprog != NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +000010138 && ((allow_dirs
10139 && (vim_regexec(&regmatch, fname, (colnr_T)0)
10140 || (sfname != NULL
10141 && vim_regexec(&regmatch, sfname, (colnr_T)0))))
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010142 || (!allow_dirs && vim_regexec(&regmatch, tail, (colnr_T)0))))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010143 result = TRUE;
10144
Bram Moolenaardffa5b82014-11-19 16:38:07 +010010145 if (prog != NULL)
10146 *prog = regmatch.regprog;
10147 else
Bram Moolenaar473de612013-06-08 18:19:48 +020010148 vim_regfree(regmatch.regprog);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010149 return result;
10150}
10151#endif
10152
10153#if defined(FEAT_WILDIGN) || defined(PROTO)
10154/*
10155 * Return TRUE if a file matches with a pattern in "list".
10156 * "list" is a comma-separated list of patterns, like 'wildignore'.
10157 * "sfname" is the short file name or NULL, "ffname" the long file name.
10158 */
10159 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010160match_file_list(char_u *list, char_u *sfname, char_u *ffname)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010161{
10162 char_u buf[100];
10163 char_u *tail;
10164 char_u *regpat;
10165 char allow_dirs;
10166 int match;
10167 char_u *p;
10168
10169 tail = gettail(sfname);
10170
10171 /* try all patterns in 'wildignore' */
10172 p = list;
10173 while (*p)
10174 {
10175 copy_option_part(&p, buf, 100, ",");
10176 regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, FALSE);
10177 if (regpat == NULL)
10178 break;
Bram Moolenaar748bf032005-02-02 23:04:36 +000010179 match = match_file_pat(regpat, NULL, ffname, sfname,
10180 tail, (int)allow_dirs);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010181 vim_free(regpat);
10182 if (match)
10183 return TRUE;
10184 }
10185 return FALSE;
10186}
10187#endif
10188
10189/*
10190 * Convert the given pattern "pat" which has shell style wildcards in it, into
10191 * a regular expression, and return the result in allocated memory. If there
10192 * is a directory path separator to be matched, then TRUE is put in
10193 * allow_dirs, otherwise FALSE is put there -- webb.
10194 * Handle backslashes before special characters, like "\*" and "\ ".
10195 *
Bram Moolenaar071d4272004-06-13 20:20:40 +000010196 * Returns NULL when out of memory.
10197 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010198 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010199file_pat_to_reg_pat(
10200 char_u *pat,
10201 char_u *pat_end, /* first char after pattern or NULL */
10202 char *allow_dirs, /* Result passed back out in here */
10203 int no_bslash UNUSED) /* Don't use a backward slash as pathsep */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010204{
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010205 int size = 2; /* '^' at start, '$' at end */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010206 char_u *endp;
10207 char_u *reg_pat;
10208 char_u *p;
10209 int i;
10210 int nested = 0;
10211 int add_dollar = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010212
10213 if (allow_dirs != NULL)
10214 *allow_dirs = FALSE;
10215 if (pat_end == NULL)
10216 pat_end = pat + STRLEN(pat);
10217
Bram Moolenaar071d4272004-06-13 20:20:40 +000010218 for (p = pat; p < pat_end; p++)
10219 {
10220 switch (*p)
10221 {
10222 case '*':
10223 case '.':
10224 case ',':
10225 case '{':
10226 case '}':
10227 case '~':
10228 size += 2; /* extra backslash */
10229 break;
10230#ifdef BACKSLASH_IN_FILENAME
10231 case '\\':
10232 case '/':
10233 size += 4; /* could become "[\/]" */
10234 break;
10235#endif
10236 default:
10237 size++;
Bram Moolenaar2288afe2015-08-11 16:20:05 +020010238# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010239 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010240 {
10241 ++p;
10242 ++size;
10243 }
10244# endif
10245 break;
10246 }
10247 }
10248 reg_pat = alloc(size + 1);
10249 if (reg_pat == NULL)
10250 return NULL;
10251
Bram Moolenaar071d4272004-06-13 20:20:40 +000010252 i = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010253
10254 if (pat[0] == '*')
10255 while (pat[0] == '*' && pat < pat_end - 1)
10256 pat++;
10257 else
10258 reg_pat[i++] = '^';
10259 endp = pat_end - 1;
Bram Moolenaar8fee8782015-08-11 18:45:48 +020010260 if (endp >= pat && *endp == '*')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010261 {
10262 while (endp - pat > 0 && *endp == '*')
10263 endp--;
10264 add_dollar = FALSE;
10265 }
10266 for (p = pat; *p && nested >= 0 && p <= endp; p++)
10267 {
10268 switch (*p)
10269 {
10270 case '*':
10271 reg_pat[i++] = '.';
10272 reg_pat[i++] = '*';
Bram Moolenaar02743632005-07-25 20:42:36 +000010273 while (p[1] == '*') /* "**" matches like "*" */
10274 ++p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010275 break;
10276 case '.':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010277 case '~':
10278 reg_pat[i++] = '\\';
10279 reg_pat[i++] = *p;
10280 break;
10281 case '?':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010282 reg_pat[i++] = '.';
10283 break;
10284 case '\\':
10285 if (p[1] == NUL)
10286 break;
10287#ifdef BACKSLASH_IN_FILENAME
10288 if (!no_bslash)
10289 {
10290 /* translate:
10291 * "\x" to "\\x" e.g., "dir\file"
10292 * "\*" to "\\.*" e.g., "dir\*.c"
10293 * "\?" to "\\." e.g., "dir\??.c"
10294 * "\+" to "\+" e.g., "fileX\+.c"
10295 */
10296 if ((vim_isfilec(p[1]) || p[1] == '*' || p[1] == '?')
10297 && p[1] != '+')
10298 {
10299 reg_pat[i++] = '[';
10300 reg_pat[i++] = '\\';
10301 reg_pat[i++] = '/';
10302 reg_pat[i++] = ']';
10303 if (allow_dirs != NULL)
10304 *allow_dirs = TRUE;
10305 break;
10306 }
10307 }
10308#endif
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010309 /* Undo escaping from ExpandEscape():
10310 * foo\?bar -> foo?bar
10311 * foo\%bar -> foo%bar
10312 * foo\,bar -> foo,bar
10313 * foo\ bar -> foo bar
10314 * Don't unescape \, * and others that are also special in a
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010315 * regexp.
10316 * An escaped { must be unescaped since we use magic not
Bram Moolenaara946afe2013-08-02 15:22:39 +020010317 * verymagic. Use "\\\{n,m\}"" to get "\{n,m}".
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010318 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010319 if (*++p == '?'
10320#ifdef BACKSLASH_IN_FILENAME
10321 && no_bslash
10322#endif
10323 )
10324 reg_pat[i++] = '?';
10325 else
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010326 if (*p == ',' || *p == '%' || *p == '#'
Bram Moolenaar2288afe2015-08-11 16:20:05 +020010327 || vim_isspace(*p) || *p == '{' || *p == '}')
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010328 reg_pat[i++] = *p;
Bram Moolenaara946afe2013-08-02 15:22:39 +020010329 else if (*p == '\\' && p[1] == '\\' && p[2] == '{')
10330 {
10331 reg_pat[i++] = '\\';
10332 reg_pat[i++] = '{';
10333 p += 2;
10334 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010335 else
10336 {
10337 if (allow_dirs != NULL && vim_ispathsep(*p)
10338#ifdef BACKSLASH_IN_FILENAME
10339 && (!no_bslash || *p != '\\')
10340#endif
10341 )
10342 *allow_dirs = TRUE;
10343 reg_pat[i++] = '\\';
10344 reg_pat[i++] = *p;
10345 }
10346 break;
10347#ifdef BACKSLASH_IN_FILENAME
10348 case '/':
10349 reg_pat[i++] = '[';
10350 reg_pat[i++] = '\\';
10351 reg_pat[i++] = '/';
10352 reg_pat[i++] = ']';
10353 if (allow_dirs != NULL)
10354 *allow_dirs = TRUE;
10355 break;
10356#endif
10357 case '{':
10358 reg_pat[i++] = '\\';
10359 reg_pat[i++] = '(';
10360 nested++;
10361 break;
10362 case '}':
10363 reg_pat[i++] = '\\';
10364 reg_pat[i++] = ')';
10365 --nested;
10366 break;
10367 case ',':
10368 if (nested)
10369 {
10370 reg_pat[i++] = '\\';
10371 reg_pat[i++] = '|';
10372 }
10373 else
10374 reg_pat[i++] = ',';
10375 break;
10376 default:
10377# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010378 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010379 reg_pat[i++] = *p++;
10380 else
10381# endif
10382 if (allow_dirs != NULL && vim_ispathsep(*p))
10383 *allow_dirs = TRUE;
10384 reg_pat[i++] = *p;
10385 break;
10386 }
10387 }
10388 if (add_dollar)
10389 reg_pat[i++] = '$';
10390 reg_pat[i] = NUL;
10391 if (nested != 0)
10392 {
10393 if (nested < 0)
10394 EMSG(_("E219: Missing {."));
10395 else
10396 EMSG(_("E220: Missing }."));
10397 vim_free(reg_pat);
10398 reg_pat = NULL;
10399 }
10400 return reg_pat;
10401}
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010402
10403#if defined(EINTR) || defined(PROTO)
10404/*
10405 * Version of read() that retries when interrupted by EINTR (possibly
10406 * by a SIGWINCH).
10407 */
10408 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010409read_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010410{
10411 long ret;
10412
10413 for (;;)
10414 {
10415 ret = vim_read(fd, buf, bufsize);
10416 if (ret >= 0 || errno != EINTR)
10417 break;
10418 }
10419 return ret;
10420}
10421
10422/*
10423 * Version of write() that retries when interrupted by EINTR (possibly
10424 * by a SIGWINCH).
10425 */
10426 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010427write_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010428{
10429 long ret = 0;
10430 long wlen;
10431
10432 /* Repeat the write() so long it didn't fail, other than being interrupted
10433 * by a signal. */
10434 while (ret < (long)bufsize)
10435 {
Bram Moolenaar9c263032010-12-17 18:06:06 +010010436 wlen = vim_write(fd, (char *)buf + ret, bufsize - ret);
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010437 if (wlen < 0)
10438 {
10439 if (errno != EINTR)
10440 break;
10441 }
10442 else
10443 ret += wlen;
10444 }
10445 return ret;
10446}
10447#endif