blob: 14a6f31baa48075e4dce25297e5c77c060f1208a [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 Moolenaar8767f522016-07-01 17:17:39 +020044static 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);
Bram Moolenaar8767f522016-07-01 17:17:39 +020052static int check_mtime(buf_T *buf, stat_T *s);
Bram Moolenaard25c16e2016-01-29 22:13:30 +010053static 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 Moolenaarc3691332016-04-20 12:49:49 +0200146#ifdef FEAT_AUTOCMD
147/*
148 * Set by the apply_autocmds_group function if the given event is equal to
149 * EVENT_FILETYPE. Used by the readfile function in order to determine if
150 * EVENT_BUFREADPOST triggered the EVENT_FILETYPE.
151 *
152 * Relying on this value requires one to reset it prior calling
153 * apply_autocmds_group.
154 */
155static int au_did_filetype INIT(= FALSE);
156#endif
157
Bram Moolenaar071d4272004-06-13 20:20:40 +0000158 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +0100159filemess(
160 buf_T *buf,
161 char_u *name,
162 char_u *s,
163 int attr)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000164{
165 int msg_scroll_save;
166
167 if (msg_silent != 0)
168 return;
169 msg_add_fname(buf, name); /* put file name in IObuff with quotes */
170 /* If it's extremely long, truncate it. */
171 if (STRLEN(IObuff) > IOSIZE - 80)
172 IObuff[IOSIZE - 80] = NUL;
173 STRCAT(IObuff, s);
174 /*
175 * For the first message may have to start a new line.
176 * For further ones overwrite the previous one, reset msg_scroll before
177 * calling filemess().
178 */
179 msg_scroll_save = msg_scroll;
180 if (shortmess(SHM_OVERALL) && !exiting && p_verbose == 0)
181 msg_scroll = FALSE;
182 if (!msg_scroll) /* wait a bit when overwriting an error msg */
183 check_for_delay(FALSE);
184 msg_start();
185 msg_scroll = msg_scroll_save;
186 msg_scrolled_ign = TRUE;
187 /* may truncate the message to avoid a hit-return prompt */
188 msg_outtrans_attr(msg_may_trunc(FALSE, IObuff), attr);
189 msg_clr_eos();
190 out_flush();
191 msg_scrolled_ign = FALSE;
192}
193
194/*
195 * Read lines from file "fname" into the buffer after line "from".
196 *
197 * 1. We allocate blocks with lalloc, as big as possible.
198 * 2. Each block is filled with characters from the file with a single read().
199 * 3. The lines are inserted in the buffer with ml_append().
200 *
201 * (caller must check that fname != NULL, unless READ_STDIN is used)
202 *
203 * "lines_to_skip" is the number of lines that must be skipped
204 * "lines_to_read" is the number of lines that are appended
205 * When not recovering lines_to_skip is 0 and lines_to_read MAXLNUM.
206 *
207 * flags:
208 * READ_NEW starting to edit a new buffer
209 * READ_FILTER reading filter output
210 * READ_STDIN read from stdin instead of a file
211 * READ_BUFFER read from curbuf instead of a file (converting after reading
212 * stdin)
213 * READ_DUMMY read into a dummy buffer (to check if file contents changed)
Bram Moolenaar59f931e2010-07-24 20:27:03 +0200214 * READ_KEEP_UNDO don't clear undo info or read it from a file
Bram Moolenaar071d4272004-06-13 20:20:40 +0000215 *
216 * return FAIL for failure, OK otherwise
217 */
218 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +0100219readfile(
220 char_u *fname,
221 char_u *sfname,
222 linenr_T from,
223 linenr_T lines_to_skip,
224 linenr_T lines_to_read,
225 exarg_T *eap, /* can be NULL! */
226 int flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000227{
228 int fd = 0;
229 int newfile = (flags & READ_NEW);
230 int check_readonly;
231 int filtering = (flags & READ_FILTER);
232 int read_stdin = (flags & READ_STDIN);
233 int read_buffer = (flags & READ_BUFFER);
Bram Moolenaar690ffc02008-01-04 15:31:21 +0000234 int set_options = newfile || read_buffer
235 || (eap != NULL && eap->read_edit);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000236 linenr_T read_buf_lnum = 1; /* next line to read from curbuf */
237 colnr_T read_buf_col = 0; /* next char to read from this line */
238 char_u c;
239 linenr_T lnum = from;
240 char_u *ptr = NULL; /* pointer into read buffer */
241 char_u *buffer = NULL; /* read buffer */
242 char_u *new_buffer = NULL; /* init to shut up gcc */
243 char_u *line_start = NULL; /* init to shut up gcc */
244 int wasempty; /* buffer was empty before reading */
245 colnr_T len;
246 long size = 0;
247 char_u *p;
Bram Moolenaar8767f522016-07-01 17:17:39 +0200248 off_T filesize = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000249 int skip_read = FALSE;
250#ifdef FEAT_CRYPT
251 char_u *cryptkey = NULL;
Bram Moolenaarf50a2532010-05-21 15:36:08 +0200252 int did_ask_for_key = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000253#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +0200254#ifdef FEAT_PERSISTENT_UNDO
255 context_sha256_T sha_ctx;
256 int read_undo_file = FALSE;
257#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000258 int split = 0; /* number of split lines */
259#define UNKNOWN 0x0fffffff /* file size is unknown */
260 linenr_T linecnt;
261 int error = FALSE; /* errors encountered */
262 int ff_error = EOL_UNKNOWN; /* file format with errors */
263 long linerest = 0; /* remaining chars in line */
264#ifdef UNIX
265 int perm = 0;
266 int swap_mode = -1; /* protection bits for swap file */
267#else
268 int perm;
269#endif
270 int fileformat = 0; /* end-of-line format */
271 int keep_fileformat = FALSE;
Bram Moolenaar8767f522016-07-01 17:17:39 +0200272 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000273 int file_readonly;
274 linenr_T skip_count = 0;
275 linenr_T read_count = 0;
276 int msg_save = msg_scroll;
277 linenr_T read_no_eol_lnum = 0; /* non-zero lnum when last line of
278 * last read was missing the eol */
279 int try_mac = (vim_strchr(p_ffs, 'm') != NULL);
280 int try_dos = (vim_strchr(p_ffs, 'd') != NULL);
281 int try_unix = (vim_strchr(p_ffs, 'x') != NULL);
282 int file_rewind = FALSE;
283#ifdef FEAT_MBYTE
284 int can_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000285 linenr_T conv_error = 0; /* line nr with conversion error */
286 linenr_T illegal_byte = 0; /* line nr with illegal byte */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000287 int keep_dest_enc = FALSE; /* don't retry when char doesn't fit
288 in destination encoding */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000289 int bad_char_behavior = BAD_REPLACE;
290 /* BAD_KEEP, BAD_DROP or character to
291 * replace with */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000292 char_u *tmpname = NULL; /* name of 'charconvert' output file */
293 int fio_flags = 0;
294 char_u *fenc; /* fileencoding to use */
295 int fenc_alloced; /* fenc_next is in allocated memory */
296 char_u *fenc_next = NULL; /* next item in 'fencs' or NULL */
297 int advance_fenc = FALSE;
298 long real_size = 0;
299# ifdef USE_ICONV
300 iconv_t iconv_fd = (iconv_t)-1; /* descriptor for iconv() or -1 */
301# ifdef FEAT_EVAL
302 int did_iconv = FALSE; /* TRUE when iconv() failed and trying
303 'charconvert' next */
304# endif
305# endif
306 int converted = FALSE; /* TRUE if conversion done */
307 int notconverted = FALSE; /* TRUE if conversion wanted but it
308 wasn't possible */
309 char_u conv_rest[CONV_RESTLEN];
310 int conv_restlen = 0; /* nr of bytes in conv_rest[] */
311#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000312#ifdef FEAT_AUTOCMD
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200313 buf_T *old_curbuf;
314 char_u *old_b_ffname;
315 char_u *old_b_fname;
316 int using_b_ffname;
317 int using_b_fname;
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000318#endif
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200319
Bram Moolenaarc3691332016-04-20 12:49:49 +0200320#ifdef FEAT_AUTOCMD
321 au_did_filetype = FALSE; /* reset before triggering any autocommands */
322#endif
323
Bram Moolenaarcab35ad2011-02-15 17:39:22 +0100324 curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000325
326 /*
327 * If there is no file name yet, use the one for the read file.
328 * BF_NOTEDITED is set to reflect this.
329 * Don't do this for a read from a filter.
330 * Only do this when 'cpoptions' contains the 'f' flag.
331 */
332 if (curbuf->b_ffname == NULL
333 && !filtering
334 && fname != NULL
335 && vim_strchr(p_cpo, CPO_FNAMER) != NULL
336 && !(flags & READ_DUMMY))
337 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000338 if (set_rw_fname(fname, sfname) == FAIL)
339 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000340 }
341
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200342#ifdef FEAT_AUTOCMD
343 /* Remember the initial values of curbuf, curbuf->b_ffname and
344 * curbuf->b_fname to detect whether they are altered as a result of
345 * executing nasty autocommands. Also check if "fname" and "sfname"
346 * point to one of these values. */
347 old_curbuf = curbuf;
348 old_b_ffname = curbuf->b_ffname;
349 old_b_fname = curbuf->b_fname;
350 using_b_ffname = (fname == curbuf->b_ffname)
351 || (sfname == curbuf->b_ffname);
352 using_b_fname = (fname == curbuf->b_fname) || (sfname == curbuf->b_fname);
353#endif
354
Bram Moolenaardf177f62005-02-22 08:39:57 +0000355 /* After reading a file the cursor line changes but we don't want to
356 * display the line. */
357 ex_no_reprint = TRUE;
358
Bram Moolenaar55b7cf82006-09-09 12:52:42 +0000359 /* don't display the file info for another buffer now */
360 need_fileinfo = FALSE;
361
Bram Moolenaar071d4272004-06-13 20:20:40 +0000362 /*
363 * For Unix: Use the short file name whenever possible.
364 * Avoids problems with networks and when directory names are changed.
365 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
366 * another directory, which we don't detect.
367 */
368 if (sfname == NULL)
369 sfname = fname;
370#if defined(UNIX) || defined(__EMX__)
371 fname = sfname;
372#endif
373
374#ifdef FEAT_AUTOCMD
375 /*
376 * The BufReadCmd and FileReadCmd events intercept the reading process by
377 * executing the associated commands instead.
378 */
379 if (!filtering && !read_stdin && !read_buffer)
380 {
381 pos_T pos;
382
383 pos = curbuf->b_op_start;
384
385 /* Set '[ mark to the line above where the lines go (line 1 if zero). */
386 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
387 curbuf->b_op_start.col = 0;
388
389 if (newfile)
390 {
391 if (apply_autocmds_exarg(EVENT_BUFREADCMD, NULL, sfname,
392 FALSE, curbuf, eap))
393#ifdef FEAT_EVAL
394 return aborting() ? FAIL : OK;
395#else
396 return OK;
397#endif
398 }
399 else if (apply_autocmds_exarg(EVENT_FILEREADCMD, sfname, sfname,
400 FALSE, NULL, eap))
401#ifdef FEAT_EVAL
402 return aborting() ? FAIL : OK;
403#else
404 return OK;
405#endif
406
407 curbuf->b_op_start = pos;
408 }
409#endif
410
411 if ((shortmess(SHM_OVER) || curbuf->b_help) && p_verbose == 0)
412 msg_scroll = FALSE; /* overwrite previous file message */
413 else
414 msg_scroll = TRUE; /* don't overwrite previous file message */
415
416 /*
417 * If the name ends in a path separator, we can't open it. Check here,
418 * because reading the file may actually work, but then creating the swap
419 * file may destroy it! Reported on MS-DOS and Win 95.
420 * If the name is too long we might crash further on, quit here.
421 */
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000422 if (fname != NULL && *fname != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000423 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000424 p = fname + STRLEN(fname);
425 if (after_pathsep(fname, p) || STRLEN(fname) >= MAXPATHL)
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000426 {
427 filemess(curbuf, fname, (char_u *)_("Illegal file name"), 0);
428 msg_end();
429 msg_scroll = msg_save;
430 return FAIL;
431 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000432 }
433
Bram Moolenaar071d4272004-06-13 20:20:40 +0000434 if (!read_stdin && !read_buffer)
435 {
Bram Moolenaar4e4f5292013-08-30 17:07:01 +0200436#ifdef UNIX
437 /*
438 * On Unix it is possible to read a directory, so we have to
439 * check for it before the mch_open().
440 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000441 perm = mch_getperm(fname);
442 if (perm >= 0 && !S_ISREG(perm) /* not a regular file ... */
443# ifdef S_ISFIFO
444 && !S_ISFIFO(perm) /* ... or fifo */
445# endif
446# ifdef S_ISSOCK
447 && !S_ISSOCK(perm) /* ... or socket */
448# endif
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +0000449# ifdef OPEN_CHR_FILES
450 && !(S_ISCHR(perm) && is_dev_fd_file(fname))
451 /* ... or a character special file named /dev/fd/<n> */
452# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000453 )
454 {
455 if (S_ISDIR(perm))
456 filemess(curbuf, fname, (char_u *)_("is a directory"), 0);
457 else
458 filemess(curbuf, fname, (char_u *)_("is not a file"), 0);
459 msg_end();
460 msg_scroll = msg_save;
461 return FAIL;
462 }
Bram Moolenaar4e4f5292013-08-30 17:07:01 +0200463#endif
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100464#if defined(MSWIN)
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000465 /*
466 * MS-Windows allows opening a device, but we will probably get stuck
467 * trying to read it.
468 */
469 if (!p_odev && mch_nodetype(fname) == NODE_WRITABLE)
470 {
Bram Moolenaar5386a122007-06-28 20:02:32 +0000471 filemess(curbuf, fname, (char_u *)_("is a device (disabled with 'opendevice' option)"), 0);
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000472 msg_end();
473 msg_scroll = msg_save;
474 return FAIL;
475 }
Bram Moolenaar043545e2006-10-10 16:44:07 +0000476#endif
Bram Moolenaar4e4f5292013-08-30 17:07:01 +0200477 }
Bram Moolenaar043545e2006-10-10 16:44:07 +0000478
Bram Moolenaarad875fb2013-07-24 15:02:03 +0200479 /* Set default or forced 'fileformat' and 'binary'. */
480 set_file_options(set_options, eap);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000481
482 /*
483 * When opening a new file we take the readonly flag from the file.
484 * Default is r/w, can be set to r/o below.
485 * Don't reset it when in readonly mode
486 * Only set/reset b_p_ro when BF_CHECK_RO is set.
487 */
488 check_readonly = (newfile && (curbuf->b_flags & BF_CHECK_RO));
Bram Moolenaar4399ef42005-02-12 14:29:27 +0000489 if (check_readonly && !readonlymode)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000490 curbuf->b_p_ro = FALSE;
491
492 if (newfile && !read_stdin && !read_buffer)
493 {
Bram Moolenaare60acc12011-05-10 16:41:25 +0200494 /* Remember time of file. */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000495 if (mch_stat((char *)fname, &st) >= 0)
496 {
497 buf_store_time(curbuf, &st, fname);
498 curbuf->b_mtime_read = curbuf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000499#ifdef UNIX
500 /*
501 * Use the protection bits of the original file for the swap file.
502 * This makes it possible for others to read the name of the
503 * edited file from the swapfile, but only if they can read the
504 * edited file.
505 * Remove the "write" and "execute" bits for group and others
506 * (they must not write the swapfile).
507 * Add the "read" and "write" bits for the user, otherwise we may
508 * not be able to write to the file ourselves.
509 * Setting the bits is done below, after creating the swap file.
510 */
511 swap_mode = (st.st_mode & 0644) | 0600;
512#endif
513#ifdef FEAT_CW_EDITOR
514 /* Get the FSSpec on MacOS
515 * TODO: Update it properly when the buffer name changes
516 */
517 (void)GetFSSpecFromPath(curbuf->b_ffname, &curbuf->b_FSSpec);
518#endif
519#ifdef VMS
520 curbuf->b_fab_rfm = st.st_fab_rfm;
Bram Moolenaard4755bb2004-09-02 19:12:26 +0000521 curbuf->b_fab_rat = st.st_fab_rat;
522 curbuf->b_fab_mrs = st.st_fab_mrs;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000523#endif
524 }
525 else
526 {
527 curbuf->b_mtime = 0;
528 curbuf->b_mtime_read = 0;
529 curbuf->b_orig_size = 0;
530 curbuf->b_orig_mode = 0;
531 }
532
533 /* Reset the "new file" flag. It will be set again below when the
534 * file doesn't exist. */
535 curbuf->b_flags &= ~(BF_NEW | BF_NEW_W);
536 }
537
538/*
539 * for UNIX: check readonly with perm and mch_access()
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100540 * for Amiga: check readonly by trying to open the file for writing
Bram Moolenaar071d4272004-06-13 20:20:40 +0000541 */
542 file_readonly = FALSE;
543 if (read_stdin)
544 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100545#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000546 /* Force binary I/O on stdin to avoid CR-LF -> LF conversion. */
547 setmode(0, O_BINARY);
548#endif
549 }
550 else if (!read_buffer)
551 {
552#ifdef USE_MCH_ACCESS
553 if (
554# ifdef UNIX
555 !(perm & 0222) ||
556# endif
557 mch_access((char *)fname, W_OK))
558 file_readonly = TRUE;
559 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
560#else
561 if (!newfile
562 || readonlymode
563 || (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0)
564 {
565 file_readonly = TRUE;
566 /* try to open ro */
567 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
568 }
569#endif
570 }
571
572 if (fd < 0) /* cannot open at all */
573 {
574#ifndef UNIX
575 int isdir_f;
576#endif
577 msg_scroll = msg_save;
578#ifndef UNIX
579 /*
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100580 * On Amiga we can't open a directory, check here.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000581 */
582 isdir_f = (mch_isdir(fname));
583 perm = mch_getperm(fname); /* check if the file exists */
584 if (isdir_f)
585 {
586 filemess(curbuf, sfname, (char_u *)_("is a directory"), 0);
587 curbuf->b_p_ro = TRUE; /* must use "w!" now */
588 }
589 else
590#endif
591 if (newfile)
592 {
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200593 if (perm < 0
594#ifdef ENOENT
595 && errno == ENOENT
596#endif
597 )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000598 {
599 /*
600 * Set the 'new-file' flag, so that when the file has
601 * been created by someone else, a ":w" will complain.
602 */
603 curbuf->b_flags |= BF_NEW;
604
605 /* Create a swap file now, so that other Vims are warned
606 * that we are editing this file. Don't do this for a
607 * "nofile" or "nowrite" buffer type. */
608#ifdef FEAT_QUICKFIX
609 if (!bt_dontwrite(curbuf))
610#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000611 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000612 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000613#ifdef FEAT_AUTOCMD
614 /* SwapExists autocommand may mess things up */
615 if (curbuf != old_curbuf
616 || (using_b_ffname
617 && (old_b_ffname != curbuf->b_ffname))
618 || (using_b_fname
619 && (old_b_fname != curbuf->b_fname)))
620 {
621 EMSG(_(e_auchangedbuf));
622 return FAIL;
623 }
624#endif
625 }
Bram Moolenaar5b962cf2005-12-12 21:58:40 +0000626 if (dir_of_file_exists(fname))
627 filemess(curbuf, sfname, (char_u *)_("[New File]"), 0);
628 else
629 filemess(curbuf, sfname,
630 (char_u *)_("[New DIRECTORY]"), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000631#ifdef FEAT_VIMINFO
632 /* Even though this is a new file, it might have been
633 * edited before and deleted. Get the old marks. */
634 check_marks_read();
635#endif
636#ifdef FEAT_MBYTE
Bram Moolenaarad875fb2013-07-24 15:02:03 +0200637 /* Set forced 'fileencoding'. */
638 if (eap != NULL)
639 set_forced_fenc(eap);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000640#endif
641#ifdef FEAT_AUTOCMD
642 apply_autocmds_exarg(EVENT_BUFNEWFILE, sfname, sfname,
643 FALSE, curbuf, eap);
644#endif
645 /* remember the current fileformat */
646 save_file_ff(curbuf);
647
648#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
649 if (aborting()) /* autocmds may abort script processing */
650 return FAIL;
651#endif
652 return OK; /* a new file is not an error */
653 }
654 else
655 {
Bram Moolenaar202795b2005-10-11 20:29:39 +0000656 filemess(curbuf, sfname, (char_u *)(
657# ifdef EFBIG
658 (errno == EFBIG) ? _("[File too big]") :
659# endif
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200660# ifdef EOVERFLOW
661 (errno == EOVERFLOW) ? _("[File too big]") :
662# endif
Bram Moolenaar202795b2005-10-11 20:29:39 +0000663 _("[Permission Denied]")), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000664 curbuf->b_p_ro = TRUE; /* must use "w!" now */
665 }
666 }
667
668 return FAIL;
669 }
670
671 /*
672 * Only set the 'ro' flag for readonly files the first time they are
673 * loaded. Help files always get readonly mode
674 */
675 if ((check_readonly && file_readonly) || curbuf->b_help)
676 curbuf->b_p_ro = TRUE;
677
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000678 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000679 {
Bram Moolenaar690ffc02008-01-04 15:31:21 +0000680 /* Don't change 'eol' if reading from buffer as it will already be
681 * correctly set when reading stdin. */
682 if (!read_buffer)
683 {
684 curbuf->b_p_eol = TRUE;
685 curbuf->b_start_eol = TRUE;
686 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000687#ifdef FEAT_MBYTE
688 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000689 curbuf->b_start_bomb = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000690#endif
691 }
692
693 /* Create a swap file now, so that other Vims are warned that we are
694 * editing this file.
695 * Don't do this for a "nofile" or "nowrite" buffer type. */
696#ifdef FEAT_QUICKFIX
697 if (!bt_dontwrite(curbuf))
698#endif
699 {
700 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000701#ifdef FEAT_AUTOCMD
702 if (!read_stdin && (curbuf != old_curbuf
703 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
704 || (using_b_fname && (old_b_fname != curbuf->b_fname))))
705 {
706 EMSG(_(e_auchangedbuf));
707 if (!read_buffer)
708 close(fd);
709 return FAIL;
710 }
711#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000712#ifdef UNIX
713 /* Set swap file protection bits after creating it. */
Bram Moolenaarf061e0b2009-06-24 15:32:01 +0000714 if (swap_mode > 0 && curbuf->b_ml.ml_mfp != NULL
715 && curbuf->b_ml.ml_mfp->mf_fname != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000716 (void)mch_setperm(curbuf->b_ml.ml_mfp->mf_fname, (long)swap_mode);
717#endif
718 }
719
Bram Moolenaarb815dac2005-12-07 20:59:24 +0000720#if defined(HAS_SWAP_EXISTS_ACTION)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000721 /* If "Quit" selected at ATTENTION dialog, don't load the file */
722 if (swap_exists_action == SEA_QUIT)
723 {
724 if (!read_buffer && !read_stdin)
725 close(fd);
726 return FAIL;
727 }
728#endif
729
730 ++no_wait_return; /* don't wait for return yet */
731
732 /*
733 * Set '[ mark to the line above where the lines go (line 1 if zero).
734 */
735 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
736 curbuf->b_op_start.col = 0;
737
738#ifdef FEAT_AUTOCMD
739 if (!read_buffer)
740 {
741 int m = msg_scroll;
742 int n = msg_scrolled;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000743
744 /*
745 * The file must be closed again, the autocommands may want to change
746 * the file before reading it.
747 */
748 if (!read_stdin)
749 close(fd); /* ignore errors */
750
751 /*
752 * The output from the autocommands should not overwrite anything and
753 * should not be overwritten: Set msg_scroll, restore its value if no
754 * output was done.
755 */
756 msg_scroll = TRUE;
757 if (filtering)
758 apply_autocmds_exarg(EVENT_FILTERREADPRE, NULL, sfname,
759 FALSE, curbuf, eap);
760 else if (read_stdin)
761 apply_autocmds_exarg(EVENT_STDINREADPRE, NULL, sfname,
762 FALSE, curbuf, eap);
763 else if (newfile)
764 apply_autocmds_exarg(EVENT_BUFREADPRE, NULL, sfname,
765 FALSE, curbuf, eap);
766 else
767 apply_autocmds_exarg(EVENT_FILEREADPRE, sfname, sfname,
768 FALSE, NULL, eap);
769 if (msg_scrolled == n)
770 msg_scroll = m;
771
772#ifdef FEAT_EVAL
773 if (aborting()) /* autocmds may abort script processing */
774 {
775 --no_wait_return;
776 msg_scroll = msg_save;
777 curbuf->b_p_ro = TRUE; /* must use "w!" now */
778 return FAIL;
779 }
780#endif
781 /*
782 * Don't allow the autocommands to change the current buffer.
783 * Try to re-open the file.
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000784 *
785 * Don't allow the autocommands to change the buffer name either
786 * (cd for example) if it invalidates fname or sfname.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000787 */
788 if (!read_stdin && (curbuf != old_curbuf
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000789 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
790 || (using_b_fname && (old_b_fname != curbuf->b_fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000791 || (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) < 0))
792 {
793 --no_wait_return;
794 msg_scroll = msg_save;
795 if (fd < 0)
796 EMSG(_("E200: *ReadPre autocommands made the file unreadable"));
797 else
798 EMSG(_("E201: *ReadPre autocommands must not change current buffer"));
799 curbuf->b_p_ro = TRUE; /* must use "w!" now */
800 return FAIL;
801 }
802 }
803#endif /* FEAT_AUTOCMD */
804
805 /* Autocommands may add lines to the file, need to check if it is empty */
806 wasempty = (curbuf->b_ml.ml_flags & ML_EMPTY);
807
808 if (!recoverymode && !filtering && !(flags & READ_DUMMY))
809 {
810 /*
811 * Show the user that we are busy reading the input. Sometimes this
812 * may take a while. When reading from stdin another program may
813 * still be running, don't move the cursor to the last line, unless
814 * always using the GUI.
815 */
816 if (read_stdin)
817 {
818#ifndef ALWAYS_USE_GUI
819 mch_msg(_("Vim: Reading from stdin...\n"));
820#endif
821#ifdef FEAT_GUI
822 /* Also write a message in the GUI window, if there is one. */
823 if (gui.in_use && !gui.dying && !gui.starting)
824 {
825 p = (char_u *)_("Reading from stdin...");
826 gui_write(p, (int)STRLEN(p));
827 }
828#endif
829 }
830 else if (!read_buffer)
831 filemess(curbuf, sfname, (char_u *)"", 0);
832 }
833
834 msg_scroll = FALSE; /* overwrite the file message */
835
836 /*
837 * Set linecnt now, before the "retry" caused by a wrong guess for
838 * fileformat, and after the autocommands, which may change them.
839 */
840 linecnt = curbuf->b_ml.ml_line_count;
841
842#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000843 /* "++bad=" argument. */
844 if (eap != NULL && eap->bad_char != 0)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000845 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000846 bad_char_behavior = eap->bad_char;
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000847 if (set_options)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000848 curbuf->b_bad_char = eap->bad_char;
849 }
850 else
851 curbuf->b_bad_char = 0;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000852
Bram Moolenaar071d4272004-06-13 20:20:40 +0000853 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000854 * Decide which 'encoding' to use or use first.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000855 */
856 if (eap != NULL && eap->force_enc != 0)
857 {
858 fenc = enc_canonize(eap->cmd + eap->force_enc);
859 fenc_alloced = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000860 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000861 }
862 else if (curbuf->b_p_bin)
863 {
864 fenc = (char_u *)""; /* binary: don't convert */
865 fenc_alloced = FALSE;
866 }
867 else if (curbuf->b_help)
868 {
869 char_u firstline[80];
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000870 int fc;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000871
872 /* Help files are either utf-8 or latin1. Try utf-8 first, if this
873 * fails it must be latin1.
874 * Always do this when 'encoding' is "utf-8". Otherwise only do
875 * this when needed to avoid [converted] remarks all the time.
876 * It is needed when the first line contains non-ASCII characters.
877 * That is only in *.??x files. */
878 fenc = (char_u *)"latin1";
879 c = enc_utf8;
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000880 if (!c && !read_stdin)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000881 {
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000882 fc = fname[STRLEN(fname) - 1];
883 if (TOLOWER_ASC(fc) == 'x')
884 {
885 /* Read the first line (and a bit more). Immediately rewind to
886 * the start of the file. If the read() fails "len" is -1. */
Bram Moolenaar540fc6f2010-12-17 16:27:16 +0100887 len = read_eintr(fd, firstline, 80);
Bram Moolenaar8767f522016-07-01 17:17:39 +0200888 vim_lseek(fd, (off_T)0L, SEEK_SET);
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000889 for (p = firstline; p < firstline + len; ++p)
890 if (*p >= 0x80)
891 {
892 c = TRUE;
893 break;
894 }
895 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000896 }
897
898 if (c)
899 {
900 fenc_next = fenc;
901 fenc = (char_u *)"utf-8";
902
903 /* When the file is utf-8 but a character doesn't fit in
904 * 'encoding' don't retry. In help text editing utf-8 bytes
905 * doesn't make sense. */
Bram Moolenaarf193fff2006-04-27 00:02:13 +0000906 if (!enc_utf8)
907 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000908 }
909 fenc_alloced = FALSE;
910 }
911 else if (*p_fencs == NUL)
912 {
913 fenc = curbuf->b_p_fenc; /* use format from buffer */
914 fenc_alloced = FALSE;
915 }
916 else
917 {
918 fenc_next = p_fencs; /* try items in 'fileencodings' */
919 fenc = next_fenc(&fenc_next);
920 fenc_alloced = TRUE;
921 }
922#endif
923
924 /*
925 * Jump back here to retry reading the file in different ways.
926 * Reasons to retry:
927 * - encoding conversion failed: try another one from "fenc_next"
928 * - BOM detected and fenc was set, need to setup conversion
929 * - "fileformat" check failed: try another
930 *
931 * Variables set for special retry actions:
932 * "file_rewind" Rewind the file to start reading it again.
933 * "advance_fenc" Advance "fenc" using "fenc_next".
934 * "skip_read" Re-use already read bytes (BOM detected).
935 * "did_iconv" iconv() conversion failed, try 'charconvert'.
936 * "keep_fileformat" Don't reset "fileformat".
937 *
938 * Other status indicators:
939 * "tmpname" When != NULL did conversion with 'charconvert'.
940 * Output file has to be deleted afterwards.
941 * "iconv_fd" When != -1 did conversion with iconv().
942 */
943retry:
944
945 if (file_rewind)
946 {
947 if (read_buffer)
948 {
949 read_buf_lnum = 1;
950 read_buf_col = 0;
951 }
Bram Moolenaar8767f522016-07-01 17:17:39 +0200952 else if (read_stdin || vim_lseek(fd, (off_T)0L, SEEK_SET) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000953 {
954 /* Can't rewind the file, give up. */
955 error = TRUE;
956 goto failed;
957 }
958 /* Delete the previously read lines. */
959 while (lnum > from)
960 ml_delete(lnum--, FALSE);
961 file_rewind = FALSE;
962#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000963 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000964 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000965 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000966 curbuf->b_start_bomb = FALSE;
967 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000968 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000969#endif
970 }
971
972 /*
973 * When retrying with another "fenc" and the first time "fileformat"
974 * will be reset.
975 */
976 if (keep_fileformat)
977 keep_fileformat = FALSE;
978 else
979 {
980 if (eap != NULL && eap->force_ff != 0)
Bram Moolenaar1c860362008-11-12 15:05:21 +0000981 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000982 fileformat = get_fileformat_force(curbuf, eap);
Bram Moolenaar1c860362008-11-12 15:05:21 +0000983 try_unix = try_dos = try_mac = FALSE;
984 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000985 else if (curbuf->b_p_bin)
986 fileformat = EOL_UNIX; /* binary: use Unix format */
987 else if (*p_ffs == NUL)
988 fileformat = get_fileformat(curbuf);/* use format from buffer */
989 else
990 fileformat = EOL_UNKNOWN; /* detect from file */
991 }
992
993#ifdef FEAT_MBYTE
994# ifdef USE_ICONV
995 if (iconv_fd != (iconv_t)-1)
996 {
997 /* aborted conversion with iconv(), close the descriptor */
998 iconv_close(iconv_fd);
999 iconv_fd = (iconv_t)-1;
1000 }
1001# endif
1002
1003 if (advance_fenc)
1004 {
1005 /*
1006 * Try the next entry in 'fileencodings'.
1007 */
1008 advance_fenc = FALSE;
1009
1010 if (eap != NULL && eap->force_enc != 0)
1011 {
1012 /* Conversion given with "++cc=" wasn't possible, read
1013 * without conversion. */
1014 notconverted = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001015 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001016 if (fenc_alloced)
1017 vim_free(fenc);
1018 fenc = (char_u *)"";
1019 fenc_alloced = FALSE;
1020 }
1021 else
1022 {
1023 if (fenc_alloced)
1024 vim_free(fenc);
1025 if (fenc_next != NULL)
1026 {
1027 fenc = next_fenc(&fenc_next);
1028 fenc_alloced = (fenc_next != NULL);
1029 }
1030 else
1031 {
1032 fenc = (char_u *)"";
1033 fenc_alloced = FALSE;
1034 }
1035 }
1036 if (tmpname != NULL)
1037 {
1038 mch_remove(tmpname); /* delete converted file */
1039 vim_free(tmpname);
1040 tmpname = NULL;
1041 }
1042 }
1043
1044 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001045 * Conversion may be required when the encoding of the file is different
1046 * from 'encoding' or 'encoding' is UTF-16, UCS-2 or UCS-4.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001047 */
1048 fio_flags = 0;
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001049 converted = need_conversion(fenc);
1050 if (converted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001051 {
1052
1053 /* "ucs-bom" means we need to check the first bytes of the file
1054 * for a BOM. */
1055 if (STRCMP(fenc, ENC_UCSBOM) == 0)
1056 fio_flags = FIO_UCSBOM;
1057
1058 /*
1059 * Check if UCS-2/4 or Latin1 to UTF-8 conversion needs to be
1060 * done. This is handled below after read(). Prepare the
1061 * fio_flags to avoid having to parse the string each time.
1062 * Also check for Unicode to Latin1 conversion, because iconv()
1063 * appears not to handle this correctly. This works just like
1064 * conversion to UTF-8 except how the resulting character is put in
1065 * the buffer.
1066 */
1067 else if (enc_utf8 || STRCMP(p_enc, "latin1") == 0)
1068 fio_flags = get_fio_flags(fenc);
1069
1070# ifdef WIN3264
1071 /*
1072 * Conversion from an MS-Windows codepage to UTF-8 or another codepage
1073 * is handled with MultiByteToWideChar().
1074 */
1075 if (fio_flags == 0)
1076 fio_flags = get_win_fio_flags(fenc);
1077# endif
1078
1079# ifdef MACOS_X
1080 /* Conversion from Apple MacRoman to latin1 or UTF-8 */
1081 if (fio_flags == 0)
1082 fio_flags = get_mac_fio_flags(fenc);
1083# endif
1084
1085# ifdef USE_ICONV
1086 /*
1087 * Try using iconv() if we can't convert internally.
1088 */
1089 if (fio_flags == 0
1090# ifdef FEAT_EVAL
1091 && !did_iconv
1092# endif
1093 )
1094 iconv_fd = (iconv_t)my_iconv_open(
1095 enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc);
1096# endif
1097
1098# ifdef FEAT_EVAL
1099 /*
1100 * Use the 'charconvert' expression when conversion is required
1101 * and we can't do it internally or with iconv().
1102 */
1103 if (fio_flags == 0 && !read_stdin && !read_buffer && *p_ccv != NUL
1104# ifdef USE_ICONV
1105 && iconv_fd == (iconv_t)-1
1106# endif
1107 )
1108 {
1109# ifdef USE_ICONV
1110 did_iconv = FALSE;
1111# endif
1112 /* Skip conversion when it's already done (retry for wrong
1113 * "fileformat"). */
1114 if (tmpname == NULL)
1115 {
1116 tmpname = readfile_charconvert(fname, fenc, &fd);
1117 if (tmpname == NULL)
1118 {
1119 /* Conversion failed. Try another one. */
1120 advance_fenc = TRUE;
1121 if (fd < 0)
1122 {
1123 /* Re-opening the original file failed! */
1124 EMSG(_("E202: Conversion made file unreadable!"));
1125 error = TRUE;
1126 goto failed;
1127 }
1128 goto retry;
1129 }
1130 }
1131 }
1132 else
1133# endif
1134 {
1135 if (fio_flags == 0
1136# ifdef USE_ICONV
1137 && iconv_fd == (iconv_t)-1
1138# endif
1139 )
1140 {
1141 /* Conversion wanted but we can't.
1142 * Try the next conversion in 'fileencodings' */
1143 advance_fenc = TRUE;
1144 goto retry;
1145 }
1146 }
1147 }
1148
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001149 /* Set "can_retry" when it's possible to rewind the file and try with
Bram Moolenaar071d4272004-06-13 20:20:40 +00001150 * another "fenc" value. It's FALSE when no other "fenc" to try, reading
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001151 * stdin or fixed at a specific encoding. */
1152 can_retry = (*fenc != NUL && !read_stdin && !keep_dest_enc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001153#endif
1154
1155 if (!skip_read)
1156 {
1157 linerest = 0;
1158 filesize = 0;
1159 skip_count = lines_to_skip;
1160 read_count = lines_to_read;
1161#ifdef FEAT_MBYTE
1162 conv_restlen = 0;
1163#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001164#ifdef FEAT_PERSISTENT_UNDO
Bram Moolenaar59f931e2010-07-24 20:27:03 +02001165 read_undo_file = (newfile && (flags & READ_KEEP_UNDO) == 0
1166 && curbuf->b_ffname != NULL
1167 && curbuf->b_p_udf
1168 && !filtering
1169 && !read_stdin
1170 && !read_buffer);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001171 if (read_undo_file)
1172 sha256_start(&sha_ctx);
1173#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001174#ifdef FEAT_CRYPT
1175 if (curbuf->b_cryptstate != NULL)
1176 {
1177 /* Need to free the state, but keep the key, don't want to ask for
1178 * it again. */
1179 crypt_free_state(curbuf->b_cryptstate);
1180 curbuf->b_cryptstate = NULL;
1181 }
1182#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001183 }
1184
1185 while (!error && !got_int)
1186 {
1187 /*
1188 * We allocate as much space for the file as we can get, plus
1189 * space for the old line plus room for one terminating NUL.
1190 * The amount is limited by the fact that read() only can read
1191 * upto max_unsigned characters (and other things).
1192 */
Bram Moolenaara2aa31a2014-02-23 22:52:40 +01001193#if VIM_SIZEOF_INT <= 2
Bram Moolenaar071d4272004-06-13 20:20:40 +00001194 if (linerest >= 0x7ff0)
1195 {
1196 ++split;
1197 *ptr = NL; /* split line by inserting a NL */
1198 size = 1;
1199 }
1200 else
1201#endif
1202 {
1203 if (!skip_read)
1204 {
Bram Moolenaara2aa31a2014-02-23 22:52:40 +01001205#if VIM_SIZEOF_INT > 2
Bram Moolenaar311d9822007-02-27 15:48:28 +00001206# if defined(SSIZE_MAX) && (SSIZE_MAX < 0x10000L)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001207 size = SSIZE_MAX; /* use max I/O size, 52K */
1208# else
1209 size = 0x10000L; /* use buffer >= 64K */
1210# endif
1211#else
1212 size = 0x7ff0L - linerest; /* limit buffer to 32K */
1213#endif
1214
Bram Moolenaarc1e37902006-04-18 21:55:01 +00001215 for ( ; size >= 10; size = (long)((long_u)size >> 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001216 {
1217 if ((new_buffer = lalloc((long_u)(size + linerest + 1),
1218 FALSE)) != NULL)
1219 break;
1220 }
1221 if (new_buffer == NULL)
1222 {
1223 do_outofmem_msg((long_u)(size * 2 + linerest + 1));
1224 error = TRUE;
1225 break;
1226 }
1227 if (linerest) /* copy characters from the previous buffer */
1228 mch_memmove(new_buffer, ptr - linerest, (size_t)linerest);
1229 vim_free(buffer);
1230 buffer = new_buffer;
1231 ptr = buffer + linerest;
1232 line_start = buffer;
1233
1234#ifdef FEAT_MBYTE
1235 /* May need room to translate into.
1236 * For iconv() we don't really know the required space, use a
1237 * factor ICONV_MULT.
1238 * latin1 to utf-8: 1 byte becomes up to 2 bytes
1239 * utf-16 to utf-8: 2 bytes become up to 3 bytes, 4 bytes
1240 * become up to 4 bytes, size must be multiple of 2
1241 * ucs-2 to utf-8: 2 bytes become up to 3 bytes, size must be
1242 * multiple of 2
1243 * ucs-4 to utf-8: 4 bytes become up to 6 bytes, size must be
1244 * multiple of 4 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001245 real_size = (int)size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001246# ifdef USE_ICONV
1247 if (iconv_fd != (iconv_t)-1)
1248 size = size / ICONV_MULT;
1249 else
1250# endif
1251 if (fio_flags & FIO_LATIN1)
1252 size = size / 2;
1253 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1254 size = (size * 2 / 3) & ~1;
1255 else if (fio_flags & FIO_UCS4)
1256 size = (size * 2 / 3) & ~3;
1257 else if (fio_flags == FIO_UCSBOM)
1258 size = size / ICONV_MULT; /* worst case */
1259# ifdef WIN3264
1260 else if (fio_flags & FIO_CODEPAGE)
1261 size = size / ICONV_MULT; /* also worst case */
1262# endif
1263# ifdef MACOS_X
1264 else if (fio_flags & FIO_MACROMAN)
1265 size = size / ICONV_MULT; /* also worst case */
1266# endif
1267#endif
1268
1269#ifdef FEAT_MBYTE
1270 if (conv_restlen > 0)
1271 {
1272 /* Insert unconverted bytes from previous line. */
1273 mch_memmove(ptr, conv_rest, conv_restlen);
1274 ptr += conv_restlen;
1275 size -= conv_restlen;
1276 }
1277#endif
1278
1279 if (read_buffer)
1280 {
1281 /*
1282 * Read bytes from curbuf. Used for converting text read
1283 * from stdin.
1284 */
1285 if (read_buf_lnum > from)
1286 size = 0;
1287 else
1288 {
1289 int n, ni;
1290 long tlen;
1291
1292 tlen = 0;
1293 for (;;)
1294 {
1295 p = ml_get(read_buf_lnum) + read_buf_col;
1296 n = (int)STRLEN(p);
1297 if ((int)tlen + n + 1 > size)
1298 {
1299 /* Filled up to "size", append partial line.
1300 * Change NL to NUL to reverse the effect done
1301 * below. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001302 n = (int)(size - tlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001303 for (ni = 0; ni < n; ++ni)
1304 {
1305 if (p[ni] == NL)
1306 ptr[tlen++] = NUL;
1307 else
1308 ptr[tlen++] = p[ni];
1309 }
1310 read_buf_col += n;
1311 break;
1312 }
1313 else
1314 {
1315 /* Append whole line and new-line. Change NL
1316 * to NUL to reverse the effect done below. */
1317 for (ni = 0; ni < n; ++ni)
1318 {
1319 if (p[ni] == NL)
1320 ptr[tlen++] = NUL;
1321 else
1322 ptr[tlen++] = p[ni];
1323 }
1324 ptr[tlen++] = NL;
1325 read_buf_col = 0;
1326 if (++read_buf_lnum > from)
1327 {
1328 /* When the last line didn't have an
1329 * end-of-line don't add it now either. */
1330 if (!curbuf->b_p_eol)
1331 --tlen;
1332 size = tlen;
1333 break;
1334 }
1335 }
1336 }
1337 }
1338 }
1339 else
1340 {
1341 /*
1342 * Read bytes from the file.
1343 */
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01001344 size = read_eintr(fd, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001345 }
1346
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001347#ifdef FEAT_CRYPT
1348 /*
1349 * At start of file: Check for magic number of encryption.
1350 */
1351 if (filesize == 0 && size > 0)
1352 cryptkey = check_for_cryptkey(cryptkey, ptr, &size,
1353 &filesize, newfile, sfname,
1354 &did_ask_for_key);
1355 /*
1356 * Decrypt the read bytes. This is done before checking for
1357 * EOF because the crypt layer may be buffering.
1358 */
1359 if (cryptkey != NULL && size > 0)
1360 {
1361 if (crypt_works_inplace(curbuf->b_cryptstate))
1362 {
1363 crypt_decode_inplace(curbuf->b_cryptstate, ptr, size);
1364 }
1365 else
1366 {
1367 char_u *newptr = NULL;
1368 int decrypted_size;
1369
1370 decrypted_size = crypt_decode_alloc(
1371 curbuf->b_cryptstate, ptr, size, &newptr);
1372
1373 /* If the crypt layer is buffering, not producing
1374 * anything yet, need to read more. */
1375 if (size > 0 && decrypted_size == 0)
1376 continue;
1377
1378 if (linerest == 0)
1379 {
1380 /* Simple case: reuse returned buffer (may be
1381 * NULL, checked later). */
1382 new_buffer = newptr;
1383 }
1384 else
1385 {
1386 long_u new_size;
1387
1388 /* Need new buffer to add bytes carried over. */
1389 new_size = (long_u)(decrypted_size + linerest + 1);
1390 new_buffer = lalloc(new_size, FALSE);
1391 if (new_buffer == NULL)
1392 {
1393 do_outofmem_msg(new_size);
1394 error = TRUE;
1395 break;
1396 }
1397
1398 mch_memmove(new_buffer, buffer, linerest);
1399 if (newptr != NULL)
1400 mch_memmove(new_buffer + linerest, newptr,
1401 decrypted_size);
1402 }
1403
1404 if (new_buffer != NULL)
1405 {
1406 vim_free(buffer);
1407 buffer = new_buffer;
1408 new_buffer = NULL;
1409 line_start = buffer;
1410 ptr = buffer + linerest;
1411 }
1412 size = decrypted_size;
1413 }
1414 }
1415#endif
1416
Bram Moolenaar071d4272004-06-13 20:20:40 +00001417 if (size <= 0)
1418 {
1419 if (size < 0) /* read error */
1420 error = TRUE;
1421#ifdef FEAT_MBYTE
1422 else if (conv_restlen > 0)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001423 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001424 /*
1425 * Reached end-of-file but some trailing bytes could
1426 * not be converted. Truncated file?
1427 */
1428
1429 /* When we did a conversion report an error. */
1430 if (fio_flags != 0
1431# ifdef USE_ICONV
1432 || iconv_fd != (iconv_t)-1
1433# endif
1434 )
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001435 {
Bram Moolenaare8d95302013-04-24 16:34:02 +02001436 if (can_retry)
1437 goto rewind_retry;
Bram Moolenaarf453d352008-06-04 17:37:34 +00001438 if (conv_error == 0)
1439 conv_error = curbuf->b_ml.ml_line_count
1440 - linecnt + 1;
1441 }
1442 /* Remember the first linenr with an illegal byte */
1443 else if (illegal_byte == 0)
1444 illegal_byte = curbuf->b_ml.ml_line_count
1445 - linecnt + 1;
1446 if (bad_char_behavior == BAD_DROP)
1447 {
1448 *(ptr - conv_restlen) = NUL;
1449 conv_restlen = 0;
1450 }
1451 else
1452 {
1453 /* Replace the trailing bytes with the replacement
1454 * character if we were converting; if we weren't,
1455 * leave the UTF8 checking code to do it, as it
1456 * works slightly differently. */
1457 if (bad_char_behavior != BAD_KEEP && (fio_flags != 0
1458# ifdef USE_ICONV
1459 || iconv_fd != (iconv_t)-1
1460# endif
1461 ))
1462 {
1463 while (conv_restlen > 0)
1464 {
1465 *(--ptr) = bad_char_behavior;
1466 --conv_restlen;
1467 }
1468 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001469 fio_flags = 0; /* don't convert this */
Bram Moolenaarb21e5842006-04-16 18:30:08 +00001470# ifdef USE_ICONV
1471 if (iconv_fd != (iconv_t)-1)
1472 {
1473 iconv_close(iconv_fd);
1474 iconv_fd = (iconv_t)-1;
1475 }
1476# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001477 }
1478 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001479#endif
1480 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001481 }
1482 skip_read = FALSE;
1483
1484#ifdef FEAT_MBYTE
1485 /*
1486 * At start of file (or after crypt magic number): Check for BOM.
1487 * Also check for a BOM for other Unicode encodings, but not after
1488 * converting with 'charconvert' or when a BOM has already been
1489 * found.
1490 */
1491 if ((filesize == 0
1492# ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001493 || (cryptkey != NULL
1494 && filesize == crypt_get_header_len(
1495 crypt_get_method_nr(curbuf)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001496# endif
1497 )
1498 && (fio_flags == FIO_UCSBOM
1499 || (!curbuf->b_p_bomb
1500 && tmpname == NULL
1501 && (*fenc == 'u' || (*fenc == NUL && enc_utf8)))))
1502 {
1503 char_u *ccname;
1504 int blen;
1505
1506 /* no BOM detection in a short file or in binary mode */
1507 if (size < 2 || curbuf->b_p_bin)
1508 ccname = NULL;
1509 else
1510 ccname = check_for_bom(ptr, size, &blen,
1511 fio_flags == FIO_UCSBOM ? FIO_ALL : get_fio_flags(fenc));
1512 if (ccname != NULL)
1513 {
1514 /* Remove BOM from the text */
1515 filesize += blen;
1516 size -= blen;
1517 mch_memmove(ptr, ptr + blen, (size_t)size);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00001518 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001519 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001520 curbuf->b_p_bomb = TRUE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001521 curbuf->b_start_bomb = TRUE;
1522 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001523 }
1524
1525 if (fio_flags == FIO_UCSBOM)
1526 {
1527 if (ccname == NULL)
1528 {
1529 /* No BOM detected: retry with next encoding. */
1530 advance_fenc = TRUE;
1531 }
1532 else
1533 {
1534 /* BOM detected: set "fenc" and jump back */
1535 if (fenc_alloced)
1536 vim_free(fenc);
1537 fenc = ccname;
1538 fenc_alloced = FALSE;
1539 }
1540 /* retry reading without getting new bytes or rewinding */
1541 skip_read = TRUE;
1542 goto retry;
1543 }
1544 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001545
1546 /* Include not converted bytes. */
1547 ptr -= conv_restlen;
1548 size += conv_restlen;
1549 conv_restlen = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001550#endif
1551 /*
1552 * Break here for a read error or end-of-file.
1553 */
1554 if (size <= 0)
1555 break;
1556
1557#ifdef FEAT_MBYTE
1558
Bram Moolenaar071d4272004-06-13 20:20:40 +00001559# ifdef USE_ICONV
1560 if (iconv_fd != (iconv_t)-1)
1561 {
1562 /*
1563 * Attempt conversion of the read bytes to 'encoding' using
1564 * iconv().
1565 */
1566 const char *fromp;
1567 char *top;
1568 size_t from_size;
1569 size_t to_size;
1570
1571 fromp = (char *)ptr;
1572 from_size = size;
1573 ptr += size;
1574 top = (char *)ptr;
1575 to_size = real_size - size;
1576
1577 /*
1578 * If there is conversion error or not enough room try using
Bram Moolenaar19a09a12005-03-04 23:39:37 +00001579 * another conversion. Except for when there is no
1580 * alternative (help files).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001581 */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001582 while ((iconv(iconv_fd, (void *)&fromp, &from_size,
1583 &top, &to_size)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001584 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
1585 || from_size > CONV_RESTLEN)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001586 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001587 if (can_retry)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001588 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001589 if (conv_error == 0)
1590 conv_error = readfile_linenr(linecnt,
1591 ptr, (char_u *)top);
Bram Moolenaar42eeac32005-06-29 22:40:58 +00001592
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001593 /* Deal with a bad byte and continue with the next. */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001594 ++fromp;
1595 --from_size;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001596 if (bad_char_behavior == BAD_KEEP)
1597 {
1598 *top++ = *(fromp - 1);
1599 --to_size;
1600 }
1601 else if (bad_char_behavior != BAD_DROP)
1602 {
1603 *top++ = bad_char_behavior;
1604 --to_size;
1605 }
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001606 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001607
1608 if (from_size > 0)
1609 {
1610 /* Some remaining characters, keep them for the next
1611 * round. */
1612 mch_memmove(conv_rest, (char_u *)fromp, from_size);
1613 conv_restlen = (int)from_size;
1614 }
1615
1616 /* move the linerest to before the converted characters */
1617 line_start = ptr - linerest;
1618 mch_memmove(line_start, buffer, (size_t)linerest);
1619 size = (long)((char_u *)top - ptr);
1620 }
1621# endif
1622
1623# ifdef WIN3264
1624 if (fio_flags & FIO_CODEPAGE)
1625 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001626 char_u *src, *dst;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001627 WCHAR ucs2buf[3];
1628 int ucs2len;
1629 int codepage = FIO_GET_CP(fio_flags);
1630 int bytelen;
1631 int found_bad;
1632 char replstr[2];
1633
Bram Moolenaar071d4272004-06-13 20:20:40 +00001634 /*
1635 * Conversion from an MS-Windows codepage or UTF-8 to UTF-8 or
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001636 * a codepage, using standard MS-Windows functions. This
1637 * requires two steps:
1638 * 1. convert from 'fileencoding' to ucs-2
1639 * 2. convert from ucs-2 to 'encoding'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001640 *
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001641 * Because there may be illegal bytes AND an incomplete byte
1642 * sequence at the end, we may have to do the conversion one
1643 * character at a time to get it right.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001644 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001645
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001646 /* Replacement string for WideCharToMultiByte(). */
1647 if (bad_char_behavior > 0)
1648 replstr[0] = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001649 else
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001650 replstr[0] = '?';
1651 replstr[1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001652
1653 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001654 * Move the bytes to the end of the buffer, so that we have
1655 * room to put the result at the start.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001656 */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001657 src = ptr + real_size - size;
1658 mch_memmove(src, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001659
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001660 /*
1661 * Do the conversion.
1662 */
1663 dst = ptr;
1664 size = size;
1665 while (size > 0)
1666 {
1667 found_bad = FALSE;
1668
1669# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
1670 if (codepage == CP_UTF8)
1671 {
1672 /* Handle CP_UTF8 input ourselves to be able to handle
1673 * trailing bytes properly.
1674 * Get one UTF-8 character from src. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001675 bytelen = (int)utf_ptr2len_len(src, size);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001676 if (bytelen > size)
1677 {
1678 /* Only got some bytes of a character. Normally
1679 * it's put in "conv_rest", but if it's too long
1680 * deal with it as if they were illegal bytes. */
1681 if (bytelen <= CONV_RESTLEN)
1682 break;
1683
1684 /* weird overlong byte sequence */
1685 bytelen = size;
1686 found_bad = TRUE;
1687 }
1688 else
1689 {
Bram Moolenaarc01140a2006-03-24 22:21:52 +00001690 int u8c = utf_ptr2char(src);
1691
Bram Moolenaar86e01082005-12-29 22:45:34 +00001692 if (u8c > 0xffff || (*src >= 0x80 && bytelen == 1))
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001693 found_bad = TRUE;
1694 ucs2buf[0] = u8c;
1695 ucs2len = 1;
1696 }
1697 }
1698 else
1699# endif
1700 {
1701 /* We don't know how long the byte sequence is, try
1702 * from one to three bytes. */
1703 for (bytelen = 1; bytelen <= size && bytelen <= 3;
1704 ++bytelen)
1705 {
1706 ucs2len = MultiByteToWideChar(codepage,
1707 MB_ERR_INVALID_CHARS,
1708 (LPCSTR)src, bytelen,
1709 ucs2buf, 3);
1710 if (ucs2len > 0)
1711 break;
1712 }
1713 if (ucs2len == 0)
1714 {
1715 /* If we have only one byte then it's probably an
1716 * incomplete byte sequence. Otherwise discard
1717 * one byte as a bad character. */
1718 if (size == 1)
1719 break;
1720 found_bad = TRUE;
1721 bytelen = 1;
1722 }
1723 }
1724
1725 if (!found_bad)
1726 {
1727 int i;
1728
1729 /* Convert "ucs2buf[ucs2len]" to 'enc' in "dst". */
1730 if (enc_utf8)
1731 {
1732 /* From UCS-2 to UTF-8. Cannot fail. */
1733 for (i = 0; i < ucs2len; ++i)
1734 dst += utf_char2bytes(ucs2buf[i], dst);
1735 }
1736 else
1737 {
1738 BOOL bad = FALSE;
1739 int dstlen;
1740
1741 /* From UCS-2 to "enc_codepage". If the
1742 * conversion uses the default character "?",
1743 * the data doesn't fit in this encoding. */
1744 dstlen = WideCharToMultiByte(enc_codepage, 0,
1745 (LPCWSTR)ucs2buf, ucs2len,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001746 (LPSTR)dst, (int)(src - dst),
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001747 replstr, &bad);
1748 if (bad)
1749 found_bad = TRUE;
1750 else
1751 dst += dstlen;
1752 }
1753 }
1754
1755 if (found_bad)
1756 {
1757 /* Deal with bytes we can't convert. */
1758 if (can_retry)
1759 goto rewind_retry;
1760 if (conv_error == 0)
1761 conv_error = readfile_linenr(linecnt, ptr, dst);
1762 if (bad_char_behavior != BAD_DROP)
1763 {
1764 if (bad_char_behavior == BAD_KEEP)
1765 {
1766 mch_memmove(dst, src, bytelen);
1767 dst += bytelen;
1768 }
1769 else
1770 *dst++ = bad_char_behavior;
1771 }
1772 }
1773
1774 src += bytelen;
1775 size -= bytelen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001776 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001777
1778 if (size > 0)
1779 {
1780 /* An incomplete byte sequence remaining. */
1781 mch_memmove(conv_rest, src, size);
1782 conv_restlen = size;
1783 }
1784
1785 /* The new size is equal to how much "dst" was advanced. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001786 size = (long)(dst - ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001787 }
1788 else
1789# endif
Bram Moolenaar56718732006-03-15 22:53:57 +00001790# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001791 if (fio_flags & FIO_MACROMAN)
1792 {
1793 /*
1794 * Conversion from Apple MacRoman char encoding to UTF-8 or
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001795 * latin1. This is in os_mac_conv.c.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001796 */
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001797 if (macroman2enc(ptr, &size, real_size) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001798 goto rewind_retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001799 }
1800 else
1801# endif
1802 if (fio_flags != 0)
1803 {
1804 int u8c;
1805 char_u *dest;
1806 char_u *tail = NULL;
1807
1808 /*
1809 * "enc_utf8" set: Convert Unicode or Latin1 to UTF-8.
1810 * "enc_utf8" not set: Convert Unicode to Latin1.
1811 * Go from end to start through the buffer, because the number
1812 * of bytes may increase.
1813 * "dest" points to after where the UTF-8 bytes go, "p" points
1814 * to after the next character to convert.
1815 */
1816 dest = ptr + real_size;
1817 if (fio_flags == FIO_LATIN1 || fio_flags == FIO_UTF8)
1818 {
1819 p = ptr + size;
1820 if (fio_flags == FIO_UTF8)
1821 {
1822 /* Check for a trailing incomplete UTF-8 sequence */
1823 tail = ptr + size - 1;
1824 while (tail > ptr && (*tail & 0xc0) == 0x80)
1825 --tail;
1826 if (tail + utf_byte2len(*tail) <= ptr + size)
1827 tail = NULL;
1828 else
1829 p = tail;
1830 }
1831 }
1832 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1833 {
1834 /* Check for a trailing byte */
1835 p = ptr + (size & ~1);
1836 if (size & 1)
1837 tail = p;
1838 if ((fio_flags & FIO_UTF16) && p > ptr)
1839 {
1840 /* Check for a trailing leading word */
1841 if (fio_flags & FIO_ENDIAN_L)
1842 {
1843 u8c = (*--p << 8);
1844 u8c += *--p;
1845 }
1846 else
1847 {
1848 u8c = *--p;
1849 u8c += (*--p << 8);
1850 }
1851 if (u8c >= 0xd800 && u8c <= 0xdbff)
1852 tail = p;
1853 else
1854 p += 2;
1855 }
1856 }
1857 else /* FIO_UCS4 */
1858 {
1859 /* Check for trailing 1, 2 or 3 bytes */
1860 p = ptr + (size & ~3);
1861 if (size & 3)
1862 tail = p;
1863 }
1864
1865 /* If there is a trailing incomplete sequence move it to
1866 * conv_rest[]. */
1867 if (tail != NULL)
1868 {
1869 conv_restlen = (int)((ptr + size) - tail);
1870 mch_memmove(conv_rest, (char_u *)tail, conv_restlen);
1871 size -= conv_restlen;
1872 }
1873
1874
1875 while (p > ptr)
1876 {
1877 if (fio_flags & FIO_LATIN1)
1878 u8c = *--p;
1879 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1880 {
1881 if (fio_flags & FIO_ENDIAN_L)
1882 {
1883 u8c = (*--p << 8);
1884 u8c += *--p;
1885 }
1886 else
1887 {
1888 u8c = *--p;
1889 u8c += (*--p << 8);
1890 }
1891 if ((fio_flags & FIO_UTF16)
1892 && u8c >= 0xdc00 && u8c <= 0xdfff)
1893 {
1894 int u16c;
1895
1896 if (p == ptr)
1897 {
1898 /* Missing leading word. */
1899 if (can_retry)
1900 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001901 if (conv_error == 0)
1902 conv_error = readfile_linenr(linecnt,
1903 ptr, p);
1904 if (bad_char_behavior == BAD_DROP)
1905 continue;
1906 if (bad_char_behavior != BAD_KEEP)
1907 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001908 }
1909
1910 /* found second word of double-word, get the first
1911 * word and compute the resulting character */
1912 if (fio_flags & FIO_ENDIAN_L)
1913 {
1914 u16c = (*--p << 8);
1915 u16c += *--p;
1916 }
1917 else
1918 {
1919 u16c = *--p;
1920 u16c += (*--p << 8);
1921 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001922 u8c = 0x10000 + ((u16c & 0x3ff) << 10)
1923 + (u8c & 0x3ff);
1924
Bram Moolenaar071d4272004-06-13 20:20:40 +00001925 /* Check if the word is indeed a leading word. */
1926 if (u16c < 0xd800 || u16c > 0xdbff)
1927 {
1928 if (can_retry)
1929 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001930 if (conv_error == 0)
1931 conv_error = readfile_linenr(linecnt,
1932 ptr, p);
1933 if (bad_char_behavior == BAD_DROP)
1934 continue;
1935 if (bad_char_behavior != BAD_KEEP)
1936 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001937 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001938 }
1939 }
1940 else if (fio_flags & FIO_UCS4)
1941 {
1942 if (fio_flags & FIO_ENDIAN_L)
1943 {
1944 u8c = (*--p << 24);
1945 u8c += (*--p << 16);
1946 u8c += (*--p << 8);
1947 u8c += *--p;
1948 }
1949 else /* big endian */
1950 {
1951 u8c = *--p;
1952 u8c += (*--p << 8);
1953 u8c += (*--p << 16);
1954 u8c += (*--p << 24);
1955 }
1956 }
1957 else /* UTF-8 */
1958 {
1959 if (*--p < 0x80)
1960 u8c = *p;
1961 else
1962 {
1963 len = utf_head_off(ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001964 p -= len;
1965 u8c = utf_ptr2char(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001966 if (len == 0)
1967 {
1968 /* Not a valid UTF-8 character, retry with
1969 * another fenc when possible, otherwise just
1970 * report the error. */
1971 if (can_retry)
1972 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001973 if (conv_error == 0)
1974 conv_error = readfile_linenr(linecnt,
1975 ptr, p);
1976 if (bad_char_behavior == BAD_DROP)
1977 continue;
1978 if (bad_char_behavior != BAD_KEEP)
1979 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001980 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001981 }
1982 }
1983 if (enc_utf8) /* produce UTF-8 */
1984 {
1985 dest -= utf_char2len(u8c);
1986 (void)utf_char2bytes(u8c, dest);
1987 }
1988 else /* produce Latin1 */
1989 {
1990 --dest;
1991 if (u8c >= 0x100)
1992 {
1993 /* character doesn't fit in latin1, retry with
1994 * another fenc when possible, otherwise just
1995 * report the error. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001996 if (can_retry)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001997 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001998 if (conv_error == 0)
1999 conv_error = readfile_linenr(linecnt, ptr, p);
2000 if (bad_char_behavior == BAD_DROP)
2001 ++dest;
2002 else if (bad_char_behavior == BAD_KEEP)
2003 *dest = u8c;
2004 else if (eap != NULL && eap->bad_char != 0)
2005 *dest = bad_char_behavior;
2006 else
2007 *dest = 0xBF;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002008 }
2009 else
2010 *dest = u8c;
2011 }
2012 }
2013
2014 /* move the linerest to before the converted characters */
2015 line_start = dest - linerest;
2016 mch_memmove(line_start, buffer, (size_t)linerest);
2017 size = (long)((ptr + real_size) - dest);
2018 ptr = dest;
2019 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002020 else if (enc_utf8 && !curbuf->b_p_bin)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002021 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002022 int incomplete_tail = FALSE;
2023
2024 /* Reading UTF-8: Check if the bytes are valid UTF-8. */
2025 for (p = ptr; ; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002026 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002027 int todo = (int)((ptr + size) - p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002028 int l;
2029
2030 if (todo <= 0)
2031 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002032 if (*p >= 0x80)
2033 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002034 /* A length of 1 means it's an illegal byte. Accept
2035 * an incomplete character at the end though, the next
2036 * read() will get the next bytes, we'll check it
2037 * then. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002038 l = utf_ptr2len_len(p, todo);
Bram Moolenaarf453d352008-06-04 17:37:34 +00002039 if (l > todo && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002040 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002041 /* Avoid retrying with a different encoding when
2042 * a truncated file is more likely, or attempting
2043 * to read the rest of an incomplete sequence when
2044 * we have already done so. */
2045 if (p > ptr || filesize > 0)
2046 incomplete_tail = TRUE;
2047 /* Incomplete byte sequence, move it to conv_rest[]
2048 * and try to read the rest of it, unless we've
2049 * already done so. */
2050 if (p > ptr)
2051 {
2052 conv_restlen = todo;
2053 mch_memmove(conv_rest, p, conv_restlen);
2054 size -= conv_restlen;
2055 break;
2056 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002057 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002058 if (l == 1 || l > todo)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002059 {
2060 /* Illegal byte. If we can try another encoding
Bram Moolenaarf453d352008-06-04 17:37:34 +00002061 * do that, unless at EOF where a truncated
2062 * file is more likely than a conversion error. */
2063 if (can_retry && !incomplete_tail)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002064 break;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002065# ifdef USE_ICONV
2066 /* When we did a conversion report an error. */
2067 if (iconv_fd != (iconv_t)-1 && conv_error == 0)
2068 conv_error = readfile_linenr(linecnt, ptr, p);
2069# endif
Bram Moolenaarf453d352008-06-04 17:37:34 +00002070 /* Remember the first linenr with an illegal byte */
2071 if (conv_error == 0 && illegal_byte == 0)
2072 illegal_byte = readfile_linenr(linecnt, ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002073
2074 /* Drop, keep or replace the bad byte. */
2075 if (bad_char_behavior == BAD_DROP)
2076 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002077 mch_memmove(p, p + 1, todo - 1);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002078 --p;
2079 --size;
2080 }
2081 else if (bad_char_behavior != BAD_KEEP)
2082 *p = bad_char_behavior;
2083 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002084 else
2085 p += l - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002086 }
2087 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002088 if (p < ptr + size && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002089 {
2090 /* Detected a UTF-8 error. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002091rewind_retry:
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002092 /* Retry reading with another conversion. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002093# if defined(FEAT_EVAL) && defined(USE_ICONV)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002094 if (*p_ccv != NUL && iconv_fd != (iconv_t)-1)
2095 /* iconv() failed, try 'charconvert' */
2096 did_iconv = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002097 else
2098# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002099 /* use next item from 'fileencodings' */
2100 advance_fenc = TRUE;
2101 file_rewind = TRUE;
2102 goto retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002103 }
2104 }
2105#endif
2106
2107 /* count the number of characters (after conversion!) */
2108 filesize += size;
2109
2110 /*
2111 * when reading the first part of a file: guess EOL type
2112 */
2113 if (fileformat == EOL_UNKNOWN)
2114 {
2115 /* First try finding a NL, for Dos and Unix */
2116 if (try_dos || try_unix)
2117 {
Bram Moolenaarc6b72172015-02-27 17:48:09 +01002118 /* Reset the carriage return counter. */
2119 if (try_mac)
2120 try_mac = 1;
2121
Bram Moolenaar071d4272004-06-13 20:20:40 +00002122 for (p = ptr; p < ptr + size; ++p)
2123 {
2124 if (*p == NL)
2125 {
2126 if (!try_unix
2127 || (try_dos && p > ptr && p[-1] == CAR))
2128 fileformat = EOL_DOS;
2129 else
2130 fileformat = EOL_UNIX;
2131 break;
2132 }
Bram Moolenaar05eb6122015-02-17 14:15:19 +01002133 else if (*p == CAR && try_mac)
2134 try_mac++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002135 }
2136
2137 /* Don't give in to EOL_UNIX if EOL_MAC is more likely */
2138 if (fileformat == EOL_UNIX && try_mac)
2139 {
2140 /* Need to reset the counters when retrying fenc. */
2141 try_mac = 1;
2142 try_unix = 1;
2143 for (; p >= ptr && *p != CAR; p--)
2144 ;
2145 if (p >= ptr)
2146 {
2147 for (p = ptr; p < ptr + size; ++p)
2148 {
2149 if (*p == NL)
2150 try_unix++;
2151 else if (*p == CAR)
2152 try_mac++;
2153 }
2154 if (try_mac > try_unix)
2155 fileformat = EOL_MAC;
2156 }
2157 }
Bram Moolenaar05eb6122015-02-17 14:15:19 +01002158 else if (fileformat == EOL_UNKNOWN && try_mac == 1)
2159 /* Looking for CR but found no end-of-line markers at
2160 * all: use the default format. */
2161 fileformat = default_fileformat();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002162 }
2163
2164 /* No NL found: may use Mac format */
2165 if (fileformat == EOL_UNKNOWN && try_mac)
2166 fileformat = EOL_MAC;
2167
2168 /* Still nothing found? Use first format in 'ffs' */
2169 if (fileformat == EOL_UNKNOWN)
2170 fileformat = default_fileformat();
2171
2172 /* if editing a new file: may set p_tx and p_ff */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002173 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002174 set_fileformat(fileformat, OPT_LOCAL);
2175 }
2176 }
2177
2178 /*
2179 * This loop is executed once for every character read.
2180 * Keep it fast!
2181 */
2182 if (fileformat == EOL_MAC)
2183 {
2184 --ptr;
2185 while (++ptr, --size >= 0)
2186 {
2187 /* catch most common case first */
2188 if ((c = *ptr) != NUL && c != CAR && c != NL)
2189 continue;
2190 if (c == NUL)
2191 *ptr = NL; /* NULs are replaced by newlines! */
2192 else if (c == NL)
2193 *ptr = CAR; /* NLs are replaced by CRs! */
2194 else
2195 {
2196 if (skip_count == 0)
2197 {
2198 *ptr = NUL; /* end of line */
2199 len = (colnr_T) (ptr - line_start + 1);
2200 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2201 {
2202 error = TRUE;
2203 break;
2204 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002205#ifdef FEAT_PERSISTENT_UNDO
2206 if (read_undo_file)
2207 sha256_update(&sha_ctx, line_start, len);
2208#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002209 ++lnum;
2210 if (--read_count == 0)
2211 {
2212 error = TRUE; /* break loop */
2213 line_start = ptr; /* nothing left to write */
2214 break;
2215 }
2216 }
2217 else
2218 --skip_count;
2219 line_start = ptr + 1;
2220 }
2221 }
2222 }
2223 else
2224 {
2225 --ptr;
2226 while (++ptr, --size >= 0)
2227 {
2228 if ((c = *ptr) != NUL && c != NL) /* catch most common case */
2229 continue;
2230 if (c == NUL)
2231 *ptr = NL; /* NULs are replaced by newlines! */
2232 else
2233 {
2234 if (skip_count == 0)
2235 {
2236 *ptr = NUL; /* end of line */
2237 len = (colnr_T)(ptr - line_start + 1);
2238 if (fileformat == EOL_DOS)
2239 {
2240 if (ptr[-1] == CAR) /* remove CR */
2241 {
2242 ptr[-1] = NUL;
2243 --len;
2244 }
2245 /*
2246 * Reading in Dos format, but no CR-LF found!
2247 * When 'fileformats' includes "unix", delete all
2248 * the lines read so far and start all over again.
2249 * Otherwise give an error message later.
2250 */
2251 else if (ff_error != EOL_DOS)
2252 {
2253 if ( try_unix
2254 && !read_stdin
2255 && (read_buffer
Bram Moolenaar8767f522016-07-01 17:17:39 +02002256 || vim_lseek(fd, (off_T)0L, SEEK_SET)
2257 == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002258 {
2259 fileformat = EOL_UNIX;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002260 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002261 set_fileformat(EOL_UNIX, OPT_LOCAL);
2262 file_rewind = TRUE;
2263 keep_fileformat = TRUE;
2264 goto retry;
2265 }
2266 ff_error = EOL_DOS;
2267 }
2268 }
2269 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2270 {
2271 error = TRUE;
2272 break;
2273 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002274#ifdef FEAT_PERSISTENT_UNDO
2275 if (read_undo_file)
2276 sha256_update(&sha_ctx, line_start, len);
2277#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002278 ++lnum;
2279 if (--read_count == 0)
2280 {
2281 error = TRUE; /* break loop */
2282 line_start = ptr; /* nothing left to write */
2283 break;
2284 }
2285 }
2286 else
2287 --skip_count;
2288 line_start = ptr + 1;
2289 }
2290 }
2291 }
2292 linerest = (long)(ptr - line_start);
2293 ui_breakcheck();
2294 }
2295
2296failed:
2297 /* not an error, max. number of lines reached */
2298 if (error && read_count == 0)
2299 error = FALSE;
2300
2301 /*
2302 * If we get EOF in the middle of a line, note the fact and
2303 * complete the line ourselves.
2304 * In Dos format ignore a trailing CTRL-Z, unless 'binary' set.
2305 */
2306 if (!error
2307 && !got_int
2308 && linerest != 0
2309 && !(!curbuf->b_p_bin
2310 && fileformat == EOL_DOS
2311 && *line_start == Ctrl_Z
2312 && ptr == line_start + 1))
2313 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002314 /* remember for when writing */
2315 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002316 curbuf->b_p_eol = FALSE;
2317 *ptr = NUL;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002318 len = (colnr_T)(ptr - line_start + 1);
2319 if (ml_append(lnum, line_start, len, newfile) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002320 error = TRUE;
2321 else
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002322 {
2323#ifdef FEAT_PERSISTENT_UNDO
2324 if (read_undo_file)
2325 sha256_update(&sha_ctx, line_start, len);
2326#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002327 read_no_eol_lnum = ++lnum;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002328 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002329 }
2330
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002331 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002332 save_file_ff(curbuf); /* remember the current file format */
2333
2334#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002335 if (curbuf->b_cryptstate != NULL)
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002336 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002337 crypt_free_state(curbuf->b_cryptstate);
2338 curbuf->b_cryptstate = NULL;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002339 }
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002340 if (cryptkey != NULL && cryptkey != curbuf->b_p_key)
2341 crypt_free_key(cryptkey);
2342 /* Don't set cryptkey to NULL, it's used below as a flag that
2343 * encryption was used. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002344#endif
2345
2346#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002347 /* If editing a new file: set 'fenc' for the current buffer.
2348 * Also for ":read ++edit file". */
2349 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002350 set_string_option_direct((char_u *)"fenc", -1, fenc,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00002351 OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002352 if (fenc_alloced)
2353 vim_free(fenc);
2354# ifdef USE_ICONV
2355 if (iconv_fd != (iconv_t)-1)
2356 {
2357 iconv_close(iconv_fd);
2358 iconv_fd = (iconv_t)-1;
2359 }
2360# endif
2361#endif
2362
2363 if (!read_buffer && !read_stdin)
2364 close(fd); /* errors are ignored */
Bram Moolenaarf05da212009-11-17 16:13:15 +00002365#ifdef HAVE_FD_CLOEXEC
2366 else
2367 {
2368 int fdflags = fcntl(fd, F_GETFD);
2369 if (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0)
Bram Moolenaarfbc4b4d2016-02-07 15:14:01 +01002370 (void)fcntl(fd, F_SETFD, fdflags | FD_CLOEXEC);
Bram Moolenaarf05da212009-11-17 16:13:15 +00002371 }
2372#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002373 vim_free(buffer);
2374
2375#ifdef HAVE_DUP
2376 if (read_stdin)
2377 {
2378 /* Use stderr for stdin, makes shell commands work. */
2379 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00002380 ignored = dup(2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002381 }
2382#endif
2383
2384#ifdef FEAT_MBYTE
2385 if (tmpname != NULL)
2386 {
2387 mch_remove(tmpname); /* delete converted file */
2388 vim_free(tmpname);
2389 }
2390#endif
2391 --no_wait_return; /* may wait for return now */
2392
2393 /*
2394 * In recovery mode everything but autocommands is skipped.
2395 */
2396 if (!recoverymode)
2397 {
2398 /* need to delete the last line, which comes from the empty buffer */
2399 if (newfile && wasempty && !(curbuf->b_ml.ml_flags & ML_EMPTY))
2400 {
2401#ifdef FEAT_NETBEANS_INTG
2402 netbeansFireChanges = 0;
2403#endif
2404 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
2405#ifdef FEAT_NETBEANS_INTG
2406 netbeansFireChanges = 1;
2407#endif
2408 --linecnt;
2409 }
2410 linecnt = curbuf->b_ml.ml_line_count - linecnt;
2411 if (filesize == 0)
2412 linecnt = 0;
2413 if (newfile || read_buffer)
Bram Moolenaar7263a772007-05-10 17:35:54 +00002414 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002415 redraw_curbuf_later(NOT_VALID);
Bram Moolenaar7263a772007-05-10 17:35:54 +00002416#ifdef FEAT_DIFF
2417 /* After reading the text into the buffer the diff info needs to
2418 * be updated. */
2419 diff_invalidate(curbuf);
2420#endif
2421#ifdef FEAT_FOLDING
2422 /* All folds in the window are invalid now. Mark them for update
2423 * before triggering autocommands. */
2424 foldUpdateAll(curwin);
2425#endif
2426 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002427 else if (linecnt) /* appended at least one line */
2428 appended_lines_mark(from, linecnt);
2429
Bram Moolenaar071d4272004-06-13 20:20:40 +00002430#ifndef ALWAYS_USE_GUI
2431 /*
2432 * If we were reading from the same terminal as where messages go,
2433 * the screen will have been messed up.
2434 * Switch on raw mode now and clear the screen.
2435 */
2436 if (read_stdin)
2437 {
2438 settmode(TMODE_RAW); /* set to raw mode */
2439 starttermcap();
2440 screenclear();
2441 }
2442#endif
2443
2444 if (got_int)
2445 {
2446 if (!(flags & READ_DUMMY))
2447 {
2448 filemess(curbuf, sfname, (char_u *)_(e_interr), 0);
2449 if (newfile)
2450 curbuf->b_p_ro = TRUE; /* must use "w!" now */
2451 }
2452 msg_scroll = msg_save;
2453#ifdef FEAT_VIMINFO
2454 check_marks_read();
2455#endif
2456 return OK; /* an interrupt isn't really an error */
2457 }
2458
2459 if (!filtering && !(flags & READ_DUMMY))
2460 {
2461 msg_add_fname(curbuf, sfname); /* fname in IObuff with quotes */
2462 c = FALSE;
2463
2464#ifdef UNIX
2465# ifdef S_ISFIFO
2466 if (S_ISFIFO(perm)) /* fifo or socket */
2467 {
2468 STRCAT(IObuff, _("[fifo/socket]"));
2469 c = TRUE;
2470 }
2471# else
2472# ifdef S_IFIFO
2473 if ((perm & S_IFMT) == S_IFIFO) /* fifo */
2474 {
2475 STRCAT(IObuff, _("[fifo]"));
2476 c = TRUE;
2477 }
2478# endif
2479# ifdef S_IFSOCK
2480 if ((perm & S_IFMT) == S_IFSOCK) /* or socket */
2481 {
2482 STRCAT(IObuff, _("[socket]"));
2483 c = TRUE;
2484 }
2485# endif
2486# endif
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002487# ifdef OPEN_CHR_FILES
2488 if (S_ISCHR(perm)) /* or character special */
2489 {
2490 STRCAT(IObuff, _("[character special]"));
2491 c = TRUE;
2492 }
2493# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002494#endif
2495 if (curbuf->b_p_ro)
2496 {
2497 STRCAT(IObuff, shortmess(SHM_RO) ? _("[RO]") : _("[readonly]"));
2498 c = TRUE;
2499 }
2500 if (read_no_eol_lnum)
2501 {
2502 msg_add_eol();
2503 c = TRUE;
2504 }
2505 if (ff_error == EOL_DOS)
2506 {
2507 STRCAT(IObuff, _("[CR missing]"));
2508 c = TRUE;
2509 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002510 if (split)
2511 {
2512 STRCAT(IObuff, _("[long lines split]"));
2513 c = TRUE;
2514 }
2515#ifdef FEAT_MBYTE
2516 if (notconverted)
2517 {
2518 STRCAT(IObuff, _("[NOT converted]"));
2519 c = TRUE;
2520 }
2521 else if (converted)
2522 {
2523 STRCAT(IObuff, _("[converted]"));
2524 c = TRUE;
2525 }
2526#endif
2527#ifdef FEAT_CRYPT
2528 if (cryptkey != NULL)
2529 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002530 crypt_append_msg(curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002531 c = TRUE;
2532 }
2533#endif
2534#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002535 if (conv_error != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002536 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002537 sprintf((char *)IObuff + STRLEN(IObuff),
2538 _("[CONVERSION ERROR in line %ld]"), (long)conv_error);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002539 c = TRUE;
2540 }
2541 else if (illegal_byte > 0)
2542 {
2543 sprintf((char *)IObuff + STRLEN(IObuff),
2544 _("[ILLEGAL BYTE in line %ld]"), (long)illegal_byte);
2545 c = TRUE;
2546 }
2547 else
2548#endif
2549 if (error)
2550 {
2551 STRCAT(IObuff, _("[READ ERRORS]"));
2552 c = TRUE;
2553 }
2554 if (msg_add_fileformat(fileformat))
2555 c = TRUE;
2556#ifdef FEAT_CRYPT
2557 if (cryptkey != NULL)
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002558 msg_add_lines(c, (long)linecnt, filesize
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002559 - crypt_get_header_len(crypt_get_method_nr(curbuf)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002560 else
2561#endif
2562 msg_add_lines(c, (long)linecnt, filesize);
2563
2564 vim_free(keep_msg);
2565 keep_msg = NULL;
2566 msg_scrolled_ign = TRUE;
2567#ifdef ALWAYS_USE_GUI
2568 /* Don't show the message when reading stdin, it would end up in a
2569 * message box (which might be shown when exiting!) */
2570 if (read_stdin || read_buffer)
2571 p = msg_may_trunc(FALSE, IObuff);
2572 else
2573#endif
2574 p = msg_trunc_attr(IObuff, FALSE, 0);
2575 if (read_stdin || read_buffer || restart_edit != 0
Bram Moolenaar1c7715d2005-10-03 22:02:18 +00002576 || (msg_scrolled != 0 && !need_wait_return))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002577 /* Need to repeat the message after redrawing when:
2578 * - When reading from stdin (the screen will be cleared next).
2579 * - When restart_edit is set (otherwise there will be a delay
2580 * before redrawing).
2581 * - When the screen was scrolled but there is no wait-return
2582 * prompt. */
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002583 set_keep_msg(p, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002584 msg_scrolled_ign = FALSE;
2585 }
2586
2587 /* with errors writing the file requires ":w!" */
2588 if (newfile && (error
2589#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002590 || conv_error != 0
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002591 || (illegal_byte > 0 && bad_char_behavior != BAD_KEEP)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002592#endif
2593 ))
2594 curbuf->b_p_ro = TRUE;
2595
2596 u_clearline(); /* cannot use "U" command after adding lines */
2597
2598 /*
2599 * In Ex mode: cursor at last new line.
2600 * Otherwise: cursor at first new line.
2601 */
2602 if (exmode_active)
2603 curwin->w_cursor.lnum = from + linecnt;
2604 else
2605 curwin->w_cursor.lnum = from + 1;
2606 check_cursor_lnum();
2607 beginline(BL_WHITE | BL_FIX); /* on first non-blank */
2608
2609 /*
2610 * Set '[ and '] marks to the newly read lines.
2611 */
2612 curbuf->b_op_start.lnum = from + 1;
2613 curbuf->b_op_start.col = 0;
2614 curbuf->b_op_end.lnum = from + linecnt;
2615 curbuf->b_op_end.col = 0;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002616
2617#ifdef WIN32
2618 /*
2619 * Work around a weird problem: When a file has two links (only
2620 * possible on NTFS) and we write through one link, then stat() it
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00002621 * through the other link, the timestamp information may be wrong.
Bram Moolenaar03f48552006-02-28 23:52:23 +00002622 * It's correct again after reading the file, thus reset the timestamp
2623 * here.
2624 */
2625 if (newfile && !read_stdin && !read_buffer
2626 && mch_stat((char *)fname, &st) >= 0)
2627 {
2628 buf_store_time(curbuf, &st, fname);
2629 curbuf->b_mtime_read = curbuf->b_mtime;
2630 }
2631#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002632 }
2633 msg_scroll = msg_save;
2634
2635#ifdef FEAT_VIMINFO
2636 /*
2637 * Get the marks before executing autocommands, so they can be used there.
2638 */
2639 check_marks_read();
2640#endif
2641
Bram Moolenaar071d4272004-06-13 20:20:40 +00002642 /*
Bram Moolenaar34d72d42015-07-17 14:18:08 +02002643 * We remember if the last line of the read didn't have
2644 * an eol even when 'binary' is off, to support turning 'fixeol' off,
2645 * or writing the read again with 'binary' on. The latter is required
2646 * for ":autocmd FileReadPost *.gz set bin|'[,']!gunzip" to work.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002647 */
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002648 curbuf->b_no_eol_lnum = read_no_eol_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002649
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02002650 /* When reloading a buffer put the cursor at the first line that is
2651 * different. */
2652 if (flags & READ_KEEP_UNDO)
2653 u_find_first_changed();
2654
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002655#ifdef FEAT_PERSISTENT_UNDO
2656 /*
2657 * When opening a new file locate undo info and read it.
2658 */
2659 if (read_undo_file)
2660 {
2661 char_u hash[UNDO_HASH_SIZE];
2662
2663 sha256_finish(&sha_ctx, hash);
Bram Moolenaar6ed8ed82010-05-30 20:40:11 +02002664 u_read_undo(NULL, hash, fname);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002665 }
2666#endif
2667
Bram Moolenaardf177f62005-02-22 08:39:57 +00002668#ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00002669 if (!read_stdin && !read_buffer)
2670 {
2671 int m = msg_scroll;
2672 int n = msg_scrolled;
2673
2674 /* Save the fileformat now, otherwise the buffer will be considered
2675 * modified if the format/encoding was automatically detected. */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002676 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002677 save_file_ff(curbuf);
2678
2679 /*
2680 * The output from the autocommands should not overwrite anything and
2681 * should not be overwritten: Set msg_scroll, restore its value if no
2682 * output was done.
2683 */
2684 msg_scroll = TRUE;
2685 if (filtering)
2686 apply_autocmds_exarg(EVENT_FILTERREADPOST, NULL, sfname,
2687 FALSE, curbuf, eap);
2688 else if (newfile)
Bram Moolenaarc3691332016-04-20 12:49:49 +02002689 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002690 apply_autocmds_exarg(EVENT_BUFREADPOST, NULL, sfname,
2691 FALSE, curbuf, eap);
Bram Moolenaarc3691332016-04-20 12:49:49 +02002692 if (!au_did_filetype && *curbuf->b_p_ft != NUL)
2693 /*
2694 * EVENT_FILETYPE was not triggered but the buffer already has a
2695 * filetype. Trigger EVENT_FILETYPE using the existing filetype.
2696 */
2697 apply_autocmds(EVENT_FILETYPE, curbuf->b_p_ft, curbuf->b_fname,
2698 TRUE, curbuf);
2699 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002700 else
2701 apply_autocmds_exarg(EVENT_FILEREADPOST, sfname, sfname,
2702 FALSE, NULL, eap);
2703 if (msg_scrolled == n)
2704 msg_scroll = m;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002705# ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002706 if (aborting()) /* autocmds may abort script processing */
2707 return FAIL;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002708# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002709 }
2710#endif
2711
2712 if (recoverymode && error)
2713 return FAIL;
2714 return OK;
2715}
2716
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002717#ifdef OPEN_CHR_FILES
2718/*
2719 * Returns TRUE if the file name argument is of the form "/dev/fd/\d\+",
2720 * which is the name of files used for process substitution output by
2721 * some shells on some operating systems, e.g., bash on SunOS.
2722 * Do not accept "/dev/fd/[012]", opening these may hang Vim.
2723 */
2724 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002725is_dev_fd_file(char_u *fname)
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002726{
2727 return (STRNCMP(fname, "/dev/fd/", 8) == 0
2728 && VIM_ISDIGIT(fname[8])
2729 && *skipdigits(fname + 9) == NUL
2730 && (fname[9] != NUL
2731 || (fname[8] != '0' && fname[8] != '1' && fname[8] != '2')));
2732}
2733#endif
2734
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002735#ifdef FEAT_MBYTE
2736
2737/*
2738 * From the current line count and characters read after that, estimate the
2739 * line number where we are now.
2740 * Used for error messages that include a line number.
2741 */
2742 static linenr_T
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002743readfile_linenr(
2744 linenr_T linecnt, /* line count before reading more bytes */
2745 char_u *p, /* start of more bytes read */
2746 char_u *endp) /* end of more bytes read */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002747{
2748 char_u *s;
2749 linenr_T lnum;
2750
2751 lnum = curbuf->b_ml.ml_line_count - linecnt + 1;
2752 for (s = p; s < endp; ++s)
2753 if (*s == '\n')
2754 ++lnum;
2755 return lnum;
2756}
2757#endif
2758
Bram Moolenaar071d4272004-06-13 20:20:40 +00002759/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00002760 * Fill "*eap" to force the 'fileencoding', 'fileformat' and 'binary to be
2761 * equal to the buffer "buf". Used for calling readfile().
Bram Moolenaar071d4272004-06-13 20:20:40 +00002762 * Returns OK or FAIL.
2763 */
2764 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002765prep_exarg(exarg_T *eap, buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002766{
2767 eap->cmd = alloc((unsigned)(STRLEN(buf->b_p_ff)
2768#ifdef FEAT_MBYTE
2769 + STRLEN(buf->b_p_fenc)
2770#endif
2771 + 15));
2772 if (eap->cmd == NULL)
2773 return FAIL;
2774
2775#ifdef FEAT_MBYTE
2776 sprintf((char *)eap->cmd, "e ++ff=%s ++enc=%s", buf->b_p_ff, buf->b_p_fenc);
2777 eap->force_enc = 14 + (int)STRLEN(buf->b_p_ff);
Bram Moolenaar195d6352005-12-19 22:08:24 +00002778 eap->bad_char = buf->b_bad_char;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002779#else
2780 sprintf((char *)eap->cmd, "e ++ff=%s", buf->b_p_ff);
2781#endif
2782 eap->force_ff = 7;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002783
2784 eap->force_bin = buf->b_p_bin ? FORCE_BIN : FORCE_NOBIN;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002785 eap->read_edit = FALSE;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002786 eap->forceit = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002787 return OK;
2788}
2789
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002790/*
2791 * Set default or forced 'fileformat' and 'binary'.
2792 */
2793 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002794set_file_options(int set_options, exarg_T *eap)
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002795{
2796 /* set default 'fileformat' */
2797 if (set_options)
2798 {
2799 if (eap != NULL && eap->force_ff != 0)
2800 set_fileformat(get_fileformat_force(curbuf, eap), OPT_LOCAL);
2801 else if (*p_ffs != NUL)
2802 set_fileformat(default_fileformat(), OPT_LOCAL);
2803 }
2804
2805 /* set or reset 'binary' */
2806 if (eap != NULL && eap->force_bin != 0)
2807 {
2808 int oldval = curbuf->b_p_bin;
2809
2810 curbuf->b_p_bin = (eap->force_bin == FORCE_BIN);
2811 set_options_bin(oldval, curbuf->b_p_bin, OPT_LOCAL);
2812 }
2813}
2814
2815#if defined(FEAT_MBYTE) || defined(PROTO)
2816/*
2817 * Set forced 'fileencoding'.
2818 */
2819 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002820set_forced_fenc(exarg_T *eap)
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002821{
2822 if (eap->force_enc != 0)
2823 {
2824 char_u *fenc = enc_canonize(eap->cmd + eap->force_enc);
2825
2826 if (fenc != NULL)
2827 set_string_option_direct((char_u *)"fenc", -1,
2828 fenc, OPT_FREE|OPT_LOCAL, 0);
2829 vim_free(fenc);
2830 }
2831}
2832
Bram Moolenaar071d4272004-06-13 20:20:40 +00002833/*
2834 * Find next fileencoding to use from 'fileencodings'.
2835 * "pp" points to fenc_next. It's advanced to the next item.
2836 * When there are no more items, an empty string is returned and *pp is set to
2837 * NULL.
2838 * When *pp is not set to NULL, the result is in allocated memory.
2839 */
2840 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002841next_fenc(char_u **pp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002842{
2843 char_u *p;
2844 char_u *r;
2845
2846 if (**pp == NUL)
2847 {
2848 *pp = NULL;
2849 return (char_u *)"";
2850 }
2851 p = vim_strchr(*pp, ',');
2852 if (p == NULL)
2853 {
2854 r = enc_canonize(*pp);
2855 *pp += STRLEN(*pp);
2856 }
2857 else
2858 {
2859 r = vim_strnsave(*pp, (int)(p - *pp));
2860 *pp = p + 1;
2861 if (r != NULL)
2862 {
2863 p = enc_canonize(r);
2864 vim_free(r);
2865 r = p;
2866 }
2867 }
2868 if (r == NULL) /* out of memory */
2869 {
2870 r = (char_u *)"";
2871 *pp = NULL;
2872 }
2873 return r;
2874}
2875
2876# ifdef FEAT_EVAL
2877/*
2878 * Convert a file with the 'charconvert' expression.
2879 * This closes the file which is to be read, converts it and opens the
2880 * resulting file for reading.
2881 * Returns name of the resulting converted file (the caller should delete it
2882 * after reading it).
2883 * Returns NULL if the conversion failed ("*fdp" is not set) .
2884 */
2885 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002886readfile_charconvert(
2887 char_u *fname, /* name of input file */
2888 char_u *fenc, /* converted from */
2889 int *fdp) /* in/out: file descriptor of file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002890{
2891 char_u *tmpname;
2892 char_u *errmsg = NULL;
2893
Bram Moolenaare5c421c2015-03-31 13:33:08 +02002894 tmpname = vim_tempname('r', FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002895 if (tmpname == NULL)
2896 errmsg = (char_u *)_("Can't find temp file for conversion");
2897 else
2898 {
2899 close(*fdp); /* close the input file, ignore errors */
2900 *fdp = -1;
2901 if (eval_charconvert(fenc, enc_utf8 ? (char_u *)"utf-8" : p_enc,
2902 fname, tmpname) == FAIL)
2903 errmsg = (char_u *)_("Conversion with 'charconvert' failed");
2904 if (errmsg == NULL && (*fdp = mch_open((char *)tmpname,
2905 O_RDONLY | O_EXTRA, 0)) < 0)
2906 errmsg = (char_u *)_("can't read output of 'charconvert'");
2907 }
2908
2909 if (errmsg != NULL)
2910 {
2911 /* Don't use emsg(), it breaks mappings, the retry with
2912 * another type of conversion might still work. */
2913 MSG(errmsg);
2914 if (tmpname != NULL)
2915 {
2916 mch_remove(tmpname); /* delete converted file */
2917 vim_free(tmpname);
2918 tmpname = NULL;
2919 }
2920 }
2921
2922 /* If the input file is closed, open it (caller should check for error). */
2923 if (*fdp < 0)
2924 *fdp = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
2925
2926 return tmpname;
2927}
2928# endif
2929
2930#endif
2931
2932#ifdef FEAT_VIMINFO
2933/*
2934 * Read marks for the current buffer from the viminfo file, when we support
2935 * buffer marks and the buffer has a name.
2936 */
2937 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002938check_marks_read(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002939{
2940 if (!curbuf->b_marks_read && get_viminfo_parameter('\'') > 0
2941 && curbuf->b_ffname != NULL)
Bram Moolenaard812df62008-11-09 12:46:09 +00002942 read_viminfo(NULL, VIF_WANT_MARKS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002943
2944 /* Always set b_marks_read; needed when 'viminfo' is changed to include
2945 * the ' parameter after opening a buffer. */
2946 curbuf->b_marks_read = TRUE;
2947}
2948#endif
2949
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002950#if defined(FEAT_CRYPT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002951/*
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002952 * Check for magic number used for encryption. Applies to the current buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002953 * If found, the magic number is removed from ptr[*sizep] and *sizep and
2954 * *filesizep are updated.
2955 * Return the (new) encryption key, NULL for no encryption.
2956 */
2957 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002958check_for_cryptkey(
2959 char_u *cryptkey, /* previous encryption key or NULL */
2960 char_u *ptr, /* pointer to read bytes */
2961 long *sizep, /* length of read bytes */
Bram Moolenaar8767f522016-07-01 17:17:39 +02002962 off_T *filesizep, /* nr of bytes used from file */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002963 int newfile, /* editing a new buffer */
2964 char_u *fname, /* file name to display */
2965 int *did_ask) /* flag: whether already asked for key */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002966{
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002967 int method = crypt_method_nr_from_magic((char *)ptr, *sizep);
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02002968 int b_p_ro = curbuf->b_p_ro;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002969
2970 if (method >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002971 {
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02002972 /* Mark the buffer as read-only until the decryption has taken place.
2973 * Avoids accidentally overwriting the file with garbage. */
2974 curbuf->b_p_ro = TRUE;
2975
Bram Moolenaar2be79502014-08-13 21:58:28 +02002976 /* Set the cryptmethod local to the buffer. */
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002977 crypt_set_cm_option(curbuf, method);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002978 if (cryptkey == NULL && !*did_ask)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002979 {
2980 if (*curbuf->b_p_key)
2981 cryptkey = curbuf->b_p_key;
2982 else
2983 {
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002984 /* When newfile is TRUE, store the typed key in the 'key'
2985 * option and don't free it. bf needs hash of the key saved.
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002986 * Don't ask for the key again when first time Enter was hit.
2987 * Happens when retrying to detect encoding. */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002988 smsg((char_u *)_(need_key_msg), fname);
2989 msg_scroll = TRUE;
Bram Moolenaar3a0c9082014-11-12 15:15:42 +01002990 crypt_check_method(method);
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002991 cryptkey = crypt_get_key(newfile, FALSE);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002992 *did_ask = TRUE;
2993
Bram Moolenaar071d4272004-06-13 20:20:40 +00002994 /* check if empty key entered */
2995 if (cryptkey != NULL && *cryptkey == NUL)
2996 {
2997 if (cryptkey != curbuf->b_p_key)
2998 vim_free(cryptkey);
2999 cryptkey = NULL;
3000 }
3001 }
3002 }
3003
3004 if (cryptkey != NULL)
3005 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003006 int header_len;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003007
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003008 curbuf->b_cryptstate = crypt_create_from_header(
3009 method, cryptkey, ptr);
3010 crypt_set_cm_option(curbuf, method);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003011
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003012 /* Remove cryptmethod specific header from the text. */
3013 header_len = crypt_get_header_len(method);
3014 *filesizep += header_len;
3015 *sizep -= header_len;
3016 mch_memmove(ptr, ptr + header_len, (size_t)*sizep);
3017
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02003018 /* Restore the read-only flag. */
3019 curbuf->b_p_ro = b_p_ro;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003020 }
3021 }
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003022 /* When starting to edit a new file which does not have encryption, clear
3023 * the 'key' option, except when starting up (called with -x argument) */
Bram Moolenaarfa0ff9a2010-07-25 16:05:19 +02003024 else if (newfile && *curbuf->b_p_key != NUL && !starting)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003025 set_option_value((char_u *)"key", 0L, (char_u *)"", OPT_LOCAL);
3026
3027 return cryptkey;
3028}
Bram Moolenaar80794b12010-06-13 05:20:42 +02003029#endif /* FEAT_CRYPT */
3030
Bram Moolenaar071d4272004-06-13 20:20:40 +00003031#ifdef UNIX
3032 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003033set_file_time(
3034 char_u *fname,
3035 time_t atime, /* access time */
3036 time_t mtime) /* modification time */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003037{
3038# if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
3039 struct utimbuf buf;
3040
3041 buf.actime = atime;
3042 buf.modtime = mtime;
3043 (void)utime((char *)fname, &buf);
3044# else
3045# if defined(HAVE_UTIMES)
3046 struct timeval tvp[2];
3047
3048 tvp[0].tv_sec = atime;
3049 tvp[0].tv_usec = 0;
3050 tvp[1].tv_sec = mtime;
3051 tvp[1].tv_usec = 0;
3052# ifdef NeXT
3053 (void)utimes((char *)fname, tvp);
3054# else
3055 (void)utimes((char *)fname, (const struct timeval *)&tvp);
3056# endif
3057# endif
3058# endif
3059}
3060#endif /* UNIX */
3061
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003062#if defined(VMS) && !defined(MIN)
3063/* Older DECC compiler for VAX doesn't define MIN() */
3064# define MIN(a, b) ((a) < (b) ? (a) : (b))
3065#endif
3066
Bram Moolenaar071d4272004-06-13 20:20:40 +00003067/*
Bram Moolenaar5386a122007-06-28 20:02:32 +00003068 * Return TRUE if a file appears to be read-only from the file permissions.
3069 */
3070 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003071check_file_readonly(
3072 char_u *fname, /* full path to file */
3073 int perm) /* known permissions on file */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003074{
3075#ifndef USE_MCH_ACCESS
3076 int fd = 0;
3077#endif
3078
3079 return (
3080#ifdef USE_MCH_ACCESS
3081# ifdef UNIX
3082 (perm & 0222) == 0 ||
3083# endif
3084 mch_access((char *)fname, W_OK)
3085#else
3086 (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0
3087 ? TRUE : (close(fd), FALSE)
3088#endif
3089 );
3090}
3091
3092
3093/*
Bram Moolenaar292ad192005-12-11 21:29:51 +00003094 * buf_write() - write to file "fname" lines "start" through "end"
Bram Moolenaar071d4272004-06-13 20:20:40 +00003095 *
3096 * We do our own buffering here because fwrite() is so slow.
3097 *
Bram Moolenaar292ad192005-12-11 21:29:51 +00003098 * If "forceit" is true, we don't care for errors when attempting backups.
3099 * In case of an error everything possible is done to restore the original
Bram Moolenaare37d50a2008-08-06 17:06:04 +00003100 * file. But when "forceit" is TRUE, we risk losing it.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003101 *
3102 * When "reset_changed" is TRUE and "append" == FALSE and "start" == 1 and
3103 * "end" == curbuf->b_ml.ml_line_count, reset curbuf->b_changed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003104 *
3105 * This function must NOT use NameBuff (because it's called by autowrite()).
3106 *
3107 * return FAIL for failure, OK otherwise
3108 */
3109 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003110buf_write(
3111 buf_T *buf,
3112 char_u *fname,
3113 char_u *sfname,
3114 linenr_T start,
3115 linenr_T end,
3116 exarg_T *eap, /* for forced 'ff' and 'fenc', can be
Bram Moolenaar071d4272004-06-13 20:20:40 +00003117 NULL! */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003118 int append, /* append to the file */
3119 int forceit,
3120 int reset_changed,
3121 int filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003122{
3123 int fd;
3124 char_u *backup = NULL;
3125 int backup_copy = FALSE; /* copy the original file? */
3126 int dobackup;
3127 char_u *ffname;
3128 char_u *wfname = NULL; /* name of file to write to */
3129 char_u *s;
3130 char_u *ptr;
3131 char_u c;
3132 int len;
3133 linenr_T lnum;
3134 long nchars;
3135 char_u *errmsg = NULL;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003136 int errmsg_allocated = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003137 char_u *errnum = NULL;
3138 char_u *buffer;
3139 char_u smallbuf[SMBUFSIZE];
3140 char_u *backup_ext;
3141 int bufsize;
3142 long perm; /* file permissions */
3143 int retval = OK;
3144 int newfile = FALSE; /* TRUE if file doesn't exist yet */
3145 int msg_save = msg_scroll;
3146 int overwriting; /* TRUE if writing over original */
3147 int no_eol = FALSE; /* no end-of-line written */
3148 int device = FALSE; /* writing to a device */
Bram Moolenaar8767f522016-07-01 17:17:39 +02003149 stat_T st_old;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003150 int prev_got_int = got_int;
3151 int file_readonly = FALSE; /* overwritten file is read-only */
3152 static char *err_readonly = "is read-only (cannot override: \"W\" in 'cpoptions')";
3153#if defined(UNIX) || defined(__EMX__XX) /*XXX fix me sometime? */
3154 int made_writable = FALSE; /* 'w' bit has been set */
3155#endif
3156 /* writing everything */
3157 int whole = (start == 1 && end == buf->b_ml.ml_line_count);
3158#ifdef FEAT_AUTOCMD
3159 linenr_T old_line_count = buf->b_ml.ml_line_count;
3160#endif
3161 int attr;
3162 int fileformat;
3163 int write_bin;
3164 struct bw_info write_info; /* info for buf_write_bytes() */
3165#ifdef FEAT_MBYTE
3166 int converted = FALSE;
3167 int notconverted = FALSE;
3168 char_u *fenc; /* effective 'fileencoding' */
3169 char_u *fenc_tofree = NULL; /* allocated "fenc" */
3170#endif
3171#ifdef HAS_BW_FLAGS
3172 int wb_flags = 0;
3173#endif
3174#ifdef HAVE_ACL
3175 vim_acl_T acl = NULL; /* ACL copied from original file to
3176 backup or new file */
3177#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003178#ifdef FEAT_PERSISTENT_UNDO
3179 int write_undo_file = FALSE;
3180 context_sha256_T sha_ctx;
3181#endif
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003182 unsigned int bkc = get_bkc_value(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003183
3184 if (fname == NULL || *fname == NUL) /* safety check */
3185 return FAIL;
Bram Moolenaar70d60e92009-12-31 13:53:33 +00003186 if (buf->b_ml.ml_mfp == NULL)
3187 {
3188 /* This can happen during startup when there is a stray "w" in the
3189 * vimrc file. */
3190 EMSG(_(e_emptybuf));
3191 return FAIL;
3192 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003193
3194 /*
3195 * Disallow writing from .exrc and .vimrc in current directory for
3196 * security reasons.
3197 */
3198 if (check_secure())
3199 return FAIL;
3200
3201 /* Avoid a crash for a long name. */
3202 if (STRLEN(fname) >= MAXPATHL)
3203 {
3204 EMSG(_(e_longname));
3205 return FAIL;
3206 }
3207
3208#ifdef FEAT_MBYTE
3209 /* must init bw_conv_buf and bw_iconv_fd before jumping to "fail" */
3210 write_info.bw_conv_buf = NULL;
3211 write_info.bw_conv_error = FALSE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003212 write_info.bw_conv_error_lnum = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003213 write_info.bw_restlen = 0;
3214# ifdef USE_ICONV
3215 write_info.bw_iconv_fd = (iconv_t)-1;
3216# endif
3217#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003218#ifdef FEAT_CRYPT
3219 write_info.bw_buffer = buf;
3220#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003221
Bram Moolenaardf177f62005-02-22 08:39:57 +00003222 /* After writing a file changedtick changes but we don't want to display
3223 * the line. */
3224 ex_no_reprint = TRUE;
3225
Bram Moolenaar071d4272004-06-13 20:20:40 +00003226 /*
3227 * If there is no file name yet, use the one for the written file.
3228 * BF_NOTEDITED is set to reflect this (in case the write fails).
3229 * Don't do this when the write is for a filter command.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003230 * Don't do this when appending.
3231 * Only do this when 'cpoptions' contains the 'F' flag.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003232 */
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003233 if (buf->b_ffname == NULL
3234 && reset_changed
Bram Moolenaar071d4272004-06-13 20:20:40 +00003235 && whole
3236 && buf == curbuf
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00003237#ifdef FEAT_QUICKFIX
3238 && !bt_nofile(buf)
3239#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003240 && !filtering
Bram Moolenaar292ad192005-12-11 21:29:51 +00003241 && (!append || vim_strchr(p_cpo, CPO_FNAMEAPP) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003242 && vim_strchr(p_cpo, CPO_FNAMEW) != NULL)
3243 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003244 if (set_rw_fname(fname, sfname) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003245 return FAIL;
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003246 buf = curbuf; /* just in case autocmds made "buf" invalid */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003247 }
3248
3249 if (sfname == NULL)
3250 sfname = fname;
3251 /*
3252 * For Unix: Use the short file name whenever possible.
3253 * Avoids problems with networks and when directory names are changed.
3254 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
3255 * another directory, which we don't detect
3256 */
3257 ffname = fname; /* remember full fname */
3258#ifdef UNIX
3259 fname = sfname;
3260#endif
3261
3262 if (buf->b_ffname != NULL && fnamecmp(ffname, buf->b_ffname) == 0)
3263 overwriting = TRUE;
3264 else
3265 overwriting = FALSE;
3266
3267 if (exiting)
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003268 settmode(TMODE_COOK); /* when exiting allow typeahead now */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003269
3270 ++no_wait_return; /* don't wait for return yet */
3271
3272 /*
3273 * Set '[ and '] marks to the lines to be written.
3274 */
3275 buf->b_op_start.lnum = start;
3276 buf->b_op_start.col = 0;
3277 buf->b_op_end.lnum = end;
3278 buf->b_op_end.col = 0;
3279
3280#ifdef FEAT_AUTOCMD
3281 {
3282 aco_save_T aco;
3283 int buf_ffname = FALSE;
3284 int buf_sfname = FALSE;
3285 int buf_fname_f = FALSE;
3286 int buf_fname_s = FALSE;
3287 int did_cmd = FALSE;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003288 int nofile_err = FALSE;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003289 int empty_memline = (buf->b_ml.ml_mfp == NULL);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003290 bufref_T bufref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003291
3292 /*
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003293 * Apply PRE autocommands.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003294 * Set curbuf to the buffer to be written.
3295 * Careful: The autocommands may call buf_write() recursively!
3296 */
3297 if (ffname == buf->b_ffname)
3298 buf_ffname = TRUE;
3299 if (sfname == buf->b_sfname)
3300 buf_sfname = TRUE;
3301 if (fname == buf->b_ffname)
3302 buf_fname_f = TRUE;
3303 if (fname == buf->b_sfname)
3304 buf_fname_s = TRUE;
3305
3306 /* set curwin/curbuf to buf and save a few things */
3307 aucmd_prepbuf(&aco, buf);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003308 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003309
3310 if (append)
3311 {
3312 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD,
3313 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003314 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003315#ifdef FEAT_QUICKFIX
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00003316 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003317 nofile_err = TRUE;
3318 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003319#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003320 apply_autocmds_exarg(EVENT_FILEAPPENDPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003321 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003322 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003323 }
3324 else if (filtering)
3325 {
3326 apply_autocmds_exarg(EVENT_FILTERWRITEPRE,
3327 NULL, sfname, FALSE, curbuf, eap);
3328 }
3329 else if (reset_changed && whole)
3330 {
Bram Moolenaar39fc42e2011-09-02 11:56:20 +02003331 int was_changed = curbufIsChanged();
3332
3333 did_cmd = apply_autocmds_exarg(EVENT_BUFWRITECMD,
3334 sfname, sfname, FALSE, curbuf, eap);
3335 if (did_cmd)
3336 {
3337 if (was_changed && !curbufIsChanged())
3338 {
3339 /* Written everything correctly and BufWriteCmd has reset
3340 * 'modified': Correct the undo information so that an
3341 * undo now sets 'modified'. */
3342 u_unchanged(curbuf);
3343 u_update_save_nr(curbuf);
3344 }
3345 }
3346 else
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003347 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003348#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003349 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003350 nofile_err = TRUE;
3351 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003352#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003353 apply_autocmds_exarg(EVENT_BUFWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003354 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003355 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003356 }
3357 else
3358 {
3359 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD,
3360 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003361 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003362#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003363 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003364 nofile_err = TRUE;
3365 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003366#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003367 apply_autocmds_exarg(EVENT_FILEWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003368 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003369 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003370 }
3371
3372 /* restore curwin/curbuf and a few other things */
3373 aucmd_restbuf(&aco);
3374
3375 /*
3376 * In three situations we return here and don't write the file:
3377 * 1. the autocommands deleted or unloaded the buffer.
3378 * 2. The autocommands abort script processing.
3379 * 3. If one of the "Cmd" autocommands was executed.
3380 */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003381 if (!bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003382 buf = NULL;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003383 if (buf == NULL || (buf->b_ml.ml_mfp == NULL && !empty_memline)
Bram Moolenaar1e015462005-09-25 22:16:38 +00003384 || did_cmd || nofile_err
3385#ifdef FEAT_EVAL
3386 || aborting()
3387#endif
3388 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003389 {
3390 --no_wait_return;
3391 msg_scroll = msg_save;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003392 if (nofile_err)
3393 EMSG(_("E676: No matching autocommands for acwrite buffer"));
3394
Bram Moolenaar1e015462005-09-25 22:16:38 +00003395 if (nofile_err
3396#ifdef FEAT_EVAL
3397 || aborting()
3398#endif
3399 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003400 /* An aborting error, interrupt or exception in the
3401 * autocommands. */
3402 return FAIL;
3403 if (did_cmd)
3404 {
3405 if (buf == NULL)
3406 /* The buffer was deleted. We assume it was written
3407 * (can't retry anyway). */
3408 return OK;
3409 if (overwriting)
3410 {
3411 /* Assume the buffer was written, update the timestamp. */
3412 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00003413 if (append)
3414 buf->b_flags &= ~BF_NEW;
3415 else
3416 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003417 }
Bram Moolenaar292ad192005-12-11 21:29:51 +00003418 if (reset_changed && buf->b_changed && !append
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003419 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003420 /* Buffer still changed, the autocommands didn't work
3421 * properly. */
3422 return FAIL;
3423 return OK;
3424 }
3425#ifdef FEAT_EVAL
3426 if (!aborting())
3427#endif
3428 EMSG(_("E203: Autocommands deleted or unloaded buffer to be written"));
3429 return FAIL;
3430 }
3431
3432 /*
3433 * The autocommands may have changed the number of lines in the file.
3434 * When writing the whole file, adjust the end.
3435 * When writing part of the file, assume that the autocommands only
3436 * changed the number of lines that are to be written (tricky!).
3437 */
3438 if (buf->b_ml.ml_line_count != old_line_count)
3439 {
3440 if (whole) /* write all */
3441 end = buf->b_ml.ml_line_count;
3442 else if (buf->b_ml.ml_line_count > old_line_count) /* more lines */
3443 end += buf->b_ml.ml_line_count - old_line_count;
3444 else /* less lines */
3445 {
3446 end -= old_line_count - buf->b_ml.ml_line_count;
3447 if (end < start)
3448 {
3449 --no_wait_return;
3450 msg_scroll = msg_save;
3451 EMSG(_("E204: Autocommand changed number of lines in unexpected way"));
3452 return FAIL;
3453 }
3454 }
3455 }
3456
3457 /*
3458 * The autocommands may have changed the name of the buffer, which may
3459 * be kept in fname, ffname and sfname.
3460 */
3461 if (buf_ffname)
3462 ffname = buf->b_ffname;
3463 if (buf_sfname)
3464 sfname = buf->b_sfname;
3465 if (buf_fname_f)
3466 fname = buf->b_ffname;
3467 if (buf_fname_s)
3468 fname = buf->b_sfname;
3469 }
3470#endif
3471
3472#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003473 if (netbeans_active() && isNetbeansBuffer(buf))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003474 {
3475 if (whole)
3476 {
3477 /*
3478 * b_changed can be 0 after an undo, but we still need to write
3479 * the buffer to NetBeans.
3480 */
3481 if (buf->b_changed || isNetbeansModified(buf))
3482 {
Bram Moolenaar009b2592004-10-24 19:18:58 +00003483 --no_wait_return; /* may wait for return now */
3484 msg_scroll = msg_save;
3485 netbeans_save_buffer(buf); /* no error checking... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003486 return retval;
3487 }
3488 else
3489 {
3490 errnum = (char_u *)"E656: ";
Bram Moolenaared0e7452008-06-27 19:17:34 +00003491 errmsg = (char_u *)_("NetBeans disallows writes of unmodified buffers");
Bram Moolenaar071d4272004-06-13 20:20:40 +00003492 buffer = NULL;
3493 goto fail;
3494 }
3495 }
3496 else
3497 {
3498 errnum = (char_u *)"E657: ";
3499 errmsg = (char_u *)_("Partial writes disallowed for NetBeans buffers");
3500 buffer = NULL;
3501 goto fail;
3502 }
3503 }
3504#endif
3505
3506 if (shortmess(SHM_OVER) && !exiting)
3507 msg_scroll = FALSE; /* overwrite previous file message */
3508 else
3509 msg_scroll = TRUE; /* don't overwrite previous file message */
3510 if (!filtering)
3511 filemess(buf,
3512#ifndef UNIX
3513 sfname,
3514#else
3515 fname,
3516#endif
3517 (char_u *)"", 0); /* show that we are busy */
3518 msg_scroll = FALSE; /* always overwrite the file message now */
3519
3520 buffer = alloc(BUFSIZE);
3521 if (buffer == NULL) /* can't allocate big buffer, use small
3522 * one (to be able to write when out of
3523 * memory) */
3524 {
3525 buffer = smallbuf;
3526 bufsize = SMBUFSIZE;
3527 }
3528 else
3529 bufsize = BUFSIZE;
3530
3531 /*
3532 * Get information about original file (if there is one).
3533 */
Bram Moolenaar53076832015-12-31 19:53:21 +01003534#if defined(UNIX)
Bram Moolenaar6f192452007-11-08 19:49:02 +00003535 st_old.st_dev = 0;
3536 st_old.st_ino = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003537 perm = -1;
3538 if (mch_stat((char *)fname, &st_old) < 0)
3539 newfile = TRUE;
3540 else
3541 {
3542 perm = st_old.st_mode;
3543 if (!S_ISREG(st_old.st_mode)) /* not a file */
3544 {
3545 if (S_ISDIR(st_old.st_mode))
3546 {
3547 errnum = (char_u *)"E502: ";
3548 errmsg = (char_u *)_("is a directory");
3549 goto fail;
3550 }
3551 if (mch_nodetype(fname) != NODE_WRITABLE)
3552 {
3553 errnum = (char_u *)"E503: ";
3554 errmsg = (char_u *)_("is not a file or writable device");
3555 goto fail;
3556 }
3557 /* It's a device of some kind (or a fifo) which we can write to
3558 * but for which we can't make a backup. */
3559 device = TRUE;
3560 newfile = TRUE;
3561 perm = -1;
3562 }
3563 }
3564#else /* !UNIX */
3565 /*
3566 * Check for a writable device name.
3567 */
3568 c = mch_nodetype(fname);
3569 if (c == NODE_OTHER)
3570 {
3571 errnum = (char_u *)"E503: ";
3572 errmsg = (char_u *)_("is not a file or writable device");
3573 goto fail;
3574 }
3575 if (c == NODE_WRITABLE)
3576 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003577# if defined(MSWIN)
Bram Moolenaar043545e2006-10-10 16:44:07 +00003578 /* MS-Windows allows opening a device, but we will probably get stuck
3579 * trying to write to it. */
3580 if (!p_odev)
3581 {
3582 errnum = (char_u *)"E796: ";
3583 errmsg = (char_u *)_("writing to device disabled with 'opendevice' option");
3584 goto fail;
3585 }
3586# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003587 device = TRUE;
3588 newfile = TRUE;
3589 perm = -1;
3590 }
3591 else
3592 {
3593 perm = mch_getperm(fname);
3594 if (perm < 0)
3595 newfile = TRUE;
3596 else if (mch_isdir(fname))
3597 {
3598 errnum = (char_u *)"E502: ";
3599 errmsg = (char_u *)_("is a directory");
3600 goto fail;
3601 }
3602 if (overwriting)
3603 (void)mch_stat((char *)fname, &st_old);
3604 }
3605#endif /* !UNIX */
3606
3607 if (!device && !newfile)
3608 {
3609 /*
3610 * Check if the file is really writable (when renaming the file to
3611 * make a backup we won't discover it later).
3612 */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003613 file_readonly = check_file_readonly(fname, (int)perm);
3614
Bram Moolenaar071d4272004-06-13 20:20:40 +00003615 if (!forceit && file_readonly)
3616 {
3617 if (vim_strchr(p_cpo, CPO_FWRITE) != NULL)
3618 {
3619 errnum = (char_u *)"E504: ";
3620 errmsg = (char_u *)_(err_readonly);
3621 }
3622 else
3623 {
3624 errnum = (char_u *)"E505: ";
3625 errmsg = (char_u *)_("is read-only (add ! to override)");
3626 }
3627 goto fail;
3628 }
3629
3630 /*
3631 * Check if the timestamp hasn't changed since reading the file.
3632 */
3633 if (overwriting)
3634 {
3635 retval = check_mtime(buf, &st_old);
3636 if (retval == FAIL)
3637 goto fail;
3638 }
3639 }
3640
3641#ifdef HAVE_ACL
3642 /*
3643 * For systems that support ACL: get the ACL from the original file.
3644 */
3645 if (!newfile)
3646 acl = mch_get_acl(fname);
3647#endif
3648
3649 /*
3650 * If 'backupskip' is not empty, don't make a backup for some files.
3651 */
3652 dobackup = (p_wb || p_bk || *p_pm != NUL);
3653#ifdef FEAT_WILDIGN
3654 if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname))
3655 dobackup = FALSE;
3656#endif
3657
3658 /*
3659 * Save the value of got_int and reset it. We don't want a previous
3660 * interruption cancel writing, only hitting CTRL-C while writing should
3661 * abort it.
3662 */
3663 prev_got_int = got_int;
3664 got_int = FALSE;
3665
3666 /* Mark the buffer as 'being saved' to prevent changed buffer warnings */
3667 buf->b_saving = TRUE;
3668
3669 /*
3670 * If we are not appending or filtering, the file exists, and the
3671 * 'writebackup', 'backup' or 'patchmode' option is set, need a backup.
3672 * When 'patchmode' is set also make a backup when appending.
3673 *
3674 * Do not make any backup, if 'writebackup' and 'backup' are both switched
3675 * off. This helps when editing large files on almost-full disks.
3676 */
3677 if (!(append && *p_pm == NUL) && !filtering && perm >= 0 && dobackup)
3678 {
3679#if defined(UNIX) || defined(WIN32)
Bram Moolenaar8767f522016-07-01 17:17:39 +02003680 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003681#endif
3682
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003683 if ((bkc & BKC_YES) || append) /* "yes" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003684 backup_copy = TRUE;
3685#if defined(UNIX) || defined(WIN32)
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003686 else if ((bkc & BKC_AUTO)) /* "auto" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003687 {
3688 int i;
3689
3690# ifdef UNIX
3691 /*
3692 * Don't rename the file when:
3693 * - it's a hard link
3694 * - it's a symbolic link
3695 * - we don't have write permission in the directory
3696 * - we can't set the owner/group of the new file
3697 */
3698 if (st_old.st_nlink > 1
3699 || mch_lstat((char *)fname, &st) < 0
3700 || st.st_dev != st_old.st_dev
Bram Moolenaara5792f52005-11-23 21:25:05 +00003701 || st.st_ino != st_old.st_ino
3702# ifndef HAVE_FCHOWN
3703 || st.st_uid != st_old.st_uid
3704 || st.st_gid != st_old.st_gid
3705# endif
3706 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003707 backup_copy = TRUE;
3708 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003709# else
3710# ifdef WIN32
3711 /* On NTFS file systems hard links are possible. */
3712 if (mch_is_linked(fname))
3713 backup_copy = TRUE;
3714 else
3715# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003716# endif
3717 {
3718 /*
3719 * Check if we can create a file and set the owner/group to
3720 * the ones from the original file.
3721 * First find a file name that doesn't exist yet (use some
3722 * arbitrary numbers).
3723 */
3724 STRCPY(IObuff, fname);
3725 for (i = 4913; ; i += 123)
3726 {
3727 sprintf((char *)gettail(IObuff), "%d", i);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003728 if (mch_lstat((char *)IObuff, &st) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003729 break;
3730 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00003731 fd = mch_open((char *)IObuff,
3732 O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003733 if (fd < 0) /* can't write in directory */
3734 backup_copy = TRUE;
3735 else
3736 {
3737# ifdef UNIX
Bram Moolenaara5792f52005-11-23 21:25:05 +00003738# ifdef HAVE_FCHOWN
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00003739 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003740# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003741 if (mch_stat((char *)IObuff, &st) < 0
3742 || st.st_uid != st_old.st_uid
3743 || st.st_gid != st_old.st_gid
Bram Moolenaar78a15312009-05-15 19:33:18 +00003744 || (long)st.st_mode != perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003745 backup_copy = TRUE;
3746# endif
Bram Moolenaar98358622005-11-28 22:58:23 +00003747 /* Close the file before removing it, on MS-Windows we
3748 * can't delete an open file. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003749 close(fd);
Bram Moolenaar98358622005-11-28 22:58:23 +00003750 mch_remove(IObuff);
Bram Moolenaar3479c5d2010-08-08 18:46:06 +02003751# ifdef MSWIN
3752 /* MS-Windows may trigger a virus scanner to open the
3753 * file, we can't delete it then. Keep trying for half a
3754 * second. */
3755 {
3756 int try;
3757
3758 for (try = 0; try < 10; ++try)
3759 {
3760 if (mch_lstat((char *)IObuff, &st) < 0)
3761 break;
3762 ui_delay(50L, TRUE); /* wait 50 msec */
3763 mch_remove(IObuff);
3764 }
3765 }
3766# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003767 }
3768 }
3769 }
3770
Bram Moolenaar071d4272004-06-13 20:20:40 +00003771 /*
3772 * Break symlinks and/or hardlinks if we've been asked to.
3773 */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003774 if ((bkc & BKC_BREAKSYMLINK) || (bkc & BKC_BREAKHARDLINK))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003775 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003776# ifdef UNIX
Bram Moolenaar071d4272004-06-13 20:20:40 +00003777 int lstat_res;
3778
3779 lstat_res = mch_lstat((char *)fname, &st);
3780
3781 /* Symlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003782 if ((bkc & BKC_BREAKSYMLINK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003783 && lstat_res == 0
3784 && st.st_ino != st_old.st_ino)
3785 backup_copy = FALSE;
3786
3787 /* Hardlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003788 if ((bkc & BKC_BREAKHARDLINK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003789 && st_old.st_nlink > 1
3790 && (lstat_res != 0 || st.st_ino == st_old.st_ino))
3791 backup_copy = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003792# else
3793# if defined(WIN32)
3794 /* Symlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003795 if ((bkc & BKC_BREAKSYMLINK) && mch_is_symbolic_link(fname))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003796 backup_copy = FALSE;
3797
3798 /* Hardlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003799 if ((bkc & BKC_BREAKHARDLINK) && mch_is_hard_link(fname))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003800 backup_copy = FALSE;
3801# endif
3802# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003803 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003804
3805#endif
3806
3807 /* make sure we have a valid backup extension to use */
3808 if (*p_bex == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003809 backup_ext = (char_u *)".bak";
Bram Moolenaar071d4272004-06-13 20:20:40 +00003810 else
3811 backup_ext = p_bex;
3812
3813 if (backup_copy
3814 && (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) >= 0)
3815 {
3816 int bfd;
3817 char_u *copybuf, *wp;
3818 int some_error = FALSE;
Bram Moolenaar8767f522016-07-01 17:17:39 +02003819 stat_T st_new;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003820 char_u *dirp;
3821 char_u *rootname;
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003822#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003823 int did_set_shortname;
3824#endif
3825
3826 copybuf = alloc(BUFSIZE + 1);
3827 if (copybuf == NULL)
3828 {
3829 some_error = TRUE; /* out of memory */
3830 goto nobackup;
3831 }
3832
3833 /*
3834 * Try to make the backup in each directory in the 'bdir' option.
3835 *
3836 * Unix semantics has it, that we may have a writable file,
3837 * that cannot be recreated with a simple open(..., O_CREAT, ) e.g:
3838 * - the directory is not writable,
3839 * - the file may be a symbolic link,
3840 * - the file may belong to another user/group, etc.
3841 *
3842 * For these reasons, the existing writable file must be truncated
3843 * and reused. Creation of a backup COPY will be attempted.
3844 */
3845 dirp = p_bdir;
3846 while (*dirp)
3847 {
3848#ifdef UNIX
3849 st_new.st_ino = 0;
3850 st_new.st_dev = 0;
3851 st_new.st_gid = 0;
3852#endif
3853
3854 /*
3855 * Isolate one directory name, using an entry in 'bdir'.
3856 */
3857 (void)copy_option_part(&dirp, copybuf, BUFSIZE, ",");
3858 rootname = get_file_in_dir(fname, copybuf);
3859 if (rootname == NULL)
3860 {
3861 some_error = TRUE; /* out of memory */
3862 goto nobackup;
3863 }
3864
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003865#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003866 did_set_shortname = FALSE;
3867#endif
3868
3869 /*
3870 * May try twice if 'shortname' not set.
3871 */
3872 for (;;)
3873 {
3874 /*
3875 * Make backup file name.
3876 */
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003877 backup = buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003878 rootname, backup_ext, FALSE);
3879 if (backup == NULL)
3880 {
3881 vim_free(rootname);
3882 some_error = TRUE; /* out of memory */
3883 goto nobackup;
3884 }
3885
3886 /*
3887 * Check if backup file already exists.
3888 */
3889 if (mch_stat((char *)backup, &st_new) >= 0)
3890 {
3891#ifdef UNIX
3892 /*
3893 * Check if backup file is same as original file.
3894 * May happen when modname() gave the same file back.
3895 * E.g. silly link, or file name-length reached.
3896 * If we don't check here, we either ruin the file
3897 * when copying or erase it after writing. jw.
3898 */
3899 if (st_new.st_dev == st_old.st_dev
3900 && st_new.st_ino == st_old.st_ino)
3901 {
3902 vim_free(backup);
3903 backup = NULL; /* no backup file to delete */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003904 /*
3905 * may try again with 'shortname' set
3906 */
3907 if (!(buf->b_shortname || buf->b_p_sn))
3908 {
3909 buf->b_shortname = TRUE;
3910 did_set_shortname = TRUE;
3911 continue;
3912 }
3913 /* setting shortname didn't help */
3914 if (did_set_shortname)
3915 buf->b_shortname = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003916 break;
3917 }
3918#endif
3919
3920 /*
3921 * If we are not going to keep the backup file, don't
3922 * delete an existing one, try to use another name.
3923 * Change one character, just before the extension.
3924 */
3925 if (!p_bk)
3926 {
3927 wp = backup + STRLEN(backup) - 1
3928 - STRLEN(backup_ext);
3929 if (wp < backup) /* empty file name ??? */
3930 wp = backup;
3931 *wp = 'z';
3932 while (*wp > 'a'
3933 && mch_stat((char *)backup, &st_new) >= 0)
3934 --*wp;
3935 /* They all exist??? Must be something wrong. */
3936 if (*wp == 'a')
3937 {
3938 vim_free(backup);
3939 backup = NULL;
3940 }
3941 }
3942 }
3943 break;
3944 }
3945 vim_free(rootname);
3946
3947 /*
3948 * Try to create the backup file
3949 */
3950 if (backup != NULL)
3951 {
3952 /* remove old backup, if present */
3953 mch_remove(backup);
3954 /* Open with O_EXCL to avoid the file being created while
3955 * we were sleeping (symlink hacker attack?) */
3956 bfd = mch_open((char *)backup,
Bram Moolenaara5792f52005-11-23 21:25:05 +00003957 O_WRONLY|O_CREAT|O_EXTRA|O_EXCL|O_NOFOLLOW,
3958 perm & 0777);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003959 if (bfd < 0)
3960 {
3961 vim_free(backup);
3962 backup = NULL;
3963 }
3964 else
3965 {
3966 /* set file protection same as original file, but
3967 * strip s-bit */
3968 (void)mch_setperm(backup, perm & 0777);
3969
3970#ifdef UNIX
3971 /*
3972 * Try to set the group of the backup same as the
3973 * original file. If this fails, set the protection
3974 * bits for the group same as the protection bits for
3975 * others.
3976 */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003977 if (st_new.st_gid != st_old.st_gid
Bram Moolenaar071d4272004-06-13 20:20:40 +00003978# ifdef HAVE_FCHOWN /* sequent-ptx lacks fchown() */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003979 && fchown(bfd, (uid_t)-1, st_old.st_gid) != 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00003980# endif
3981 )
3982 mch_setperm(backup,
3983 (perm & 0707) | ((perm & 07) << 3));
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02003984# if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00003985 mch_copy_sec(fname, backup);
3986# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003987#endif
3988
3989 /*
3990 * copy the file.
3991 */
3992 write_info.bw_fd = bfd;
3993 write_info.bw_buf = copybuf;
3994#ifdef HAS_BW_FLAGS
3995 write_info.bw_flags = FIO_NOCONVERT;
3996#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01003997 while ((write_info.bw_len = read_eintr(fd, copybuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003998 BUFSIZE)) > 0)
3999 {
4000 if (buf_write_bytes(&write_info) == FAIL)
4001 {
4002 errmsg = (char_u *)_("E506: Can't write to backup file (add ! to override)");
4003 break;
4004 }
4005 ui_breakcheck();
4006 if (got_int)
4007 {
4008 errmsg = (char_u *)_(e_interr);
4009 break;
4010 }
4011 }
4012
4013 if (close(bfd) < 0 && errmsg == NULL)
4014 errmsg = (char_u *)_("E507: Close error for backup file (add ! to override)");
4015 if (write_info.bw_len < 0)
4016 errmsg = (char_u *)_("E508: Can't read file for backup (add ! to override)");
4017#ifdef UNIX
4018 set_file_time(backup, st_old.st_atime, st_old.st_mtime);
4019#endif
4020#ifdef HAVE_ACL
4021 mch_set_acl(backup, acl);
4022#endif
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004023#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004024 mch_copy_sec(fname, backup);
4025#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004026 break;
4027 }
4028 }
4029 }
4030 nobackup:
4031 close(fd); /* ignore errors for closing read file */
4032 vim_free(copybuf);
4033
4034 if (backup == NULL && errmsg == NULL)
4035 errmsg = (char_u *)_("E509: Cannot create backup file (add ! to override)");
4036 /* ignore errors when forceit is TRUE */
4037 if ((some_error || errmsg != NULL) && !forceit)
4038 {
4039 retval = FAIL;
4040 goto fail;
4041 }
4042 errmsg = NULL;
4043 }
4044 else
4045 {
4046 char_u *dirp;
4047 char_u *p;
4048 char_u *rootname;
4049
4050 /*
4051 * Make a backup by renaming the original file.
4052 */
4053 /*
4054 * If 'cpoptions' includes the "W" flag, we don't want to
4055 * overwrite a read-only file. But rename may be possible
4056 * anyway, thus we need an extra check here.
4057 */
4058 if (file_readonly && vim_strchr(p_cpo, CPO_FWRITE) != NULL)
4059 {
4060 errnum = (char_u *)"E504: ";
4061 errmsg = (char_u *)_(err_readonly);
4062 goto fail;
4063 }
4064
4065 /*
4066 *
4067 * Form the backup file name - change path/fo.o.h to
4068 * path/fo.o.h.bak Try all directories in 'backupdir', first one
4069 * that works is used.
4070 */
4071 dirp = p_bdir;
4072 while (*dirp)
4073 {
4074 /*
4075 * Isolate one directory name and make the backup file name.
4076 */
4077 (void)copy_option_part(&dirp, IObuff, IOSIZE, ",");
4078 rootname = get_file_in_dir(fname, IObuff);
4079 if (rootname == NULL)
4080 backup = NULL;
4081 else
4082 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01004083 backup = buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00004084 rootname, backup_ext, FALSE);
4085 vim_free(rootname);
4086 }
4087
4088 if (backup != NULL)
4089 {
4090 /*
4091 * If we are not going to keep the backup file, don't
4092 * delete an existing one, try to use another name.
4093 * Change one character, just before the extension.
4094 */
4095 if (!p_bk && mch_getperm(backup) >= 0)
4096 {
4097 p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext);
4098 if (p < backup) /* empty file name ??? */
4099 p = backup;
4100 *p = 'z';
4101 while (*p > 'a' && mch_getperm(backup) >= 0)
4102 --*p;
4103 /* They all exist??? Must be something wrong! */
4104 if (*p == 'a')
4105 {
4106 vim_free(backup);
4107 backup = NULL;
4108 }
4109 }
4110 }
4111 if (backup != NULL)
4112 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004113 /*
Bram Moolenaarbfd8fc02005-09-20 23:22:24 +00004114 * Delete any existing backup and move the current version
4115 * to the backup. For safety, we don't remove the backup
4116 * until the write has finished successfully. And if the
4117 * 'backup' option is set, leave it around.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004118 */
4119 /*
4120 * If the renaming of the original file to the backup file
4121 * works, quit here.
4122 */
4123 if (vim_rename(fname, backup) == 0)
4124 break;
4125
4126 vim_free(backup); /* don't do the rename below */
4127 backup = NULL;
4128 }
4129 }
4130 if (backup == NULL && !forceit)
4131 {
4132 errmsg = (char_u *)_("E510: Can't make backup file (add ! to override)");
4133 goto fail;
4134 }
4135 }
4136 }
4137
Bram Moolenaar53076832015-12-31 19:53:21 +01004138#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004139 /* When using ":w!" and the file was read-only: make it writable */
4140 if (forceit && perm >= 0 && !(perm & 0200) && st_old.st_uid == getuid()
4141 && vim_strchr(p_cpo, CPO_FWRITE) == NULL)
4142 {
4143 perm |= 0200;
4144 (void)mch_setperm(fname, perm);
4145 made_writable = TRUE;
4146 }
4147#endif
4148
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004149 /* When using ":w!" and writing to the current file, 'readonly' makes no
Bram Moolenaar4399ef42005-02-12 14:29:27 +00004150 * sense, reset it, unless 'Z' appears in 'cpoptions'. */
4151 if (forceit && overwriting && vim_strchr(p_cpo, CPO_KEEPRO) == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004152 {
4153 buf->b_p_ro = FALSE;
4154#ifdef FEAT_TITLE
4155 need_maketitle = TRUE; /* set window title later */
4156#endif
4157#ifdef FEAT_WINDOWS
4158 status_redraw_all(); /* redraw status lines later */
4159#endif
4160 }
4161
4162 if (end > buf->b_ml.ml_line_count)
4163 end = buf->b_ml.ml_line_count;
4164 if (buf->b_ml.ml_flags & ML_EMPTY)
4165 start = end + 1;
4166
4167 /*
4168 * If the original file is being overwritten, there is a small chance that
4169 * we crash in the middle of writing. Therefore the file is preserved now.
4170 * This makes all block numbers positive so that recovery does not need
4171 * the original file.
4172 * Don't do this if there is a backup file and we are exiting.
4173 */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004174 if (reset_changed && !newfile && overwriting
Bram Moolenaar071d4272004-06-13 20:20:40 +00004175 && !(exiting && backup != NULL))
4176 {
4177 ml_preserve(buf, FALSE);
4178 if (got_int)
4179 {
4180 errmsg = (char_u *)_(e_interr);
4181 goto restore_backup;
4182 }
4183 }
4184
4185#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
4186 /*
4187 * Before risking to lose the original file verify if there's
4188 * a resource fork to preserve, and if cannot be done warn
4189 * the users. This happens when overwriting without backups.
4190 */
4191 if (backup == NULL && overwriting && !append)
4192 if (mch_has_resource_fork(fname))
4193 {
4194 errmsg = (char_u *)_("E460: The resource fork would be lost (add ! to override)");
4195 goto restore_backup;
4196 }
4197#endif
4198
4199#ifdef VMS
4200 vms_remove_version(fname); /* remove version */
4201#endif
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00004202 /* Default: write the file directly. May write to a temp file for
Bram Moolenaar071d4272004-06-13 20:20:40 +00004203 * multi-byte conversion. */
4204 wfname = fname;
4205
4206#ifdef FEAT_MBYTE
4207 /* Check for forced 'fileencoding' from "++opt=val" argument. */
4208 if (eap != NULL && eap->force_enc != 0)
4209 {
4210 fenc = eap->cmd + eap->force_enc;
4211 fenc = enc_canonize(fenc);
4212 fenc_tofree = fenc;
4213 }
4214 else
4215 fenc = buf->b_p_fenc;
4216
4217 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004218 * Check if the file needs to be converted.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004219 */
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004220 converted = need_conversion(fenc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004221
4222 /*
4223 * Check if UTF-8 to UCS-2/4 or Latin1 conversion needs to be done. Or
4224 * Latin1 to Unicode conversion. This is handled in buf_write_bytes().
4225 * Prepare the flags for it and allocate bw_conv_buf when needed.
4226 */
4227 if (converted && (enc_utf8 || STRCMP(p_enc, "latin1") == 0))
4228 {
4229 wb_flags = get_fio_flags(fenc);
4230 if (wb_flags & (FIO_UCS2 | FIO_UCS4 | FIO_UTF16 | FIO_UTF8))
4231 {
4232 /* Need to allocate a buffer to translate into. */
4233 if (wb_flags & (FIO_UCS2 | FIO_UTF16 | FIO_UTF8))
4234 write_info.bw_conv_buflen = bufsize * 2;
4235 else /* FIO_UCS4 */
4236 write_info.bw_conv_buflen = bufsize * 4;
4237 write_info.bw_conv_buf
4238 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4239 if (write_info.bw_conv_buf == NULL)
4240 end = 0;
4241 }
4242 }
4243
4244# ifdef WIN3264
4245 if (converted && wb_flags == 0 && (wb_flags = get_win_fio_flags(fenc)) != 0)
4246 {
4247 /* Convert UTF-8 -> UCS-2 and UCS-2 -> DBCS. Worst-case * 4: */
4248 write_info.bw_conv_buflen = bufsize * 4;
4249 write_info.bw_conv_buf
4250 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4251 if (write_info.bw_conv_buf == NULL)
4252 end = 0;
4253 }
4254# endif
4255
4256# ifdef MACOS_X
4257 if (converted && wb_flags == 0 && (wb_flags = get_mac_fio_flags(fenc)) != 0)
4258 {
4259 write_info.bw_conv_buflen = bufsize * 3;
4260 write_info.bw_conv_buf
4261 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4262 if (write_info.bw_conv_buf == NULL)
4263 end = 0;
4264 }
4265# endif
4266
4267# if defined(FEAT_EVAL) || defined(USE_ICONV)
4268 if (converted && wb_flags == 0)
4269 {
4270# ifdef USE_ICONV
4271 /*
4272 * Use iconv() conversion when conversion is needed and it's not done
4273 * internally.
4274 */
4275 write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc,
4276 enc_utf8 ? (char_u *)"utf-8" : p_enc);
4277 if (write_info.bw_iconv_fd != (iconv_t)-1)
4278 {
4279 /* We're going to use iconv(), allocate a buffer to convert in. */
4280 write_info.bw_conv_buflen = bufsize * ICONV_MULT;
4281 write_info.bw_conv_buf
4282 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4283 if (write_info.bw_conv_buf == NULL)
4284 end = 0;
4285 write_info.bw_first = TRUE;
4286 }
4287# ifdef FEAT_EVAL
4288 else
4289# endif
4290# endif
4291
4292# ifdef FEAT_EVAL
4293 /*
4294 * When the file needs to be converted with 'charconvert' after
4295 * writing, write to a temp file instead and let the conversion
4296 * overwrite the original file.
4297 */
4298 if (*p_ccv != NUL)
4299 {
Bram Moolenaare5c421c2015-03-31 13:33:08 +02004300 wfname = vim_tempname('w', FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004301 if (wfname == NULL) /* Can't write without a tempfile! */
4302 {
4303 errmsg = (char_u *)_("E214: Can't find temp file for writing");
4304 goto restore_backup;
4305 }
4306 }
4307# endif
4308 }
4309# endif
4310 if (converted && wb_flags == 0
4311# ifdef USE_ICONV
4312 && write_info.bw_iconv_fd == (iconv_t)-1
4313# endif
4314# ifdef FEAT_EVAL
4315 && wfname == fname
4316# endif
4317 )
4318 {
4319 if (!forceit)
4320 {
4321 errmsg = (char_u *)_("E213: Cannot convert (add ! to write without conversion)");
4322 goto restore_backup;
4323 }
4324 notconverted = TRUE;
4325 }
4326#endif
4327
4328 /*
4329 * Open the file "wfname" for writing.
4330 * We may try to open the file twice: If we can't write to the
4331 * file and forceit is TRUE we delete the existing file and try to create
4332 * a new one. If this still fails we may have lost the original file!
4333 * (this may happen when the user reached his quotum for number of files).
4334 * Appending will fail if the file does not exist and forceit is FALSE.
4335 */
4336 while ((fd = mch_open((char *)wfname, O_WRONLY | O_EXTRA | (append
4337 ? (forceit ? (O_APPEND | O_CREAT) : O_APPEND)
4338 : (O_CREAT | O_TRUNC))
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00004339 , perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004340 {
4341 /*
4342 * A forced write will try to create a new file if the old one is
4343 * still readonly. This may also happen when the directory is
4344 * read-only. In that case the mch_remove() will fail.
4345 */
4346 if (errmsg == NULL)
4347 {
4348#ifdef UNIX
Bram Moolenaar8767f522016-07-01 17:17:39 +02004349 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004350
4351 /* Don't delete the file when it's a hard or symbolic link. */
4352 if ((!newfile && st_old.st_nlink > 1)
4353 || (mch_lstat((char *)fname, &st) == 0
4354 && (st.st_dev != st_old.st_dev
4355 || st.st_ino != st_old.st_ino)))
4356 errmsg = (char_u *)_("E166: Can't open linked file for writing");
4357 else
4358#endif
4359 {
4360 errmsg = (char_u *)_("E212: Can't open file for writing");
4361 if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL
4362 && perm >= 0)
4363 {
4364#ifdef UNIX
4365 /* we write to the file, thus it should be marked
4366 writable after all */
4367 if (!(perm & 0200))
4368 made_writable = TRUE;
4369 perm |= 0200;
4370 if (st_old.st_uid != getuid() || st_old.st_gid != getgid())
4371 perm &= 0777;
4372#endif
4373 if (!append) /* don't remove when appending */
4374 mch_remove(wfname);
4375 continue;
4376 }
4377 }
4378 }
4379
4380restore_backup:
4381 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02004382 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004383
4384 /*
4385 * If we failed to open the file, we don't need a backup. Throw it
4386 * away. If we moved or removed the original file try to put the
4387 * backup in its place.
4388 */
4389 if (backup != NULL && wfname == fname)
4390 {
4391 if (backup_copy)
4392 {
4393 /*
4394 * There is a small chance that we removed the original,
4395 * try to move the copy in its place.
4396 * This may not work if the vim_rename() fails.
4397 * In that case we leave the copy around.
4398 */
4399 /* If file does not exist, put the copy in its place */
4400 if (mch_stat((char *)fname, &st) < 0)
4401 vim_rename(backup, fname);
4402 /* if original file does exist throw away the copy */
4403 if (mch_stat((char *)fname, &st) >= 0)
4404 mch_remove(backup);
4405 }
4406 else
4407 {
4408 /* try to put the original file back */
4409 vim_rename(backup, fname);
4410 }
4411 }
4412
4413 /* if original file no longer exists give an extra warning */
4414 if (!newfile && mch_stat((char *)fname, &st) < 0)
4415 end = 0;
4416 }
4417
4418#ifdef FEAT_MBYTE
4419 if (wfname != fname)
4420 vim_free(wfname);
4421#endif
4422 goto fail;
4423 }
4424 errmsg = NULL;
4425
4426#if defined(MACOS_CLASSIC) || defined(WIN3264)
4427 /* TODO: Is it need for MACOS_X? (Dany) */
4428 /*
4429 * On macintosh copy the original files attributes (i.e. the backup)
Bram Moolenaar7263a772007-05-10 17:35:54 +00004430 * This is done in order to preserve the resource fork and the
4431 * Finder attribute (label, comments, custom icons, file creator)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004432 */
4433 if (backup != NULL && overwriting && !append)
4434 {
4435 if (backup_copy)
4436 (void)mch_copy_file_attribute(wfname, backup);
4437 else
4438 (void)mch_copy_file_attribute(backup, wfname);
4439 }
4440
4441 if (!overwriting && !append)
4442 {
4443 if (buf->b_ffname != NULL)
4444 (void)mch_copy_file_attribute(buf->b_ffname, wfname);
Bram Moolenaar7263a772007-05-10 17:35:54 +00004445 /* Should copy resource fork */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004446 }
4447#endif
4448
4449 write_info.bw_fd = fd;
4450
4451#ifdef FEAT_CRYPT
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004452 if (*buf->b_p_key != NUL && !filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004453 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004454 char_u *header;
4455 int header_len;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004456
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004457 buf->b_cryptstate = crypt_create_for_writing(crypt_get_method_nr(buf),
4458 buf->b_p_key, &header, &header_len);
4459 if (buf->b_cryptstate == NULL || header == NULL)
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02004460 end = 0;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004461 else
4462 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004463 /* Write magic number, so that Vim knows how this file is
4464 * encrypted when reading it back. */
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02004465 write_info.bw_buf = header;
4466 write_info.bw_len = header_len;
4467 write_info.bw_flags = FIO_NOCONVERT;
4468 if (buf_write_bytes(&write_info) == FAIL)
4469 end = 0;
4470 wb_flags |= FIO_ENCRYPTED;
4471 vim_free(header);
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004472 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004473 }
4474#endif
4475
4476 write_info.bw_buf = buffer;
4477 nchars = 0;
4478
4479 /* use "++bin", "++nobin" or 'binary' */
4480 if (eap != NULL && eap->force_bin != 0)
4481 write_bin = (eap->force_bin == FORCE_BIN);
4482 else
4483 write_bin = buf->b_p_bin;
4484
4485#ifdef FEAT_MBYTE
4486 /*
4487 * The BOM is written just after the encryption magic number.
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004488 * Skip it when appending and the file already existed, the BOM only makes
4489 * sense at the start of the file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004490 */
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004491 if (buf->b_p_bomb && !write_bin && (!append || perm < 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004492 {
4493 write_info.bw_len = make_bom(buffer, fenc);
4494 if (write_info.bw_len > 0)
4495 {
4496 /* don't convert, do encryption */
4497 write_info.bw_flags = FIO_NOCONVERT | wb_flags;
4498 if (buf_write_bytes(&write_info) == FAIL)
4499 end = 0;
4500 else
4501 nchars += write_info.bw_len;
4502 }
4503 }
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004504 write_info.bw_start_lnum = start;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004505#endif
4506
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004507#ifdef FEAT_PERSISTENT_UNDO
4508 write_undo_file = (buf->b_p_udf && overwriting && !append
4509 && !filtering && reset_changed);
4510 if (write_undo_file)
4511 /* Prepare for computing the hash value of the text. */
4512 sha256_start(&sha_ctx);
4513#endif
4514
Bram Moolenaar071d4272004-06-13 20:20:40 +00004515 write_info.bw_len = bufsize;
4516#ifdef HAS_BW_FLAGS
4517 write_info.bw_flags = wb_flags;
4518#endif
4519 fileformat = get_fileformat_force(buf, eap);
4520 s = buffer;
4521 len = 0;
4522 for (lnum = start; lnum <= end; ++lnum)
4523 {
4524 /*
4525 * The next while loop is done once for each character written.
4526 * Keep it fast!
4527 */
4528 ptr = ml_get_buf(buf, lnum, FALSE) - 1;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004529#ifdef FEAT_PERSISTENT_UNDO
4530 if (write_undo_file)
Bram Moolenaar442b4222010-05-24 21:34:22 +02004531 sha256_update(&sha_ctx, ptr + 1, (UINT32_T)(STRLEN(ptr + 1) + 1));
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004532#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004533 while ((c = *++ptr) != NUL)
4534 {
4535 if (c == NL)
4536 *s = NUL; /* replace newlines with NULs */
4537 else if (c == CAR && fileformat == EOL_MAC)
4538 *s = NL; /* Mac: replace CRs with NLs */
4539 else
4540 *s = c;
4541 ++s;
4542 if (++len != bufsize)
4543 continue;
4544 if (buf_write_bytes(&write_info) == FAIL)
4545 {
4546 end = 0; /* write error: break loop */
4547 break;
4548 }
4549 nchars += bufsize;
4550 s = buffer;
4551 len = 0;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004552#ifdef FEAT_MBYTE
4553 write_info.bw_start_lnum = lnum;
4554#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004555 }
4556 /* write failed or last line has no EOL: stop here */
4557 if (end == 0
4558 || (lnum == end
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004559 && (write_bin || !buf->b_p_fixeol)
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004560 && (lnum == buf->b_no_eol_lnum
Bram Moolenaar071d4272004-06-13 20:20:40 +00004561 || (lnum == buf->b_ml.ml_line_count && !buf->b_p_eol))))
4562 {
4563 ++lnum; /* written the line, count it */
4564 no_eol = TRUE;
4565 break;
4566 }
4567 if (fileformat == EOL_UNIX)
4568 *s++ = NL;
4569 else
4570 {
4571 *s++ = CAR; /* EOL_MAC or EOL_DOS: write CR */
4572 if (fileformat == EOL_DOS) /* write CR-NL */
4573 {
4574 if (++len == bufsize)
4575 {
4576 if (buf_write_bytes(&write_info) == FAIL)
4577 {
4578 end = 0; /* write error: break loop */
4579 break;
4580 }
4581 nchars += bufsize;
4582 s = buffer;
4583 len = 0;
4584 }
4585 *s++ = NL;
4586 }
4587 }
4588 if (++len == bufsize && end)
4589 {
4590 if (buf_write_bytes(&write_info) == FAIL)
4591 {
4592 end = 0; /* write error: break loop */
4593 break;
4594 }
4595 nchars += bufsize;
4596 s = buffer;
4597 len = 0;
4598
4599 ui_breakcheck();
4600 if (got_int)
4601 {
4602 end = 0; /* Interrupted, break loop */
4603 break;
4604 }
4605 }
4606#ifdef VMS
4607 /*
4608 * On VMS there is a problem: newlines get added when writing blocks
4609 * at a time. Fix it by writing a line at a time.
4610 * This is much slower!
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004611 * Explanation: VAX/DECC RTL insists that records in some RMS
4612 * structures end with a newline (carriage return) character, and if
4613 * they don't it adds one.
4614 * With other RMS structures it works perfect without this fix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004615 */
Bram Moolenaarb52e2602007-10-29 21:38:54 +00004616 if (buf->b_fab_rfm == FAB$C_VFC
4617 || ((buf->b_fab_rat & (FAB$M_FTN | FAB$M_CR)) != 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004618 {
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004619 int b2write;
4620
4621 buf->b_fab_mrs = (buf->b_fab_mrs == 0
4622 ? MIN(4096, bufsize)
4623 : MIN(buf->b_fab_mrs, bufsize));
4624
4625 b2write = len;
4626 while (b2write > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004627 {
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004628 write_info.bw_len = MIN(b2write, buf->b_fab_mrs);
4629 if (buf_write_bytes(&write_info) == FAIL)
4630 {
4631 end = 0;
4632 break;
4633 }
4634 b2write -= MIN(b2write, buf->b_fab_mrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004635 }
4636 write_info.bw_len = bufsize;
4637 nchars += len;
4638 s = buffer;
4639 len = 0;
4640 }
4641#endif
4642 }
4643 if (len > 0 && end > 0)
4644 {
4645 write_info.bw_len = len;
4646 if (buf_write_bytes(&write_info) == FAIL)
4647 end = 0; /* write error */
4648 nchars += len;
4649 }
4650
4651#if defined(UNIX) && defined(HAVE_FSYNC)
4652 /* On many journalling file systems there is a bug that causes both the
4653 * original and the backup file to be lost when halting the system right
4654 * after writing the file. That's because only the meta-data is
4655 * journalled. Syncing the file slows down the system, but assures it has
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004656 * been written to disk and we don't lose it.
4657 * For a device do try the fsync() but don't complain if it does not work
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00004658 * (could be a pipe).
4659 * If the 'fsync' option is FALSE, don't fsync(). Useful for laptops. */
4660 if (p_fs && fsync(fd) != 0 && !device)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004661 {
4662 errmsg = (char_u *)_("E667: Fsync failed");
4663 end = 0;
4664 }
4665#endif
4666
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004667#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004668 /* Probably need to set the security context. */
4669 if (!backup_copy)
4670 mch_copy_sec(backup, wfname);
4671#endif
4672
Bram Moolenaara5792f52005-11-23 21:25:05 +00004673#ifdef UNIX
4674 /* When creating a new file, set its owner/group to that of the original
4675 * file. Get the new device and inode number. */
4676 if (backup != NULL && !backup_copy)
4677 {
4678# ifdef HAVE_FCHOWN
Bram Moolenaar8767f522016-07-01 17:17:39 +02004679 stat_T st;
Bram Moolenaara5792f52005-11-23 21:25:05 +00004680
4681 /* don't change the owner when it's already OK, some systems remove
4682 * permission or ACL stuff */
4683 if (mch_stat((char *)wfname, &st) < 0
4684 || st.st_uid != st_old.st_uid
4685 || st.st_gid != st_old.st_gid)
4686 {
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004687 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004688 if (perm >= 0) /* set permission again, may have changed */
4689 (void)mch_setperm(wfname, perm);
4690 }
4691# endif
4692 buf_setino(buf);
4693 }
Bram Moolenaarf1726cc2009-05-13 18:48:16 +00004694 else if (!buf->b_dev_valid)
Bram Moolenaar8fa04452005-12-23 22:13:51 +00004695 /* Set the inode when creating a new file. */
4696 buf_setino(buf);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004697#endif
4698
Bram Moolenaar071d4272004-06-13 20:20:40 +00004699 if (close(fd) != 0)
4700 {
4701 errmsg = (char_u *)_("E512: Close failed");
4702 end = 0;
4703 }
4704
4705#ifdef UNIX
4706 if (made_writable)
4707 perm &= ~0200; /* reset 'w' bit for security reasons */
4708#endif
4709 if (perm >= 0) /* set perm. of new file same as old file */
4710 (void)mch_setperm(wfname, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004711#ifdef HAVE_ACL
4712 /* Probably need to set the ACL before changing the user (can't set the
4713 * ACL on a file the user doesn't own). */
4714 if (!backup_copy)
4715 mch_set_acl(wfname, acl);
4716#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004717#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004718 if (buf->b_cryptstate != NULL)
4719 {
4720 crypt_free_state(buf->b_cryptstate);
4721 buf->b_cryptstate = NULL;
4722 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004723#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004724
Bram Moolenaar071d4272004-06-13 20:20:40 +00004725#if defined(FEAT_MBYTE) && defined(FEAT_EVAL)
4726 if (wfname != fname)
4727 {
4728 /*
4729 * The file was written to a temp file, now it needs to be converted
4730 * with 'charconvert' to (overwrite) the output file.
4731 */
4732 if (end != 0)
4733 {
4734 if (eval_charconvert(enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc,
4735 wfname, fname) == FAIL)
4736 {
4737 write_info.bw_conv_error = TRUE;
4738 end = 0;
4739 }
4740 }
4741 mch_remove(wfname);
4742 vim_free(wfname);
4743 }
4744#endif
4745
4746 if (end == 0)
4747 {
4748 if (errmsg == NULL)
4749 {
4750#ifdef FEAT_MBYTE
4751 if (write_info.bw_conv_error)
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004752 {
4753 if (write_info.bw_conv_error_lnum == 0)
4754 errmsg = (char_u *)_("E513: write error, conversion failed (make 'fenc' empty to override)");
4755 else
4756 {
4757 errmsg_allocated = TRUE;
4758 errmsg = alloc(300);
4759 vim_snprintf((char *)errmsg, 300, _("E513: write error, conversion failed in line %ld (make 'fenc' empty to override)"),
4760 (long)write_info.bw_conv_error_lnum);
4761 }
4762 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004763 else
4764#endif
4765 if (got_int)
4766 errmsg = (char_u *)_(e_interr);
4767 else
4768 errmsg = (char_u *)_("E514: write error (file system full?)");
4769 }
4770
4771 /*
4772 * If we have a backup file, try to put it in place of the new file,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004773 * because the new file is probably corrupt. This avoids losing the
Bram Moolenaar071d4272004-06-13 20:20:40 +00004774 * original file when trying to make a backup when writing the file a
4775 * second time.
4776 * When "backup_copy" is set we need to copy the backup over the new
4777 * file. Otherwise rename the backup file.
4778 * If this is OK, don't give the extra warning message.
4779 */
4780 if (backup != NULL)
4781 {
4782 if (backup_copy)
4783 {
4784 /* This may take a while, if we were interrupted let the user
4785 * know we got the message. */
4786 if (got_int)
4787 {
4788 MSG(_(e_interr));
4789 out_flush();
4790 }
4791 if ((fd = mch_open((char *)backup, O_RDONLY | O_EXTRA, 0)) >= 0)
4792 {
4793 if ((write_info.bw_fd = mch_open((char *)fname,
Bram Moolenaar9be038d2005-03-08 22:34:32 +00004794 O_WRONLY | O_CREAT | O_TRUNC | O_EXTRA,
4795 perm & 0777)) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004796 {
4797 /* copy the file. */
4798 write_info.bw_buf = smallbuf;
4799#ifdef HAS_BW_FLAGS
4800 write_info.bw_flags = FIO_NOCONVERT;
4801#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004802 while ((write_info.bw_len = read_eintr(fd, smallbuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004803 SMBUFSIZE)) > 0)
4804 if (buf_write_bytes(&write_info) == FAIL)
4805 break;
4806
4807 if (close(write_info.bw_fd) >= 0
4808 && write_info.bw_len == 0)
4809 end = 1; /* success */
4810 }
4811 close(fd); /* ignore errors for closing read file */
4812 }
4813 }
4814 else
4815 {
4816 if (vim_rename(backup, fname) == 0)
4817 end = 1;
4818 }
4819 }
4820 goto fail;
4821 }
4822
4823 lnum -= start; /* compute number of written lines */
4824 --no_wait_return; /* may wait for return now */
4825
4826#if !(defined(UNIX) || defined(VMS))
4827 fname = sfname; /* use shortname now, for the messages */
4828#endif
4829 if (!filtering)
4830 {
4831 msg_add_fname(buf, fname); /* put fname in IObuff with quotes */
4832 c = FALSE;
4833#ifdef FEAT_MBYTE
4834 if (write_info.bw_conv_error)
4835 {
4836 STRCAT(IObuff, _(" CONVERSION ERROR"));
4837 c = TRUE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004838 if (write_info.bw_conv_error_lnum != 0)
Bram Moolenaara800b422010-06-27 01:15:55 +02004839 vim_snprintf_add((char *)IObuff, IOSIZE, _(" in line %ld;"),
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004840 (long)write_info.bw_conv_error_lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004841 }
4842 else if (notconverted)
4843 {
4844 STRCAT(IObuff, _("[NOT converted]"));
4845 c = TRUE;
4846 }
4847 else if (converted)
4848 {
4849 STRCAT(IObuff, _("[converted]"));
4850 c = TRUE;
4851 }
4852#endif
4853 if (device)
4854 {
4855 STRCAT(IObuff, _("[Device]"));
4856 c = TRUE;
4857 }
4858 else if (newfile)
4859 {
4860 STRCAT(IObuff, shortmess(SHM_NEW) ? _("[New]") : _("[New File]"));
4861 c = TRUE;
4862 }
4863 if (no_eol)
4864 {
4865 msg_add_eol();
4866 c = TRUE;
4867 }
4868 /* may add [unix/dos/mac] */
4869 if (msg_add_fileformat(fileformat))
4870 c = TRUE;
4871#ifdef FEAT_CRYPT
4872 if (wb_flags & FIO_ENCRYPTED)
4873 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004874 crypt_append_msg(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004875 c = TRUE;
4876 }
4877#endif
4878 msg_add_lines(c, (long)lnum, nchars); /* add line/char count */
4879 if (!shortmess(SHM_WRITE))
4880 {
4881 if (append)
4882 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended"));
4883 else
4884 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written"));
4885 }
4886
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00004887 set_keep_msg(msg_trunc_attr(IObuff, FALSE, 0), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004888 }
4889
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004890 /* When written everything correctly: reset 'modified'. Unless not
4891 * writing to the original file and '+' is not in 'cpoptions'. */
Bram Moolenaar292ad192005-12-11 21:29:51 +00004892 if (reset_changed && whole && !append
Bram Moolenaar071d4272004-06-13 20:20:40 +00004893#ifdef FEAT_MBYTE
4894 && !write_info.bw_conv_error
4895#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004896 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL)
4897 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004898 {
4899 unchanged(buf, TRUE);
Bram Moolenaar086329d2014-10-31 19:51:36 +01004900#ifdef FEAT_AUTOCMD
4901 /* buf->b_changedtick is always incremented in unchanged() but that
4902 * should not trigger a TextChanged event. */
4903 if (last_changedtick + 1 == buf->b_changedtick
4904 && last_changedtick_buf == buf)
4905 last_changedtick = buf->b_changedtick;
4906#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004907 u_unchanged(buf);
Bram Moolenaar730cde92010-06-27 05:18:54 +02004908 u_update_save_nr(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004909 }
4910
4911 /*
4912 * If written to the current file, update the timestamp of the swap file
4913 * and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
4914 */
4915 if (overwriting)
4916 {
4917 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00004918 if (append)
4919 buf->b_flags &= ~BF_NEW;
4920 else
4921 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004922 }
4923
4924 /*
4925 * If we kept a backup until now, and we are in patch mode, then we make
4926 * the backup file our 'original' file.
4927 */
4928 if (*p_pm && dobackup)
4929 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01004930 char *org = (char *)buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00004931 fname, p_pm, FALSE);
4932
4933 if (backup != NULL)
4934 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02004935 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004936
4937 /*
4938 * If the original file does not exist yet
4939 * the current backup file becomes the original file
4940 */
4941 if (org == NULL)
4942 EMSG(_("E205: Patchmode: can't save original file"));
4943 else if (mch_stat(org, &st) < 0)
4944 {
4945 vim_rename(backup, (char_u *)org);
4946 vim_free(backup); /* don't delete the file */
4947 backup = NULL;
4948#ifdef UNIX
4949 set_file_time((char_u *)org, st_old.st_atime, st_old.st_mtime);
4950#endif
4951 }
4952 }
4953 /*
4954 * If there is no backup file, remember that a (new) file was
4955 * created.
4956 */
4957 else
4958 {
4959 int empty_fd;
4960
4961 if (org == NULL
Bram Moolenaara5792f52005-11-23 21:25:05 +00004962 || (empty_fd = mch_open(org,
4963 O_CREAT | O_EXTRA | O_EXCL | O_NOFOLLOW,
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00004964 perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004965 EMSG(_("E206: patchmode: can't touch empty original file"));
4966 else
4967 close(empty_fd);
4968 }
4969 if (org != NULL)
4970 {
4971 mch_setperm((char_u *)org, mch_getperm(fname) & 0777);
4972 vim_free(org);
4973 }
4974 }
4975
4976 /*
4977 * Remove the backup unless 'backup' option is set
4978 */
4979 if (!p_bk && backup != NULL && mch_remove(backup) != 0)
4980 EMSG(_("E207: Can't delete backup file"));
4981
4982#ifdef FEAT_SUN_WORKSHOP
4983 if (usingSunWorkShop)
4984 workshop_file_saved((char *) ffname);
4985#endif
4986
4987 goto nofail;
4988
4989 /*
4990 * Finish up. We get here either after failure or success.
4991 */
4992fail:
4993 --no_wait_return; /* may wait for return now */
4994nofail:
4995
4996 /* Done saving, we accept changed buffer warnings again */
4997 buf->b_saving = FALSE;
4998
4999 vim_free(backup);
5000 if (buffer != smallbuf)
5001 vim_free(buffer);
5002#ifdef FEAT_MBYTE
5003 vim_free(fenc_tofree);
5004 vim_free(write_info.bw_conv_buf);
5005# ifdef USE_ICONV
5006 if (write_info.bw_iconv_fd != (iconv_t)-1)
5007 {
5008 iconv_close(write_info.bw_iconv_fd);
5009 write_info.bw_iconv_fd = (iconv_t)-1;
5010 }
5011# endif
5012#endif
5013#ifdef HAVE_ACL
5014 mch_free_acl(acl);
5015#endif
5016
5017 if (errmsg != NULL)
5018 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005019 int numlen = errnum != NULL ? (int)STRLEN(errnum) : 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005020
5021 attr = hl_attr(HLF_E); /* set highlight for error messages */
5022 msg_add_fname(buf,
5023#ifndef UNIX
5024 sfname
5025#else
5026 fname
5027#endif
5028 ); /* put file name in IObuff with quotes */
5029 if (STRLEN(IObuff) + STRLEN(errmsg) + numlen >= IOSIZE)
5030 IObuff[IOSIZE - STRLEN(errmsg) - numlen - 1] = NUL;
5031 /* If the error message has the form "is ...", put the error number in
5032 * front of the file name. */
5033 if (errnum != NULL)
5034 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00005035 STRMOVE(IObuff + numlen, IObuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005036 mch_memmove(IObuff, errnum, (size_t)numlen);
5037 }
5038 STRCAT(IObuff, errmsg);
5039 emsg(IObuff);
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005040 if (errmsg_allocated)
5041 vim_free(errmsg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005042
5043 retval = FAIL;
5044 if (end == 0)
5045 {
5046 MSG_PUTS_ATTR(_("\nWARNING: Original file may be lost or damaged\n"),
5047 attr | MSG_HIST);
5048 MSG_PUTS_ATTR(_("don't quit the editor until the file is successfully written!"),
5049 attr | MSG_HIST);
5050
5051 /* Update the timestamp to avoid an "overwrite changed file"
5052 * prompt when writing again. */
5053 if (mch_stat((char *)fname, &st_old) >= 0)
5054 {
5055 buf_store_time(buf, &st_old, fname);
5056 buf->b_mtime_read = buf->b_mtime;
5057 }
5058 }
5059 }
5060 msg_scroll = msg_save;
5061
Bram Moolenaar55debbe2010-05-23 23:34:36 +02005062#ifdef FEAT_PERSISTENT_UNDO
5063 /*
5064 * When writing the whole file and 'undofile' is set, also write the undo
5065 * file.
5066 */
5067 if (retval == OK && write_undo_file)
5068 {
5069 char_u hash[UNDO_HASH_SIZE];
5070
5071 sha256_finish(&sha_ctx, hash);
5072 u_write_undo(NULL, FALSE, buf, hash);
5073 }
5074#endif
5075
Bram Moolenaar071d4272004-06-13 20:20:40 +00005076#ifdef FEAT_AUTOCMD
5077#ifdef FEAT_EVAL
5078 if (!should_abort(retval))
5079#else
5080 if (!got_int)
5081#endif
5082 {
5083 aco_save_T aco;
5084
Bram Moolenaar68a33fc2012-04-25 16:50:48 +02005085 curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */
5086
Bram Moolenaar071d4272004-06-13 20:20:40 +00005087 /*
5088 * Apply POST autocommands.
5089 * Careful: The autocommands may call buf_write() recursively!
5090 */
5091 aucmd_prepbuf(&aco, buf);
5092
5093 if (append)
5094 apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname,
5095 FALSE, curbuf, eap);
5096 else if (filtering)
5097 apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname,
5098 FALSE, curbuf, eap);
5099 else if (reset_changed && whole)
5100 apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname,
5101 FALSE, curbuf, eap);
5102 else
5103 apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname,
5104 FALSE, curbuf, eap);
5105
5106 /* restore curwin/curbuf and a few other things */
5107 aucmd_restbuf(&aco);
5108
5109#ifdef FEAT_EVAL
5110 if (aborting()) /* autocmds may abort script processing */
5111 retval = FALSE;
5112#endif
5113 }
5114#endif
5115
5116 got_int |= prev_got_int;
5117
5118#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
5119 /* Update machine specific information. */
5120 mch_post_buffer_write(buf);
5121#endif
5122 return retval;
5123}
5124
5125/*
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005126 * Set the name of the current buffer. Use when the buffer doesn't have a
5127 * name and a ":r" or ":w" command with a file name is used.
5128 */
5129 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005130set_rw_fname(char_u *fname, char_u *sfname)
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005131{
5132#ifdef FEAT_AUTOCMD
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005133 buf_T *buf = curbuf;
5134
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005135 /* It's like the unnamed buffer is deleted.... */
5136 if (curbuf->b_p_bl)
5137 apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
5138 apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf);
5139# ifdef FEAT_EVAL
5140 if (aborting()) /* autocmds may abort script processing */
5141 return FAIL;
5142# endif
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005143 if (curbuf != buf)
5144 {
5145 /* We are in another buffer now, don't do the renaming. */
5146 EMSG(_(e_auchangedbuf));
5147 return FAIL;
5148 }
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005149#endif
5150
5151 if (setfname(curbuf, fname, sfname, FALSE) == OK)
5152 curbuf->b_flags |= BF_NOTEDITED;
5153
5154#ifdef FEAT_AUTOCMD
5155 /* ....and a new named one is created */
5156 apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, curbuf);
5157 if (curbuf->b_p_bl)
5158 apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf);
5159# ifdef FEAT_EVAL
5160 if (aborting()) /* autocmds may abort script processing */
5161 return FAIL;
5162# endif
5163
5164 /* Do filetype detection now if 'filetype' is empty. */
5165 if (*curbuf->b_p_ft == NUL)
5166 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005167 if (au_has_group((char_u *)"filetypedetect"))
Bram Moolenaar1610d052016-06-09 22:53:01 +02005168 (void)do_doautocmd((char_u *)"filetypedetect BufRead", FALSE, NULL);
Bram Moolenaara3227e22006-03-08 21:32:40 +00005169 do_modelines(0);
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005170 }
5171#endif
5172
5173 return OK;
5174}
5175
5176/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00005177 * Put file name into IObuff with quotes.
5178 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005179 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005180msg_add_fname(buf_T *buf, char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005181{
5182 if (fname == NULL)
5183 fname = (char_u *)"-stdin-";
5184 home_replace(buf, fname, IObuff + 1, IOSIZE - 4, TRUE);
5185 IObuff[0] = '"';
5186 STRCAT(IObuff, "\" ");
5187}
5188
5189/*
5190 * Append message for text mode to IObuff.
5191 * Return TRUE if something appended.
5192 */
5193 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005194msg_add_fileformat(int eol_type)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005195{
5196#ifndef USE_CRNL
5197 if (eol_type == EOL_DOS)
5198 {
5199 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[dos]") : _("[dos format]"));
5200 return TRUE;
5201 }
5202#endif
5203#ifndef USE_CR
5204 if (eol_type == EOL_MAC)
5205 {
5206 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[mac]") : _("[mac format]"));
5207 return TRUE;
5208 }
5209#endif
5210#if defined(USE_CRNL) || defined(USE_CR)
5211 if (eol_type == EOL_UNIX)
5212 {
5213 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[unix]") : _("[unix format]"));
5214 return TRUE;
5215 }
5216#endif
5217 return FALSE;
5218}
5219
5220/*
5221 * Append line and character count to IObuff.
5222 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005223 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005224msg_add_lines(
5225 int insert_space,
5226 long lnum,
Bram Moolenaar8767f522016-07-01 17:17:39 +02005227 off_T nchars)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005228{
5229 char_u *p;
5230
5231 p = IObuff + STRLEN(IObuff);
5232
5233 if (insert_space)
5234 *p++ = ' ';
5235 if (shortmess(SHM_LINES))
Bram Moolenaarbde98102016-07-01 20:03:42 +02005236 vim_snprintf((char *)p, IOSIZE - (p - IObuff),
5237 "%ldL, %lldC", lnum, (varnumber_T)nchars);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005238 else
5239 {
5240 if (lnum == 1)
5241 STRCPY(p, _("1 line, "));
5242 else
5243 sprintf((char *)p, _("%ld lines, "), lnum);
5244 p += STRLEN(p);
5245 if (nchars == 1)
5246 STRCPY(p, _("1 character"));
5247 else
Bram Moolenaarbde98102016-07-01 20:03:42 +02005248 vim_snprintf((char *)p, IOSIZE - (p - IObuff),
5249 _("%lld characters"), (varnumber_T)nchars);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005250 }
5251}
5252
5253/*
5254 * Append message for missing line separator to IObuff.
5255 */
5256 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005257msg_add_eol(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005258{
5259 STRCAT(IObuff, shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]"));
5260}
5261
5262/*
5263 * Check modification time of file, before writing to it.
5264 * The size isn't checked, because using a tool like "gzip" takes care of
5265 * using the same timestamp but can't set the size.
5266 */
5267 static int
Bram Moolenaar8767f522016-07-01 17:17:39 +02005268check_mtime(buf_T *buf, stat_T *st)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005269{
5270 if (buf->b_mtime_read != 0
5271 && time_differs((long)st->st_mtime, buf->b_mtime_read))
5272 {
5273 msg_scroll = TRUE; /* don't overwrite messages here */
5274 msg_silent = 0; /* must give this prompt */
5275 /* don't use emsg() here, don't want to flush the buffers */
5276 MSG_ATTR(_("WARNING: The file has been changed since reading it!!!"),
5277 hl_attr(HLF_E));
5278 if (ask_yesno((char_u *)_("Do you really want to write to it"),
5279 TRUE) == 'n')
5280 return FAIL;
5281 msg_scroll = FALSE; /* always overwrite the file message now */
5282 }
5283 return OK;
5284}
5285
5286 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005287time_differs(long t1, long t2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005288{
Bram Moolenaar48e330a2016-02-23 14:53:34 +01005289#if defined(__linux__) || defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005290 /* On a FAT filesystem, esp. under Linux, there are only 5 bits to store
5291 * the seconds. Since the roundoff is done when flushing the inode, the
5292 * time may change unexpectedly by one second!!! */
5293 return (t1 - t2 > 1 || t2 - t1 > 1);
5294#else
5295 return (t1 != t2);
5296#endif
5297}
5298
5299/*
5300 * Call write() to write a number of bytes to the file.
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005301 * Handles encryption and 'encoding' conversion.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005302 *
5303 * Return FAIL for failure, OK otherwise.
5304 */
5305 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005306buf_write_bytes(struct bw_info *ip)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005307{
5308 int wlen;
5309 char_u *buf = ip->bw_buf; /* data to write */
5310 int len = ip->bw_len; /* length of data */
5311#ifdef HAS_BW_FLAGS
5312 int flags = ip->bw_flags; /* extra flags */
5313#endif
5314
5315#ifdef FEAT_MBYTE
5316 /*
5317 * Skip conversion when writing the crypt magic number or the BOM.
5318 */
5319 if (!(flags & FIO_NOCONVERT))
5320 {
5321 char_u *p;
5322 unsigned c;
5323 int n;
5324
5325 if (flags & FIO_UTF8)
5326 {
5327 /*
5328 * Convert latin1 in the buffer to UTF-8 in the file.
5329 */
5330 p = ip->bw_conv_buf; /* translate to buffer */
5331 for (wlen = 0; wlen < len; ++wlen)
5332 p += utf_char2bytes(buf[wlen], p);
5333 buf = ip->bw_conv_buf;
5334 len = (int)(p - ip->bw_conv_buf);
5335 }
5336 else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1))
5337 {
5338 /*
5339 * Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
5340 * Latin1 chars in the file.
5341 */
5342 if (flags & FIO_LATIN1)
5343 p = buf; /* translate in-place (can only get shorter) */
5344 else
5345 p = ip->bw_conv_buf; /* translate to buffer */
5346 for (wlen = 0; wlen < len; wlen += n)
5347 {
5348 if (wlen == 0 && ip->bw_restlen != 0)
5349 {
5350 int l;
5351
5352 /* Use remainder of previous call. Append the start of
5353 * buf[] to get a full sequence. Might still be too
5354 * short! */
5355 l = CONV_RESTLEN - ip->bw_restlen;
5356 if (l > len)
5357 l = len;
5358 mch_memmove(ip->bw_rest + ip->bw_restlen, buf, (size_t)l);
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005359 n = utf_ptr2len_len(ip->bw_rest, ip->bw_restlen + l);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005360 if (n > ip->bw_restlen + len)
5361 {
5362 /* We have an incomplete byte sequence at the end to
5363 * be written. We can't convert it without the
5364 * remaining bytes. Keep them for the next call. */
5365 if (ip->bw_restlen + len > CONV_RESTLEN)
5366 return FAIL;
5367 ip->bw_restlen += len;
5368 break;
5369 }
5370 if (n > 1)
5371 c = utf_ptr2char(ip->bw_rest);
5372 else
5373 c = ip->bw_rest[0];
5374 if (n >= ip->bw_restlen)
5375 {
5376 n -= ip->bw_restlen;
5377 ip->bw_restlen = 0;
5378 }
5379 else
5380 {
5381 ip->bw_restlen -= n;
5382 mch_memmove(ip->bw_rest, ip->bw_rest + n,
5383 (size_t)ip->bw_restlen);
5384 n = 0;
5385 }
5386 }
5387 else
5388 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005389 n = utf_ptr2len_len(buf + wlen, len - wlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005390 if (n > len - wlen)
5391 {
5392 /* We have an incomplete byte sequence at the end to
5393 * be written. We can't convert it without the
5394 * remaining bytes. Keep them for the next call. */
5395 if (len - wlen > CONV_RESTLEN)
5396 return FAIL;
5397 ip->bw_restlen = len - wlen;
5398 mch_memmove(ip->bw_rest, buf + wlen,
5399 (size_t)ip->bw_restlen);
5400 break;
5401 }
5402 if (n > 1)
5403 c = utf_ptr2char(buf + wlen);
5404 else
5405 c = buf[wlen];
5406 }
5407
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005408 if (ucs2bytes(c, &p, flags) && !ip->bw_conv_error)
5409 {
5410 ip->bw_conv_error = TRUE;
5411 ip->bw_conv_error_lnum = ip->bw_start_lnum;
5412 }
5413 if (c == NL)
5414 ++ip->bw_start_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005415 }
5416 if (flags & FIO_LATIN1)
5417 len = (int)(p - buf);
5418 else
5419 {
5420 buf = ip->bw_conv_buf;
5421 len = (int)(p - ip->bw_conv_buf);
5422 }
5423 }
5424
5425# ifdef WIN3264
5426 else if (flags & FIO_CODEPAGE)
5427 {
5428 /*
5429 * Convert UTF-8 or codepage to UCS-2 and then to MS-Windows
5430 * codepage.
5431 */
5432 char_u *from;
5433 size_t fromlen;
5434 char_u *to;
5435 int u8c;
5436 BOOL bad = FALSE;
5437 int needed;
5438
5439 if (ip->bw_restlen > 0)
5440 {
5441 /* Need to concatenate the remainder of the previous call and
5442 * the bytes of the current call. Use the end of the
5443 * conversion buffer for this. */
5444 fromlen = len + ip->bw_restlen;
5445 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5446 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5447 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5448 }
5449 else
5450 {
5451 from = buf;
5452 fromlen = len;
5453 }
5454
5455 to = ip->bw_conv_buf;
5456 if (enc_utf8)
5457 {
5458 /* Convert from UTF-8 to UCS-2, to the start of the buffer.
5459 * The buffer has been allocated to be big enough. */
5460 while (fromlen > 0)
5461 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005462 n = (int)utf_ptr2len_len(from, (int)fromlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005463 if (n > (int)fromlen) /* incomplete byte sequence */
5464 break;
5465 u8c = utf_ptr2char(from);
5466 *to++ = (u8c & 0xff);
5467 *to++ = (u8c >> 8);
5468 fromlen -= n;
5469 from += n;
5470 }
5471
5472 /* Copy remainder to ip->bw_rest[] to be used for the next
5473 * call. */
5474 if (fromlen > CONV_RESTLEN)
5475 {
5476 /* weird overlong sequence */
5477 ip->bw_conv_error = TRUE;
5478 return FAIL;
5479 }
5480 mch_memmove(ip->bw_rest, from, fromlen);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005481 ip->bw_restlen = (int)fromlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005482 }
5483 else
5484 {
5485 /* Convert from enc_codepage to UCS-2, to the start of the
5486 * buffer. The buffer has been allocated to be big enough. */
5487 ip->bw_restlen = 0;
5488 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005489 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005490 NULL, 0);
5491 if (needed == 0)
5492 {
5493 /* When conversion fails there may be a trailing byte. */
5494 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005495 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen - 1,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005496 NULL, 0);
5497 if (needed == 0)
5498 {
5499 /* Conversion doesn't work. */
5500 ip->bw_conv_error = TRUE;
5501 return FAIL;
5502 }
5503 /* Save the trailing byte for the next call. */
5504 ip->bw_rest[0] = from[fromlen - 1];
5505 ip->bw_restlen = 1;
5506 }
5507 needed = MultiByteToWideChar(enc_codepage, MB_ERR_INVALID_CHARS,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005508 (LPCSTR)from, (int)(fromlen - ip->bw_restlen),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005509 (LPWSTR)to, needed);
5510 if (needed == 0)
5511 {
5512 /* Safety check: Conversion doesn't work. */
5513 ip->bw_conv_error = TRUE;
5514 return FAIL;
5515 }
5516 to += needed * 2;
5517 }
5518
5519 fromlen = to - ip->bw_conv_buf;
5520 buf = to;
5521# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5522 if (FIO_GET_CP(flags) == CP_UTF8)
5523 {
5524 /* Convert from UCS-2 to UTF-8, using the remainder of the
5525 * conversion buffer. Fails when out of space. */
5526 for (from = ip->bw_conv_buf; fromlen > 1; fromlen -= 2)
5527 {
5528 u8c = *from++;
5529 u8c += (*from++ << 8);
5530 to += utf_char2bytes(u8c, to);
5531 if (to + 6 >= ip->bw_conv_buf + ip->bw_conv_buflen)
5532 {
5533 ip->bw_conv_error = TRUE;
5534 return FAIL;
5535 }
5536 }
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005537 len = (int)(to - buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005538 }
5539 else
5540#endif
5541 {
5542 /* Convert from UCS-2 to the codepage, using the remainder of
5543 * the conversion buffer. If the conversion uses the default
5544 * character "0", the data doesn't fit in this encoding, so
5545 * fail. */
5546 len = WideCharToMultiByte(FIO_GET_CP(flags), 0,
5547 (LPCWSTR)ip->bw_conv_buf, (int)fromlen / sizeof(WCHAR),
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005548 (LPSTR)to, (int)(ip->bw_conv_buflen - fromlen), 0,
5549 &bad);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005550 if (bad)
5551 {
5552 ip->bw_conv_error = TRUE;
5553 return FAIL;
5554 }
5555 }
5556 }
5557# endif
5558
Bram Moolenaar56718732006-03-15 22:53:57 +00005559# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00005560 else if (flags & FIO_MACROMAN)
5561 {
5562 /*
5563 * Convert UTF-8 or latin1 to Apple MacRoman.
5564 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005565 char_u *from;
5566 size_t fromlen;
5567
5568 if (ip->bw_restlen > 0)
5569 {
5570 /* Need to concatenate the remainder of the previous call and
5571 * the bytes of the current call. Use the end of the
5572 * conversion buffer for this. */
5573 fromlen = len + ip->bw_restlen;
5574 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5575 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5576 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5577 }
5578 else
5579 {
5580 from = buf;
5581 fromlen = len;
5582 }
5583
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00005584 if (enc2macroman(from, fromlen,
5585 ip->bw_conv_buf, &len, ip->bw_conv_buflen,
5586 ip->bw_rest, &ip->bw_restlen) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005587 {
5588 ip->bw_conv_error = TRUE;
5589 return FAIL;
5590 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005591 buf = ip->bw_conv_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005592 }
5593# endif
5594
5595# ifdef USE_ICONV
5596 if (ip->bw_iconv_fd != (iconv_t)-1)
5597 {
5598 const char *from;
5599 size_t fromlen;
5600 char *to;
5601 size_t tolen;
5602
5603 /* Convert with iconv(). */
5604 if (ip->bw_restlen > 0)
5605 {
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005606 char *fp;
5607
Bram Moolenaar071d4272004-06-13 20:20:40 +00005608 /* Need to concatenate the remainder of the previous call and
5609 * the bytes of the current call. Use the end of the
5610 * conversion buffer for this. */
5611 fromlen = len + ip->bw_restlen;
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005612 fp = (char *)ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5613 mch_memmove(fp, ip->bw_rest, (size_t)ip->bw_restlen);
5614 mch_memmove(fp + ip->bw_restlen, buf, (size_t)len);
5615 from = fp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005616 tolen = ip->bw_conv_buflen - fromlen;
5617 }
5618 else
5619 {
5620 from = (const char *)buf;
5621 fromlen = len;
5622 tolen = ip->bw_conv_buflen;
5623 }
5624 to = (char *)ip->bw_conv_buf;
5625
5626 if (ip->bw_first)
5627 {
5628 size_t save_len = tolen;
5629
5630 /* output the initial shift state sequence */
5631 (void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen);
5632
5633 /* There is a bug in iconv() on Linux (which appears to be
5634 * wide-spread) which sets "to" to NULL and messes up "tolen".
5635 */
5636 if (to == NULL)
5637 {
5638 to = (char *)ip->bw_conv_buf;
5639 tolen = save_len;
5640 }
5641 ip->bw_first = FALSE;
5642 }
5643
5644 /*
5645 * If iconv() has an error or there is not enough room, fail.
5646 */
5647 if ((iconv(ip->bw_iconv_fd, (void *)&from, &fromlen, &to, &tolen)
5648 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
5649 || fromlen > CONV_RESTLEN)
5650 {
5651 ip->bw_conv_error = TRUE;
5652 return FAIL;
5653 }
5654
5655 /* copy remainder to ip->bw_rest[] to be used for the next call. */
5656 if (fromlen > 0)
5657 mch_memmove(ip->bw_rest, (void *)from, fromlen);
5658 ip->bw_restlen = (int)fromlen;
5659
5660 buf = ip->bw_conv_buf;
5661 len = (int)((char_u *)to - ip->bw_conv_buf);
5662 }
5663# endif
5664 }
5665#endif /* FEAT_MBYTE */
5666
5667#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02005668 if (flags & FIO_ENCRYPTED)
5669 {
5670 /* Encrypt the data. Do it in-place if possible, otherwise use an
5671 * allocated buffer. */
5672 if (crypt_works_inplace(ip->bw_buffer->b_cryptstate))
5673 {
5674 crypt_encode_inplace(ip->bw_buffer->b_cryptstate, buf, len);
5675 }
5676 else
5677 {
5678 char_u *outbuf;
5679
5680 len = crypt_encode_alloc(curbuf->b_cryptstate, buf, len, &outbuf);
5681 if (len == 0)
5682 return OK; /* Crypt layer is buffering, will flush later. */
5683 wlen = write_eintr(ip->bw_fd, outbuf, len);
5684 vim_free(outbuf);
5685 return (wlen < len) ? FAIL : OK;
5686 }
5687 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005688#endif
5689
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005690 wlen = write_eintr(ip->bw_fd, buf, len);
5691 return (wlen < len) ? FAIL : OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005692}
5693
5694#ifdef FEAT_MBYTE
5695/*
5696 * Convert a Unicode character to bytes.
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005697 * Return TRUE for an error, FALSE when it's OK.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005698 */
5699 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005700ucs2bytes(
5701 unsigned c, /* in: character */
5702 char_u **pp, /* in/out: pointer to result */
5703 int flags) /* FIO_ flags */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005704{
5705 char_u *p = *pp;
5706 int error = FALSE;
5707 int cc;
5708
5709
5710 if (flags & FIO_UCS4)
5711 {
5712 if (flags & FIO_ENDIAN_L)
5713 {
5714 *p++ = c;
5715 *p++ = (c >> 8);
5716 *p++ = (c >> 16);
5717 *p++ = (c >> 24);
5718 }
5719 else
5720 {
5721 *p++ = (c >> 24);
5722 *p++ = (c >> 16);
5723 *p++ = (c >> 8);
5724 *p++ = c;
5725 }
5726 }
5727 else if (flags & (FIO_UCS2 | FIO_UTF16))
5728 {
5729 if (c >= 0x10000)
5730 {
5731 if (flags & FIO_UTF16)
5732 {
5733 /* Make two words, ten bits of the character in each. First
5734 * word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff */
5735 c -= 0x10000;
5736 if (c >= 0x100000)
5737 error = TRUE;
5738 cc = ((c >> 10) & 0x3ff) + 0xd800;
5739 if (flags & FIO_ENDIAN_L)
5740 {
5741 *p++ = cc;
5742 *p++ = ((unsigned)cc >> 8);
5743 }
5744 else
5745 {
5746 *p++ = ((unsigned)cc >> 8);
5747 *p++ = cc;
5748 }
5749 c = (c & 0x3ff) + 0xdc00;
5750 }
5751 else
5752 error = TRUE;
5753 }
5754 if (flags & FIO_ENDIAN_L)
5755 {
5756 *p++ = c;
5757 *p++ = (c >> 8);
5758 }
5759 else
5760 {
5761 *p++ = (c >> 8);
5762 *p++ = c;
5763 }
5764 }
5765 else /* Latin1 */
5766 {
5767 if (c >= 0x100)
5768 {
5769 error = TRUE;
5770 *p++ = 0xBF;
5771 }
5772 else
5773 *p++ = c;
5774 }
5775
5776 *pp = p;
5777 return error;
5778}
5779
5780/*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005781 * Return TRUE if file encoding "fenc" requires conversion from or to
5782 * 'encoding'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005783 */
5784 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005785need_conversion(char_u *fenc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005786{
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005787 int same_encoding;
5788 int enc_flags;
5789 int fenc_flags;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005790
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005791 if (*fenc == NUL || STRCMP(p_enc, fenc) == 0)
Bram Moolenaar442b4222010-05-24 21:34:22 +02005792 {
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005793 same_encoding = TRUE;
Bram Moolenaar442b4222010-05-24 21:34:22 +02005794 fenc_flags = 0;
5795 }
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005796 else
5797 {
5798 /* Ignore difference between "ansi" and "latin1", "ucs-4" and
5799 * "ucs-4be", etc. */
5800 enc_flags = get_fio_flags(p_enc);
5801 fenc_flags = get_fio_flags(fenc);
5802 same_encoding = (enc_flags != 0 && fenc_flags == enc_flags);
5803 }
5804 if (same_encoding)
5805 {
5806 /* Specified encoding matches with 'encoding'. This requires
5807 * conversion when 'encoding' is Unicode but not UTF-8. */
5808 return enc_unicode != 0;
5809 }
5810
5811 /* Encodings differ. However, conversion is not needed when 'enc' is any
5812 * Unicode encoding and the file is UTF-8. */
5813 return !(enc_utf8 && fenc_flags == FIO_UTF8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005814}
5815
5816/*
5817 * Check "ptr" for a unicode encoding and return the FIO_ flags needed for the
5818 * internal conversion.
5819 * if "ptr" is an empty string, use 'encoding'.
5820 */
5821 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005822get_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005823{
5824 int prop;
5825
5826 if (*ptr == NUL)
5827 ptr = p_enc;
5828
5829 prop = enc_canon_props(ptr);
5830 if (prop & ENC_UNICODE)
5831 {
5832 if (prop & ENC_2BYTE)
5833 {
5834 if (prop & ENC_ENDIAN_L)
5835 return FIO_UCS2 | FIO_ENDIAN_L;
5836 return FIO_UCS2;
5837 }
5838 if (prop & ENC_4BYTE)
5839 {
5840 if (prop & ENC_ENDIAN_L)
5841 return FIO_UCS4 | FIO_ENDIAN_L;
5842 return FIO_UCS4;
5843 }
5844 if (prop & ENC_2WORD)
5845 {
5846 if (prop & ENC_ENDIAN_L)
5847 return FIO_UTF16 | FIO_ENDIAN_L;
5848 return FIO_UTF16;
5849 }
5850 return FIO_UTF8;
5851 }
5852 if (prop & ENC_LATIN1)
5853 return FIO_LATIN1;
5854 /* must be ENC_DBCS, requires iconv() */
5855 return 0;
5856}
5857
5858#ifdef WIN3264
5859/*
5860 * Check "ptr" for a MS-Windows codepage name and return the FIO_ flags needed
5861 * for the conversion MS-Windows can do for us. Also accept "utf-8".
5862 * Used for conversion between 'encoding' and 'fileencoding'.
5863 */
5864 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005865get_win_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005866{
5867 int cp;
5868
5869 /* Cannot do this when 'encoding' is not utf-8 and not a codepage. */
5870 if (!enc_utf8 && enc_codepage <= 0)
5871 return 0;
5872
5873 cp = encname2codepage(ptr);
5874 if (cp == 0)
5875 {
5876# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5877 if (STRCMP(ptr, "utf-8") == 0)
5878 cp = CP_UTF8;
5879 else
5880# endif
5881 return 0;
5882 }
5883 return FIO_PUT_CP(cp) | FIO_CODEPAGE;
5884}
5885#endif
5886
5887#ifdef MACOS_X
5888/*
5889 * Check "ptr" for a Carbon supported encoding and return the FIO_ flags
5890 * needed for the internal conversion to/from utf-8 or latin1.
5891 */
5892 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005893get_mac_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005894{
5895 if ((enc_utf8 || STRCMP(p_enc, "latin1") == 0)
5896 && (enc_canon_props(ptr) & ENC_MACROMAN))
5897 return FIO_MACROMAN;
5898 return 0;
5899}
5900#endif
5901
5902/*
5903 * Check for a Unicode BOM (Byte Order Mark) at the start of p[size].
5904 * "size" must be at least 2.
5905 * Return the name of the encoding and set "*lenp" to the length.
5906 * Returns NULL when no BOM found.
5907 */
5908 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005909check_for_bom(
5910 char_u *p,
5911 long size,
5912 int *lenp,
5913 int flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005914{
5915 char *name = NULL;
5916 int len = 2;
5917
5918 if (p[0] == 0xef && p[1] == 0xbb && size >= 3 && p[2] == 0xbf
Bram Moolenaaree0f5a62008-07-24 20:09:16 +00005919 && (flags == FIO_ALL || flags == FIO_UTF8 || flags == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005920 {
5921 name = "utf-8"; /* EF BB BF */
5922 len = 3;
5923 }
5924 else if (p[0] == 0xff && p[1] == 0xfe)
5925 {
5926 if (size >= 4 && p[2] == 0 && p[3] == 0
5927 && (flags == FIO_ALL || flags == (FIO_UCS4 | FIO_ENDIAN_L)))
5928 {
5929 name = "ucs-4le"; /* FF FE 00 00 */
5930 len = 4;
5931 }
Bram Moolenaar223a1892008-11-11 20:57:11 +00005932 else if (flags == (FIO_UCS2 | FIO_ENDIAN_L))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005933 name = "ucs-2le"; /* FF FE */
Bram Moolenaar223a1892008-11-11 20:57:11 +00005934 else if (flags == FIO_ALL || flags == (FIO_UTF16 | FIO_ENDIAN_L))
5935 /* utf-16le is preferred, it also works for ucs-2le text */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005936 name = "utf-16le"; /* FF FE */
5937 }
5938 else if (p[0] == 0xfe && p[1] == 0xff
5939 && (flags == FIO_ALL || flags == FIO_UCS2 || flags == FIO_UTF16))
5940 {
Bram Moolenaarffd82c52008-02-20 17:15:26 +00005941 /* Default to utf-16, it works also for ucs-2 text. */
5942 if (flags == FIO_UCS2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005943 name = "ucs-2"; /* FE FF */
Bram Moolenaarffd82c52008-02-20 17:15:26 +00005944 else
5945 name = "utf-16"; /* FE FF */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005946 }
5947 else if (size >= 4 && p[0] == 0 && p[1] == 0 && p[2] == 0xfe
5948 && p[3] == 0xff && (flags == FIO_ALL || flags == FIO_UCS4))
5949 {
5950 name = "ucs-4"; /* 00 00 FE FF */
5951 len = 4;
5952 }
5953
5954 *lenp = len;
5955 return (char_u *)name;
5956}
5957
5958/*
5959 * Generate a BOM in "buf[4]" for encoding "name".
5960 * Return the length of the BOM (zero when no BOM).
5961 */
5962 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005963make_bom(char_u *buf, char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005964{
5965 int flags;
5966 char_u *p;
5967
5968 flags = get_fio_flags(name);
5969
5970 /* Can't put a BOM in a non-Unicode file. */
5971 if (flags == FIO_LATIN1 || flags == 0)
5972 return 0;
5973
5974 if (flags == FIO_UTF8) /* UTF-8 */
5975 {
5976 buf[0] = 0xef;
5977 buf[1] = 0xbb;
5978 buf[2] = 0xbf;
5979 return 3;
5980 }
5981 p = buf;
5982 (void)ucs2bytes(0xfeff, &p, flags);
5983 return (int)(p - buf);
5984}
5985#endif
5986
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00005987#if defined(FEAT_VIMINFO) || defined(FEAT_BROWSE) || \
Bram Moolenaara0174af2008-01-02 20:08:25 +00005988 defined(FEAT_QUICKFIX) || defined(FEAT_AUTOCMD) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005989/*
5990 * Try to find a shortname by comparing the fullname with the current
5991 * directory.
Bram Moolenaard089d9b2007-09-30 12:02:55 +00005992 * Returns "full_path" or pointer into "full_path" if shortened.
5993 */
5994 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005995shorten_fname1(char_u *full_path)
Bram Moolenaard089d9b2007-09-30 12:02:55 +00005996{
Bram Moolenaard9462e32011-04-11 21:35:11 +02005997 char_u *dirname;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00005998 char_u *p = full_path;
5999
Bram Moolenaard9462e32011-04-11 21:35:11 +02006000 dirname = alloc(MAXPATHL);
6001 if (dirname == NULL)
6002 return full_path;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006003 if (mch_dirname(dirname, MAXPATHL) == OK)
6004 {
6005 p = shorten_fname(full_path, dirname);
6006 if (p == NULL || *p == NUL)
6007 p = full_path;
6008 }
Bram Moolenaard9462e32011-04-11 21:35:11 +02006009 vim_free(dirname);
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006010 return p;
6011}
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00006012#endif
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006013
6014/*
6015 * Try to find a shortname by comparing the fullname with the current
6016 * directory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006017 * Returns NULL if not shorter name possible, pointer into "full_path"
6018 * otherwise.
6019 */
6020 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006021shorten_fname(char_u *full_path, char_u *dir_name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006022{
6023 int len;
6024 char_u *p;
6025
6026 if (full_path == NULL)
6027 return NULL;
6028 len = (int)STRLEN(dir_name);
6029 if (fnamencmp(dir_name, full_path, len) == 0)
6030 {
6031 p = full_path + len;
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006032#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006033 /*
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006034 * MSWIN: when a file is in the root directory, dir_name will end in a
Bram Moolenaar071d4272004-06-13 20:20:40 +00006035 * slash, since C: by itself does not define a specific dir. In this
6036 * case p may already be correct. <negri>
6037 */
6038 if (!((len > 2) && (*(p - 2) == ':')))
6039#endif
6040 {
6041 if (vim_ispathsep(*p))
6042 ++p;
6043#ifndef VMS /* the path separator is always part of the path */
6044 else
6045 p = NULL;
6046#endif
6047 }
6048 }
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006049#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006050 /*
6051 * When using a file in the current drive, remove the drive name:
6052 * "A:\dir\file" -> "\dir\file". This helps when moving a session file on
6053 * a floppy from "A:\dir" to "B:\dir".
6054 */
6055 else if (len > 3
6056 && TOUPPER_LOC(full_path[0]) == TOUPPER_LOC(dir_name[0])
6057 && full_path[1] == ':'
6058 && vim_ispathsep(full_path[2]))
6059 p = full_path + 2;
6060#endif
6061 else
6062 p = NULL;
6063 return p;
6064}
6065
6066/*
6067 * Shorten filenames for all buffers.
6068 * When "force" is TRUE: Use full path from now on for files currently being
6069 * edited, both for file name and swap file name. Try to shorten the file
6070 * names a bit, if safe to do so.
6071 * When "force" is FALSE: Only try to shorten absolute file names.
6072 * For buffers that have buftype "nofile" or "scratch": never change the file
6073 * name.
6074 */
6075 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006076shorten_fnames(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006077{
6078 char_u dirname[MAXPATHL];
6079 buf_T *buf;
6080 char_u *p;
6081
6082 mch_dirname(dirname, MAXPATHL);
6083 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
6084 {
6085 if (buf->b_fname != NULL
6086#ifdef FEAT_QUICKFIX
6087 && !bt_nofile(buf)
6088#endif
6089 && !path_with_url(buf->b_fname)
6090 && (force
6091 || buf->b_sfname == NULL
6092 || mch_isFullName(buf->b_sfname)))
6093 {
6094 vim_free(buf->b_sfname);
6095 buf->b_sfname = NULL;
6096 p = shorten_fname(buf->b_ffname, dirname);
6097 if (p != NULL)
6098 {
6099 buf->b_sfname = vim_strsave(p);
6100 buf->b_fname = buf->b_sfname;
6101 }
6102 if (p == NULL || buf->b_fname == NULL)
6103 buf->b_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006104 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00006105
6106 /* Always make the swap file name a full path, a "nofile" buffer may
6107 * also have a swap file. */
6108 mf_fullname(buf->b_ml.ml_mfp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006109 }
6110#ifdef FEAT_WINDOWS
6111 status_redraw_all();
Bram Moolenaar49d7bf12006-02-17 21:45:41 +00006112 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006113#endif
6114}
6115
6116#if (defined(FEAT_DND) && defined(FEAT_GUI_GTK)) \
6117 || defined(FEAT_GUI_MSWIN) \
6118 || defined(FEAT_GUI_MAC) \
6119 || defined(PROTO)
6120/*
6121 * Shorten all filenames in "fnames[count]" by current directory.
6122 */
6123 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006124shorten_filenames(char_u **fnames, int count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006125{
6126 int i;
6127 char_u dirname[MAXPATHL];
6128 char_u *p;
6129
6130 if (fnames == NULL || count < 1)
6131 return;
6132 mch_dirname(dirname, sizeof(dirname));
6133 for (i = 0; i < count; ++i)
6134 {
6135 if ((p = shorten_fname(fnames[i], dirname)) != NULL)
6136 {
6137 /* shorten_fname() returns pointer in given "fnames[i]". If free
6138 * "fnames[i]" first, "p" becomes invalid. So we need to copy
6139 * "p" first then free fnames[i]. */
6140 p = vim_strsave(p);
6141 vim_free(fnames[i]);
6142 fnames[i] = p;
6143 }
6144 }
6145}
6146#endif
6147
6148/*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006149 * add extension to file name - change path/fo.o.h to path/fo.o.h.ext or
Bram Moolenaar071d4272004-06-13 20:20:40 +00006150 * fo_o_h.ext for MSDOS or when shortname option set.
6151 *
6152 * Assumed that fname is a valid name found in the filesystem we assure that
6153 * the return value is a different name and ends in 'ext'.
6154 * "ext" MUST be at most 4 characters long if it starts with a dot, 3
6155 * characters otherwise.
6156 * Space for the returned name is allocated, must be freed later.
6157 * Returns NULL when out of memory.
6158 */
6159 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006160modname(
6161 char_u *fname,
6162 char_u *ext,
6163 int prepend_dot) /* may prepend a '.' to file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006164{
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006165 return buf_modname((curbuf->b_p_sn || curbuf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00006166 fname, ext, prepend_dot);
6167}
6168
6169 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006170buf_modname(
6171 int shortname, /* use 8.3 file name */
6172 char_u *fname,
6173 char_u *ext,
6174 int prepend_dot) /* may prepend a '.' to file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006175{
6176 char_u *retval;
6177 char_u *s;
6178 char_u *e;
6179 char_u *ptr;
6180 int fnamelen, extlen;
6181
6182 extlen = (int)STRLEN(ext);
6183
6184 /*
6185 * If there is no file name we must get the name of the current directory
6186 * (we need the full path in case :cd is used).
6187 */
6188 if (fname == NULL || *fname == NUL)
6189 {
6190 retval = alloc((unsigned)(MAXPATHL + extlen + 3));
6191 if (retval == NULL)
6192 return NULL;
6193 if (mch_dirname(retval, MAXPATHL) == FAIL ||
6194 (fnamelen = (int)STRLEN(retval)) == 0)
6195 {
6196 vim_free(retval);
6197 return NULL;
6198 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006199 if (!after_pathsep(retval, retval + fnamelen))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006200 {
6201 retval[fnamelen++] = PATHSEP;
6202 retval[fnamelen] = NUL;
6203 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006204 prepend_dot = FALSE; /* nothing to prepend a dot to */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006205 }
6206 else
6207 {
6208 fnamelen = (int)STRLEN(fname);
6209 retval = alloc((unsigned)(fnamelen + extlen + 3));
6210 if (retval == NULL)
6211 return NULL;
6212 STRCPY(retval, fname);
6213#ifdef VMS
6214 vms_remove_version(retval); /* we do not need versions here */
6215#endif
6216 }
6217
6218 /*
6219 * search backwards until we hit a '/', '\' or ':' replacing all '.'
6220 * by '_' for MSDOS or when shortname option set and ext starts with a dot.
6221 * Then truncate what is after the '/', '\' or ':' to 8 characters for
6222 * MSDOS and 26 characters for AMIGA, a lot more for UNIX.
6223 */
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006224 for (ptr = retval + fnamelen; ptr > retval; mb_ptr_back(retval, ptr))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006225 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006226 if (*ext == '.'
Bram Moolenaare60acc12011-05-10 16:41:25 +02006227#ifdef USE_LONG_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00006228 && (!USE_LONG_FNAME || shortname)
Bram Moolenaare60acc12011-05-10 16:41:25 +02006229#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006230 && shortname
Bram Moolenaare60acc12011-05-10 16:41:25 +02006231#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006232 )
6233 if (*ptr == '.') /* replace '.' by '_' */
6234 *ptr = '_';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006235 if (vim_ispathsep(*ptr))
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006236 {
6237 ++ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006238 break;
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006239 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006240 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006241
6242 /* the file name has at most BASENAMELEN characters. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006243 if (STRLEN(ptr) > (unsigned)BASENAMELEN)
6244 ptr[BASENAMELEN] = '\0';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006245
6246 s = ptr + STRLEN(ptr);
6247
6248 /*
6249 * For 8.3 file names we may have to reduce the length.
6250 */
6251#ifdef USE_LONG_FNAME
6252 if (!USE_LONG_FNAME || shortname)
6253#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006254 if (shortname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006255#endif
6256 {
6257 /*
6258 * If there is no file name, or the file name ends in '/', and the
6259 * extension starts with '.', put a '_' before the dot, because just
6260 * ".ext" is invalid.
6261 */
6262 if (fname == NULL || *fname == NUL
6263 || vim_ispathsep(fname[STRLEN(fname) - 1]))
6264 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006265 if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006266 *s++ = '_';
6267 }
6268 /*
6269 * If the extension starts with '.', truncate the base name at 8
6270 * characters
6271 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006272 else if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006273 {
Bram Moolenaar78a15312009-05-15 19:33:18 +00006274 if ((size_t)(s - ptr) > (size_t)8)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006275 {
6276 s = ptr + 8;
6277 *s = '\0';
6278 }
6279 }
6280 /*
6281 * If the extension doesn't start with '.', and the file name
6282 * doesn't have an extension yet, append a '.'
6283 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006284 else if ((e = vim_strchr(ptr, '.')) == NULL)
6285 *s++ = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006286 /*
6287 * If the extension doesn't start with '.', and there already is an
Bram Moolenaar7263a772007-05-10 17:35:54 +00006288 * extension, it may need to be truncated
Bram Moolenaar071d4272004-06-13 20:20:40 +00006289 */
6290 else if ((int)STRLEN(e) + extlen > 4)
6291 s = e + 4 - extlen;
6292 }
Bram Moolenaare7fedb62015-12-31 19:07:19 +01006293#if defined(USE_LONG_FNAME) || defined(WIN3264)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006294 /*
6295 * If there is no file name, and the extension starts with '.', put a
6296 * '_' before the dot, because just ".ext" may be invalid if it's on a
6297 * FAT partition, and on HPFS it doesn't matter.
6298 */
6299 else if ((fname == NULL || *fname == NUL) && *ext == '.')
6300 *s++ = '_';
6301#endif
6302
6303 /*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006304 * Append the extension.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006305 * ext can start with '.' and cannot exceed 3 more characters.
6306 */
6307 STRCPY(s, ext);
6308
Bram Moolenaar071d4272004-06-13 20:20:40 +00006309 /*
6310 * Prepend the dot.
6311 */
Bram Moolenaare60acc12011-05-10 16:41:25 +02006312 if (prepend_dot && !shortname && *(e = gettail(retval)) != '.'
Bram Moolenaar071d4272004-06-13 20:20:40 +00006313#ifdef USE_LONG_FNAME
6314 && USE_LONG_FNAME
6315#endif
6316 )
6317 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006318 STRMOVE(e + 1, e);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006319 *e = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006320 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006321
6322 /*
6323 * Check that, after appending the extension, the file name is really
6324 * different.
6325 */
6326 if (fname != NULL && STRCMP(fname, retval) == 0)
6327 {
6328 /* we search for a character that can be replaced by '_' */
6329 while (--s >= ptr)
6330 {
6331 if (*s != '_')
6332 {
6333 *s = '_';
6334 break;
6335 }
6336 }
6337 if (s < ptr) /* fname was "________.<ext>", how tricky! */
6338 *ptr = 'v';
6339 }
6340 return retval;
6341}
6342
6343/*
6344 * Like fgets(), but if the file line is too long, it is truncated and the
6345 * rest of the line is thrown away. Returns TRUE for end-of-file.
6346 */
6347 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006348vim_fgets(char_u *buf, int size, FILE *fp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006349{
6350 char *eof;
6351#define FGETS_SIZE 200
6352 char tbuf[FGETS_SIZE];
6353
6354 buf[size - 2] = NUL;
6355#ifdef USE_CR
6356 eof = fgets_cr((char *)buf, size, fp);
6357#else
6358 eof = fgets((char *)buf, size, fp);
6359#endif
6360 if (buf[size - 2] != NUL && buf[size - 2] != '\n')
6361 {
6362 buf[size - 1] = NUL; /* Truncate the line */
6363
6364 /* Now throw away the rest of the line: */
6365 do
6366 {
6367 tbuf[FGETS_SIZE - 2] = NUL;
6368#ifdef USE_CR
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006369 ignoredp = fgets_cr((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006370#else
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006371 ignoredp = fgets((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006372#endif
6373 } while (tbuf[FGETS_SIZE - 2] != NUL && tbuf[FGETS_SIZE - 2] != '\n');
6374 }
6375 return (eof == NULL);
6376}
6377
6378#if defined(USE_CR) || defined(PROTO)
6379/*
6380 * Like vim_fgets(), but accept any line terminator: CR, CR-LF or LF.
6381 * Returns TRUE for end-of-file.
6382 * Only used for the Mac, because it's much slower than vim_fgets().
6383 */
6384 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006385tag_fgets(char_u *buf, int size, FILE *fp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006386{
6387 int i = 0;
6388 int c;
6389 int eof = FALSE;
6390
6391 for (;;)
6392 {
6393 c = fgetc(fp);
6394 if (c == EOF)
6395 {
6396 eof = TRUE;
6397 break;
6398 }
6399 if (c == '\r')
6400 {
6401 /* Always store a NL for end-of-line. */
6402 if (i < size - 1)
6403 buf[i++] = '\n';
6404 c = fgetc(fp);
6405 if (c != '\n') /* Macintosh format: single CR. */
6406 ungetc(c, fp);
6407 break;
6408 }
6409 if (i < size - 1)
6410 buf[i++] = c;
6411 if (c == '\n')
6412 break;
6413 }
6414 buf[i] = NUL;
6415 return eof;
6416}
6417#endif
6418
6419/*
6420 * rename() only works if both files are on the same file system, this
6421 * function will (attempts to?) copy the file across if rename fails -- webb
6422 * Return -1 for failure, 0 for success.
6423 */
6424 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006425vim_rename(char_u *from, char_u *to)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006426{
6427 int fd_in;
6428 int fd_out;
6429 int n;
6430 char *errmsg = NULL;
6431 char *buffer;
6432#ifdef AMIGA
6433 BPTR flock;
6434#endif
Bram Moolenaar8767f522016-07-01 17:17:39 +02006435 stat_T st;
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006436 long perm;
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006437#ifdef HAVE_ACL
6438 vim_acl_T acl; /* ACL from original file */
6439#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006440 int use_tmp_file = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006441
6442 /*
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006443 * When the names are identical, there is nothing to do. When they refer
6444 * to the same file (ignoring case and slash/backslash differences) but
6445 * the file name differs we need to go through a temp file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006446 */
6447 if (fnamecmp(from, to) == 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006448 {
Bram Moolenaar71afbfe2013-03-19 16:49:16 +01006449 if (p_fic && STRCMP(gettail(from), gettail(to)) != 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006450 use_tmp_file = TRUE;
6451 else
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006452 return 0;
6453 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006454
6455 /*
6456 * Fail if the "from" file doesn't exist. Avoids that "to" is deleted.
6457 */
6458 if (mch_stat((char *)from, &st) < 0)
6459 return -1;
6460
Bram Moolenaar3576da72008-12-30 15:15:57 +00006461#ifdef UNIX
6462 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02006463 stat_T st_to;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006464
6465 /* It's possible for the source and destination to be the same file.
6466 * This happens when "from" and "to" differ in case and are on a FAT32
6467 * filesystem. In that case go through a temp file name. */
6468 if (mch_stat((char *)to, &st_to) >= 0
6469 && st.st_dev == st_to.st_dev
6470 && st.st_ino == st_to.st_ino)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006471 use_tmp_file = TRUE;
6472 }
6473#endif
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02006474#ifdef WIN3264
6475 {
6476 BY_HANDLE_FILE_INFORMATION info1, info2;
6477
6478 /* It's possible for the source and destination to be the same file.
6479 * In that case go through a temp file name. This makes rename("foo",
6480 * "./foo") a no-op (in a complicated way). */
6481 if (win32_fileinfo(from, &info1) == FILEINFO_OK
6482 && win32_fileinfo(to, &info2) == FILEINFO_OK
6483 && info1.dwVolumeSerialNumber == info2.dwVolumeSerialNumber
6484 && info1.nFileIndexHigh == info2.nFileIndexHigh
6485 && info1.nFileIndexLow == info2.nFileIndexLow)
6486 use_tmp_file = TRUE;
6487 }
6488#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006489
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006490 if (use_tmp_file)
6491 {
6492 char tempname[MAXPATHL + 1];
6493
6494 /*
6495 * Find a name that doesn't exist and is in the same directory.
6496 * Rename "from" to "tempname" and then rename "tempname" to "to".
6497 */
6498 if (STRLEN(from) >= MAXPATHL - 5)
6499 return -1;
6500 STRCPY(tempname, from);
6501 for (n = 123; n < 99999; ++n)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006502 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006503 sprintf((char *)gettail((char_u *)tempname), "%d", n);
6504 if (mch_stat(tempname, &st) < 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006505 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006506 if (mch_rename((char *)from, tempname) == 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006507 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006508 if (mch_rename(tempname, (char *)to) == 0)
6509 return 0;
6510 /* Strange, the second step failed. Try moving the
6511 * file back and return failure. */
6512 mch_rename(tempname, (char *)from);
Bram Moolenaar3576da72008-12-30 15:15:57 +00006513 return -1;
6514 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006515 /* If it fails for one temp name it will most likely fail
6516 * for any temp name, give up. */
6517 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006518 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006519 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006520 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006521 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006522
Bram Moolenaar071d4272004-06-13 20:20:40 +00006523 /*
6524 * Delete the "to" file, this is required on some systems to make the
6525 * mch_rename() work, on other systems it makes sure that we don't have
6526 * two files when the mch_rename() fails.
6527 */
6528
6529#ifdef AMIGA
6530 /*
6531 * With MSDOS-compatible filesystems (crossdos, messydos) it is possible
6532 * that the name of the "to" file is the same as the "from" file, even
Bram Moolenaar7263a772007-05-10 17:35:54 +00006533 * though the names are different. To avoid the chance of accidentally
Bram Moolenaar071d4272004-06-13 20:20:40 +00006534 * deleting the "from" file (horror!) we lock it during the remove.
6535 *
6536 * When used for making a backup before writing the file: This should not
6537 * happen with ":w", because startscript() should detect this problem and
6538 * set buf->b_shortname, causing modname() to return a correct ".bak" file
6539 * name. This problem does exist with ":w filename", but then the
6540 * original file will be somewhere else so the backup isn't really
6541 * important. If autoscripting is off the rename may fail.
6542 */
6543 flock = Lock((UBYTE *)from, (long)ACCESS_READ);
6544#endif
6545 mch_remove(to);
6546#ifdef AMIGA
6547 if (flock)
6548 UnLock(flock);
6549#endif
6550
6551 /*
6552 * First try a normal rename, return if it works.
6553 */
6554 if (mch_rename((char *)from, (char *)to) == 0)
6555 return 0;
6556
6557 /*
6558 * Rename() failed, try copying the file.
6559 */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006560 perm = mch_getperm(from);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006561#ifdef HAVE_ACL
6562 /* For systems that support ACL: get the ACL from the original file. */
6563 acl = mch_get_acl(from);
6564#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006565 fd_in = mch_open((char *)from, O_RDONLY|O_EXTRA, 0);
6566 if (fd_in == -1)
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006567 {
6568#ifdef HAVE_ACL
6569 mch_free_acl(acl);
6570#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006571 return -1;
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006572 }
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006573
6574 /* Create the new file with same permissions as the original. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00006575 fd_out = mch_open((char *)to,
6576 O_CREAT|O_EXCL|O_WRONLY|O_EXTRA|O_NOFOLLOW, (int)perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006577 if (fd_out == -1)
6578 {
6579 close(fd_in);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006580#ifdef HAVE_ACL
6581 mch_free_acl(acl);
6582#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006583 return -1;
6584 }
6585
6586 buffer = (char *)alloc(BUFSIZE);
6587 if (buffer == NULL)
6588 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006589 close(fd_out);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006590 close(fd_in);
6591#ifdef HAVE_ACL
6592 mch_free_acl(acl);
6593#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006594 return -1;
6595 }
6596
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01006597 while ((n = read_eintr(fd_in, buffer, BUFSIZE)) > 0)
6598 if (write_eintr(fd_out, buffer, n) != n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006599 {
6600 errmsg = _("E208: Error writing to \"%s\"");
6601 break;
6602 }
6603
6604 vim_free(buffer);
6605 close(fd_in);
6606 if (close(fd_out) < 0)
6607 errmsg = _("E209: Error closing \"%s\"");
6608 if (n < 0)
6609 {
6610 errmsg = _("E210: Error reading \"%s\"");
6611 to = from;
6612 }
Bram Moolenaar7263a772007-05-10 17:35:54 +00006613#ifndef UNIX /* for Unix mch_open() already set the permission */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006614 mch_setperm(to, perm);
Bram Moolenaarc6039d82005-12-02 00:44:04 +00006615#endif
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006616#ifdef HAVE_ACL
6617 mch_set_acl(to, acl);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006618 mch_free_acl(acl);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006619#endif
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02006620#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaare8747442013-11-12 18:09:29 +01006621 mch_copy_sec(from, to);
Bram Moolenaar0671de32013-11-12 05:12:03 +01006622#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006623 if (errmsg != NULL)
6624 {
6625 EMSG2(errmsg, to);
6626 return -1;
6627 }
6628 mch_remove(from);
6629 return 0;
6630}
6631
6632static int already_warned = FALSE;
6633
6634/*
6635 * Check if any not hidden buffer has been changed.
6636 * Postpone the check if there are characters in the stuff buffer, a global
6637 * command is being executed, a mapping is being executed or an autocommand is
6638 * busy.
6639 * Returns TRUE if some message was written (screen should be redrawn and
6640 * cursor positioned).
6641 */
6642 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006643check_timestamps(
6644 int focus) /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006645{
6646 buf_T *buf;
6647 int didit = 0;
6648 int n;
6649
6650 /* Don't check timestamps while system() or another low-level function may
6651 * cause us to lose and gain focus. */
6652 if (no_check_timestamps > 0)
6653 return FALSE;
6654
6655 /* Avoid doing a check twice. The OK/Reload dialog can cause a focus
6656 * event and we would keep on checking if the file is steadily growing.
6657 * Do check again after typing something. */
6658 if (focus && did_check_timestamps)
6659 {
6660 need_check_timestamps = TRUE;
6661 return FALSE;
6662 }
6663
6664 if (!stuff_empty() || global_busy || !typebuf_typed()
6665#ifdef FEAT_AUTOCMD
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006666 || autocmd_busy || curbuf_lock > 0 || allbuf_lock > 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00006667#endif
6668 )
6669 need_check_timestamps = TRUE; /* check later */
6670 else
6671 {
6672 ++no_wait_return;
6673 did_check_timestamps = TRUE;
6674 already_warned = FALSE;
6675 for (buf = firstbuf; buf != NULL; )
6676 {
6677 /* Only check buffers in a window. */
6678 if (buf->b_nwindows > 0)
6679 {
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006680 bufref_T bufref;
6681
6682 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006683 n = buf_check_timestamp(buf, focus);
6684 if (didit < n)
6685 didit = n;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006686 if (n > 0 && !bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006687 {
6688 /* Autocommands have removed the buffer, start at the
6689 * first one again. */
6690 buf = firstbuf;
6691 continue;
6692 }
6693 }
6694 buf = buf->b_next;
6695 }
6696 --no_wait_return;
6697 need_check_timestamps = FALSE;
6698 if (need_wait_return && didit == 2)
6699 {
6700 /* make sure msg isn't overwritten */
6701 msg_puts((char_u *)"\n");
6702 out_flush();
6703 }
6704 }
6705 return didit;
6706}
6707
6708/*
6709 * Move all the lines from buffer "frombuf" to buffer "tobuf".
6710 * Return OK or FAIL. When FAIL "tobuf" is incomplete and/or "frombuf" is not
6711 * empty.
6712 */
6713 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006714move_lines(buf_T *frombuf, buf_T *tobuf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006715{
6716 buf_T *tbuf = curbuf;
6717 int retval = OK;
6718 linenr_T lnum;
6719 char_u *p;
6720
6721 /* Copy the lines in "frombuf" to "tobuf". */
6722 curbuf = tobuf;
6723 for (lnum = 1; lnum <= frombuf->b_ml.ml_line_count; ++lnum)
6724 {
6725 p = vim_strsave(ml_get_buf(frombuf, lnum, FALSE));
6726 if (p == NULL || ml_append(lnum - 1, p, 0, FALSE) == FAIL)
6727 {
6728 vim_free(p);
6729 retval = FAIL;
6730 break;
6731 }
6732 vim_free(p);
6733 }
6734
6735 /* Delete all the lines in "frombuf". */
6736 if (retval != FAIL)
6737 {
6738 curbuf = frombuf;
Bram Moolenaar9460b9d2007-01-09 14:37:01 +00006739 for (lnum = curbuf->b_ml.ml_line_count; lnum > 0; --lnum)
6740 if (ml_delete(lnum, FALSE) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006741 {
6742 /* Oops! We could try putting back the saved lines, but that
6743 * might fail again... */
6744 retval = FAIL;
6745 break;
6746 }
6747 }
6748
6749 curbuf = tbuf;
6750 return retval;
6751}
6752
6753/*
6754 * Check if buffer "buf" has been changed.
6755 * Also check if the file for a new buffer unexpectedly appeared.
6756 * return 1 if a changed buffer was found.
6757 * return 2 if a message has been displayed.
6758 * return 0 otherwise.
6759 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006760 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006761buf_check_timestamp(
6762 buf_T *buf,
6763 int focus UNUSED) /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006764{
Bram Moolenaar8767f522016-07-01 17:17:39 +02006765 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006766 int stat_res;
6767 int retval = 0;
6768 char_u *path;
6769 char_u *tbuf;
6770 char *mesg = NULL;
Bram Moolenaar44ecf652005-03-07 23:09:59 +00006771 char *mesg2 = "";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006772 int helpmesg = FALSE;
6773 int reload = FALSE;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006774 char *reason;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006775#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6776 int can_reload = FALSE;
6777#endif
Bram Moolenaar8767f522016-07-01 17:17:39 +02006778 off_T orig_size = buf->b_orig_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006779 int orig_mode = buf->b_orig_mode;
6780#ifdef FEAT_GUI
6781 int save_mouse_correct = need_mouse_correct;
6782#endif
6783#ifdef FEAT_AUTOCMD
6784 static int busy = FALSE;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006785 int n;
6786 char_u *s;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006787 bufref_T bufref;
6788
6789 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006790#endif
6791
6792 /* If there is no file name, the buffer is not loaded, 'buftype' is
6793 * set, we are in the middle of a save or being called recursively: ignore
6794 * this buffer. */
6795 if (buf->b_ffname == NULL
6796 || buf->b_ml.ml_mfp == NULL
6797#if defined(FEAT_QUICKFIX)
6798 || *buf->b_p_bt != NUL
6799#endif
6800 || buf->b_saving
6801#ifdef FEAT_AUTOCMD
6802 || busy
6803#endif
Bram Moolenaar009b2592004-10-24 19:18:58 +00006804#ifdef FEAT_NETBEANS_INTG
6805 || isNetbeansBuffer(buf)
6806#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006807 )
6808 return 0;
6809
6810 if ( !(buf->b_flags & BF_NOTEDITED)
6811 && buf->b_mtime != 0
6812 && ((stat_res = mch_stat((char *)buf->b_ffname, &st)) < 0
6813 || time_differs((long)st.st_mtime, buf->b_mtime)
Bram Moolenaara7611f62014-05-02 15:46:14 +02006814 || st.st_size != buf->b_orig_size
Bram Moolenaar071d4272004-06-13 20:20:40 +00006815#ifdef HAVE_ST_MODE
6816 || (int)st.st_mode != buf->b_orig_mode
6817#else
6818 || mch_getperm(buf->b_ffname) != buf->b_orig_mode
6819#endif
6820 ))
6821 {
6822 retval = 1;
6823
Bram Moolenaar316059c2006-01-14 21:18:42 +00006824 /* set b_mtime to stop further warnings (e.g., when executing
6825 * FileChangedShell autocmd) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006826 if (stat_res < 0)
6827 {
6828 buf->b_mtime = 0;
6829 buf->b_orig_size = 0;
6830 buf->b_orig_mode = 0;
6831 }
6832 else
6833 buf_store_time(buf, &st, buf->b_ffname);
6834
6835 /* Don't do anything for a directory. Might contain the file
6836 * explorer. */
6837 if (mch_isdir(buf->b_fname))
6838 ;
6839
6840 /*
6841 * If 'autoread' is set, the buffer has no changes and the file still
6842 * exists, reload the buffer. Use the buffer-local option value if it
6843 * was set, the global option value otherwise.
6844 */
6845 else if ((buf->b_p_ar >= 0 ? buf->b_p_ar : p_ar)
6846 && !bufIsChanged(buf) && stat_res >= 0)
6847 reload = TRUE;
6848 else
6849 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006850 if (stat_res < 0)
6851 reason = "deleted";
6852 else if (bufIsChanged(buf))
6853 reason = "conflict";
6854 else if (orig_size != buf->b_orig_size || buf_contents_changed(buf))
6855 reason = "changed";
6856 else if (orig_mode != buf->b_orig_mode)
6857 reason = "mode";
6858 else
6859 reason = "time";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006860
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006861#ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006862 /*
6863 * Only give the warning if there are no FileChangedShell
6864 * autocommands.
6865 * Avoid being called recursively by setting "busy".
6866 */
6867 busy = TRUE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00006868# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006869 set_vim_var_string(VV_FCS_REASON, (char_u *)reason, -1);
6870 set_vim_var_string(VV_FCS_CHOICE, (char_u *)"", -1);
Bram Moolenaar1e015462005-09-25 22:16:38 +00006871# endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006872 ++allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006873 n = apply_autocmds(EVENT_FILECHANGEDSHELL,
6874 buf->b_fname, buf->b_fname, FALSE, buf);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006875 --allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006876 busy = FALSE;
6877 if (n)
6878 {
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006879 if (!bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006880 EMSG(_("E246: FileChangedShell autocommand deleted buffer"));
Bram Moolenaar1e015462005-09-25 22:16:38 +00006881# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006882 s = get_vim_var_str(VV_FCS_CHOICE);
6883 if (STRCMP(s, "reload") == 0 && *reason != 'd')
6884 reload = TRUE;
6885 else if (STRCMP(s, "ask") == 0)
6886 n = FALSE;
6887 else
Bram Moolenaar1e015462005-09-25 22:16:38 +00006888# endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006889 return 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006890 }
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006891 if (!n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006892#endif
6893 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006894 if (*reason == 'd')
6895 mesg = _("E211: File \"%s\" no longer available");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006896 else
6897 {
6898 helpmesg = TRUE;
6899#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6900 can_reload = TRUE;
6901#endif
6902 /*
6903 * Check if the file contents really changed to avoid
6904 * giving a warning when only the timestamp was set (e.g.,
6905 * checked out of CVS). Always warn when the buffer was
6906 * changed.
6907 */
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006908 if (reason[2] == 'n')
6909 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006910 mesg = _("W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006911 mesg2 = _("See \":help W12\" for more info.");
6912 }
6913 else if (reason[1] == 'h')
6914 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006915 mesg = _("W11: Warning: File \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006916 mesg2 = _("See \":help W11\" for more info.");
6917 }
6918 else if (*reason == 'm')
6919 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006920 mesg = _("W16: Warning: Mode of file \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006921 mesg2 = _("See \":help W16\" for more info.");
6922 }
Bram Moolenaar85388b52009-06-24 09:58:32 +00006923 else
6924 /* Only timestamp changed, store it to avoid a warning
6925 * in check_mtime() later. */
6926 buf->b_mtime_read = buf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006927 }
6928 }
6929 }
6930
6931 }
6932 else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W)
6933 && vim_fexists(buf->b_ffname))
6934 {
6935 retval = 1;
6936 mesg = _("W13: Warning: File \"%s\" has been created after editing started");
6937 buf->b_flags |= BF_NEW_W;
6938#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6939 can_reload = TRUE;
6940#endif
6941 }
6942
6943 if (mesg != NULL)
6944 {
6945 path = home_replace_save(buf, buf->b_fname);
6946 if (path != NULL)
6947 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006948 if (!helpmesg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006949 mesg2 = "";
6950 tbuf = alloc((unsigned)(STRLEN(path) + STRLEN(mesg)
6951 + STRLEN(mesg2) + 2));
6952 sprintf((char *)tbuf, mesg, path);
Bram Moolenaar496c5262009-03-18 14:42:00 +00006953#ifdef FEAT_EVAL
6954 /* Set warningmsg here, before the unimportant and output-specific
6955 * mesg2 has been appended. */
6956 set_vim_var_string(VV_WARNINGMSG, tbuf, -1);
6957#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006958#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6959 if (can_reload)
6960 {
6961 if (*mesg2 != NUL)
6962 {
6963 STRCAT(tbuf, "\n");
6964 STRCAT(tbuf, mesg2);
6965 }
6966 if (do_dialog(VIM_WARNING, (char_u *)_("Warning"), tbuf,
Bram Moolenaard2c340a2011-01-17 20:08:11 +01006967 (char_u *)_("&OK\n&Load File"), 1, NULL, TRUE) == 2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006968 reload = TRUE;
6969 }
6970 else
6971#endif
6972 if (State > NORMAL_BUSY || (State & CMDLINE) || already_warned)
6973 {
6974 if (*mesg2 != NUL)
6975 {
6976 STRCAT(tbuf, "; ");
6977 STRCAT(tbuf, mesg2);
6978 }
6979 EMSG(tbuf);
6980 retval = 2;
6981 }
6982 else
6983 {
Bram Moolenaared203462004-06-16 11:19:22 +00006984# ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006985 if (!autocmd_busy)
Bram Moolenaared203462004-06-16 11:19:22 +00006986# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006987 {
6988 msg_start();
6989 msg_puts_attr(tbuf, hl_attr(HLF_E) + MSG_HIST);
6990 if (*mesg2 != NUL)
6991 msg_puts_attr((char_u *)mesg2,
6992 hl_attr(HLF_W) + MSG_HIST);
6993 msg_clr_eos();
6994 (void)msg_end();
6995 if (emsg_silent == 0)
6996 {
6997 out_flush();
Bram Moolenaared203462004-06-16 11:19:22 +00006998# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00006999 if (!focus)
Bram Moolenaared203462004-06-16 11:19:22 +00007000# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007001 /* give the user some time to think about it */
7002 ui_delay(1000L, TRUE);
7003
7004 /* don't redraw and erase the message */
7005 redraw_cmdline = FALSE;
7006 }
7007 }
7008 already_warned = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007009 }
7010
7011 vim_free(path);
7012 vim_free(tbuf);
7013 }
7014 }
7015
7016 if (reload)
Bram Moolenaar465748e2012-08-29 18:50:54 +02007017 {
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007018 /* Reload the buffer. */
Bram Moolenaar316059c2006-01-14 21:18:42 +00007019 buf_reload(buf, orig_mode);
Bram Moolenaar465748e2012-08-29 18:50:54 +02007020#ifdef FEAT_PERSISTENT_UNDO
7021 if (buf->b_p_udf && buf->b_ffname != NULL)
7022 {
7023 char_u hash[UNDO_HASH_SIZE];
7024 buf_T *save_curbuf = curbuf;
7025
7026 /* Any existing undo file is unusable, write it now. */
7027 curbuf = buf;
7028 u_compute_hash(hash);
7029 u_write_undo(NULL, FALSE, buf, hash);
7030 curbuf = save_curbuf;
7031 }
7032#endif
7033 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007034
Bram Moolenaar56718732006-03-15 22:53:57 +00007035#ifdef FEAT_AUTOCMD
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00007036 /* Trigger FileChangedShell when the file was changed in any way. */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007037 if (bufref_valid(&bufref) && retval != 0)
Bram Moolenaar56718732006-03-15 22:53:57 +00007038 (void)apply_autocmds(EVENT_FILECHANGEDSHELLPOST,
7039 buf->b_fname, buf->b_fname, FALSE, buf);
7040#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007041#ifdef FEAT_GUI
7042 /* restore this in case an autocommand has set it; it would break
7043 * 'mousefocus' */
7044 need_mouse_correct = save_mouse_correct;
7045#endif
7046
7047 return retval;
7048}
7049
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007050/*
7051 * Reload a buffer that is already loaded.
7052 * Used when the file was changed outside of Vim.
Bram Moolenaar316059c2006-01-14 21:18:42 +00007053 * "orig_mode" is buf->b_orig_mode before the need for reloading was detected.
7054 * buf->b_orig_mode may have been reset already.
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007055 */
7056 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007057buf_reload(buf_T *buf, int orig_mode)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007058{
7059 exarg_T ea;
7060 pos_T old_cursor;
7061 linenr_T old_topline;
7062 int old_ro = buf->b_p_ro;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007063 buf_T *savebuf;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007064 bufref_T bufref;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007065 int saved = OK;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007066 aco_save_T aco;
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007067 int flags = READ_NEW;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007068
7069 /* set curwin/curbuf for "buf" and save some things */
7070 aucmd_prepbuf(&aco, buf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007071
7072 /* We only want to read the text from the file, not reset the syntax
7073 * highlighting, clear marks, diff status, etc. Force the fileformat
7074 * and encoding to be the same. */
7075 if (prep_exarg(&ea, buf) == OK)
7076 {
7077 old_cursor = curwin->w_cursor;
7078 old_topline = curwin->w_topline;
7079
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007080 if (p_ur < 0 || curbuf->b_ml.ml_line_count <= p_ur)
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007081 {
7082 /* Save all the text, so that the reload can be undone.
7083 * Sync first so that this is a separate undo-able action. */
7084 u_sync(FALSE);
7085 saved = u_savecommon(0, curbuf->b_ml.ml_line_count + 1, 0, TRUE);
7086 flags |= READ_KEEP_UNDO;
7087 }
7088
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007089 /*
7090 * To behave like when a new file is edited (matters for
7091 * BufReadPost autocommands) we first need to delete the current
7092 * buffer contents. But if reading the file fails we should keep
7093 * the old contents. Can't use memory only, the file might be
7094 * too big. Use a hidden buffer to move the buffer contents to.
7095 */
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007096 if (bufempty() || saved == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007097 savebuf = NULL;
7098 else
7099 {
7100 /* Allocate a buffer without putting it in the buffer list. */
7101 savebuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007102 set_bufref(&bufref, savebuf);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007103 if (savebuf != NULL && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007104 {
7105 /* Open the memline. */
7106 curbuf = savebuf;
7107 curwin->w_buffer = savebuf;
Bram Moolenaar4770d092006-01-12 23:22:24 +00007108 saved = ml_open(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007109 curbuf = buf;
7110 curwin->w_buffer = buf;
7111 }
Bram Moolenaar8424a622006-04-19 21:23:36 +00007112 if (savebuf == NULL || saved == FAIL || buf != curbuf
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007113 || move_lines(buf, savebuf) == FAIL)
7114 {
7115 EMSG2(_("E462: Could not prepare for reloading \"%s\""),
7116 buf->b_fname);
7117 saved = FAIL;
7118 }
7119 }
7120
7121 if (saved == OK)
7122 {
7123 curbuf->b_flags |= BF_CHECK_RO; /* check for RO again */
7124#ifdef FEAT_AUTOCMD
7125 keep_filetype = TRUE; /* don't detect 'filetype' */
7126#endif
7127 if (readfile(buf->b_ffname, buf->b_fname, (linenr_T)0,
7128 (linenr_T)0,
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007129 (linenr_T)MAXLNUM, &ea, flags) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007130 {
7131#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
7132 if (!aborting())
7133#endif
7134 EMSG2(_("E321: Could not reload \"%s\""), buf->b_fname);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007135 if (savebuf != NULL && bufref_valid(&bufref) && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007136 {
7137 /* Put the text back from the save buffer. First
7138 * delete any lines that readfile() added. */
7139 while (!bufempty())
Bram Moolenaar8424a622006-04-19 21:23:36 +00007140 if (ml_delete(buf->b_ml.ml_line_count, FALSE) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007141 break;
7142 (void)move_lines(savebuf, buf);
7143 }
7144 }
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007145 else if (buf == curbuf) /* "buf" still valid */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007146 {
7147 /* Mark the buffer as unmodified and free undo info. */
7148 unchanged(buf, TRUE);
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007149 if ((flags & READ_KEEP_UNDO) == 0)
7150 {
7151 u_blockfree(buf);
7152 u_clearall(buf);
7153 }
7154 else
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007155 {
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007156 /* Mark all undo states as changed. */
7157 u_unchanged(curbuf);
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007158 }
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007159 }
7160 }
7161 vim_free(ea.cmd);
7162
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007163 if (savebuf != NULL && bufref_valid(&bufref))
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007164 wipe_buffer(savebuf, FALSE);
7165
7166#ifdef FEAT_DIFF
7167 /* Invalidate diff info if necessary. */
Bram Moolenaar8424a622006-04-19 21:23:36 +00007168 diff_invalidate(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007169#endif
7170
7171 /* Restore the topline and cursor position and check it (lines may
7172 * have been removed). */
7173 if (old_topline > curbuf->b_ml.ml_line_count)
7174 curwin->w_topline = curbuf->b_ml.ml_line_count;
7175 else
7176 curwin->w_topline = old_topline;
7177 curwin->w_cursor = old_cursor;
7178 check_cursor();
7179 update_topline();
7180#ifdef FEAT_AUTOCMD
7181 keep_filetype = FALSE;
7182#endif
7183#ifdef FEAT_FOLDING
7184 {
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007185 win_T *wp;
7186 tabpage_T *tp;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007187
7188 /* Update folds unless they are defined manually. */
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007189 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007190 if (wp->w_buffer == curwin->w_buffer
7191 && !foldmethodIsManual(wp))
7192 foldUpdateAll(wp);
7193 }
7194#endif
7195 /* If the mode didn't change and 'readonly' was set, keep the old
7196 * value; the user probably used the ":view" command. But don't
7197 * reset it, might have had a read error. */
7198 if (orig_mode == curbuf->b_orig_mode)
7199 curbuf->b_p_ro |= old_ro;
Bram Moolenaar52f85b72013-01-30 14:13:56 +01007200
7201 /* Modelines must override settings done by autocommands. */
7202 do_modelines(0);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007203 }
7204
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007205 /* restore curwin/curbuf and a few other things */
7206 aucmd_restbuf(&aco);
7207 /* Careful: autocommands may have made "buf" invalid! */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007208}
7209
Bram Moolenaar071d4272004-06-13 20:20:40 +00007210 void
Bram Moolenaar8767f522016-07-01 17:17:39 +02007211buf_store_time(buf_T *buf, stat_T *st, char_u *fname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007212{
7213 buf->b_mtime = (long)st->st_mtime;
Bram Moolenaar914703b2010-05-31 21:59:46 +02007214 buf->b_orig_size = st->st_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007215#ifdef HAVE_ST_MODE
7216 buf->b_orig_mode = (int)st->st_mode;
7217#else
7218 buf->b_orig_mode = mch_getperm(fname);
7219#endif
7220}
7221
7222/*
7223 * Adjust the line with missing eol, used for the next write.
7224 * Used for do_filter(), when the input lines for the filter are deleted.
7225 */
7226 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007227write_lnum_adjust(linenr_T offset)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007228{
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01007229 if (curbuf->b_no_eol_lnum != 0) /* only if there is a missing eol */
7230 curbuf->b_no_eol_lnum += offset;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007231}
7232
Bram Moolenaarda440d22016-01-16 21:27:23 +01007233#if defined(TEMPDIRNAMES) || defined(FEAT_EVAL) || defined(PROTO)
7234/*
7235 * Delete "name" and everything in it, recursively.
7236 * return 0 for succes, -1 if some file was not deleted.
7237 */
7238 int
7239delete_recursive(char_u *name)
7240{
7241 int result = 0;
7242 char_u **files;
7243 int file_count;
7244 int i;
7245 char_u *exp;
7246
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007247 /* A symbolic link to a directory itself is deleted, not the directory it
7248 * points to. */
7249 if (
Bram Moolenaar203258c2016-01-17 22:15:16 +01007250# if defined(UNIX) || defined(WIN32)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007251 mch_isrealdir(name)
Bram Moolenaar203258c2016-01-17 22:15:16 +01007252# else
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007253 mch_isdir(name)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007254# endif
7255 )
Bram Moolenaarda440d22016-01-16 21:27:23 +01007256 {
7257 vim_snprintf((char *)NameBuff, MAXPATHL, "%s/*", name);
7258 exp = vim_strsave(NameBuff);
7259 if (exp == NULL)
7260 return -1;
7261 if (gen_expand_wildcards(1, &exp, &file_count, &files,
Bram Moolenaar336bd622016-01-17 18:23:58 +01007262 EW_DIR|EW_FILE|EW_SILENT|EW_ALLLINKS|EW_DODOT|EW_EMPTYOK) == OK)
Bram Moolenaarda440d22016-01-16 21:27:23 +01007263 {
7264 for (i = 0; i < file_count; ++i)
7265 if (delete_recursive(files[i]) != 0)
7266 result = -1;
7267 FreeWild(file_count, files);
7268 }
7269 else
7270 result = -1;
7271 vim_free(exp);
7272 (void)mch_rmdir(name);
7273 }
7274 else
7275 result = mch_remove(name) == 0 ? 0 : -1;
7276
7277 return result;
7278}
7279#endif
7280
Bram Moolenaar071d4272004-06-13 20:20:40 +00007281#if defined(TEMPDIRNAMES) || defined(PROTO)
7282static long temp_count = 0; /* Temp filename counter. */
7283
7284/*
7285 * Delete the temp directory and all files it contains.
7286 */
7287 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007288vim_deltempdir(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007289{
Bram Moolenaar071d4272004-06-13 20:20:40 +00007290 if (vim_tempdir != NULL)
7291 {
Bram Moolenaarda440d22016-01-16 21:27:23 +01007292 /* remove the trailing path separator */
7293 gettail(vim_tempdir)[-1] = NUL;
7294 delete_recursive(vim_tempdir);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007295 vim_free(vim_tempdir);
7296 vim_tempdir = NULL;
7297 }
7298}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007299
7300/*
Bram Moolenaareaf03392009-11-17 11:08:52 +00007301 * Directory "tempdir" was created. Expand this name to a full path and put
7302 * it in "vim_tempdir". This avoids that using ":cd" would confuse us.
7303 * "tempdir" must be no longer than MAXPATHL.
7304 */
7305 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007306vim_settempdir(char_u *tempdir)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007307{
7308 char_u *buf;
7309
7310 buf = alloc((unsigned)MAXPATHL + 2);
7311 if (buf != NULL)
7312 {
7313 if (vim_FullName(tempdir, buf, MAXPATHL, FALSE) == FAIL)
7314 STRCPY(buf, tempdir);
7315# ifdef __EMX__
7316 if (vim_strchr(buf, '/') != NULL)
7317 STRCAT(buf, "/");
7318 else
7319# endif
7320 add_pathsep(buf);
7321 vim_tempdir = vim_strsave(buf);
7322 vim_free(buf);
7323 }
7324}
Bram Moolenaar4592dee2009-11-18 19:11:58 +00007325#endif
Bram Moolenaareaf03392009-11-17 11:08:52 +00007326
7327/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007328 * vim_tempname(): Return a unique name that can be used for a temp file.
7329 *
Bram Moolenaar76ae22f2016-06-13 20:00:29 +02007330 * The temp file is NOT guaranteed to be created. If "keep" is FALSE it is
7331 * guaranteed to NOT be created.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007332 *
7333 * The returned pointer is to allocated memory.
7334 * The returned pointer is NULL if no valid name was found.
7335 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007336 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007337vim_tempname(
7338 int extra_char UNUSED, /* char to use in the name instead of '?' */
7339 int keep UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007340{
7341#ifdef USE_TMPNAM
7342 char_u itmp[L_tmpnam]; /* use tmpnam() */
7343#else
7344 char_u itmp[TEMPNAMELEN];
7345#endif
7346
7347#ifdef TEMPDIRNAMES
7348 static char *(tempdirs[]) = {TEMPDIRNAMES};
7349 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007350# ifndef EEXIST
Bram Moolenaar8767f522016-07-01 17:17:39 +02007351 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007352# endif
7353
7354 /*
7355 * This will create a directory for private use by this instance of Vim.
7356 * This is done once, and the same directory is used for all temp files.
7357 * This method avoids security problems because of symlink attacks et al.
7358 * It's also a bit faster, because we only need to check for an existing
7359 * file when creating the directory and not for each temp file.
7360 */
7361 if (vim_tempdir == NULL)
7362 {
7363 /*
7364 * Try the entries in TEMPDIRNAMES to create the temp directory.
7365 */
Bram Moolenaar78a15312009-05-15 19:33:18 +00007366 for (i = 0; i < (int)(sizeof(tempdirs) / sizeof(char *)); ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007367 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007368# ifndef HAVE_MKDTEMP
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007369 size_t itmplen;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007370 long nr;
7371 long off;
7372# endif
7373
Bram Moolenaare1a61992015-12-03 21:02:27 +01007374 /* Expand $TMP, leave room for "/v1100000/999999999".
7375 * Skip the directory check if the expansion fails. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007376 expand_env((char_u *)tempdirs[i], itmp, TEMPNAMELEN - 20);
Bram Moolenaare1a61992015-12-03 21:02:27 +01007377 if (itmp[0] != '$' && mch_isdir(itmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007378 {
Bram Moolenaare1a61992015-12-03 21:02:27 +01007379 /* directory exists */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007380# ifdef __EMX__
7381 /* If $TMP contains a forward slash (perhaps using bash or
7382 * tcsh), don't add a backslash, use a forward slash!
7383 * Adding 2 backslashes didn't work. */
7384 if (vim_strchr(itmp, '/') != NULL)
7385 STRCAT(itmp, "/");
7386 else
7387# endif
7388 add_pathsep(itmp);
7389
Bram Moolenaareaf03392009-11-17 11:08:52 +00007390# ifdef HAVE_MKDTEMP
Bram Moolenaar35d88f42016-06-04 14:52:00 +02007391 {
7392# if defined(UNIX) || defined(VMS)
7393 /* Make sure the umask doesn't remove the executable bit.
7394 * "repl" has been reported to use "177". */
7395 mode_t umask_save = umask(077);
7396# endif
7397 /* Leave room for filename */
7398 STRCAT(itmp, "vXXXXXX");
7399 if (mkdtemp((char *)itmp) != NULL)
7400 vim_settempdir(itmp);
7401# if defined(UNIX) || defined(VMS)
7402 (void)umask(umask_save);
7403# endif
7404 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007405# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007406 /* Get an arbitrary number of up to 6 digits. When it's
7407 * unlikely that it already exists it will be faster,
7408 * otherwise it doesn't matter. The use of mkdir() avoids any
7409 * security problems because of the predictable number. */
7410 nr = (mch_get_pid() + (long)time(NULL)) % 1000000L;
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007411 itmplen = STRLEN(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007412
7413 /* Try up to 10000 different values until we find a name that
7414 * doesn't exist. */
7415 for (off = 0; off < 10000L; ++off)
7416 {
7417 int r;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007418# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007419 mode_t umask_save;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007420# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007421
Bram Moolenaareaf03392009-11-17 11:08:52 +00007422 sprintf((char *)itmp + itmplen, "v%ld", nr + off);
7423# ifndef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007424 /* If mkdir() does not set errno to EEXIST, check for
7425 * existing file here. There is a race condition then,
7426 * although it's fail-safe. */
7427 if (mch_stat((char *)itmp, &st) >= 0)
7428 continue;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007429# endif
7430# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007431 /* Make sure the umask doesn't remove the executable bit.
7432 * "repl" has been reported to use "177". */
7433 umask_save = umask(077);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007434# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007435 r = vim_mkdir(itmp, 0700);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007436# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007437 (void)umask(umask_save);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007438# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007439 if (r == 0)
7440 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007441 vim_settempdir(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007442 break;
7443 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007444# ifdef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007445 /* If the mkdir() didn't fail because the file/dir exists,
7446 * we probably can't create any dir here, try another
7447 * place. */
7448 if (errno != EEXIST)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007449# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007450 break;
7451 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007452# endif /* HAVE_MKDTEMP */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007453 if (vim_tempdir != NULL)
7454 break;
7455 }
7456 }
7457 }
7458
7459 if (vim_tempdir != NULL)
7460 {
7461 /* There is no need to check if the file exists, because we own the
7462 * directory and nobody else creates a file in it. */
7463 sprintf((char *)itmp, "%s%ld", vim_tempdir, temp_count++);
7464 return vim_strsave(itmp);
7465 }
7466
7467 return NULL;
7468
7469#else /* TEMPDIRNAMES */
7470
7471# ifdef WIN3264
7472 char szTempFile[_MAX_PATH + 1];
7473 char buf4[4];
7474 char_u *retval;
7475 char_u *p;
7476
7477 STRCPY(itmp, "");
7478 if (GetTempPath(_MAX_PATH, szTempFile) == 0)
Bram Moolenaarb1891912011-02-09 14:47:03 +01007479 {
7480 szTempFile[0] = '.'; /* GetTempPath() failed, use current dir */
7481 szTempFile[1] = NUL;
7482 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007483 strcpy(buf4, "VIM");
7484 buf4[2] = extra_char; /* make it "VIa", "VIb", etc. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007485 if (GetTempFileName(szTempFile, buf4, 0, (LPSTR)itmp) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007486 return NULL;
Bram Moolenaare5c421c2015-03-31 13:33:08 +02007487 if (!keep)
7488 /* GetTempFileName() will create the file, we don't want that */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007489 (void)DeleteFile((LPSTR)itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007490
7491 /* Backslashes in a temp file name cause problems when filtering with
7492 * "sh". NOTE: This also checks 'shellcmdflag' to help those people who
7493 * didn't set 'shellslash'. */
7494 retval = vim_strsave(itmp);
7495 if (*p_shcf == '-' || p_ssl)
7496 for (p = retval; *p; ++p)
7497 if (*p == '\\')
7498 *p = '/';
7499 return retval;
7500
7501# else /* WIN3264 */
7502
7503# ifdef USE_TMPNAM
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007504 char_u *p;
7505
Bram Moolenaar071d4272004-06-13 20:20:40 +00007506 /* tmpnam() will make its own name */
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007507 p = tmpnam((char *)itmp);
7508 if (p == NULL || *p == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007509 return NULL;
7510# else
7511 char_u *p;
7512
7513# ifdef VMS_TEMPNAM
7514 /* mktemp() is not working on VMS. It seems to be
7515 * a do-nothing function. Therefore we use tempnam().
7516 */
7517 sprintf((char *)itmp, "VIM%c", extra_char);
7518 p = (char_u *)tempnam("tmp:", (char *)itmp);
7519 if (p != NULL)
7520 {
Bram Moolenaar206f0112014-03-12 16:51:55 +01007521 /* VMS will use '.LIS' if we don't explicitly specify an extension,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007522 * and VIM will then be unable to find the file later */
7523 STRCPY(itmp, p);
7524 STRCAT(itmp, ".txt");
7525 free(p);
7526 }
7527 else
7528 return NULL;
7529# else
7530 STRCPY(itmp, TEMPNAME);
7531 if ((p = vim_strchr(itmp, '?')) != NULL)
7532 *p = extra_char;
7533 if (mktemp((char *)itmp) == NULL)
7534 return NULL;
7535# endif
7536# endif
7537
7538 return vim_strsave(itmp);
7539# endif /* WIN3264 */
7540#endif /* TEMPDIRNAMES */
7541}
7542
7543#if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
7544/*
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02007545 * Convert all backslashes in fname to forward slashes in-place, unless when
7546 * it looks like a URL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007547 */
7548 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007549forward_slash(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007550{
7551 char_u *p;
7552
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02007553 if (path_with_url(fname))
7554 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007555 for (p = fname; *p != NUL; ++p)
7556# ifdef FEAT_MBYTE
7557 /* The Big5 encoding can have '\' in the trail byte. */
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00007558 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007559 ++p;
7560 else
7561# endif
7562 if (*p == '\\')
7563 *p = '/';
7564}
7565#endif
7566
7567
7568/*
7569 * Code for automatic commands.
7570 *
7571 * Only included when "FEAT_AUTOCMD" has been defined.
7572 */
7573
7574#if defined(FEAT_AUTOCMD) || defined(PROTO)
7575
7576/*
7577 * The autocommands are stored in a list for each event.
7578 * Autocommands for the same pattern, that are consecutive, are joined
7579 * together, to avoid having to match the pattern too often.
7580 * The result is an array of Autopat lists, which point to AutoCmd lists:
7581 *
7582 * first_autopat[0] --> Autopat.next --> Autopat.next --> NULL
7583 * Autopat.cmds Autopat.cmds
7584 * | |
7585 * V V
7586 * AutoCmd.next AutoCmd.next
7587 * | |
7588 * V V
7589 * AutoCmd.next NULL
7590 * |
7591 * V
7592 * NULL
7593 *
7594 * first_autopat[1] --> Autopat.next --> NULL
7595 * Autopat.cmds
7596 * |
7597 * V
7598 * AutoCmd.next
7599 * |
7600 * V
7601 * NULL
7602 * etc.
7603 *
7604 * The order of AutoCmds is important, this is the order in which they were
7605 * defined and will have to be executed.
7606 */
7607typedef struct AutoCmd
7608{
7609 char_u *cmd; /* The command to be executed (NULL
7610 when command has been removed) */
7611 char nested; /* If autocommands nest here */
7612 char last; /* last command in list */
7613#ifdef FEAT_EVAL
7614 scid_T scriptID; /* script ID where defined */
7615#endif
7616 struct AutoCmd *next; /* Next AutoCmd in list */
7617} AutoCmd;
7618
7619typedef struct AutoPat
7620{
Bram Moolenaar071d4272004-06-13 20:20:40 +00007621 char_u *pat; /* pattern as typed (NULL when pattern
7622 has been removed) */
Bram Moolenaar748bf032005-02-02 23:04:36 +00007623 regprog_T *reg_prog; /* compiled regprog for pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007624 AutoCmd *cmds; /* list of commands to do */
7625 struct AutoPat *next; /* next AutoPat in AutoPat list */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007626 int group; /* group ID */
7627 int patlen; /* strlen() of pat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007628 int buflocal_nr; /* !=0 for buffer-local AutoPat */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007629 char allow_dirs; /* Pattern may match whole path */
7630 char last; /* last pattern for apply_autocmds() */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007631} AutoPat;
7632
7633static struct event_name
7634{
7635 char *name; /* event name */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007636 event_T event; /* event number */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007637} event_names[] =
7638{
7639 {"BufAdd", EVENT_BUFADD},
7640 {"BufCreate", EVENT_BUFADD},
7641 {"BufDelete", EVENT_BUFDELETE},
7642 {"BufEnter", EVENT_BUFENTER},
7643 {"BufFilePost", EVENT_BUFFILEPOST},
7644 {"BufFilePre", EVENT_BUFFILEPRE},
7645 {"BufHidden", EVENT_BUFHIDDEN},
7646 {"BufLeave", EVENT_BUFLEAVE},
7647 {"BufNew", EVENT_BUFNEW},
7648 {"BufNewFile", EVENT_BUFNEWFILE},
7649 {"BufRead", EVENT_BUFREADPOST},
7650 {"BufReadCmd", EVENT_BUFREADCMD},
7651 {"BufReadPost", EVENT_BUFREADPOST},
7652 {"BufReadPre", EVENT_BUFREADPRE},
7653 {"BufUnload", EVENT_BUFUNLOAD},
7654 {"BufWinEnter", EVENT_BUFWINENTER},
7655 {"BufWinLeave", EVENT_BUFWINLEAVE},
7656 {"BufWipeout", EVENT_BUFWIPEOUT},
7657 {"BufWrite", EVENT_BUFWRITEPRE},
7658 {"BufWritePost", EVENT_BUFWRITEPOST},
7659 {"BufWritePre", EVENT_BUFWRITEPRE},
7660 {"BufWriteCmd", EVENT_BUFWRITECMD},
7661 {"CmdwinEnter", EVENT_CMDWINENTER},
7662 {"CmdwinLeave", EVENT_CMDWINLEAVE},
Bram Moolenaard5005162014-08-22 23:05:54 +02007663 {"CmdUndefined", EVENT_CMDUNDEFINED},
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007664 {"ColorScheme", EVENT_COLORSCHEME},
Bram Moolenaarcfa3cae2012-07-10 17:14:56 +02007665 {"CompleteDone", EVENT_COMPLETEDONE},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007666 {"CursorHold", EVENT_CURSORHOLD},
7667 {"CursorHoldI", EVENT_CURSORHOLDI},
7668 {"CursorMoved", EVENT_CURSORMOVED},
7669 {"CursorMovedI", EVENT_CURSORMOVEDI},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007670 {"EncodingChanged", EVENT_ENCODINGCHANGED},
7671 {"FileEncoding", EVENT_ENCODINGCHANGED},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007672 {"FileAppendPost", EVENT_FILEAPPENDPOST},
7673 {"FileAppendPre", EVENT_FILEAPPENDPRE},
7674 {"FileAppendCmd", EVENT_FILEAPPENDCMD},
7675 {"FileChangedShell",EVENT_FILECHANGEDSHELL},
Bram Moolenaar56718732006-03-15 22:53:57 +00007676 {"FileChangedShellPost",EVENT_FILECHANGEDSHELLPOST},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007677 {"FileChangedRO", EVENT_FILECHANGEDRO},
7678 {"FileReadPost", EVENT_FILEREADPOST},
7679 {"FileReadPre", EVENT_FILEREADPRE},
7680 {"FileReadCmd", EVENT_FILEREADCMD},
7681 {"FileType", EVENT_FILETYPE},
7682 {"FileWritePost", EVENT_FILEWRITEPOST},
7683 {"FileWritePre", EVENT_FILEWRITEPRE},
7684 {"FileWriteCmd", EVENT_FILEWRITECMD},
7685 {"FilterReadPost", EVENT_FILTERREADPOST},
7686 {"FilterReadPre", EVENT_FILTERREADPRE},
7687 {"FilterWritePost", EVENT_FILTERWRITEPOST},
7688 {"FilterWritePre", EVENT_FILTERWRITEPRE},
7689 {"FocusGained", EVENT_FOCUSGAINED},
7690 {"FocusLost", EVENT_FOCUSLOST},
7691 {"FuncUndefined", EVENT_FUNCUNDEFINED},
7692 {"GUIEnter", EVENT_GUIENTER},
Bram Moolenaar265e5072006-08-29 16:13:22 +00007693 {"GUIFailed", EVENT_GUIFAILED},
Bram Moolenaar843ee412004-06-30 16:16:41 +00007694 {"InsertChange", EVENT_INSERTCHANGE},
7695 {"InsertEnter", EVENT_INSERTENTER},
7696 {"InsertLeave", EVENT_INSERTLEAVE},
Bram Moolenaare659c952011-05-19 17:25:41 +02007697 {"InsertCharPre", EVENT_INSERTCHARPRE},
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00007698 {"MenuPopup", EVENT_MENUPOPUP},
Bram Moolenaar53744302015-07-17 17:38:22 +02007699 {"OptionSet", EVENT_OPTIONSET},
Bram Moolenaar7c626922005-02-07 22:01:03 +00007700 {"QuickFixCmdPost", EVENT_QUICKFIXCMDPOST},
7701 {"QuickFixCmdPre", EVENT_QUICKFIXCMDPRE},
Bram Moolenaar3b53dfb2012-06-06 18:03:07 +02007702 {"QuitPre", EVENT_QUITPRE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007703 {"RemoteReply", EVENT_REMOTEREPLY},
Bram Moolenaar9372a112005-12-06 19:59:18 +00007704 {"SessionLoadPost", EVENT_SESSIONLOADPOST},
Bram Moolenaar5c4bab02006-03-10 21:37:46 +00007705 {"ShellCmdPost", EVENT_SHELLCMDPOST},
7706 {"ShellFilterPost", EVENT_SHELLFILTERPOST},
Bram Moolenaara2031822006-03-07 22:29:51 +00007707 {"SourcePre", EVENT_SOURCEPRE},
Bram Moolenaar8dd1aa52007-01-16 20:33:19 +00007708 {"SourceCmd", EVENT_SOURCECMD},
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00007709 {"SpellFileMissing",EVENT_SPELLFILEMISSING},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007710 {"StdinReadPost", EVENT_STDINREADPOST},
7711 {"StdinReadPre", EVENT_STDINREADPRE},
Bram Moolenaarb815dac2005-12-07 20:59:24 +00007712 {"SwapExists", EVENT_SWAPEXISTS},
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00007713 {"Syntax", EVENT_SYNTAX},
Bram Moolenaar70836c82006-02-20 21:28:49 +00007714 {"TabEnter", EVENT_TABENTER},
7715 {"TabLeave", EVENT_TABLEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007716 {"TermChanged", EVENT_TERMCHANGED},
7717 {"TermResponse", EVENT_TERMRESPONSE},
Bram Moolenaar186628f2013-03-19 13:33:23 +01007718 {"TextChanged", EVENT_TEXTCHANGED},
7719 {"TextChangedI", EVENT_TEXTCHANGEDI},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007720 {"User", EVENT_USER},
7721 {"VimEnter", EVENT_VIMENTER},
7722 {"VimLeave", EVENT_VIMLEAVE},
7723 {"VimLeavePre", EVENT_VIMLEAVEPRE},
7724 {"WinEnter", EVENT_WINENTER},
7725 {"WinLeave", EVENT_WINLEAVE},
Bram Moolenaar56718732006-03-15 22:53:57 +00007726 {"VimResized", EVENT_VIMRESIZED},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007727 {NULL, (event_T)0}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007728};
7729
7730static AutoPat *first_autopat[NUM_EVENTS] =
7731{
7732 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7733 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7734 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7735 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00007736 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaar53744302015-07-17 17:38:22 +02007737 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007738};
7739
7740/*
7741 * struct used to keep status while executing autocommands for an event.
7742 */
7743typedef struct AutoPatCmd
7744{
7745 AutoPat *curpat; /* next AutoPat to examine */
7746 AutoCmd *nextcmd; /* next AutoCmd to execute */
7747 int group; /* group being used */
7748 char_u *fname; /* fname to match with */
7749 char_u *sfname; /* sfname to match with */
7750 char_u *tail; /* tail of fname */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007751 event_T event; /* current event */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007752 int arg_bufnr; /* initially equal to <abuf>, set to zero when
7753 buf is deleted */
7754 struct AutoPatCmd *next; /* chain of active apc-s for auto-invalidation*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00007755} AutoPatCmd;
7756
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007757static AutoPatCmd *active_apc_list = NULL; /* stack of active autocommands */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007758
Bram Moolenaar071d4272004-06-13 20:20:40 +00007759/*
7760 * augroups stores a list of autocmd group names.
7761 */
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007762static garray_T augroups = {0, 0, sizeof(char_u *), 10, NULL};
Bram Moolenaar071d4272004-06-13 20:20:40 +00007763#define AUGROUP_NAME(i) (((char_u **)augroups.ga_data)[i])
7764
7765/*
7766 * The ID of the current group. Group 0 is the default one.
7767 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007768static int current_augroup = AUGROUP_DEFAULT;
7769
7770static int au_need_clean = FALSE; /* need to delete marked patterns */
7771
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007772static void show_autocmd(AutoPat *ap, event_T event);
7773static void au_remove_pat(AutoPat *ap);
7774static void au_remove_cmds(AutoPat *ap);
7775static void au_cleanup(void);
7776static int au_new_group(char_u *name);
7777static void au_del_group(char_u *name);
7778static event_T event_name2nr(char_u *start, char_u **end);
7779static char_u *event_nr2name(event_T event);
7780static char_u *find_end_event(char_u *arg, int have_group);
7781static int event_ignored(event_T event);
7782static int au_get_grouparg(char_u **argp);
7783static int do_autocmd_event(event_T event, char_u *pat, int nested, char_u *cmd, int forceit, int group);
7784static int apply_autocmds_group(event_T event, char_u *fname, char_u *fname_io, int force, int group, buf_T *buf, exarg_T *eap);
7785static void auto_next_pat(AutoPatCmd *apc, int stop_at_last);
Bram Moolenaardffa5b82014-11-19 16:38:07 +01007786#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN)
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007787static 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 +01007788#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007789
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007790
Bram Moolenaar754b5602006-02-09 23:53:20 +00007791static event_T last_event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007792static int last_group;
Bram Moolenaar78ab3312007-09-29 12:16:41 +00007793static int autocmd_blocked = 0; /* block all autocmds */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007794
7795/*
7796 * Show the autocommands for one AutoPat.
7797 */
7798 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007799show_autocmd(AutoPat *ap, event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007800{
7801 AutoCmd *ac;
7802
7803 /* Check for "got_int" (here and at various places below), which is set
7804 * when "q" has been hit for the "--more--" prompt */
7805 if (got_int)
7806 return;
7807 if (ap->pat == NULL) /* pattern has been removed */
7808 return;
7809
7810 msg_putchar('\n');
7811 if (got_int)
7812 return;
7813 if (event != last_event || ap->group != last_group)
7814 {
7815 if (ap->group != AUGROUP_DEFAULT)
7816 {
7817 if (AUGROUP_NAME(ap->group) == NULL)
7818 msg_puts_attr((char_u *)_("--Deleted--"), hl_attr(HLF_E));
7819 else
7820 msg_puts_attr(AUGROUP_NAME(ap->group), hl_attr(HLF_T));
7821 msg_puts((char_u *)" ");
7822 }
7823 msg_puts_attr(event_nr2name(event), hl_attr(HLF_T));
7824 last_event = event;
7825 last_group = ap->group;
7826 msg_putchar('\n');
7827 if (got_int)
7828 return;
7829 }
7830 msg_col = 4;
7831 msg_outtrans(ap->pat);
7832
7833 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7834 {
7835 if (ac->cmd != NULL) /* skip removed commands */
7836 {
7837 if (msg_col >= 14)
7838 msg_putchar('\n');
7839 msg_col = 14;
7840 if (got_int)
7841 return;
7842 msg_outtrans(ac->cmd);
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00007843#ifdef FEAT_EVAL
7844 if (p_verbose > 0)
7845 last_set_msg(ac->scriptID);
7846#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007847 if (got_int)
7848 return;
7849 if (ac->next != NULL)
7850 {
7851 msg_putchar('\n');
7852 if (got_int)
7853 return;
7854 }
7855 }
7856 }
7857}
7858
7859/*
7860 * Mark an autocommand pattern for deletion.
7861 */
7862 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007863au_remove_pat(AutoPat *ap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007864{
7865 vim_free(ap->pat);
7866 ap->pat = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007867 ap->buflocal_nr = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007868 au_need_clean = TRUE;
7869}
7870
7871/*
7872 * Mark all commands for a pattern for deletion.
7873 */
7874 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007875au_remove_cmds(AutoPat *ap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007876{
7877 AutoCmd *ac;
7878
7879 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7880 {
7881 vim_free(ac->cmd);
7882 ac->cmd = NULL;
7883 }
7884 au_need_clean = TRUE;
7885}
7886
7887/*
7888 * Cleanup autocommands and patterns that have been deleted.
7889 * This is only done when not executing autocommands.
7890 */
7891 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007892au_cleanup(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007893{
7894 AutoPat *ap, **prev_ap;
7895 AutoCmd *ac, **prev_ac;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007896 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007897
7898 if (autocmd_busy || !au_need_clean)
7899 return;
7900
7901 /* loop over all events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007902 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7903 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007904 {
7905 /* loop over all autocommand patterns */
7906 prev_ap = &(first_autopat[(int)event]);
7907 for (ap = *prev_ap; ap != NULL; ap = *prev_ap)
7908 {
7909 /* loop over all commands for this pattern */
7910 prev_ac = &(ap->cmds);
7911 for (ac = *prev_ac; ac != NULL; ac = *prev_ac)
7912 {
7913 /* remove the command if the pattern is to be deleted or when
7914 * the command has been marked for deletion */
7915 if (ap->pat == NULL || ac->cmd == NULL)
7916 {
7917 *prev_ac = ac->next;
7918 vim_free(ac->cmd);
7919 vim_free(ac);
7920 }
7921 else
7922 prev_ac = &(ac->next);
7923 }
7924
7925 /* remove the pattern if it has been marked for deletion */
7926 if (ap->pat == NULL)
7927 {
7928 *prev_ap = ap->next;
Bram Moolenaar473de612013-06-08 18:19:48 +02007929 vim_regfree(ap->reg_prog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007930 vim_free(ap);
7931 }
7932 else
7933 prev_ap = &(ap->next);
7934 }
7935 }
7936
7937 au_need_clean = FALSE;
7938}
7939
7940/*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007941 * Called when buffer is freed, to remove/invalidate related buffer-local
7942 * autocmds.
7943 */
7944 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007945aubuflocal_remove(buf_T *buf)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007946{
7947 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007948 event_T event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007949 AutoPatCmd *apc;
7950
7951 /* invalidate currently executing autocommands */
7952 for (apc = active_apc_list; apc; apc = apc->next)
7953 if (buf->b_fnum == apc->arg_bufnr)
7954 apc->arg_bufnr = 0;
7955
7956 /* invalidate buflocals looping through events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007957 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7958 event = (event_T)((int)event + 1))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007959 /* loop over all autocommand patterns */
7960 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
7961 if (ap->buflocal_nr == buf->b_fnum)
7962 {
7963 au_remove_pat(ap);
7964 if (p_verbose >= 6)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007965 {
7966 verbose_enter();
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007967 smsg((char_u *)
7968 _("auto-removing autocommand: %s <buffer=%d>"),
7969 event_nr2name(event), buf->b_fnum);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007970 verbose_leave();
7971 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007972 }
7973 au_cleanup();
7974}
7975
7976/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007977 * Add an autocmd group name.
7978 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
7979 */
7980 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007981au_new_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007982{
7983 int i;
7984
7985 i = au_find_group(name);
7986 if (i == AUGROUP_ERROR) /* the group doesn't exist yet, add it */
7987 {
7988 /* First try using a free entry. */
7989 for (i = 0; i < augroups.ga_len; ++i)
7990 if (AUGROUP_NAME(i) == NULL)
7991 break;
7992 if (i == augroups.ga_len && ga_grow(&augroups, 1) == FAIL)
7993 return AUGROUP_ERROR;
7994
7995 AUGROUP_NAME(i) = vim_strsave(name);
7996 if (AUGROUP_NAME(i) == NULL)
7997 return AUGROUP_ERROR;
7998 if (i == augroups.ga_len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007999 ++augroups.ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008000 }
8001
8002 return i;
8003}
8004
8005 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008006au_del_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008007{
8008 int i;
8009
8010 i = au_find_group(name);
8011 if (i == AUGROUP_ERROR) /* the group doesn't exist */
8012 EMSG2(_("E367: No such group: \"%s\""), name);
8013 else
8014 {
8015 vim_free(AUGROUP_NAME(i));
8016 AUGROUP_NAME(i) = NULL;
8017 }
8018}
8019
8020/*
8021 * Find the ID of an autocmd group name.
8022 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
8023 */
8024 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008025au_find_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008026{
8027 int i;
8028
8029 for (i = 0; i < augroups.ga_len; ++i)
8030 if (AUGROUP_NAME(i) != NULL && STRCMP(AUGROUP_NAME(i), name) == 0)
8031 return i;
8032 return AUGROUP_ERROR;
8033}
8034
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008035/*
8036 * Return TRUE if augroup "name" exists.
8037 */
8038 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008039au_has_group(char_u *name)
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008040{
8041 return au_find_group(name) != AUGROUP_ERROR;
8042}
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008043
Bram Moolenaar071d4272004-06-13 20:20:40 +00008044/*
8045 * ":augroup {name}".
8046 */
8047 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008048do_augroup(char_u *arg, int del_group)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008049{
8050 int i;
8051
8052 if (del_group)
8053 {
8054 if (*arg == NUL)
8055 EMSG(_(e_argreq));
8056 else
8057 au_del_group(arg);
8058 }
8059 else if (STRICMP(arg, "end") == 0) /* ":aug end": back to group 0 */
8060 current_augroup = AUGROUP_DEFAULT;
8061 else if (*arg) /* ":aug xxx": switch to group xxx */
8062 {
8063 i = au_new_group(arg);
8064 if (i != AUGROUP_ERROR)
8065 current_augroup = i;
8066 }
8067 else /* ":aug": list the group names */
8068 {
8069 msg_start();
8070 for (i = 0; i < augroups.ga_len; ++i)
8071 {
8072 if (AUGROUP_NAME(i) != NULL)
8073 {
8074 msg_puts(AUGROUP_NAME(i));
8075 msg_puts((char_u *)" ");
8076 }
8077 }
8078 msg_clr_eos();
8079 msg_end();
8080 }
8081}
8082
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008083#if defined(EXITFREE) || defined(PROTO)
8084 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008085free_all_autocmds(void)
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008086{
8087 for (current_augroup = -1; current_augroup < augroups.ga_len;
8088 ++current_augroup)
8089 do_autocmd((char_u *)"", TRUE);
8090 ga_clear_strings(&augroups);
8091}
8092#endif
8093
Bram Moolenaar071d4272004-06-13 20:20:40 +00008094/*
8095 * Return the event number for event name "start".
8096 * Return NUM_EVENTS if the event name was not found.
8097 * Return a pointer to the next event name in "end".
8098 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008099 static event_T
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008100event_name2nr(char_u *start, char_u **end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008101{
8102 char_u *p;
8103 int i;
8104 int len;
8105
8106 /* the event name ends with end of line, a blank or a comma */
8107 for (p = start; *p && !vim_iswhite(*p) && *p != ','; ++p)
8108 ;
8109 for (i = 0; event_names[i].name != NULL; ++i)
8110 {
8111 len = (int)STRLEN(event_names[i].name);
8112 if (len == p - start && STRNICMP(event_names[i].name, start, len) == 0)
8113 break;
8114 }
8115 if (*p == ',')
8116 ++p;
8117 *end = p;
8118 if (event_names[i].name == NULL)
8119 return NUM_EVENTS;
8120 return event_names[i].event;
8121}
8122
8123/*
8124 * Return the name for event "event".
8125 */
8126 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008127event_nr2name(event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008128{
8129 int i;
8130
8131 for (i = 0; event_names[i].name != NULL; ++i)
8132 if (event_names[i].event == event)
8133 return (char_u *)event_names[i].name;
8134 return (char_u *)"Unknown";
8135}
8136
8137/*
8138 * Scan over the events. "*" stands for all events.
8139 */
8140 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008141find_end_event(
8142 char_u *arg,
8143 int have_group) /* TRUE when group name was found */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008144{
8145 char_u *pat;
8146 char_u *p;
8147
8148 if (*arg == '*')
8149 {
8150 if (arg[1] && !vim_iswhite(arg[1]))
8151 {
8152 EMSG2(_("E215: Illegal character after *: %s"), arg);
8153 return NULL;
8154 }
8155 pat = arg + 1;
8156 }
8157 else
8158 {
8159 for (pat = arg; *pat && !vim_iswhite(*pat); pat = p)
8160 {
8161 if ((int)event_name2nr(pat, &p) >= (int)NUM_EVENTS)
8162 {
8163 if (have_group)
8164 EMSG2(_("E216: No such event: %s"), pat);
8165 else
8166 EMSG2(_("E216: No such group or event: %s"), pat);
8167 return NULL;
8168 }
8169 }
8170 }
8171 return pat;
8172}
8173
8174/*
8175 * Return TRUE if "event" is included in 'eventignore'.
8176 */
8177 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008178event_ignored(event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008179{
8180 char_u *p = p_ei;
8181
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008182 while (*p != NUL)
8183 {
8184 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8185 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008186 if (event_name2nr(p, &p) == event)
8187 return TRUE;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008188 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008189
8190 return FALSE;
8191}
8192
8193/*
8194 * Return OK when the contents of p_ei is valid, FAIL otherwise.
8195 */
8196 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008197check_ei(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008198{
8199 char_u *p = p_ei;
8200
Bram Moolenaar071d4272004-06-13 20:20:40 +00008201 while (*p)
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008202 {
8203 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8204 {
8205 p += 3;
8206 if (*p == ',')
8207 ++p;
8208 }
8209 else if (event_name2nr(p, &p) == NUM_EVENTS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008210 return FAIL;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008211 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008212
8213 return OK;
8214}
8215
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008216# if defined(FEAT_SYN_HL) || defined(PROTO)
8217
8218/*
8219 * Add "what" to 'eventignore' to skip loading syntax highlighting for every
8220 * buffer loaded into the window. "what" must start with a comma.
8221 * Returns the old value of 'eventignore' in allocated memory.
8222 */
8223 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008224au_event_disable(char *what)
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008225{
8226 char_u *new_ei;
8227 char_u *save_ei;
8228
8229 save_ei = vim_strsave(p_ei);
8230 if (save_ei != NULL)
8231 {
Bram Moolenaara5792f52005-11-23 21:25:05 +00008232 new_ei = vim_strnsave(p_ei, (int)(STRLEN(p_ei) + STRLEN(what)));
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008233 if (new_ei != NULL)
8234 {
Bram Moolenaar8cac9fd2010-03-02 12:48:05 +01008235 if (*what == ',' && *p_ei == NUL)
8236 STRCPY(new_ei, what + 1);
8237 else
8238 STRCAT(new_ei, what);
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008239 set_string_option_direct((char_u *)"ei", -1, new_ei,
8240 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008241 vim_free(new_ei);
8242 }
8243 }
8244 return save_ei;
8245}
8246
8247 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008248au_event_restore(char_u *old_ei)
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008249{
8250 if (old_ei != NULL)
8251 {
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008252 set_string_option_direct((char_u *)"ei", -1, old_ei,
8253 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008254 vim_free(old_ei);
8255 }
8256}
8257# endif /* FEAT_SYN_HL */
8258
Bram Moolenaar071d4272004-06-13 20:20:40 +00008259/*
8260 * do_autocmd() -- implements the :autocmd command. Can be used in the
8261 * following ways:
8262 *
8263 * :autocmd <event> <pat> <cmd> Add <cmd> to the list of commands that
8264 * will be automatically executed for <event>
8265 * when editing a file matching <pat>, in
8266 * the current group.
8267 * :autocmd <event> <pat> Show the auto-commands associated with
8268 * <event> and <pat>.
8269 * :autocmd <event> Show the auto-commands associated with
8270 * <event>.
8271 * :autocmd Show all auto-commands.
8272 * :autocmd! <event> <pat> <cmd> Remove all auto-commands associated with
8273 * <event> and <pat>, and add the command
8274 * <cmd>, for the current group.
8275 * :autocmd! <event> <pat> Remove all auto-commands associated with
8276 * <event> and <pat> for the current group.
8277 * :autocmd! <event> Remove all auto-commands associated with
8278 * <event> for the current group.
8279 * :autocmd! Remove ALL auto-commands for the current
8280 * group.
8281 *
8282 * Multiple events and patterns may be given separated by commas. Here are
8283 * some examples:
8284 * :autocmd bufread,bufenter *.c,*.h set tw=0 smartindent noic
8285 * :autocmd bufleave * set tw=79 nosmartindent ic infercase
8286 *
8287 * :autocmd * *.c show all autocommands for *.c files.
Bram Moolenaard35f9712005-12-18 22:02:33 +00008288 *
8289 * Mostly a {group} argument can optionally appear before <event>.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008290 */
8291 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008292do_autocmd(char_u *arg, int forceit)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008293{
8294 char_u *pat;
8295 char_u *envpat = NULL;
8296 char_u *cmd;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008297 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008298 int need_free = FALSE;
8299 int nested = FALSE;
8300 int group;
8301
8302 /*
8303 * Check for a legal group name. If not, use AUGROUP_ALL.
8304 */
8305 group = au_get_grouparg(&arg);
8306 if (arg == NULL) /* out of memory */
8307 return;
8308
8309 /*
8310 * Scan over the events.
8311 * If we find an illegal name, return here, don't do anything.
8312 */
8313 pat = find_end_event(arg, group != AUGROUP_ALL);
8314 if (pat == NULL)
8315 return;
8316
8317 /*
8318 * Scan over the pattern. Put a NUL at the end.
8319 */
8320 pat = skipwhite(pat);
8321 cmd = pat;
8322 while (*cmd && (!vim_iswhite(*cmd) || cmd[-1] == '\\'))
8323 cmd++;
8324 if (*cmd)
8325 *cmd++ = NUL;
8326
8327 /* Expand environment variables in the pattern. Set 'shellslash', we want
8328 * forward slashes here. */
8329 if (vim_strchr(pat, '$') != NULL || vim_strchr(pat, '~') != NULL)
8330 {
8331#ifdef BACKSLASH_IN_FILENAME
8332 int p_ssl_save = p_ssl;
8333
8334 p_ssl = TRUE;
8335#endif
8336 envpat = expand_env_save(pat);
8337#ifdef BACKSLASH_IN_FILENAME
8338 p_ssl = p_ssl_save;
8339#endif
8340 if (envpat != NULL)
8341 pat = envpat;
8342 }
8343
8344 /*
8345 * Check for "nested" flag.
8346 */
8347 cmd = skipwhite(cmd);
8348 if (*cmd != NUL && STRNCMP(cmd, "nested", 6) == 0 && vim_iswhite(cmd[6]))
8349 {
8350 nested = TRUE;
8351 cmd = skipwhite(cmd + 6);
8352 }
8353
8354 /*
8355 * Find the start of the commands.
8356 * Expand <sfile> in it.
8357 */
8358 if (*cmd != NUL)
8359 {
8360 cmd = expand_sfile(cmd);
8361 if (cmd == NULL) /* some error */
8362 return;
8363 need_free = TRUE;
8364 }
8365
8366 /*
8367 * Print header when showing autocommands.
8368 */
8369 if (!forceit && *cmd == NUL)
8370 {
8371 /* Highlight title */
8372 MSG_PUTS_TITLE(_("\n--- Auto-Commands ---"));
8373 }
8374
8375 /*
8376 * Loop over the events.
8377 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008378 last_event = (event_T)-1; /* for listing the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008379 last_group = AUGROUP_ERROR; /* for listing the group name */
8380 if (*arg == '*' || *arg == NUL)
8381 {
Bram Moolenaar754b5602006-02-09 23:53:20 +00008382 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8383 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008384 if (do_autocmd_event(event, pat,
8385 nested, cmd, forceit, group) == FAIL)
8386 break;
8387 }
8388 else
8389 {
8390 while (*arg && !vim_iswhite(*arg))
8391 if (do_autocmd_event(event_name2nr(arg, &arg), pat,
8392 nested, cmd, forceit, group) == FAIL)
8393 break;
8394 }
8395
8396 if (need_free)
8397 vim_free(cmd);
8398 vim_free(envpat);
8399}
8400
8401/*
8402 * Find the group ID in a ":autocmd" or ":doautocmd" argument.
8403 * The "argp" argument is advanced to the following argument.
8404 *
8405 * Returns the group ID, AUGROUP_ERROR for error (out of memory).
8406 */
8407 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008408au_get_grouparg(char_u **argp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008409{
8410 char_u *group_name;
8411 char_u *p;
8412 char_u *arg = *argp;
8413 int group = AUGROUP_ALL;
8414
8415 p = skiptowhite(arg);
8416 if (p > arg)
8417 {
8418 group_name = vim_strnsave(arg, (int)(p - arg));
8419 if (group_name == NULL) /* out of memory */
8420 return AUGROUP_ERROR;
8421 group = au_find_group(group_name);
8422 if (group == AUGROUP_ERROR)
8423 group = AUGROUP_ALL; /* no match, use all groups */
8424 else
8425 *argp = skipwhite(p); /* match, skip over group name */
8426 vim_free(group_name);
8427 }
8428 return group;
8429}
8430
8431/*
8432 * do_autocmd() for one event.
8433 * If *pat == NUL do for all patterns.
8434 * If *cmd == NUL show entries.
8435 * If forceit == TRUE delete entries.
8436 * If group is not AUGROUP_ALL, only use this group.
8437 */
8438 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008439do_autocmd_event(
8440 event_T event,
8441 char_u *pat,
8442 int nested,
8443 char_u *cmd,
8444 int forceit,
8445 int group)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008446{
8447 AutoPat *ap;
8448 AutoPat **prev_ap;
8449 AutoCmd *ac;
8450 AutoCmd **prev_ac;
8451 int brace_level;
8452 char_u *endpat;
8453 int findgroup;
8454 int allgroups;
8455 int patlen;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00008456 int is_buflocal;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008457 int buflocal_nr;
8458 char_u buflocal_pat[25]; /* for "<buffer=X>" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008459
8460 if (group == AUGROUP_ALL)
8461 findgroup = current_augroup;
8462 else
8463 findgroup = group;
8464 allgroups = (group == AUGROUP_ALL && !forceit && *cmd == NUL);
8465
8466 /*
8467 * Show or delete all patterns for an event.
8468 */
8469 if (*pat == NUL)
8470 {
8471 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8472 {
8473 if (forceit) /* delete the AutoPat, if it's in the current group */
8474 {
8475 if (ap->group == findgroup)
8476 au_remove_pat(ap);
8477 }
8478 else if (group == AUGROUP_ALL || ap->group == group)
8479 show_autocmd(ap, event);
8480 }
8481 }
8482
8483 /*
8484 * Loop through all the specified patterns.
8485 */
8486 for ( ; *pat; pat = (*endpat == ',' ? endpat + 1 : endpat))
8487 {
8488 /*
8489 * Find end of the pattern.
8490 * Watch out for a comma in braces, like "*.\{obj,o\}".
8491 */
8492 brace_level = 0;
8493 for (endpat = pat; *endpat && (*endpat != ',' || brace_level
Bram Moolenaar6b9be1b2015-07-28 13:33:45 +02008494 || (endpat > pat && endpat[-1] == '\\')); ++endpat)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008495 {
8496 if (*endpat == '{')
8497 brace_level++;
8498 else if (*endpat == '}')
8499 brace_level--;
8500 }
8501 if (pat == endpat) /* ignore single comma */
8502 continue;
8503 patlen = (int)(endpat - pat);
8504
8505 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008506 * detect special <buflocal[=X]> buffer-local patterns
8507 */
8508 is_buflocal = FALSE;
8509 buflocal_nr = 0;
8510
Bram Moolenaar1e997822015-02-17 16:04:57 +01008511 if (patlen >= 8 && STRNCMP(pat, "<buffer", 7) == 0
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008512 && pat[patlen - 1] == '>')
8513 {
Bram Moolenaar1e997822015-02-17 16:04:57 +01008514 /* "<buffer...>": Error will be printed only for addition.
8515 * printing and removing will proceed silently. */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008516 is_buflocal = TRUE;
8517 if (patlen == 8)
Bram Moolenaar1e997822015-02-17 16:04:57 +01008518 /* "<buffer>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008519 buflocal_nr = curbuf->b_fnum;
8520 else if (patlen > 9 && pat[7] == '=')
8521 {
Bram Moolenaar1e997822015-02-17 16:04:57 +01008522 if (patlen == 13 && STRNICMP(pat, "<buffer=abuf>", 13) == 0)
8523 /* "<buffer=abuf>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008524 buflocal_nr = autocmd_bufnr;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008525 else if (skipdigits(pat + 8) == pat + patlen - 1)
Bram Moolenaar1e997822015-02-17 16:04:57 +01008526 /* "<buffer=123>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008527 buflocal_nr = atoi((char *)pat + 8);
8528 }
8529 }
8530
8531 if (is_buflocal)
8532 {
8533 /* normalize pat into standard "<buffer>#N" form */
8534 sprintf((char *)buflocal_pat, "<buffer=%d>", buflocal_nr);
8535 pat = buflocal_pat; /* can modify pat and patlen */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008536 patlen = (int)STRLEN(buflocal_pat); /* but not endpat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008537 }
8538
8539 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008540 * Find AutoPat entries with this pattern.
8541 */
8542 prev_ap = &first_autopat[(int)event];
8543 while ((ap = *prev_ap) != NULL)
8544 {
8545 if (ap->pat != NULL)
8546 {
8547 /* Accept a pattern when:
8548 * - a group was specified and it's that group, or a group was
8549 * not specified and it's the current group, or a group was
8550 * not specified and we are listing
8551 * - the length of the pattern matches
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008552 * - the pattern matches.
8553 * For <buffer[=X]>, this condition works because we normalize
8554 * all buffer-local patterns.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008555 */
8556 if ((allgroups || ap->group == findgroup)
8557 && ap->patlen == patlen
8558 && STRNCMP(pat, ap->pat, patlen) == 0)
8559 {
8560 /*
8561 * Remove existing autocommands.
8562 * If adding any new autocmd's for this AutoPat, don't
8563 * delete the pattern from the autopat list, append to
8564 * this list.
8565 */
8566 if (forceit)
8567 {
8568 if (*cmd != NUL && ap->next == NULL)
8569 {
8570 au_remove_cmds(ap);
8571 break;
8572 }
8573 au_remove_pat(ap);
8574 }
8575
8576 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008577 * Show autocmd's for this autopat, or buflocals <buffer=X>
Bram Moolenaar071d4272004-06-13 20:20:40 +00008578 */
8579 else if (*cmd == NUL)
8580 show_autocmd(ap, event);
8581
8582 /*
8583 * Add autocmd to this autopat, if it's the last one.
8584 */
8585 else if (ap->next == NULL)
8586 break;
8587 }
8588 }
8589 prev_ap = &ap->next;
8590 }
8591
8592 /*
8593 * Add a new command.
8594 */
8595 if (*cmd != NUL)
8596 {
8597 /*
8598 * If the pattern we want to add a command to does appear at the
8599 * end of the list (or not is not in the list at all), add the
8600 * pattern at the end of the list.
8601 */
8602 if (ap == NULL)
8603 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008604 /* refuse to add buffer-local ap if buffer number is invalid */
8605 if (is_buflocal && (buflocal_nr == 0
8606 || buflist_findnr(buflocal_nr) == NULL))
8607 {
8608 EMSGN(_("E680: <buffer=%d>: invalid buffer number "),
8609 buflocal_nr);
8610 return FAIL;
8611 }
8612
Bram Moolenaar071d4272004-06-13 20:20:40 +00008613 ap = (AutoPat *)alloc((unsigned)sizeof(AutoPat));
8614 if (ap == NULL)
8615 return FAIL;
8616 ap->pat = vim_strnsave(pat, patlen);
8617 ap->patlen = patlen;
8618 if (ap->pat == NULL)
8619 {
8620 vim_free(ap);
8621 return FAIL;
8622 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008623
8624 if (is_buflocal)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008625 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008626 ap->buflocal_nr = buflocal_nr;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008627 ap->reg_prog = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008628 }
8629 else
8630 {
Bram Moolenaar748bf032005-02-02 23:04:36 +00008631 char_u *reg_pat;
8632
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008633 ap->buflocal_nr = 0;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008634 reg_pat = file_pat_to_reg_pat(pat, endpat,
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008635 &ap->allow_dirs, TRUE);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008636 if (reg_pat != NULL)
8637 ap->reg_prog = vim_regcomp(reg_pat, RE_MAGIC);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008638 vim_free(reg_pat);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008639 if (reg_pat == NULL || ap->reg_prog == NULL)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008640 {
8641 vim_free(ap->pat);
8642 vim_free(ap);
8643 return FAIL;
8644 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008645 }
8646 ap->cmds = NULL;
8647 *prev_ap = ap;
8648 ap->next = NULL;
8649 if (group == AUGROUP_ALL)
8650 ap->group = current_augroup;
8651 else
8652 ap->group = group;
8653 }
8654
8655 /*
8656 * Add the autocmd at the end of the AutoCmd list.
8657 */
8658 prev_ac = &(ap->cmds);
8659 while ((ac = *prev_ac) != NULL)
8660 prev_ac = &ac->next;
8661 ac = (AutoCmd *)alloc((unsigned)sizeof(AutoCmd));
8662 if (ac == NULL)
8663 return FAIL;
8664 ac->cmd = vim_strsave(cmd);
8665#ifdef FEAT_EVAL
8666 ac->scriptID = current_SID;
8667#endif
8668 if (ac->cmd == NULL)
8669 {
8670 vim_free(ac);
8671 return FAIL;
8672 }
8673 ac->next = NULL;
8674 *prev_ac = ac;
8675 ac->nested = nested;
8676 }
8677 }
8678
8679 au_cleanup(); /* may really delete removed patterns/commands now */
8680 return OK;
8681}
8682
8683/*
8684 * Implementation of ":doautocmd [group] event [fname]".
8685 * Return OK for success, FAIL for failure;
8686 */
8687 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008688do_doautocmd(
8689 char_u *arg,
Bram Moolenaar1610d052016-06-09 22:53:01 +02008690 int do_msg, /* give message for no matching autocmds? */
8691 int *did_something)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008692{
8693 char_u *fname;
8694 int nothing_done = TRUE;
8695 int group;
8696
Bram Moolenaar1610d052016-06-09 22:53:01 +02008697 if (did_something != NULL)
Bram Moolenaar76ae22f2016-06-13 20:00:29 +02008698 *did_something = FALSE;
Bram Moolenaar1610d052016-06-09 22:53:01 +02008699
Bram Moolenaar071d4272004-06-13 20:20:40 +00008700 /*
8701 * Check for a legal group name. If not, use AUGROUP_ALL.
8702 */
8703 group = au_get_grouparg(&arg);
8704 if (arg == NULL) /* out of memory */
8705 return FAIL;
8706
8707 if (*arg == '*')
8708 {
8709 EMSG(_("E217: Can't execute autocommands for ALL events"));
8710 return FAIL;
8711 }
8712
8713 /*
8714 * Scan over the events.
8715 * If we find an illegal name, return here, don't do anything.
8716 */
8717 fname = find_end_event(arg, group != AUGROUP_ALL);
8718 if (fname == NULL)
8719 return FAIL;
8720
8721 fname = skipwhite(fname);
8722
8723 /*
8724 * Loop over the events.
8725 */
8726 while (*arg && !vim_iswhite(*arg))
8727 if (apply_autocmds_group(event_name2nr(arg, &arg),
8728 fname, NULL, TRUE, group, curbuf, NULL))
8729 nothing_done = FALSE;
8730
8731 if (nothing_done && do_msg)
8732 MSG(_("No matching autocommands"));
Bram Moolenaar1610d052016-06-09 22:53:01 +02008733 if (did_something != NULL)
8734 *did_something = !nothing_done;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008735
8736#ifdef FEAT_EVAL
8737 return aborting() ? FAIL : OK;
8738#else
8739 return OK;
8740#endif
8741}
8742
8743/*
8744 * ":doautoall": execute autocommands for each loaded buffer.
8745 */
8746 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008747ex_doautoall(exarg_T *eap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008748{
8749 int retval;
8750 aco_save_T aco;
8751 buf_T *buf;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008752 bufref_T bufref;
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008753 char_u *arg = eap->arg;
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008754 int call_do_modelines = check_nomodeline(&arg);
Bram Moolenaar1610d052016-06-09 22:53:01 +02008755 int did_aucmd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008756
8757 /*
8758 * This is a bit tricky: For some commands curwin->w_buffer needs to be
8759 * equal to curbuf, but for some buffers there may not be a window.
8760 * So we change the buffer for the current window for a moment. This
8761 * gives problems when the autocommands make changes to the list of
8762 * buffers or windows...
8763 */
8764 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8765 {
Bram Moolenaar3a847972008-07-08 09:36:58 +00008766 if (buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008767 {
8768 /* find a window for this buffer and save some values */
8769 aucmd_prepbuf(&aco, buf);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008770 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008771
8772 /* execute the autocommands for this buffer */
Bram Moolenaar1610d052016-06-09 22:53:01 +02008773 retval = do_doautocmd(arg, FALSE, &did_aucmd);
Bram Moolenaareeefcc72007-05-01 21:21:21 +00008774
Bram Moolenaar1610d052016-06-09 22:53:01 +02008775 if (call_do_modelines && did_aucmd)
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008776 {
8777 /* Execute the modeline settings, but don't set window-local
8778 * options if we are using the current window for another
8779 * buffer. */
8780 do_modelines(curwin == aucmd_win ? OPT_NOWIN : 0);
8781 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008782
8783 /* restore the current window */
8784 aucmd_restbuf(&aco);
8785
8786 /* stop if there is some error or buffer was deleted */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008787 if (retval == FAIL || !bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008788 break;
8789 }
8790 }
8791
8792 check_cursor(); /* just in case lines got deleted */
8793}
8794
8795/*
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008796 * Check *argp for <nomodeline>. When it is present return FALSE, otherwise
8797 * return TRUE and advance *argp to after it.
8798 * Thus return TRUE when do_modelines() should be called.
8799 */
8800 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008801check_nomodeline(char_u **argp)
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008802{
8803 if (STRNCMP(*argp, "<nomodeline>", 12) == 0)
8804 {
8805 *argp = skipwhite(*argp + 12);
8806 return FALSE;
8807 }
8808 return TRUE;
8809}
8810
8811/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008812 * Prepare for executing autocommands for (hidden) buffer "buf".
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008813 * Search for a visible window containing the current buffer. If there isn't
8814 * one then use "aucmd_win".
Bram Moolenaar071d4272004-06-13 20:20:40 +00008815 * Set "curbuf" and "curwin" to match "buf".
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00008816 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008817 */
8818 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008819aucmd_prepbuf(
8820 aco_save_T *aco, /* structure to save values in */
8821 buf_T *buf) /* new curbuf */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008822{
8823 win_T *win;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008824#ifdef FEAT_WINDOWS
8825 int save_ea;
8826#endif
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008827#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008828 int save_acd;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008829#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008830
8831 /* Find a window that is for the new buffer */
8832 if (buf == curbuf) /* be quick when buf is curbuf */
8833 win = curwin;
8834 else
8835#ifdef FEAT_WINDOWS
8836 for (win = firstwin; win != NULL; win = win->w_next)
8837 if (win->w_buffer == buf)
8838 break;
8839#else
8840 win = NULL;
8841#endif
8842
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008843 /* Allocate "aucmd_win" when needed. If this fails (out of memory) fall
8844 * back to using the current window. */
8845 if (win == NULL && aucmd_win == NULL)
8846 {
8847 win_alloc_aucmd_win();
8848 if (aucmd_win == NULL)
8849 win = curwin;
8850 }
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008851 if (win == NULL && aucmd_win_used)
8852 /* Strange recursive autocommand, fall back to using the current
8853 * window. Expect a few side effects... */
8854 win = curwin;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008855
8856 aco->save_curwin = curwin;
8857 aco->save_curbuf = curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008858 if (win != NULL)
8859 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008860 /* There is a window for "buf" in the current tab page, make it the
8861 * curwin. This is preferred, it has the least side effects (esp. if
8862 * "buf" is curbuf). */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008863 aco->use_aucmd_win = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008864 curwin = win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008865 }
8866 else
8867 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008868 /* There is no window for "buf", use "aucmd_win". To minimize the side
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02008869 * effects, insert it in the current tab page.
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008870 * Anything related to a window (e.g., setting folds) may have
8871 * unexpected results. */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008872 aco->use_aucmd_win = TRUE;
8873 aucmd_win_used = TRUE;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008874 aucmd_win->w_buffer = buf;
Bram Moolenaarcdddaa42010-06-07 23:07:44 +02008875 aucmd_win->w_s = &buf->b_s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008876 ++buf->b_nwindows;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008877 win_init_empty(aucmd_win); /* set cursor and topline to safe values */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008878
8879 /* Make sure w_localdir and globaldir are NULL to avoid a chdir() in
8880 * win_enter_ext(). */
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008881 vim_free(aucmd_win->w_localdir);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008882 aucmd_win->w_localdir = NULL;
8883 aco->globaldir = globaldir;
8884 globaldir = NULL;
8885
Bram Moolenaar071d4272004-06-13 20:20:40 +00008886
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008887#ifdef FEAT_WINDOWS
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008888 /* Split the current window, put the aucmd_win in the upper half.
8889 * We don't want the BufEnter or WinEnter autocommands. */
8890 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008891 make_snapshot(SNAP_AUCMD_IDX);
8892 save_ea = p_ea;
8893 p_ea = FALSE;
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008894
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008895# ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008896 /* Prevent chdir() call in win_enter_ext(), through do_autochdir(). */
8897 save_acd = p_acd;
8898 p_acd = FALSE;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008899# endif
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008900
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008901 (void)win_split_ins(0, WSP_TOP, aucmd_win, 0);
8902 (void)win_comp_pos(); /* recompute window positions */
8903 p_ea = save_ea;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008904# ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008905 p_acd = save_acd;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008906# endif
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008907 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008908#endif
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008909 curwin = aucmd_win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008910 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008911 curbuf = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008912 aco->new_curwin = curwin;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008913 set_bufref(&aco->new_curbuf, curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008914}
8915
8916/*
8917 * Cleanup after executing autocommands for a (hidden) buffer.
8918 * Restore the window as it was (if possible).
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00008919 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008920 */
8921 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008922aucmd_restbuf(
8923 aco_save_T *aco) /* structure holding saved values */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008924{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008925#ifdef FEAT_WINDOWS
8926 int dummy;
8927#endif
8928
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008929 if (aco->use_aucmd_win)
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008930 {
8931 --curbuf->b_nwindows;
8932#ifdef FEAT_WINDOWS
8933 /* Find "aucmd_win", it can't be closed, but it may be in another tab
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008934 * page. Do not trigger autocommands here. */
8935 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008936 if (curwin != aucmd_win)
8937 {
8938 tabpage_T *tp;
8939 win_T *wp;
8940
8941 FOR_ALL_TAB_WINDOWS(tp, wp)
8942 {
8943 if (wp == aucmd_win)
8944 {
8945 if (tp != curtab)
Bram Moolenaar49e649f2013-05-06 04:50:35 +02008946 goto_tabpage_tp(tp, TRUE, TRUE);
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008947 win_goto(aucmd_win);
Bram Moolenaar28f29082012-02-11 23:45:37 +01008948 goto win_found;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008949 }
8950 }
8951 }
Bram Moolenaar28f29082012-02-11 23:45:37 +01008952win_found:
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008953
8954 /* Remove the window and frame from the tree of frames. */
8955 (void)winframe_remove(curwin, &dummy, NULL);
8956 win_remove(curwin, NULL);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008957 aucmd_win_used = FALSE;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008958 last_status(FALSE); /* may need to remove last status line */
8959 restore_snapshot(SNAP_AUCMD_IDX, FALSE);
8960 (void)win_comp_pos(); /* recompute window positions */
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008961 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008962
8963 if (win_valid(aco->save_curwin))
8964 curwin = aco->save_curwin;
8965 else
8966 /* Hmm, original window disappeared. Just use the first one. */
8967 curwin = firstwin;
8968# ifdef FEAT_EVAL
Bram Moolenaar429fa852013-04-15 12:27:36 +02008969 vars_clear(&aucmd_win->w_vars->dv_hashtab); /* free all w: variables */
8970 hash_init(&aucmd_win->w_vars->dv_hashtab); /* re-use the hashtab */
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008971# endif
8972#else
8973 curwin = aco->save_curwin;
8974#endif
8975 curbuf = curwin->w_buffer;
8976
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008977 vim_free(globaldir);
8978 globaldir = aco->globaldir;
8979
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008980 /* the buffer contents may have changed */
8981 check_cursor();
8982 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
8983 {
8984 curwin->w_topline = curbuf->b_ml.ml_line_count;
8985#ifdef FEAT_DIFF
8986 curwin->w_topfill = 0;
8987#endif
8988 }
8989#if defined(FEAT_GUI)
8990 /* Hide the scrollbars from the aucmd_win and update. */
8991 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_LEFT], FALSE);
8992 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_RIGHT], FALSE);
8993 gui_may_update_scrollbars();
8994#endif
8995 }
8996 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00008997 {
8998 /* restore curwin */
8999#ifdef FEAT_WINDOWS
9000 if (win_valid(aco->save_curwin))
9001#endif
9002 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009003 /* Restore the buffer which was previously edited by curwin, if
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009004 * it was changed, we are still the same window and the buffer is
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009005 * valid. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009006 if (curwin == aco->new_curwin
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009007 && curbuf != aco->new_curbuf.br_buf
9008 && bufref_valid(&aco->new_curbuf)
9009 && aco->new_curbuf.br_buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009010 {
Bram Moolenaar7da9c372012-04-30 17:04:52 +02009011# if defined(FEAT_SYN_HL) || defined(FEAT_SPELL)
9012 if (curwin->w_s == &curbuf->b_s)
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009013 curwin->w_s = &aco->new_curbuf.br_buf->b_s;
Bram Moolenaar7da9c372012-04-30 17:04:52 +02009014# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009015 --curbuf->b_nwindows;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009016 curbuf = aco->new_curbuf.br_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009017 curwin->w_buffer = curbuf;
9018 ++curbuf->b_nwindows;
9019 }
9020
9021 curwin = aco->save_curwin;
9022 curbuf = curwin->w_buffer;
Bram Moolenaar371932a2014-09-09 16:59:38 +02009023 /* In case the autocommand move the cursor to a position that that
9024 * not exist in curbuf. */
9025 check_cursor();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009026 }
9027 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009028}
9029
9030static int autocmd_nested = FALSE;
9031
9032/*
9033 * Execute autocommands for "event" and file name "fname".
9034 * Return TRUE if some commands were executed.
9035 */
9036 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009037apply_autocmds(
9038 event_T event,
9039 char_u *fname, /* NULL or empty means use actual file name */
9040 char_u *fname_io, /* fname to use for <afile> on cmdline */
9041 int force, /* when TRUE, ignore autocmd_busy */
9042 buf_T *buf) /* buffer for <abuf> */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009043{
9044 return apply_autocmds_group(event, fname, fname_io, force,
9045 AUGROUP_ALL, buf, NULL);
9046}
9047
9048/*
9049 * Like apply_autocmds(), but with extra "eap" argument. This takes care of
9050 * setting v:filearg.
9051 */
9052 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009053apply_autocmds_exarg(
9054 event_T event,
9055 char_u *fname,
9056 char_u *fname_io,
9057 int force,
9058 buf_T *buf,
9059 exarg_T *eap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009060{
9061 return apply_autocmds_group(event, fname, fname_io, force,
9062 AUGROUP_ALL, buf, eap);
9063}
9064
9065/*
9066 * Like apply_autocmds(), but handles the caller's retval. If the script
9067 * processing is being aborted or if retval is FAIL when inside a try
9068 * conditional, no autocommands are executed. If otherwise the autocommands
9069 * cause the script to be aborted, retval is set to FAIL.
9070 */
9071 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009072apply_autocmds_retval(
9073 event_T event,
9074 char_u *fname, /* NULL or empty means use actual file name */
9075 char_u *fname_io, /* fname to use for <afile> on cmdline */
9076 int force, /* when TRUE, ignore autocmd_busy */
9077 buf_T *buf, /* buffer for <abuf> */
9078 int *retval) /* pointer to caller's retval */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009079{
9080 int did_cmd;
9081
Bram Moolenaar1e015462005-09-25 22:16:38 +00009082#ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00009083 if (should_abort(*retval))
9084 return FALSE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00009085#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009086
9087 did_cmd = apply_autocmds_group(event, fname, fname_io, force,
9088 AUGROUP_ALL, buf, NULL);
Bram Moolenaar1e015462005-09-25 22:16:38 +00009089 if (did_cmd
9090#ifdef FEAT_EVAL
9091 && aborting()
9092#endif
9093 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00009094 *retval = FAIL;
9095 return did_cmd;
9096}
9097
Bram Moolenaard35f9712005-12-18 22:02:33 +00009098/*
9099 * Return TRUE when there is a CursorHold autocommand defined.
9100 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009101 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009102has_cursorhold(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009103{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009104 return (first_autopat[(int)(get_real_state() == NORMAL_BUSY
9105 ? EVENT_CURSORHOLD : EVENT_CURSORHOLDI)] != NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009106}
Bram Moolenaard35f9712005-12-18 22:02:33 +00009107
9108/*
9109 * Return TRUE if the CursorHold event can be triggered.
9110 */
9111 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009112trigger_cursorhold(void)
Bram Moolenaard35f9712005-12-18 22:02:33 +00009113{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009114 int state;
9115
Bram Moolenaar05334432011-07-20 18:29:39 +02009116 if (!did_cursorhold
9117 && has_cursorhold()
9118 && !Recording
9119 && typebuf.tb_len == 0
Bram Moolenaard29a9ee2006-09-14 09:07:34 +00009120#ifdef FEAT_INS_EXPAND
9121 && !ins_compl_active()
9122#endif
9123 )
Bram Moolenaar754b5602006-02-09 23:53:20 +00009124 {
9125 state = get_real_state();
9126 if (state == NORMAL_BUSY || (state & INSERT) != 0)
9127 return TRUE;
9128 }
9129 return FALSE;
Bram Moolenaard35f9712005-12-18 22:02:33 +00009130}
Bram Moolenaar754b5602006-02-09 23:53:20 +00009131
9132/*
9133 * Return TRUE when there is a CursorMoved autocommand defined.
9134 */
9135 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009136has_cursormoved(void)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009137{
9138 return (first_autopat[(int)EVENT_CURSORMOVED] != NULL);
9139}
9140
9141/*
9142 * Return TRUE when there is a CursorMovedI autocommand defined.
9143 */
9144 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009145has_cursormovedI(void)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009146{
9147 return (first_autopat[(int)EVENT_CURSORMOVEDI] != NULL);
9148}
Bram Moolenaar071d4272004-06-13 20:20:40 +00009149
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009150/*
Bram Moolenaar186628f2013-03-19 13:33:23 +01009151 * Return TRUE when there is a TextChanged autocommand defined.
9152 */
9153 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009154has_textchanged(void)
Bram Moolenaar186628f2013-03-19 13:33:23 +01009155{
9156 return (first_autopat[(int)EVENT_TEXTCHANGED] != NULL);
9157}
9158
9159/*
9160 * Return TRUE when there is a TextChangedI autocommand defined.
9161 */
9162 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009163has_textchangedI(void)
Bram Moolenaar186628f2013-03-19 13:33:23 +01009164{
9165 return (first_autopat[(int)EVENT_TEXTCHANGEDI] != NULL);
9166}
9167
9168/*
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009169 * Return TRUE when there is an InsertCharPre autocommand defined.
9170 */
9171 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009172has_insertcharpre(void)
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009173{
9174 return (first_autopat[(int)EVENT_INSERTCHARPRE] != NULL);
9175}
9176
Bram Moolenaard5005162014-08-22 23:05:54 +02009177/*
9178 * Return TRUE when there is an CmdUndefined autocommand defined.
9179 */
9180 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009181has_cmdundefined(void)
Bram Moolenaard5005162014-08-22 23:05:54 +02009182{
9183 return (first_autopat[(int)EVENT_CMDUNDEFINED] != NULL);
9184}
9185
9186/*
9187 * Return TRUE when there is an FuncUndefined autocommand defined.
9188 */
9189 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009190has_funcundefined(void)
Bram Moolenaard5005162014-08-22 23:05:54 +02009191{
9192 return (first_autopat[(int)EVENT_FUNCUNDEFINED] != NULL);
9193}
9194
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009195/*
9196 * Execute autocommands for "event" and file name "fname".
9197 * Return TRUE if some commands were executed.
9198 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009199 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009200apply_autocmds_group(
9201 event_T event,
9202 char_u *fname, /* NULL or empty means use actual file name */
9203 char_u *fname_io, /* fname to use for <afile> on cmdline, NULL means
Bram Moolenaar071d4272004-06-13 20:20:40 +00009204 use fname */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009205 int force, /* when TRUE, ignore autocmd_busy */
9206 int group, /* group ID, or AUGROUP_ALL */
9207 buf_T *buf, /* buffer for <abuf> */
9208 exarg_T *eap) /* command arguments */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009209{
9210 char_u *sfname = NULL; /* short file name */
9211 char_u *tail;
9212 int save_changed;
9213 buf_T *old_curbuf;
9214 int retval = FALSE;
9215 char_u *save_sourcing_name;
9216 linenr_T save_sourcing_lnum;
9217 char_u *save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009218 int save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009219 int save_autocmd_bufnr;
9220 char_u *save_autocmd_match;
9221 int save_autocmd_busy;
9222 int save_autocmd_nested;
9223 static int nesting = 0;
9224 AutoPatCmd patcmd;
9225 AutoPat *ap;
9226#ifdef FEAT_EVAL
9227 scid_T save_current_SID;
9228 void *save_funccalp;
9229 char_u *save_cmdarg;
9230 long save_cmdbang;
9231#endif
9232 static int filechangeshell_busy = FALSE;
Bram Moolenaar05159a02005-02-26 23:04:13 +00009233#ifdef FEAT_PROFILE
9234 proftime_T wait_time;
9235#endif
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009236 int did_save_redobuff = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009237
9238 /*
9239 * Quickly return if there are no autocommands for this event or
9240 * autocommands are blocked.
9241 */
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009242 if (first_autopat[(int)event] == NULL || autocmd_blocked > 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009243 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009244
9245 /*
9246 * When autocommands are busy, new autocommands are only executed when
9247 * explicitly enabled with the "nested" flag.
9248 */
9249 if (autocmd_busy && !(force || autocmd_nested))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009250 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009251
9252#ifdef FEAT_EVAL
9253 /*
Bram Moolenaar7263a772007-05-10 17:35:54 +00009254 * Quickly return when immediately aborting on error, or when an interrupt
Bram Moolenaar071d4272004-06-13 20:20:40 +00009255 * occurred or an exception was thrown but not caught.
9256 */
9257 if (aborting())
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009258 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009259#endif
9260
9261 /*
9262 * FileChangedShell never nests, because it can create an endless loop.
9263 */
Bram Moolenaar56718732006-03-15 22:53:57 +00009264 if (filechangeshell_busy && (event == EVENT_FILECHANGEDSHELL
9265 || event == EVENT_FILECHANGEDSHELLPOST))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009266 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009267
9268 /*
9269 * Ignore events in 'eventignore'.
9270 */
9271 if (event_ignored(event))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009272 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009273
9274 /*
9275 * Allow nesting of autocommands, but restrict the depth, because it's
9276 * possible to create an endless loop.
9277 */
9278 if (nesting == 10)
9279 {
9280 EMSG(_("E218: autocommand nesting too deep"));
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009281 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009282 }
9283
9284 /*
9285 * Check if these autocommands are disabled. Used when doing ":all" or
9286 * ":ball".
9287 */
9288 if ( (autocmd_no_enter
9289 && (event == EVENT_WINENTER || event == EVENT_BUFENTER))
9290 || (autocmd_no_leave
9291 && (event == EVENT_WINLEAVE || event == EVENT_BUFLEAVE)))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009292 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009293
9294 /*
9295 * Save the autocmd_* variables and info about the current buffer.
9296 */
9297 save_autocmd_fname = autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009298 save_autocmd_fname_full = autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009299 save_autocmd_bufnr = autocmd_bufnr;
9300 save_autocmd_match = autocmd_match;
9301 save_autocmd_busy = autocmd_busy;
9302 save_autocmd_nested = autocmd_nested;
9303 save_changed = curbuf->b_changed;
9304 old_curbuf = curbuf;
9305
9306 /*
9307 * Set the file name to be used for <afile>.
Bram Moolenaara0174af2008-01-02 20:08:25 +00009308 * Make a copy to avoid that changing a buffer name or directory makes it
9309 * invalid.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009310 */
9311 if (fname_io == NULL)
9312 {
Bram Moolenaar53744302015-07-17 17:38:22 +02009313 if (event == EVENT_COLORSCHEME || event == EVENT_OPTIONSET)
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009314 autocmd_fname = NULL;
9315 else if (fname != NULL && *fname != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009316 autocmd_fname = fname;
9317 else if (buf != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009318 autocmd_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009319 else
9320 autocmd_fname = NULL;
9321 }
9322 else
9323 autocmd_fname = fname_io;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009324 if (autocmd_fname != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009325 autocmd_fname = vim_strsave(autocmd_fname);
9326 autocmd_fname_full = FALSE; /* call FullName_save() later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009327
9328 /*
9329 * Set the buffer number to be used for <abuf>.
9330 */
9331 if (buf == NULL)
9332 autocmd_bufnr = 0;
9333 else
9334 autocmd_bufnr = buf->b_fnum;
9335
9336 /*
9337 * When the file name is NULL or empty, use the file name of buffer "buf".
9338 * Always use the full path of the file name to match with, in case
9339 * "allow_dirs" is set.
9340 */
9341 if (fname == NULL || *fname == NUL)
9342 {
9343 if (buf == NULL)
9344 fname = NULL;
9345 else
9346 {
9347#ifdef FEAT_SYN_HL
9348 if (event == EVENT_SYNTAX)
9349 fname = buf->b_p_syn;
9350 else
9351#endif
9352 if (event == EVENT_FILETYPE)
9353 fname = buf->b_p_ft;
9354 else
9355 {
9356 if (buf->b_sfname != NULL)
9357 sfname = vim_strsave(buf->b_sfname);
9358 fname = buf->b_ffname;
9359 }
9360 }
9361 if (fname == NULL)
9362 fname = (char_u *)"";
9363 fname = vim_strsave(fname); /* make a copy, so we can change it */
9364 }
9365 else
9366 {
9367 sfname = vim_strsave(fname);
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009368 /* Don't try expanding FileType, Syntax, FuncUndefined, WindowID,
9369 * ColorScheme or QuickFixCmd* */
Bram Moolenaar7c626922005-02-07 22:01:03 +00009370 if (event == EVENT_FILETYPE
9371 || event == EVENT_SYNTAX
Bram Moolenaar5135d462009-04-29 16:03:38 +00009372 || event == EVENT_FUNCUNDEFINED
Bram Moolenaar7c626922005-02-07 22:01:03 +00009373 || event == EVENT_REMOTEREPLY
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00009374 || event == EVENT_SPELLFILEMISSING
Bram Moolenaar7c626922005-02-07 22:01:03 +00009375 || event == EVENT_QUICKFIXCMDPRE
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009376 || event == EVENT_COLORSCHEME
Bram Moolenaar53744302015-07-17 17:38:22 +02009377 || event == EVENT_OPTIONSET
Bram Moolenaar7c626922005-02-07 22:01:03 +00009378 || event == EVENT_QUICKFIXCMDPOST)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009379 fname = vim_strsave(fname);
9380 else
9381 fname = FullName_save(fname, FALSE);
9382 }
9383 if (fname == NULL) /* out of memory */
9384 {
9385 vim_free(sfname);
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009386 retval = FALSE;
9387 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009388 }
9389
9390#ifdef BACKSLASH_IN_FILENAME
9391 /*
9392 * Replace all backslashes with forward slashes. This makes the
9393 * autocommand patterns portable between Unix and MS-DOS.
9394 */
9395 if (sfname != NULL)
9396 forward_slash(sfname);
9397 forward_slash(fname);
9398#endif
9399
9400#ifdef VMS
9401 /* remove version for correct match */
9402 if (sfname != NULL)
9403 vms_remove_version(sfname);
9404 vms_remove_version(fname);
9405#endif
9406
9407 /*
9408 * Set the name to be used for <amatch>.
9409 */
9410 autocmd_match = fname;
9411
9412
9413 /* Don't redraw while doing auto commands. */
9414 ++RedrawingDisabled;
9415 save_sourcing_name = sourcing_name;
9416 sourcing_name = NULL; /* don't free this one */
9417 save_sourcing_lnum = sourcing_lnum;
9418 sourcing_lnum = 0; /* no line number here */
9419
9420#ifdef FEAT_EVAL
9421 save_current_SID = current_SID;
9422
Bram Moolenaar05159a02005-02-26 23:04:13 +00009423# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009424 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009425 prof_child_enter(&wait_time); /* doesn't count for the caller itself */
9426# endif
9427
Bram Moolenaar071d4272004-06-13 20:20:40 +00009428 /* Don't use local function variables, if called from a function */
9429 save_funccalp = save_funccal();
9430#endif
9431
9432 /*
9433 * When starting to execute autocommands, save the search patterns.
9434 */
9435 if (!autocmd_busy)
9436 {
9437 save_search_patterns();
Bram Moolenaar20ad69c2015-12-03 13:52:52 +01009438#ifdef FEAT_INS_EXPAND
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009439 if (!ins_compl_active())
Bram Moolenaar20ad69c2015-12-03 13:52:52 +01009440#endif
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009441 {
9442 saveRedobuff();
9443 did_save_redobuff = TRUE;
9444 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009445 did_filetype = keep_filetype;
9446 }
9447
9448 /*
9449 * Note that we are applying autocmds. Some commands need to know.
9450 */
9451 autocmd_busy = TRUE;
9452 filechangeshell_busy = (event == EVENT_FILECHANGEDSHELL);
9453 ++nesting; /* see matching decrement below */
9454
9455 /* Remember that FileType was triggered. Used for did_filetype(). */
9456 if (event == EVENT_FILETYPE)
9457 did_filetype = TRUE;
9458
9459 tail = gettail(fname);
9460
9461 /* Find first autocommand that matches */
9462 patcmd.curpat = first_autopat[(int)event];
9463 patcmd.nextcmd = NULL;
9464 patcmd.group = group;
9465 patcmd.fname = fname;
9466 patcmd.sfname = sfname;
9467 patcmd.tail = tail;
9468 patcmd.event = event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009469 patcmd.arg_bufnr = autocmd_bufnr;
9470 patcmd.next = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009471 auto_next_pat(&patcmd, FALSE);
9472
9473 /* found one, start executing the autocommands */
9474 if (patcmd.curpat != NULL)
9475 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009476 /* add to active_apc_list */
9477 patcmd.next = active_apc_list;
9478 active_apc_list = &patcmd;
9479
Bram Moolenaar071d4272004-06-13 20:20:40 +00009480#ifdef FEAT_EVAL
9481 /* set v:cmdarg (only when there is a matching pattern) */
Bram Moolenaar22fcfad2016-07-01 18:17:26 +02009482 save_cmdbang = (long)get_vim_var_nr(VV_CMDBANG);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009483 if (eap != NULL)
9484 {
9485 save_cmdarg = set_cmdarg(eap, NULL);
9486 set_vim_var_nr(VV_CMDBANG, (long)eap->forceit);
9487 }
9488 else
9489 save_cmdarg = NULL; /* avoid gcc warning */
9490#endif
9491 retval = TRUE;
9492 /* mark the last pattern, to avoid an endless loop when more patterns
9493 * are added when executing autocommands */
9494 for (ap = patcmd.curpat; ap->next != NULL; ap = ap->next)
9495 ap->last = FALSE;
9496 ap->last = TRUE;
9497 check_lnums(TRUE); /* make sure cursor and topline are valid */
9498 do_cmdline(NULL, getnextac, (void *)&patcmd,
9499 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
9500#ifdef FEAT_EVAL
9501 if (eap != NULL)
9502 {
9503 (void)set_cmdarg(NULL, save_cmdarg);
9504 set_vim_var_nr(VV_CMDBANG, save_cmdbang);
9505 }
9506#endif
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009507 /* delete from active_apc_list */
9508 if (active_apc_list == &patcmd) /* just in case */
9509 active_apc_list = patcmd.next;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009510 }
9511
9512 --RedrawingDisabled;
9513 autocmd_busy = save_autocmd_busy;
9514 filechangeshell_busy = FALSE;
9515 autocmd_nested = save_autocmd_nested;
9516 vim_free(sourcing_name);
9517 sourcing_name = save_sourcing_name;
9518 sourcing_lnum = save_sourcing_lnum;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009519 vim_free(autocmd_fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009520 autocmd_fname = save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009521 autocmd_fname_full = save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009522 autocmd_bufnr = save_autocmd_bufnr;
9523 autocmd_match = save_autocmd_match;
9524#ifdef FEAT_EVAL
9525 current_SID = save_current_SID;
9526 restore_funccal(save_funccalp);
Bram Moolenaar05159a02005-02-26 23:04:13 +00009527# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009528 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009529 prof_child_exit(&wait_time);
9530# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009531#endif
9532 vim_free(fname);
9533 vim_free(sfname);
9534 --nesting; /* see matching increment above */
9535
9536 /*
9537 * When stopping to execute autocommands, restore the search patterns and
Bram Moolenaar3be85852014-06-12 14:01:31 +02009538 * the redo buffer. Free any buffers in the au_pending_free_buf list and
9539 * free any windows in the au_pending_free_win list.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009540 */
9541 if (!autocmd_busy)
9542 {
9543 restore_search_patterns();
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009544 if (did_save_redobuff)
9545 restoreRedobuff();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009546 did_filetype = FALSE;
Bram Moolenaar4c7ab1b2014-04-06 20:45:43 +02009547 while (au_pending_free_buf != NULL)
9548 {
9549 buf_T *b = au_pending_free_buf->b_next;
9550 vim_free(au_pending_free_buf);
9551 au_pending_free_buf = b;
9552 }
Bram Moolenaar3be85852014-06-12 14:01:31 +02009553 while (au_pending_free_win != NULL)
9554 {
9555 win_T *w = au_pending_free_win->w_next;
9556 vim_free(au_pending_free_win);
9557 au_pending_free_win = w;
9558 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009559 }
9560
9561 /*
9562 * Some events don't set or reset the Changed flag.
9563 * Check if still in the same buffer!
9564 */
9565 if (curbuf == old_curbuf
9566 && (event == EVENT_BUFREADPOST
9567 || event == EVENT_BUFWRITEPOST
9568 || event == EVENT_FILEAPPENDPOST
9569 || event == EVENT_VIMLEAVE
9570 || event == EVENT_VIMLEAVEPRE))
9571 {
9572#ifdef FEAT_TITLE
9573 if (curbuf->b_changed != save_changed)
9574 need_maketitle = TRUE;
9575#endif
9576 curbuf->b_changed = save_changed;
9577 }
9578
9579 au_cleanup(); /* may really delete removed patterns/commands now */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009580
9581BYPASS_AU:
9582 /* When wiping out a buffer make sure all its buffer-local autocommands
9583 * are deleted. */
9584 if (event == EVENT_BUFWIPEOUT && buf != NULL)
9585 aubuflocal_remove(buf);
9586
Bram Moolenaarc3691332016-04-20 12:49:49 +02009587 if (retval == OK && event == EVENT_FILETYPE)
9588 au_did_filetype = TRUE;
9589
Bram Moolenaar071d4272004-06-13 20:20:40 +00009590 return retval;
9591}
9592
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009593# ifdef FEAT_EVAL
9594static char_u *old_termresponse = NULL;
9595# endif
9596
9597/*
9598 * Block triggering autocommands until unblock_autocmd() is called.
9599 * Can be used recursively, so long as it's symmetric.
9600 */
9601 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009602block_autocmds(void)
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009603{
9604# ifdef FEAT_EVAL
9605 /* Remember the value of v:termresponse. */
9606 if (autocmd_blocked == 0)
9607 old_termresponse = get_vim_var_str(VV_TERMRESPONSE);
9608# endif
9609 ++autocmd_blocked;
9610}
9611
9612 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009613unblock_autocmds(void)
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009614{
9615 --autocmd_blocked;
9616
9617# ifdef FEAT_EVAL
9618 /* When v:termresponse was set while autocommands were blocked, trigger
9619 * the autocommands now. Esp. useful when executing a shell command
9620 * during startup (vimdiff). */
9621 if (autocmd_blocked == 0
9622 && get_vim_var_str(VV_TERMRESPONSE) != old_termresponse)
9623 apply_autocmds(EVENT_TERMRESPONSE, NULL, NULL, FALSE, curbuf);
9624# endif
9625}
9626
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009627 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009628is_autocmd_blocked(void)
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009629{
9630 return autocmd_blocked != 0;
9631}
9632
Bram Moolenaar071d4272004-06-13 20:20:40 +00009633/*
9634 * Find next autocommand pattern that matches.
9635 */
9636 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009637auto_next_pat(
9638 AutoPatCmd *apc,
9639 int stop_at_last) /* stop when 'last' flag is set */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009640{
9641 AutoPat *ap;
9642 AutoCmd *cp;
9643 char_u *name;
9644 char *s;
9645
9646 vim_free(sourcing_name);
9647 sourcing_name = NULL;
9648
9649 for (ap = apc->curpat; ap != NULL && !got_int; ap = ap->next)
9650 {
9651 apc->curpat = NULL;
9652
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009653 /* Only use a pattern when it has not been removed, has commands and
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009654 * the group matches. For buffer-local autocommands only check the
9655 * buffer number. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009656 if (ap->pat != NULL && ap->cmds != NULL
9657 && (apc->group == AUGROUP_ALL || apc->group == ap->group))
9658 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009659 /* execution-condition */
9660 if (ap->buflocal_nr == 0
Bram Moolenaardffa5b82014-11-19 16:38:07 +01009661 ? (match_file_pat(NULL, &ap->reg_prog, apc->fname,
Bram Moolenaar748bf032005-02-02 23:04:36 +00009662 apc->sfname, apc->tail, ap->allow_dirs))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009663 : ap->buflocal_nr == apc->arg_bufnr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009664 {
9665 name = event_nr2name(apc->event);
9666 s = _("%s Auto commands for \"%s\"");
9667 sourcing_name = alloc((unsigned)(STRLEN(s)
9668 + STRLEN(name) + ap->patlen + 1));
9669 if (sourcing_name != NULL)
9670 {
9671 sprintf((char *)sourcing_name, s,
9672 (char *)name, (char *)ap->pat);
9673 if (p_verbose >= 8)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009674 {
9675 verbose_enter();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009676 smsg((char_u *)_("Executing %s"), sourcing_name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009677 verbose_leave();
9678 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009679 }
9680
9681 apc->curpat = ap;
9682 apc->nextcmd = ap->cmds;
9683 /* mark last command */
9684 for (cp = ap->cmds; cp->next != NULL; cp = cp->next)
9685 cp->last = FALSE;
9686 cp->last = TRUE;
9687 }
9688 line_breakcheck();
9689 if (apc->curpat != NULL) /* found a match */
9690 break;
9691 }
9692 if (stop_at_last && ap->last)
9693 break;
9694 }
9695}
9696
9697/*
9698 * Get next autocommand command.
9699 * Called by do_cmdline() to get the next line for ":if".
9700 * Returns allocated string, or NULL for end of autocommands.
9701 */
Bram Moolenaar21691f82012-12-05 19:13:18 +01009702 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009703getnextac(int c UNUSED, void *cookie, int indent UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009704{
9705 AutoPatCmd *acp = (AutoPatCmd *)cookie;
9706 char_u *retval;
9707 AutoCmd *ac;
9708
9709 /* Can be called again after returning the last line. */
9710 if (acp->curpat == NULL)
9711 return NULL;
9712
9713 /* repeat until we find an autocommand to execute */
9714 for (;;)
9715 {
9716 /* skip removed commands */
9717 while (acp->nextcmd != NULL && acp->nextcmd->cmd == NULL)
9718 if (acp->nextcmd->last)
9719 acp->nextcmd = NULL;
9720 else
9721 acp->nextcmd = acp->nextcmd->next;
9722
9723 if (acp->nextcmd != NULL)
9724 break;
9725
9726 /* at end of commands, find next pattern that matches */
9727 if (acp->curpat->last)
9728 acp->curpat = NULL;
9729 else
9730 acp->curpat = acp->curpat->next;
9731 if (acp->curpat != NULL)
9732 auto_next_pat(acp, TRUE);
9733 if (acp->curpat == NULL)
9734 return NULL;
9735 }
9736
9737 ac = acp->nextcmd;
9738
9739 if (p_verbose >= 9)
9740 {
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009741 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009742 smsg((char_u *)_("autocommand %s"), ac->cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009743 msg_puts((char_u *)"\n"); /* don't overwrite this either */
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009744 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009745 }
9746 retval = vim_strsave(ac->cmd);
9747 autocmd_nested = ac->nested;
9748#ifdef FEAT_EVAL
9749 current_SID = ac->scriptID;
9750#endif
9751 if (ac->last)
9752 acp->nextcmd = NULL;
9753 else
9754 acp->nextcmd = ac->next;
9755 return retval;
9756}
9757
9758/*
9759 * Return TRUE if there is a matching autocommand for "fname".
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009760 * To account for buffer-local autocommands, function needs to know
9761 * in which buffer the file will be opened.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009762 */
9763 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009764has_autocmd(event_T event, char_u *sfname, buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009765{
9766 AutoPat *ap;
9767 char_u *fname;
9768 char_u *tail = gettail(sfname);
9769 int retval = FALSE;
9770
9771 fname = FullName_save(sfname, FALSE);
9772 if (fname == NULL)
9773 return FALSE;
9774
9775#ifdef BACKSLASH_IN_FILENAME
9776 /*
9777 * Replace all backslashes with forward slashes. This makes the
9778 * autocommand patterns portable between Unix and MS-DOS.
9779 */
9780 sfname = vim_strsave(sfname);
9781 if (sfname != NULL)
9782 forward_slash(sfname);
9783 forward_slash(fname);
9784#endif
9785
9786 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
9787 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009788 && (ap->buflocal_nr == 0
Bram Moolenaardffa5b82014-11-19 16:38:07 +01009789 ? match_file_pat(NULL, &ap->reg_prog,
Bram Moolenaar748bf032005-02-02 23:04:36 +00009790 fname, sfname, tail, ap->allow_dirs)
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009791 : buf != NULL && ap->buflocal_nr == buf->b_fnum
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009792 ))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009793 {
9794 retval = TRUE;
9795 break;
9796 }
9797
9798 vim_free(fname);
9799#ifdef BACKSLASH_IN_FILENAME
9800 vim_free(sfname);
9801#endif
9802
9803 return retval;
9804}
9805
9806#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
9807/*
9808 * Function given to ExpandGeneric() to obtain the list of autocommand group
9809 * names.
9810 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009811 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009812get_augroup_name(expand_T *xp UNUSED, int idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009813{
9814 if (idx == augroups.ga_len) /* add "END" add the end */
9815 return (char_u *)"END";
9816 if (idx >= augroups.ga_len) /* end of list */
9817 return NULL;
9818 if (AUGROUP_NAME(idx) == NULL) /* skip deleted entries */
9819 return (char_u *)"";
9820 return AUGROUP_NAME(idx); /* return a name */
9821}
9822
9823static int include_groups = FALSE;
9824
9825 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009826set_context_in_autocmd(
9827 expand_T *xp,
9828 char_u *arg,
9829 int doautocmd) /* TRUE for :doauto*, FALSE for :autocmd */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009830{
9831 char_u *p;
9832 int group;
9833
9834 /* check for a group name, skip it if present */
9835 include_groups = FALSE;
9836 p = arg;
9837 group = au_get_grouparg(&arg);
9838 if (group == AUGROUP_ERROR)
9839 return NULL;
9840 /* If there only is a group name that's what we expand. */
9841 if (*arg == NUL && group != AUGROUP_ALL && !vim_iswhite(arg[-1]))
9842 {
9843 arg = p;
9844 group = AUGROUP_ALL;
9845 }
9846
9847 /* skip over event name */
9848 for (p = arg; *p != NUL && !vim_iswhite(*p); ++p)
9849 if (*p == ',')
9850 arg = p + 1;
9851 if (*p == NUL)
9852 {
9853 if (group == AUGROUP_ALL)
9854 include_groups = TRUE;
9855 xp->xp_context = EXPAND_EVENTS; /* expand event name */
9856 xp->xp_pattern = arg;
9857 return NULL;
9858 }
9859
9860 /* skip over pattern */
9861 arg = skipwhite(p);
9862 while (*arg && (!vim_iswhite(*arg) || arg[-1] == '\\'))
9863 arg++;
9864 if (*arg)
9865 return arg; /* expand (next) command */
9866
9867 if (doautocmd)
9868 xp->xp_context = EXPAND_FILES; /* expand file names */
9869 else
9870 xp->xp_context = EXPAND_NOTHING; /* pattern is not expanded */
9871 return NULL;
9872}
9873
9874/*
9875 * Function given to ExpandGeneric() to obtain the list of event names.
9876 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009877 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009878get_event_name(expand_T *xp UNUSED, int idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009879{
9880 if (idx < augroups.ga_len) /* First list group names, if wanted */
9881 {
9882 if (!include_groups || AUGROUP_NAME(idx) == NULL)
9883 return (char_u *)""; /* skip deleted entries */
9884 return AUGROUP_NAME(idx); /* return a name */
9885 }
9886 return (char_u *)event_names[idx - augroups.ga_len].name;
9887}
9888
9889#endif /* FEAT_CMDL_COMPL */
9890
9891/*
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009892 * Return TRUE if autocmd is supported.
9893 */
9894 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009895autocmd_supported(char_u *name)
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009896{
9897 char_u *p;
9898
9899 return (event_name2nr(name, &p) != NUM_EVENTS);
9900}
9901
9902/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00009903 * Return TRUE if an autocommand is defined for a group, event and
9904 * pattern: The group can be omitted to accept any group. "event" and "pattern"
9905 * can be NULL to accept any event and pattern. "pattern" can be NULL to accept
9906 * any pattern. Buffer-local patterns <buffer> or <buffer=N> are accepted.
9907 * Used for:
9908 * exists("#Group") or
9909 * exists("#Group#Event") or
9910 * exists("#Group#Event#pat") or
9911 * exists("#Event") or
9912 * exists("#Event#pat")
Bram Moolenaar071d4272004-06-13 20:20:40 +00009913 */
9914 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009915au_exists(char_u *arg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009916{
Bram Moolenaar195d6352005-12-19 22:08:24 +00009917 char_u *arg_save;
9918 char_u *pattern = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009919 char_u *event_name;
9920 char_u *p;
Bram Moolenaar754b5602006-02-09 23:53:20 +00009921 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009922 AutoPat *ap;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009923 buf_T *buflocal_buf = NULL;
Bram Moolenaar195d6352005-12-19 22:08:24 +00009924 int group;
9925 int retval = FALSE;
9926
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009927 /* Make a copy so that we can change the '#' chars to a NUL. */
Bram Moolenaar195d6352005-12-19 22:08:24 +00009928 arg_save = vim_strsave(arg);
9929 if (arg_save == NULL)
9930 return FALSE;
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009931 p = vim_strchr(arg_save, '#');
Bram Moolenaar195d6352005-12-19 22:08:24 +00009932 if (p != NULL)
9933 *p++ = NUL;
9934
9935 /* First, look for an autocmd group name */
9936 group = au_find_group(arg_save);
9937 if (group == AUGROUP_ERROR)
9938 {
9939 /* Didn't match a group name, assume the first argument is an event. */
9940 group = AUGROUP_ALL;
9941 event_name = arg_save;
9942 }
9943 else
9944 {
9945 if (p == NULL)
9946 {
9947 /* "Group": group name is present and it's recognized */
9948 retval = TRUE;
9949 goto theend;
9950 }
9951
9952 /* Must be "Group#Event" or "Group#Event#pat". */
9953 event_name = p;
9954 p = vim_strchr(event_name, '#');
9955 if (p != NULL)
9956 *p++ = NUL; /* "Group#Event#pat" */
9957 }
9958
9959 pattern = p; /* "pattern" is NULL when there is no pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009960
9961 /* find the index (enum) for the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009962 event = event_name2nr(event_name, &p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009963
9964 /* return FALSE if the event name is not recognized */
Bram Moolenaar195d6352005-12-19 22:08:24 +00009965 if (event == NUM_EVENTS)
9966 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009967
9968 /* Find the first autocommand for this event.
9969 * If there isn't any, return FALSE;
9970 * If there is one and no pattern given, return TRUE; */
9971 ap = first_autopat[(int)event];
9972 if (ap == NULL)
Bram Moolenaar195d6352005-12-19 22:08:24 +00009973 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009974
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009975 /* if pattern is "<buffer>", special handling is needed which uses curbuf */
9976 /* for pattern "<buffer=N>, fnamecmp() will work fine */
Bram Moolenaar5b7880d2009-09-11 15:24:31 +00009977 if (pattern != NULL && STRICMP(pattern, "<buffer>") == 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009978 buflocal_buf = curbuf;
9979
Bram Moolenaar071d4272004-06-13 20:20:40 +00009980 /* Check if there is an autocommand with the given pattern. */
9981 for ( ; ap != NULL; ap = ap->next)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009982 /* only use a pattern when it has not been removed and has commands. */
9983 /* For buffer-local autocommands, fnamecmp() works fine. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009984 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaar195d6352005-12-19 22:08:24 +00009985 && (group == AUGROUP_ALL || ap->group == group)
Bram Moolenaar5b7880d2009-09-11 15:24:31 +00009986 && (pattern == NULL
9987 || (buflocal_buf == NULL
9988 ? fnamecmp(ap->pat, pattern) == 0
9989 : ap->buflocal_nr == buflocal_buf->b_fnum)))
Bram Moolenaar195d6352005-12-19 22:08:24 +00009990 {
9991 retval = TRUE;
9992 break;
9993 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009994
Bram Moolenaar195d6352005-12-19 22:08:24 +00009995theend:
9996 vim_free(arg_save);
9997 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009998}
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009999
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010000#else /* FEAT_AUTOCMD */
10001
10002/*
10003 * Prepare for executing commands for (hidden) buffer "buf".
10004 * This is the non-autocommand version, it simply saves "curbuf" and sets
10005 * "curbuf" and "curwin" to match "buf".
10006 */
10007 void
Bram Moolenaard14e00e2016-01-31 17:30:51 +010010008aucmd_prepbuf(
10009 aco_save_T *aco, /* structure to save values in */
10010 buf_T *buf) /* new curbuf */
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010011{
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010012 aco->save_curbuf = curbuf;
10013 --curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010014 curbuf = buf;
10015 curwin->w_buffer = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010016 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010017}
10018
10019/*
10020 * Restore after executing commands for a (hidden) buffer.
10021 * This is the non-autocommand version.
10022 */
10023 void
Bram Moolenaard14e00e2016-01-31 17:30:51 +010010024aucmd_restbuf(
10025 aco_save_T *aco) /* structure holding saved values */
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010026{
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010027 --curbuf->b_nwindows;
10028 curbuf = aco->save_curbuf;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010029 curwin->w_buffer = curbuf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010030 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010031}
10032
Bram Moolenaar071d4272004-06-13 20:20:40 +000010033#endif /* FEAT_AUTOCMD */
10034
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010035
Bram Moolenaar071d4272004-06-13 20:20:40 +000010036#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN) || defined(PROTO)
10037/*
Bram Moolenaar748bf032005-02-02 23:04:36 +000010038 * Try matching a filename with a "pattern" ("prog" is NULL), or use the
10039 * precompiled regprog "prog" ("pattern" is NULL). That avoids calling
10040 * vim_regcomp() often.
Bram Moolenaar071d4272004-06-13 20:20:40 +000010041 * Used for autocommands and 'wildignore'.
10042 * Returns TRUE if there is a match, FALSE otherwise.
10043 */
Bram Moolenaardffa5b82014-11-19 16:38:07 +010010044 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010045match_file_pat(
10046 char_u *pattern, /* pattern to match with */
10047 regprog_T **prog, /* pre-compiled regprog or NULL */
10048 char_u *fname, /* full path of file name */
10049 char_u *sfname, /* short file name or NULL */
10050 char_u *tail, /* tail of path */
10051 int allow_dirs) /* allow matching with dir */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010052{
10053 regmatch_T regmatch;
10054 int result = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010055
Bram Moolenaar71afbfe2013-03-19 16:49:16 +010010056 regmatch.rm_ic = p_fic; /* ignore case if 'fileignorecase' is set */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010057 if (prog != NULL)
10058 regmatch.regprog = *prog;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010059 else
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010060 regmatch.regprog = vim_regcomp(pattern, RE_MAGIC);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010061
10062 /*
10063 * Try for a match with the pattern with:
10064 * 1. the full file name, when the pattern has a '/'.
10065 * 2. the short file name, when the pattern has a '/'.
10066 * 3. the tail of the file name, when the pattern has no '/'.
10067 */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010068 if (regmatch.regprog != NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +000010069 && ((allow_dirs
10070 && (vim_regexec(&regmatch, fname, (colnr_T)0)
10071 || (sfname != NULL
10072 && vim_regexec(&regmatch, sfname, (colnr_T)0))))
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010073 || (!allow_dirs && vim_regexec(&regmatch, tail, (colnr_T)0))))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010074 result = TRUE;
10075
Bram Moolenaardffa5b82014-11-19 16:38:07 +010010076 if (prog != NULL)
10077 *prog = regmatch.regprog;
10078 else
Bram Moolenaar473de612013-06-08 18:19:48 +020010079 vim_regfree(regmatch.regprog);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010080 return result;
10081}
10082#endif
10083
10084#if defined(FEAT_WILDIGN) || defined(PROTO)
10085/*
10086 * Return TRUE if a file matches with a pattern in "list".
10087 * "list" is a comma-separated list of patterns, like 'wildignore'.
10088 * "sfname" is the short file name or NULL, "ffname" the long file name.
10089 */
10090 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010091match_file_list(char_u *list, char_u *sfname, char_u *ffname)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010092{
10093 char_u buf[100];
10094 char_u *tail;
10095 char_u *regpat;
10096 char allow_dirs;
10097 int match;
10098 char_u *p;
10099
10100 tail = gettail(sfname);
10101
10102 /* try all patterns in 'wildignore' */
10103 p = list;
10104 while (*p)
10105 {
10106 copy_option_part(&p, buf, 100, ",");
10107 regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, FALSE);
10108 if (regpat == NULL)
10109 break;
Bram Moolenaar748bf032005-02-02 23:04:36 +000010110 match = match_file_pat(regpat, NULL, ffname, sfname,
10111 tail, (int)allow_dirs);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010112 vim_free(regpat);
10113 if (match)
10114 return TRUE;
10115 }
10116 return FALSE;
10117}
10118#endif
10119
10120/*
10121 * Convert the given pattern "pat" which has shell style wildcards in it, into
10122 * a regular expression, and return the result in allocated memory. If there
10123 * is a directory path separator to be matched, then TRUE is put in
10124 * allow_dirs, otherwise FALSE is put there -- webb.
10125 * Handle backslashes before special characters, like "\*" and "\ ".
10126 *
Bram Moolenaar071d4272004-06-13 20:20:40 +000010127 * Returns NULL when out of memory.
10128 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010129 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010130file_pat_to_reg_pat(
10131 char_u *pat,
10132 char_u *pat_end, /* first char after pattern or NULL */
10133 char *allow_dirs, /* Result passed back out in here */
10134 int no_bslash UNUSED) /* Don't use a backward slash as pathsep */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010135{
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010136 int size = 2; /* '^' at start, '$' at end */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010137 char_u *endp;
10138 char_u *reg_pat;
10139 char_u *p;
10140 int i;
10141 int nested = 0;
10142 int add_dollar = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010143
10144 if (allow_dirs != NULL)
10145 *allow_dirs = FALSE;
10146 if (pat_end == NULL)
10147 pat_end = pat + STRLEN(pat);
10148
Bram Moolenaar071d4272004-06-13 20:20:40 +000010149 for (p = pat; p < pat_end; p++)
10150 {
10151 switch (*p)
10152 {
10153 case '*':
10154 case '.':
10155 case ',':
10156 case '{':
10157 case '}':
10158 case '~':
10159 size += 2; /* extra backslash */
10160 break;
10161#ifdef BACKSLASH_IN_FILENAME
10162 case '\\':
10163 case '/':
10164 size += 4; /* could become "[\/]" */
10165 break;
10166#endif
10167 default:
10168 size++;
Bram Moolenaar2288afe2015-08-11 16:20:05 +020010169# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010170 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010171 {
10172 ++p;
10173 ++size;
10174 }
10175# endif
10176 break;
10177 }
10178 }
10179 reg_pat = alloc(size + 1);
10180 if (reg_pat == NULL)
10181 return NULL;
10182
Bram Moolenaar071d4272004-06-13 20:20:40 +000010183 i = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010184
10185 if (pat[0] == '*')
10186 while (pat[0] == '*' && pat < pat_end - 1)
10187 pat++;
10188 else
10189 reg_pat[i++] = '^';
10190 endp = pat_end - 1;
Bram Moolenaar8fee8782015-08-11 18:45:48 +020010191 if (endp >= pat && *endp == '*')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010192 {
10193 while (endp - pat > 0 && *endp == '*')
10194 endp--;
10195 add_dollar = FALSE;
10196 }
10197 for (p = pat; *p && nested >= 0 && p <= endp; p++)
10198 {
10199 switch (*p)
10200 {
10201 case '*':
10202 reg_pat[i++] = '.';
10203 reg_pat[i++] = '*';
Bram Moolenaar02743632005-07-25 20:42:36 +000010204 while (p[1] == '*') /* "**" matches like "*" */
10205 ++p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010206 break;
10207 case '.':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010208 case '~':
10209 reg_pat[i++] = '\\';
10210 reg_pat[i++] = *p;
10211 break;
10212 case '?':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010213 reg_pat[i++] = '.';
10214 break;
10215 case '\\':
10216 if (p[1] == NUL)
10217 break;
10218#ifdef BACKSLASH_IN_FILENAME
10219 if (!no_bslash)
10220 {
10221 /* translate:
10222 * "\x" to "\\x" e.g., "dir\file"
10223 * "\*" to "\\.*" e.g., "dir\*.c"
10224 * "\?" to "\\." e.g., "dir\??.c"
10225 * "\+" to "\+" e.g., "fileX\+.c"
10226 */
10227 if ((vim_isfilec(p[1]) || p[1] == '*' || p[1] == '?')
10228 && p[1] != '+')
10229 {
10230 reg_pat[i++] = '[';
10231 reg_pat[i++] = '\\';
10232 reg_pat[i++] = '/';
10233 reg_pat[i++] = ']';
10234 if (allow_dirs != NULL)
10235 *allow_dirs = TRUE;
10236 break;
10237 }
10238 }
10239#endif
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010240 /* Undo escaping from ExpandEscape():
10241 * foo\?bar -> foo?bar
10242 * foo\%bar -> foo%bar
10243 * foo\,bar -> foo,bar
10244 * foo\ bar -> foo bar
10245 * Don't unescape \, * and others that are also special in a
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010246 * regexp.
10247 * An escaped { must be unescaped since we use magic not
Bram Moolenaara946afe2013-08-02 15:22:39 +020010248 * verymagic. Use "\\\{n,m\}"" to get "\{n,m}".
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010249 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010250 if (*++p == '?'
10251#ifdef BACKSLASH_IN_FILENAME
10252 && no_bslash
10253#endif
10254 )
10255 reg_pat[i++] = '?';
10256 else
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010257 if (*p == ',' || *p == '%' || *p == '#'
Bram Moolenaar2288afe2015-08-11 16:20:05 +020010258 || vim_isspace(*p) || *p == '{' || *p == '}')
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010259 reg_pat[i++] = *p;
Bram Moolenaara946afe2013-08-02 15:22:39 +020010260 else if (*p == '\\' && p[1] == '\\' && p[2] == '{')
10261 {
10262 reg_pat[i++] = '\\';
10263 reg_pat[i++] = '{';
10264 p += 2;
10265 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010266 else
10267 {
10268 if (allow_dirs != NULL && vim_ispathsep(*p)
10269#ifdef BACKSLASH_IN_FILENAME
10270 && (!no_bslash || *p != '\\')
10271#endif
10272 )
10273 *allow_dirs = TRUE;
10274 reg_pat[i++] = '\\';
10275 reg_pat[i++] = *p;
10276 }
10277 break;
10278#ifdef BACKSLASH_IN_FILENAME
10279 case '/':
10280 reg_pat[i++] = '[';
10281 reg_pat[i++] = '\\';
10282 reg_pat[i++] = '/';
10283 reg_pat[i++] = ']';
10284 if (allow_dirs != NULL)
10285 *allow_dirs = TRUE;
10286 break;
10287#endif
10288 case '{':
10289 reg_pat[i++] = '\\';
10290 reg_pat[i++] = '(';
10291 nested++;
10292 break;
10293 case '}':
10294 reg_pat[i++] = '\\';
10295 reg_pat[i++] = ')';
10296 --nested;
10297 break;
10298 case ',':
10299 if (nested)
10300 {
10301 reg_pat[i++] = '\\';
10302 reg_pat[i++] = '|';
10303 }
10304 else
10305 reg_pat[i++] = ',';
10306 break;
10307 default:
10308# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010309 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010310 reg_pat[i++] = *p++;
10311 else
10312# endif
10313 if (allow_dirs != NULL && vim_ispathsep(*p))
10314 *allow_dirs = TRUE;
10315 reg_pat[i++] = *p;
10316 break;
10317 }
10318 }
10319 if (add_dollar)
10320 reg_pat[i++] = '$';
10321 reg_pat[i] = NUL;
10322 if (nested != 0)
10323 {
10324 if (nested < 0)
10325 EMSG(_("E219: Missing {."));
10326 else
10327 EMSG(_("E220: Missing }."));
10328 vim_free(reg_pat);
10329 reg_pat = NULL;
10330 }
10331 return reg_pat;
10332}
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010333
10334#if defined(EINTR) || defined(PROTO)
10335/*
10336 * Version of read() that retries when interrupted by EINTR (possibly
10337 * by a SIGWINCH).
10338 */
10339 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010340read_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010341{
10342 long ret;
10343
10344 for (;;)
10345 {
10346 ret = vim_read(fd, buf, bufsize);
10347 if (ret >= 0 || errno != EINTR)
10348 break;
10349 }
10350 return ret;
10351}
10352
10353/*
10354 * Version of write() that retries when interrupted by EINTR (possibly
10355 * by a SIGWINCH).
10356 */
10357 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010358write_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010359{
10360 long ret = 0;
10361 long wlen;
10362
10363 /* Repeat the write() so long it didn't fail, other than being interrupted
10364 * by a signal. */
10365 while (ret < (long)bufsize)
10366 {
Bram Moolenaar9c263032010-12-17 18:06:06 +010010367 wlen = vim_write(fd, (char *)buf + ret, bufsize - ret);
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010368 if (wlen < 0)
10369 {
10370 if (errno != EINTR)
10371 break;
10372 }
10373 else
10374 ret += wlen;
10375 }
10376 return ret;
10377}
10378#endif