blob: c5a3f2a8d15c4de8650e806aea3b77bb52078d2c [file] [log] [blame]
Bram Moolenaar071d4272004-06-13 20:20:40 +00001/* vi:set ts=8 sts=4 sw=4:
2 *
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
Bram Moolenaar941aea22015-12-11 17:14:27 +010030#if (defined(sun) || defined(__FreeBSD__)) && defined(S_ISCHR)
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +000031# define OPEN_CHR_FILES
32static int is_dev_fd_file(char_u *fname);
33#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000034#ifdef FEAT_MBYTE
Bram Moolenaard25c16e2016-01-29 22:13:30 +010035static char_u *next_fenc(char_u **pp);
Bram Moolenaar071d4272004-06-13 20:20:40 +000036# ifdef FEAT_EVAL
Bram Moolenaard25c16e2016-01-29 22:13:30 +010037static char_u *readfile_charconvert(char_u *fname, char_u *fenc, int *fdp);
Bram Moolenaar071d4272004-06-13 20:20:40 +000038# endif
39#endif
40#ifdef FEAT_VIMINFO
Bram Moolenaard25c16e2016-01-29 22:13:30 +010041static void check_marks_read(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +000042#endif
43#ifdef FEAT_CRYPT
Bram Moolenaard25c16e2016-01-29 22:13:30 +010044static 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 +000045#endif
46#ifdef UNIX
Bram Moolenaard25c16e2016-01-29 22:13:30 +010047static void set_file_time(char_u *fname, time_t atime, time_t mtime);
Bram Moolenaar071d4272004-06-13 20:20:40 +000048#endif
Bram Moolenaard25c16e2016-01-29 22:13:30 +010049static int set_rw_fname(char_u *fname, char_u *sfname);
50static int msg_add_fileformat(int eol_type);
51static void msg_add_eol(void);
52static int check_mtime(buf_T *buf, struct stat *s);
53static int time_differs(long t1, long t2);
Bram Moolenaar071d4272004-06-13 20:20:40 +000054#ifdef FEAT_AUTOCMD
Bram Moolenaard25c16e2016-01-29 22:13:30 +010055static int apply_autocmds_exarg(event_T event, char_u *fname, char_u *fname_io, int force, buf_T *buf, exarg_T *eap);
56static int au_find_group(char_u *name);
Bram Moolenaar70836c82006-02-20 21:28:49 +000057
58# define AUGROUP_DEFAULT -1 /* default autocmd group */
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +000059# define AUGROUP_ERROR -2 /* erroneous autocmd group */
Bram Moolenaar70836c82006-02-20 21:28:49 +000060# define AUGROUP_ALL -3 /* all autocmd groups */
Bram Moolenaar071d4272004-06-13 20:20:40 +000061#endif
62
63#if defined(FEAT_CRYPT) || defined(FEAT_MBYTE)
64# define HAS_BW_FLAGS
65# define FIO_LATIN1 0x01 /* convert Latin1 */
66# define FIO_UTF8 0x02 /* convert UTF-8 */
67# define FIO_UCS2 0x04 /* convert UCS-2 */
68# define FIO_UCS4 0x08 /* convert UCS-4 */
69# define FIO_UTF16 0x10 /* convert UTF-16 */
70# ifdef WIN3264
71# define FIO_CODEPAGE 0x20 /* convert MS-Windows codepage */
72# define FIO_PUT_CP(x) (((x) & 0xffff) << 16) /* put codepage in top word */
73# define FIO_GET_CP(x) (((x)>>16) & 0xffff) /* get codepage from top word */
74# endif
75# ifdef MACOS_X
76# define FIO_MACROMAN 0x20 /* convert MacRoman */
77# endif
78# define FIO_ENDIAN_L 0x80 /* little endian */
79# define FIO_ENCRYPTED 0x1000 /* encrypt written bytes */
80# define FIO_NOCONVERT 0x2000 /* skip encoding conversion */
81# define FIO_UCSBOM 0x4000 /* check for BOM at start of file */
82# define FIO_ALL -1 /* allow all formats */
83#endif
84
85/* When converting, a read() or write() may leave some bytes to be converted
86 * for the next call. The value is guessed... */
87#define CONV_RESTLEN 30
88
89/* We have to guess how much a sequence of bytes may expand when converting
90 * with iconv() to be able to allocate a buffer. */
91#define ICONV_MULT 8
92
93/*
94 * Structure to pass arguments from buf_write() to buf_write_bytes().
95 */
96struct bw_info
97{
98 int bw_fd; /* file descriptor */
99 char_u *bw_buf; /* buffer with data to be written */
Bram Moolenaard089d9b2007-09-30 12:02:55 +0000100 int bw_len; /* length of data */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000101#ifdef HAS_BW_FLAGS
102 int bw_flags; /* FIO_ flags */
103#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +0200104#ifdef FEAT_CRYPT
105 buf_T *bw_buffer; /* buffer being written */
106#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000107#ifdef FEAT_MBYTE
108 char_u bw_rest[CONV_RESTLEN]; /* not converted bytes */
109 int bw_restlen; /* nr of bytes in bw_rest[] */
110 int bw_first; /* first write call */
111 char_u *bw_conv_buf; /* buffer for writing converted chars */
112 int bw_conv_buflen; /* size of bw_conv_buf */
113 int bw_conv_error; /* set for conversion error */
Bram Moolenaar32b485f2009-07-29 16:06:27 +0000114 linenr_T bw_conv_error_lnum; /* first line with error or zero */
115 linenr_T bw_start_lnum; /* line number at start of buffer */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000116# ifdef USE_ICONV
117 iconv_t bw_iconv_fd; /* descriptor for iconv() or -1 */
118# endif
119#endif
120};
121
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100122static int buf_write_bytes(struct bw_info *ip);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000123
124#ifdef FEAT_MBYTE
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100125static linenr_T readfile_linenr(linenr_T linecnt, char_u *p, char_u *endp);
126static int ucs2bytes(unsigned c, char_u **pp, int flags);
127static int need_conversion(char_u *fenc);
128static int get_fio_flags(char_u *ptr);
129static char_u *check_for_bom(char_u *p, long size, int *lenp, int flags);
130static int make_bom(char_u *buf, char_u *name);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000131# ifdef WIN3264
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100132static int get_win_fio_flags(char_u *ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000133# endif
134# ifdef MACOS_X
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100135static int get_mac_fio_flags(char_u *ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000136# endif
137#endif
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100138static int move_lines(buf_T *frombuf, buf_T *tobuf);
Bram Moolenaar4592dee2009-11-18 19:11:58 +0000139#ifdef TEMPDIRNAMES
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100140static void vim_settempdir(char_u *tempdir);
Bram Moolenaar4592dee2009-11-18 19:11:58 +0000141#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000142#ifdef FEAT_AUTOCMD
143static char *e_auchangedbuf = N_("E812: Autocommands changed buffer or buffer name");
144#endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000145
Bram Moolenaar071d4272004-06-13 20:20:40 +0000146 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +0100147filemess(
148 buf_T *buf,
149 char_u *name,
150 char_u *s,
151 int attr)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000152{
153 int msg_scroll_save;
154
155 if (msg_silent != 0)
156 return;
157 msg_add_fname(buf, name); /* put file name in IObuff with quotes */
158 /* If it's extremely long, truncate it. */
159 if (STRLEN(IObuff) > IOSIZE - 80)
160 IObuff[IOSIZE - 80] = NUL;
161 STRCAT(IObuff, s);
162 /*
163 * For the first message may have to start a new line.
164 * For further ones overwrite the previous one, reset msg_scroll before
165 * calling filemess().
166 */
167 msg_scroll_save = msg_scroll;
168 if (shortmess(SHM_OVERALL) && !exiting && p_verbose == 0)
169 msg_scroll = FALSE;
170 if (!msg_scroll) /* wait a bit when overwriting an error msg */
171 check_for_delay(FALSE);
172 msg_start();
173 msg_scroll = msg_scroll_save;
174 msg_scrolled_ign = TRUE;
175 /* may truncate the message to avoid a hit-return prompt */
176 msg_outtrans_attr(msg_may_trunc(FALSE, IObuff), attr);
177 msg_clr_eos();
178 out_flush();
179 msg_scrolled_ign = FALSE;
180}
181
182/*
183 * Read lines from file "fname" into the buffer after line "from".
184 *
185 * 1. We allocate blocks with lalloc, as big as possible.
186 * 2. Each block is filled with characters from the file with a single read().
187 * 3. The lines are inserted in the buffer with ml_append().
188 *
189 * (caller must check that fname != NULL, unless READ_STDIN is used)
190 *
191 * "lines_to_skip" is the number of lines that must be skipped
192 * "lines_to_read" is the number of lines that are appended
193 * When not recovering lines_to_skip is 0 and lines_to_read MAXLNUM.
194 *
195 * flags:
196 * READ_NEW starting to edit a new buffer
197 * READ_FILTER reading filter output
198 * READ_STDIN read from stdin instead of a file
199 * READ_BUFFER read from curbuf instead of a file (converting after reading
200 * stdin)
201 * READ_DUMMY read into a dummy buffer (to check if file contents changed)
Bram Moolenaar59f931e2010-07-24 20:27:03 +0200202 * READ_KEEP_UNDO don't clear undo info or read it from a file
Bram Moolenaar071d4272004-06-13 20:20:40 +0000203 *
204 * return FAIL for failure, OK otherwise
205 */
206 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +0100207readfile(
208 char_u *fname,
209 char_u *sfname,
210 linenr_T from,
211 linenr_T lines_to_skip,
212 linenr_T lines_to_read,
213 exarg_T *eap, /* can be NULL! */
214 int flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000215{
216 int fd = 0;
217 int newfile = (flags & READ_NEW);
218 int check_readonly;
219 int filtering = (flags & READ_FILTER);
220 int read_stdin = (flags & READ_STDIN);
221 int read_buffer = (flags & READ_BUFFER);
Bram Moolenaar690ffc02008-01-04 15:31:21 +0000222 int set_options = newfile || read_buffer
223 || (eap != NULL && eap->read_edit);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000224 linenr_T read_buf_lnum = 1; /* next line to read from curbuf */
225 colnr_T read_buf_col = 0; /* next char to read from this line */
226 char_u c;
227 linenr_T lnum = from;
228 char_u *ptr = NULL; /* pointer into read buffer */
229 char_u *buffer = NULL; /* read buffer */
230 char_u *new_buffer = NULL; /* init to shut up gcc */
231 char_u *line_start = NULL; /* init to shut up gcc */
232 int wasempty; /* buffer was empty before reading */
233 colnr_T len;
234 long size = 0;
235 char_u *p;
Bram Moolenaar914703b2010-05-31 21:59:46 +0200236 off_t filesize = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000237 int skip_read = FALSE;
238#ifdef FEAT_CRYPT
239 char_u *cryptkey = NULL;
Bram Moolenaarf50a2532010-05-21 15:36:08 +0200240 int did_ask_for_key = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000241#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +0200242#ifdef FEAT_PERSISTENT_UNDO
243 context_sha256_T sha_ctx;
244 int read_undo_file = FALSE;
245#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000246 int split = 0; /* number of split lines */
247#define UNKNOWN 0x0fffffff /* file size is unknown */
248 linenr_T linecnt;
249 int error = FALSE; /* errors encountered */
250 int ff_error = EOL_UNKNOWN; /* file format with errors */
251 long linerest = 0; /* remaining chars in line */
252#ifdef UNIX
253 int perm = 0;
254 int swap_mode = -1; /* protection bits for swap file */
255#else
256 int perm;
257#endif
258 int fileformat = 0; /* end-of-line format */
259 int keep_fileformat = FALSE;
260 struct stat st;
261 int file_readonly;
262 linenr_T skip_count = 0;
263 linenr_T read_count = 0;
264 int msg_save = msg_scroll;
265 linenr_T read_no_eol_lnum = 0; /* non-zero lnum when last line of
266 * last read was missing the eol */
267 int try_mac = (vim_strchr(p_ffs, 'm') != NULL);
268 int try_dos = (vim_strchr(p_ffs, 'd') != NULL);
269 int try_unix = (vim_strchr(p_ffs, 'x') != NULL);
270 int file_rewind = FALSE;
271#ifdef FEAT_MBYTE
272 int can_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000273 linenr_T conv_error = 0; /* line nr with conversion error */
274 linenr_T illegal_byte = 0; /* line nr with illegal byte */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000275 int keep_dest_enc = FALSE; /* don't retry when char doesn't fit
276 in destination encoding */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000277 int bad_char_behavior = BAD_REPLACE;
278 /* BAD_KEEP, BAD_DROP or character to
279 * replace with */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000280 char_u *tmpname = NULL; /* name of 'charconvert' output file */
281 int fio_flags = 0;
282 char_u *fenc; /* fileencoding to use */
283 int fenc_alloced; /* fenc_next is in allocated memory */
284 char_u *fenc_next = NULL; /* next item in 'fencs' or NULL */
285 int advance_fenc = FALSE;
286 long real_size = 0;
287# ifdef USE_ICONV
288 iconv_t iconv_fd = (iconv_t)-1; /* descriptor for iconv() or -1 */
289# ifdef FEAT_EVAL
290 int did_iconv = FALSE; /* TRUE when iconv() failed and trying
291 'charconvert' next */
292# endif
293# endif
294 int converted = FALSE; /* TRUE if conversion done */
295 int notconverted = FALSE; /* TRUE if conversion wanted but it
296 wasn't possible */
297 char_u conv_rest[CONV_RESTLEN];
298 int conv_restlen = 0; /* nr of bytes in conv_rest[] */
299#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000300#ifdef FEAT_AUTOCMD
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200301 buf_T *old_curbuf;
302 char_u *old_b_ffname;
303 char_u *old_b_fname;
304 int using_b_ffname;
305 int using_b_fname;
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000306#endif
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200307
Bram Moolenaarcab35ad2011-02-15 17:39:22 +0100308 curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000309
310 /*
311 * If there is no file name yet, use the one for the read file.
312 * BF_NOTEDITED is set to reflect this.
313 * Don't do this for a read from a filter.
314 * Only do this when 'cpoptions' contains the 'f' flag.
315 */
316 if (curbuf->b_ffname == NULL
317 && !filtering
318 && fname != NULL
319 && vim_strchr(p_cpo, CPO_FNAMER) != NULL
320 && !(flags & READ_DUMMY))
321 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000322 if (set_rw_fname(fname, sfname) == FAIL)
323 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000324 }
325
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200326#ifdef FEAT_AUTOCMD
327 /* Remember the initial values of curbuf, curbuf->b_ffname and
328 * curbuf->b_fname to detect whether they are altered as a result of
329 * executing nasty autocommands. Also check if "fname" and "sfname"
330 * point to one of these values. */
331 old_curbuf = curbuf;
332 old_b_ffname = curbuf->b_ffname;
333 old_b_fname = curbuf->b_fname;
334 using_b_ffname = (fname == curbuf->b_ffname)
335 || (sfname == curbuf->b_ffname);
336 using_b_fname = (fname == curbuf->b_fname) || (sfname == curbuf->b_fname);
337#endif
338
Bram Moolenaardf177f62005-02-22 08:39:57 +0000339 /* After reading a file the cursor line changes but we don't want to
340 * display the line. */
341 ex_no_reprint = TRUE;
342
Bram Moolenaar55b7cf82006-09-09 12:52:42 +0000343 /* don't display the file info for another buffer now */
344 need_fileinfo = FALSE;
345
Bram Moolenaar071d4272004-06-13 20:20:40 +0000346 /*
347 * For Unix: Use the short file name whenever possible.
348 * Avoids problems with networks and when directory names are changed.
349 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
350 * another directory, which we don't detect.
351 */
352 if (sfname == NULL)
353 sfname = fname;
354#if defined(UNIX) || defined(__EMX__)
355 fname = sfname;
356#endif
357
358#ifdef FEAT_AUTOCMD
359 /*
360 * The BufReadCmd and FileReadCmd events intercept the reading process by
361 * executing the associated commands instead.
362 */
363 if (!filtering && !read_stdin && !read_buffer)
364 {
365 pos_T pos;
366
367 pos = curbuf->b_op_start;
368
369 /* Set '[ mark to the line above where the lines go (line 1 if zero). */
370 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
371 curbuf->b_op_start.col = 0;
372
373 if (newfile)
374 {
375 if (apply_autocmds_exarg(EVENT_BUFREADCMD, NULL, sfname,
376 FALSE, curbuf, eap))
377#ifdef FEAT_EVAL
378 return aborting() ? FAIL : OK;
379#else
380 return OK;
381#endif
382 }
383 else if (apply_autocmds_exarg(EVENT_FILEREADCMD, sfname, sfname,
384 FALSE, NULL, eap))
385#ifdef FEAT_EVAL
386 return aborting() ? FAIL : OK;
387#else
388 return OK;
389#endif
390
391 curbuf->b_op_start = pos;
392 }
393#endif
394
395 if ((shortmess(SHM_OVER) || curbuf->b_help) && p_verbose == 0)
396 msg_scroll = FALSE; /* overwrite previous file message */
397 else
398 msg_scroll = TRUE; /* don't overwrite previous file message */
399
400 /*
401 * If the name ends in a path separator, we can't open it. Check here,
402 * because reading the file may actually work, but then creating the swap
403 * file may destroy it! Reported on MS-DOS and Win 95.
404 * If the name is too long we might crash further on, quit here.
405 */
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000406 if (fname != NULL && *fname != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000407 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000408 p = fname + STRLEN(fname);
409 if (after_pathsep(fname, p) || STRLEN(fname) >= MAXPATHL)
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000410 {
411 filemess(curbuf, fname, (char_u *)_("Illegal file name"), 0);
412 msg_end();
413 msg_scroll = msg_save;
414 return FAIL;
415 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000416 }
417
Bram Moolenaar071d4272004-06-13 20:20:40 +0000418 if (!read_stdin && !read_buffer)
419 {
Bram Moolenaar4e4f5292013-08-30 17:07:01 +0200420#ifdef UNIX
421 /*
422 * On Unix it is possible to read a directory, so we have to
423 * check for it before the mch_open().
424 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000425 perm = mch_getperm(fname);
426 if (perm >= 0 && !S_ISREG(perm) /* not a regular file ... */
427# ifdef S_ISFIFO
428 && !S_ISFIFO(perm) /* ... or fifo */
429# endif
430# ifdef S_ISSOCK
431 && !S_ISSOCK(perm) /* ... or socket */
432# endif
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +0000433# ifdef OPEN_CHR_FILES
434 && !(S_ISCHR(perm) && is_dev_fd_file(fname))
435 /* ... or a character special file named /dev/fd/<n> */
436# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000437 )
438 {
439 if (S_ISDIR(perm))
440 filemess(curbuf, fname, (char_u *)_("is a directory"), 0);
441 else
442 filemess(curbuf, fname, (char_u *)_("is not a file"), 0);
443 msg_end();
444 msg_scroll = msg_save;
445 return FAIL;
446 }
Bram Moolenaar4e4f5292013-08-30 17:07:01 +0200447#endif
Bram Moolenaare7fedb62015-12-31 19:07:19 +0100448#if defined(MSDOS) || defined(MSWIN)
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000449 /*
450 * MS-Windows allows opening a device, but we will probably get stuck
451 * trying to read it.
452 */
453 if (!p_odev && mch_nodetype(fname) == NODE_WRITABLE)
454 {
Bram Moolenaar5386a122007-06-28 20:02:32 +0000455 filemess(curbuf, fname, (char_u *)_("is a device (disabled with 'opendevice' option)"), 0);
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000456 msg_end();
457 msg_scroll = msg_save;
458 return FAIL;
459 }
Bram Moolenaar043545e2006-10-10 16:44:07 +0000460#endif
Bram Moolenaar4e4f5292013-08-30 17:07:01 +0200461 }
Bram Moolenaar043545e2006-10-10 16:44:07 +0000462
Bram Moolenaarad875fb2013-07-24 15:02:03 +0200463 /* Set default or forced 'fileformat' and 'binary'. */
464 set_file_options(set_options, eap);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000465
466 /*
467 * When opening a new file we take the readonly flag from the file.
468 * Default is r/w, can be set to r/o below.
469 * Don't reset it when in readonly mode
470 * Only set/reset b_p_ro when BF_CHECK_RO is set.
471 */
472 check_readonly = (newfile && (curbuf->b_flags & BF_CHECK_RO));
Bram Moolenaar4399ef42005-02-12 14:29:27 +0000473 if (check_readonly && !readonlymode)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000474 curbuf->b_p_ro = FALSE;
475
476 if (newfile && !read_stdin && !read_buffer)
477 {
Bram Moolenaare60acc12011-05-10 16:41:25 +0200478 /* Remember time of file. */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000479 if (mch_stat((char *)fname, &st) >= 0)
480 {
481 buf_store_time(curbuf, &st, fname);
482 curbuf->b_mtime_read = curbuf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000483#ifdef UNIX
484 /*
485 * Use the protection bits of the original file for the swap file.
486 * This makes it possible for others to read the name of the
487 * edited file from the swapfile, but only if they can read the
488 * edited file.
489 * Remove the "write" and "execute" bits for group and others
490 * (they must not write the swapfile).
491 * Add the "read" and "write" bits for the user, otherwise we may
492 * not be able to write to the file ourselves.
493 * Setting the bits is done below, after creating the swap file.
494 */
495 swap_mode = (st.st_mode & 0644) | 0600;
496#endif
497#ifdef FEAT_CW_EDITOR
498 /* Get the FSSpec on MacOS
499 * TODO: Update it properly when the buffer name changes
500 */
501 (void)GetFSSpecFromPath(curbuf->b_ffname, &curbuf->b_FSSpec);
502#endif
503#ifdef VMS
504 curbuf->b_fab_rfm = st.st_fab_rfm;
Bram Moolenaard4755bb2004-09-02 19:12:26 +0000505 curbuf->b_fab_rat = st.st_fab_rat;
506 curbuf->b_fab_mrs = st.st_fab_mrs;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000507#endif
508 }
509 else
510 {
511 curbuf->b_mtime = 0;
512 curbuf->b_mtime_read = 0;
513 curbuf->b_orig_size = 0;
514 curbuf->b_orig_mode = 0;
515 }
516
517 /* Reset the "new file" flag. It will be set again below when the
518 * file doesn't exist. */
519 curbuf->b_flags &= ~(BF_NEW | BF_NEW_W);
520 }
521
522/*
523 * for UNIX: check readonly with perm and mch_access()
Bram Moolenaar071d4272004-06-13 20:20:40 +0000524 * for MSDOS and Amiga: check readonly by trying to open the file for writing
525 */
526 file_readonly = FALSE;
527 if (read_stdin)
528 {
Bram Moolenaare7fedb62015-12-31 19:07:19 +0100529#if defined(MSDOS) || defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000530 /* Force binary I/O on stdin to avoid CR-LF -> LF conversion. */
531 setmode(0, O_BINARY);
532#endif
533 }
534 else if (!read_buffer)
535 {
536#ifdef USE_MCH_ACCESS
537 if (
538# ifdef UNIX
539 !(perm & 0222) ||
540# endif
541 mch_access((char *)fname, W_OK))
542 file_readonly = TRUE;
543 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
544#else
545 if (!newfile
546 || readonlymode
547 || (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0)
548 {
549 file_readonly = TRUE;
550 /* try to open ro */
551 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
552 }
553#endif
554 }
555
556 if (fd < 0) /* cannot open at all */
557 {
558#ifndef UNIX
559 int isdir_f;
560#endif
561 msg_scroll = msg_save;
562#ifndef UNIX
563 /*
564 * On MSDOS and Amiga we can't open a directory, check here.
565 */
566 isdir_f = (mch_isdir(fname));
567 perm = mch_getperm(fname); /* check if the file exists */
568 if (isdir_f)
569 {
570 filemess(curbuf, sfname, (char_u *)_("is a directory"), 0);
571 curbuf->b_p_ro = TRUE; /* must use "w!" now */
572 }
573 else
574#endif
575 if (newfile)
576 {
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200577 if (perm < 0
578#ifdef ENOENT
579 && errno == ENOENT
580#endif
581 )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000582 {
583 /*
584 * Set the 'new-file' flag, so that when the file has
585 * been created by someone else, a ":w" will complain.
586 */
587 curbuf->b_flags |= BF_NEW;
588
589 /* Create a swap file now, so that other Vims are warned
590 * that we are editing this file. Don't do this for a
591 * "nofile" or "nowrite" buffer type. */
592#ifdef FEAT_QUICKFIX
593 if (!bt_dontwrite(curbuf))
594#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000595 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000596 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000597#ifdef FEAT_AUTOCMD
598 /* SwapExists autocommand may mess things up */
599 if (curbuf != old_curbuf
600 || (using_b_ffname
601 && (old_b_ffname != curbuf->b_ffname))
602 || (using_b_fname
603 && (old_b_fname != curbuf->b_fname)))
604 {
605 EMSG(_(e_auchangedbuf));
606 return FAIL;
607 }
608#endif
609 }
Bram Moolenaar5b962cf2005-12-12 21:58:40 +0000610 if (dir_of_file_exists(fname))
611 filemess(curbuf, sfname, (char_u *)_("[New File]"), 0);
612 else
613 filemess(curbuf, sfname,
614 (char_u *)_("[New DIRECTORY]"), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000615#ifdef FEAT_VIMINFO
616 /* Even though this is a new file, it might have been
617 * edited before and deleted. Get the old marks. */
618 check_marks_read();
619#endif
620#ifdef FEAT_MBYTE
Bram Moolenaarad875fb2013-07-24 15:02:03 +0200621 /* Set forced 'fileencoding'. */
622 if (eap != NULL)
623 set_forced_fenc(eap);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000624#endif
625#ifdef FEAT_AUTOCMD
626 apply_autocmds_exarg(EVENT_BUFNEWFILE, sfname, sfname,
627 FALSE, curbuf, eap);
628#endif
629 /* remember the current fileformat */
630 save_file_ff(curbuf);
631
632#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
633 if (aborting()) /* autocmds may abort script processing */
634 return FAIL;
635#endif
636 return OK; /* a new file is not an error */
637 }
638 else
639 {
Bram Moolenaar202795b2005-10-11 20:29:39 +0000640 filemess(curbuf, sfname, (char_u *)(
641# ifdef EFBIG
642 (errno == EFBIG) ? _("[File too big]") :
643# endif
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200644# ifdef EOVERFLOW
645 (errno == EOVERFLOW) ? _("[File too big]") :
646# endif
Bram Moolenaar202795b2005-10-11 20:29:39 +0000647 _("[Permission Denied]")), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000648 curbuf->b_p_ro = TRUE; /* must use "w!" now */
649 }
650 }
651
652 return FAIL;
653 }
654
655 /*
656 * Only set the 'ro' flag for readonly files the first time they are
657 * loaded. Help files always get readonly mode
658 */
659 if ((check_readonly && file_readonly) || curbuf->b_help)
660 curbuf->b_p_ro = TRUE;
661
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000662 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000663 {
Bram Moolenaar690ffc02008-01-04 15:31:21 +0000664 /* Don't change 'eol' if reading from buffer as it will already be
665 * correctly set when reading stdin. */
666 if (!read_buffer)
667 {
668 curbuf->b_p_eol = TRUE;
669 curbuf->b_start_eol = TRUE;
670 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000671#ifdef FEAT_MBYTE
672 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000673 curbuf->b_start_bomb = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000674#endif
675 }
676
677 /* Create a swap file now, so that other Vims are warned that we are
678 * editing this file.
679 * Don't do this for a "nofile" or "nowrite" buffer type. */
680#ifdef FEAT_QUICKFIX
681 if (!bt_dontwrite(curbuf))
682#endif
683 {
684 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000685#ifdef FEAT_AUTOCMD
686 if (!read_stdin && (curbuf != old_curbuf
687 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
688 || (using_b_fname && (old_b_fname != curbuf->b_fname))))
689 {
690 EMSG(_(e_auchangedbuf));
691 if (!read_buffer)
692 close(fd);
693 return FAIL;
694 }
695#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000696#ifdef UNIX
697 /* Set swap file protection bits after creating it. */
Bram Moolenaarf061e0b2009-06-24 15:32:01 +0000698 if (swap_mode > 0 && curbuf->b_ml.ml_mfp != NULL
699 && curbuf->b_ml.ml_mfp->mf_fname != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000700 (void)mch_setperm(curbuf->b_ml.ml_mfp->mf_fname, (long)swap_mode);
701#endif
702 }
703
Bram Moolenaarb815dac2005-12-07 20:59:24 +0000704#if defined(HAS_SWAP_EXISTS_ACTION)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000705 /* If "Quit" selected at ATTENTION dialog, don't load the file */
706 if (swap_exists_action == SEA_QUIT)
707 {
708 if (!read_buffer && !read_stdin)
709 close(fd);
710 return FAIL;
711 }
712#endif
713
714 ++no_wait_return; /* don't wait for return yet */
715
716 /*
717 * Set '[ mark to the line above where the lines go (line 1 if zero).
718 */
719 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
720 curbuf->b_op_start.col = 0;
721
722#ifdef FEAT_AUTOCMD
723 if (!read_buffer)
724 {
725 int m = msg_scroll;
726 int n = msg_scrolled;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000727
728 /*
729 * The file must be closed again, the autocommands may want to change
730 * the file before reading it.
731 */
732 if (!read_stdin)
733 close(fd); /* ignore errors */
734
735 /*
736 * The output from the autocommands should not overwrite anything and
737 * should not be overwritten: Set msg_scroll, restore its value if no
738 * output was done.
739 */
740 msg_scroll = TRUE;
741 if (filtering)
742 apply_autocmds_exarg(EVENT_FILTERREADPRE, NULL, sfname,
743 FALSE, curbuf, eap);
744 else if (read_stdin)
745 apply_autocmds_exarg(EVENT_STDINREADPRE, NULL, sfname,
746 FALSE, curbuf, eap);
747 else if (newfile)
748 apply_autocmds_exarg(EVENT_BUFREADPRE, NULL, sfname,
749 FALSE, curbuf, eap);
750 else
751 apply_autocmds_exarg(EVENT_FILEREADPRE, sfname, sfname,
752 FALSE, NULL, eap);
753 if (msg_scrolled == n)
754 msg_scroll = m;
755
756#ifdef FEAT_EVAL
757 if (aborting()) /* autocmds may abort script processing */
758 {
759 --no_wait_return;
760 msg_scroll = msg_save;
761 curbuf->b_p_ro = TRUE; /* must use "w!" now */
762 return FAIL;
763 }
764#endif
765 /*
766 * Don't allow the autocommands to change the current buffer.
767 * Try to re-open the file.
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000768 *
769 * Don't allow the autocommands to change the buffer name either
770 * (cd for example) if it invalidates fname or sfname.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000771 */
772 if (!read_stdin && (curbuf != old_curbuf
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000773 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
774 || (using_b_fname && (old_b_fname != curbuf->b_fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000775 || (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) < 0))
776 {
777 --no_wait_return;
778 msg_scroll = msg_save;
779 if (fd < 0)
780 EMSG(_("E200: *ReadPre autocommands made the file unreadable"));
781 else
782 EMSG(_("E201: *ReadPre autocommands must not change current buffer"));
783 curbuf->b_p_ro = TRUE; /* must use "w!" now */
784 return FAIL;
785 }
786 }
787#endif /* FEAT_AUTOCMD */
788
789 /* Autocommands may add lines to the file, need to check if it is empty */
790 wasempty = (curbuf->b_ml.ml_flags & ML_EMPTY);
791
792 if (!recoverymode && !filtering && !(flags & READ_DUMMY))
793 {
794 /*
795 * Show the user that we are busy reading the input. Sometimes this
796 * may take a while. When reading from stdin another program may
797 * still be running, don't move the cursor to the last line, unless
798 * always using the GUI.
799 */
800 if (read_stdin)
801 {
802#ifndef ALWAYS_USE_GUI
803 mch_msg(_("Vim: Reading from stdin...\n"));
804#endif
805#ifdef FEAT_GUI
806 /* Also write a message in the GUI window, if there is one. */
807 if (gui.in_use && !gui.dying && !gui.starting)
808 {
809 p = (char_u *)_("Reading from stdin...");
810 gui_write(p, (int)STRLEN(p));
811 }
812#endif
813 }
814 else if (!read_buffer)
815 filemess(curbuf, sfname, (char_u *)"", 0);
816 }
817
818 msg_scroll = FALSE; /* overwrite the file message */
819
820 /*
821 * Set linecnt now, before the "retry" caused by a wrong guess for
822 * fileformat, and after the autocommands, which may change them.
823 */
824 linecnt = curbuf->b_ml.ml_line_count;
825
826#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000827 /* "++bad=" argument. */
828 if (eap != NULL && eap->bad_char != 0)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000829 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000830 bad_char_behavior = eap->bad_char;
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000831 if (set_options)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000832 curbuf->b_bad_char = eap->bad_char;
833 }
834 else
835 curbuf->b_bad_char = 0;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000836
Bram Moolenaar071d4272004-06-13 20:20:40 +0000837 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000838 * Decide which 'encoding' to use or use first.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000839 */
840 if (eap != NULL && eap->force_enc != 0)
841 {
842 fenc = enc_canonize(eap->cmd + eap->force_enc);
843 fenc_alloced = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000844 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000845 }
846 else if (curbuf->b_p_bin)
847 {
848 fenc = (char_u *)""; /* binary: don't convert */
849 fenc_alloced = FALSE;
850 }
851 else if (curbuf->b_help)
852 {
853 char_u firstline[80];
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000854 int fc;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000855
856 /* Help files are either utf-8 or latin1. Try utf-8 first, if this
857 * fails it must be latin1.
858 * Always do this when 'encoding' is "utf-8". Otherwise only do
859 * this when needed to avoid [converted] remarks all the time.
860 * It is needed when the first line contains non-ASCII characters.
861 * That is only in *.??x files. */
862 fenc = (char_u *)"latin1";
863 c = enc_utf8;
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000864 if (!c && !read_stdin)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000865 {
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000866 fc = fname[STRLEN(fname) - 1];
867 if (TOLOWER_ASC(fc) == 'x')
868 {
869 /* Read the first line (and a bit more). Immediately rewind to
870 * the start of the file. If the read() fails "len" is -1. */
Bram Moolenaar540fc6f2010-12-17 16:27:16 +0100871 len = read_eintr(fd, firstline, 80);
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000872 lseek(fd, (off_t)0L, SEEK_SET);
873 for (p = firstline; p < firstline + len; ++p)
874 if (*p >= 0x80)
875 {
876 c = TRUE;
877 break;
878 }
879 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000880 }
881
882 if (c)
883 {
884 fenc_next = fenc;
885 fenc = (char_u *)"utf-8";
886
887 /* When the file is utf-8 but a character doesn't fit in
888 * 'encoding' don't retry. In help text editing utf-8 bytes
889 * doesn't make sense. */
Bram Moolenaarf193fff2006-04-27 00:02:13 +0000890 if (!enc_utf8)
891 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000892 }
893 fenc_alloced = FALSE;
894 }
895 else if (*p_fencs == NUL)
896 {
897 fenc = curbuf->b_p_fenc; /* use format from buffer */
898 fenc_alloced = FALSE;
899 }
900 else
901 {
902 fenc_next = p_fencs; /* try items in 'fileencodings' */
903 fenc = next_fenc(&fenc_next);
904 fenc_alloced = TRUE;
905 }
906#endif
907
908 /*
909 * Jump back here to retry reading the file in different ways.
910 * Reasons to retry:
911 * - encoding conversion failed: try another one from "fenc_next"
912 * - BOM detected and fenc was set, need to setup conversion
913 * - "fileformat" check failed: try another
914 *
915 * Variables set for special retry actions:
916 * "file_rewind" Rewind the file to start reading it again.
917 * "advance_fenc" Advance "fenc" using "fenc_next".
918 * "skip_read" Re-use already read bytes (BOM detected).
919 * "did_iconv" iconv() conversion failed, try 'charconvert'.
920 * "keep_fileformat" Don't reset "fileformat".
921 *
922 * Other status indicators:
923 * "tmpname" When != NULL did conversion with 'charconvert'.
924 * Output file has to be deleted afterwards.
925 * "iconv_fd" When != -1 did conversion with iconv().
926 */
927retry:
928
929 if (file_rewind)
930 {
931 if (read_buffer)
932 {
933 read_buf_lnum = 1;
934 read_buf_col = 0;
935 }
936 else if (read_stdin || lseek(fd, (off_t)0L, SEEK_SET) != 0)
937 {
938 /* Can't rewind the file, give up. */
939 error = TRUE;
940 goto failed;
941 }
942 /* Delete the previously read lines. */
943 while (lnum > from)
944 ml_delete(lnum--, FALSE);
945 file_rewind = FALSE;
946#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000947 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000948 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000949 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000950 curbuf->b_start_bomb = FALSE;
951 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000952 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000953#endif
954 }
955
956 /*
957 * When retrying with another "fenc" and the first time "fileformat"
958 * will be reset.
959 */
960 if (keep_fileformat)
961 keep_fileformat = FALSE;
962 else
963 {
964 if (eap != NULL && eap->force_ff != 0)
Bram Moolenaar1c860362008-11-12 15:05:21 +0000965 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000966 fileformat = get_fileformat_force(curbuf, eap);
Bram Moolenaar1c860362008-11-12 15:05:21 +0000967 try_unix = try_dos = try_mac = FALSE;
968 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000969 else if (curbuf->b_p_bin)
970 fileformat = EOL_UNIX; /* binary: use Unix format */
971 else if (*p_ffs == NUL)
972 fileformat = get_fileformat(curbuf);/* use format from buffer */
973 else
974 fileformat = EOL_UNKNOWN; /* detect from file */
975 }
976
977#ifdef FEAT_MBYTE
978# ifdef USE_ICONV
979 if (iconv_fd != (iconv_t)-1)
980 {
981 /* aborted conversion with iconv(), close the descriptor */
982 iconv_close(iconv_fd);
983 iconv_fd = (iconv_t)-1;
984 }
985# endif
986
987 if (advance_fenc)
988 {
989 /*
990 * Try the next entry in 'fileencodings'.
991 */
992 advance_fenc = FALSE;
993
994 if (eap != NULL && eap->force_enc != 0)
995 {
996 /* Conversion given with "++cc=" wasn't possible, read
997 * without conversion. */
998 notconverted = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000999 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001000 if (fenc_alloced)
1001 vim_free(fenc);
1002 fenc = (char_u *)"";
1003 fenc_alloced = FALSE;
1004 }
1005 else
1006 {
1007 if (fenc_alloced)
1008 vim_free(fenc);
1009 if (fenc_next != NULL)
1010 {
1011 fenc = next_fenc(&fenc_next);
1012 fenc_alloced = (fenc_next != NULL);
1013 }
1014 else
1015 {
1016 fenc = (char_u *)"";
1017 fenc_alloced = FALSE;
1018 }
1019 }
1020 if (tmpname != NULL)
1021 {
1022 mch_remove(tmpname); /* delete converted file */
1023 vim_free(tmpname);
1024 tmpname = NULL;
1025 }
1026 }
1027
1028 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001029 * Conversion may be required when the encoding of the file is different
1030 * from 'encoding' or 'encoding' is UTF-16, UCS-2 or UCS-4.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001031 */
1032 fio_flags = 0;
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001033 converted = need_conversion(fenc);
1034 if (converted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001035 {
1036
1037 /* "ucs-bom" means we need to check the first bytes of the file
1038 * for a BOM. */
1039 if (STRCMP(fenc, ENC_UCSBOM) == 0)
1040 fio_flags = FIO_UCSBOM;
1041
1042 /*
1043 * Check if UCS-2/4 or Latin1 to UTF-8 conversion needs to be
1044 * done. This is handled below after read(). Prepare the
1045 * fio_flags to avoid having to parse the string each time.
1046 * Also check for Unicode to Latin1 conversion, because iconv()
1047 * appears not to handle this correctly. This works just like
1048 * conversion to UTF-8 except how the resulting character is put in
1049 * the buffer.
1050 */
1051 else if (enc_utf8 || STRCMP(p_enc, "latin1") == 0)
1052 fio_flags = get_fio_flags(fenc);
1053
1054# ifdef WIN3264
1055 /*
1056 * Conversion from an MS-Windows codepage to UTF-8 or another codepage
1057 * is handled with MultiByteToWideChar().
1058 */
1059 if (fio_flags == 0)
1060 fio_flags = get_win_fio_flags(fenc);
1061# endif
1062
1063# ifdef MACOS_X
1064 /* Conversion from Apple MacRoman to latin1 or UTF-8 */
1065 if (fio_flags == 0)
1066 fio_flags = get_mac_fio_flags(fenc);
1067# endif
1068
1069# ifdef USE_ICONV
1070 /*
1071 * Try using iconv() if we can't convert internally.
1072 */
1073 if (fio_flags == 0
1074# ifdef FEAT_EVAL
1075 && !did_iconv
1076# endif
1077 )
1078 iconv_fd = (iconv_t)my_iconv_open(
1079 enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc);
1080# endif
1081
1082# ifdef FEAT_EVAL
1083 /*
1084 * Use the 'charconvert' expression when conversion is required
1085 * and we can't do it internally or with iconv().
1086 */
1087 if (fio_flags == 0 && !read_stdin && !read_buffer && *p_ccv != NUL
1088# ifdef USE_ICONV
1089 && iconv_fd == (iconv_t)-1
1090# endif
1091 )
1092 {
1093# ifdef USE_ICONV
1094 did_iconv = FALSE;
1095# endif
1096 /* Skip conversion when it's already done (retry for wrong
1097 * "fileformat"). */
1098 if (tmpname == NULL)
1099 {
1100 tmpname = readfile_charconvert(fname, fenc, &fd);
1101 if (tmpname == NULL)
1102 {
1103 /* Conversion failed. Try another one. */
1104 advance_fenc = TRUE;
1105 if (fd < 0)
1106 {
1107 /* Re-opening the original file failed! */
1108 EMSG(_("E202: Conversion made file unreadable!"));
1109 error = TRUE;
1110 goto failed;
1111 }
1112 goto retry;
1113 }
1114 }
1115 }
1116 else
1117# endif
1118 {
1119 if (fio_flags == 0
1120# ifdef USE_ICONV
1121 && iconv_fd == (iconv_t)-1
1122# endif
1123 )
1124 {
1125 /* Conversion wanted but we can't.
1126 * Try the next conversion in 'fileencodings' */
1127 advance_fenc = TRUE;
1128 goto retry;
1129 }
1130 }
1131 }
1132
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001133 /* Set "can_retry" when it's possible to rewind the file and try with
Bram Moolenaar071d4272004-06-13 20:20:40 +00001134 * another "fenc" value. It's FALSE when no other "fenc" to try, reading
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001135 * stdin or fixed at a specific encoding. */
1136 can_retry = (*fenc != NUL && !read_stdin && !keep_dest_enc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001137#endif
1138
1139 if (!skip_read)
1140 {
1141 linerest = 0;
1142 filesize = 0;
1143 skip_count = lines_to_skip;
1144 read_count = lines_to_read;
1145#ifdef FEAT_MBYTE
1146 conv_restlen = 0;
1147#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001148#ifdef FEAT_PERSISTENT_UNDO
Bram Moolenaar59f931e2010-07-24 20:27:03 +02001149 read_undo_file = (newfile && (flags & READ_KEEP_UNDO) == 0
1150 && curbuf->b_ffname != NULL
1151 && curbuf->b_p_udf
1152 && !filtering
1153 && !read_stdin
1154 && !read_buffer);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001155 if (read_undo_file)
1156 sha256_start(&sha_ctx);
1157#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001158#ifdef FEAT_CRYPT
1159 if (curbuf->b_cryptstate != NULL)
1160 {
1161 /* Need to free the state, but keep the key, don't want to ask for
1162 * it again. */
1163 crypt_free_state(curbuf->b_cryptstate);
1164 curbuf->b_cryptstate = NULL;
1165 }
1166#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001167 }
1168
1169 while (!error && !got_int)
1170 {
1171 /*
1172 * We allocate as much space for the file as we can get, plus
1173 * space for the old line plus room for one terminating NUL.
1174 * The amount is limited by the fact that read() only can read
1175 * upto max_unsigned characters (and other things).
1176 */
Bram Moolenaara2aa31a2014-02-23 22:52:40 +01001177#if VIM_SIZEOF_INT <= 2
Bram Moolenaar071d4272004-06-13 20:20:40 +00001178 if (linerest >= 0x7ff0)
1179 {
1180 ++split;
1181 *ptr = NL; /* split line by inserting a NL */
1182 size = 1;
1183 }
1184 else
1185#endif
1186 {
1187 if (!skip_read)
1188 {
Bram Moolenaara2aa31a2014-02-23 22:52:40 +01001189#if VIM_SIZEOF_INT > 2
Bram Moolenaar311d9822007-02-27 15:48:28 +00001190# if defined(SSIZE_MAX) && (SSIZE_MAX < 0x10000L)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001191 size = SSIZE_MAX; /* use max I/O size, 52K */
1192# else
1193 size = 0x10000L; /* use buffer >= 64K */
1194# endif
1195#else
1196 size = 0x7ff0L - linerest; /* limit buffer to 32K */
1197#endif
1198
Bram Moolenaarc1e37902006-04-18 21:55:01 +00001199 for ( ; size >= 10; size = (long)((long_u)size >> 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001200 {
1201 if ((new_buffer = lalloc((long_u)(size + linerest + 1),
1202 FALSE)) != NULL)
1203 break;
1204 }
1205 if (new_buffer == NULL)
1206 {
1207 do_outofmem_msg((long_u)(size * 2 + linerest + 1));
1208 error = TRUE;
1209 break;
1210 }
1211 if (linerest) /* copy characters from the previous buffer */
1212 mch_memmove(new_buffer, ptr - linerest, (size_t)linerest);
1213 vim_free(buffer);
1214 buffer = new_buffer;
1215 ptr = buffer + linerest;
1216 line_start = buffer;
1217
1218#ifdef FEAT_MBYTE
1219 /* May need room to translate into.
1220 * For iconv() we don't really know the required space, use a
1221 * factor ICONV_MULT.
1222 * latin1 to utf-8: 1 byte becomes up to 2 bytes
1223 * utf-16 to utf-8: 2 bytes become up to 3 bytes, 4 bytes
1224 * become up to 4 bytes, size must be multiple of 2
1225 * ucs-2 to utf-8: 2 bytes become up to 3 bytes, size must be
1226 * multiple of 2
1227 * ucs-4 to utf-8: 4 bytes become up to 6 bytes, size must be
1228 * multiple of 4 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001229 real_size = (int)size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001230# ifdef USE_ICONV
1231 if (iconv_fd != (iconv_t)-1)
1232 size = size / ICONV_MULT;
1233 else
1234# endif
1235 if (fio_flags & FIO_LATIN1)
1236 size = size / 2;
1237 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1238 size = (size * 2 / 3) & ~1;
1239 else if (fio_flags & FIO_UCS4)
1240 size = (size * 2 / 3) & ~3;
1241 else if (fio_flags == FIO_UCSBOM)
1242 size = size / ICONV_MULT; /* worst case */
1243# ifdef WIN3264
1244 else if (fio_flags & FIO_CODEPAGE)
1245 size = size / ICONV_MULT; /* also worst case */
1246# endif
1247# ifdef MACOS_X
1248 else if (fio_flags & FIO_MACROMAN)
1249 size = size / ICONV_MULT; /* also worst case */
1250# endif
1251#endif
1252
1253#ifdef FEAT_MBYTE
1254 if (conv_restlen > 0)
1255 {
1256 /* Insert unconverted bytes from previous line. */
1257 mch_memmove(ptr, conv_rest, conv_restlen);
1258 ptr += conv_restlen;
1259 size -= conv_restlen;
1260 }
1261#endif
1262
1263 if (read_buffer)
1264 {
1265 /*
1266 * Read bytes from curbuf. Used for converting text read
1267 * from stdin.
1268 */
1269 if (read_buf_lnum > from)
1270 size = 0;
1271 else
1272 {
1273 int n, ni;
1274 long tlen;
1275
1276 tlen = 0;
1277 for (;;)
1278 {
1279 p = ml_get(read_buf_lnum) + read_buf_col;
1280 n = (int)STRLEN(p);
1281 if ((int)tlen + n + 1 > size)
1282 {
1283 /* Filled up to "size", append partial line.
1284 * Change NL to NUL to reverse the effect done
1285 * below. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001286 n = (int)(size - tlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001287 for (ni = 0; ni < n; ++ni)
1288 {
1289 if (p[ni] == NL)
1290 ptr[tlen++] = NUL;
1291 else
1292 ptr[tlen++] = p[ni];
1293 }
1294 read_buf_col += n;
1295 break;
1296 }
1297 else
1298 {
1299 /* Append whole line and new-line. Change NL
1300 * to NUL to reverse the effect done below. */
1301 for (ni = 0; ni < n; ++ni)
1302 {
1303 if (p[ni] == NL)
1304 ptr[tlen++] = NUL;
1305 else
1306 ptr[tlen++] = p[ni];
1307 }
1308 ptr[tlen++] = NL;
1309 read_buf_col = 0;
1310 if (++read_buf_lnum > from)
1311 {
1312 /* When the last line didn't have an
1313 * end-of-line don't add it now either. */
1314 if (!curbuf->b_p_eol)
1315 --tlen;
1316 size = tlen;
1317 break;
1318 }
1319 }
1320 }
1321 }
1322 }
1323 else
1324 {
1325 /*
1326 * Read bytes from the file.
1327 */
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01001328 size = read_eintr(fd, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001329 }
1330
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001331#ifdef FEAT_CRYPT
1332 /*
1333 * At start of file: Check for magic number of encryption.
1334 */
1335 if (filesize == 0 && size > 0)
1336 cryptkey = check_for_cryptkey(cryptkey, ptr, &size,
1337 &filesize, newfile, sfname,
1338 &did_ask_for_key);
1339 /*
1340 * Decrypt the read bytes. This is done before checking for
1341 * EOF because the crypt layer may be buffering.
1342 */
1343 if (cryptkey != NULL && size > 0)
1344 {
1345 if (crypt_works_inplace(curbuf->b_cryptstate))
1346 {
1347 crypt_decode_inplace(curbuf->b_cryptstate, ptr, size);
1348 }
1349 else
1350 {
1351 char_u *newptr = NULL;
1352 int decrypted_size;
1353
1354 decrypted_size = crypt_decode_alloc(
1355 curbuf->b_cryptstate, ptr, size, &newptr);
1356
1357 /* If the crypt layer is buffering, not producing
1358 * anything yet, need to read more. */
1359 if (size > 0 && decrypted_size == 0)
1360 continue;
1361
1362 if (linerest == 0)
1363 {
1364 /* Simple case: reuse returned buffer (may be
1365 * NULL, checked later). */
1366 new_buffer = newptr;
1367 }
1368 else
1369 {
1370 long_u new_size;
1371
1372 /* Need new buffer to add bytes carried over. */
1373 new_size = (long_u)(decrypted_size + linerest + 1);
1374 new_buffer = lalloc(new_size, FALSE);
1375 if (new_buffer == NULL)
1376 {
1377 do_outofmem_msg(new_size);
1378 error = TRUE;
1379 break;
1380 }
1381
1382 mch_memmove(new_buffer, buffer, linerest);
1383 if (newptr != NULL)
1384 mch_memmove(new_buffer + linerest, newptr,
1385 decrypted_size);
1386 }
1387
1388 if (new_buffer != NULL)
1389 {
1390 vim_free(buffer);
1391 buffer = new_buffer;
1392 new_buffer = NULL;
1393 line_start = buffer;
1394 ptr = buffer + linerest;
1395 }
1396 size = decrypted_size;
1397 }
1398 }
1399#endif
1400
Bram Moolenaar071d4272004-06-13 20:20:40 +00001401 if (size <= 0)
1402 {
1403 if (size < 0) /* read error */
1404 error = TRUE;
1405#ifdef FEAT_MBYTE
1406 else if (conv_restlen > 0)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001407 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001408 /*
1409 * Reached end-of-file but some trailing bytes could
1410 * not be converted. Truncated file?
1411 */
1412
1413 /* When we did a conversion report an error. */
1414 if (fio_flags != 0
1415# ifdef USE_ICONV
1416 || iconv_fd != (iconv_t)-1
1417# endif
1418 )
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001419 {
Bram Moolenaare8d95302013-04-24 16:34:02 +02001420 if (can_retry)
1421 goto rewind_retry;
Bram Moolenaarf453d352008-06-04 17:37:34 +00001422 if (conv_error == 0)
1423 conv_error = curbuf->b_ml.ml_line_count
1424 - linecnt + 1;
1425 }
1426 /* Remember the first linenr with an illegal byte */
1427 else if (illegal_byte == 0)
1428 illegal_byte = curbuf->b_ml.ml_line_count
1429 - linecnt + 1;
1430 if (bad_char_behavior == BAD_DROP)
1431 {
1432 *(ptr - conv_restlen) = NUL;
1433 conv_restlen = 0;
1434 }
1435 else
1436 {
1437 /* Replace the trailing bytes with the replacement
1438 * character if we were converting; if we weren't,
1439 * leave the UTF8 checking code to do it, as it
1440 * works slightly differently. */
1441 if (bad_char_behavior != BAD_KEEP && (fio_flags != 0
1442# ifdef USE_ICONV
1443 || iconv_fd != (iconv_t)-1
1444# endif
1445 ))
1446 {
1447 while (conv_restlen > 0)
1448 {
1449 *(--ptr) = bad_char_behavior;
1450 --conv_restlen;
1451 }
1452 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001453 fio_flags = 0; /* don't convert this */
Bram Moolenaarb21e5842006-04-16 18:30:08 +00001454# ifdef USE_ICONV
1455 if (iconv_fd != (iconv_t)-1)
1456 {
1457 iconv_close(iconv_fd);
1458 iconv_fd = (iconv_t)-1;
1459 }
1460# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001461 }
1462 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001463#endif
1464 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001465 }
1466 skip_read = FALSE;
1467
1468#ifdef FEAT_MBYTE
1469 /*
1470 * At start of file (or after crypt magic number): Check for BOM.
1471 * Also check for a BOM for other Unicode encodings, but not after
1472 * converting with 'charconvert' or when a BOM has already been
1473 * found.
1474 */
1475 if ((filesize == 0
1476# ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001477 || (cryptkey != NULL
1478 && filesize == crypt_get_header_len(
1479 crypt_get_method_nr(curbuf)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001480# endif
1481 )
1482 && (fio_flags == FIO_UCSBOM
1483 || (!curbuf->b_p_bomb
1484 && tmpname == NULL
1485 && (*fenc == 'u' || (*fenc == NUL && enc_utf8)))))
1486 {
1487 char_u *ccname;
1488 int blen;
1489
1490 /* no BOM detection in a short file or in binary mode */
1491 if (size < 2 || curbuf->b_p_bin)
1492 ccname = NULL;
1493 else
1494 ccname = check_for_bom(ptr, size, &blen,
1495 fio_flags == FIO_UCSBOM ? FIO_ALL : get_fio_flags(fenc));
1496 if (ccname != NULL)
1497 {
1498 /* Remove BOM from the text */
1499 filesize += blen;
1500 size -= blen;
1501 mch_memmove(ptr, ptr + blen, (size_t)size);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00001502 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001503 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001504 curbuf->b_p_bomb = TRUE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001505 curbuf->b_start_bomb = TRUE;
1506 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001507 }
1508
1509 if (fio_flags == FIO_UCSBOM)
1510 {
1511 if (ccname == NULL)
1512 {
1513 /* No BOM detected: retry with next encoding. */
1514 advance_fenc = TRUE;
1515 }
1516 else
1517 {
1518 /* BOM detected: set "fenc" and jump back */
1519 if (fenc_alloced)
1520 vim_free(fenc);
1521 fenc = ccname;
1522 fenc_alloced = FALSE;
1523 }
1524 /* retry reading without getting new bytes or rewinding */
1525 skip_read = TRUE;
1526 goto retry;
1527 }
1528 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001529
1530 /* Include not converted bytes. */
1531 ptr -= conv_restlen;
1532 size += conv_restlen;
1533 conv_restlen = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001534#endif
1535 /*
1536 * Break here for a read error or end-of-file.
1537 */
1538 if (size <= 0)
1539 break;
1540
1541#ifdef FEAT_MBYTE
1542
Bram Moolenaar071d4272004-06-13 20:20:40 +00001543# ifdef USE_ICONV
1544 if (iconv_fd != (iconv_t)-1)
1545 {
1546 /*
1547 * Attempt conversion of the read bytes to 'encoding' using
1548 * iconv().
1549 */
1550 const char *fromp;
1551 char *top;
1552 size_t from_size;
1553 size_t to_size;
1554
1555 fromp = (char *)ptr;
1556 from_size = size;
1557 ptr += size;
1558 top = (char *)ptr;
1559 to_size = real_size - size;
1560
1561 /*
1562 * If there is conversion error or not enough room try using
Bram Moolenaar19a09a12005-03-04 23:39:37 +00001563 * another conversion. Except for when there is no
1564 * alternative (help files).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001565 */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001566 while ((iconv(iconv_fd, (void *)&fromp, &from_size,
1567 &top, &to_size)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001568 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
1569 || from_size > CONV_RESTLEN)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001570 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001571 if (can_retry)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001572 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001573 if (conv_error == 0)
1574 conv_error = readfile_linenr(linecnt,
1575 ptr, (char_u *)top);
Bram Moolenaar42eeac32005-06-29 22:40:58 +00001576
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001577 /* Deal with a bad byte and continue with the next. */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001578 ++fromp;
1579 --from_size;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001580 if (bad_char_behavior == BAD_KEEP)
1581 {
1582 *top++ = *(fromp - 1);
1583 --to_size;
1584 }
1585 else if (bad_char_behavior != BAD_DROP)
1586 {
1587 *top++ = bad_char_behavior;
1588 --to_size;
1589 }
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001590 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001591
1592 if (from_size > 0)
1593 {
1594 /* Some remaining characters, keep them for the next
1595 * round. */
1596 mch_memmove(conv_rest, (char_u *)fromp, from_size);
1597 conv_restlen = (int)from_size;
1598 }
1599
1600 /* move the linerest to before the converted characters */
1601 line_start = ptr - linerest;
1602 mch_memmove(line_start, buffer, (size_t)linerest);
1603 size = (long)((char_u *)top - ptr);
1604 }
1605# endif
1606
1607# ifdef WIN3264
1608 if (fio_flags & FIO_CODEPAGE)
1609 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001610 char_u *src, *dst;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001611 WCHAR ucs2buf[3];
1612 int ucs2len;
1613 int codepage = FIO_GET_CP(fio_flags);
1614 int bytelen;
1615 int found_bad;
1616 char replstr[2];
1617
Bram Moolenaar071d4272004-06-13 20:20:40 +00001618 /*
1619 * Conversion from an MS-Windows codepage or UTF-8 to UTF-8 or
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001620 * a codepage, using standard MS-Windows functions. This
1621 * requires two steps:
1622 * 1. convert from 'fileencoding' to ucs-2
1623 * 2. convert from ucs-2 to 'encoding'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001624 *
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001625 * Because there may be illegal bytes AND an incomplete byte
1626 * sequence at the end, we may have to do the conversion one
1627 * character at a time to get it right.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001628 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001629
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001630 /* Replacement string for WideCharToMultiByte(). */
1631 if (bad_char_behavior > 0)
1632 replstr[0] = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001633 else
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001634 replstr[0] = '?';
1635 replstr[1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001636
1637 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001638 * Move the bytes to the end of the buffer, so that we have
1639 * room to put the result at the start.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001640 */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001641 src = ptr + real_size - size;
1642 mch_memmove(src, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001643
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001644 /*
1645 * Do the conversion.
1646 */
1647 dst = ptr;
1648 size = size;
1649 while (size > 0)
1650 {
1651 found_bad = FALSE;
1652
1653# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
1654 if (codepage == CP_UTF8)
1655 {
1656 /* Handle CP_UTF8 input ourselves to be able to handle
1657 * trailing bytes properly.
1658 * Get one UTF-8 character from src. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001659 bytelen = (int)utf_ptr2len_len(src, size);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001660 if (bytelen > size)
1661 {
1662 /* Only got some bytes of a character. Normally
1663 * it's put in "conv_rest", but if it's too long
1664 * deal with it as if they were illegal bytes. */
1665 if (bytelen <= CONV_RESTLEN)
1666 break;
1667
1668 /* weird overlong byte sequence */
1669 bytelen = size;
1670 found_bad = TRUE;
1671 }
1672 else
1673 {
Bram Moolenaarc01140a2006-03-24 22:21:52 +00001674 int u8c = utf_ptr2char(src);
1675
Bram Moolenaar86e01082005-12-29 22:45:34 +00001676 if (u8c > 0xffff || (*src >= 0x80 && bytelen == 1))
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001677 found_bad = TRUE;
1678 ucs2buf[0] = u8c;
1679 ucs2len = 1;
1680 }
1681 }
1682 else
1683# endif
1684 {
1685 /* We don't know how long the byte sequence is, try
1686 * from one to three bytes. */
1687 for (bytelen = 1; bytelen <= size && bytelen <= 3;
1688 ++bytelen)
1689 {
1690 ucs2len = MultiByteToWideChar(codepage,
1691 MB_ERR_INVALID_CHARS,
1692 (LPCSTR)src, bytelen,
1693 ucs2buf, 3);
1694 if (ucs2len > 0)
1695 break;
1696 }
1697 if (ucs2len == 0)
1698 {
1699 /* If we have only one byte then it's probably an
1700 * incomplete byte sequence. Otherwise discard
1701 * one byte as a bad character. */
1702 if (size == 1)
1703 break;
1704 found_bad = TRUE;
1705 bytelen = 1;
1706 }
1707 }
1708
1709 if (!found_bad)
1710 {
1711 int i;
1712
1713 /* Convert "ucs2buf[ucs2len]" to 'enc' in "dst". */
1714 if (enc_utf8)
1715 {
1716 /* From UCS-2 to UTF-8. Cannot fail. */
1717 for (i = 0; i < ucs2len; ++i)
1718 dst += utf_char2bytes(ucs2buf[i], dst);
1719 }
1720 else
1721 {
1722 BOOL bad = FALSE;
1723 int dstlen;
1724
1725 /* From UCS-2 to "enc_codepage". If the
1726 * conversion uses the default character "?",
1727 * the data doesn't fit in this encoding. */
1728 dstlen = WideCharToMultiByte(enc_codepage, 0,
1729 (LPCWSTR)ucs2buf, ucs2len,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001730 (LPSTR)dst, (int)(src - dst),
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001731 replstr, &bad);
1732 if (bad)
1733 found_bad = TRUE;
1734 else
1735 dst += dstlen;
1736 }
1737 }
1738
1739 if (found_bad)
1740 {
1741 /* Deal with bytes we can't convert. */
1742 if (can_retry)
1743 goto rewind_retry;
1744 if (conv_error == 0)
1745 conv_error = readfile_linenr(linecnt, ptr, dst);
1746 if (bad_char_behavior != BAD_DROP)
1747 {
1748 if (bad_char_behavior == BAD_KEEP)
1749 {
1750 mch_memmove(dst, src, bytelen);
1751 dst += bytelen;
1752 }
1753 else
1754 *dst++ = bad_char_behavior;
1755 }
1756 }
1757
1758 src += bytelen;
1759 size -= bytelen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001760 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001761
1762 if (size > 0)
1763 {
1764 /* An incomplete byte sequence remaining. */
1765 mch_memmove(conv_rest, src, size);
1766 conv_restlen = size;
1767 }
1768
1769 /* The new size is equal to how much "dst" was advanced. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001770 size = (long)(dst - ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001771 }
1772 else
1773# endif
Bram Moolenaar56718732006-03-15 22:53:57 +00001774# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001775 if (fio_flags & FIO_MACROMAN)
1776 {
1777 /*
1778 * Conversion from Apple MacRoman char encoding to UTF-8 or
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001779 * latin1. This is in os_mac_conv.c.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001780 */
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001781 if (macroman2enc(ptr, &size, real_size) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001782 goto rewind_retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001783 }
1784 else
1785# endif
1786 if (fio_flags != 0)
1787 {
1788 int u8c;
1789 char_u *dest;
1790 char_u *tail = NULL;
1791
1792 /*
1793 * "enc_utf8" set: Convert Unicode or Latin1 to UTF-8.
1794 * "enc_utf8" not set: Convert Unicode to Latin1.
1795 * Go from end to start through the buffer, because the number
1796 * of bytes may increase.
1797 * "dest" points to after where the UTF-8 bytes go, "p" points
1798 * to after the next character to convert.
1799 */
1800 dest = ptr + real_size;
1801 if (fio_flags == FIO_LATIN1 || fio_flags == FIO_UTF8)
1802 {
1803 p = ptr + size;
1804 if (fio_flags == FIO_UTF8)
1805 {
1806 /* Check for a trailing incomplete UTF-8 sequence */
1807 tail = ptr + size - 1;
1808 while (tail > ptr && (*tail & 0xc0) == 0x80)
1809 --tail;
1810 if (tail + utf_byte2len(*tail) <= ptr + size)
1811 tail = NULL;
1812 else
1813 p = tail;
1814 }
1815 }
1816 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1817 {
1818 /* Check for a trailing byte */
1819 p = ptr + (size & ~1);
1820 if (size & 1)
1821 tail = p;
1822 if ((fio_flags & FIO_UTF16) && p > ptr)
1823 {
1824 /* Check for a trailing leading word */
1825 if (fio_flags & FIO_ENDIAN_L)
1826 {
1827 u8c = (*--p << 8);
1828 u8c += *--p;
1829 }
1830 else
1831 {
1832 u8c = *--p;
1833 u8c += (*--p << 8);
1834 }
1835 if (u8c >= 0xd800 && u8c <= 0xdbff)
1836 tail = p;
1837 else
1838 p += 2;
1839 }
1840 }
1841 else /* FIO_UCS4 */
1842 {
1843 /* Check for trailing 1, 2 or 3 bytes */
1844 p = ptr + (size & ~3);
1845 if (size & 3)
1846 tail = p;
1847 }
1848
1849 /* If there is a trailing incomplete sequence move it to
1850 * conv_rest[]. */
1851 if (tail != NULL)
1852 {
1853 conv_restlen = (int)((ptr + size) - tail);
1854 mch_memmove(conv_rest, (char_u *)tail, conv_restlen);
1855 size -= conv_restlen;
1856 }
1857
1858
1859 while (p > ptr)
1860 {
1861 if (fio_flags & FIO_LATIN1)
1862 u8c = *--p;
1863 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1864 {
1865 if (fio_flags & FIO_ENDIAN_L)
1866 {
1867 u8c = (*--p << 8);
1868 u8c += *--p;
1869 }
1870 else
1871 {
1872 u8c = *--p;
1873 u8c += (*--p << 8);
1874 }
1875 if ((fio_flags & FIO_UTF16)
1876 && u8c >= 0xdc00 && u8c <= 0xdfff)
1877 {
1878 int u16c;
1879
1880 if (p == ptr)
1881 {
1882 /* Missing leading word. */
1883 if (can_retry)
1884 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001885 if (conv_error == 0)
1886 conv_error = readfile_linenr(linecnt,
1887 ptr, p);
1888 if (bad_char_behavior == BAD_DROP)
1889 continue;
1890 if (bad_char_behavior != BAD_KEEP)
1891 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001892 }
1893
1894 /* found second word of double-word, get the first
1895 * word and compute the resulting character */
1896 if (fio_flags & FIO_ENDIAN_L)
1897 {
1898 u16c = (*--p << 8);
1899 u16c += *--p;
1900 }
1901 else
1902 {
1903 u16c = *--p;
1904 u16c += (*--p << 8);
1905 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001906 u8c = 0x10000 + ((u16c & 0x3ff) << 10)
1907 + (u8c & 0x3ff);
1908
Bram Moolenaar071d4272004-06-13 20:20:40 +00001909 /* Check if the word is indeed a leading word. */
1910 if (u16c < 0xd800 || u16c > 0xdbff)
1911 {
1912 if (can_retry)
1913 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001914 if (conv_error == 0)
1915 conv_error = readfile_linenr(linecnt,
1916 ptr, p);
1917 if (bad_char_behavior == BAD_DROP)
1918 continue;
1919 if (bad_char_behavior != BAD_KEEP)
1920 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001921 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001922 }
1923 }
1924 else if (fio_flags & FIO_UCS4)
1925 {
1926 if (fio_flags & FIO_ENDIAN_L)
1927 {
1928 u8c = (*--p << 24);
1929 u8c += (*--p << 16);
1930 u8c += (*--p << 8);
1931 u8c += *--p;
1932 }
1933 else /* big endian */
1934 {
1935 u8c = *--p;
1936 u8c += (*--p << 8);
1937 u8c += (*--p << 16);
1938 u8c += (*--p << 24);
1939 }
1940 }
1941 else /* UTF-8 */
1942 {
1943 if (*--p < 0x80)
1944 u8c = *p;
1945 else
1946 {
1947 len = utf_head_off(ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001948 p -= len;
1949 u8c = utf_ptr2char(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001950 if (len == 0)
1951 {
1952 /* Not a valid UTF-8 character, retry with
1953 * another fenc when possible, otherwise just
1954 * report the error. */
1955 if (can_retry)
1956 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001957 if (conv_error == 0)
1958 conv_error = readfile_linenr(linecnt,
1959 ptr, p);
1960 if (bad_char_behavior == BAD_DROP)
1961 continue;
1962 if (bad_char_behavior != BAD_KEEP)
1963 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001964 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001965 }
1966 }
1967 if (enc_utf8) /* produce UTF-8 */
1968 {
1969 dest -= utf_char2len(u8c);
1970 (void)utf_char2bytes(u8c, dest);
1971 }
1972 else /* produce Latin1 */
1973 {
1974 --dest;
1975 if (u8c >= 0x100)
1976 {
1977 /* character doesn't fit in latin1, retry with
1978 * another fenc when possible, otherwise just
1979 * report the error. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001980 if (can_retry)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001981 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001982 if (conv_error == 0)
1983 conv_error = readfile_linenr(linecnt, ptr, p);
1984 if (bad_char_behavior == BAD_DROP)
1985 ++dest;
1986 else if (bad_char_behavior == BAD_KEEP)
1987 *dest = u8c;
1988 else if (eap != NULL && eap->bad_char != 0)
1989 *dest = bad_char_behavior;
1990 else
1991 *dest = 0xBF;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001992 }
1993 else
1994 *dest = u8c;
1995 }
1996 }
1997
1998 /* move the linerest to before the converted characters */
1999 line_start = dest - linerest;
2000 mch_memmove(line_start, buffer, (size_t)linerest);
2001 size = (long)((ptr + real_size) - dest);
2002 ptr = dest;
2003 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002004 else if (enc_utf8 && !curbuf->b_p_bin)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002005 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002006 int incomplete_tail = FALSE;
2007
2008 /* Reading UTF-8: Check if the bytes are valid UTF-8. */
2009 for (p = ptr; ; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002010 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002011 int todo = (int)((ptr + size) - p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002012 int l;
2013
2014 if (todo <= 0)
2015 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002016 if (*p >= 0x80)
2017 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002018 /* A length of 1 means it's an illegal byte. Accept
2019 * an incomplete character at the end though, the next
2020 * read() will get the next bytes, we'll check it
2021 * then. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002022 l = utf_ptr2len_len(p, todo);
Bram Moolenaarf453d352008-06-04 17:37:34 +00002023 if (l > todo && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002024 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002025 /* Avoid retrying with a different encoding when
2026 * a truncated file is more likely, or attempting
2027 * to read the rest of an incomplete sequence when
2028 * we have already done so. */
2029 if (p > ptr || filesize > 0)
2030 incomplete_tail = TRUE;
2031 /* Incomplete byte sequence, move it to conv_rest[]
2032 * and try to read the rest of it, unless we've
2033 * already done so. */
2034 if (p > ptr)
2035 {
2036 conv_restlen = todo;
2037 mch_memmove(conv_rest, p, conv_restlen);
2038 size -= conv_restlen;
2039 break;
2040 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002041 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002042 if (l == 1 || l > todo)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002043 {
2044 /* Illegal byte. If we can try another encoding
Bram Moolenaarf453d352008-06-04 17:37:34 +00002045 * do that, unless at EOF where a truncated
2046 * file is more likely than a conversion error. */
2047 if (can_retry && !incomplete_tail)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002048 break;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002049# ifdef USE_ICONV
2050 /* When we did a conversion report an error. */
2051 if (iconv_fd != (iconv_t)-1 && conv_error == 0)
2052 conv_error = readfile_linenr(linecnt, ptr, p);
2053# endif
Bram Moolenaarf453d352008-06-04 17:37:34 +00002054 /* Remember the first linenr with an illegal byte */
2055 if (conv_error == 0 && illegal_byte == 0)
2056 illegal_byte = readfile_linenr(linecnt, ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002057
2058 /* Drop, keep or replace the bad byte. */
2059 if (bad_char_behavior == BAD_DROP)
2060 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002061 mch_memmove(p, p + 1, todo - 1);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002062 --p;
2063 --size;
2064 }
2065 else if (bad_char_behavior != BAD_KEEP)
2066 *p = bad_char_behavior;
2067 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002068 else
2069 p += l - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002070 }
2071 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002072 if (p < ptr + size && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002073 {
2074 /* Detected a UTF-8 error. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002075rewind_retry:
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002076 /* Retry reading with another conversion. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002077# if defined(FEAT_EVAL) && defined(USE_ICONV)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002078 if (*p_ccv != NUL && iconv_fd != (iconv_t)-1)
2079 /* iconv() failed, try 'charconvert' */
2080 did_iconv = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002081 else
2082# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002083 /* use next item from 'fileencodings' */
2084 advance_fenc = TRUE;
2085 file_rewind = TRUE;
2086 goto retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002087 }
2088 }
2089#endif
2090
2091 /* count the number of characters (after conversion!) */
2092 filesize += size;
2093
2094 /*
2095 * when reading the first part of a file: guess EOL type
2096 */
2097 if (fileformat == EOL_UNKNOWN)
2098 {
2099 /* First try finding a NL, for Dos and Unix */
2100 if (try_dos || try_unix)
2101 {
Bram Moolenaarc6b72172015-02-27 17:48:09 +01002102 /* Reset the carriage return counter. */
2103 if (try_mac)
2104 try_mac = 1;
2105
Bram Moolenaar071d4272004-06-13 20:20:40 +00002106 for (p = ptr; p < ptr + size; ++p)
2107 {
2108 if (*p == NL)
2109 {
2110 if (!try_unix
2111 || (try_dos && p > ptr && p[-1] == CAR))
2112 fileformat = EOL_DOS;
2113 else
2114 fileformat = EOL_UNIX;
2115 break;
2116 }
Bram Moolenaar05eb6122015-02-17 14:15:19 +01002117 else if (*p == CAR && try_mac)
2118 try_mac++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002119 }
2120
2121 /* Don't give in to EOL_UNIX if EOL_MAC is more likely */
2122 if (fileformat == EOL_UNIX && try_mac)
2123 {
2124 /* Need to reset the counters when retrying fenc. */
2125 try_mac = 1;
2126 try_unix = 1;
2127 for (; p >= ptr && *p != CAR; p--)
2128 ;
2129 if (p >= ptr)
2130 {
2131 for (p = ptr; p < ptr + size; ++p)
2132 {
2133 if (*p == NL)
2134 try_unix++;
2135 else if (*p == CAR)
2136 try_mac++;
2137 }
2138 if (try_mac > try_unix)
2139 fileformat = EOL_MAC;
2140 }
2141 }
Bram Moolenaar05eb6122015-02-17 14:15:19 +01002142 else if (fileformat == EOL_UNKNOWN && try_mac == 1)
2143 /* Looking for CR but found no end-of-line markers at
2144 * all: use the default format. */
2145 fileformat = default_fileformat();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002146 }
2147
2148 /* No NL found: may use Mac format */
2149 if (fileformat == EOL_UNKNOWN && try_mac)
2150 fileformat = EOL_MAC;
2151
2152 /* Still nothing found? Use first format in 'ffs' */
2153 if (fileformat == EOL_UNKNOWN)
2154 fileformat = default_fileformat();
2155
2156 /* if editing a new file: may set p_tx and p_ff */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002157 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002158 set_fileformat(fileformat, OPT_LOCAL);
2159 }
2160 }
2161
2162 /*
2163 * This loop is executed once for every character read.
2164 * Keep it fast!
2165 */
2166 if (fileformat == EOL_MAC)
2167 {
2168 --ptr;
2169 while (++ptr, --size >= 0)
2170 {
2171 /* catch most common case first */
2172 if ((c = *ptr) != NUL && c != CAR && c != NL)
2173 continue;
2174 if (c == NUL)
2175 *ptr = NL; /* NULs are replaced by newlines! */
2176 else if (c == NL)
2177 *ptr = CAR; /* NLs are replaced by CRs! */
2178 else
2179 {
2180 if (skip_count == 0)
2181 {
2182 *ptr = NUL; /* end of line */
2183 len = (colnr_T) (ptr - line_start + 1);
2184 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2185 {
2186 error = TRUE;
2187 break;
2188 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002189#ifdef FEAT_PERSISTENT_UNDO
2190 if (read_undo_file)
2191 sha256_update(&sha_ctx, line_start, len);
2192#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002193 ++lnum;
2194 if (--read_count == 0)
2195 {
2196 error = TRUE; /* break loop */
2197 line_start = ptr; /* nothing left to write */
2198 break;
2199 }
2200 }
2201 else
2202 --skip_count;
2203 line_start = ptr + 1;
2204 }
2205 }
2206 }
2207 else
2208 {
2209 --ptr;
2210 while (++ptr, --size >= 0)
2211 {
2212 if ((c = *ptr) != NUL && c != NL) /* catch most common case */
2213 continue;
2214 if (c == NUL)
2215 *ptr = NL; /* NULs are replaced by newlines! */
2216 else
2217 {
2218 if (skip_count == 0)
2219 {
2220 *ptr = NUL; /* end of line */
2221 len = (colnr_T)(ptr - line_start + 1);
2222 if (fileformat == EOL_DOS)
2223 {
2224 if (ptr[-1] == CAR) /* remove CR */
2225 {
2226 ptr[-1] = NUL;
2227 --len;
2228 }
2229 /*
2230 * Reading in Dos format, but no CR-LF found!
2231 * When 'fileformats' includes "unix", delete all
2232 * the lines read so far and start all over again.
2233 * Otherwise give an error message later.
2234 */
2235 else if (ff_error != EOL_DOS)
2236 {
2237 if ( try_unix
2238 && !read_stdin
2239 && (read_buffer
2240 || lseek(fd, (off_t)0L, SEEK_SET) == 0))
2241 {
2242 fileformat = EOL_UNIX;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002243 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002244 set_fileformat(EOL_UNIX, OPT_LOCAL);
2245 file_rewind = TRUE;
2246 keep_fileformat = TRUE;
2247 goto retry;
2248 }
2249 ff_error = EOL_DOS;
2250 }
2251 }
2252 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2253 {
2254 error = TRUE;
2255 break;
2256 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002257#ifdef FEAT_PERSISTENT_UNDO
2258 if (read_undo_file)
2259 sha256_update(&sha_ctx, line_start, len);
2260#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002261 ++lnum;
2262 if (--read_count == 0)
2263 {
2264 error = TRUE; /* break loop */
2265 line_start = ptr; /* nothing left to write */
2266 break;
2267 }
2268 }
2269 else
2270 --skip_count;
2271 line_start = ptr + 1;
2272 }
2273 }
2274 }
2275 linerest = (long)(ptr - line_start);
2276 ui_breakcheck();
2277 }
2278
2279failed:
2280 /* not an error, max. number of lines reached */
2281 if (error && read_count == 0)
2282 error = FALSE;
2283
2284 /*
2285 * If we get EOF in the middle of a line, note the fact and
2286 * complete the line ourselves.
2287 * In Dos format ignore a trailing CTRL-Z, unless 'binary' set.
2288 */
2289 if (!error
2290 && !got_int
2291 && linerest != 0
2292 && !(!curbuf->b_p_bin
2293 && fileformat == EOL_DOS
2294 && *line_start == Ctrl_Z
2295 && ptr == line_start + 1))
2296 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002297 /* remember for when writing */
2298 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002299 curbuf->b_p_eol = FALSE;
2300 *ptr = NUL;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002301 len = (colnr_T)(ptr - line_start + 1);
2302 if (ml_append(lnum, line_start, len, newfile) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002303 error = TRUE;
2304 else
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002305 {
2306#ifdef FEAT_PERSISTENT_UNDO
2307 if (read_undo_file)
2308 sha256_update(&sha_ctx, line_start, len);
2309#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002310 read_no_eol_lnum = ++lnum;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002311 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002312 }
2313
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002314 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002315 save_file_ff(curbuf); /* remember the current file format */
2316
2317#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002318 if (curbuf->b_cryptstate != NULL)
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002319 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002320 crypt_free_state(curbuf->b_cryptstate);
2321 curbuf->b_cryptstate = NULL;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002322 }
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002323 if (cryptkey != NULL && cryptkey != curbuf->b_p_key)
2324 crypt_free_key(cryptkey);
2325 /* Don't set cryptkey to NULL, it's used below as a flag that
2326 * encryption was used. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002327#endif
2328
2329#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002330 /* If editing a new file: set 'fenc' for the current buffer.
2331 * Also for ":read ++edit file". */
2332 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002333 set_string_option_direct((char_u *)"fenc", -1, fenc,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00002334 OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002335 if (fenc_alloced)
2336 vim_free(fenc);
2337# ifdef USE_ICONV
2338 if (iconv_fd != (iconv_t)-1)
2339 {
2340 iconv_close(iconv_fd);
2341 iconv_fd = (iconv_t)-1;
2342 }
2343# endif
2344#endif
2345
2346 if (!read_buffer && !read_stdin)
2347 close(fd); /* errors are ignored */
Bram Moolenaarf05da212009-11-17 16:13:15 +00002348#ifdef HAVE_FD_CLOEXEC
2349 else
2350 {
2351 int fdflags = fcntl(fd, F_GETFD);
2352 if (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0)
Bram Moolenaarfbc4b4d2016-02-07 15:14:01 +01002353 (void)fcntl(fd, F_SETFD, fdflags | FD_CLOEXEC);
Bram Moolenaarf05da212009-11-17 16:13:15 +00002354 }
2355#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002356 vim_free(buffer);
2357
2358#ifdef HAVE_DUP
2359 if (read_stdin)
2360 {
2361 /* Use stderr for stdin, makes shell commands work. */
2362 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00002363 ignored = dup(2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002364 }
2365#endif
2366
2367#ifdef FEAT_MBYTE
2368 if (tmpname != NULL)
2369 {
2370 mch_remove(tmpname); /* delete converted file */
2371 vim_free(tmpname);
2372 }
2373#endif
2374 --no_wait_return; /* may wait for return now */
2375
2376 /*
2377 * In recovery mode everything but autocommands is skipped.
2378 */
2379 if (!recoverymode)
2380 {
2381 /* need to delete the last line, which comes from the empty buffer */
2382 if (newfile && wasempty && !(curbuf->b_ml.ml_flags & ML_EMPTY))
2383 {
2384#ifdef FEAT_NETBEANS_INTG
2385 netbeansFireChanges = 0;
2386#endif
2387 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
2388#ifdef FEAT_NETBEANS_INTG
2389 netbeansFireChanges = 1;
2390#endif
2391 --linecnt;
2392 }
2393 linecnt = curbuf->b_ml.ml_line_count - linecnt;
2394 if (filesize == 0)
2395 linecnt = 0;
2396 if (newfile || read_buffer)
Bram Moolenaar7263a772007-05-10 17:35:54 +00002397 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002398 redraw_curbuf_later(NOT_VALID);
Bram Moolenaar7263a772007-05-10 17:35:54 +00002399#ifdef FEAT_DIFF
2400 /* After reading the text into the buffer the diff info needs to
2401 * be updated. */
2402 diff_invalidate(curbuf);
2403#endif
2404#ifdef FEAT_FOLDING
2405 /* All folds in the window are invalid now. Mark them for update
2406 * before triggering autocommands. */
2407 foldUpdateAll(curwin);
2408#endif
2409 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002410 else if (linecnt) /* appended at least one line */
2411 appended_lines_mark(from, linecnt);
2412
Bram Moolenaar071d4272004-06-13 20:20:40 +00002413#ifndef ALWAYS_USE_GUI
2414 /*
2415 * If we were reading from the same terminal as where messages go,
2416 * the screen will have been messed up.
2417 * Switch on raw mode now and clear the screen.
2418 */
2419 if (read_stdin)
2420 {
2421 settmode(TMODE_RAW); /* set to raw mode */
2422 starttermcap();
2423 screenclear();
2424 }
2425#endif
2426
2427 if (got_int)
2428 {
2429 if (!(flags & READ_DUMMY))
2430 {
2431 filemess(curbuf, sfname, (char_u *)_(e_interr), 0);
2432 if (newfile)
2433 curbuf->b_p_ro = TRUE; /* must use "w!" now */
2434 }
2435 msg_scroll = msg_save;
2436#ifdef FEAT_VIMINFO
2437 check_marks_read();
2438#endif
2439 return OK; /* an interrupt isn't really an error */
2440 }
2441
2442 if (!filtering && !(flags & READ_DUMMY))
2443 {
2444 msg_add_fname(curbuf, sfname); /* fname in IObuff with quotes */
2445 c = FALSE;
2446
2447#ifdef UNIX
2448# ifdef S_ISFIFO
2449 if (S_ISFIFO(perm)) /* fifo or socket */
2450 {
2451 STRCAT(IObuff, _("[fifo/socket]"));
2452 c = TRUE;
2453 }
2454# else
2455# ifdef S_IFIFO
2456 if ((perm & S_IFMT) == S_IFIFO) /* fifo */
2457 {
2458 STRCAT(IObuff, _("[fifo]"));
2459 c = TRUE;
2460 }
2461# endif
2462# ifdef S_IFSOCK
2463 if ((perm & S_IFMT) == S_IFSOCK) /* or socket */
2464 {
2465 STRCAT(IObuff, _("[socket]"));
2466 c = TRUE;
2467 }
2468# endif
2469# endif
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002470# ifdef OPEN_CHR_FILES
2471 if (S_ISCHR(perm)) /* or character special */
2472 {
2473 STRCAT(IObuff, _("[character special]"));
2474 c = TRUE;
2475 }
2476# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002477#endif
2478 if (curbuf->b_p_ro)
2479 {
2480 STRCAT(IObuff, shortmess(SHM_RO) ? _("[RO]") : _("[readonly]"));
2481 c = TRUE;
2482 }
2483 if (read_no_eol_lnum)
2484 {
2485 msg_add_eol();
2486 c = TRUE;
2487 }
2488 if (ff_error == EOL_DOS)
2489 {
2490 STRCAT(IObuff, _("[CR missing]"));
2491 c = TRUE;
2492 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002493 if (split)
2494 {
2495 STRCAT(IObuff, _("[long lines split]"));
2496 c = TRUE;
2497 }
2498#ifdef FEAT_MBYTE
2499 if (notconverted)
2500 {
2501 STRCAT(IObuff, _("[NOT converted]"));
2502 c = TRUE;
2503 }
2504 else if (converted)
2505 {
2506 STRCAT(IObuff, _("[converted]"));
2507 c = TRUE;
2508 }
2509#endif
2510#ifdef FEAT_CRYPT
2511 if (cryptkey != NULL)
2512 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002513 crypt_append_msg(curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002514 c = TRUE;
2515 }
2516#endif
2517#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002518 if (conv_error != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002519 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002520 sprintf((char *)IObuff + STRLEN(IObuff),
2521 _("[CONVERSION ERROR in line %ld]"), (long)conv_error);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002522 c = TRUE;
2523 }
2524 else if (illegal_byte > 0)
2525 {
2526 sprintf((char *)IObuff + STRLEN(IObuff),
2527 _("[ILLEGAL BYTE in line %ld]"), (long)illegal_byte);
2528 c = TRUE;
2529 }
2530 else
2531#endif
2532 if (error)
2533 {
2534 STRCAT(IObuff, _("[READ ERRORS]"));
2535 c = TRUE;
2536 }
2537 if (msg_add_fileformat(fileformat))
2538 c = TRUE;
2539#ifdef FEAT_CRYPT
2540 if (cryptkey != NULL)
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002541 msg_add_lines(c, (long)linecnt, filesize
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002542 - crypt_get_header_len(crypt_get_method_nr(curbuf)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002543 else
2544#endif
2545 msg_add_lines(c, (long)linecnt, filesize);
2546
2547 vim_free(keep_msg);
2548 keep_msg = NULL;
2549 msg_scrolled_ign = TRUE;
2550#ifdef ALWAYS_USE_GUI
2551 /* Don't show the message when reading stdin, it would end up in a
2552 * message box (which might be shown when exiting!) */
2553 if (read_stdin || read_buffer)
2554 p = msg_may_trunc(FALSE, IObuff);
2555 else
2556#endif
2557 p = msg_trunc_attr(IObuff, FALSE, 0);
2558 if (read_stdin || read_buffer || restart_edit != 0
Bram Moolenaar1c7715d2005-10-03 22:02:18 +00002559 || (msg_scrolled != 0 && !need_wait_return))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002560 /* Need to repeat the message after redrawing when:
2561 * - When reading from stdin (the screen will be cleared next).
2562 * - When restart_edit is set (otherwise there will be a delay
2563 * before redrawing).
2564 * - When the screen was scrolled but there is no wait-return
2565 * prompt. */
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002566 set_keep_msg(p, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002567 msg_scrolled_ign = FALSE;
2568 }
2569
2570 /* with errors writing the file requires ":w!" */
2571 if (newfile && (error
2572#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002573 || conv_error != 0
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002574 || (illegal_byte > 0 && bad_char_behavior != BAD_KEEP)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002575#endif
2576 ))
2577 curbuf->b_p_ro = TRUE;
2578
2579 u_clearline(); /* cannot use "U" command after adding lines */
2580
2581 /*
2582 * In Ex mode: cursor at last new line.
2583 * Otherwise: cursor at first new line.
2584 */
2585 if (exmode_active)
2586 curwin->w_cursor.lnum = from + linecnt;
2587 else
2588 curwin->w_cursor.lnum = from + 1;
2589 check_cursor_lnum();
2590 beginline(BL_WHITE | BL_FIX); /* on first non-blank */
2591
2592 /*
2593 * Set '[ and '] marks to the newly read lines.
2594 */
2595 curbuf->b_op_start.lnum = from + 1;
2596 curbuf->b_op_start.col = 0;
2597 curbuf->b_op_end.lnum = from + linecnt;
2598 curbuf->b_op_end.col = 0;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002599
2600#ifdef WIN32
2601 /*
2602 * Work around a weird problem: When a file has two links (only
2603 * possible on NTFS) and we write through one link, then stat() it
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00002604 * through the other link, the timestamp information may be wrong.
Bram Moolenaar03f48552006-02-28 23:52:23 +00002605 * It's correct again after reading the file, thus reset the timestamp
2606 * here.
2607 */
2608 if (newfile && !read_stdin && !read_buffer
2609 && mch_stat((char *)fname, &st) >= 0)
2610 {
2611 buf_store_time(curbuf, &st, fname);
2612 curbuf->b_mtime_read = curbuf->b_mtime;
2613 }
2614#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002615 }
2616 msg_scroll = msg_save;
2617
2618#ifdef FEAT_VIMINFO
2619 /*
2620 * Get the marks before executing autocommands, so they can be used there.
2621 */
2622 check_marks_read();
2623#endif
2624
Bram Moolenaar071d4272004-06-13 20:20:40 +00002625 /*
Bram Moolenaar34d72d42015-07-17 14:18:08 +02002626 * We remember if the last line of the read didn't have
2627 * an eol even when 'binary' is off, to support turning 'fixeol' off,
2628 * or writing the read again with 'binary' on. The latter is required
2629 * for ":autocmd FileReadPost *.gz set bin|'[,']!gunzip" to work.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002630 */
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002631 curbuf->b_no_eol_lnum = read_no_eol_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002632
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02002633 /* When reloading a buffer put the cursor at the first line that is
2634 * different. */
2635 if (flags & READ_KEEP_UNDO)
2636 u_find_first_changed();
2637
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002638#ifdef FEAT_PERSISTENT_UNDO
2639 /*
2640 * When opening a new file locate undo info and read it.
2641 */
2642 if (read_undo_file)
2643 {
2644 char_u hash[UNDO_HASH_SIZE];
2645
2646 sha256_finish(&sha_ctx, hash);
Bram Moolenaar6ed8ed82010-05-30 20:40:11 +02002647 u_read_undo(NULL, hash, fname);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002648 }
2649#endif
2650
Bram Moolenaardf177f62005-02-22 08:39:57 +00002651#ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00002652 if (!read_stdin && !read_buffer)
2653 {
2654 int m = msg_scroll;
2655 int n = msg_scrolled;
2656
2657 /* Save the fileformat now, otherwise the buffer will be considered
2658 * modified if the format/encoding was automatically detected. */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002659 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002660 save_file_ff(curbuf);
2661
2662 /*
2663 * The output from the autocommands should not overwrite anything and
2664 * should not be overwritten: Set msg_scroll, restore its value if no
2665 * output was done.
2666 */
2667 msg_scroll = TRUE;
2668 if (filtering)
2669 apply_autocmds_exarg(EVENT_FILTERREADPOST, NULL, sfname,
2670 FALSE, curbuf, eap);
2671 else if (newfile)
2672 apply_autocmds_exarg(EVENT_BUFREADPOST, NULL, sfname,
2673 FALSE, curbuf, eap);
2674 else
2675 apply_autocmds_exarg(EVENT_FILEREADPOST, sfname, sfname,
2676 FALSE, NULL, eap);
2677 if (msg_scrolled == n)
2678 msg_scroll = m;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002679# ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002680 if (aborting()) /* autocmds may abort script processing */
2681 return FAIL;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002682# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002683 }
2684#endif
2685
2686 if (recoverymode && error)
2687 return FAIL;
2688 return OK;
2689}
2690
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002691#ifdef OPEN_CHR_FILES
2692/*
2693 * Returns TRUE if the file name argument is of the form "/dev/fd/\d\+",
2694 * which is the name of files used for process substitution output by
2695 * some shells on some operating systems, e.g., bash on SunOS.
2696 * Do not accept "/dev/fd/[012]", opening these may hang Vim.
2697 */
2698 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002699is_dev_fd_file(char_u *fname)
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002700{
2701 return (STRNCMP(fname, "/dev/fd/", 8) == 0
2702 && VIM_ISDIGIT(fname[8])
2703 && *skipdigits(fname + 9) == NUL
2704 && (fname[9] != NUL
2705 || (fname[8] != '0' && fname[8] != '1' && fname[8] != '2')));
2706}
2707#endif
2708
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002709#ifdef FEAT_MBYTE
2710
2711/*
2712 * From the current line count and characters read after that, estimate the
2713 * line number where we are now.
2714 * Used for error messages that include a line number.
2715 */
2716 static linenr_T
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002717readfile_linenr(
2718 linenr_T linecnt, /* line count before reading more bytes */
2719 char_u *p, /* start of more bytes read */
2720 char_u *endp) /* end of more bytes read */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002721{
2722 char_u *s;
2723 linenr_T lnum;
2724
2725 lnum = curbuf->b_ml.ml_line_count - linecnt + 1;
2726 for (s = p; s < endp; ++s)
2727 if (*s == '\n')
2728 ++lnum;
2729 return lnum;
2730}
2731#endif
2732
Bram Moolenaar071d4272004-06-13 20:20:40 +00002733/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00002734 * Fill "*eap" to force the 'fileencoding', 'fileformat' and 'binary to be
2735 * equal to the buffer "buf". Used for calling readfile().
Bram Moolenaar071d4272004-06-13 20:20:40 +00002736 * Returns OK or FAIL.
2737 */
2738 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002739prep_exarg(exarg_T *eap, buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002740{
2741 eap->cmd = alloc((unsigned)(STRLEN(buf->b_p_ff)
2742#ifdef FEAT_MBYTE
2743 + STRLEN(buf->b_p_fenc)
2744#endif
2745 + 15));
2746 if (eap->cmd == NULL)
2747 return FAIL;
2748
2749#ifdef FEAT_MBYTE
2750 sprintf((char *)eap->cmd, "e ++ff=%s ++enc=%s", buf->b_p_ff, buf->b_p_fenc);
2751 eap->force_enc = 14 + (int)STRLEN(buf->b_p_ff);
Bram Moolenaar195d6352005-12-19 22:08:24 +00002752 eap->bad_char = buf->b_bad_char;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002753#else
2754 sprintf((char *)eap->cmd, "e ++ff=%s", buf->b_p_ff);
2755#endif
2756 eap->force_ff = 7;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002757
2758 eap->force_bin = buf->b_p_bin ? FORCE_BIN : FORCE_NOBIN;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002759 eap->read_edit = FALSE;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002760 eap->forceit = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002761 return OK;
2762}
2763
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002764/*
2765 * Set default or forced 'fileformat' and 'binary'.
2766 */
2767 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002768set_file_options(int set_options, exarg_T *eap)
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002769{
2770 /* set default 'fileformat' */
2771 if (set_options)
2772 {
2773 if (eap != NULL && eap->force_ff != 0)
2774 set_fileformat(get_fileformat_force(curbuf, eap), OPT_LOCAL);
2775 else if (*p_ffs != NUL)
2776 set_fileformat(default_fileformat(), OPT_LOCAL);
2777 }
2778
2779 /* set or reset 'binary' */
2780 if (eap != NULL && eap->force_bin != 0)
2781 {
2782 int oldval = curbuf->b_p_bin;
2783
2784 curbuf->b_p_bin = (eap->force_bin == FORCE_BIN);
2785 set_options_bin(oldval, curbuf->b_p_bin, OPT_LOCAL);
2786 }
2787}
2788
2789#if defined(FEAT_MBYTE) || defined(PROTO)
2790/*
2791 * Set forced 'fileencoding'.
2792 */
2793 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002794set_forced_fenc(exarg_T *eap)
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002795{
2796 if (eap->force_enc != 0)
2797 {
2798 char_u *fenc = enc_canonize(eap->cmd + eap->force_enc);
2799
2800 if (fenc != NULL)
2801 set_string_option_direct((char_u *)"fenc", -1,
2802 fenc, OPT_FREE|OPT_LOCAL, 0);
2803 vim_free(fenc);
2804 }
2805}
2806
Bram Moolenaar071d4272004-06-13 20:20:40 +00002807/*
2808 * Find next fileencoding to use from 'fileencodings'.
2809 * "pp" points to fenc_next. It's advanced to the next item.
2810 * When there are no more items, an empty string is returned and *pp is set to
2811 * NULL.
2812 * When *pp is not set to NULL, the result is in allocated memory.
2813 */
2814 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002815next_fenc(char_u **pp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002816{
2817 char_u *p;
2818 char_u *r;
2819
2820 if (**pp == NUL)
2821 {
2822 *pp = NULL;
2823 return (char_u *)"";
2824 }
2825 p = vim_strchr(*pp, ',');
2826 if (p == NULL)
2827 {
2828 r = enc_canonize(*pp);
2829 *pp += STRLEN(*pp);
2830 }
2831 else
2832 {
2833 r = vim_strnsave(*pp, (int)(p - *pp));
2834 *pp = p + 1;
2835 if (r != NULL)
2836 {
2837 p = enc_canonize(r);
2838 vim_free(r);
2839 r = p;
2840 }
2841 }
2842 if (r == NULL) /* out of memory */
2843 {
2844 r = (char_u *)"";
2845 *pp = NULL;
2846 }
2847 return r;
2848}
2849
2850# ifdef FEAT_EVAL
2851/*
2852 * Convert a file with the 'charconvert' expression.
2853 * This closes the file which is to be read, converts it and opens the
2854 * resulting file for reading.
2855 * Returns name of the resulting converted file (the caller should delete it
2856 * after reading it).
2857 * Returns NULL if the conversion failed ("*fdp" is not set) .
2858 */
2859 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002860readfile_charconvert(
2861 char_u *fname, /* name of input file */
2862 char_u *fenc, /* converted from */
2863 int *fdp) /* in/out: file descriptor of file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002864{
2865 char_u *tmpname;
2866 char_u *errmsg = NULL;
2867
Bram Moolenaare5c421c2015-03-31 13:33:08 +02002868 tmpname = vim_tempname('r', FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002869 if (tmpname == NULL)
2870 errmsg = (char_u *)_("Can't find temp file for conversion");
2871 else
2872 {
2873 close(*fdp); /* close the input file, ignore errors */
2874 *fdp = -1;
2875 if (eval_charconvert(fenc, enc_utf8 ? (char_u *)"utf-8" : p_enc,
2876 fname, tmpname) == FAIL)
2877 errmsg = (char_u *)_("Conversion with 'charconvert' failed");
2878 if (errmsg == NULL && (*fdp = mch_open((char *)tmpname,
2879 O_RDONLY | O_EXTRA, 0)) < 0)
2880 errmsg = (char_u *)_("can't read output of 'charconvert'");
2881 }
2882
2883 if (errmsg != NULL)
2884 {
2885 /* Don't use emsg(), it breaks mappings, the retry with
2886 * another type of conversion might still work. */
2887 MSG(errmsg);
2888 if (tmpname != NULL)
2889 {
2890 mch_remove(tmpname); /* delete converted file */
2891 vim_free(tmpname);
2892 tmpname = NULL;
2893 }
2894 }
2895
2896 /* If the input file is closed, open it (caller should check for error). */
2897 if (*fdp < 0)
2898 *fdp = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
2899
2900 return tmpname;
2901}
2902# endif
2903
2904#endif
2905
2906#ifdef FEAT_VIMINFO
2907/*
2908 * Read marks for the current buffer from the viminfo file, when we support
2909 * buffer marks and the buffer has a name.
2910 */
2911 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002912check_marks_read(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002913{
2914 if (!curbuf->b_marks_read && get_viminfo_parameter('\'') > 0
2915 && curbuf->b_ffname != NULL)
Bram Moolenaard812df62008-11-09 12:46:09 +00002916 read_viminfo(NULL, VIF_WANT_MARKS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002917
2918 /* Always set b_marks_read; needed when 'viminfo' is changed to include
2919 * the ' parameter after opening a buffer. */
2920 curbuf->b_marks_read = TRUE;
2921}
2922#endif
2923
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002924#if defined(FEAT_CRYPT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002925/*
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002926 * Check for magic number used for encryption. Applies to the current buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002927 * If found, the magic number is removed from ptr[*sizep] and *sizep and
2928 * *filesizep are updated.
2929 * Return the (new) encryption key, NULL for no encryption.
2930 */
2931 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002932check_for_cryptkey(
2933 char_u *cryptkey, /* previous encryption key or NULL */
2934 char_u *ptr, /* pointer to read bytes */
2935 long *sizep, /* length of read bytes */
2936 off_t *filesizep, /* nr of bytes used from file */
2937 int newfile, /* editing a new buffer */
2938 char_u *fname, /* file name to display */
2939 int *did_ask) /* flag: whether already asked for key */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002940{
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002941 int method = crypt_method_nr_from_magic((char *)ptr, *sizep);
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02002942 int b_p_ro = curbuf->b_p_ro;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002943
2944 if (method >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002945 {
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02002946 /* Mark the buffer as read-only until the decryption has taken place.
2947 * Avoids accidentally overwriting the file with garbage. */
2948 curbuf->b_p_ro = TRUE;
2949
Bram Moolenaar2be79502014-08-13 21:58:28 +02002950 /* Set the cryptmethod local to the buffer. */
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002951 crypt_set_cm_option(curbuf, method);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002952 if (cryptkey == NULL && !*did_ask)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002953 {
2954 if (*curbuf->b_p_key)
2955 cryptkey = curbuf->b_p_key;
2956 else
2957 {
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002958 /* When newfile is TRUE, store the typed key in the 'key'
2959 * option and don't free it. bf needs hash of the key saved.
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002960 * Don't ask for the key again when first time Enter was hit.
2961 * Happens when retrying to detect encoding. */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002962 smsg((char_u *)_(need_key_msg), fname);
2963 msg_scroll = TRUE;
Bram Moolenaar3a0c9082014-11-12 15:15:42 +01002964 crypt_check_method(method);
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002965 cryptkey = crypt_get_key(newfile, FALSE);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002966 *did_ask = TRUE;
2967
Bram Moolenaar071d4272004-06-13 20:20:40 +00002968 /* check if empty key entered */
2969 if (cryptkey != NULL && *cryptkey == NUL)
2970 {
2971 if (cryptkey != curbuf->b_p_key)
2972 vim_free(cryptkey);
2973 cryptkey = NULL;
2974 }
2975 }
2976 }
2977
2978 if (cryptkey != NULL)
2979 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002980 int header_len;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002981
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002982 curbuf->b_cryptstate = crypt_create_from_header(
2983 method, cryptkey, ptr);
2984 crypt_set_cm_option(curbuf, method);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002985
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002986 /* Remove cryptmethod specific header from the text. */
2987 header_len = crypt_get_header_len(method);
2988 *filesizep += header_len;
2989 *sizep -= header_len;
2990 mch_memmove(ptr, ptr + header_len, (size_t)*sizep);
2991
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02002992 /* Restore the read-only flag. */
2993 curbuf->b_p_ro = b_p_ro;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002994 }
2995 }
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002996 /* When starting to edit a new file which does not have encryption, clear
2997 * the 'key' option, except when starting up (called with -x argument) */
Bram Moolenaarfa0ff9a2010-07-25 16:05:19 +02002998 else if (newfile && *curbuf->b_p_key != NUL && !starting)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002999 set_option_value((char_u *)"key", 0L, (char_u *)"", OPT_LOCAL);
3000
3001 return cryptkey;
3002}
Bram Moolenaar80794b12010-06-13 05:20:42 +02003003#endif /* FEAT_CRYPT */
3004
Bram Moolenaar071d4272004-06-13 20:20:40 +00003005#ifdef UNIX
3006 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003007set_file_time(
3008 char_u *fname,
3009 time_t atime, /* access time */
3010 time_t mtime) /* modification time */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003011{
3012# if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
3013 struct utimbuf buf;
3014
3015 buf.actime = atime;
3016 buf.modtime = mtime;
3017 (void)utime((char *)fname, &buf);
3018# else
3019# if defined(HAVE_UTIMES)
3020 struct timeval tvp[2];
3021
3022 tvp[0].tv_sec = atime;
3023 tvp[0].tv_usec = 0;
3024 tvp[1].tv_sec = mtime;
3025 tvp[1].tv_usec = 0;
3026# ifdef NeXT
3027 (void)utimes((char *)fname, tvp);
3028# else
3029 (void)utimes((char *)fname, (const struct timeval *)&tvp);
3030# endif
3031# endif
3032# endif
3033}
3034#endif /* UNIX */
3035
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003036#if defined(VMS) && !defined(MIN)
3037/* Older DECC compiler for VAX doesn't define MIN() */
3038# define MIN(a, b) ((a) < (b) ? (a) : (b))
3039#endif
3040
Bram Moolenaar071d4272004-06-13 20:20:40 +00003041/*
Bram Moolenaar5386a122007-06-28 20:02:32 +00003042 * Return TRUE if a file appears to be read-only from the file permissions.
3043 */
3044 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003045check_file_readonly(
3046 char_u *fname, /* full path to file */
3047 int perm) /* known permissions on file */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003048{
3049#ifndef USE_MCH_ACCESS
3050 int fd = 0;
3051#endif
3052
3053 return (
3054#ifdef USE_MCH_ACCESS
3055# ifdef UNIX
3056 (perm & 0222) == 0 ||
3057# endif
3058 mch_access((char *)fname, W_OK)
3059#else
3060 (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0
3061 ? TRUE : (close(fd), FALSE)
3062#endif
3063 );
3064}
3065
3066
3067/*
Bram Moolenaar292ad192005-12-11 21:29:51 +00003068 * buf_write() - write to file "fname" lines "start" through "end"
Bram Moolenaar071d4272004-06-13 20:20:40 +00003069 *
3070 * We do our own buffering here because fwrite() is so slow.
3071 *
Bram Moolenaar292ad192005-12-11 21:29:51 +00003072 * If "forceit" is true, we don't care for errors when attempting backups.
3073 * In case of an error everything possible is done to restore the original
Bram Moolenaare37d50a2008-08-06 17:06:04 +00003074 * file. But when "forceit" is TRUE, we risk losing it.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003075 *
3076 * When "reset_changed" is TRUE and "append" == FALSE and "start" == 1 and
3077 * "end" == curbuf->b_ml.ml_line_count, reset curbuf->b_changed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003078 *
3079 * This function must NOT use NameBuff (because it's called by autowrite()).
3080 *
3081 * return FAIL for failure, OK otherwise
3082 */
3083 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003084buf_write(
3085 buf_T *buf,
3086 char_u *fname,
3087 char_u *sfname,
3088 linenr_T start,
3089 linenr_T end,
3090 exarg_T *eap, /* for forced 'ff' and 'fenc', can be
Bram Moolenaar071d4272004-06-13 20:20:40 +00003091 NULL! */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003092 int append, /* append to the file */
3093 int forceit,
3094 int reset_changed,
3095 int filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003096{
3097 int fd;
3098 char_u *backup = NULL;
3099 int backup_copy = FALSE; /* copy the original file? */
3100 int dobackup;
3101 char_u *ffname;
3102 char_u *wfname = NULL; /* name of file to write to */
3103 char_u *s;
3104 char_u *ptr;
3105 char_u c;
3106 int len;
3107 linenr_T lnum;
3108 long nchars;
3109 char_u *errmsg = NULL;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003110 int errmsg_allocated = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003111 char_u *errnum = NULL;
3112 char_u *buffer;
3113 char_u smallbuf[SMBUFSIZE];
3114 char_u *backup_ext;
3115 int bufsize;
3116 long perm; /* file permissions */
3117 int retval = OK;
3118 int newfile = FALSE; /* TRUE if file doesn't exist yet */
3119 int msg_save = msg_scroll;
3120 int overwriting; /* TRUE if writing over original */
3121 int no_eol = FALSE; /* no end-of-line written */
3122 int device = FALSE; /* writing to a device */
3123 struct stat st_old;
3124 int prev_got_int = got_int;
3125 int file_readonly = FALSE; /* overwritten file is read-only */
3126 static char *err_readonly = "is read-only (cannot override: \"W\" in 'cpoptions')";
3127#if defined(UNIX) || defined(__EMX__XX) /*XXX fix me sometime? */
3128 int made_writable = FALSE; /* 'w' bit has been set */
3129#endif
3130 /* writing everything */
3131 int whole = (start == 1 && end == buf->b_ml.ml_line_count);
3132#ifdef FEAT_AUTOCMD
3133 linenr_T old_line_count = buf->b_ml.ml_line_count;
3134#endif
3135 int attr;
3136 int fileformat;
3137 int write_bin;
3138 struct bw_info write_info; /* info for buf_write_bytes() */
3139#ifdef FEAT_MBYTE
3140 int converted = FALSE;
3141 int notconverted = FALSE;
3142 char_u *fenc; /* effective 'fileencoding' */
3143 char_u *fenc_tofree = NULL; /* allocated "fenc" */
3144#endif
3145#ifdef HAS_BW_FLAGS
3146 int wb_flags = 0;
3147#endif
3148#ifdef HAVE_ACL
3149 vim_acl_T acl = NULL; /* ACL copied from original file to
3150 backup or new file */
3151#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003152#ifdef FEAT_PERSISTENT_UNDO
3153 int write_undo_file = FALSE;
3154 context_sha256_T sha_ctx;
3155#endif
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003156 unsigned int bkc = get_bkc_value(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003157
3158 if (fname == NULL || *fname == NUL) /* safety check */
3159 return FAIL;
Bram Moolenaar70d60e92009-12-31 13:53:33 +00003160 if (buf->b_ml.ml_mfp == NULL)
3161 {
3162 /* This can happen during startup when there is a stray "w" in the
3163 * vimrc file. */
3164 EMSG(_(e_emptybuf));
3165 return FAIL;
3166 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003167
3168 /*
3169 * Disallow writing from .exrc and .vimrc in current directory for
3170 * security reasons.
3171 */
3172 if (check_secure())
3173 return FAIL;
3174
3175 /* Avoid a crash for a long name. */
3176 if (STRLEN(fname) >= MAXPATHL)
3177 {
3178 EMSG(_(e_longname));
3179 return FAIL;
3180 }
3181
3182#ifdef FEAT_MBYTE
3183 /* must init bw_conv_buf and bw_iconv_fd before jumping to "fail" */
3184 write_info.bw_conv_buf = NULL;
3185 write_info.bw_conv_error = FALSE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003186 write_info.bw_conv_error_lnum = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003187 write_info.bw_restlen = 0;
3188# ifdef USE_ICONV
3189 write_info.bw_iconv_fd = (iconv_t)-1;
3190# endif
3191#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003192#ifdef FEAT_CRYPT
3193 write_info.bw_buffer = buf;
3194#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003195
Bram Moolenaardf177f62005-02-22 08:39:57 +00003196 /* After writing a file changedtick changes but we don't want to display
3197 * the line. */
3198 ex_no_reprint = TRUE;
3199
Bram Moolenaar071d4272004-06-13 20:20:40 +00003200 /*
3201 * If there is no file name yet, use the one for the written file.
3202 * BF_NOTEDITED is set to reflect this (in case the write fails).
3203 * Don't do this when the write is for a filter command.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003204 * Don't do this when appending.
3205 * Only do this when 'cpoptions' contains the 'F' flag.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003206 */
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003207 if (buf->b_ffname == NULL
3208 && reset_changed
Bram Moolenaar071d4272004-06-13 20:20:40 +00003209 && whole
3210 && buf == curbuf
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00003211#ifdef FEAT_QUICKFIX
3212 && !bt_nofile(buf)
3213#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003214 && !filtering
Bram Moolenaar292ad192005-12-11 21:29:51 +00003215 && (!append || vim_strchr(p_cpo, CPO_FNAMEAPP) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003216 && vim_strchr(p_cpo, CPO_FNAMEW) != NULL)
3217 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003218 if (set_rw_fname(fname, sfname) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003219 return FAIL;
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003220 buf = curbuf; /* just in case autocmds made "buf" invalid */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003221 }
3222
3223 if (sfname == NULL)
3224 sfname = fname;
3225 /*
3226 * For Unix: Use the short file name whenever possible.
3227 * Avoids problems with networks and when directory names are changed.
3228 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
3229 * another directory, which we don't detect
3230 */
3231 ffname = fname; /* remember full fname */
3232#ifdef UNIX
3233 fname = sfname;
3234#endif
3235
3236 if (buf->b_ffname != NULL && fnamecmp(ffname, buf->b_ffname) == 0)
3237 overwriting = TRUE;
3238 else
3239 overwriting = FALSE;
3240
3241 if (exiting)
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003242 settmode(TMODE_COOK); /* when exiting allow typeahead now */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003243
3244 ++no_wait_return; /* don't wait for return yet */
3245
3246 /*
3247 * Set '[ and '] marks to the lines to be written.
3248 */
3249 buf->b_op_start.lnum = start;
3250 buf->b_op_start.col = 0;
3251 buf->b_op_end.lnum = end;
3252 buf->b_op_end.col = 0;
3253
3254#ifdef FEAT_AUTOCMD
3255 {
3256 aco_save_T aco;
3257 int buf_ffname = FALSE;
3258 int buf_sfname = FALSE;
3259 int buf_fname_f = FALSE;
3260 int buf_fname_s = FALSE;
3261 int did_cmd = FALSE;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003262 int nofile_err = FALSE;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003263 int empty_memline = (buf->b_ml.ml_mfp == NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003264
3265 /*
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003266 * Apply PRE autocommands.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003267 * Set curbuf to the buffer to be written.
3268 * Careful: The autocommands may call buf_write() recursively!
3269 */
3270 if (ffname == buf->b_ffname)
3271 buf_ffname = TRUE;
3272 if (sfname == buf->b_sfname)
3273 buf_sfname = TRUE;
3274 if (fname == buf->b_ffname)
3275 buf_fname_f = TRUE;
3276 if (fname == buf->b_sfname)
3277 buf_fname_s = TRUE;
3278
3279 /* set curwin/curbuf to buf and save a few things */
3280 aucmd_prepbuf(&aco, buf);
3281
3282 if (append)
3283 {
3284 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD,
3285 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003286 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003287#ifdef FEAT_QUICKFIX
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00003288 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003289 nofile_err = TRUE;
3290 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003291#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003292 apply_autocmds_exarg(EVENT_FILEAPPENDPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003293 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003294 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003295 }
3296 else if (filtering)
3297 {
3298 apply_autocmds_exarg(EVENT_FILTERWRITEPRE,
3299 NULL, sfname, FALSE, curbuf, eap);
3300 }
3301 else if (reset_changed && whole)
3302 {
Bram Moolenaar39fc42e2011-09-02 11:56:20 +02003303 int was_changed = curbufIsChanged();
3304
3305 did_cmd = apply_autocmds_exarg(EVENT_BUFWRITECMD,
3306 sfname, sfname, FALSE, curbuf, eap);
3307 if (did_cmd)
3308 {
3309 if (was_changed && !curbufIsChanged())
3310 {
3311 /* Written everything correctly and BufWriteCmd has reset
3312 * 'modified': Correct the undo information so that an
3313 * undo now sets 'modified'. */
3314 u_unchanged(curbuf);
3315 u_update_save_nr(curbuf);
3316 }
3317 }
3318 else
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003319 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003320#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003321 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003322 nofile_err = TRUE;
3323 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003324#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003325 apply_autocmds_exarg(EVENT_BUFWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003326 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003327 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003328 }
3329 else
3330 {
3331 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD,
3332 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003333 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003334#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003335 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003336 nofile_err = TRUE;
3337 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003338#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003339 apply_autocmds_exarg(EVENT_FILEWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003340 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003341 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003342 }
3343
3344 /* restore curwin/curbuf and a few other things */
3345 aucmd_restbuf(&aco);
3346
3347 /*
3348 * In three situations we return here and don't write the file:
3349 * 1. the autocommands deleted or unloaded the buffer.
3350 * 2. The autocommands abort script processing.
3351 * 3. If one of the "Cmd" autocommands was executed.
3352 */
3353 if (!buf_valid(buf))
3354 buf = NULL;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003355 if (buf == NULL || (buf->b_ml.ml_mfp == NULL && !empty_memline)
Bram Moolenaar1e015462005-09-25 22:16:38 +00003356 || did_cmd || nofile_err
3357#ifdef FEAT_EVAL
3358 || aborting()
3359#endif
3360 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003361 {
3362 --no_wait_return;
3363 msg_scroll = msg_save;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003364 if (nofile_err)
3365 EMSG(_("E676: No matching autocommands for acwrite buffer"));
3366
Bram Moolenaar1e015462005-09-25 22:16:38 +00003367 if (nofile_err
3368#ifdef FEAT_EVAL
3369 || aborting()
3370#endif
3371 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003372 /* An aborting error, interrupt or exception in the
3373 * autocommands. */
3374 return FAIL;
3375 if (did_cmd)
3376 {
3377 if (buf == NULL)
3378 /* The buffer was deleted. We assume it was written
3379 * (can't retry anyway). */
3380 return OK;
3381 if (overwriting)
3382 {
3383 /* Assume the buffer was written, update the timestamp. */
3384 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00003385 if (append)
3386 buf->b_flags &= ~BF_NEW;
3387 else
3388 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003389 }
Bram Moolenaar292ad192005-12-11 21:29:51 +00003390 if (reset_changed && buf->b_changed && !append
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003391 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003392 /* Buffer still changed, the autocommands didn't work
3393 * properly. */
3394 return FAIL;
3395 return OK;
3396 }
3397#ifdef FEAT_EVAL
3398 if (!aborting())
3399#endif
3400 EMSG(_("E203: Autocommands deleted or unloaded buffer to be written"));
3401 return FAIL;
3402 }
3403
3404 /*
3405 * The autocommands may have changed the number of lines in the file.
3406 * When writing the whole file, adjust the end.
3407 * When writing part of the file, assume that the autocommands only
3408 * changed the number of lines that are to be written (tricky!).
3409 */
3410 if (buf->b_ml.ml_line_count != old_line_count)
3411 {
3412 if (whole) /* write all */
3413 end = buf->b_ml.ml_line_count;
3414 else if (buf->b_ml.ml_line_count > old_line_count) /* more lines */
3415 end += buf->b_ml.ml_line_count - old_line_count;
3416 else /* less lines */
3417 {
3418 end -= old_line_count - buf->b_ml.ml_line_count;
3419 if (end < start)
3420 {
3421 --no_wait_return;
3422 msg_scroll = msg_save;
3423 EMSG(_("E204: Autocommand changed number of lines in unexpected way"));
3424 return FAIL;
3425 }
3426 }
3427 }
3428
3429 /*
3430 * The autocommands may have changed the name of the buffer, which may
3431 * be kept in fname, ffname and sfname.
3432 */
3433 if (buf_ffname)
3434 ffname = buf->b_ffname;
3435 if (buf_sfname)
3436 sfname = buf->b_sfname;
3437 if (buf_fname_f)
3438 fname = buf->b_ffname;
3439 if (buf_fname_s)
3440 fname = buf->b_sfname;
3441 }
3442#endif
3443
3444#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003445 if (netbeans_active() && isNetbeansBuffer(buf))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003446 {
3447 if (whole)
3448 {
3449 /*
3450 * b_changed can be 0 after an undo, but we still need to write
3451 * the buffer to NetBeans.
3452 */
3453 if (buf->b_changed || isNetbeansModified(buf))
3454 {
Bram Moolenaar009b2592004-10-24 19:18:58 +00003455 --no_wait_return; /* may wait for return now */
3456 msg_scroll = msg_save;
3457 netbeans_save_buffer(buf); /* no error checking... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003458 return retval;
3459 }
3460 else
3461 {
3462 errnum = (char_u *)"E656: ";
Bram Moolenaared0e7452008-06-27 19:17:34 +00003463 errmsg = (char_u *)_("NetBeans disallows writes of unmodified buffers");
Bram Moolenaar071d4272004-06-13 20:20:40 +00003464 buffer = NULL;
3465 goto fail;
3466 }
3467 }
3468 else
3469 {
3470 errnum = (char_u *)"E657: ";
3471 errmsg = (char_u *)_("Partial writes disallowed for NetBeans buffers");
3472 buffer = NULL;
3473 goto fail;
3474 }
3475 }
3476#endif
3477
3478 if (shortmess(SHM_OVER) && !exiting)
3479 msg_scroll = FALSE; /* overwrite previous file message */
3480 else
3481 msg_scroll = TRUE; /* don't overwrite previous file message */
3482 if (!filtering)
3483 filemess(buf,
3484#ifndef UNIX
3485 sfname,
3486#else
3487 fname,
3488#endif
3489 (char_u *)"", 0); /* show that we are busy */
3490 msg_scroll = FALSE; /* always overwrite the file message now */
3491
3492 buffer = alloc(BUFSIZE);
3493 if (buffer == NULL) /* can't allocate big buffer, use small
3494 * one (to be able to write when out of
3495 * memory) */
3496 {
3497 buffer = smallbuf;
3498 bufsize = SMBUFSIZE;
3499 }
3500 else
3501 bufsize = BUFSIZE;
3502
3503 /*
3504 * Get information about original file (if there is one).
3505 */
Bram Moolenaar53076832015-12-31 19:53:21 +01003506#if defined(UNIX)
Bram Moolenaar6f192452007-11-08 19:49:02 +00003507 st_old.st_dev = 0;
3508 st_old.st_ino = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003509 perm = -1;
3510 if (mch_stat((char *)fname, &st_old) < 0)
3511 newfile = TRUE;
3512 else
3513 {
3514 perm = st_old.st_mode;
3515 if (!S_ISREG(st_old.st_mode)) /* not a file */
3516 {
3517 if (S_ISDIR(st_old.st_mode))
3518 {
3519 errnum = (char_u *)"E502: ";
3520 errmsg = (char_u *)_("is a directory");
3521 goto fail;
3522 }
3523 if (mch_nodetype(fname) != NODE_WRITABLE)
3524 {
3525 errnum = (char_u *)"E503: ";
3526 errmsg = (char_u *)_("is not a file or writable device");
3527 goto fail;
3528 }
3529 /* It's a device of some kind (or a fifo) which we can write to
3530 * but for which we can't make a backup. */
3531 device = TRUE;
3532 newfile = TRUE;
3533 perm = -1;
3534 }
3535 }
3536#else /* !UNIX */
3537 /*
3538 * Check for a writable device name.
3539 */
3540 c = mch_nodetype(fname);
3541 if (c == NODE_OTHER)
3542 {
3543 errnum = (char_u *)"E503: ";
3544 errmsg = (char_u *)_("is not a file or writable device");
3545 goto fail;
3546 }
3547 if (c == NODE_WRITABLE)
3548 {
Bram Moolenaare7fedb62015-12-31 19:07:19 +01003549# if defined(MSDOS) || defined(MSWIN)
Bram Moolenaar043545e2006-10-10 16:44:07 +00003550 /* MS-Windows allows opening a device, but we will probably get stuck
3551 * trying to write to it. */
3552 if (!p_odev)
3553 {
3554 errnum = (char_u *)"E796: ";
3555 errmsg = (char_u *)_("writing to device disabled with 'opendevice' option");
3556 goto fail;
3557 }
3558# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003559 device = TRUE;
3560 newfile = TRUE;
3561 perm = -1;
3562 }
3563 else
3564 {
3565 perm = mch_getperm(fname);
3566 if (perm < 0)
3567 newfile = TRUE;
3568 else if (mch_isdir(fname))
3569 {
3570 errnum = (char_u *)"E502: ";
3571 errmsg = (char_u *)_("is a directory");
3572 goto fail;
3573 }
3574 if (overwriting)
3575 (void)mch_stat((char *)fname, &st_old);
3576 }
3577#endif /* !UNIX */
3578
3579 if (!device && !newfile)
3580 {
3581 /*
3582 * Check if the file is really writable (when renaming the file to
3583 * make a backup we won't discover it later).
3584 */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003585 file_readonly = check_file_readonly(fname, (int)perm);
3586
Bram Moolenaar071d4272004-06-13 20:20:40 +00003587 if (!forceit && file_readonly)
3588 {
3589 if (vim_strchr(p_cpo, CPO_FWRITE) != NULL)
3590 {
3591 errnum = (char_u *)"E504: ";
3592 errmsg = (char_u *)_(err_readonly);
3593 }
3594 else
3595 {
3596 errnum = (char_u *)"E505: ";
3597 errmsg = (char_u *)_("is read-only (add ! to override)");
3598 }
3599 goto fail;
3600 }
3601
3602 /*
3603 * Check if the timestamp hasn't changed since reading the file.
3604 */
3605 if (overwriting)
3606 {
3607 retval = check_mtime(buf, &st_old);
3608 if (retval == FAIL)
3609 goto fail;
3610 }
3611 }
3612
3613#ifdef HAVE_ACL
3614 /*
3615 * For systems that support ACL: get the ACL from the original file.
3616 */
3617 if (!newfile)
3618 acl = mch_get_acl(fname);
3619#endif
3620
3621 /*
3622 * If 'backupskip' is not empty, don't make a backup for some files.
3623 */
3624 dobackup = (p_wb || p_bk || *p_pm != NUL);
3625#ifdef FEAT_WILDIGN
3626 if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname))
3627 dobackup = FALSE;
3628#endif
3629
3630 /*
3631 * Save the value of got_int and reset it. We don't want a previous
3632 * interruption cancel writing, only hitting CTRL-C while writing should
3633 * abort it.
3634 */
3635 prev_got_int = got_int;
3636 got_int = FALSE;
3637
3638 /* Mark the buffer as 'being saved' to prevent changed buffer warnings */
3639 buf->b_saving = TRUE;
3640
3641 /*
3642 * If we are not appending or filtering, the file exists, and the
3643 * 'writebackup', 'backup' or 'patchmode' option is set, need a backup.
3644 * When 'patchmode' is set also make a backup when appending.
3645 *
3646 * Do not make any backup, if 'writebackup' and 'backup' are both switched
3647 * off. This helps when editing large files on almost-full disks.
3648 */
3649 if (!(append && *p_pm == NUL) && !filtering && perm >= 0 && dobackup)
3650 {
3651#if defined(UNIX) || defined(WIN32)
3652 struct stat st;
3653#endif
3654
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003655 if ((bkc & BKC_YES) || append) /* "yes" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003656 backup_copy = TRUE;
3657#if defined(UNIX) || defined(WIN32)
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003658 else if ((bkc & BKC_AUTO)) /* "auto" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003659 {
3660 int i;
3661
3662# ifdef UNIX
3663 /*
3664 * Don't rename the file when:
3665 * - it's a hard link
3666 * - it's a symbolic link
3667 * - we don't have write permission in the directory
3668 * - we can't set the owner/group of the new file
3669 */
3670 if (st_old.st_nlink > 1
3671 || mch_lstat((char *)fname, &st) < 0
3672 || st.st_dev != st_old.st_dev
Bram Moolenaara5792f52005-11-23 21:25:05 +00003673 || st.st_ino != st_old.st_ino
3674# ifndef HAVE_FCHOWN
3675 || st.st_uid != st_old.st_uid
3676 || st.st_gid != st_old.st_gid
3677# endif
3678 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003679 backup_copy = TRUE;
3680 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003681# else
3682# ifdef WIN32
3683 /* On NTFS file systems hard links are possible. */
3684 if (mch_is_linked(fname))
3685 backup_copy = TRUE;
3686 else
3687# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003688# endif
3689 {
3690 /*
3691 * Check if we can create a file and set the owner/group to
3692 * the ones from the original file.
3693 * First find a file name that doesn't exist yet (use some
3694 * arbitrary numbers).
3695 */
3696 STRCPY(IObuff, fname);
3697 for (i = 4913; ; i += 123)
3698 {
3699 sprintf((char *)gettail(IObuff), "%d", i);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003700 if (mch_lstat((char *)IObuff, &st) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003701 break;
3702 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00003703 fd = mch_open((char *)IObuff,
3704 O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003705 if (fd < 0) /* can't write in directory */
3706 backup_copy = TRUE;
3707 else
3708 {
3709# ifdef UNIX
Bram Moolenaara5792f52005-11-23 21:25:05 +00003710# ifdef HAVE_FCHOWN
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00003711 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003712# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003713 if (mch_stat((char *)IObuff, &st) < 0
3714 || st.st_uid != st_old.st_uid
3715 || st.st_gid != st_old.st_gid
Bram Moolenaar78a15312009-05-15 19:33:18 +00003716 || (long)st.st_mode != perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003717 backup_copy = TRUE;
3718# endif
Bram Moolenaar98358622005-11-28 22:58:23 +00003719 /* Close the file before removing it, on MS-Windows we
3720 * can't delete an open file. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003721 close(fd);
Bram Moolenaar98358622005-11-28 22:58:23 +00003722 mch_remove(IObuff);
Bram Moolenaar3479c5d2010-08-08 18:46:06 +02003723# ifdef MSWIN
3724 /* MS-Windows may trigger a virus scanner to open the
3725 * file, we can't delete it then. Keep trying for half a
3726 * second. */
3727 {
3728 int try;
3729
3730 for (try = 0; try < 10; ++try)
3731 {
3732 if (mch_lstat((char *)IObuff, &st) < 0)
3733 break;
3734 ui_delay(50L, TRUE); /* wait 50 msec */
3735 mch_remove(IObuff);
3736 }
3737 }
3738# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003739 }
3740 }
3741 }
3742
Bram Moolenaar071d4272004-06-13 20:20:40 +00003743 /*
3744 * Break symlinks and/or hardlinks if we've been asked to.
3745 */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003746 if ((bkc & BKC_BREAKSYMLINK) || (bkc & BKC_BREAKHARDLINK))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003747 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003748# ifdef UNIX
Bram Moolenaar071d4272004-06-13 20:20:40 +00003749 int lstat_res;
3750
3751 lstat_res = mch_lstat((char *)fname, &st);
3752
3753 /* Symlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003754 if ((bkc & BKC_BREAKSYMLINK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003755 && lstat_res == 0
3756 && st.st_ino != st_old.st_ino)
3757 backup_copy = FALSE;
3758
3759 /* Hardlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003760 if ((bkc & BKC_BREAKHARDLINK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003761 && st_old.st_nlink > 1
3762 && (lstat_res != 0 || st.st_ino == st_old.st_ino))
3763 backup_copy = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003764# else
3765# if defined(WIN32)
3766 /* Symlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003767 if ((bkc & BKC_BREAKSYMLINK) && mch_is_symbolic_link(fname))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003768 backup_copy = FALSE;
3769
3770 /* Hardlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003771 if ((bkc & BKC_BREAKHARDLINK) && mch_is_hard_link(fname))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003772 backup_copy = FALSE;
3773# endif
3774# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003775 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003776
3777#endif
3778
3779 /* make sure we have a valid backup extension to use */
3780 if (*p_bex == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003781 backup_ext = (char_u *)".bak";
Bram Moolenaar071d4272004-06-13 20:20:40 +00003782 else
3783 backup_ext = p_bex;
3784
3785 if (backup_copy
3786 && (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) >= 0)
3787 {
3788 int bfd;
3789 char_u *copybuf, *wp;
3790 int some_error = FALSE;
3791 struct stat st_new;
3792 char_u *dirp;
3793 char_u *rootname;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003794#if defined(UNIX) && !defined(SHORT_FNAME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003795 int did_set_shortname;
3796#endif
3797
3798 copybuf = alloc(BUFSIZE + 1);
3799 if (copybuf == NULL)
3800 {
3801 some_error = TRUE; /* out of memory */
3802 goto nobackup;
3803 }
3804
3805 /*
3806 * Try to make the backup in each directory in the 'bdir' option.
3807 *
3808 * Unix semantics has it, that we may have a writable file,
3809 * that cannot be recreated with a simple open(..., O_CREAT, ) e.g:
3810 * - the directory is not writable,
3811 * - the file may be a symbolic link,
3812 * - the file may belong to another user/group, etc.
3813 *
3814 * For these reasons, the existing writable file must be truncated
3815 * and reused. Creation of a backup COPY will be attempted.
3816 */
3817 dirp = p_bdir;
3818 while (*dirp)
3819 {
3820#ifdef UNIX
3821 st_new.st_ino = 0;
3822 st_new.st_dev = 0;
3823 st_new.st_gid = 0;
3824#endif
3825
3826 /*
3827 * Isolate one directory name, using an entry in 'bdir'.
3828 */
3829 (void)copy_option_part(&dirp, copybuf, BUFSIZE, ",");
3830 rootname = get_file_in_dir(fname, copybuf);
3831 if (rootname == NULL)
3832 {
3833 some_error = TRUE; /* out of memory */
3834 goto nobackup;
3835 }
3836
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003837#if defined(UNIX) && !defined(SHORT_FNAME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003838 did_set_shortname = FALSE;
3839#endif
3840
3841 /*
3842 * May try twice if 'shortname' not set.
3843 */
3844 for (;;)
3845 {
3846 /*
3847 * Make backup file name.
3848 */
3849 backup = buf_modname(
3850#ifdef SHORT_FNAME
3851 TRUE,
3852#else
3853 (buf->b_p_sn || buf->b_shortname),
3854#endif
3855 rootname, backup_ext, FALSE);
3856 if (backup == NULL)
3857 {
3858 vim_free(rootname);
3859 some_error = TRUE; /* out of memory */
3860 goto nobackup;
3861 }
3862
3863 /*
3864 * Check if backup file already exists.
3865 */
3866 if (mch_stat((char *)backup, &st_new) >= 0)
3867 {
3868#ifdef UNIX
3869 /*
3870 * Check if backup file is same as original file.
3871 * May happen when modname() gave the same file back.
3872 * E.g. silly link, or file name-length reached.
3873 * If we don't check here, we either ruin the file
3874 * when copying or erase it after writing. jw.
3875 */
3876 if (st_new.st_dev == st_old.st_dev
3877 && st_new.st_ino == st_old.st_ino)
3878 {
3879 vim_free(backup);
3880 backup = NULL; /* no backup file to delete */
3881# ifndef SHORT_FNAME
3882 /*
3883 * may try again with 'shortname' set
3884 */
3885 if (!(buf->b_shortname || buf->b_p_sn))
3886 {
3887 buf->b_shortname = TRUE;
3888 did_set_shortname = TRUE;
3889 continue;
3890 }
3891 /* setting shortname didn't help */
3892 if (did_set_shortname)
3893 buf->b_shortname = FALSE;
3894# endif
3895 break;
3896 }
3897#endif
3898
3899 /*
3900 * If we are not going to keep the backup file, don't
3901 * delete an existing one, try to use another name.
3902 * Change one character, just before the extension.
3903 */
3904 if (!p_bk)
3905 {
3906 wp = backup + STRLEN(backup) - 1
3907 - STRLEN(backup_ext);
3908 if (wp < backup) /* empty file name ??? */
3909 wp = backup;
3910 *wp = 'z';
3911 while (*wp > 'a'
3912 && mch_stat((char *)backup, &st_new) >= 0)
3913 --*wp;
3914 /* They all exist??? Must be something wrong. */
3915 if (*wp == 'a')
3916 {
3917 vim_free(backup);
3918 backup = NULL;
3919 }
3920 }
3921 }
3922 break;
3923 }
3924 vim_free(rootname);
3925
3926 /*
3927 * Try to create the backup file
3928 */
3929 if (backup != NULL)
3930 {
3931 /* remove old backup, if present */
3932 mch_remove(backup);
3933 /* Open with O_EXCL to avoid the file being created while
3934 * we were sleeping (symlink hacker attack?) */
3935 bfd = mch_open((char *)backup,
Bram Moolenaara5792f52005-11-23 21:25:05 +00003936 O_WRONLY|O_CREAT|O_EXTRA|O_EXCL|O_NOFOLLOW,
3937 perm & 0777);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003938 if (bfd < 0)
3939 {
3940 vim_free(backup);
3941 backup = NULL;
3942 }
3943 else
3944 {
3945 /* set file protection same as original file, but
3946 * strip s-bit */
3947 (void)mch_setperm(backup, perm & 0777);
3948
3949#ifdef UNIX
3950 /*
3951 * Try to set the group of the backup same as the
3952 * original file. If this fails, set the protection
3953 * bits for the group same as the protection bits for
3954 * others.
3955 */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003956 if (st_new.st_gid != st_old.st_gid
Bram Moolenaar071d4272004-06-13 20:20:40 +00003957# ifdef HAVE_FCHOWN /* sequent-ptx lacks fchown() */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003958 && fchown(bfd, (uid_t)-1, st_old.st_gid) != 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00003959# endif
3960 )
3961 mch_setperm(backup,
3962 (perm & 0707) | ((perm & 07) << 3));
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02003963# if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00003964 mch_copy_sec(fname, backup);
3965# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003966#endif
3967
3968 /*
3969 * copy the file.
3970 */
3971 write_info.bw_fd = bfd;
3972 write_info.bw_buf = copybuf;
3973#ifdef HAS_BW_FLAGS
3974 write_info.bw_flags = FIO_NOCONVERT;
3975#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01003976 while ((write_info.bw_len = read_eintr(fd, copybuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003977 BUFSIZE)) > 0)
3978 {
3979 if (buf_write_bytes(&write_info) == FAIL)
3980 {
3981 errmsg = (char_u *)_("E506: Can't write to backup file (add ! to override)");
3982 break;
3983 }
3984 ui_breakcheck();
3985 if (got_int)
3986 {
3987 errmsg = (char_u *)_(e_interr);
3988 break;
3989 }
3990 }
3991
3992 if (close(bfd) < 0 && errmsg == NULL)
3993 errmsg = (char_u *)_("E507: Close error for backup file (add ! to override)");
3994 if (write_info.bw_len < 0)
3995 errmsg = (char_u *)_("E508: Can't read file for backup (add ! to override)");
3996#ifdef UNIX
3997 set_file_time(backup, st_old.st_atime, st_old.st_mtime);
3998#endif
3999#ifdef HAVE_ACL
4000 mch_set_acl(backup, acl);
4001#endif
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004002#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004003 mch_copy_sec(fname, backup);
4004#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004005 break;
4006 }
4007 }
4008 }
4009 nobackup:
4010 close(fd); /* ignore errors for closing read file */
4011 vim_free(copybuf);
4012
4013 if (backup == NULL && errmsg == NULL)
4014 errmsg = (char_u *)_("E509: Cannot create backup file (add ! to override)");
4015 /* ignore errors when forceit is TRUE */
4016 if ((some_error || errmsg != NULL) && !forceit)
4017 {
4018 retval = FAIL;
4019 goto fail;
4020 }
4021 errmsg = NULL;
4022 }
4023 else
4024 {
4025 char_u *dirp;
4026 char_u *p;
4027 char_u *rootname;
4028
4029 /*
4030 * Make a backup by renaming the original file.
4031 */
4032 /*
4033 * If 'cpoptions' includes the "W" flag, we don't want to
4034 * overwrite a read-only file. But rename may be possible
4035 * anyway, thus we need an extra check here.
4036 */
4037 if (file_readonly && vim_strchr(p_cpo, CPO_FWRITE) != NULL)
4038 {
4039 errnum = (char_u *)"E504: ";
4040 errmsg = (char_u *)_(err_readonly);
4041 goto fail;
4042 }
4043
4044 /*
4045 *
4046 * Form the backup file name - change path/fo.o.h to
4047 * path/fo.o.h.bak Try all directories in 'backupdir', first one
4048 * that works is used.
4049 */
4050 dirp = p_bdir;
4051 while (*dirp)
4052 {
4053 /*
4054 * Isolate one directory name and make the backup file name.
4055 */
4056 (void)copy_option_part(&dirp, IObuff, IOSIZE, ",");
4057 rootname = get_file_in_dir(fname, IObuff);
4058 if (rootname == NULL)
4059 backup = NULL;
4060 else
4061 {
4062 backup = buf_modname(
4063#ifdef SHORT_FNAME
4064 TRUE,
4065#else
4066 (buf->b_p_sn || buf->b_shortname),
4067#endif
4068 rootname, backup_ext, FALSE);
4069 vim_free(rootname);
4070 }
4071
4072 if (backup != NULL)
4073 {
4074 /*
4075 * If we are not going to keep the backup file, don't
4076 * delete an existing one, try to use another name.
4077 * Change one character, just before the extension.
4078 */
4079 if (!p_bk && mch_getperm(backup) >= 0)
4080 {
4081 p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext);
4082 if (p < backup) /* empty file name ??? */
4083 p = backup;
4084 *p = 'z';
4085 while (*p > 'a' && mch_getperm(backup) >= 0)
4086 --*p;
4087 /* They all exist??? Must be something wrong! */
4088 if (*p == 'a')
4089 {
4090 vim_free(backup);
4091 backup = NULL;
4092 }
4093 }
4094 }
4095 if (backup != NULL)
4096 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004097 /*
Bram Moolenaarbfd8fc02005-09-20 23:22:24 +00004098 * Delete any existing backup and move the current version
4099 * to the backup. For safety, we don't remove the backup
4100 * until the write has finished successfully. And if the
4101 * 'backup' option is set, leave it around.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004102 */
4103 /*
4104 * If the renaming of the original file to the backup file
4105 * works, quit here.
4106 */
4107 if (vim_rename(fname, backup) == 0)
4108 break;
4109
4110 vim_free(backup); /* don't do the rename below */
4111 backup = NULL;
4112 }
4113 }
4114 if (backup == NULL && !forceit)
4115 {
4116 errmsg = (char_u *)_("E510: Can't make backup file (add ! to override)");
4117 goto fail;
4118 }
4119 }
4120 }
4121
Bram Moolenaar53076832015-12-31 19:53:21 +01004122#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004123 /* When using ":w!" and the file was read-only: make it writable */
4124 if (forceit && perm >= 0 && !(perm & 0200) && st_old.st_uid == getuid()
4125 && vim_strchr(p_cpo, CPO_FWRITE) == NULL)
4126 {
4127 perm |= 0200;
4128 (void)mch_setperm(fname, perm);
4129 made_writable = TRUE;
4130 }
4131#endif
4132
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004133 /* When using ":w!" and writing to the current file, 'readonly' makes no
Bram Moolenaar4399ef42005-02-12 14:29:27 +00004134 * sense, reset it, unless 'Z' appears in 'cpoptions'. */
4135 if (forceit && overwriting && vim_strchr(p_cpo, CPO_KEEPRO) == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004136 {
4137 buf->b_p_ro = FALSE;
4138#ifdef FEAT_TITLE
4139 need_maketitle = TRUE; /* set window title later */
4140#endif
4141#ifdef FEAT_WINDOWS
4142 status_redraw_all(); /* redraw status lines later */
4143#endif
4144 }
4145
4146 if (end > buf->b_ml.ml_line_count)
4147 end = buf->b_ml.ml_line_count;
4148 if (buf->b_ml.ml_flags & ML_EMPTY)
4149 start = end + 1;
4150
4151 /*
4152 * If the original file is being overwritten, there is a small chance that
4153 * we crash in the middle of writing. Therefore the file is preserved now.
4154 * This makes all block numbers positive so that recovery does not need
4155 * the original file.
4156 * Don't do this if there is a backup file and we are exiting.
4157 */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004158 if (reset_changed && !newfile && overwriting
Bram Moolenaar071d4272004-06-13 20:20:40 +00004159 && !(exiting && backup != NULL))
4160 {
4161 ml_preserve(buf, FALSE);
4162 if (got_int)
4163 {
4164 errmsg = (char_u *)_(e_interr);
4165 goto restore_backup;
4166 }
4167 }
4168
4169#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
4170 /*
4171 * Before risking to lose the original file verify if there's
4172 * a resource fork to preserve, and if cannot be done warn
4173 * the users. This happens when overwriting without backups.
4174 */
4175 if (backup == NULL && overwriting && !append)
4176 if (mch_has_resource_fork(fname))
4177 {
4178 errmsg = (char_u *)_("E460: The resource fork would be lost (add ! to override)");
4179 goto restore_backup;
4180 }
4181#endif
4182
4183#ifdef VMS
4184 vms_remove_version(fname); /* remove version */
4185#endif
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00004186 /* Default: write the file directly. May write to a temp file for
Bram Moolenaar071d4272004-06-13 20:20:40 +00004187 * multi-byte conversion. */
4188 wfname = fname;
4189
4190#ifdef FEAT_MBYTE
4191 /* Check for forced 'fileencoding' from "++opt=val" argument. */
4192 if (eap != NULL && eap->force_enc != 0)
4193 {
4194 fenc = eap->cmd + eap->force_enc;
4195 fenc = enc_canonize(fenc);
4196 fenc_tofree = fenc;
4197 }
4198 else
4199 fenc = buf->b_p_fenc;
4200
4201 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004202 * Check if the file needs to be converted.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004203 */
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004204 converted = need_conversion(fenc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004205
4206 /*
4207 * Check if UTF-8 to UCS-2/4 or Latin1 conversion needs to be done. Or
4208 * Latin1 to Unicode conversion. This is handled in buf_write_bytes().
4209 * Prepare the flags for it and allocate bw_conv_buf when needed.
4210 */
4211 if (converted && (enc_utf8 || STRCMP(p_enc, "latin1") == 0))
4212 {
4213 wb_flags = get_fio_flags(fenc);
4214 if (wb_flags & (FIO_UCS2 | FIO_UCS4 | FIO_UTF16 | FIO_UTF8))
4215 {
4216 /* Need to allocate a buffer to translate into. */
4217 if (wb_flags & (FIO_UCS2 | FIO_UTF16 | FIO_UTF8))
4218 write_info.bw_conv_buflen = bufsize * 2;
4219 else /* FIO_UCS4 */
4220 write_info.bw_conv_buflen = bufsize * 4;
4221 write_info.bw_conv_buf
4222 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4223 if (write_info.bw_conv_buf == NULL)
4224 end = 0;
4225 }
4226 }
4227
4228# ifdef WIN3264
4229 if (converted && wb_flags == 0 && (wb_flags = get_win_fio_flags(fenc)) != 0)
4230 {
4231 /* Convert UTF-8 -> UCS-2 and UCS-2 -> DBCS. Worst-case * 4: */
4232 write_info.bw_conv_buflen = bufsize * 4;
4233 write_info.bw_conv_buf
4234 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4235 if (write_info.bw_conv_buf == NULL)
4236 end = 0;
4237 }
4238# endif
4239
4240# ifdef MACOS_X
4241 if (converted && wb_flags == 0 && (wb_flags = get_mac_fio_flags(fenc)) != 0)
4242 {
4243 write_info.bw_conv_buflen = bufsize * 3;
4244 write_info.bw_conv_buf
4245 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4246 if (write_info.bw_conv_buf == NULL)
4247 end = 0;
4248 }
4249# endif
4250
4251# if defined(FEAT_EVAL) || defined(USE_ICONV)
4252 if (converted && wb_flags == 0)
4253 {
4254# ifdef USE_ICONV
4255 /*
4256 * Use iconv() conversion when conversion is needed and it's not done
4257 * internally.
4258 */
4259 write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc,
4260 enc_utf8 ? (char_u *)"utf-8" : p_enc);
4261 if (write_info.bw_iconv_fd != (iconv_t)-1)
4262 {
4263 /* We're going to use iconv(), allocate a buffer to convert in. */
4264 write_info.bw_conv_buflen = bufsize * ICONV_MULT;
4265 write_info.bw_conv_buf
4266 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4267 if (write_info.bw_conv_buf == NULL)
4268 end = 0;
4269 write_info.bw_first = TRUE;
4270 }
4271# ifdef FEAT_EVAL
4272 else
4273# endif
4274# endif
4275
4276# ifdef FEAT_EVAL
4277 /*
4278 * When the file needs to be converted with 'charconvert' after
4279 * writing, write to a temp file instead and let the conversion
4280 * overwrite the original file.
4281 */
4282 if (*p_ccv != NUL)
4283 {
Bram Moolenaare5c421c2015-03-31 13:33:08 +02004284 wfname = vim_tempname('w', FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004285 if (wfname == NULL) /* Can't write without a tempfile! */
4286 {
4287 errmsg = (char_u *)_("E214: Can't find temp file for writing");
4288 goto restore_backup;
4289 }
4290 }
4291# endif
4292 }
4293# endif
4294 if (converted && wb_flags == 0
4295# ifdef USE_ICONV
4296 && write_info.bw_iconv_fd == (iconv_t)-1
4297# endif
4298# ifdef FEAT_EVAL
4299 && wfname == fname
4300# endif
4301 )
4302 {
4303 if (!forceit)
4304 {
4305 errmsg = (char_u *)_("E213: Cannot convert (add ! to write without conversion)");
4306 goto restore_backup;
4307 }
4308 notconverted = TRUE;
4309 }
4310#endif
4311
4312 /*
4313 * Open the file "wfname" for writing.
4314 * We may try to open the file twice: If we can't write to the
4315 * file and forceit is TRUE we delete the existing file and try to create
4316 * a new one. If this still fails we may have lost the original file!
4317 * (this may happen when the user reached his quotum for number of files).
4318 * Appending will fail if the file does not exist and forceit is FALSE.
4319 */
4320 while ((fd = mch_open((char *)wfname, O_WRONLY | O_EXTRA | (append
4321 ? (forceit ? (O_APPEND | O_CREAT) : O_APPEND)
4322 : (O_CREAT | O_TRUNC))
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00004323 , perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004324 {
4325 /*
4326 * A forced write will try to create a new file if the old one is
4327 * still readonly. This may also happen when the directory is
4328 * read-only. In that case the mch_remove() will fail.
4329 */
4330 if (errmsg == NULL)
4331 {
4332#ifdef UNIX
4333 struct stat st;
4334
4335 /* Don't delete the file when it's a hard or symbolic link. */
4336 if ((!newfile && st_old.st_nlink > 1)
4337 || (mch_lstat((char *)fname, &st) == 0
4338 && (st.st_dev != st_old.st_dev
4339 || st.st_ino != st_old.st_ino)))
4340 errmsg = (char_u *)_("E166: Can't open linked file for writing");
4341 else
4342#endif
4343 {
4344 errmsg = (char_u *)_("E212: Can't open file for writing");
4345 if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL
4346 && perm >= 0)
4347 {
4348#ifdef UNIX
4349 /* we write to the file, thus it should be marked
4350 writable after all */
4351 if (!(perm & 0200))
4352 made_writable = TRUE;
4353 perm |= 0200;
4354 if (st_old.st_uid != getuid() || st_old.st_gid != getgid())
4355 perm &= 0777;
4356#endif
4357 if (!append) /* don't remove when appending */
4358 mch_remove(wfname);
4359 continue;
4360 }
4361 }
4362 }
4363
4364restore_backup:
4365 {
4366 struct stat st;
4367
4368 /*
4369 * If we failed to open the file, we don't need a backup. Throw it
4370 * away. If we moved or removed the original file try to put the
4371 * backup in its place.
4372 */
4373 if (backup != NULL && wfname == fname)
4374 {
4375 if (backup_copy)
4376 {
4377 /*
4378 * There is a small chance that we removed the original,
4379 * try to move the copy in its place.
4380 * This may not work if the vim_rename() fails.
4381 * In that case we leave the copy around.
4382 */
4383 /* If file does not exist, put the copy in its place */
4384 if (mch_stat((char *)fname, &st) < 0)
4385 vim_rename(backup, fname);
4386 /* if original file does exist throw away the copy */
4387 if (mch_stat((char *)fname, &st) >= 0)
4388 mch_remove(backup);
4389 }
4390 else
4391 {
4392 /* try to put the original file back */
4393 vim_rename(backup, fname);
4394 }
4395 }
4396
4397 /* if original file no longer exists give an extra warning */
4398 if (!newfile && mch_stat((char *)fname, &st) < 0)
4399 end = 0;
4400 }
4401
4402#ifdef FEAT_MBYTE
4403 if (wfname != fname)
4404 vim_free(wfname);
4405#endif
4406 goto fail;
4407 }
4408 errmsg = NULL;
4409
4410#if defined(MACOS_CLASSIC) || defined(WIN3264)
4411 /* TODO: Is it need for MACOS_X? (Dany) */
4412 /*
4413 * On macintosh copy the original files attributes (i.e. the backup)
Bram Moolenaar7263a772007-05-10 17:35:54 +00004414 * This is done in order to preserve the resource fork and the
4415 * Finder attribute (label, comments, custom icons, file creator)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004416 */
4417 if (backup != NULL && overwriting && !append)
4418 {
4419 if (backup_copy)
4420 (void)mch_copy_file_attribute(wfname, backup);
4421 else
4422 (void)mch_copy_file_attribute(backup, wfname);
4423 }
4424
4425 if (!overwriting && !append)
4426 {
4427 if (buf->b_ffname != NULL)
4428 (void)mch_copy_file_attribute(buf->b_ffname, wfname);
Bram Moolenaar7263a772007-05-10 17:35:54 +00004429 /* Should copy resource fork */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004430 }
4431#endif
4432
4433 write_info.bw_fd = fd;
4434
4435#ifdef FEAT_CRYPT
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004436 if (*buf->b_p_key != NUL && !filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004437 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004438 char_u *header;
4439 int header_len;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004440
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004441 buf->b_cryptstate = crypt_create_for_writing(crypt_get_method_nr(buf),
4442 buf->b_p_key, &header, &header_len);
4443 if (buf->b_cryptstate == NULL || header == NULL)
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02004444 end = 0;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004445 else
4446 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004447 /* Write magic number, so that Vim knows how this file is
4448 * encrypted when reading it back. */
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02004449 write_info.bw_buf = header;
4450 write_info.bw_len = header_len;
4451 write_info.bw_flags = FIO_NOCONVERT;
4452 if (buf_write_bytes(&write_info) == FAIL)
4453 end = 0;
4454 wb_flags |= FIO_ENCRYPTED;
4455 vim_free(header);
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004456 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004457 }
4458#endif
4459
4460 write_info.bw_buf = buffer;
4461 nchars = 0;
4462
4463 /* use "++bin", "++nobin" or 'binary' */
4464 if (eap != NULL && eap->force_bin != 0)
4465 write_bin = (eap->force_bin == FORCE_BIN);
4466 else
4467 write_bin = buf->b_p_bin;
4468
4469#ifdef FEAT_MBYTE
4470 /*
4471 * The BOM is written just after the encryption magic number.
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004472 * Skip it when appending and the file already existed, the BOM only makes
4473 * sense at the start of the file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004474 */
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004475 if (buf->b_p_bomb && !write_bin && (!append || perm < 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004476 {
4477 write_info.bw_len = make_bom(buffer, fenc);
4478 if (write_info.bw_len > 0)
4479 {
4480 /* don't convert, do encryption */
4481 write_info.bw_flags = FIO_NOCONVERT | wb_flags;
4482 if (buf_write_bytes(&write_info) == FAIL)
4483 end = 0;
4484 else
4485 nchars += write_info.bw_len;
4486 }
4487 }
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004488 write_info.bw_start_lnum = start;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004489#endif
4490
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004491#ifdef FEAT_PERSISTENT_UNDO
4492 write_undo_file = (buf->b_p_udf && overwriting && !append
4493 && !filtering && reset_changed);
4494 if (write_undo_file)
4495 /* Prepare for computing the hash value of the text. */
4496 sha256_start(&sha_ctx);
4497#endif
4498
Bram Moolenaar071d4272004-06-13 20:20:40 +00004499 write_info.bw_len = bufsize;
4500#ifdef HAS_BW_FLAGS
4501 write_info.bw_flags = wb_flags;
4502#endif
4503 fileformat = get_fileformat_force(buf, eap);
4504 s = buffer;
4505 len = 0;
4506 for (lnum = start; lnum <= end; ++lnum)
4507 {
4508 /*
4509 * The next while loop is done once for each character written.
4510 * Keep it fast!
4511 */
4512 ptr = ml_get_buf(buf, lnum, FALSE) - 1;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004513#ifdef FEAT_PERSISTENT_UNDO
4514 if (write_undo_file)
Bram Moolenaar442b4222010-05-24 21:34:22 +02004515 sha256_update(&sha_ctx, ptr + 1, (UINT32_T)(STRLEN(ptr + 1) + 1));
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004516#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004517 while ((c = *++ptr) != NUL)
4518 {
4519 if (c == NL)
4520 *s = NUL; /* replace newlines with NULs */
4521 else if (c == CAR && fileformat == EOL_MAC)
4522 *s = NL; /* Mac: replace CRs with NLs */
4523 else
4524 *s = c;
4525 ++s;
4526 if (++len != bufsize)
4527 continue;
4528 if (buf_write_bytes(&write_info) == FAIL)
4529 {
4530 end = 0; /* write error: break loop */
4531 break;
4532 }
4533 nchars += bufsize;
4534 s = buffer;
4535 len = 0;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004536#ifdef FEAT_MBYTE
4537 write_info.bw_start_lnum = lnum;
4538#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004539 }
4540 /* write failed or last line has no EOL: stop here */
4541 if (end == 0
4542 || (lnum == end
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004543 && (write_bin || !buf->b_p_fixeol)
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004544 && (lnum == buf->b_no_eol_lnum
Bram Moolenaar071d4272004-06-13 20:20:40 +00004545 || (lnum == buf->b_ml.ml_line_count && !buf->b_p_eol))))
4546 {
4547 ++lnum; /* written the line, count it */
4548 no_eol = TRUE;
4549 break;
4550 }
4551 if (fileformat == EOL_UNIX)
4552 *s++ = NL;
4553 else
4554 {
4555 *s++ = CAR; /* EOL_MAC or EOL_DOS: write CR */
4556 if (fileformat == EOL_DOS) /* write CR-NL */
4557 {
4558 if (++len == bufsize)
4559 {
4560 if (buf_write_bytes(&write_info) == FAIL)
4561 {
4562 end = 0; /* write error: break loop */
4563 break;
4564 }
4565 nchars += bufsize;
4566 s = buffer;
4567 len = 0;
4568 }
4569 *s++ = NL;
4570 }
4571 }
4572 if (++len == bufsize && end)
4573 {
4574 if (buf_write_bytes(&write_info) == FAIL)
4575 {
4576 end = 0; /* write error: break loop */
4577 break;
4578 }
4579 nchars += bufsize;
4580 s = buffer;
4581 len = 0;
4582
4583 ui_breakcheck();
4584 if (got_int)
4585 {
4586 end = 0; /* Interrupted, break loop */
4587 break;
4588 }
4589 }
4590#ifdef VMS
4591 /*
4592 * On VMS there is a problem: newlines get added when writing blocks
4593 * at a time. Fix it by writing a line at a time.
4594 * This is much slower!
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004595 * Explanation: VAX/DECC RTL insists that records in some RMS
4596 * structures end with a newline (carriage return) character, and if
4597 * they don't it adds one.
4598 * With other RMS structures it works perfect without this fix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004599 */
Bram Moolenaarb52e2602007-10-29 21:38:54 +00004600 if (buf->b_fab_rfm == FAB$C_VFC
4601 || ((buf->b_fab_rat & (FAB$M_FTN | FAB$M_CR)) != 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004602 {
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004603 int b2write;
4604
4605 buf->b_fab_mrs = (buf->b_fab_mrs == 0
4606 ? MIN(4096, bufsize)
4607 : MIN(buf->b_fab_mrs, bufsize));
4608
4609 b2write = len;
4610 while (b2write > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004611 {
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004612 write_info.bw_len = MIN(b2write, buf->b_fab_mrs);
4613 if (buf_write_bytes(&write_info) == FAIL)
4614 {
4615 end = 0;
4616 break;
4617 }
4618 b2write -= MIN(b2write, buf->b_fab_mrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004619 }
4620 write_info.bw_len = bufsize;
4621 nchars += len;
4622 s = buffer;
4623 len = 0;
4624 }
4625#endif
4626 }
4627 if (len > 0 && end > 0)
4628 {
4629 write_info.bw_len = len;
4630 if (buf_write_bytes(&write_info) == FAIL)
4631 end = 0; /* write error */
4632 nchars += len;
4633 }
4634
4635#if defined(UNIX) && defined(HAVE_FSYNC)
4636 /* On many journalling file systems there is a bug that causes both the
4637 * original and the backup file to be lost when halting the system right
4638 * after writing the file. That's because only the meta-data is
4639 * journalled. Syncing the file slows down the system, but assures it has
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004640 * been written to disk and we don't lose it.
4641 * For a device do try the fsync() but don't complain if it does not work
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00004642 * (could be a pipe).
4643 * If the 'fsync' option is FALSE, don't fsync(). Useful for laptops. */
4644 if (p_fs && fsync(fd) != 0 && !device)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004645 {
4646 errmsg = (char_u *)_("E667: Fsync failed");
4647 end = 0;
4648 }
4649#endif
4650
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004651#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004652 /* Probably need to set the security context. */
4653 if (!backup_copy)
4654 mch_copy_sec(backup, wfname);
4655#endif
4656
Bram Moolenaara5792f52005-11-23 21:25:05 +00004657#ifdef UNIX
4658 /* When creating a new file, set its owner/group to that of the original
4659 * file. Get the new device and inode number. */
4660 if (backup != NULL && !backup_copy)
4661 {
4662# ifdef HAVE_FCHOWN
4663 struct stat st;
4664
4665 /* don't change the owner when it's already OK, some systems remove
4666 * permission or ACL stuff */
4667 if (mch_stat((char *)wfname, &st) < 0
4668 || st.st_uid != st_old.st_uid
4669 || st.st_gid != st_old.st_gid)
4670 {
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004671 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004672 if (perm >= 0) /* set permission again, may have changed */
4673 (void)mch_setperm(wfname, perm);
4674 }
4675# endif
4676 buf_setino(buf);
4677 }
Bram Moolenaarf1726cc2009-05-13 18:48:16 +00004678 else if (!buf->b_dev_valid)
Bram Moolenaar8fa04452005-12-23 22:13:51 +00004679 /* Set the inode when creating a new file. */
4680 buf_setino(buf);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004681#endif
4682
Bram Moolenaar071d4272004-06-13 20:20:40 +00004683 if (close(fd) != 0)
4684 {
4685 errmsg = (char_u *)_("E512: Close failed");
4686 end = 0;
4687 }
4688
4689#ifdef UNIX
4690 if (made_writable)
4691 perm &= ~0200; /* reset 'w' bit for security reasons */
4692#endif
4693 if (perm >= 0) /* set perm. of new file same as old file */
4694 (void)mch_setperm(wfname, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004695#ifdef HAVE_ACL
4696 /* Probably need to set the ACL before changing the user (can't set the
4697 * ACL on a file the user doesn't own). */
4698 if (!backup_copy)
4699 mch_set_acl(wfname, acl);
4700#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004701#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004702 if (buf->b_cryptstate != NULL)
4703 {
4704 crypt_free_state(buf->b_cryptstate);
4705 buf->b_cryptstate = NULL;
4706 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004707#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004708
Bram Moolenaar071d4272004-06-13 20:20:40 +00004709#if defined(FEAT_MBYTE) && defined(FEAT_EVAL)
4710 if (wfname != fname)
4711 {
4712 /*
4713 * The file was written to a temp file, now it needs to be converted
4714 * with 'charconvert' to (overwrite) the output file.
4715 */
4716 if (end != 0)
4717 {
4718 if (eval_charconvert(enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc,
4719 wfname, fname) == FAIL)
4720 {
4721 write_info.bw_conv_error = TRUE;
4722 end = 0;
4723 }
4724 }
4725 mch_remove(wfname);
4726 vim_free(wfname);
4727 }
4728#endif
4729
4730 if (end == 0)
4731 {
4732 if (errmsg == NULL)
4733 {
4734#ifdef FEAT_MBYTE
4735 if (write_info.bw_conv_error)
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004736 {
4737 if (write_info.bw_conv_error_lnum == 0)
4738 errmsg = (char_u *)_("E513: write error, conversion failed (make 'fenc' empty to override)");
4739 else
4740 {
4741 errmsg_allocated = TRUE;
4742 errmsg = alloc(300);
4743 vim_snprintf((char *)errmsg, 300, _("E513: write error, conversion failed in line %ld (make 'fenc' empty to override)"),
4744 (long)write_info.bw_conv_error_lnum);
4745 }
4746 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004747 else
4748#endif
4749 if (got_int)
4750 errmsg = (char_u *)_(e_interr);
4751 else
4752 errmsg = (char_u *)_("E514: write error (file system full?)");
4753 }
4754
4755 /*
4756 * If we have a backup file, try to put it in place of the new file,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004757 * because the new file is probably corrupt. This avoids losing the
Bram Moolenaar071d4272004-06-13 20:20:40 +00004758 * original file when trying to make a backup when writing the file a
4759 * second time.
4760 * When "backup_copy" is set we need to copy the backup over the new
4761 * file. Otherwise rename the backup file.
4762 * If this is OK, don't give the extra warning message.
4763 */
4764 if (backup != NULL)
4765 {
4766 if (backup_copy)
4767 {
4768 /* This may take a while, if we were interrupted let the user
4769 * know we got the message. */
4770 if (got_int)
4771 {
4772 MSG(_(e_interr));
4773 out_flush();
4774 }
4775 if ((fd = mch_open((char *)backup, O_RDONLY | O_EXTRA, 0)) >= 0)
4776 {
4777 if ((write_info.bw_fd = mch_open((char *)fname,
Bram Moolenaar9be038d2005-03-08 22:34:32 +00004778 O_WRONLY | O_CREAT | O_TRUNC | O_EXTRA,
4779 perm & 0777)) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004780 {
4781 /* copy the file. */
4782 write_info.bw_buf = smallbuf;
4783#ifdef HAS_BW_FLAGS
4784 write_info.bw_flags = FIO_NOCONVERT;
4785#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004786 while ((write_info.bw_len = read_eintr(fd, smallbuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004787 SMBUFSIZE)) > 0)
4788 if (buf_write_bytes(&write_info) == FAIL)
4789 break;
4790
4791 if (close(write_info.bw_fd) >= 0
4792 && write_info.bw_len == 0)
4793 end = 1; /* success */
4794 }
4795 close(fd); /* ignore errors for closing read file */
4796 }
4797 }
4798 else
4799 {
4800 if (vim_rename(backup, fname) == 0)
4801 end = 1;
4802 }
4803 }
4804 goto fail;
4805 }
4806
4807 lnum -= start; /* compute number of written lines */
4808 --no_wait_return; /* may wait for return now */
4809
4810#if !(defined(UNIX) || defined(VMS))
4811 fname = sfname; /* use shortname now, for the messages */
4812#endif
4813 if (!filtering)
4814 {
4815 msg_add_fname(buf, fname); /* put fname in IObuff with quotes */
4816 c = FALSE;
4817#ifdef FEAT_MBYTE
4818 if (write_info.bw_conv_error)
4819 {
4820 STRCAT(IObuff, _(" CONVERSION ERROR"));
4821 c = TRUE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004822 if (write_info.bw_conv_error_lnum != 0)
Bram Moolenaara800b422010-06-27 01:15:55 +02004823 vim_snprintf_add((char *)IObuff, IOSIZE, _(" in line %ld;"),
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004824 (long)write_info.bw_conv_error_lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004825 }
4826 else if (notconverted)
4827 {
4828 STRCAT(IObuff, _("[NOT converted]"));
4829 c = TRUE;
4830 }
4831 else if (converted)
4832 {
4833 STRCAT(IObuff, _("[converted]"));
4834 c = TRUE;
4835 }
4836#endif
4837 if (device)
4838 {
4839 STRCAT(IObuff, _("[Device]"));
4840 c = TRUE;
4841 }
4842 else if (newfile)
4843 {
4844 STRCAT(IObuff, shortmess(SHM_NEW) ? _("[New]") : _("[New File]"));
4845 c = TRUE;
4846 }
4847 if (no_eol)
4848 {
4849 msg_add_eol();
4850 c = TRUE;
4851 }
4852 /* may add [unix/dos/mac] */
4853 if (msg_add_fileformat(fileformat))
4854 c = TRUE;
4855#ifdef FEAT_CRYPT
4856 if (wb_flags & FIO_ENCRYPTED)
4857 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004858 crypt_append_msg(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004859 c = TRUE;
4860 }
4861#endif
4862 msg_add_lines(c, (long)lnum, nchars); /* add line/char count */
4863 if (!shortmess(SHM_WRITE))
4864 {
4865 if (append)
4866 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended"));
4867 else
4868 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written"));
4869 }
4870
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00004871 set_keep_msg(msg_trunc_attr(IObuff, FALSE, 0), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004872 }
4873
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004874 /* When written everything correctly: reset 'modified'. Unless not
4875 * writing to the original file and '+' is not in 'cpoptions'. */
Bram Moolenaar292ad192005-12-11 21:29:51 +00004876 if (reset_changed && whole && !append
Bram Moolenaar071d4272004-06-13 20:20:40 +00004877#ifdef FEAT_MBYTE
4878 && !write_info.bw_conv_error
4879#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004880 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL)
4881 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004882 {
4883 unchanged(buf, TRUE);
Bram Moolenaar086329d2014-10-31 19:51:36 +01004884#ifdef FEAT_AUTOCMD
4885 /* buf->b_changedtick is always incremented in unchanged() but that
4886 * should not trigger a TextChanged event. */
4887 if (last_changedtick + 1 == buf->b_changedtick
4888 && last_changedtick_buf == buf)
4889 last_changedtick = buf->b_changedtick;
4890#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004891 u_unchanged(buf);
Bram Moolenaar730cde92010-06-27 05:18:54 +02004892 u_update_save_nr(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004893 }
4894
4895 /*
4896 * If written to the current file, update the timestamp of the swap file
4897 * and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
4898 */
4899 if (overwriting)
4900 {
4901 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00004902 if (append)
4903 buf->b_flags &= ~BF_NEW;
4904 else
4905 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004906 }
4907
4908 /*
4909 * If we kept a backup until now, and we are in patch mode, then we make
4910 * the backup file our 'original' file.
4911 */
4912 if (*p_pm && dobackup)
4913 {
4914 char *org = (char *)buf_modname(
4915#ifdef SHORT_FNAME
4916 TRUE,
4917#else
4918 (buf->b_p_sn || buf->b_shortname),
4919#endif
4920 fname, p_pm, FALSE);
4921
4922 if (backup != NULL)
4923 {
4924 struct stat st;
4925
4926 /*
4927 * If the original file does not exist yet
4928 * the current backup file becomes the original file
4929 */
4930 if (org == NULL)
4931 EMSG(_("E205: Patchmode: can't save original file"));
4932 else if (mch_stat(org, &st) < 0)
4933 {
4934 vim_rename(backup, (char_u *)org);
4935 vim_free(backup); /* don't delete the file */
4936 backup = NULL;
4937#ifdef UNIX
4938 set_file_time((char_u *)org, st_old.st_atime, st_old.st_mtime);
4939#endif
4940 }
4941 }
4942 /*
4943 * If there is no backup file, remember that a (new) file was
4944 * created.
4945 */
4946 else
4947 {
4948 int empty_fd;
4949
4950 if (org == NULL
Bram Moolenaara5792f52005-11-23 21:25:05 +00004951 || (empty_fd = mch_open(org,
4952 O_CREAT | O_EXTRA | O_EXCL | O_NOFOLLOW,
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00004953 perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004954 EMSG(_("E206: patchmode: can't touch empty original file"));
4955 else
4956 close(empty_fd);
4957 }
4958 if (org != NULL)
4959 {
4960 mch_setperm((char_u *)org, mch_getperm(fname) & 0777);
4961 vim_free(org);
4962 }
4963 }
4964
4965 /*
4966 * Remove the backup unless 'backup' option is set
4967 */
4968 if (!p_bk && backup != NULL && mch_remove(backup) != 0)
4969 EMSG(_("E207: Can't delete backup file"));
4970
4971#ifdef FEAT_SUN_WORKSHOP
4972 if (usingSunWorkShop)
4973 workshop_file_saved((char *) ffname);
4974#endif
4975
4976 goto nofail;
4977
4978 /*
4979 * Finish up. We get here either after failure or success.
4980 */
4981fail:
4982 --no_wait_return; /* may wait for return now */
4983nofail:
4984
4985 /* Done saving, we accept changed buffer warnings again */
4986 buf->b_saving = FALSE;
4987
4988 vim_free(backup);
4989 if (buffer != smallbuf)
4990 vim_free(buffer);
4991#ifdef FEAT_MBYTE
4992 vim_free(fenc_tofree);
4993 vim_free(write_info.bw_conv_buf);
4994# ifdef USE_ICONV
4995 if (write_info.bw_iconv_fd != (iconv_t)-1)
4996 {
4997 iconv_close(write_info.bw_iconv_fd);
4998 write_info.bw_iconv_fd = (iconv_t)-1;
4999 }
5000# endif
5001#endif
5002#ifdef HAVE_ACL
5003 mch_free_acl(acl);
5004#endif
5005
5006 if (errmsg != NULL)
5007 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005008 int numlen = errnum != NULL ? (int)STRLEN(errnum) : 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005009
5010 attr = hl_attr(HLF_E); /* set highlight for error messages */
5011 msg_add_fname(buf,
5012#ifndef UNIX
5013 sfname
5014#else
5015 fname
5016#endif
5017 ); /* put file name in IObuff with quotes */
5018 if (STRLEN(IObuff) + STRLEN(errmsg) + numlen >= IOSIZE)
5019 IObuff[IOSIZE - STRLEN(errmsg) - numlen - 1] = NUL;
5020 /* If the error message has the form "is ...", put the error number in
5021 * front of the file name. */
5022 if (errnum != NULL)
5023 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00005024 STRMOVE(IObuff + numlen, IObuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005025 mch_memmove(IObuff, errnum, (size_t)numlen);
5026 }
5027 STRCAT(IObuff, errmsg);
5028 emsg(IObuff);
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005029 if (errmsg_allocated)
5030 vim_free(errmsg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005031
5032 retval = FAIL;
5033 if (end == 0)
5034 {
5035 MSG_PUTS_ATTR(_("\nWARNING: Original file may be lost or damaged\n"),
5036 attr | MSG_HIST);
5037 MSG_PUTS_ATTR(_("don't quit the editor until the file is successfully written!"),
5038 attr | MSG_HIST);
5039
5040 /* Update the timestamp to avoid an "overwrite changed file"
5041 * prompt when writing again. */
5042 if (mch_stat((char *)fname, &st_old) >= 0)
5043 {
5044 buf_store_time(buf, &st_old, fname);
5045 buf->b_mtime_read = buf->b_mtime;
5046 }
5047 }
5048 }
5049 msg_scroll = msg_save;
5050
Bram Moolenaar55debbe2010-05-23 23:34:36 +02005051#ifdef FEAT_PERSISTENT_UNDO
5052 /*
5053 * When writing the whole file and 'undofile' is set, also write the undo
5054 * file.
5055 */
5056 if (retval == OK && write_undo_file)
5057 {
5058 char_u hash[UNDO_HASH_SIZE];
5059
5060 sha256_finish(&sha_ctx, hash);
5061 u_write_undo(NULL, FALSE, buf, hash);
5062 }
5063#endif
5064
Bram Moolenaar071d4272004-06-13 20:20:40 +00005065#ifdef FEAT_AUTOCMD
5066#ifdef FEAT_EVAL
5067 if (!should_abort(retval))
5068#else
5069 if (!got_int)
5070#endif
5071 {
5072 aco_save_T aco;
5073
Bram Moolenaar68a33fc2012-04-25 16:50:48 +02005074 curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */
5075
Bram Moolenaar071d4272004-06-13 20:20:40 +00005076 /*
5077 * Apply POST autocommands.
5078 * Careful: The autocommands may call buf_write() recursively!
5079 */
5080 aucmd_prepbuf(&aco, buf);
5081
5082 if (append)
5083 apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname,
5084 FALSE, curbuf, eap);
5085 else if (filtering)
5086 apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname,
5087 FALSE, curbuf, eap);
5088 else if (reset_changed && whole)
5089 apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname,
5090 FALSE, curbuf, eap);
5091 else
5092 apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname,
5093 FALSE, curbuf, eap);
5094
5095 /* restore curwin/curbuf and a few other things */
5096 aucmd_restbuf(&aco);
5097
5098#ifdef FEAT_EVAL
5099 if (aborting()) /* autocmds may abort script processing */
5100 retval = FALSE;
5101#endif
5102 }
5103#endif
5104
5105 got_int |= prev_got_int;
5106
5107#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
5108 /* Update machine specific information. */
5109 mch_post_buffer_write(buf);
5110#endif
5111 return retval;
5112}
5113
5114/*
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005115 * Set the name of the current buffer. Use when the buffer doesn't have a
5116 * name and a ":r" or ":w" command with a file name is used.
5117 */
5118 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005119set_rw_fname(char_u *fname, char_u *sfname)
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005120{
5121#ifdef FEAT_AUTOCMD
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005122 buf_T *buf = curbuf;
5123
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005124 /* It's like the unnamed buffer is deleted.... */
5125 if (curbuf->b_p_bl)
5126 apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
5127 apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf);
5128# ifdef FEAT_EVAL
5129 if (aborting()) /* autocmds may abort script processing */
5130 return FAIL;
5131# endif
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005132 if (curbuf != buf)
5133 {
5134 /* We are in another buffer now, don't do the renaming. */
5135 EMSG(_(e_auchangedbuf));
5136 return FAIL;
5137 }
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005138#endif
5139
5140 if (setfname(curbuf, fname, sfname, FALSE) == OK)
5141 curbuf->b_flags |= BF_NOTEDITED;
5142
5143#ifdef FEAT_AUTOCMD
5144 /* ....and a new named one is created */
5145 apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, curbuf);
5146 if (curbuf->b_p_bl)
5147 apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf);
5148# ifdef FEAT_EVAL
5149 if (aborting()) /* autocmds may abort script processing */
5150 return FAIL;
5151# endif
5152
5153 /* Do filetype detection now if 'filetype' is empty. */
5154 if (*curbuf->b_p_ft == NUL)
5155 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005156 if (au_has_group((char_u *)"filetypedetect"))
Bram Moolenaar70836c82006-02-20 21:28:49 +00005157 (void)do_doautocmd((char_u *)"filetypedetect BufRead", FALSE);
Bram Moolenaara3227e22006-03-08 21:32:40 +00005158 do_modelines(0);
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005159 }
5160#endif
5161
5162 return OK;
5163}
5164
5165/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00005166 * Put file name into IObuff with quotes.
5167 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005168 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005169msg_add_fname(buf_T *buf, char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005170{
5171 if (fname == NULL)
5172 fname = (char_u *)"-stdin-";
5173 home_replace(buf, fname, IObuff + 1, IOSIZE - 4, TRUE);
5174 IObuff[0] = '"';
5175 STRCAT(IObuff, "\" ");
5176}
5177
5178/*
5179 * Append message for text mode to IObuff.
5180 * Return TRUE if something appended.
5181 */
5182 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005183msg_add_fileformat(int eol_type)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005184{
5185#ifndef USE_CRNL
5186 if (eol_type == EOL_DOS)
5187 {
5188 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[dos]") : _("[dos format]"));
5189 return TRUE;
5190 }
5191#endif
5192#ifndef USE_CR
5193 if (eol_type == EOL_MAC)
5194 {
5195 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[mac]") : _("[mac format]"));
5196 return TRUE;
5197 }
5198#endif
5199#if defined(USE_CRNL) || defined(USE_CR)
5200 if (eol_type == EOL_UNIX)
5201 {
5202 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[unix]") : _("[unix format]"));
5203 return TRUE;
5204 }
5205#endif
5206 return FALSE;
5207}
5208
5209/*
5210 * Append line and character count to IObuff.
5211 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005212 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005213msg_add_lines(
5214 int insert_space,
5215 long lnum,
5216 off_t nchars)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005217{
5218 char_u *p;
5219
5220 p = IObuff + STRLEN(IObuff);
5221
5222 if (insert_space)
5223 *p++ = ' ';
5224 if (shortmess(SHM_LINES))
Bram Moolenaar914703b2010-05-31 21:59:46 +02005225 sprintf((char *)p,
5226#ifdef LONG_LONG_OFF_T
Bram Moolenaar581966e2014-02-23 22:58:17 +01005227 "%ldL, %lldC", lnum, (long long)nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005228#else
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005229 /* Explicit typecast avoids warning on Mac OS X 10.6 */
5230 "%ldL, %ldC", lnum, (long)nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005231#endif
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005232 );
Bram Moolenaar071d4272004-06-13 20:20:40 +00005233 else
5234 {
5235 if (lnum == 1)
5236 STRCPY(p, _("1 line, "));
5237 else
5238 sprintf((char *)p, _("%ld lines, "), lnum);
5239 p += STRLEN(p);
5240 if (nchars == 1)
5241 STRCPY(p, _("1 character"));
5242 else
Bram Moolenaar914703b2010-05-31 21:59:46 +02005243 sprintf((char *)p,
5244#ifdef LONG_LONG_OFF_T
Bram Moolenaar581966e2014-02-23 22:58:17 +01005245 _("%lld characters"), (long long)nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005246#else
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005247 /* Explicit typecast avoids warning on Mac OS X 10.6 */
5248 _("%ld characters"), (long)nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005249#endif
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005250 );
Bram Moolenaar071d4272004-06-13 20:20:40 +00005251 }
5252}
5253
5254/*
5255 * Append message for missing line separator to IObuff.
5256 */
5257 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005258msg_add_eol(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005259{
5260 STRCAT(IObuff, shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]"));
5261}
5262
5263/*
5264 * Check modification time of file, before writing to it.
5265 * The size isn't checked, because using a tool like "gzip" takes care of
5266 * using the same timestamp but can't set the size.
5267 */
5268 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005269check_mtime(buf_T *buf, struct stat *st)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005270{
5271 if (buf->b_mtime_read != 0
5272 && time_differs((long)st->st_mtime, buf->b_mtime_read))
5273 {
5274 msg_scroll = TRUE; /* don't overwrite messages here */
5275 msg_silent = 0; /* must give this prompt */
5276 /* don't use emsg() here, don't want to flush the buffers */
5277 MSG_ATTR(_("WARNING: The file has been changed since reading it!!!"),
5278 hl_attr(HLF_E));
5279 if (ask_yesno((char_u *)_("Do you really want to write to it"),
5280 TRUE) == 'n')
5281 return FAIL;
5282 msg_scroll = FALSE; /* always overwrite the file message now */
5283 }
5284 return OK;
5285}
5286
5287 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005288time_differs(long t1, long t2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005289{
5290#if defined(__linux__) || defined(MSDOS) || defined(MSWIN)
5291 /* On a FAT filesystem, esp. under Linux, there are only 5 bits to store
5292 * the seconds. Since the roundoff is done when flushing the inode, the
5293 * time may change unexpectedly by one second!!! */
5294 return (t1 - t2 > 1 || t2 - t1 > 1);
5295#else
5296 return (t1 != t2);
5297#endif
5298}
5299
5300/*
5301 * Call write() to write a number of bytes to the file.
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005302 * Handles encryption and 'encoding' conversion.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005303 *
5304 * Return FAIL for failure, OK otherwise.
5305 */
5306 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005307buf_write_bytes(struct bw_info *ip)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005308{
5309 int wlen;
5310 char_u *buf = ip->bw_buf; /* data to write */
5311 int len = ip->bw_len; /* length of data */
5312#ifdef HAS_BW_FLAGS
5313 int flags = ip->bw_flags; /* extra flags */
5314#endif
5315
5316#ifdef FEAT_MBYTE
5317 /*
5318 * Skip conversion when writing the crypt magic number or the BOM.
5319 */
5320 if (!(flags & FIO_NOCONVERT))
5321 {
5322 char_u *p;
5323 unsigned c;
5324 int n;
5325
5326 if (flags & FIO_UTF8)
5327 {
5328 /*
5329 * Convert latin1 in the buffer to UTF-8 in the file.
5330 */
5331 p = ip->bw_conv_buf; /* translate to buffer */
5332 for (wlen = 0; wlen < len; ++wlen)
5333 p += utf_char2bytes(buf[wlen], p);
5334 buf = ip->bw_conv_buf;
5335 len = (int)(p - ip->bw_conv_buf);
5336 }
5337 else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1))
5338 {
5339 /*
5340 * Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
5341 * Latin1 chars in the file.
5342 */
5343 if (flags & FIO_LATIN1)
5344 p = buf; /* translate in-place (can only get shorter) */
5345 else
5346 p = ip->bw_conv_buf; /* translate to buffer */
5347 for (wlen = 0; wlen < len; wlen += n)
5348 {
5349 if (wlen == 0 && ip->bw_restlen != 0)
5350 {
5351 int l;
5352
5353 /* Use remainder of previous call. Append the start of
5354 * buf[] to get a full sequence. Might still be too
5355 * short! */
5356 l = CONV_RESTLEN - ip->bw_restlen;
5357 if (l > len)
5358 l = len;
5359 mch_memmove(ip->bw_rest + ip->bw_restlen, buf, (size_t)l);
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005360 n = utf_ptr2len_len(ip->bw_rest, ip->bw_restlen + l);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005361 if (n > ip->bw_restlen + len)
5362 {
5363 /* We have an incomplete byte sequence at the end to
5364 * be written. We can't convert it without the
5365 * remaining bytes. Keep them for the next call. */
5366 if (ip->bw_restlen + len > CONV_RESTLEN)
5367 return FAIL;
5368 ip->bw_restlen += len;
5369 break;
5370 }
5371 if (n > 1)
5372 c = utf_ptr2char(ip->bw_rest);
5373 else
5374 c = ip->bw_rest[0];
5375 if (n >= ip->bw_restlen)
5376 {
5377 n -= ip->bw_restlen;
5378 ip->bw_restlen = 0;
5379 }
5380 else
5381 {
5382 ip->bw_restlen -= n;
5383 mch_memmove(ip->bw_rest, ip->bw_rest + n,
5384 (size_t)ip->bw_restlen);
5385 n = 0;
5386 }
5387 }
5388 else
5389 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005390 n = utf_ptr2len_len(buf + wlen, len - wlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005391 if (n > len - wlen)
5392 {
5393 /* We have an incomplete byte sequence at the end to
5394 * be written. We can't convert it without the
5395 * remaining bytes. Keep them for the next call. */
5396 if (len - wlen > CONV_RESTLEN)
5397 return FAIL;
5398 ip->bw_restlen = len - wlen;
5399 mch_memmove(ip->bw_rest, buf + wlen,
5400 (size_t)ip->bw_restlen);
5401 break;
5402 }
5403 if (n > 1)
5404 c = utf_ptr2char(buf + wlen);
5405 else
5406 c = buf[wlen];
5407 }
5408
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005409 if (ucs2bytes(c, &p, flags) && !ip->bw_conv_error)
5410 {
5411 ip->bw_conv_error = TRUE;
5412 ip->bw_conv_error_lnum = ip->bw_start_lnum;
5413 }
5414 if (c == NL)
5415 ++ip->bw_start_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005416 }
5417 if (flags & FIO_LATIN1)
5418 len = (int)(p - buf);
5419 else
5420 {
5421 buf = ip->bw_conv_buf;
5422 len = (int)(p - ip->bw_conv_buf);
5423 }
5424 }
5425
5426# ifdef WIN3264
5427 else if (flags & FIO_CODEPAGE)
5428 {
5429 /*
5430 * Convert UTF-8 or codepage to UCS-2 and then to MS-Windows
5431 * codepage.
5432 */
5433 char_u *from;
5434 size_t fromlen;
5435 char_u *to;
5436 int u8c;
5437 BOOL bad = FALSE;
5438 int needed;
5439
5440 if (ip->bw_restlen > 0)
5441 {
5442 /* Need to concatenate the remainder of the previous call and
5443 * the bytes of the current call. Use the end of the
5444 * conversion buffer for this. */
5445 fromlen = len + ip->bw_restlen;
5446 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5447 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5448 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5449 }
5450 else
5451 {
5452 from = buf;
5453 fromlen = len;
5454 }
5455
5456 to = ip->bw_conv_buf;
5457 if (enc_utf8)
5458 {
5459 /* Convert from UTF-8 to UCS-2, to the start of the buffer.
5460 * The buffer has been allocated to be big enough. */
5461 while (fromlen > 0)
5462 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005463 n = (int)utf_ptr2len_len(from, (int)fromlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005464 if (n > (int)fromlen) /* incomplete byte sequence */
5465 break;
5466 u8c = utf_ptr2char(from);
5467 *to++ = (u8c & 0xff);
5468 *to++ = (u8c >> 8);
5469 fromlen -= n;
5470 from += n;
5471 }
5472
5473 /* Copy remainder to ip->bw_rest[] to be used for the next
5474 * call. */
5475 if (fromlen > CONV_RESTLEN)
5476 {
5477 /* weird overlong sequence */
5478 ip->bw_conv_error = TRUE;
5479 return FAIL;
5480 }
5481 mch_memmove(ip->bw_rest, from, fromlen);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005482 ip->bw_restlen = (int)fromlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005483 }
5484 else
5485 {
5486 /* Convert from enc_codepage to UCS-2, to the start of the
5487 * buffer. The buffer has been allocated to be big enough. */
5488 ip->bw_restlen = 0;
5489 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005490 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005491 NULL, 0);
5492 if (needed == 0)
5493 {
5494 /* When conversion fails there may be a trailing byte. */
5495 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005496 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen - 1,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005497 NULL, 0);
5498 if (needed == 0)
5499 {
5500 /* Conversion doesn't work. */
5501 ip->bw_conv_error = TRUE;
5502 return FAIL;
5503 }
5504 /* Save the trailing byte for the next call. */
5505 ip->bw_rest[0] = from[fromlen - 1];
5506 ip->bw_restlen = 1;
5507 }
5508 needed = MultiByteToWideChar(enc_codepage, MB_ERR_INVALID_CHARS,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005509 (LPCSTR)from, (int)(fromlen - ip->bw_restlen),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005510 (LPWSTR)to, needed);
5511 if (needed == 0)
5512 {
5513 /* Safety check: Conversion doesn't work. */
5514 ip->bw_conv_error = TRUE;
5515 return FAIL;
5516 }
5517 to += needed * 2;
5518 }
5519
5520 fromlen = to - ip->bw_conv_buf;
5521 buf = to;
5522# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5523 if (FIO_GET_CP(flags) == CP_UTF8)
5524 {
5525 /* Convert from UCS-2 to UTF-8, using the remainder of the
5526 * conversion buffer. Fails when out of space. */
5527 for (from = ip->bw_conv_buf; fromlen > 1; fromlen -= 2)
5528 {
5529 u8c = *from++;
5530 u8c += (*from++ << 8);
5531 to += utf_char2bytes(u8c, to);
5532 if (to + 6 >= ip->bw_conv_buf + ip->bw_conv_buflen)
5533 {
5534 ip->bw_conv_error = TRUE;
5535 return FAIL;
5536 }
5537 }
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005538 len = (int)(to - buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005539 }
5540 else
5541#endif
5542 {
5543 /* Convert from UCS-2 to the codepage, using the remainder of
5544 * the conversion buffer. If the conversion uses the default
5545 * character "0", the data doesn't fit in this encoding, so
5546 * fail. */
5547 len = WideCharToMultiByte(FIO_GET_CP(flags), 0,
5548 (LPCWSTR)ip->bw_conv_buf, (int)fromlen / sizeof(WCHAR),
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005549 (LPSTR)to, (int)(ip->bw_conv_buflen - fromlen), 0,
5550 &bad);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005551 if (bad)
5552 {
5553 ip->bw_conv_error = TRUE;
5554 return FAIL;
5555 }
5556 }
5557 }
5558# endif
5559
Bram Moolenaar56718732006-03-15 22:53:57 +00005560# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00005561 else if (flags & FIO_MACROMAN)
5562 {
5563 /*
5564 * Convert UTF-8 or latin1 to Apple MacRoman.
5565 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005566 char_u *from;
5567 size_t fromlen;
5568
5569 if (ip->bw_restlen > 0)
5570 {
5571 /* Need to concatenate the remainder of the previous call and
5572 * the bytes of the current call. Use the end of the
5573 * conversion buffer for this. */
5574 fromlen = len + ip->bw_restlen;
5575 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5576 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5577 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5578 }
5579 else
5580 {
5581 from = buf;
5582 fromlen = len;
5583 }
5584
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00005585 if (enc2macroman(from, fromlen,
5586 ip->bw_conv_buf, &len, ip->bw_conv_buflen,
5587 ip->bw_rest, &ip->bw_restlen) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005588 {
5589 ip->bw_conv_error = TRUE;
5590 return FAIL;
5591 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005592 buf = ip->bw_conv_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005593 }
5594# endif
5595
5596# ifdef USE_ICONV
5597 if (ip->bw_iconv_fd != (iconv_t)-1)
5598 {
5599 const char *from;
5600 size_t fromlen;
5601 char *to;
5602 size_t tolen;
5603
5604 /* Convert with iconv(). */
5605 if (ip->bw_restlen > 0)
5606 {
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005607 char *fp;
5608
Bram Moolenaar071d4272004-06-13 20:20:40 +00005609 /* Need to concatenate the remainder of the previous call and
5610 * the bytes of the current call. Use the end of the
5611 * conversion buffer for this. */
5612 fromlen = len + ip->bw_restlen;
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005613 fp = (char *)ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5614 mch_memmove(fp, ip->bw_rest, (size_t)ip->bw_restlen);
5615 mch_memmove(fp + ip->bw_restlen, buf, (size_t)len);
5616 from = fp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005617 tolen = ip->bw_conv_buflen - fromlen;
5618 }
5619 else
5620 {
5621 from = (const char *)buf;
5622 fromlen = len;
5623 tolen = ip->bw_conv_buflen;
5624 }
5625 to = (char *)ip->bw_conv_buf;
5626
5627 if (ip->bw_first)
5628 {
5629 size_t save_len = tolen;
5630
5631 /* output the initial shift state sequence */
5632 (void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen);
5633
5634 /* There is a bug in iconv() on Linux (which appears to be
5635 * wide-spread) which sets "to" to NULL and messes up "tolen".
5636 */
5637 if (to == NULL)
5638 {
5639 to = (char *)ip->bw_conv_buf;
5640 tolen = save_len;
5641 }
5642 ip->bw_first = FALSE;
5643 }
5644
5645 /*
5646 * If iconv() has an error or there is not enough room, fail.
5647 */
5648 if ((iconv(ip->bw_iconv_fd, (void *)&from, &fromlen, &to, &tolen)
5649 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
5650 || fromlen > CONV_RESTLEN)
5651 {
5652 ip->bw_conv_error = TRUE;
5653 return FAIL;
5654 }
5655
5656 /* copy remainder to ip->bw_rest[] to be used for the next call. */
5657 if (fromlen > 0)
5658 mch_memmove(ip->bw_rest, (void *)from, fromlen);
5659 ip->bw_restlen = (int)fromlen;
5660
5661 buf = ip->bw_conv_buf;
5662 len = (int)((char_u *)to - ip->bw_conv_buf);
5663 }
5664# endif
5665 }
5666#endif /* FEAT_MBYTE */
5667
5668#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02005669 if (flags & FIO_ENCRYPTED)
5670 {
5671 /* Encrypt the data. Do it in-place if possible, otherwise use an
5672 * allocated buffer. */
5673 if (crypt_works_inplace(ip->bw_buffer->b_cryptstate))
5674 {
5675 crypt_encode_inplace(ip->bw_buffer->b_cryptstate, buf, len);
5676 }
5677 else
5678 {
5679 char_u *outbuf;
5680
5681 len = crypt_encode_alloc(curbuf->b_cryptstate, buf, len, &outbuf);
5682 if (len == 0)
5683 return OK; /* Crypt layer is buffering, will flush later. */
5684 wlen = write_eintr(ip->bw_fd, outbuf, len);
5685 vim_free(outbuf);
5686 return (wlen < len) ? FAIL : OK;
5687 }
5688 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005689#endif
5690
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005691 wlen = write_eintr(ip->bw_fd, buf, len);
5692 return (wlen < len) ? FAIL : OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005693}
5694
5695#ifdef FEAT_MBYTE
5696/*
5697 * Convert a Unicode character to bytes.
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005698 * Return TRUE for an error, FALSE when it's OK.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005699 */
5700 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005701ucs2bytes(
5702 unsigned c, /* in: character */
5703 char_u **pp, /* in/out: pointer to result */
5704 int flags) /* FIO_ flags */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005705{
5706 char_u *p = *pp;
5707 int error = FALSE;
5708 int cc;
5709
5710
5711 if (flags & FIO_UCS4)
5712 {
5713 if (flags & FIO_ENDIAN_L)
5714 {
5715 *p++ = c;
5716 *p++ = (c >> 8);
5717 *p++ = (c >> 16);
5718 *p++ = (c >> 24);
5719 }
5720 else
5721 {
5722 *p++ = (c >> 24);
5723 *p++ = (c >> 16);
5724 *p++ = (c >> 8);
5725 *p++ = c;
5726 }
5727 }
5728 else if (flags & (FIO_UCS2 | FIO_UTF16))
5729 {
5730 if (c >= 0x10000)
5731 {
5732 if (flags & FIO_UTF16)
5733 {
5734 /* Make two words, ten bits of the character in each. First
5735 * word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff */
5736 c -= 0x10000;
5737 if (c >= 0x100000)
5738 error = TRUE;
5739 cc = ((c >> 10) & 0x3ff) + 0xd800;
5740 if (flags & FIO_ENDIAN_L)
5741 {
5742 *p++ = cc;
5743 *p++ = ((unsigned)cc >> 8);
5744 }
5745 else
5746 {
5747 *p++ = ((unsigned)cc >> 8);
5748 *p++ = cc;
5749 }
5750 c = (c & 0x3ff) + 0xdc00;
5751 }
5752 else
5753 error = TRUE;
5754 }
5755 if (flags & FIO_ENDIAN_L)
5756 {
5757 *p++ = c;
5758 *p++ = (c >> 8);
5759 }
5760 else
5761 {
5762 *p++ = (c >> 8);
5763 *p++ = c;
5764 }
5765 }
5766 else /* Latin1 */
5767 {
5768 if (c >= 0x100)
5769 {
5770 error = TRUE;
5771 *p++ = 0xBF;
5772 }
5773 else
5774 *p++ = c;
5775 }
5776
5777 *pp = p;
5778 return error;
5779}
5780
5781/*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005782 * Return TRUE if file encoding "fenc" requires conversion from or to
5783 * 'encoding'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005784 */
5785 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005786need_conversion(char_u *fenc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005787{
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005788 int same_encoding;
5789 int enc_flags;
5790 int fenc_flags;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005791
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005792 if (*fenc == NUL || STRCMP(p_enc, fenc) == 0)
Bram Moolenaar442b4222010-05-24 21:34:22 +02005793 {
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005794 same_encoding = TRUE;
Bram Moolenaar442b4222010-05-24 21:34:22 +02005795 fenc_flags = 0;
5796 }
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005797 else
5798 {
5799 /* Ignore difference between "ansi" and "latin1", "ucs-4" and
5800 * "ucs-4be", etc. */
5801 enc_flags = get_fio_flags(p_enc);
5802 fenc_flags = get_fio_flags(fenc);
5803 same_encoding = (enc_flags != 0 && fenc_flags == enc_flags);
5804 }
5805 if (same_encoding)
5806 {
5807 /* Specified encoding matches with 'encoding'. This requires
5808 * conversion when 'encoding' is Unicode but not UTF-8. */
5809 return enc_unicode != 0;
5810 }
5811
5812 /* Encodings differ. However, conversion is not needed when 'enc' is any
5813 * Unicode encoding and the file is UTF-8. */
5814 return !(enc_utf8 && fenc_flags == FIO_UTF8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005815}
5816
5817/*
5818 * Check "ptr" for a unicode encoding and return the FIO_ flags needed for the
5819 * internal conversion.
5820 * if "ptr" is an empty string, use 'encoding'.
5821 */
5822 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005823get_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005824{
5825 int prop;
5826
5827 if (*ptr == NUL)
5828 ptr = p_enc;
5829
5830 prop = enc_canon_props(ptr);
5831 if (prop & ENC_UNICODE)
5832 {
5833 if (prop & ENC_2BYTE)
5834 {
5835 if (prop & ENC_ENDIAN_L)
5836 return FIO_UCS2 | FIO_ENDIAN_L;
5837 return FIO_UCS2;
5838 }
5839 if (prop & ENC_4BYTE)
5840 {
5841 if (prop & ENC_ENDIAN_L)
5842 return FIO_UCS4 | FIO_ENDIAN_L;
5843 return FIO_UCS4;
5844 }
5845 if (prop & ENC_2WORD)
5846 {
5847 if (prop & ENC_ENDIAN_L)
5848 return FIO_UTF16 | FIO_ENDIAN_L;
5849 return FIO_UTF16;
5850 }
5851 return FIO_UTF8;
5852 }
5853 if (prop & ENC_LATIN1)
5854 return FIO_LATIN1;
5855 /* must be ENC_DBCS, requires iconv() */
5856 return 0;
5857}
5858
5859#ifdef WIN3264
5860/*
5861 * Check "ptr" for a MS-Windows codepage name and return the FIO_ flags needed
5862 * for the conversion MS-Windows can do for us. Also accept "utf-8".
5863 * Used for conversion between 'encoding' and 'fileencoding'.
5864 */
5865 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005866get_win_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005867{
5868 int cp;
5869
5870 /* Cannot do this when 'encoding' is not utf-8 and not a codepage. */
5871 if (!enc_utf8 && enc_codepage <= 0)
5872 return 0;
5873
5874 cp = encname2codepage(ptr);
5875 if (cp == 0)
5876 {
5877# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5878 if (STRCMP(ptr, "utf-8") == 0)
5879 cp = CP_UTF8;
5880 else
5881# endif
5882 return 0;
5883 }
5884 return FIO_PUT_CP(cp) | FIO_CODEPAGE;
5885}
5886#endif
5887
5888#ifdef MACOS_X
5889/*
5890 * Check "ptr" for a Carbon supported encoding and return the FIO_ flags
5891 * needed for the internal conversion to/from utf-8 or latin1.
5892 */
5893 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005894get_mac_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005895{
5896 if ((enc_utf8 || STRCMP(p_enc, "latin1") == 0)
5897 && (enc_canon_props(ptr) & ENC_MACROMAN))
5898 return FIO_MACROMAN;
5899 return 0;
5900}
5901#endif
5902
5903/*
5904 * Check for a Unicode BOM (Byte Order Mark) at the start of p[size].
5905 * "size" must be at least 2.
5906 * Return the name of the encoding and set "*lenp" to the length.
5907 * Returns NULL when no BOM found.
5908 */
5909 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005910check_for_bom(
5911 char_u *p,
5912 long size,
5913 int *lenp,
5914 int flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005915{
5916 char *name = NULL;
5917 int len = 2;
5918
5919 if (p[0] == 0xef && p[1] == 0xbb && size >= 3 && p[2] == 0xbf
Bram Moolenaaree0f5a62008-07-24 20:09:16 +00005920 && (flags == FIO_ALL || flags == FIO_UTF8 || flags == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005921 {
5922 name = "utf-8"; /* EF BB BF */
5923 len = 3;
5924 }
5925 else if (p[0] == 0xff && p[1] == 0xfe)
5926 {
5927 if (size >= 4 && p[2] == 0 && p[3] == 0
5928 && (flags == FIO_ALL || flags == (FIO_UCS4 | FIO_ENDIAN_L)))
5929 {
5930 name = "ucs-4le"; /* FF FE 00 00 */
5931 len = 4;
5932 }
Bram Moolenaar223a1892008-11-11 20:57:11 +00005933 else if (flags == (FIO_UCS2 | FIO_ENDIAN_L))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005934 name = "ucs-2le"; /* FF FE */
Bram Moolenaar223a1892008-11-11 20:57:11 +00005935 else if (flags == FIO_ALL || flags == (FIO_UTF16 | FIO_ENDIAN_L))
5936 /* utf-16le is preferred, it also works for ucs-2le text */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005937 name = "utf-16le"; /* FF FE */
5938 }
5939 else if (p[0] == 0xfe && p[1] == 0xff
5940 && (flags == FIO_ALL || flags == FIO_UCS2 || flags == FIO_UTF16))
5941 {
Bram Moolenaarffd82c52008-02-20 17:15:26 +00005942 /* Default to utf-16, it works also for ucs-2 text. */
5943 if (flags == FIO_UCS2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005944 name = "ucs-2"; /* FE FF */
Bram Moolenaarffd82c52008-02-20 17:15:26 +00005945 else
5946 name = "utf-16"; /* FE FF */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005947 }
5948 else if (size >= 4 && p[0] == 0 && p[1] == 0 && p[2] == 0xfe
5949 && p[3] == 0xff && (flags == FIO_ALL || flags == FIO_UCS4))
5950 {
5951 name = "ucs-4"; /* 00 00 FE FF */
5952 len = 4;
5953 }
5954
5955 *lenp = len;
5956 return (char_u *)name;
5957}
5958
5959/*
5960 * Generate a BOM in "buf[4]" for encoding "name".
5961 * Return the length of the BOM (zero when no BOM).
5962 */
5963 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005964make_bom(char_u *buf, char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005965{
5966 int flags;
5967 char_u *p;
5968
5969 flags = get_fio_flags(name);
5970
5971 /* Can't put a BOM in a non-Unicode file. */
5972 if (flags == FIO_LATIN1 || flags == 0)
5973 return 0;
5974
5975 if (flags == FIO_UTF8) /* UTF-8 */
5976 {
5977 buf[0] = 0xef;
5978 buf[1] = 0xbb;
5979 buf[2] = 0xbf;
5980 return 3;
5981 }
5982 p = buf;
5983 (void)ucs2bytes(0xfeff, &p, flags);
5984 return (int)(p - buf);
5985}
5986#endif
5987
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00005988#if defined(FEAT_VIMINFO) || defined(FEAT_BROWSE) || \
Bram Moolenaara0174af2008-01-02 20:08:25 +00005989 defined(FEAT_QUICKFIX) || defined(FEAT_AUTOCMD) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005990/*
5991 * Try to find a shortname by comparing the fullname with the current
5992 * directory.
Bram Moolenaard089d9b2007-09-30 12:02:55 +00005993 * Returns "full_path" or pointer into "full_path" if shortened.
5994 */
5995 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005996shorten_fname1(char_u *full_path)
Bram Moolenaard089d9b2007-09-30 12:02:55 +00005997{
Bram Moolenaard9462e32011-04-11 21:35:11 +02005998 char_u *dirname;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00005999 char_u *p = full_path;
6000
Bram Moolenaard9462e32011-04-11 21:35:11 +02006001 dirname = alloc(MAXPATHL);
6002 if (dirname == NULL)
6003 return full_path;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006004 if (mch_dirname(dirname, MAXPATHL) == OK)
6005 {
6006 p = shorten_fname(full_path, dirname);
6007 if (p == NULL || *p == NUL)
6008 p = full_path;
6009 }
Bram Moolenaard9462e32011-04-11 21:35:11 +02006010 vim_free(dirname);
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006011 return p;
6012}
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00006013#endif
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006014
6015/*
6016 * Try to find a shortname by comparing the fullname with the current
6017 * directory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006018 * Returns NULL if not shorter name possible, pointer into "full_path"
6019 * otherwise.
6020 */
6021 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006022shorten_fname(char_u *full_path, char_u *dir_name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006023{
6024 int len;
6025 char_u *p;
6026
6027 if (full_path == NULL)
6028 return NULL;
6029 len = (int)STRLEN(dir_name);
6030 if (fnamencmp(dir_name, full_path, len) == 0)
6031 {
6032 p = full_path + len;
Bram Moolenaare7fedb62015-12-31 19:07:19 +01006033#if defined(MSDOS) || defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006034 /*
6035 * MSDOS: when a file is in the root directory, dir_name will end in a
6036 * slash, since C: by itself does not define a specific dir. In this
6037 * case p may already be correct. <negri>
6038 */
6039 if (!((len > 2) && (*(p - 2) == ':')))
6040#endif
6041 {
6042 if (vim_ispathsep(*p))
6043 ++p;
6044#ifndef VMS /* the path separator is always part of the path */
6045 else
6046 p = NULL;
6047#endif
6048 }
6049 }
Bram Moolenaare7fedb62015-12-31 19:07:19 +01006050#if defined(MSDOS) || defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006051 /*
6052 * When using a file in the current drive, remove the drive name:
6053 * "A:\dir\file" -> "\dir\file". This helps when moving a session file on
6054 * a floppy from "A:\dir" to "B:\dir".
6055 */
6056 else if (len > 3
6057 && TOUPPER_LOC(full_path[0]) == TOUPPER_LOC(dir_name[0])
6058 && full_path[1] == ':'
6059 && vim_ispathsep(full_path[2]))
6060 p = full_path + 2;
6061#endif
6062 else
6063 p = NULL;
6064 return p;
6065}
6066
6067/*
6068 * Shorten filenames for all buffers.
6069 * When "force" is TRUE: Use full path from now on for files currently being
6070 * edited, both for file name and swap file name. Try to shorten the file
6071 * names a bit, if safe to do so.
6072 * When "force" is FALSE: Only try to shorten absolute file names.
6073 * For buffers that have buftype "nofile" or "scratch": never change the file
6074 * name.
6075 */
6076 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006077shorten_fnames(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006078{
6079 char_u dirname[MAXPATHL];
6080 buf_T *buf;
6081 char_u *p;
6082
6083 mch_dirname(dirname, MAXPATHL);
6084 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
6085 {
6086 if (buf->b_fname != NULL
6087#ifdef FEAT_QUICKFIX
6088 && !bt_nofile(buf)
6089#endif
6090 && !path_with_url(buf->b_fname)
6091 && (force
6092 || buf->b_sfname == NULL
6093 || mch_isFullName(buf->b_sfname)))
6094 {
6095 vim_free(buf->b_sfname);
6096 buf->b_sfname = NULL;
6097 p = shorten_fname(buf->b_ffname, dirname);
6098 if (p != NULL)
6099 {
6100 buf->b_sfname = vim_strsave(p);
6101 buf->b_fname = buf->b_sfname;
6102 }
6103 if (p == NULL || buf->b_fname == NULL)
6104 buf->b_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006105 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00006106
6107 /* Always make the swap file name a full path, a "nofile" buffer may
6108 * also have a swap file. */
6109 mf_fullname(buf->b_ml.ml_mfp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006110 }
6111#ifdef FEAT_WINDOWS
6112 status_redraw_all();
Bram Moolenaar49d7bf12006-02-17 21:45:41 +00006113 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006114#endif
6115}
6116
6117#if (defined(FEAT_DND) && defined(FEAT_GUI_GTK)) \
6118 || defined(FEAT_GUI_MSWIN) \
6119 || defined(FEAT_GUI_MAC) \
6120 || defined(PROTO)
6121/*
6122 * Shorten all filenames in "fnames[count]" by current directory.
6123 */
6124 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006125shorten_filenames(char_u **fnames, int count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006126{
6127 int i;
6128 char_u dirname[MAXPATHL];
6129 char_u *p;
6130
6131 if (fnames == NULL || count < 1)
6132 return;
6133 mch_dirname(dirname, sizeof(dirname));
6134 for (i = 0; i < count; ++i)
6135 {
6136 if ((p = shorten_fname(fnames[i], dirname)) != NULL)
6137 {
6138 /* shorten_fname() returns pointer in given "fnames[i]". If free
6139 * "fnames[i]" first, "p" becomes invalid. So we need to copy
6140 * "p" first then free fnames[i]. */
6141 p = vim_strsave(p);
6142 vim_free(fnames[i]);
6143 fnames[i] = p;
6144 }
6145 }
6146}
6147#endif
6148
6149/*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006150 * add extension to file name - change path/fo.o.h to path/fo.o.h.ext or
Bram Moolenaar071d4272004-06-13 20:20:40 +00006151 * fo_o_h.ext for MSDOS or when shortname option set.
6152 *
6153 * Assumed that fname is a valid name found in the filesystem we assure that
6154 * the return value is a different name and ends in 'ext'.
6155 * "ext" MUST be at most 4 characters long if it starts with a dot, 3
6156 * characters otherwise.
6157 * Space for the returned name is allocated, must be freed later.
6158 * Returns NULL when out of memory.
6159 */
6160 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006161modname(
6162 char_u *fname,
6163 char_u *ext,
6164 int prepend_dot) /* may prepend a '.' to file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006165{
6166 return buf_modname(
6167#ifdef SHORT_FNAME
6168 TRUE,
6169#else
6170 (curbuf->b_p_sn || curbuf->b_shortname),
6171#endif
6172 fname, ext, prepend_dot);
6173}
6174
6175 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006176buf_modname(
6177 int shortname, /* use 8.3 file name */
6178 char_u *fname,
6179 char_u *ext,
6180 int prepend_dot) /* may prepend a '.' to file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006181{
6182 char_u *retval;
6183 char_u *s;
6184 char_u *e;
6185 char_u *ptr;
6186 int fnamelen, extlen;
6187
6188 extlen = (int)STRLEN(ext);
6189
6190 /*
6191 * If there is no file name we must get the name of the current directory
6192 * (we need the full path in case :cd is used).
6193 */
6194 if (fname == NULL || *fname == NUL)
6195 {
6196 retval = alloc((unsigned)(MAXPATHL + extlen + 3));
6197 if (retval == NULL)
6198 return NULL;
6199 if (mch_dirname(retval, MAXPATHL) == FAIL ||
6200 (fnamelen = (int)STRLEN(retval)) == 0)
6201 {
6202 vim_free(retval);
6203 return NULL;
6204 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006205 if (!after_pathsep(retval, retval + fnamelen))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006206 {
6207 retval[fnamelen++] = PATHSEP;
6208 retval[fnamelen] = NUL;
6209 }
6210#ifndef SHORT_FNAME
6211 prepend_dot = FALSE; /* nothing to prepend a dot to */
6212#endif
6213 }
6214 else
6215 {
6216 fnamelen = (int)STRLEN(fname);
6217 retval = alloc((unsigned)(fnamelen + extlen + 3));
6218 if (retval == NULL)
6219 return NULL;
6220 STRCPY(retval, fname);
6221#ifdef VMS
6222 vms_remove_version(retval); /* we do not need versions here */
6223#endif
6224 }
6225
6226 /*
6227 * search backwards until we hit a '/', '\' or ':' replacing all '.'
6228 * by '_' for MSDOS or when shortname option set and ext starts with a dot.
6229 * Then truncate what is after the '/', '\' or ':' to 8 characters for
6230 * MSDOS and 26 characters for AMIGA, a lot more for UNIX.
6231 */
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006232 for (ptr = retval + fnamelen; ptr > retval; mb_ptr_back(retval, ptr))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006233 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006234 if (*ext == '.'
Bram Moolenaare60acc12011-05-10 16:41:25 +02006235#ifdef USE_LONG_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00006236 && (!USE_LONG_FNAME || shortname)
Bram Moolenaare60acc12011-05-10 16:41:25 +02006237#else
6238# ifndef SHORT_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00006239 && shortname
6240# endif
Bram Moolenaare60acc12011-05-10 16:41:25 +02006241#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006242 )
6243 if (*ptr == '.') /* replace '.' by '_' */
6244 *ptr = '_';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006245 if (vim_ispathsep(*ptr))
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006246 {
6247 ++ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006248 break;
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006249 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006250 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006251
6252 /* the file name has at most BASENAMELEN characters. */
6253#ifndef SHORT_FNAME
6254 if (STRLEN(ptr) > (unsigned)BASENAMELEN)
6255 ptr[BASENAMELEN] = '\0';
6256#endif
6257
6258 s = ptr + STRLEN(ptr);
6259
6260 /*
6261 * For 8.3 file names we may have to reduce the length.
6262 */
6263#ifdef USE_LONG_FNAME
6264 if (!USE_LONG_FNAME || shortname)
6265#else
6266# ifndef SHORT_FNAME
6267 if (shortname)
6268# endif
6269#endif
6270 {
6271 /*
6272 * If there is no file name, or the file name ends in '/', and the
6273 * extension starts with '.', put a '_' before the dot, because just
6274 * ".ext" is invalid.
6275 */
6276 if (fname == NULL || *fname == NUL
6277 || vim_ispathsep(fname[STRLEN(fname) - 1]))
6278 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006279 if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006280 *s++ = '_';
6281 }
6282 /*
6283 * If the extension starts with '.', truncate the base name at 8
6284 * characters
6285 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006286 else if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006287 {
Bram Moolenaar78a15312009-05-15 19:33:18 +00006288 if ((size_t)(s - ptr) > (size_t)8)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006289 {
6290 s = ptr + 8;
6291 *s = '\0';
6292 }
6293 }
6294 /*
6295 * If the extension doesn't start with '.', and the file name
6296 * doesn't have an extension yet, append a '.'
6297 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006298 else if ((e = vim_strchr(ptr, '.')) == NULL)
6299 *s++ = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006300 /*
6301 * If the extension doesn't start with '.', and there already is an
Bram Moolenaar7263a772007-05-10 17:35:54 +00006302 * extension, it may need to be truncated
Bram Moolenaar071d4272004-06-13 20:20:40 +00006303 */
6304 else if ((int)STRLEN(e) + extlen > 4)
6305 s = e + 4 - extlen;
6306 }
Bram Moolenaare7fedb62015-12-31 19:07:19 +01006307#if defined(USE_LONG_FNAME) || defined(WIN3264)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006308 /*
6309 * If there is no file name, and the extension starts with '.', put a
6310 * '_' before the dot, because just ".ext" may be invalid if it's on a
6311 * FAT partition, and on HPFS it doesn't matter.
6312 */
6313 else if ((fname == NULL || *fname == NUL) && *ext == '.')
6314 *s++ = '_';
6315#endif
6316
6317 /*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006318 * Append the extension.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006319 * ext can start with '.' and cannot exceed 3 more characters.
6320 */
6321 STRCPY(s, ext);
6322
6323#ifndef SHORT_FNAME
6324 /*
6325 * Prepend the dot.
6326 */
Bram Moolenaare60acc12011-05-10 16:41:25 +02006327 if (prepend_dot && !shortname && *(e = gettail(retval)) != '.'
Bram Moolenaar071d4272004-06-13 20:20:40 +00006328#ifdef USE_LONG_FNAME
6329 && USE_LONG_FNAME
6330#endif
6331 )
6332 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006333 STRMOVE(e + 1, e);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006334 *e = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006335 }
6336#endif
6337
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
6451 struct stat 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 {
6479 struct stat 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;
6691 for (buf = firstbuf; buf != NULL; )
6692 {
6693 /* Only check buffers in a window. */
6694 if (buf->b_nwindows > 0)
6695 {
6696 n = buf_check_timestamp(buf, focus);
6697 if (didit < n)
6698 didit = n;
6699 if (n > 0 && !buf_valid(buf))
6700 {
6701 /* Autocommands have removed the buffer, start at the
6702 * first one again. */
6703 buf = firstbuf;
6704 continue;
6705 }
6706 }
6707 buf = buf->b_next;
6708 }
6709 --no_wait_return;
6710 need_check_timestamps = FALSE;
6711 if (need_wait_return && didit == 2)
6712 {
6713 /* make sure msg isn't overwritten */
6714 msg_puts((char_u *)"\n");
6715 out_flush();
6716 }
6717 }
6718 return didit;
6719}
6720
6721/*
6722 * Move all the lines from buffer "frombuf" to buffer "tobuf".
6723 * Return OK or FAIL. When FAIL "tobuf" is incomplete and/or "frombuf" is not
6724 * empty.
6725 */
6726 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006727move_lines(buf_T *frombuf, buf_T *tobuf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006728{
6729 buf_T *tbuf = curbuf;
6730 int retval = OK;
6731 linenr_T lnum;
6732 char_u *p;
6733
6734 /* Copy the lines in "frombuf" to "tobuf". */
6735 curbuf = tobuf;
6736 for (lnum = 1; lnum <= frombuf->b_ml.ml_line_count; ++lnum)
6737 {
6738 p = vim_strsave(ml_get_buf(frombuf, lnum, FALSE));
6739 if (p == NULL || ml_append(lnum - 1, p, 0, FALSE) == FAIL)
6740 {
6741 vim_free(p);
6742 retval = FAIL;
6743 break;
6744 }
6745 vim_free(p);
6746 }
6747
6748 /* Delete all the lines in "frombuf". */
6749 if (retval != FAIL)
6750 {
6751 curbuf = frombuf;
Bram Moolenaar9460b9d2007-01-09 14:37:01 +00006752 for (lnum = curbuf->b_ml.ml_line_count; lnum > 0; --lnum)
6753 if (ml_delete(lnum, FALSE) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006754 {
6755 /* Oops! We could try putting back the saved lines, but that
6756 * might fail again... */
6757 retval = FAIL;
6758 break;
6759 }
6760 }
6761
6762 curbuf = tbuf;
6763 return retval;
6764}
6765
6766/*
6767 * Check if buffer "buf" has been changed.
6768 * Also check if the file for a new buffer unexpectedly appeared.
6769 * return 1 if a changed buffer was found.
6770 * return 2 if a message has been displayed.
6771 * return 0 otherwise.
6772 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006773 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006774buf_check_timestamp(
6775 buf_T *buf,
6776 int focus UNUSED) /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006777{
6778 struct stat st;
6779 int stat_res;
6780 int retval = 0;
6781 char_u *path;
6782 char_u *tbuf;
6783 char *mesg = NULL;
Bram Moolenaar44ecf652005-03-07 23:09:59 +00006784 char *mesg2 = "";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006785 int helpmesg = FALSE;
6786 int reload = FALSE;
6787#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6788 int can_reload = FALSE;
6789#endif
Bram Moolenaar914703b2010-05-31 21:59:46 +02006790 off_t orig_size = buf->b_orig_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006791 int orig_mode = buf->b_orig_mode;
6792#ifdef FEAT_GUI
6793 int save_mouse_correct = need_mouse_correct;
6794#endif
6795#ifdef FEAT_AUTOCMD
6796 static int busy = FALSE;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006797 int n;
6798 char_u *s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006799#endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006800 char *reason;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006801
6802 /* If there is no file name, the buffer is not loaded, 'buftype' is
6803 * set, we are in the middle of a save or being called recursively: ignore
6804 * this buffer. */
6805 if (buf->b_ffname == NULL
6806 || buf->b_ml.ml_mfp == NULL
6807#if defined(FEAT_QUICKFIX)
6808 || *buf->b_p_bt != NUL
6809#endif
6810 || buf->b_saving
6811#ifdef FEAT_AUTOCMD
6812 || busy
6813#endif
Bram Moolenaar009b2592004-10-24 19:18:58 +00006814#ifdef FEAT_NETBEANS_INTG
6815 || isNetbeansBuffer(buf)
6816#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006817 )
6818 return 0;
6819
6820 if ( !(buf->b_flags & BF_NOTEDITED)
6821 && buf->b_mtime != 0
6822 && ((stat_res = mch_stat((char *)buf->b_ffname, &st)) < 0
6823 || time_differs((long)st.st_mtime, buf->b_mtime)
Bram Moolenaara7611f62014-05-02 15:46:14 +02006824 || st.st_size != buf->b_orig_size
Bram Moolenaar071d4272004-06-13 20:20:40 +00006825#ifdef HAVE_ST_MODE
6826 || (int)st.st_mode != buf->b_orig_mode
6827#else
6828 || mch_getperm(buf->b_ffname) != buf->b_orig_mode
6829#endif
6830 ))
6831 {
6832 retval = 1;
6833
Bram Moolenaar316059c2006-01-14 21:18:42 +00006834 /* set b_mtime to stop further warnings (e.g., when executing
6835 * FileChangedShell autocmd) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006836 if (stat_res < 0)
6837 {
6838 buf->b_mtime = 0;
6839 buf->b_orig_size = 0;
6840 buf->b_orig_mode = 0;
6841 }
6842 else
6843 buf_store_time(buf, &st, buf->b_ffname);
6844
6845 /* Don't do anything for a directory. Might contain the file
6846 * explorer. */
6847 if (mch_isdir(buf->b_fname))
6848 ;
6849
6850 /*
6851 * If 'autoread' is set, the buffer has no changes and the file still
6852 * exists, reload the buffer. Use the buffer-local option value if it
6853 * was set, the global option value otherwise.
6854 */
6855 else if ((buf->b_p_ar >= 0 ? buf->b_p_ar : p_ar)
6856 && !bufIsChanged(buf) && stat_res >= 0)
6857 reload = TRUE;
6858 else
6859 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006860 if (stat_res < 0)
6861 reason = "deleted";
6862 else if (bufIsChanged(buf))
6863 reason = "conflict";
6864 else if (orig_size != buf->b_orig_size || buf_contents_changed(buf))
6865 reason = "changed";
6866 else if (orig_mode != buf->b_orig_mode)
6867 reason = "mode";
6868 else
6869 reason = "time";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006870
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006871#ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006872 /*
6873 * Only give the warning if there are no FileChangedShell
6874 * autocommands.
6875 * Avoid being called recursively by setting "busy".
6876 */
6877 busy = TRUE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00006878# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006879 set_vim_var_string(VV_FCS_REASON, (char_u *)reason, -1);
6880 set_vim_var_string(VV_FCS_CHOICE, (char_u *)"", -1);
Bram Moolenaar1e015462005-09-25 22:16:38 +00006881# endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006882 ++allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006883 n = apply_autocmds(EVENT_FILECHANGEDSHELL,
6884 buf->b_fname, buf->b_fname, FALSE, buf);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006885 --allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006886 busy = FALSE;
6887 if (n)
6888 {
6889 if (!buf_valid(buf))
6890 EMSG(_("E246: FileChangedShell autocommand deleted buffer"));
Bram Moolenaar1e015462005-09-25 22:16:38 +00006891# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006892 s = get_vim_var_str(VV_FCS_CHOICE);
6893 if (STRCMP(s, "reload") == 0 && *reason != 'd')
6894 reload = TRUE;
6895 else if (STRCMP(s, "ask") == 0)
6896 n = FALSE;
6897 else
Bram Moolenaar1e015462005-09-25 22:16:38 +00006898# endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006899 return 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006900 }
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006901 if (!n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006902#endif
6903 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006904 if (*reason == 'd')
6905 mesg = _("E211: File \"%s\" no longer available");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006906 else
6907 {
6908 helpmesg = TRUE;
6909#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6910 can_reload = TRUE;
6911#endif
6912 /*
6913 * Check if the file contents really changed to avoid
6914 * giving a warning when only the timestamp was set (e.g.,
6915 * checked out of CVS). Always warn when the buffer was
6916 * changed.
6917 */
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006918 if (reason[2] == 'n')
6919 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006920 mesg = _("W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006921 mesg2 = _("See \":help W12\" for more info.");
6922 }
6923 else if (reason[1] == 'h')
6924 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006925 mesg = _("W11: Warning: File \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006926 mesg2 = _("See \":help W11\" for more info.");
6927 }
6928 else if (*reason == 'm')
6929 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006930 mesg = _("W16: Warning: Mode of file \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006931 mesg2 = _("See \":help W16\" for more info.");
6932 }
Bram Moolenaar85388b52009-06-24 09:58:32 +00006933 else
6934 /* Only timestamp changed, store it to avoid a warning
6935 * in check_mtime() later. */
6936 buf->b_mtime_read = buf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006937 }
6938 }
6939 }
6940
6941 }
6942 else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W)
6943 && vim_fexists(buf->b_ffname))
6944 {
6945 retval = 1;
6946 mesg = _("W13: Warning: File \"%s\" has been created after editing started");
6947 buf->b_flags |= BF_NEW_W;
6948#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6949 can_reload = TRUE;
6950#endif
6951 }
6952
6953 if (mesg != NULL)
6954 {
6955 path = home_replace_save(buf, buf->b_fname);
6956 if (path != NULL)
6957 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006958 if (!helpmesg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006959 mesg2 = "";
6960 tbuf = alloc((unsigned)(STRLEN(path) + STRLEN(mesg)
6961 + STRLEN(mesg2) + 2));
6962 sprintf((char *)tbuf, mesg, path);
Bram Moolenaar496c5262009-03-18 14:42:00 +00006963#ifdef FEAT_EVAL
6964 /* Set warningmsg here, before the unimportant and output-specific
6965 * mesg2 has been appended. */
6966 set_vim_var_string(VV_WARNINGMSG, tbuf, -1);
6967#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006968#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6969 if (can_reload)
6970 {
6971 if (*mesg2 != NUL)
6972 {
6973 STRCAT(tbuf, "\n");
6974 STRCAT(tbuf, mesg2);
6975 }
6976 if (do_dialog(VIM_WARNING, (char_u *)_("Warning"), tbuf,
Bram Moolenaard2c340a2011-01-17 20:08:11 +01006977 (char_u *)_("&OK\n&Load File"), 1, NULL, TRUE) == 2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006978 reload = TRUE;
6979 }
6980 else
6981#endif
6982 if (State > NORMAL_BUSY || (State & CMDLINE) || already_warned)
6983 {
6984 if (*mesg2 != NUL)
6985 {
6986 STRCAT(tbuf, "; ");
6987 STRCAT(tbuf, mesg2);
6988 }
6989 EMSG(tbuf);
6990 retval = 2;
6991 }
6992 else
6993 {
Bram Moolenaared203462004-06-16 11:19:22 +00006994# ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006995 if (!autocmd_busy)
Bram Moolenaared203462004-06-16 11:19:22 +00006996# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006997 {
6998 msg_start();
6999 msg_puts_attr(tbuf, hl_attr(HLF_E) + MSG_HIST);
7000 if (*mesg2 != NUL)
7001 msg_puts_attr((char_u *)mesg2,
7002 hl_attr(HLF_W) + MSG_HIST);
7003 msg_clr_eos();
7004 (void)msg_end();
7005 if (emsg_silent == 0)
7006 {
7007 out_flush();
Bram Moolenaared203462004-06-16 11:19:22 +00007008# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00007009 if (!focus)
Bram Moolenaared203462004-06-16 11:19:22 +00007010# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007011 /* give the user some time to think about it */
7012 ui_delay(1000L, TRUE);
7013
7014 /* don't redraw and erase the message */
7015 redraw_cmdline = FALSE;
7016 }
7017 }
7018 already_warned = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007019 }
7020
7021 vim_free(path);
7022 vim_free(tbuf);
7023 }
7024 }
7025
7026 if (reload)
Bram Moolenaar465748e2012-08-29 18:50:54 +02007027 {
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007028 /* Reload the buffer. */
Bram Moolenaar316059c2006-01-14 21:18:42 +00007029 buf_reload(buf, orig_mode);
Bram Moolenaar465748e2012-08-29 18:50:54 +02007030#ifdef FEAT_PERSISTENT_UNDO
7031 if (buf->b_p_udf && buf->b_ffname != NULL)
7032 {
7033 char_u hash[UNDO_HASH_SIZE];
7034 buf_T *save_curbuf = curbuf;
7035
7036 /* Any existing undo file is unusable, write it now. */
7037 curbuf = buf;
7038 u_compute_hash(hash);
7039 u_write_undo(NULL, FALSE, buf, hash);
7040 curbuf = save_curbuf;
7041 }
7042#endif
7043 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007044
Bram Moolenaar56718732006-03-15 22:53:57 +00007045#ifdef FEAT_AUTOCMD
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00007046 /* Trigger FileChangedShell when the file was changed in any way. */
7047 if (buf_valid(buf) && retval != 0)
Bram Moolenaar56718732006-03-15 22:53:57 +00007048 (void)apply_autocmds(EVENT_FILECHANGEDSHELLPOST,
7049 buf->b_fname, buf->b_fname, FALSE, buf);
7050#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007051#ifdef FEAT_GUI
7052 /* restore this in case an autocommand has set it; it would break
7053 * 'mousefocus' */
7054 need_mouse_correct = save_mouse_correct;
7055#endif
7056
7057 return retval;
7058}
7059
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007060/*
7061 * Reload a buffer that is already loaded.
7062 * Used when the file was changed outside of Vim.
Bram Moolenaar316059c2006-01-14 21:18:42 +00007063 * "orig_mode" is buf->b_orig_mode before the need for reloading was detected.
7064 * buf->b_orig_mode may have been reset already.
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007065 */
7066 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007067buf_reload(buf_T *buf, int orig_mode)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007068{
7069 exarg_T ea;
7070 pos_T old_cursor;
7071 linenr_T old_topline;
7072 int old_ro = buf->b_p_ro;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007073 buf_T *savebuf;
7074 int saved = OK;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007075 aco_save_T aco;
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007076 int flags = READ_NEW;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007077
7078 /* set curwin/curbuf for "buf" and save some things */
7079 aucmd_prepbuf(&aco, buf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007080
7081 /* We only want to read the text from the file, not reset the syntax
7082 * highlighting, clear marks, diff status, etc. Force the fileformat
7083 * and encoding to be the same. */
7084 if (prep_exarg(&ea, buf) == OK)
7085 {
7086 old_cursor = curwin->w_cursor;
7087 old_topline = curwin->w_topline;
7088
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007089 if (p_ur < 0 || curbuf->b_ml.ml_line_count <= p_ur)
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007090 {
7091 /* Save all the text, so that the reload can be undone.
7092 * Sync first so that this is a separate undo-able action. */
7093 u_sync(FALSE);
7094 saved = u_savecommon(0, curbuf->b_ml.ml_line_count + 1, 0, TRUE);
7095 flags |= READ_KEEP_UNDO;
7096 }
7097
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007098 /*
7099 * To behave like when a new file is edited (matters for
7100 * BufReadPost autocommands) we first need to delete the current
7101 * buffer contents. But if reading the file fails we should keep
7102 * the old contents. Can't use memory only, the file might be
7103 * too big. Use a hidden buffer to move the buffer contents to.
7104 */
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007105 if (bufempty() || saved == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007106 savebuf = NULL;
7107 else
7108 {
7109 /* Allocate a buffer without putting it in the buffer list. */
7110 savebuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007111 if (savebuf != NULL && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007112 {
7113 /* Open the memline. */
7114 curbuf = savebuf;
7115 curwin->w_buffer = savebuf;
Bram Moolenaar4770d092006-01-12 23:22:24 +00007116 saved = ml_open(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007117 curbuf = buf;
7118 curwin->w_buffer = buf;
7119 }
Bram Moolenaar8424a622006-04-19 21:23:36 +00007120 if (savebuf == NULL || saved == FAIL || buf != curbuf
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007121 || move_lines(buf, savebuf) == FAIL)
7122 {
7123 EMSG2(_("E462: Could not prepare for reloading \"%s\""),
7124 buf->b_fname);
7125 saved = FAIL;
7126 }
7127 }
7128
7129 if (saved == OK)
7130 {
7131 curbuf->b_flags |= BF_CHECK_RO; /* check for RO again */
7132#ifdef FEAT_AUTOCMD
7133 keep_filetype = TRUE; /* don't detect 'filetype' */
7134#endif
7135 if (readfile(buf->b_ffname, buf->b_fname, (linenr_T)0,
7136 (linenr_T)0,
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007137 (linenr_T)MAXLNUM, &ea, flags) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007138 {
7139#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
7140 if (!aborting())
7141#endif
7142 EMSG2(_("E321: Could not reload \"%s\""), buf->b_fname);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007143 if (savebuf != NULL && buf_valid(savebuf) && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007144 {
7145 /* Put the text back from the save buffer. First
7146 * delete any lines that readfile() added. */
7147 while (!bufempty())
Bram Moolenaar8424a622006-04-19 21:23:36 +00007148 if (ml_delete(buf->b_ml.ml_line_count, FALSE) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007149 break;
7150 (void)move_lines(savebuf, buf);
7151 }
7152 }
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007153 else if (buf == curbuf) /* "buf" still valid */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007154 {
7155 /* Mark the buffer as unmodified and free undo info. */
7156 unchanged(buf, TRUE);
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007157 if ((flags & READ_KEEP_UNDO) == 0)
7158 {
7159 u_blockfree(buf);
7160 u_clearall(buf);
7161 }
7162 else
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007163 {
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007164 /* Mark all undo states as changed. */
7165 u_unchanged(curbuf);
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007166 }
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007167 }
7168 }
7169 vim_free(ea.cmd);
7170
Bram Moolenaar8424a622006-04-19 21:23:36 +00007171 if (savebuf != NULL && buf_valid(savebuf))
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007172 wipe_buffer(savebuf, FALSE);
7173
7174#ifdef FEAT_DIFF
7175 /* Invalidate diff info if necessary. */
Bram Moolenaar8424a622006-04-19 21:23:36 +00007176 diff_invalidate(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007177#endif
7178
7179 /* Restore the topline and cursor position and check it (lines may
7180 * have been removed). */
7181 if (old_topline > curbuf->b_ml.ml_line_count)
7182 curwin->w_topline = curbuf->b_ml.ml_line_count;
7183 else
7184 curwin->w_topline = old_topline;
7185 curwin->w_cursor = old_cursor;
7186 check_cursor();
7187 update_topline();
7188#ifdef FEAT_AUTOCMD
7189 keep_filetype = FALSE;
7190#endif
7191#ifdef FEAT_FOLDING
7192 {
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007193 win_T *wp;
7194 tabpage_T *tp;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007195
7196 /* Update folds unless they are defined manually. */
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007197 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007198 if (wp->w_buffer == curwin->w_buffer
7199 && !foldmethodIsManual(wp))
7200 foldUpdateAll(wp);
7201 }
7202#endif
7203 /* If the mode didn't change and 'readonly' was set, keep the old
7204 * value; the user probably used the ":view" command. But don't
7205 * reset it, might have had a read error. */
7206 if (orig_mode == curbuf->b_orig_mode)
7207 curbuf->b_p_ro |= old_ro;
Bram Moolenaar52f85b72013-01-30 14:13:56 +01007208
7209 /* Modelines must override settings done by autocommands. */
7210 do_modelines(0);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007211 }
7212
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007213 /* restore curwin/curbuf and a few other things */
7214 aucmd_restbuf(&aco);
7215 /* Careful: autocommands may have made "buf" invalid! */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007216}
7217
Bram Moolenaar071d4272004-06-13 20:20:40 +00007218 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007219buf_store_time(buf_T *buf, struct stat *st, char_u *fname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007220{
7221 buf->b_mtime = (long)st->st_mtime;
Bram Moolenaar914703b2010-05-31 21:59:46 +02007222 buf->b_orig_size = st->st_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007223#ifdef HAVE_ST_MODE
7224 buf->b_orig_mode = (int)st->st_mode;
7225#else
7226 buf->b_orig_mode = mch_getperm(fname);
7227#endif
7228}
7229
7230/*
7231 * Adjust the line with missing eol, used for the next write.
7232 * Used for do_filter(), when the input lines for the filter are deleted.
7233 */
7234 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007235write_lnum_adjust(linenr_T offset)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007236{
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01007237 if (curbuf->b_no_eol_lnum != 0) /* only if there is a missing eol */
7238 curbuf->b_no_eol_lnum += offset;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007239}
7240
Bram Moolenaarda440d22016-01-16 21:27:23 +01007241#if defined(TEMPDIRNAMES) || defined(FEAT_EVAL) || defined(PROTO)
7242/*
7243 * Delete "name" and everything in it, recursively.
7244 * return 0 for succes, -1 if some file was not deleted.
7245 */
7246 int
7247delete_recursive(char_u *name)
7248{
7249 int result = 0;
7250 char_u **files;
7251 int file_count;
7252 int i;
7253 char_u *exp;
7254
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007255 /* A symbolic link to a directory itself is deleted, not the directory it
7256 * points to. */
7257 if (
Bram Moolenaar203258c2016-01-17 22:15:16 +01007258# if defined(UNIX) || defined(WIN32)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007259 mch_isrealdir(name)
Bram Moolenaar203258c2016-01-17 22:15:16 +01007260# else
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007261 mch_isdir(name)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007262# endif
7263 )
Bram Moolenaarda440d22016-01-16 21:27:23 +01007264 {
7265 vim_snprintf((char *)NameBuff, MAXPATHL, "%s/*", name);
7266 exp = vim_strsave(NameBuff);
7267 if (exp == NULL)
7268 return -1;
7269 if (gen_expand_wildcards(1, &exp, &file_count, &files,
Bram Moolenaar336bd622016-01-17 18:23:58 +01007270 EW_DIR|EW_FILE|EW_SILENT|EW_ALLLINKS|EW_DODOT|EW_EMPTYOK) == OK)
Bram Moolenaarda440d22016-01-16 21:27:23 +01007271 {
7272 for (i = 0; i < file_count; ++i)
7273 if (delete_recursive(files[i]) != 0)
7274 result = -1;
7275 FreeWild(file_count, files);
7276 }
7277 else
7278 result = -1;
7279 vim_free(exp);
7280 (void)mch_rmdir(name);
7281 }
7282 else
7283 result = mch_remove(name) == 0 ? 0 : -1;
7284
7285 return result;
7286}
7287#endif
7288
Bram Moolenaar071d4272004-06-13 20:20:40 +00007289#if defined(TEMPDIRNAMES) || defined(PROTO)
7290static long temp_count = 0; /* Temp filename counter. */
7291
7292/*
7293 * Delete the temp directory and all files it contains.
7294 */
7295 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007296vim_deltempdir(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007297{
Bram Moolenaar071d4272004-06-13 20:20:40 +00007298 if (vim_tempdir != NULL)
7299 {
Bram Moolenaarda440d22016-01-16 21:27:23 +01007300 /* remove the trailing path separator */
7301 gettail(vim_tempdir)[-1] = NUL;
7302 delete_recursive(vim_tempdir);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007303 vim_free(vim_tempdir);
7304 vim_tempdir = NULL;
7305 }
7306}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007307
7308/*
Bram Moolenaareaf03392009-11-17 11:08:52 +00007309 * Directory "tempdir" was created. Expand this name to a full path and put
7310 * it in "vim_tempdir". This avoids that using ":cd" would confuse us.
7311 * "tempdir" must be no longer than MAXPATHL.
7312 */
7313 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007314vim_settempdir(char_u *tempdir)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007315{
7316 char_u *buf;
7317
7318 buf = alloc((unsigned)MAXPATHL + 2);
7319 if (buf != NULL)
7320 {
7321 if (vim_FullName(tempdir, buf, MAXPATHL, FALSE) == FAIL)
7322 STRCPY(buf, tempdir);
7323# ifdef __EMX__
7324 if (vim_strchr(buf, '/') != NULL)
7325 STRCAT(buf, "/");
7326 else
7327# endif
7328 add_pathsep(buf);
7329 vim_tempdir = vim_strsave(buf);
7330 vim_free(buf);
7331 }
7332}
Bram Moolenaar4592dee2009-11-18 19:11:58 +00007333#endif
Bram Moolenaareaf03392009-11-17 11:08:52 +00007334
7335/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007336 * vim_tempname(): Return a unique name that can be used for a temp file.
7337 *
Bram Moolenaare5c421c2015-03-31 13:33:08 +02007338 * The temp file is NOT garanteed to be created. If "keep" is FALSE it is
7339 * garanteed to NOT be created.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007340 *
7341 * The returned pointer is to allocated memory.
7342 * The returned pointer is NULL if no valid name was found.
7343 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007344 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007345vim_tempname(
7346 int extra_char UNUSED, /* char to use in the name instead of '?' */
7347 int keep UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007348{
7349#ifdef USE_TMPNAM
7350 char_u itmp[L_tmpnam]; /* use tmpnam() */
7351#else
7352 char_u itmp[TEMPNAMELEN];
7353#endif
7354
7355#ifdef TEMPDIRNAMES
7356 static char *(tempdirs[]) = {TEMPDIRNAMES};
7357 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007358# ifndef EEXIST
7359 struct stat st;
7360# endif
7361
7362 /*
7363 * This will create a directory for private use by this instance of Vim.
7364 * This is done once, and the same directory is used for all temp files.
7365 * This method avoids security problems because of symlink attacks et al.
7366 * It's also a bit faster, because we only need to check for an existing
7367 * file when creating the directory and not for each temp file.
7368 */
7369 if (vim_tempdir == NULL)
7370 {
7371 /*
7372 * Try the entries in TEMPDIRNAMES to create the temp directory.
7373 */
Bram Moolenaar78a15312009-05-15 19:33:18 +00007374 for (i = 0; i < (int)(sizeof(tempdirs) / sizeof(char *)); ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007375 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007376# ifndef HAVE_MKDTEMP
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007377 size_t itmplen;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007378 long nr;
7379 long off;
7380# endif
7381
Bram Moolenaare1a61992015-12-03 21:02:27 +01007382 /* Expand $TMP, leave room for "/v1100000/999999999".
7383 * Skip the directory check if the expansion fails. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007384 expand_env((char_u *)tempdirs[i], itmp, TEMPNAMELEN - 20);
Bram Moolenaare1a61992015-12-03 21:02:27 +01007385 if (itmp[0] != '$' && mch_isdir(itmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007386 {
Bram Moolenaare1a61992015-12-03 21:02:27 +01007387 /* directory exists */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007388# ifdef __EMX__
7389 /* If $TMP contains a forward slash (perhaps using bash or
7390 * tcsh), don't add a backslash, use a forward slash!
7391 * Adding 2 backslashes didn't work. */
7392 if (vim_strchr(itmp, '/') != NULL)
7393 STRCAT(itmp, "/");
7394 else
7395# endif
7396 add_pathsep(itmp);
7397
Bram Moolenaareaf03392009-11-17 11:08:52 +00007398# ifdef HAVE_MKDTEMP
7399 /* Leave room for filename */
7400 STRCAT(itmp, "vXXXXXX");
7401 if (mkdtemp((char *)itmp) != NULL)
7402 vim_settempdir(itmp);
7403# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007404 /* Get an arbitrary number of up to 6 digits. When it's
7405 * unlikely that it already exists it will be faster,
7406 * otherwise it doesn't matter. The use of mkdir() avoids any
7407 * security problems because of the predictable number. */
7408 nr = (mch_get_pid() + (long)time(NULL)) % 1000000L;
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007409 itmplen = STRLEN(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007410
7411 /* Try up to 10000 different values until we find a name that
7412 * doesn't exist. */
7413 for (off = 0; off < 10000L; ++off)
7414 {
7415 int r;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007416# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007417 mode_t umask_save;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007418# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007419
Bram Moolenaareaf03392009-11-17 11:08:52 +00007420 sprintf((char *)itmp + itmplen, "v%ld", nr + off);
7421# ifndef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007422 /* If mkdir() does not set errno to EEXIST, check for
7423 * existing file here. There is a race condition then,
7424 * although it's fail-safe. */
7425 if (mch_stat((char *)itmp, &st) >= 0)
7426 continue;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007427# endif
7428# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007429 /* Make sure the umask doesn't remove the executable bit.
7430 * "repl" has been reported to use "177". */
7431 umask_save = umask(077);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007432# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007433 r = vim_mkdir(itmp, 0700);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007434# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007435 (void)umask(umask_save);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007436# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007437 if (r == 0)
7438 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007439 vim_settempdir(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007440 break;
7441 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007442# ifdef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007443 /* If the mkdir() didn't fail because the file/dir exists,
7444 * we probably can't create any dir here, try another
7445 * place. */
7446 if (errno != EEXIST)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007447# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007448 break;
7449 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007450# endif /* HAVE_MKDTEMP */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007451 if (vim_tempdir != NULL)
7452 break;
7453 }
7454 }
7455 }
7456
7457 if (vim_tempdir != NULL)
7458 {
7459 /* There is no need to check if the file exists, because we own the
7460 * directory and nobody else creates a file in it. */
7461 sprintf((char *)itmp, "%s%ld", vim_tempdir, temp_count++);
7462 return vim_strsave(itmp);
7463 }
7464
7465 return NULL;
7466
7467#else /* TEMPDIRNAMES */
7468
7469# ifdef WIN3264
7470 char szTempFile[_MAX_PATH + 1];
7471 char buf4[4];
7472 char_u *retval;
7473 char_u *p;
7474
7475 STRCPY(itmp, "");
7476 if (GetTempPath(_MAX_PATH, szTempFile) == 0)
Bram Moolenaarb1891912011-02-09 14:47:03 +01007477 {
7478 szTempFile[0] = '.'; /* GetTempPath() failed, use current dir */
7479 szTempFile[1] = NUL;
7480 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007481 strcpy(buf4, "VIM");
7482 buf4[2] = extra_char; /* make it "VIa", "VIb", etc. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007483 if (GetTempFileName(szTempFile, buf4, 0, (LPSTR)itmp) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007484 return NULL;
Bram Moolenaare5c421c2015-03-31 13:33:08 +02007485 if (!keep)
7486 /* GetTempFileName() will create the file, we don't want that */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007487 (void)DeleteFile((LPSTR)itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007488
7489 /* Backslashes in a temp file name cause problems when filtering with
7490 * "sh". NOTE: This also checks 'shellcmdflag' to help those people who
7491 * didn't set 'shellslash'. */
7492 retval = vim_strsave(itmp);
7493 if (*p_shcf == '-' || p_ssl)
7494 for (p = retval; *p; ++p)
7495 if (*p == '\\')
7496 *p = '/';
7497 return retval;
7498
7499# else /* WIN3264 */
7500
7501# ifdef USE_TMPNAM
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007502 char_u *p;
7503
Bram Moolenaar071d4272004-06-13 20:20:40 +00007504 /* tmpnam() will make its own name */
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007505 p = tmpnam((char *)itmp);
7506 if (p == NULL || *p == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007507 return NULL;
7508# else
7509 char_u *p;
7510
7511# ifdef VMS_TEMPNAM
7512 /* mktemp() is not working on VMS. It seems to be
7513 * a do-nothing function. Therefore we use tempnam().
7514 */
7515 sprintf((char *)itmp, "VIM%c", extra_char);
7516 p = (char_u *)tempnam("tmp:", (char *)itmp);
7517 if (p != NULL)
7518 {
Bram Moolenaar206f0112014-03-12 16:51:55 +01007519 /* VMS will use '.LIS' if we don't explicitly specify an extension,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007520 * and VIM will then be unable to find the file later */
7521 STRCPY(itmp, p);
7522 STRCAT(itmp, ".txt");
7523 free(p);
7524 }
7525 else
7526 return NULL;
7527# else
7528 STRCPY(itmp, TEMPNAME);
7529 if ((p = vim_strchr(itmp, '?')) != NULL)
7530 *p = extra_char;
7531 if (mktemp((char *)itmp) == NULL)
7532 return NULL;
7533# endif
7534# endif
7535
7536 return vim_strsave(itmp);
7537# endif /* WIN3264 */
7538#endif /* TEMPDIRNAMES */
7539}
7540
7541#if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
7542/*
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02007543 * Convert all backslashes in fname to forward slashes in-place, unless when
7544 * it looks like a URL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007545 */
7546 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007547forward_slash(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007548{
7549 char_u *p;
7550
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02007551 if (path_with_url(fname))
7552 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007553 for (p = fname; *p != NUL; ++p)
7554# ifdef FEAT_MBYTE
7555 /* The Big5 encoding can have '\' in the trail byte. */
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00007556 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007557 ++p;
7558 else
7559# endif
7560 if (*p == '\\')
7561 *p = '/';
7562}
7563#endif
7564
7565
7566/*
7567 * Code for automatic commands.
7568 *
7569 * Only included when "FEAT_AUTOCMD" has been defined.
7570 */
7571
7572#if defined(FEAT_AUTOCMD) || defined(PROTO)
7573
7574/*
7575 * The autocommands are stored in a list for each event.
7576 * Autocommands for the same pattern, that are consecutive, are joined
7577 * together, to avoid having to match the pattern too often.
7578 * The result is an array of Autopat lists, which point to AutoCmd lists:
7579 *
7580 * first_autopat[0] --> Autopat.next --> Autopat.next --> NULL
7581 * Autopat.cmds Autopat.cmds
7582 * | |
7583 * V V
7584 * AutoCmd.next AutoCmd.next
7585 * | |
7586 * V V
7587 * AutoCmd.next NULL
7588 * |
7589 * V
7590 * NULL
7591 *
7592 * first_autopat[1] --> Autopat.next --> NULL
7593 * Autopat.cmds
7594 * |
7595 * V
7596 * AutoCmd.next
7597 * |
7598 * V
7599 * NULL
7600 * etc.
7601 *
7602 * The order of AutoCmds is important, this is the order in which they were
7603 * defined and will have to be executed.
7604 */
7605typedef struct AutoCmd
7606{
7607 char_u *cmd; /* The command to be executed (NULL
7608 when command has been removed) */
7609 char nested; /* If autocommands nest here */
7610 char last; /* last command in list */
7611#ifdef FEAT_EVAL
7612 scid_T scriptID; /* script ID where defined */
7613#endif
7614 struct AutoCmd *next; /* Next AutoCmd in list */
7615} AutoCmd;
7616
7617typedef struct AutoPat
7618{
Bram Moolenaar071d4272004-06-13 20:20:40 +00007619 char_u *pat; /* pattern as typed (NULL when pattern
7620 has been removed) */
Bram Moolenaar748bf032005-02-02 23:04:36 +00007621 regprog_T *reg_prog; /* compiled regprog for pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007622 AutoCmd *cmds; /* list of commands to do */
7623 struct AutoPat *next; /* next AutoPat in AutoPat list */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007624 int group; /* group ID */
7625 int patlen; /* strlen() of pat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007626 int buflocal_nr; /* !=0 for buffer-local AutoPat */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007627 char allow_dirs; /* Pattern may match whole path */
7628 char last; /* last pattern for apply_autocmds() */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007629} AutoPat;
7630
7631static struct event_name
7632{
7633 char *name; /* event name */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007634 event_T event; /* event number */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007635} event_names[] =
7636{
7637 {"BufAdd", EVENT_BUFADD},
7638 {"BufCreate", EVENT_BUFADD},
7639 {"BufDelete", EVENT_BUFDELETE},
7640 {"BufEnter", EVENT_BUFENTER},
7641 {"BufFilePost", EVENT_BUFFILEPOST},
7642 {"BufFilePre", EVENT_BUFFILEPRE},
7643 {"BufHidden", EVENT_BUFHIDDEN},
7644 {"BufLeave", EVENT_BUFLEAVE},
7645 {"BufNew", EVENT_BUFNEW},
7646 {"BufNewFile", EVENT_BUFNEWFILE},
7647 {"BufRead", EVENT_BUFREADPOST},
7648 {"BufReadCmd", EVENT_BUFREADCMD},
7649 {"BufReadPost", EVENT_BUFREADPOST},
7650 {"BufReadPre", EVENT_BUFREADPRE},
7651 {"BufUnload", EVENT_BUFUNLOAD},
7652 {"BufWinEnter", EVENT_BUFWINENTER},
7653 {"BufWinLeave", EVENT_BUFWINLEAVE},
7654 {"BufWipeout", EVENT_BUFWIPEOUT},
7655 {"BufWrite", EVENT_BUFWRITEPRE},
7656 {"BufWritePost", EVENT_BUFWRITEPOST},
7657 {"BufWritePre", EVENT_BUFWRITEPRE},
7658 {"BufWriteCmd", EVENT_BUFWRITECMD},
7659 {"CmdwinEnter", EVENT_CMDWINENTER},
7660 {"CmdwinLeave", EVENT_CMDWINLEAVE},
Bram Moolenaard5005162014-08-22 23:05:54 +02007661 {"CmdUndefined", EVENT_CMDUNDEFINED},
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007662 {"ColorScheme", EVENT_COLORSCHEME},
Bram Moolenaarcfa3cae2012-07-10 17:14:56 +02007663 {"CompleteDone", EVENT_COMPLETEDONE},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007664 {"CursorHold", EVENT_CURSORHOLD},
7665 {"CursorHoldI", EVENT_CURSORHOLDI},
7666 {"CursorMoved", EVENT_CURSORMOVED},
7667 {"CursorMovedI", EVENT_CURSORMOVEDI},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007668 {"EncodingChanged", EVENT_ENCODINGCHANGED},
7669 {"FileEncoding", EVENT_ENCODINGCHANGED},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007670 {"FileAppendPost", EVENT_FILEAPPENDPOST},
7671 {"FileAppendPre", EVENT_FILEAPPENDPRE},
7672 {"FileAppendCmd", EVENT_FILEAPPENDCMD},
7673 {"FileChangedShell",EVENT_FILECHANGEDSHELL},
Bram Moolenaar56718732006-03-15 22:53:57 +00007674 {"FileChangedShellPost",EVENT_FILECHANGEDSHELLPOST},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007675 {"FileChangedRO", EVENT_FILECHANGEDRO},
7676 {"FileReadPost", EVENT_FILEREADPOST},
7677 {"FileReadPre", EVENT_FILEREADPRE},
7678 {"FileReadCmd", EVENT_FILEREADCMD},
7679 {"FileType", EVENT_FILETYPE},
7680 {"FileWritePost", EVENT_FILEWRITEPOST},
7681 {"FileWritePre", EVENT_FILEWRITEPRE},
7682 {"FileWriteCmd", EVENT_FILEWRITECMD},
7683 {"FilterReadPost", EVENT_FILTERREADPOST},
7684 {"FilterReadPre", EVENT_FILTERREADPRE},
7685 {"FilterWritePost", EVENT_FILTERWRITEPOST},
7686 {"FilterWritePre", EVENT_FILTERWRITEPRE},
7687 {"FocusGained", EVENT_FOCUSGAINED},
7688 {"FocusLost", EVENT_FOCUSLOST},
7689 {"FuncUndefined", EVENT_FUNCUNDEFINED},
7690 {"GUIEnter", EVENT_GUIENTER},
Bram Moolenaar265e5072006-08-29 16:13:22 +00007691 {"GUIFailed", EVENT_GUIFAILED},
Bram Moolenaar843ee412004-06-30 16:16:41 +00007692 {"InsertChange", EVENT_INSERTCHANGE},
7693 {"InsertEnter", EVENT_INSERTENTER},
7694 {"InsertLeave", EVENT_INSERTLEAVE},
Bram Moolenaare659c952011-05-19 17:25:41 +02007695 {"InsertCharPre", EVENT_INSERTCHARPRE},
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00007696 {"MenuPopup", EVENT_MENUPOPUP},
Bram Moolenaar53744302015-07-17 17:38:22 +02007697 {"OptionSet", EVENT_OPTIONSET},
Bram Moolenaar7c626922005-02-07 22:01:03 +00007698 {"QuickFixCmdPost", EVENT_QUICKFIXCMDPOST},
7699 {"QuickFixCmdPre", EVENT_QUICKFIXCMDPRE},
Bram Moolenaar3b53dfb2012-06-06 18:03:07 +02007700 {"QuitPre", EVENT_QUITPRE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007701 {"RemoteReply", EVENT_REMOTEREPLY},
Bram Moolenaar9372a112005-12-06 19:59:18 +00007702 {"SessionLoadPost", EVENT_SESSIONLOADPOST},
Bram Moolenaar5c4bab02006-03-10 21:37:46 +00007703 {"ShellCmdPost", EVENT_SHELLCMDPOST},
7704 {"ShellFilterPost", EVENT_SHELLFILTERPOST},
Bram Moolenaara2031822006-03-07 22:29:51 +00007705 {"SourcePre", EVENT_SOURCEPRE},
Bram Moolenaar8dd1aa52007-01-16 20:33:19 +00007706 {"SourceCmd", EVENT_SOURCECMD},
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00007707 {"SpellFileMissing",EVENT_SPELLFILEMISSING},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007708 {"StdinReadPost", EVENT_STDINREADPOST},
7709 {"StdinReadPre", EVENT_STDINREADPRE},
Bram Moolenaarb815dac2005-12-07 20:59:24 +00007710 {"SwapExists", EVENT_SWAPEXISTS},
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00007711 {"Syntax", EVENT_SYNTAX},
Bram Moolenaar70836c82006-02-20 21:28:49 +00007712 {"TabEnter", EVENT_TABENTER},
7713 {"TabLeave", EVENT_TABLEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007714 {"TermChanged", EVENT_TERMCHANGED},
7715 {"TermResponse", EVENT_TERMRESPONSE},
Bram Moolenaar186628f2013-03-19 13:33:23 +01007716 {"TextChanged", EVENT_TEXTCHANGED},
7717 {"TextChangedI", EVENT_TEXTCHANGEDI},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007718 {"User", EVENT_USER},
7719 {"VimEnter", EVENT_VIMENTER},
7720 {"VimLeave", EVENT_VIMLEAVE},
7721 {"VimLeavePre", EVENT_VIMLEAVEPRE},
7722 {"WinEnter", EVENT_WINENTER},
7723 {"WinLeave", EVENT_WINLEAVE},
Bram Moolenaar56718732006-03-15 22:53:57 +00007724 {"VimResized", EVENT_VIMRESIZED},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007725 {NULL, (event_T)0}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007726};
7727
7728static AutoPat *first_autopat[NUM_EVENTS] =
7729{
7730 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7731 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7732 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7733 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00007734 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaar53744302015-07-17 17:38:22 +02007735 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007736};
7737
7738/*
7739 * struct used to keep status while executing autocommands for an event.
7740 */
7741typedef struct AutoPatCmd
7742{
7743 AutoPat *curpat; /* next AutoPat to examine */
7744 AutoCmd *nextcmd; /* next AutoCmd to execute */
7745 int group; /* group being used */
7746 char_u *fname; /* fname to match with */
7747 char_u *sfname; /* sfname to match with */
7748 char_u *tail; /* tail of fname */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007749 event_T event; /* current event */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007750 int arg_bufnr; /* initially equal to <abuf>, set to zero when
7751 buf is deleted */
7752 struct AutoPatCmd *next; /* chain of active apc-s for auto-invalidation*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00007753} AutoPatCmd;
7754
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007755static AutoPatCmd *active_apc_list = NULL; /* stack of active autocommands */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007756
Bram Moolenaar071d4272004-06-13 20:20:40 +00007757/*
7758 * augroups stores a list of autocmd group names.
7759 */
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007760static garray_T augroups = {0, 0, sizeof(char_u *), 10, NULL};
Bram Moolenaar071d4272004-06-13 20:20:40 +00007761#define AUGROUP_NAME(i) (((char_u **)augroups.ga_data)[i])
7762
7763/*
7764 * The ID of the current group. Group 0 is the default one.
7765 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007766static int current_augroup = AUGROUP_DEFAULT;
7767
7768static int au_need_clean = FALSE; /* need to delete marked patterns */
7769
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007770static void show_autocmd(AutoPat *ap, event_T event);
7771static void au_remove_pat(AutoPat *ap);
7772static void au_remove_cmds(AutoPat *ap);
7773static void au_cleanup(void);
7774static int au_new_group(char_u *name);
7775static void au_del_group(char_u *name);
7776static event_T event_name2nr(char_u *start, char_u **end);
7777static char_u *event_nr2name(event_T event);
7778static char_u *find_end_event(char_u *arg, int have_group);
7779static int event_ignored(event_T event);
7780static int au_get_grouparg(char_u **argp);
7781static int do_autocmd_event(event_T event, char_u *pat, int nested, char_u *cmd, int forceit, int group);
7782static int apply_autocmds_group(event_T event, char_u *fname, char_u *fname_io, int force, int group, buf_T *buf, exarg_T *eap);
7783static void auto_next_pat(AutoPatCmd *apc, int stop_at_last);
Bram Moolenaardffa5b82014-11-19 16:38:07 +01007784#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN)
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007785static 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 +01007786#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007787
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007788
Bram Moolenaar754b5602006-02-09 23:53:20 +00007789static event_T last_event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007790static int last_group;
Bram Moolenaar78ab3312007-09-29 12:16:41 +00007791static int autocmd_blocked = 0; /* block all autocmds */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007792
7793/*
7794 * Show the autocommands for one AutoPat.
7795 */
7796 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007797show_autocmd(AutoPat *ap, event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007798{
7799 AutoCmd *ac;
7800
7801 /* Check for "got_int" (here and at various places below), which is set
7802 * when "q" has been hit for the "--more--" prompt */
7803 if (got_int)
7804 return;
7805 if (ap->pat == NULL) /* pattern has been removed */
7806 return;
7807
7808 msg_putchar('\n');
7809 if (got_int)
7810 return;
7811 if (event != last_event || ap->group != last_group)
7812 {
7813 if (ap->group != AUGROUP_DEFAULT)
7814 {
7815 if (AUGROUP_NAME(ap->group) == NULL)
7816 msg_puts_attr((char_u *)_("--Deleted--"), hl_attr(HLF_E));
7817 else
7818 msg_puts_attr(AUGROUP_NAME(ap->group), hl_attr(HLF_T));
7819 msg_puts((char_u *)" ");
7820 }
7821 msg_puts_attr(event_nr2name(event), hl_attr(HLF_T));
7822 last_event = event;
7823 last_group = ap->group;
7824 msg_putchar('\n');
7825 if (got_int)
7826 return;
7827 }
7828 msg_col = 4;
7829 msg_outtrans(ap->pat);
7830
7831 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7832 {
7833 if (ac->cmd != NULL) /* skip removed commands */
7834 {
7835 if (msg_col >= 14)
7836 msg_putchar('\n');
7837 msg_col = 14;
7838 if (got_int)
7839 return;
7840 msg_outtrans(ac->cmd);
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00007841#ifdef FEAT_EVAL
7842 if (p_verbose > 0)
7843 last_set_msg(ac->scriptID);
7844#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007845 if (got_int)
7846 return;
7847 if (ac->next != NULL)
7848 {
7849 msg_putchar('\n');
7850 if (got_int)
7851 return;
7852 }
7853 }
7854 }
7855}
7856
7857/*
7858 * Mark an autocommand pattern for deletion.
7859 */
7860 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007861au_remove_pat(AutoPat *ap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007862{
7863 vim_free(ap->pat);
7864 ap->pat = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007865 ap->buflocal_nr = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007866 au_need_clean = TRUE;
7867}
7868
7869/*
7870 * Mark all commands for a pattern for deletion.
7871 */
7872 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007873au_remove_cmds(AutoPat *ap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007874{
7875 AutoCmd *ac;
7876
7877 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7878 {
7879 vim_free(ac->cmd);
7880 ac->cmd = NULL;
7881 }
7882 au_need_clean = TRUE;
7883}
7884
7885/*
7886 * Cleanup autocommands and patterns that have been deleted.
7887 * This is only done when not executing autocommands.
7888 */
7889 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007890au_cleanup(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007891{
7892 AutoPat *ap, **prev_ap;
7893 AutoCmd *ac, **prev_ac;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007894 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007895
7896 if (autocmd_busy || !au_need_clean)
7897 return;
7898
7899 /* loop over all events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007900 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7901 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007902 {
7903 /* loop over all autocommand patterns */
7904 prev_ap = &(first_autopat[(int)event]);
7905 for (ap = *prev_ap; ap != NULL; ap = *prev_ap)
7906 {
7907 /* loop over all commands for this pattern */
7908 prev_ac = &(ap->cmds);
7909 for (ac = *prev_ac; ac != NULL; ac = *prev_ac)
7910 {
7911 /* remove the command if the pattern is to be deleted or when
7912 * the command has been marked for deletion */
7913 if (ap->pat == NULL || ac->cmd == NULL)
7914 {
7915 *prev_ac = ac->next;
7916 vim_free(ac->cmd);
7917 vim_free(ac);
7918 }
7919 else
7920 prev_ac = &(ac->next);
7921 }
7922
7923 /* remove the pattern if it has been marked for deletion */
7924 if (ap->pat == NULL)
7925 {
7926 *prev_ap = ap->next;
Bram Moolenaar473de612013-06-08 18:19:48 +02007927 vim_regfree(ap->reg_prog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007928 vim_free(ap);
7929 }
7930 else
7931 prev_ap = &(ap->next);
7932 }
7933 }
7934
7935 au_need_clean = FALSE;
7936}
7937
7938/*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007939 * Called when buffer is freed, to remove/invalidate related buffer-local
7940 * autocmds.
7941 */
7942 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007943aubuflocal_remove(buf_T *buf)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007944{
7945 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007946 event_T event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007947 AutoPatCmd *apc;
7948
7949 /* invalidate currently executing autocommands */
7950 for (apc = active_apc_list; apc; apc = apc->next)
7951 if (buf->b_fnum == apc->arg_bufnr)
7952 apc->arg_bufnr = 0;
7953
7954 /* invalidate buflocals looping through events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007955 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7956 event = (event_T)((int)event + 1))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007957 /* loop over all autocommand patterns */
7958 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
7959 if (ap->buflocal_nr == buf->b_fnum)
7960 {
7961 au_remove_pat(ap);
7962 if (p_verbose >= 6)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007963 {
7964 verbose_enter();
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007965 smsg((char_u *)
7966 _("auto-removing autocommand: %s <buffer=%d>"),
7967 event_nr2name(event), buf->b_fnum);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007968 verbose_leave();
7969 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007970 }
7971 au_cleanup();
7972}
7973
7974/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007975 * Add an autocmd group name.
7976 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
7977 */
7978 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007979au_new_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007980{
7981 int i;
7982
7983 i = au_find_group(name);
7984 if (i == AUGROUP_ERROR) /* the group doesn't exist yet, add it */
7985 {
7986 /* First try using a free entry. */
7987 for (i = 0; i < augroups.ga_len; ++i)
7988 if (AUGROUP_NAME(i) == NULL)
7989 break;
7990 if (i == augroups.ga_len && ga_grow(&augroups, 1) == FAIL)
7991 return AUGROUP_ERROR;
7992
7993 AUGROUP_NAME(i) = vim_strsave(name);
7994 if (AUGROUP_NAME(i) == NULL)
7995 return AUGROUP_ERROR;
7996 if (i == augroups.ga_len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007997 ++augroups.ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007998 }
7999
8000 return i;
8001}
8002
8003 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008004au_del_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008005{
8006 int i;
8007
8008 i = au_find_group(name);
8009 if (i == AUGROUP_ERROR) /* the group doesn't exist */
8010 EMSG2(_("E367: No such group: \"%s\""), name);
8011 else
8012 {
8013 vim_free(AUGROUP_NAME(i));
8014 AUGROUP_NAME(i) = NULL;
8015 }
8016}
8017
8018/*
8019 * Find the ID of an autocmd group name.
8020 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
8021 */
8022 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008023au_find_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008024{
8025 int i;
8026
8027 for (i = 0; i < augroups.ga_len; ++i)
8028 if (AUGROUP_NAME(i) != NULL && STRCMP(AUGROUP_NAME(i), name) == 0)
8029 return i;
8030 return AUGROUP_ERROR;
8031}
8032
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008033/*
8034 * Return TRUE if augroup "name" exists.
8035 */
8036 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008037au_has_group(char_u *name)
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008038{
8039 return au_find_group(name) != AUGROUP_ERROR;
8040}
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008041
Bram Moolenaar071d4272004-06-13 20:20:40 +00008042/*
8043 * ":augroup {name}".
8044 */
8045 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008046do_augroup(char_u *arg, int del_group)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008047{
8048 int i;
8049
8050 if (del_group)
8051 {
8052 if (*arg == NUL)
8053 EMSG(_(e_argreq));
8054 else
8055 au_del_group(arg);
8056 }
8057 else if (STRICMP(arg, "end") == 0) /* ":aug end": back to group 0 */
8058 current_augroup = AUGROUP_DEFAULT;
8059 else if (*arg) /* ":aug xxx": switch to group xxx */
8060 {
8061 i = au_new_group(arg);
8062 if (i != AUGROUP_ERROR)
8063 current_augroup = i;
8064 }
8065 else /* ":aug": list the group names */
8066 {
8067 msg_start();
8068 for (i = 0; i < augroups.ga_len; ++i)
8069 {
8070 if (AUGROUP_NAME(i) != NULL)
8071 {
8072 msg_puts(AUGROUP_NAME(i));
8073 msg_puts((char_u *)" ");
8074 }
8075 }
8076 msg_clr_eos();
8077 msg_end();
8078 }
8079}
8080
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008081#if defined(EXITFREE) || defined(PROTO)
8082 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008083free_all_autocmds(void)
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008084{
8085 for (current_augroup = -1; current_augroup < augroups.ga_len;
8086 ++current_augroup)
8087 do_autocmd((char_u *)"", TRUE);
8088 ga_clear_strings(&augroups);
8089}
8090#endif
8091
Bram Moolenaar071d4272004-06-13 20:20:40 +00008092/*
8093 * Return the event number for event name "start".
8094 * Return NUM_EVENTS if the event name was not found.
8095 * Return a pointer to the next event name in "end".
8096 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008097 static event_T
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008098event_name2nr(char_u *start, char_u **end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008099{
8100 char_u *p;
8101 int i;
8102 int len;
8103
8104 /* the event name ends with end of line, a blank or a comma */
8105 for (p = start; *p && !vim_iswhite(*p) && *p != ','; ++p)
8106 ;
8107 for (i = 0; event_names[i].name != NULL; ++i)
8108 {
8109 len = (int)STRLEN(event_names[i].name);
8110 if (len == p - start && STRNICMP(event_names[i].name, start, len) == 0)
8111 break;
8112 }
8113 if (*p == ',')
8114 ++p;
8115 *end = p;
8116 if (event_names[i].name == NULL)
8117 return NUM_EVENTS;
8118 return event_names[i].event;
8119}
8120
8121/*
8122 * Return the name for event "event".
8123 */
8124 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008125event_nr2name(event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008126{
8127 int i;
8128
8129 for (i = 0; event_names[i].name != NULL; ++i)
8130 if (event_names[i].event == event)
8131 return (char_u *)event_names[i].name;
8132 return (char_u *)"Unknown";
8133}
8134
8135/*
8136 * Scan over the events. "*" stands for all events.
8137 */
8138 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008139find_end_event(
8140 char_u *arg,
8141 int have_group) /* TRUE when group name was found */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008142{
8143 char_u *pat;
8144 char_u *p;
8145
8146 if (*arg == '*')
8147 {
8148 if (arg[1] && !vim_iswhite(arg[1]))
8149 {
8150 EMSG2(_("E215: Illegal character after *: %s"), arg);
8151 return NULL;
8152 }
8153 pat = arg + 1;
8154 }
8155 else
8156 {
8157 for (pat = arg; *pat && !vim_iswhite(*pat); pat = p)
8158 {
8159 if ((int)event_name2nr(pat, &p) >= (int)NUM_EVENTS)
8160 {
8161 if (have_group)
8162 EMSG2(_("E216: No such event: %s"), pat);
8163 else
8164 EMSG2(_("E216: No such group or event: %s"), pat);
8165 return NULL;
8166 }
8167 }
8168 }
8169 return pat;
8170}
8171
8172/*
8173 * Return TRUE if "event" is included in 'eventignore'.
8174 */
8175 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008176event_ignored(event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008177{
8178 char_u *p = p_ei;
8179
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008180 while (*p != NUL)
8181 {
8182 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8183 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008184 if (event_name2nr(p, &p) == event)
8185 return TRUE;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008186 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008187
8188 return FALSE;
8189}
8190
8191/*
8192 * Return OK when the contents of p_ei is valid, FAIL otherwise.
8193 */
8194 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008195check_ei(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008196{
8197 char_u *p = p_ei;
8198
Bram Moolenaar071d4272004-06-13 20:20:40 +00008199 while (*p)
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008200 {
8201 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8202 {
8203 p += 3;
8204 if (*p == ',')
8205 ++p;
8206 }
8207 else if (event_name2nr(p, &p) == NUM_EVENTS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008208 return FAIL;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008209 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008210
8211 return OK;
8212}
8213
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008214# if defined(FEAT_SYN_HL) || defined(PROTO)
8215
8216/*
8217 * Add "what" to 'eventignore' to skip loading syntax highlighting for every
8218 * buffer loaded into the window. "what" must start with a comma.
8219 * Returns the old value of 'eventignore' in allocated memory.
8220 */
8221 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008222au_event_disable(char *what)
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008223{
8224 char_u *new_ei;
8225 char_u *save_ei;
8226
8227 save_ei = vim_strsave(p_ei);
8228 if (save_ei != NULL)
8229 {
Bram Moolenaara5792f52005-11-23 21:25:05 +00008230 new_ei = vim_strnsave(p_ei, (int)(STRLEN(p_ei) + STRLEN(what)));
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008231 if (new_ei != NULL)
8232 {
Bram Moolenaar8cac9fd2010-03-02 12:48:05 +01008233 if (*what == ',' && *p_ei == NUL)
8234 STRCPY(new_ei, what + 1);
8235 else
8236 STRCAT(new_ei, what);
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008237 set_string_option_direct((char_u *)"ei", -1, new_ei,
8238 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008239 vim_free(new_ei);
8240 }
8241 }
8242 return save_ei;
8243}
8244
8245 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008246au_event_restore(char_u *old_ei)
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008247{
8248 if (old_ei != NULL)
8249 {
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008250 set_string_option_direct((char_u *)"ei", -1, old_ei,
8251 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008252 vim_free(old_ei);
8253 }
8254}
8255# endif /* FEAT_SYN_HL */
8256
Bram Moolenaar071d4272004-06-13 20:20:40 +00008257/*
8258 * do_autocmd() -- implements the :autocmd command. Can be used in the
8259 * following ways:
8260 *
8261 * :autocmd <event> <pat> <cmd> Add <cmd> to the list of commands that
8262 * will be automatically executed for <event>
8263 * when editing a file matching <pat>, in
8264 * the current group.
8265 * :autocmd <event> <pat> Show the auto-commands associated with
8266 * <event> and <pat>.
8267 * :autocmd <event> Show the auto-commands associated with
8268 * <event>.
8269 * :autocmd Show all auto-commands.
8270 * :autocmd! <event> <pat> <cmd> Remove all auto-commands associated with
8271 * <event> and <pat>, and add the command
8272 * <cmd>, for the current group.
8273 * :autocmd! <event> <pat> Remove all auto-commands associated with
8274 * <event> and <pat> for the current group.
8275 * :autocmd! <event> Remove all auto-commands associated with
8276 * <event> for the current group.
8277 * :autocmd! Remove ALL auto-commands for the current
8278 * group.
8279 *
8280 * Multiple events and patterns may be given separated by commas. Here are
8281 * some examples:
8282 * :autocmd bufread,bufenter *.c,*.h set tw=0 smartindent noic
8283 * :autocmd bufleave * set tw=79 nosmartindent ic infercase
8284 *
8285 * :autocmd * *.c show all autocommands for *.c files.
Bram Moolenaard35f9712005-12-18 22:02:33 +00008286 *
8287 * Mostly a {group} argument can optionally appear before <event>.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008288 */
8289 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008290do_autocmd(char_u *arg, int forceit)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008291{
8292 char_u *pat;
8293 char_u *envpat = NULL;
8294 char_u *cmd;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008295 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008296 int need_free = FALSE;
8297 int nested = FALSE;
8298 int group;
8299
8300 /*
8301 * Check for a legal group name. If not, use AUGROUP_ALL.
8302 */
8303 group = au_get_grouparg(&arg);
8304 if (arg == NULL) /* out of memory */
8305 return;
8306
8307 /*
8308 * Scan over the events.
8309 * If we find an illegal name, return here, don't do anything.
8310 */
8311 pat = find_end_event(arg, group != AUGROUP_ALL);
8312 if (pat == NULL)
8313 return;
8314
8315 /*
8316 * Scan over the pattern. Put a NUL at the end.
8317 */
8318 pat = skipwhite(pat);
8319 cmd = pat;
8320 while (*cmd && (!vim_iswhite(*cmd) || cmd[-1] == '\\'))
8321 cmd++;
8322 if (*cmd)
8323 *cmd++ = NUL;
8324
8325 /* Expand environment variables in the pattern. Set 'shellslash', we want
8326 * forward slashes here. */
8327 if (vim_strchr(pat, '$') != NULL || vim_strchr(pat, '~') != NULL)
8328 {
8329#ifdef BACKSLASH_IN_FILENAME
8330 int p_ssl_save = p_ssl;
8331
8332 p_ssl = TRUE;
8333#endif
8334 envpat = expand_env_save(pat);
8335#ifdef BACKSLASH_IN_FILENAME
8336 p_ssl = p_ssl_save;
8337#endif
8338 if (envpat != NULL)
8339 pat = envpat;
8340 }
8341
8342 /*
8343 * Check for "nested" flag.
8344 */
8345 cmd = skipwhite(cmd);
8346 if (*cmd != NUL && STRNCMP(cmd, "nested", 6) == 0 && vim_iswhite(cmd[6]))
8347 {
8348 nested = TRUE;
8349 cmd = skipwhite(cmd + 6);
8350 }
8351
8352 /*
8353 * Find the start of the commands.
8354 * Expand <sfile> in it.
8355 */
8356 if (*cmd != NUL)
8357 {
8358 cmd = expand_sfile(cmd);
8359 if (cmd == NULL) /* some error */
8360 return;
8361 need_free = TRUE;
8362 }
8363
8364 /*
8365 * Print header when showing autocommands.
8366 */
8367 if (!forceit && *cmd == NUL)
8368 {
8369 /* Highlight title */
8370 MSG_PUTS_TITLE(_("\n--- Auto-Commands ---"));
8371 }
8372
8373 /*
8374 * Loop over the events.
8375 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008376 last_event = (event_T)-1; /* for listing the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008377 last_group = AUGROUP_ERROR; /* for listing the group name */
8378 if (*arg == '*' || *arg == NUL)
8379 {
Bram Moolenaar754b5602006-02-09 23:53:20 +00008380 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8381 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008382 if (do_autocmd_event(event, pat,
8383 nested, cmd, forceit, group) == FAIL)
8384 break;
8385 }
8386 else
8387 {
8388 while (*arg && !vim_iswhite(*arg))
8389 if (do_autocmd_event(event_name2nr(arg, &arg), pat,
8390 nested, cmd, forceit, group) == FAIL)
8391 break;
8392 }
8393
8394 if (need_free)
8395 vim_free(cmd);
8396 vim_free(envpat);
8397}
8398
8399/*
8400 * Find the group ID in a ":autocmd" or ":doautocmd" argument.
8401 * The "argp" argument is advanced to the following argument.
8402 *
8403 * Returns the group ID, AUGROUP_ERROR for error (out of memory).
8404 */
8405 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008406au_get_grouparg(char_u **argp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008407{
8408 char_u *group_name;
8409 char_u *p;
8410 char_u *arg = *argp;
8411 int group = AUGROUP_ALL;
8412
8413 p = skiptowhite(arg);
8414 if (p > arg)
8415 {
8416 group_name = vim_strnsave(arg, (int)(p - arg));
8417 if (group_name == NULL) /* out of memory */
8418 return AUGROUP_ERROR;
8419 group = au_find_group(group_name);
8420 if (group == AUGROUP_ERROR)
8421 group = AUGROUP_ALL; /* no match, use all groups */
8422 else
8423 *argp = skipwhite(p); /* match, skip over group name */
8424 vim_free(group_name);
8425 }
8426 return group;
8427}
8428
8429/*
8430 * do_autocmd() for one event.
8431 * If *pat == NUL do for all patterns.
8432 * If *cmd == NUL show entries.
8433 * If forceit == TRUE delete entries.
8434 * If group is not AUGROUP_ALL, only use this group.
8435 */
8436 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008437do_autocmd_event(
8438 event_T event,
8439 char_u *pat,
8440 int nested,
8441 char_u *cmd,
8442 int forceit,
8443 int group)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008444{
8445 AutoPat *ap;
8446 AutoPat **prev_ap;
8447 AutoCmd *ac;
8448 AutoCmd **prev_ac;
8449 int brace_level;
8450 char_u *endpat;
8451 int findgroup;
8452 int allgroups;
8453 int patlen;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00008454 int is_buflocal;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008455 int buflocal_nr;
8456 char_u buflocal_pat[25]; /* for "<buffer=X>" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008457
8458 if (group == AUGROUP_ALL)
8459 findgroup = current_augroup;
8460 else
8461 findgroup = group;
8462 allgroups = (group == AUGROUP_ALL && !forceit && *cmd == NUL);
8463
8464 /*
8465 * Show or delete all patterns for an event.
8466 */
8467 if (*pat == NUL)
8468 {
8469 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8470 {
8471 if (forceit) /* delete the AutoPat, if it's in the current group */
8472 {
8473 if (ap->group == findgroup)
8474 au_remove_pat(ap);
8475 }
8476 else if (group == AUGROUP_ALL || ap->group == group)
8477 show_autocmd(ap, event);
8478 }
8479 }
8480
8481 /*
8482 * Loop through all the specified patterns.
8483 */
8484 for ( ; *pat; pat = (*endpat == ',' ? endpat + 1 : endpat))
8485 {
8486 /*
8487 * Find end of the pattern.
8488 * Watch out for a comma in braces, like "*.\{obj,o\}".
8489 */
8490 brace_level = 0;
8491 for (endpat = pat; *endpat && (*endpat != ',' || brace_level
Bram Moolenaar6b9be1b2015-07-28 13:33:45 +02008492 || (endpat > pat && endpat[-1] == '\\')); ++endpat)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008493 {
8494 if (*endpat == '{')
8495 brace_level++;
8496 else if (*endpat == '}')
8497 brace_level--;
8498 }
8499 if (pat == endpat) /* ignore single comma */
8500 continue;
8501 patlen = (int)(endpat - pat);
8502
8503 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008504 * detect special <buflocal[=X]> buffer-local patterns
8505 */
8506 is_buflocal = FALSE;
8507 buflocal_nr = 0;
8508
Bram Moolenaar1e997822015-02-17 16:04:57 +01008509 if (patlen >= 8 && STRNCMP(pat, "<buffer", 7) == 0
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008510 && pat[patlen - 1] == '>')
8511 {
Bram Moolenaar1e997822015-02-17 16:04:57 +01008512 /* "<buffer...>": Error will be printed only for addition.
8513 * printing and removing will proceed silently. */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008514 is_buflocal = TRUE;
8515 if (patlen == 8)
Bram Moolenaar1e997822015-02-17 16:04:57 +01008516 /* "<buffer>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008517 buflocal_nr = curbuf->b_fnum;
8518 else if (patlen > 9 && pat[7] == '=')
8519 {
Bram Moolenaar1e997822015-02-17 16:04:57 +01008520 if (patlen == 13 && STRNICMP(pat, "<buffer=abuf>", 13) == 0)
8521 /* "<buffer=abuf>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008522 buflocal_nr = autocmd_bufnr;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008523 else if (skipdigits(pat + 8) == pat + patlen - 1)
Bram Moolenaar1e997822015-02-17 16:04:57 +01008524 /* "<buffer=123>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008525 buflocal_nr = atoi((char *)pat + 8);
8526 }
8527 }
8528
8529 if (is_buflocal)
8530 {
8531 /* normalize pat into standard "<buffer>#N" form */
8532 sprintf((char *)buflocal_pat, "<buffer=%d>", buflocal_nr);
8533 pat = buflocal_pat; /* can modify pat and patlen */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008534 patlen = (int)STRLEN(buflocal_pat); /* but not endpat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008535 }
8536
8537 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008538 * Find AutoPat entries with this pattern.
8539 */
8540 prev_ap = &first_autopat[(int)event];
8541 while ((ap = *prev_ap) != NULL)
8542 {
8543 if (ap->pat != NULL)
8544 {
8545 /* Accept a pattern when:
8546 * - a group was specified and it's that group, or a group was
8547 * not specified and it's the current group, or a group was
8548 * not specified and we are listing
8549 * - the length of the pattern matches
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008550 * - the pattern matches.
8551 * For <buffer[=X]>, this condition works because we normalize
8552 * all buffer-local patterns.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008553 */
8554 if ((allgroups || ap->group == findgroup)
8555 && ap->patlen == patlen
8556 && STRNCMP(pat, ap->pat, patlen) == 0)
8557 {
8558 /*
8559 * Remove existing autocommands.
8560 * If adding any new autocmd's for this AutoPat, don't
8561 * delete the pattern from the autopat list, append to
8562 * this list.
8563 */
8564 if (forceit)
8565 {
8566 if (*cmd != NUL && ap->next == NULL)
8567 {
8568 au_remove_cmds(ap);
8569 break;
8570 }
8571 au_remove_pat(ap);
8572 }
8573
8574 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008575 * Show autocmd's for this autopat, or buflocals <buffer=X>
Bram Moolenaar071d4272004-06-13 20:20:40 +00008576 */
8577 else if (*cmd == NUL)
8578 show_autocmd(ap, event);
8579
8580 /*
8581 * Add autocmd to this autopat, if it's the last one.
8582 */
8583 else if (ap->next == NULL)
8584 break;
8585 }
8586 }
8587 prev_ap = &ap->next;
8588 }
8589
8590 /*
8591 * Add a new command.
8592 */
8593 if (*cmd != NUL)
8594 {
8595 /*
8596 * If the pattern we want to add a command to does appear at the
8597 * end of the list (or not is not in the list at all), add the
8598 * pattern at the end of the list.
8599 */
8600 if (ap == NULL)
8601 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008602 /* refuse to add buffer-local ap if buffer number is invalid */
8603 if (is_buflocal && (buflocal_nr == 0
8604 || buflist_findnr(buflocal_nr) == NULL))
8605 {
8606 EMSGN(_("E680: <buffer=%d>: invalid buffer number "),
8607 buflocal_nr);
8608 return FAIL;
8609 }
8610
Bram Moolenaar071d4272004-06-13 20:20:40 +00008611 ap = (AutoPat *)alloc((unsigned)sizeof(AutoPat));
8612 if (ap == NULL)
8613 return FAIL;
8614 ap->pat = vim_strnsave(pat, patlen);
8615 ap->patlen = patlen;
8616 if (ap->pat == NULL)
8617 {
8618 vim_free(ap);
8619 return FAIL;
8620 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008621
8622 if (is_buflocal)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008623 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008624 ap->buflocal_nr = buflocal_nr;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008625 ap->reg_prog = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008626 }
8627 else
8628 {
Bram Moolenaar748bf032005-02-02 23:04:36 +00008629 char_u *reg_pat;
8630
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008631 ap->buflocal_nr = 0;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008632 reg_pat = file_pat_to_reg_pat(pat, endpat,
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008633 &ap->allow_dirs, TRUE);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008634 if (reg_pat != NULL)
8635 ap->reg_prog = vim_regcomp(reg_pat, RE_MAGIC);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008636 vim_free(reg_pat);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008637 if (reg_pat == NULL || ap->reg_prog == NULL)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008638 {
8639 vim_free(ap->pat);
8640 vim_free(ap);
8641 return FAIL;
8642 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008643 }
8644 ap->cmds = NULL;
8645 *prev_ap = ap;
8646 ap->next = NULL;
8647 if (group == AUGROUP_ALL)
8648 ap->group = current_augroup;
8649 else
8650 ap->group = group;
8651 }
8652
8653 /*
8654 * Add the autocmd at the end of the AutoCmd list.
8655 */
8656 prev_ac = &(ap->cmds);
8657 while ((ac = *prev_ac) != NULL)
8658 prev_ac = &ac->next;
8659 ac = (AutoCmd *)alloc((unsigned)sizeof(AutoCmd));
8660 if (ac == NULL)
8661 return FAIL;
8662 ac->cmd = vim_strsave(cmd);
8663#ifdef FEAT_EVAL
8664 ac->scriptID = current_SID;
8665#endif
8666 if (ac->cmd == NULL)
8667 {
8668 vim_free(ac);
8669 return FAIL;
8670 }
8671 ac->next = NULL;
8672 *prev_ac = ac;
8673 ac->nested = nested;
8674 }
8675 }
8676
8677 au_cleanup(); /* may really delete removed patterns/commands now */
8678 return OK;
8679}
8680
8681/*
8682 * Implementation of ":doautocmd [group] event [fname]".
8683 * Return OK for success, FAIL for failure;
8684 */
8685 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008686do_doautocmd(
8687 char_u *arg,
8688 int do_msg) /* give message for no matching autocmds? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008689{
8690 char_u *fname;
8691 int nothing_done = TRUE;
8692 int group;
8693
8694 /*
8695 * Check for a legal group name. If not, use AUGROUP_ALL.
8696 */
8697 group = au_get_grouparg(&arg);
8698 if (arg == NULL) /* out of memory */
8699 return FAIL;
8700
8701 if (*arg == '*')
8702 {
8703 EMSG(_("E217: Can't execute autocommands for ALL events"));
8704 return FAIL;
8705 }
8706
8707 /*
8708 * Scan over the events.
8709 * If we find an illegal name, return here, don't do anything.
8710 */
8711 fname = find_end_event(arg, group != AUGROUP_ALL);
8712 if (fname == NULL)
8713 return FAIL;
8714
8715 fname = skipwhite(fname);
8716
8717 /*
8718 * Loop over the events.
8719 */
8720 while (*arg && !vim_iswhite(*arg))
8721 if (apply_autocmds_group(event_name2nr(arg, &arg),
8722 fname, NULL, TRUE, group, curbuf, NULL))
8723 nothing_done = FALSE;
8724
8725 if (nothing_done && do_msg)
8726 MSG(_("No matching autocommands"));
8727
8728#ifdef FEAT_EVAL
8729 return aborting() ? FAIL : OK;
8730#else
8731 return OK;
8732#endif
8733}
8734
8735/*
8736 * ":doautoall": execute autocommands for each loaded buffer.
8737 */
8738 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008739ex_doautoall(exarg_T *eap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008740{
8741 int retval;
8742 aco_save_T aco;
8743 buf_T *buf;
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008744 char_u *arg = eap->arg;
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008745 int call_do_modelines = check_nomodeline(&arg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008746
8747 /*
8748 * This is a bit tricky: For some commands curwin->w_buffer needs to be
8749 * equal to curbuf, but for some buffers there may not be a window.
8750 * So we change the buffer for the current window for a moment. This
8751 * gives problems when the autocommands make changes to the list of
8752 * buffers or windows...
8753 */
8754 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8755 {
Bram Moolenaar3a847972008-07-08 09:36:58 +00008756 if (buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008757 {
8758 /* find a window for this buffer and save some values */
8759 aucmd_prepbuf(&aco, buf);
8760
8761 /* execute the autocommands for this buffer */
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008762 retval = do_doautocmd(arg, FALSE);
Bram Moolenaareeefcc72007-05-01 21:21:21 +00008763
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008764 if (call_do_modelines)
8765 {
8766 /* Execute the modeline settings, but don't set window-local
8767 * options if we are using the current window for another
8768 * buffer. */
8769 do_modelines(curwin == aucmd_win ? OPT_NOWIN : 0);
8770 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008771
8772 /* restore the current window */
8773 aucmd_restbuf(&aco);
8774
8775 /* stop if there is some error or buffer was deleted */
8776 if (retval == FAIL || !buf_valid(buf))
8777 break;
8778 }
8779 }
8780
8781 check_cursor(); /* just in case lines got deleted */
8782}
8783
8784/*
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008785 * Check *argp for <nomodeline>. When it is present return FALSE, otherwise
8786 * return TRUE and advance *argp to after it.
8787 * Thus return TRUE when do_modelines() should be called.
8788 */
8789 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008790check_nomodeline(char_u **argp)
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008791{
8792 if (STRNCMP(*argp, "<nomodeline>", 12) == 0)
8793 {
8794 *argp = skipwhite(*argp + 12);
8795 return FALSE;
8796 }
8797 return TRUE;
8798}
8799
8800/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008801 * Prepare for executing autocommands for (hidden) buffer "buf".
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008802 * Search for a visible window containing the current buffer. If there isn't
8803 * one then use "aucmd_win".
Bram Moolenaar071d4272004-06-13 20:20:40 +00008804 * Set "curbuf" and "curwin" to match "buf".
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00008805 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008806 */
8807 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008808aucmd_prepbuf(
8809 aco_save_T *aco, /* structure to save values in */
8810 buf_T *buf) /* new curbuf */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008811{
8812 win_T *win;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008813#ifdef FEAT_WINDOWS
8814 int save_ea;
8815#endif
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008816#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008817 int save_acd;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008818#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008819
8820 /* Find a window that is for the new buffer */
8821 if (buf == curbuf) /* be quick when buf is curbuf */
8822 win = curwin;
8823 else
8824#ifdef FEAT_WINDOWS
8825 for (win = firstwin; win != NULL; win = win->w_next)
8826 if (win->w_buffer == buf)
8827 break;
8828#else
8829 win = NULL;
8830#endif
8831
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008832 /* Allocate "aucmd_win" when needed. If this fails (out of memory) fall
8833 * back to using the current window. */
8834 if (win == NULL && aucmd_win == NULL)
8835 {
8836 win_alloc_aucmd_win();
8837 if (aucmd_win == NULL)
8838 win = curwin;
8839 }
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008840 if (win == NULL && aucmd_win_used)
8841 /* Strange recursive autocommand, fall back to using the current
8842 * window. Expect a few side effects... */
8843 win = curwin;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008844
8845 aco->save_curwin = curwin;
8846 aco->save_curbuf = curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008847 if (win != NULL)
8848 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008849 /* There is a window for "buf" in the current tab page, make it the
8850 * curwin. This is preferred, it has the least side effects (esp. if
8851 * "buf" is curbuf). */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008852 aco->use_aucmd_win = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008853 curwin = win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008854 }
8855 else
8856 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008857 /* There is no window for "buf", use "aucmd_win". To minimize the side
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02008858 * effects, insert it in the current tab page.
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008859 * Anything related to a window (e.g., setting folds) may have
8860 * unexpected results. */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008861 aco->use_aucmd_win = TRUE;
8862 aucmd_win_used = TRUE;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008863 aucmd_win->w_buffer = buf;
Bram Moolenaarcdddaa42010-06-07 23:07:44 +02008864 aucmd_win->w_s = &buf->b_s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008865 ++buf->b_nwindows;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008866 win_init_empty(aucmd_win); /* set cursor and topline to safe values */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008867
8868 /* Make sure w_localdir and globaldir are NULL to avoid a chdir() in
8869 * win_enter_ext(). */
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008870 vim_free(aucmd_win->w_localdir);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008871 aucmd_win->w_localdir = NULL;
8872 aco->globaldir = globaldir;
8873 globaldir = NULL;
8874
Bram Moolenaar071d4272004-06-13 20:20:40 +00008875
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008876#ifdef FEAT_WINDOWS
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008877 /* Split the current window, put the aucmd_win in the upper half.
8878 * We don't want the BufEnter or WinEnter autocommands. */
8879 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008880 make_snapshot(SNAP_AUCMD_IDX);
8881 save_ea = p_ea;
8882 p_ea = FALSE;
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008883
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008884# ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008885 /* Prevent chdir() call in win_enter_ext(), through do_autochdir(). */
8886 save_acd = p_acd;
8887 p_acd = FALSE;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008888# endif
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008889
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008890 (void)win_split_ins(0, WSP_TOP, aucmd_win, 0);
8891 (void)win_comp_pos(); /* recompute window positions */
8892 p_ea = save_ea;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008893# ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008894 p_acd = save_acd;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008895# endif
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008896 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008897#endif
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008898 curwin = aucmd_win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008899 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008900 curbuf = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008901 aco->new_curwin = curwin;
8902 aco->new_curbuf = curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008903}
8904
8905/*
8906 * Cleanup after executing autocommands for a (hidden) buffer.
8907 * Restore the window as it was (if possible).
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00008908 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008909 */
8910 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008911aucmd_restbuf(
8912 aco_save_T *aco) /* structure holding saved values */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008913{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008914#ifdef FEAT_WINDOWS
8915 int dummy;
8916#endif
8917
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008918 if (aco->use_aucmd_win)
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008919 {
8920 --curbuf->b_nwindows;
8921#ifdef FEAT_WINDOWS
8922 /* Find "aucmd_win", it can't be closed, but it may be in another tab
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008923 * page. Do not trigger autocommands here. */
8924 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008925 if (curwin != aucmd_win)
8926 {
8927 tabpage_T *tp;
8928 win_T *wp;
8929
8930 FOR_ALL_TAB_WINDOWS(tp, wp)
8931 {
8932 if (wp == aucmd_win)
8933 {
8934 if (tp != curtab)
Bram Moolenaar49e649f2013-05-06 04:50:35 +02008935 goto_tabpage_tp(tp, TRUE, TRUE);
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008936 win_goto(aucmd_win);
Bram Moolenaar28f29082012-02-11 23:45:37 +01008937 goto win_found;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008938 }
8939 }
8940 }
Bram Moolenaar28f29082012-02-11 23:45:37 +01008941win_found:
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008942
8943 /* Remove the window and frame from the tree of frames. */
8944 (void)winframe_remove(curwin, &dummy, NULL);
8945 win_remove(curwin, NULL);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008946 aucmd_win_used = FALSE;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008947 last_status(FALSE); /* may need to remove last status line */
8948 restore_snapshot(SNAP_AUCMD_IDX, FALSE);
8949 (void)win_comp_pos(); /* recompute window positions */
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008950 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008951
8952 if (win_valid(aco->save_curwin))
8953 curwin = aco->save_curwin;
8954 else
8955 /* Hmm, original window disappeared. Just use the first one. */
8956 curwin = firstwin;
8957# ifdef FEAT_EVAL
Bram Moolenaar429fa852013-04-15 12:27:36 +02008958 vars_clear(&aucmd_win->w_vars->dv_hashtab); /* free all w: variables */
8959 hash_init(&aucmd_win->w_vars->dv_hashtab); /* re-use the hashtab */
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008960# endif
8961#else
8962 curwin = aco->save_curwin;
8963#endif
8964 curbuf = curwin->w_buffer;
8965
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008966 vim_free(globaldir);
8967 globaldir = aco->globaldir;
8968
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008969 /* the buffer contents may have changed */
8970 check_cursor();
8971 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
8972 {
8973 curwin->w_topline = curbuf->b_ml.ml_line_count;
8974#ifdef FEAT_DIFF
8975 curwin->w_topfill = 0;
8976#endif
8977 }
8978#if defined(FEAT_GUI)
8979 /* Hide the scrollbars from the aucmd_win and update. */
8980 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_LEFT], FALSE);
8981 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_RIGHT], FALSE);
8982 gui_may_update_scrollbars();
8983#endif
8984 }
8985 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00008986 {
8987 /* restore curwin */
8988#ifdef FEAT_WINDOWS
8989 if (win_valid(aco->save_curwin))
8990#endif
8991 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008992 /* Restore the buffer which was previously edited by curwin, if
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008993 * it was changed, we are still the same window and the buffer is
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008994 * valid. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008995 if (curwin == aco->new_curwin
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008996 && curbuf != aco->new_curbuf
8997 && buf_valid(aco->new_curbuf)
8998 && aco->new_curbuf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008999 {
Bram Moolenaar7da9c372012-04-30 17:04:52 +02009000# if defined(FEAT_SYN_HL) || defined(FEAT_SPELL)
9001 if (curwin->w_s == &curbuf->b_s)
9002 curwin->w_s = &aco->new_curbuf->b_s;
9003# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009004 --curbuf->b_nwindows;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009005 curbuf = aco->new_curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009006 curwin->w_buffer = curbuf;
9007 ++curbuf->b_nwindows;
9008 }
9009
9010 curwin = aco->save_curwin;
9011 curbuf = curwin->w_buffer;
Bram Moolenaar371932a2014-09-09 16:59:38 +02009012 /* In case the autocommand move the cursor to a position that that
9013 * not exist in curbuf. */
9014 check_cursor();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009015 }
9016 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009017}
9018
9019static int autocmd_nested = FALSE;
9020
9021/*
9022 * Execute autocommands for "event" and file name "fname".
9023 * Return TRUE if some commands were executed.
9024 */
9025 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009026apply_autocmds(
9027 event_T event,
9028 char_u *fname, /* NULL or empty means use actual file name */
9029 char_u *fname_io, /* fname to use for <afile> on cmdline */
9030 int force, /* when TRUE, ignore autocmd_busy */
9031 buf_T *buf) /* buffer for <abuf> */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009032{
9033 return apply_autocmds_group(event, fname, fname_io, force,
9034 AUGROUP_ALL, buf, NULL);
9035}
9036
9037/*
9038 * Like apply_autocmds(), but with extra "eap" argument. This takes care of
9039 * setting v:filearg.
9040 */
9041 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009042apply_autocmds_exarg(
9043 event_T event,
9044 char_u *fname,
9045 char_u *fname_io,
9046 int force,
9047 buf_T *buf,
9048 exarg_T *eap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009049{
9050 return apply_autocmds_group(event, fname, fname_io, force,
9051 AUGROUP_ALL, buf, eap);
9052}
9053
9054/*
9055 * Like apply_autocmds(), but handles the caller's retval. If the script
9056 * processing is being aborted or if retval is FAIL when inside a try
9057 * conditional, no autocommands are executed. If otherwise the autocommands
9058 * cause the script to be aborted, retval is set to FAIL.
9059 */
9060 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009061apply_autocmds_retval(
9062 event_T event,
9063 char_u *fname, /* NULL or empty means use actual file name */
9064 char_u *fname_io, /* fname to use for <afile> on cmdline */
9065 int force, /* when TRUE, ignore autocmd_busy */
9066 buf_T *buf, /* buffer for <abuf> */
9067 int *retval) /* pointer to caller's retval */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009068{
9069 int did_cmd;
9070
Bram Moolenaar1e015462005-09-25 22:16:38 +00009071#ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00009072 if (should_abort(*retval))
9073 return FALSE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00009074#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009075
9076 did_cmd = apply_autocmds_group(event, fname, fname_io, force,
9077 AUGROUP_ALL, buf, NULL);
Bram Moolenaar1e015462005-09-25 22:16:38 +00009078 if (did_cmd
9079#ifdef FEAT_EVAL
9080 && aborting()
9081#endif
9082 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00009083 *retval = FAIL;
9084 return did_cmd;
9085}
9086
Bram Moolenaard35f9712005-12-18 22:02:33 +00009087/*
9088 * Return TRUE when there is a CursorHold autocommand defined.
9089 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009090 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009091has_cursorhold(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009092{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009093 return (first_autopat[(int)(get_real_state() == NORMAL_BUSY
9094 ? EVENT_CURSORHOLD : EVENT_CURSORHOLDI)] != NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009095}
Bram Moolenaard35f9712005-12-18 22:02:33 +00009096
9097/*
9098 * Return TRUE if the CursorHold event can be triggered.
9099 */
9100 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009101trigger_cursorhold(void)
Bram Moolenaard35f9712005-12-18 22:02:33 +00009102{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009103 int state;
9104
Bram Moolenaar05334432011-07-20 18:29:39 +02009105 if (!did_cursorhold
9106 && has_cursorhold()
9107 && !Recording
9108 && typebuf.tb_len == 0
Bram Moolenaard29a9ee2006-09-14 09:07:34 +00009109#ifdef FEAT_INS_EXPAND
9110 && !ins_compl_active()
9111#endif
9112 )
Bram Moolenaar754b5602006-02-09 23:53:20 +00009113 {
9114 state = get_real_state();
9115 if (state == NORMAL_BUSY || (state & INSERT) != 0)
9116 return TRUE;
9117 }
9118 return FALSE;
Bram Moolenaard35f9712005-12-18 22:02:33 +00009119}
Bram Moolenaar754b5602006-02-09 23:53:20 +00009120
9121/*
9122 * Return TRUE when there is a CursorMoved autocommand defined.
9123 */
9124 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009125has_cursormoved(void)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009126{
9127 return (first_autopat[(int)EVENT_CURSORMOVED] != NULL);
9128}
9129
9130/*
9131 * Return TRUE when there is a CursorMovedI autocommand defined.
9132 */
9133 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009134has_cursormovedI(void)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009135{
9136 return (first_autopat[(int)EVENT_CURSORMOVEDI] != NULL);
9137}
Bram Moolenaar071d4272004-06-13 20:20:40 +00009138
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009139/*
Bram Moolenaar186628f2013-03-19 13:33:23 +01009140 * Return TRUE when there is a TextChanged autocommand defined.
9141 */
9142 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009143has_textchanged(void)
Bram Moolenaar186628f2013-03-19 13:33:23 +01009144{
9145 return (first_autopat[(int)EVENT_TEXTCHANGED] != NULL);
9146}
9147
9148/*
9149 * Return TRUE when there is a TextChangedI autocommand defined.
9150 */
9151 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009152has_textchangedI(void)
Bram Moolenaar186628f2013-03-19 13:33:23 +01009153{
9154 return (first_autopat[(int)EVENT_TEXTCHANGEDI] != NULL);
9155}
9156
9157/*
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009158 * Return TRUE when there is an InsertCharPre autocommand defined.
9159 */
9160 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009161has_insertcharpre(void)
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009162{
9163 return (first_autopat[(int)EVENT_INSERTCHARPRE] != NULL);
9164}
9165
Bram Moolenaard5005162014-08-22 23:05:54 +02009166/*
9167 * Return TRUE when there is an CmdUndefined autocommand defined.
9168 */
9169 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009170has_cmdundefined(void)
Bram Moolenaard5005162014-08-22 23:05:54 +02009171{
9172 return (first_autopat[(int)EVENT_CMDUNDEFINED] != NULL);
9173}
9174
9175/*
9176 * Return TRUE when there is an FuncUndefined autocommand defined.
9177 */
9178 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009179has_funcundefined(void)
Bram Moolenaard5005162014-08-22 23:05:54 +02009180{
9181 return (first_autopat[(int)EVENT_FUNCUNDEFINED] != NULL);
9182}
9183
Bram Moolenaar071d4272004-06-13 20:20:40 +00009184 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009185apply_autocmds_group(
9186 event_T event,
9187 char_u *fname, /* NULL or empty means use actual file name */
9188 char_u *fname_io, /* fname to use for <afile> on cmdline, NULL means
Bram Moolenaar071d4272004-06-13 20:20:40 +00009189 use fname */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009190 int force, /* when TRUE, ignore autocmd_busy */
9191 int group, /* group ID, or AUGROUP_ALL */
9192 buf_T *buf, /* buffer for <abuf> */
9193 exarg_T *eap) /* command arguments */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009194{
9195 char_u *sfname = NULL; /* short file name */
9196 char_u *tail;
9197 int save_changed;
9198 buf_T *old_curbuf;
9199 int retval = FALSE;
9200 char_u *save_sourcing_name;
9201 linenr_T save_sourcing_lnum;
9202 char_u *save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009203 int save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009204 int save_autocmd_bufnr;
9205 char_u *save_autocmd_match;
9206 int save_autocmd_busy;
9207 int save_autocmd_nested;
9208 static int nesting = 0;
9209 AutoPatCmd patcmd;
9210 AutoPat *ap;
9211#ifdef FEAT_EVAL
9212 scid_T save_current_SID;
9213 void *save_funccalp;
9214 char_u *save_cmdarg;
9215 long save_cmdbang;
9216#endif
9217 static int filechangeshell_busy = FALSE;
Bram Moolenaar05159a02005-02-26 23:04:13 +00009218#ifdef FEAT_PROFILE
9219 proftime_T wait_time;
9220#endif
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009221 int did_save_redobuff = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009222
9223 /*
9224 * Quickly return if there are no autocommands for this event or
9225 * autocommands are blocked.
9226 */
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009227 if (first_autopat[(int)event] == NULL || autocmd_blocked > 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009228 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009229
9230 /*
9231 * When autocommands are busy, new autocommands are only executed when
9232 * explicitly enabled with the "nested" flag.
9233 */
9234 if (autocmd_busy && !(force || autocmd_nested))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009235 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009236
9237#ifdef FEAT_EVAL
9238 /*
Bram Moolenaar7263a772007-05-10 17:35:54 +00009239 * Quickly return when immediately aborting on error, or when an interrupt
Bram Moolenaar071d4272004-06-13 20:20:40 +00009240 * occurred or an exception was thrown but not caught.
9241 */
9242 if (aborting())
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009243 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009244#endif
9245
9246 /*
9247 * FileChangedShell never nests, because it can create an endless loop.
9248 */
Bram Moolenaar56718732006-03-15 22:53:57 +00009249 if (filechangeshell_busy && (event == EVENT_FILECHANGEDSHELL
9250 || event == EVENT_FILECHANGEDSHELLPOST))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009251 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009252
9253 /*
9254 * Ignore events in 'eventignore'.
9255 */
9256 if (event_ignored(event))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009257 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009258
9259 /*
9260 * Allow nesting of autocommands, but restrict the depth, because it's
9261 * possible to create an endless loop.
9262 */
9263 if (nesting == 10)
9264 {
9265 EMSG(_("E218: autocommand nesting too deep"));
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009266 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009267 }
9268
9269 /*
9270 * Check if these autocommands are disabled. Used when doing ":all" or
9271 * ":ball".
9272 */
9273 if ( (autocmd_no_enter
9274 && (event == EVENT_WINENTER || event == EVENT_BUFENTER))
9275 || (autocmd_no_leave
9276 && (event == EVENT_WINLEAVE || event == EVENT_BUFLEAVE)))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009277 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009278
9279 /*
9280 * Save the autocmd_* variables and info about the current buffer.
9281 */
9282 save_autocmd_fname = autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009283 save_autocmd_fname_full = autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009284 save_autocmd_bufnr = autocmd_bufnr;
9285 save_autocmd_match = autocmd_match;
9286 save_autocmd_busy = autocmd_busy;
9287 save_autocmd_nested = autocmd_nested;
9288 save_changed = curbuf->b_changed;
9289 old_curbuf = curbuf;
9290
9291 /*
9292 * Set the file name to be used for <afile>.
Bram Moolenaara0174af2008-01-02 20:08:25 +00009293 * Make a copy to avoid that changing a buffer name or directory makes it
9294 * invalid.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009295 */
9296 if (fname_io == NULL)
9297 {
Bram Moolenaar53744302015-07-17 17:38:22 +02009298 if (event == EVENT_COLORSCHEME || event == EVENT_OPTIONSET)
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009299 autocmd_fname = NULL;
9300 else if (fname != NULL && *fname != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009301 autocmd_fname = fname;
9302 else if (buf != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009303 autocmd_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009304 else
9305 autocmd_fname = NULL;
9306 }
9307 else
9308 autocmd_fname = fname_io;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009309 if (autocmd_fname != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009310 autocmd_fname = vim_strsave(autocmd_fname);
9311 autocmd_fname_full = FALSE; /* call FullName_save() later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009312
9313 /*
9314 * Set the buffer number to be used for <abuf>.
9315 */
9316 if (buf == NULL)
9317 autocmd_bufnr = 0;
9318 else
9319 autocmd_bufnr = buf->b_fnum;
9320
9321 /*
9322 * When the file name is NULL or empty, use the file name of buffer "buf".
9323 * Always use the full path of the file name to match with, in case
9324 * "allow_dirs" is set.
9325 */
9326 if (fname == NULL || *fname == NUL)
9327 {
9328 if (buf == NULL)
9329 fname = NULL;
9330 else
9331 {
9332#ifdef FEAT_SYN_HL
9333 if (event == EVENT_SYNTAX)
9334 fname = buf->b_p_syn;
9335 else
9336#endif
9337 if (event == EVENT_FILETYPE)
9338 fname = buf->b_p_ft;
9339 else
9340 {
9341 if (buf->b_sfname != NULL)
9342 sfname = vim_strsave(buf->b_sfname);
9343 fname = buf->b_ffname;
9344 }
9345 }
9346 if (fname == NULL)
9347 fname = (char_u *)"";
9348 fname = vim_strsave(fname); /* make a copy, so we can change it */
9349 }
9350 else
9351 {
9352 sfname = vim_strsave(fname);
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009353 /* Don't try expanding FileType, Syntax, FuncUndefined, WindowID,
9354 * ColorScheme or QuickFixCmd* */
Bram Moolenaar7c626922005-02-07 22:01:03 +00009355 if (event == EVENT_FILETYPE
9356 || event == EVENT_SYNTAX
Bram Moolenaar5135d462009-04-29 16:03:38 +00009357 || event == EVENT_FUNCUNDEFINED
Bram Moolenaar7c626922005-02-07 22:01:03 +00009358 || event == EVENT_REMOTEREPLY
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00009359 || event == EVENT_SPELLFILEMISSING
Bram Moolenaar7c626922005-02-07 22:01:03 +00009360 || event == EVENT_QUICKFIXCMDPRE
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009361 || event == EVENT_COLORSCHEME
Bram Moolenaar53744302015-07-17 17:38:22 +02009362 || event == EVENT_OPTIONSET
Bram Moolenaar7c626922005-02-07 22:01:03 +00009363 || event == EVENT_QUICKFIXCMDPOST)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009364 fname = vim_strsave(fname);
9365 else
9366 fname = FullName_save(fname, FALSE);
9367 }
9368 if (fname == NULL) /* out of memory */
9369 {
9370 vim_free(sfname);
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009371 retval = FALSE;
9372 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009373 }
9374
9375#ifdef BACKSLASH_IN_FILENAME
9376 /*
9377 * Replace all backslashes with forward slashes. This makes the
9378 * autocommand patterns portable between Unix and MS-DOS.
9379 */
9380 if (sfname != NULL)
9381 forward_slash(sfname);
9382 forward_slash(fname);
9383#endif
9384
9385#ifdef VMS
9386 /* remove version for correct match */
9387 if (sfname != NULL)
9388 vms_remove_version(sfname);
9389 vms_remove_version(fname);
9390#endif
9391
9392 /*
9393 * Set the name to be used for <amatch>.
9394 */
9395 autocmd_match = fname;
9396
9397
9398 /* Don't redraw while doing auto commands. */
9399 ++RedrawingDisabled;
9400 save_sourcing_name = sourcing_name;
9401 sourcing_name = NULL; /* don't free this one */
9402 save_sourcing_lnum = sourcing_lnum;
9403 sourcing_lnum = 0; /* no line number here */
9404
9405#ifdef FEAT_EVAL
9406 save_current_SID = current_SID;
9407
Bram Moolenaar05159a02005-02-26 23:04:13 +00009408# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009409 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009410 prof_child_enter(&wait_time); /* doesn't count for the caller itself */
9411# endif
9412
Bram Moolenaar071d4272004-06-13 20:20:40 +00009413 /* Don't use local function variables, if called from a function */
9414 save_funccalp = save_funccal();
9415#endif
9416
9417 /*
9418 * When starting to execute autocommands, save the search patterns.
9419 */
9420 if (!autocmd_busy)
9421 {
9422 save_search_patterns();
Bram Moolenaar20ad69c2015-12-03 13:52:52 +01009423#ifdef FEAT_INS_EXPAND
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009424 if (!ins_compl_active())
Bram Moolenaar20ad69c2015-12-03 13:52:52 +01009425#endif
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009426 {
9427 saveRedobuff();
9428 did_save_redobuff = TRUE;
9429 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009430 did_filetype = keep_filetype;
9431 }
9432
9433 /*
9434 * Note that we are applying autocmds. Some commands need to know.
9435 */
9436 autocmd_busy = TRUE;
9437 filechangeshell_busy = (event == EVENT_FILECHANGEDSHELL);
9438 ++nesting; /* see matching decrement below */
9439
9440 /* Remember that FileType was triggered. Used for did_filetype(). */
9441 if (event == EVENT_FILETYPE)
9442 did_filetype = TRUE;
9443
9444 tail = gettail(fname);
9445
9446 /* Find first autocommand that matches */
9447 patcmd.curpat = first_autopat[(int)event];
9448 patcmd.nextcmd = NULL;
9449 patcmd.group = group;
9450 patcmd.fname = fname;
9451 patcmd.sfname = sfname;
9452 patcmd.tail = tail;
9453 patcmd.event = event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009454 patcmd.arg_bufnr = autocmd_bufnr;
9455 patcmd.next = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009456 auto_next_pat(&patcmd, FALSE);
9457
9458 /* found one, start executing the autocommands */
9459 if (patcmd.curpat != NULL)
9460 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009461 /* add to active_apc_list */
9462 patcmd.next = active_apc_list;
9463 active_apc_list = &patcmd;
9464
Bram Moolenaar071d4272004-06-13 20:20:40 +00009465#ifdef FEAT_EVAL
9466 /* set v:cmdarg (only when there is a matching pattern) */
9467 save_cmdbang = get_vim_var_nr(VV_CMDBANG);
9468 if (eap != NULL)
9469 {
9470 save_cmdarg = set_cmdarg(eap, NULL);
9471 set_vim_var_nr(VV_CMDBANG, (long)eap->forceit);
9472 }
9473 else
9474 save_cmdarg = NULL; /* avoid gcc warning */
9475#endif
9476 retval = TRUE;
9477 /* mark the last pattern, to avoid an endless loop when more patterns
9478 * are added when executing autocommands */
9479 for (ap = patcmd.curpat; ap->next != NULL; ap = ap->next)
9480 ap->last = FALSE;
9481 ap->last = TRUE;
9482 check_lnums(TRUE); /* make sure cursor and topline are valid */
9483 do_cmdline(NULL, getnextac, (void *)&patcmd,
9484 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
9485#ifdef FEAT_EVAL
9486 if (eap != NULL)
9487 {
9488 (void)set_cmdarg(NULL, save_cmdarg);
9489 set_vim_var_nr(VV_CMDBANG, save_cmdbang);
9490 }
9491#endif
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009492 /* delete from active_apc_list */
9493 if (active_apc_list == &patcmd) /* just in case */
9494 active_apc_list = patcmd.next;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009495 }
9496
9497 --RedrawingDisabled;
9498 autocmd_busy = save_autocmd_busy;
9499 filechangeshell_busy = FALSE;
9500 autocmd_nested = save_autocmd_nested;
9501 vim_free(sourcing_name);
9502 sourcing_name = save_sourcing_name;
9503 sourcing_lnum = save_sourcing_lnum;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009504 vim_free(autocmd_fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009505 autocmd_fname = save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009506 autocmd_fname_full = save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009507 autocmd_bufnr = save_autocmd_bufnr;
9508 autocmd_match = save_autocmd_match;
9509#ifdef FEAT_EVAL
9510 current_SID = save_current_SID;
9511 restore_funccal(save_funccalp);
Bram Moolenaar05159a02005-02-26 23:04:13 +00009512# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009513 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009514 prof_child_exit(&wait_time);
9515# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009516#endif
9517 vim_free(fname);
9518 vim_free(sfname);
9519 --nesting; /* see matching increment above */
9520
9521 /*
9522 * When stopping to execute autocommands, restore the search patterns and
Bram Moolenaar3be85852014-06-12 14:01:31 +02009523 * the redo buffer. Free any buffers in the au_pending_free_buf list and
9524 * free any windows in the au_pending_free_win list.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009525 */
9526 if (!autocmd_busy)
9527 {
9528 restore_search_patterns();
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009529 if (did_save_redobuff)
9530 restoreRedobuff();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009531 did_filetype = FALSE;
Bram Moolenaar4c7ab1b2014-04-06 20:45:43 +02009532 while (au_pending_free_buf != NULL)
9533 {
9534 buf_T *b = au_pending_free_buf->b_next;
9535 vim_free(au_pending_free_buf);
9536 au_pending_free_buf = b;
9537 }
Bram Moolenaar3be85852014-06-12 14:01:31 +02009538 while (au_pending_free_win != NULL)
9539 {
9540 win_T *w = au_pending_free_win->w_next;
9541 vim_free(au_pending_free_win);
9542 au_pending_free_win = w;
9543 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009544 }
9545
9546 /*
9547 * Some events don't set or reset the Changed flag.
9548 * Check if still in the same buffer!
9549 */
9550 if (curbuf == old_curbuf
9551 && (event == EVENT_BUFREADPOST
9552 || event == EVENT_BUFWRITEPOST
9553 || event == EVENT_FILEAPPENDPOST
9554 || event == EVENT_VIMLEAVE
9555 || event == EVENT_VIMLEAVEPRE))
9556 {
9557#ifdef FEAT_TITLE
9558 if (curbuf->b_changed != save_changed)
9559 need_maketitle = TRUE;
9560#endif
9561 curbuf->b_changed = save_changed;
9562 }
9563
9564 au_cleanup(); /* may really delete removed patterns/commands now */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009565
9566BYPASS_AU:
9567 /* When wiping out a buffer make sure all its buffer-local autocommands
9568 * are deleted. */
9569 if (event == EVENT_BUFWIPEOUT && buf != NULL)
9570 aubuflocal_remove(buf);
9571
Bram Moolenaar071d4272004-06-13 20:20:40 +00009572 return retval;
9573}
9574
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009575# ifdef FEAT_EVAL
9576static char_u *old_termresponse = NULL;
9577# endif
9578
9579/*
9580 * Block triggering autocommands until unblock_autocmd() is called.
9581 * Can be used recursively, so long as it's symmetric.
9582 */
9583 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009584block_autocmds(void)
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009585{
9586# ifdef FEAT_EVAL
9587 /* Remember the value of v:termresponse. */
9588 if (autocmd_blocked == 0)
9589 old_termresponse = get_vim_var_str(VV_TERMRESPONSE);
9590# endif
9591 ++autocmd_blocked;
9592}
9593
9594 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009595unblock_autocmds(void)
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009596{
9597 --autocmd_blocked;
9598
9599# ifdef FEAT_EVAL
9600 /* When v:termresponse was set while autocommands were blocked, trigger
9601 * the autocommands now. Esp. useful when executing a shell command
9602 * during startup (vimdiff). */
9603 if (autocmd_blocked == 0
9604 && get_vim_var_str(VV_TERMRESPONSE) != old_termresponse)
9605 apply_autocmds(EVENT_TERMRESPONSE, NULL, NULL, FALSE, curbuf);
9606# endif
9607}
9608
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009609 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009610is_autocmd_blocked(void)
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009611{
9612 return autocmd_blocked != 0;
9613}
9614
Bram Moolenaar071d4272004-06-13 20:20:40 +00009615/*
9616 * Find next autocommand pattern that matches.
9617 */
9618 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009619auto_next_pat(
9620 AutoPatCmd *apc,
9621 int stop_at_last) /* stop when 'last' flag is set */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009622{
9623 AutoPat *ap;
9624 AutoCmd *cp;
9625 char_u *name;
9626 char *s;
9627
9628 vim_free(sourcing_name);
9629 sourcing_name = NULL;
9630
9631 for (ap = apc->curpat; ap != NULL && !got_int; ap = ap->next)
9632 {
9633 apc->curpat = NULL;
9634
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009635 /* Only use a pattern when it has not been removed, has commands and
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009636 * the group matches. For buffer-local autocommands only check the
9637 * buffer number. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009638 if (ap->pat != NULL && ap->cmds != NULL
9639 && (apc->group == AUGROUP_ALL || apc->group == ap->group))
9640 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009641 /* execution-condition */
9642 if (ap->buflocal_nr == 0
Bram Moolenaardffa5b82014-11-19 16:38:07 +01009643 ? (match_file_pat(NULL, &ap->reg_prog, apc->fname,
Bram Moolenaar748bf032005-02-02 23:04:36 +00009644 apc->sfname, apc->tail, ap->allow_dirs))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009645 : ap->buflocal_nr == apc->arg_bufnr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009646 {
9647 name = event_nr2name(apc->event);
9648 s = _("%s Auto commands for \"%s\"");
9649 sourcing_name = alloc((unsigned)(STRLEN(s)
9650 + STRLEN(name) + ap->patlen + 1));
9651 if (sourcing_name != NULL)
9652 {
9653 sprintf((char *)sourcing_name, s,
9654 (char *)name, (char *)ap->pat);
9655 if (p_verbose >= 8)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009656 {
9657 verbose_enter();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009658 smsg((char_u *)_("Executing %s"), sourcing_name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009659 verbose_leave();
9660 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009661 }
9662
9663 apc->curpat = ap;
9664 apc->nextcmd = ap->cmds;
9665 /* mark last command */
9666 for (cp = ap->cmds; cp->next != NULL; cp = cp->next)
9667 cp->last = FALSE;
9668 cp->last = TRUE;
9669 }
9670 line_breakcheck();
9671 if (apc->curpat != NULL) /* found a match */
9672 break;
9673 }
9674 if (stop_at_last && ap->last)
9675 break;
9676 }
9677}
9678
9679/*
9680 * Get next autocommand command.
9681 * Called by do_cmdline() to get the next line for ":if".
9682 * Returns allocated string, or NULL for end of autocommands.
9683 */
Bram Moolenaar21691f82012-12-05 19:13:18 +01009684 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009685getnextac(int c UNUSED, void *cookie, int indent UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009686{
9687 AutoPatCmd *acp = (AutoPatCmd *)cookie;
9688 char_u *retval;
9689 AutoCmd *ac;
9690
9691 /* Can be called again after returning the last line. */
9692 if (acp->curpat == NULL)
9693 return NULL;
9694
9695 /* repeat until we find an autocommand to execute */
9696 for (;;)
9697 {
9698 /* skip removed commands */
9699 while (acp->nextcmd != NULL && acp->nextcmd->cmd == NULL)
9700 if (acp->nextcmd->last)
9701 acp->nextcmd = NULL;
9702 else
9703 acp->nextcmd = acp->nextcmd->next;
9704
9705 if (acp->nextcmd != NULL)
9706 break;
9707
9708 /* at end of commands, find next pattern that matches */
9709 if (acp->curpat->last)
9710 acp->curpat = NULL;
9711 else
9712 acp->curpat = acp->curpat->next;
9713 if (acp->curpat != NULL)
9714 auto_next_pat(acp, TRUE);
9715 if (acp->curpat == NULL)
9716 return NULL;
9717 }
9718
9719 ac = acp->nextcmd;
9720
9721 if (p_verbose >= 9)
9722 {
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009723 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009724 smsg((char_u *)_("autocommand %s"), ac->cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009725 msg_puts((char_u *)"\n"); /* don't overwrite this either */
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009726 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009727 }
9728 retval = vim_strsave(ac->cmd);
9729 autocmd_nested = ac->nested;
9730#ifdef FEAT_EVAL
9731 current_SID = ac->scriptID;
9732#endif
9733 if (ac->last)
9734 acp->nextcmd = NULL;
9735 else
9736 acp->nextcmd = ac->next;
9737 return retval;
9738}
9739
9740/*
9741 * Return TRUE if there is a matching autocommand for "fname".
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009742 * To account for buffer-local autocommands, function needs to know
9743 * in which buffer the file will be opened.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009744 */
9745 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009746has_autocmd(event_T event, char_u *sfname, buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009747{
9748 AutoPat *ap;
9749 char_u *fname;
9750 char_u *tail = gettail(sfname);
9751 int retval = FALSE;
9752
9753 fname = FullName_save(sfname, FALSE);
9754 if (fname == NULL)
9755 return FALSE;
9756
9757#ifdef BACKSLASH_IN_FILENAME
9758 /*
9759 * Replace all backslashes with forward slashes. This makes the
9760 * autocommand patterns portable between Unix and MS-DOS.
9761 */
9762 sfname = vim_strsave(sfname);
9763 if (sfname != NULL)
9764 forward_slash(sfname);
9765 forward_slash(fname);
9766#endif
9767
9768 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
9769 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009770 && (ap->buflocal_nr == 0
Bram Moolenaardffa5b82014-11-19 16:38:07 +01009771 ? match_file_pat(NULL, &ap->reg_prog,
Bram Moolenaar748bf032005-02-02 23:04:36 +00009772 fname, sfname, tail, ap->allow_dirs)
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009773 : buf != NULL && ap->buflocal_nr == buf->b_fnum
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009774 ))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009775 {
9776 retval = TRUE;
9777 break;
9778 }
9779
9780 vim_free(fname);
9781#ifdef BACKSLASH_IN_FILENAME
9782 vim_free(sfname);
9783#endif
9784
9785 return retval;
9786}
9787
9788#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
9789/*
9790 * Function given to ExpandGeneric() to obtain the list of autocommand group
9791 * names.
9792 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009793 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009794get_augroup_name(expand_T *xp UNUSED, int idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009795{
9796 if (idx == augroups.ga_len) /* add "END" add the end */
9797 return (char_u *)"END";
9798 if (idx >= augroups.ga_len) /* end of list */
9799 return NULL;
9800 if (AUGROUP_NAME(idx) == NULL) /* skip deleted entries */
9801 return (char_u *)"";
9802 return AUGROUP_NAME(idx); /* return a name */
9803}
9804
9805static int include_groups = FALSE;
9806
9807 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009808set_context_in_autocmd(
9809 expand_T *xp,
9810 char_u *arg,
9811 int doautocmd) /* TRUE for :doauto*, FALSE for :autocmd */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009812{
9813 char_u *p;
9814 int group;
9815
9816 /* check for a group name, skip it if present */
9817 include_groups = FALSE;
9818 p = arg;
9819 group = au_get_grouparg(&arg);
9820 if (group == AUGROUP_ERROR)
9821 return NULL;
9822 /* If there only is a group name that's what we expand. */
9823 if (*arg == NUL && group != AUGROUP_ALL && !vim_iswhite(arg[-1]))
9824 {
9825 arg = p;
9826 group = AUGROUP_ALL;
9827 }
9828
9829 /* skip over event name */
9830 for (p = arg; *p != NUL && !vim_iswhite(*p); ++p)
9831 if (*p == ',')
9832 arg = p + 1;
9833 if (*p == NUL)
9834 {
9835 if (group == AUGROUP_ALL)
9836 include_groups = TRUE;
9837 xp->xp_context = EXPAND_EVENTS; /* expand event name */
9838 xp->xp_pattern = arg;
9839 return NULL;
9840 }
9841
9842 /* skip over pattern */
9843 arg = skipwhite(p);
9844 while (*arg && (!vim_iswhite(*arg) || arg[-1] == '\\'))
9845 arg++;
9846 if (*arg)
9847 return arg; /* expand (next) command */
9848
9849 if (doautocmd)
9850 xp->xp_context = EXPAND_FILES; /* expand file names */
9851 else
9852 xp->xp_context = EXPAND_NOTHING; /* pattern is not expanded */
9853 return NULL;
9854}
9855
9856/*
9857 * Function given to ExpandGeneric() to obtain the list of event names.
9858 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009859 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009860get_event_name(expand_T *xp UNUSED, int idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009861{
9862 if (idx < augroups.ga_len) /* First list group names, if wanted */
9863 {
9864 if (!include_groups || AUGROUP_NAME(idx) == NULL)
9865 return (char_u *)""; /* skip deleted entries */
9866 return AUGROUP_NAME(idx); /* return a name */
9867 }
9868 return (char_u *)event_names[idx - augroups.ga_len].name;
9869}
9870
9871#endif /* FEAT_CMDL_COMPL */
9872
9873/*
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009874 * Return TRUE if autocmd is supported.
9875 */
9876 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009877autocmd_supported(char_u *name)
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009878{
9879 char_u *p;
9880
9881 return (event_name2nr(name, &p) != NUM_EVENTS);
9882}
9883
9884/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00009885 * Return TRUE if an autocommand is defined for a group, event and
9886 * pattern: The group can be omitted to accept any group. "event" and "pattern"
9887 * can be NULL to accept any event and pattern. "pattern" can be NULL to accept
9888 * any pattern. Buffer-local patterns <buffer> or <buffer=N> are accepted.
9889 * Used for:
9890 * exists("#Group") or
9891 * exists("#Group#Event") or
9892 * exists("#Group#Event#pat") or
9893 * exists("#Event") or
9894 * exists("#Event#pat")
Bram Moolenaar071d4272004-06-13 20:20:40 +00009895 */
9896 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009897au_exists(char_u *arg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009898{
Bram Moolenaar195d6352005-12-19 22:08:24 +00009899 char_u *arg_save;
9900 char_u *pattern = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009901 char_u *event_name;
9902 char_u *p;
Bram Moolenaar754b5602006-02-09 23:53:20 +00009903 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009904 AutoPat *ap;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009905 buf_T *buflocal_buf = NULL;
Bram Moolenaar195d6352005-12-19 22:08:24 +00009906 int group;
9907 int retval = FALSE;
9908
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009909 /* Make a copy so that we can change the '#' chars to a NUL. */
Bram Moolenaar195d6352005-12-19 22:08:24 +00009910 arg_save = vim_strsave(arg);
9911 if (arg_save == NULL)
9912 return FALSE;
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009913 p = vim_strchr(arg_save, '#');
Bram Moolenaar195d6352005-12-19 22:08:24 +00009914 if (p != NULL)
9915 *p++ = NUL;
9916
9917 /* First, look for an autocmd group name */
9918 group = au_find_group(arg_save);
9919 if (group == AUGROUP_ERROR)
9920 {
9921 /* Didn't match a group name, assume the first argument is an event. */
9922 group = AUGROUP_ALL;
9923 event_name = arg_save;
9924 }
9925 else
9926 {
9927 if (p == NULL)
9928 {
9929 /* "Group": group name is present and it's recognized */
9930 retval = TRUE;
9931 goto theend;
9932 }
9933
9934 /* Must be "Group#Event" or "Group#Event#pat". */
9935 event_name = p;
9936 p = vim_strchr(event_name, '#');
9937 if (p != NULL)
9938 *p++ = NUL; /* "Group#Event#pat" */
9939 }
9940
9941 pattern = p; /* "pattern" is NULL when there is no pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009942
9943 /* find the index (enum) for the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009944 event = event_name2nr(event_name, &p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009945
9946 /* return FALSE if the event name is not recognized */
Bram Moolenaar195d6352005-12-19 22:08:24 +00009947 if (event == NUM_EVENTS)
9948 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009949
9950 /* Find the first autocommand for this event.
9951 * If there isn't any, return FALSE;
9952 * If there is one and no pattern given, return TRUE; */
9953 ap = first_autopat[(int)event];
9954 if (ap == NULL)
Bram Moolenaar195d6352005-12-19 22:08:24 +00009955 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009956
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009957 /* if pattern is "<buffer>", special handling is needed which uses curbuf */
9958 /* for pattern "<buffer=N>, fnamecmp() will work fine */
Bram Moolenaar5b7880d2009-09-11 15:24:31 +00009959 if (pattern != NULL && STRICMP(pattern, "<buffer>") == 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009960 buflocal_buf = curbuf;
9961
Bram Moolenaar071d4272004-06-13 20:20:40 +00009962 /* Check if there is an autocommand with the given pattern. */
9963 for ( ; ap != NULL; ap = ap->next)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009964 /* only use a pattern when it has not been removed and has commands. */
9965 /* For buffer-local autocommands, fnamecmp() works fine. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009966 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaar195d6352005-12-19 22:08:24 +00009967 && (group == AUGROUP_ALL || ap->group == group)
Bram Moolenaar5b7880d2009-09-11 15:24:31 +00009968 && (pattern == NULL
9969 || (buflocal_buf == NULL
9970 ? fnamecmp(ap->pat, pattern) == 0
9971 : ap->buflocal_nr == buflocal_buf->b_fnum)))
Bram Moolenaar195d6352005-12-19 22:08:24 +00009972 {
9973 retval = TRUE;
9974 break;
9975 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009976
Bram Moolenaar195d6352005-12-19 22:08:24 +00009977theend:
9978 vim_free(arg_save);
9979 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009980}
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009981
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009982#else /* FEAT_AUTOCMD */
9983
9984/*
9985 * Prepare for executing commands for (hidden) buffer "buf".
9986 * This is the non-autocommand version, it simply saves "curbuf" and sets
9987 * "curbuf" and "curwin" to match "buf".
9988 */
9989 void
Bram Moolenaard14e00e2016-01-31 17:30:51 +01009990aucmd_prepbuf(
9991 aco_save_T *aco, /* structure to save values in */
9992 buf_T *buf) /* new curbuf */
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009993{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009994 aco->save_curbuf = curbuf;
9995 --curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009996 curbuf = buf;
9997 curwin->w_buffer = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009998 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009999}
10000
10001/*
10002 * Restore after executing commands for a (hidden) buffer.
10003 * This is the non-autocommand version.
10004 */
10005 void
Bram Moolenaard14e00e2016-01-31 17:30:51 +010010006aucmd_restbuf(
10007 aco_save_T *aco) /* structure holding saved values */
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010008{
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010009 --curbuf->b_nwindows;
10010 curbuf = aco->save_curbuf;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010011 curwin->w_buffer = curbuf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010012 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010013}
10014
Bram Moolenaar071d4272004-06-13 20:20:40 +000010015#endif /* FEAT_AUTOCMD */
10016
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010017
Bram Moolenaar071d4272004-06-13 20:20:40 +000010018#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN) || defined(PROTO)
10019/*
Bram Moolenaar748bf032005-02-02 23:04:36 +000010020 * Try matching a filename with a "pattern" ("prog" is NULL), or use the
10021 * precompiled regprog "prog" ("pattern" is NULL). That avoids calling
10022 * vim_regcomp() often.
Bram Moolenaar071d4272004-06-13 20:20:40 +000010023 * Used for autocommands and 'wildignore'.
10024 * Returns TRUE if there is a match, FALSE otherwise.
10025 */
Bram Moolenaardffa5b82014-11-19 16:38:07 +010010026 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010027match_file_pat(
10028 char_u *pattern, /* pattern to match with */
10029 regprog_T **prog, /* pre-compiled regprog or NULL */
10030 char_u *fname, /* full path of file name */
10031 char_u *sfname, /* short file name or NULL */
10032 char_u *tail, /* tail of path */
10033 int allow_dirs) /* allow matching with dir */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010034{
10035 regmatch_T regmatch;
10036 int result = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010037
Bram Moolenaar71afbfe2013-03-19 16:49:16 +010010038 regmatch.rm_ic = p_fic; /* ignore case if 'fileignorecase' is set */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010039 if (prog != NULL)
10040 regmatch.regprog = *prog;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010041 else
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010042 regmatch.regprog = vim_regcomp(pattern, RE_MAGIC);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010043
10044 /*
10045 * Try for a match with the pattern with:
10046 * 1. the full file name, when the pattern has a '/'.
10047 * 2. the short file name, when the pattern has a '/'.
10048 * 3. the tail of the file name, when the pattern has no '/'.
10049 */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010050 if (regmatch.regprog != NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +000010051 && ((allow_dirs
10052 && (vim_regexec(&regmatch, fname, (colnr_T)0)
10053 || (sfname != NULL
10054 && vim_regexec(&regmatch, sfname, (colnr_T)0))))
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010055 || (!allow_dirs && vim_regexec(&regmatch, tail, (colnr_T)0))))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010056 result = TRUE;
10057
Bram Moolenaardffa5b82014-11-19 16:38:07 +010010058 if (prog != NULL)
10059 *prog = regmatch.regprog;
10060 else
Bram Moolenaar473de612013-06-08 18:19:48 +020010061 vim_regfree(regmatch.regprog);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010062 return result;
10063}
10064#endif
10065
10066#if defined(FEAT_WILDIGN) || defined(PROTO)
10067/*
10068 * Return TRUE if a file matches with a pattern in "list".
10069 * "list" is a comma-separated list of patterns, like 'wildignore'.
10070 * "sfname" is the short file name or NULL, "ffname" the long file name.
10071 */
10072 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010073match_file_list(char_u *list, char_u *sfname, char_u *ffname)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010074{
10075 char_u buf[100];
10076 char_u *tail;
10077 char_u *regpat;
10078 char allow_dirs;
10079 int match;
10080 char_u *p;
10081
10082 tail = gettail(sfname);
10083
10084 /* try all patterns in 'wildignore' */
10085 p = list;
10086 while (*p)
10087 {
10088 copy_option_part(&p, buf, 100, ",");
10089 regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, FALSE);
10090 if (regpat == NULL)
10091 break;
Bram Moolenaar748bf032005-02-02 23:04:36 +000010092 match = match_file_pat(regpat, NULL, ffname, sfname,
10093 tail, (int)allow_dirs);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010094 vim_free(regpat);
10095 if (match)
10096 return TRUE;
10097 }
10098 return FALSE;
10099}
10100#endif
10101
10102/*
10103 * Convert the given pattern "pat" which has shell style wildcards in it, into
10104 * a regular expression, and return the result in allocated memory. If there
10105 * is a directory path separator to be matched, then TRUE is put in
10106 * allow_dirs, otherwise FALSE is put there -- webb.
10107 * Handle backslashes before special characters, like "\*" and "\ ".
10108 *
Bram Moolenaar071d4272004-06-13 20:20:40 +000010109 * Returns NULL when out of memory.
10110 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010111 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010112file_pat_to_reg_pat(
10113 char_u *pat,
10114 char_u *pat_end, /* first char after pattern or NULL */
10115 char *allow_dirs, /* Result passed back out in here */
10116 int no_bslash UNUSED) /* Don't use a backward slash as pathsep */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010117{
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010118 int size = 2; /* '^' at start, '$' at end */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010119 char_u *endp;
10120 char_u *reg_pat;
10121 char_u *p;
10122 int i;
10123 int nested = 0;
10124 int add_dollar = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010125
10126 if (allow_dirs != NULL)
10127 *allow_dirs = FALSE;
10128 if (pat_end == NULL)
10129 pat_end = pat + STRLEN(pat);
10130
Bram Moolenaar071d4272004-06-13 20:20:40 +000010131 for (p = pat; p < pat_end; p++)
10132 {
10133 switch (*p)
10134 {
10135 case '*':
10136 case '.':
10137 case ',':
10138 case '{':
10139 case '}':
10140 case '~':
10141 size += 2; /* extra backslash */
10142 break;
10143#ifdef BACKSLASH_IN_FILENAME
10144 case '\\':
10145 case '/':
10146 size += 4; /* could become "[\/]" */
10147 break;
10148#endif
10149 default:
10150 size++;
Bram Moolenaar2288afe2015-08-11 16:20:05 +020010151# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010152 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010153 {
10154 ++p;
10155 ++size;
10156 }
10157# endif
10158 break;
10159 }
10160 }
10161 reg_pat = alloc(size + 1);
10162 if (reg_pat == NULL)
10163 return NULL;
10164
Bram Moolenaar071d4272004-06-13 20:20:40 +000010165 i = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010166
10167 if (pat[0] == '*')
10168 while (pat[0] == '*' && pat < pat_end - 1)
10169 pat++;
10170 else
10171 reg_pat[i++] = '^';
10172 endp = pat_end - 1;
Bram Moolenaar8fee8782015-08-11 18:45:48 +020010173 if (endp >= pat && *endp == '*')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010174 {
10175 while (endp - pat > 0 && *endp == '*')
10176 endp--;
10177 add_dollar = FALSE;
10178 }
10179 for (p = pat; *p && nested >= 0 && p <= endp; p++)
10180 {
10181 switch (*p)
10182 {
10183 case '*':
10184 reg_pat[i++] = '.';
10185 reg_pat[i++] = '*';
Bram Moolenaar02743632005-07-25 20:42:36 +000010186 while (p[1] == '*') /* "**" matches like "*" */
10187 ++p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010188 break;
10189 case '.':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010190 case '~':
10191 reg_pat[i++] = '\\';
10192 reg_pat[i++] = *p;
10193 break;
10194 case '?':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010195 reg_pat[i++] = '.';
10196 break;
10197 case '\\':
10198 if (p[1] == NUL)
10199 break;
10200#ifdef BACKSLASH_IN_FILENAME
10201 if (!no_bslash)
10202 {
10203 /* translate:
10204 * "\x" to "\\x" e.g., "dir\file"
10205 * "\*" to "\\.*" e.g., "dir\*.c"
10206 * "\?" to "\\." e.g., "dir\??.c"
10207 * "\+" to "\+" e.g., "fileX\+.c"
10208 */
10209 if ((vim_isfilec(p[1]) || p[1] == '*' || p[1] == '?')
10210 && p[1] != '+')
10211 {
10212 reg_pat[i++] = '[';
10213 reg_pat[i++] = '\\';
10214 reg_pat[i++] = '/';
10215 reg_pat[i++] = ']';
10216 if (allow_dirs != NULL)
10217 *allow_dirs = TRUE;
10218 break;
10219 }
10220 }
10221#endif
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010222 /* Undo escaping from ExpandEscape():
10223 * foo\?bar -> foo?bar
10224 * foo\%bar -> foo%bar
10225 * foo\,bar -> foo,bar
10226 * foo\ bar -> foo bar
10227 * Don't unescape \, * and others that are also special in a
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010228 * regexp.
10229 * An escaped { must be unescaped since we use magic not
Bram Moolenaara946afe2013-08-02 15:22:39 +020010230 * verymagic. Use "\\\{n,m\}"" to get "\{n,m}".
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010231 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010232 if (*++p == '?'
10233#ifdef BACKSLASH_IN_FILENAME
10234 && no_bslash
10235#endif
10236 )
10237 reg_pat[i++] = '?';
10238 else
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010239 if (*p == ',' || *p == '%' || *p == '#'
Bram Moolenaar2288afe2015-08-11 16:20:05 +020010240 || vim_isspace(*p) || *p == '{' || *p == '}')
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010241 reg_pat[i++] = *p;
Bram Moolenaara946afe2013-08-02 15:22:39 +020010242 else if (*p == '\\' && p[1] == '\\' && p[2] == '{')
10243 {
10244 reg_pat[i++] = '\\';
10245 reg_pat[i++] = '{';
10246 p += 2;
10247 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010248 else
10249 {
10250 if (allow_dirs != NULL && vim_ispathsep(*p)
10251#ifdef BACKSLASH_IN_FILENAME
10252 && (!no_bslash || *p != '\\')
10253#endif
10254 )
10255 *allow_dirs = TRUE;
10256 reg_pat[i++] = '\\';
10257 reg_pat[i++] = *p;
10258 }
10259 break;
10260#ifdef BACKSLASH_IN_FILENAME
10261 case '/':
10262 reg_pat[i++] = '[';
10263 reg_pat[i++] = '\\';
10264 reg_pat[i++] = '/';
10265 reg_pat[i++] = ']';
10266 if (allow_dirs != NULL)
10267 *allow_dirs = TRUE;
10268 break;
10269#endif
10270 case '{':
10271 reg_pat[i++] = '\\';
10272 reg_pat[i++] = '(';
10273 nested++;
10274 break;
10275 case '}':
10276 reg_pat[i++] = '\\';
10277 reg_pat[i++] = ')';
10278 --nested;
10279 break;
10280 case ',':
10281 if (nested)
10282 {
10283 reg_pat[i++] = '\\';
10284 reg_pat[i++] = '|';
10285 }
10286 else
10287 reg_pat[i++] = ',';
10288 break;
10289 default:
10290# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010291 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010292 reg_pat[i++] = *p++;
10293 else
10294# endif
10295 if (allow_dirs != NULL && vim_ispathsep(*p))
10296 *allow_dirs = TRUE;
10297 reg_pat[i++] = *p;
10298 break;
10299 }
10300 }
10301 if (add_dollar)
10302 reg_pat[i++] = '$';
10303 reg_pat[i] = NUL;
10304 if (nested != 0)
10305 {
10306 if (nested < 0)
10307 EMSG(_("E219: Missing {."));
10308 else
10309 EMSG(_("E220: Missing }."));
10310 vim_free(reg_pat);
10311 reg_pat = NULL;
10312 }
10313 return reg_pat;
10314}
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010315
10316#if defined(EINTR) || defined(PROTO)
10317/*
10318 * Version of read() that retries when interrupted by EINTR (possibly
10319 * by a SIGWINCH).
10320 */
10321 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010322read_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010323{
10324 long ret;
10325
10326 for (;;)
10327 {
10328 ret = vim_read(fd, buf, bufsize);
10329 if (ret >= 0 || errno != EINTR)
10330 break;
10331 }
10332 return ret;
10333}
10334
10335/*
10336 * Version of write() that retries when interrupted by EINTR (possibly
10337 * by a SIGWINCH).
10338 */
10339 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010340write_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010341{
10342 long ret = 0;
10343 long wlen;
10344
10345 /* Repeat the write() so long it didn't fail, other than being interrupted
10346 * by a signal. */
10347 while (ret < (long)bufsize)
10348 {
Bram Moolenaar9c263032010-12-17 18:06:06 +010010349 wlen = vim_write(fd, (char *)buf + ret, bufsize - ret);
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010350 if (wlen < 0)
10351 {
10352 if (errno != EINTR)
10353 break;
10354 }
10355 else
10356 ret += wlen;
10357 }
10358 return ret;
10359}
10360#endif