blob: 235b412fa9d8d4e880ac5356a8732ea4978bc629 [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
Bram Moolenaarda412772016-07-14 20:37:07 +02004712 /*
4713 * Probably need to set the ACL before changing the user (can't set the
4714 * ACL on a file the user doesn't own).
4715 * On Solaris, with ZFS and the aclmode property set to "discard" (the
4716 * default), chmod() discards all part of a file's ACL that don't represent
4717 * the mode of the file. It's non-trivial for us to discover whether we're
4718 * in that situation, so we simply always re-set the ACL.
4719 */
4720# ifndef HAVE_SOLARIS_ZFS_ACL
Bram Moolenaar071d4272004-06-13 20:20:40 +00004721 if (!backup_copy)
Bram Moolenaarda412772016-07-14 20:37:07 +02004722# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004723 mch_set_acl(wfname, acl);
4724#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004725#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004726 if (buf->b_cryptstate != NULL)
4727 {
4728 crypt_free_state(buf->b_cryptstate);
4729 buf->b_cryptstate = NULL;
4730 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004731#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004732
Bram Moolenaar071d4272004-06-13 20:20:40 +00004733#if defined(FEAT_MBYTE) && defined(FEAT_EVAL)
4734 if (wfname != fname)
4735 {
4736 /*
4737 * The file was written to a temp file, now it needs to be converted
4738 * with 'charconvert' to (overwrite) the output file.
4739 */
4740 if (end != 0)
4741 {
4742 if (eval_charconvert(enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc,
4743 wfname, fname) == FAIL)
4744 {
4745 write_info.bw_conv_error = TRUE;
4746 end = 0;
4747 }
4748 }
4749 mch_remove(wfname);
4750 vim_free(wfname);
4751 }
4752#endif
4753
4754 if (end == 0)
4755 {
4756 if (errmsg == NULL)
4757 {
4758#ifdef FEAT_MBYTE
4759 if (write_info.bw_conv_error)
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004760 {
4761 if (write_info.bw_conv_error_lnum == 0)
4762 errmsg = (char_u *)_("E513: write error, conversion failed (make 'fenc' empty to override)");
4763 else
4764 {
4765 errmsg_allocated = TRUE;
4766 errmsg = alloc(300);
4767 vim_snprintf((char *)errmsg, 300, _("E513: write error, conversion failed in line %ld (make 'fenc' empty to override)"),
4768 (long)write_info.bw_conv_error_lnum);
4769 }
4770 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004771 else
4772#endif
4773 if (got_int)
4774 errmsg = (char_u *)_(e_interr);
4775 else
4776 errmsg = (char_u *)_("E514: write error (file system full?)");
4777 }
4778
4779 /*
4780 * If we have a backup file, try to put it in place of the new file,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004781 * because the new file is probably corrupt. This avoids losing the
Bram Moolenaar071d4272004-06-13 20:20:40 +00004782 * original file when trying to make a backup when writing the file a
4783 * second time.
4784 * When "backup_copy" is set we need to copy the backup over the new
4785 * file. Otherwise rename the backup file.
4786 * If this is OK, don't give the extra warning message.
4787 */
4788 if (backup != NULL)
4789 {
4790 if (backup_copy)
4791 {
4792 /* This may take a while, if we were interrupted let the user
4793 * know we got the message. */
4794 if (got_int)
4795 {
4796 MSG(_(e_interr));
4797 out_flush();
4798 }
4799 if ((fd = mch_open((char *)backup, O_RDONLY | O_EXTRA, 0)) >= 0)
4800 {
4801 if ((write_info.bw_fd = mch_open((char *)fname,
Bram Moolenaar9be038d2005-03-08 22:34:32 +00004802 O_WRONLY | O_CREAT | O_TRUNC | O_EXTRA,
4803 perm & 0777)) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004804 {
4805 /* copy the file. */
4806 write_info.bw_buf = smallbuf;
4807#ifdef HAS_BW_FLAGS
4808 write_info.bw_flags = FIO_NOCONVERT;
4809#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004810 while ((write_info.bw_len = read_eintr(fd, smallbuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004811 SMBUFSIZE)) > 0)
4812 if (buf_write_bytes(&write_info) == FAIL)
4813 break;
4814
4815 if (close(write_info.bw_fd) >= 0
4816 && write_info.bw_len == 0)
4817 end = 1; /* success */
4818 }
4819 close(fd); /* ignore errors for closing read file */
4820 }
4821 }
4822 else
4823 {
4824 if (vim_rename(backup, fname) == 0)
4825 end = 1;
4826 }
4827 }
4828 goto fail;
4829 }
4830
4831 lnum -= start; /* compute number of written lines */
4832 --no_wait_return; /* may wait for return now */
4833
4834#if !(defined(UNIX) || defined(VMS))
4835 fname = sfname; /* use shortname now, for the messages */
4836#endif
4837 if (!filtering)
4838 {
4839 msg_add_fname(buf, fname); /* put fname in IObuff with quotes */
4840 c = FALSE;
4841#ifdef FEAT_MBYTE
4842 if (write_info.bw_conv_error)
4843 {
4844 STRCAT(IObuff, _(" CONVERSION ERROR"));
4845 c = TRUE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004846 if (write_info.bw_conv_error_lnum != 0)
Bram Moolenaara800b422010-06-27 01:15:55 +02004847 vim_snprintf_add((char *)IObuff, IOSIZE, _(" in line %ld;"),
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004848 (long)write_info.bw_conv_error_lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004849 }
4850 else if (notconverted)
4851 {
4852 STRCAT(IObuff, _("[NOT converted]"));
4853 c = TRUE;
4854 }
4855 else if (converted)
4856 {
4857 STRCAT(IObuff, _("[converted]"));
4858 c = TRUE;
4859 }
4860#endif
4861 if (device)
4862 {
4863 STRCAT(IObuff, _("[Device]"));
4864 c = TRUE;
4865 }
4866 else if (newfile)
4867 {
4868 STRCAT(IObuff, shortmess(SHM_NEW) ? _("[New]") : _("[New File]"));
4869 c = TRUE;
4870 }
4871 if (no_eol)
4872 {
4873 msg_add_eol();
4874 c = TRUE;
4875 }
4876 /* may add [unix/dos/mac] */
4877 if (msg_add_fileformat(fileformat))
4878 c = TRUE;
4879#ifdef FEAT_CRYPT
4880 if (wb_flags & FIO_ENCRYPTED)
4881 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004882 crypt_append_msg(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004883 c = TRUE;
4884 }
4885#endif
4886 msg_add_lines(c, (long)lnum, nchars); /* add line/char count */
4887 if (!shortmess(SHM_WRITE))
4888 {
4889 if (append)
4890 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended"));
4891 else
4892 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written"));
4893 }
4894
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00004895 set_keep_msg(msg_trunc_attr(IObuff, FALSE, 0), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004896 }
4897
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004898 /* When written everything correctly: reset 'modified'. Unless not
4899 * writing to the original file and '+' is not in 'cpoptions'. */
Bram Moolenaar292ad192005-12-11 21:29:51 +00004900 if (reset_changed && whole && !append
Bram Moolenaar071d4272004-06-13 20:20:40 +00004901#ifdef FEAT_MBYTE
4902 && !write_info.bw_conv_error
4903#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004904 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL)
4905 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004906 {
4907 unchanged(buf, TRUE);
Bram Moolenaar086329d2014-10-31 19:51:36 +01004908#ifdef FEAT_AUTOCMD
4909 /* buf->b_changedtick is always incremented in unchanged() but that
4910 * should not trigger a TextChanged event. */
4911 if (last_changedtick + 1 == buf->b_changedtick
4912 && last_changedtick_buf == buf)
4913 last_changedtick = buf->b_changedtick;
4914#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004915 u_unchanged(buf);
Bram Moolenaar730cde92010-06-27 05:18:54 +02004916 u_update_save_nr(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004917 }
4918
4919 /*
4920 * If written to the current file, update the timestamp of the swap file
4921 * and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
4922 */
4923 if (overwriting)
4924 {
4925 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00004926 if (append)
4927 buf->b_flags &= ~BF_NEW;
4928 else
4929 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004930 }
4931
4932 /*
4933 * If we kept a backup until now, and we are in patch mode, then we make
4934 * the backup file our 'original' file.
4935 */
4936 if (*p_pm && dobackup)
4937 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01004938 char *org = (char *)buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00004939 fname, p_pm, FALSE);
4940
4941 if (backup != NULL)
4942 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02004943 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004944
4945 /*
4946 * If the original file does not exist yet
4947 * the current backup file becomes the original file
4948 */
4949 if (org == NULL)
4950 EMSG(_("E205: Patchmode: can't save original file"));
4951 else if (mch_stat(org, &st) < 0)
4952 {
4953 vim_rename(backup, (char_u *)org);
4954 vim_free(backup); /* don't delete the file */
4955 backup = NULL;
4956#ifdef UNIX
4957 set_file_time((char_u *)org, st_old.st_atime, st_old.st_mtime);
4958#endif
4959 }
4960 }
4961 /*
4962 * If there is no backup file, remember that a (new) file was
4963 * created.
4964 */
4965 else
4966 {
4967 int empty_fd;
4968
4969 if (org == NULL
Bram Moolenaara5792f52005-11-23 21:25:05 +00004970 || (empty_fd = mch_open(org,
4971 O_CREAT | O_EXTRA | O_EXCL | O_NOFOLLOW,
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00004972 perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004973 EMSG(_("E206: patchmode: can't touch empty original file"));
4974 else
4975 close(empty_fd);
4976 }
4977 if (org != NULL)
4978 {
4979 mch_setperm((char_u *)org, mch_getperm(fname) & 0777);
4980 vim_free(org);
4981 }
4982 }
4983
4984 /*
4985 * Remove the backup unless 'backup' option is set
4986 */
4987 if (!p_bk && backup != NULL && mch_remove(backup) != 0)
4988 EMSG(_("E207: Can't delete backup file"));
4989
4990#ifdef FEAT_SUN_WORKSHOP
4991 if (usingSunWorkShop)
4992 workshop_file_saved((char *) ffname);
4993#endif
4994
4995 goto nofail;
4996
4997 /*
4998 * Finish up. We get here either after failure or success.
4999 */
5000fail:
5001 --no_wait_return; /* may wait for return now */
5002nofail:
5003
5004 /* Done saving, we accept changed buffer warnings again */
5005 buf->b_saving = FALSE;
5006
5007 vim_free(backup);
5008 if (buffer != smallbuf)
5009 vim_free(buffer);
5010#ifdef FEAT_MBYTE
5011 vim_free(fenc_tofree);
5012 vim_free(write_info.bw_conv_buf);
5013# ifdef USE_ICONV
5014 if (write_info.bw_iconv_fd != (iconv_t)-1)
5015 {
5016 iconv_close(write_info.bw_iconv_fd);
5017 write_info.bw_iconv_fd = (iconv_t)-1;
5018 }
5019# endif
5020#endif
5021#ifdef HAVE_ACL
5022 mch_free_acl(acl);
5023#endif
5024
5025 if (errmsg != NULL)
5026 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005027 int numlen = errnum != NULL ? (int)STRLEN(errnum) : 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005028
5029 attr = hl_attr(HLF_E); /* set highlight for error messages */
5030 msg_add_fname(buf,
5031#ifndef UNIX
5032 sfname
5033#else
5034 fname
5035#endif
5036 ); /* put file name in IObuff with quotes */
5037 if (STRLEN(IObuff) + STRLEN(errmsg) + numlen >= IOSIZE)
5038 IObuff[IOSIZE - STRLEN(errmsg) - numlen - 1] = NUL;
5039 /* If the error message has the form "is ...", put the error number in
5040 * front of the file name. */
5041 if (errnum != NULL)
5042 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00005043 STRMOVE(IObuff + numlen, IObuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005044 mch_memmove(IObuff, errnum, (size_t)numlen);
5045 }
5046 STRCAT(IObuff, errmsg);
5047 emsg(IObuff);
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005048 if (errmsg_allocated)
5049 vim_free(errmsg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005050
5051 retval = FAIL;
5052 if (end == 0)
5053 {
5054 MSG_PUTS_ATTR(_("\nWARNING: Original file may be lost or damaged\n"),
5055 attr | MSG_HIST);
5056 MSG_PUTS_ATTR(_("don't quit the editor until the file is successfully written!"),
5057 attr | MSG_HIST);
5058
5059 /* Update the timestamp to avoid an "overwrite changed file"
5060 * prompt when writing again. */
5061 if (mch_stat((char *)fname, &st_old) >= 0)
5062 {
5063 buf_store_time(buf, &st_old, fname);
5064 buf->b_mtime_read = buf->b_mtime;
5065 }
5066 }
5067 }
5068 msg_scroll = msg_save;
5069
Bram Moolenaar55debbe2010-05-23 23:34:36 +02005070#ifdef FEAT_PERSISTENT_UNDO
5071 /*
5072 * When writing the whole file and 'undofile' is set, also write the undo
5073 * file.
5074 */
5075 if (retval == OK && write_undo_file)
5076 {
5077 char_u hash[UNDO_HASH_SIZE];
5078
5079 sha256_finish(&sha_ctx, hash);
5080 u_write_undo(NULL, FALSE, buf, hash);
5081 }
5082#endif
5083
Bram Moolenaar071d4272004-06-13 20:20:40 +00005084#ifdef FEAT_AUTOCMD
5085#ifdef FEAT_EVAL
5086 if (!should_abort(retval))
5087#else
5088 if (!got_int)
5089#endif
5090 {
5091 aco_save_T aco;
5092
Bram Moolenaar68a33fc2012-04-25 16:50:48 +02005093 curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */
5094
Bram Moolenaar071d4272004-06-13 20:20:40 +00005095 /*
5096 * Apply POST autocommands.
5097 * Careful: The autocommands may call buf_write() recursively!
5098 */
5099 aucmd_prepbuf(&aco, buf);
5100
5101 if (append)
5102 apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname,
5103 FALSE, curbuf, eap);
5104 else if (filtering)
5105 apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname,
5106 FALSE, curbuf, eap);
5107 else if (reset_changed && whole)
5108 apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname,
5109 FALSE, curbuf, eap);
5110 else
5111 apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname,
5112 FALSE, curbuf, eap);
5113
5114 /* restore curwin/curbuf and a few other things */
5115 aucmd_restbuf(&aco);
5116
5117#ifdef FEAT_EVAL
5118 if (aborting()) /* autocmds may abort script processing */
5119 retval = FALSE;
5120#endif
5121 }
5122#endif
5123
5124 got_int |= prev_got_int;
5125
5126#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
5127 /* Update machine specific information. */
5128 mch_post_buffer_write(buf);
5129#endif
5130 return retval;
5131}
5132
5133/*
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005134 * Set the name of the current buffer. Use when the buffer doesn't have a
5135 * name and a ":r" or ":w" command with a file name is used.
5136 */
5137 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005138set_rw_fname(char_u *fname, char_u *sfname)
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005139{
5140#ifdef FEAT_AUTOCMD
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005141 buf_T *buf = curbuf;
5142
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005143 /* It's like the unnamed buffer is deleted.... */
5144 if (curbuf->b_p_bl)
5145 apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
5146 apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf);
5147# ifdef FEAT_EVAL
5148 if (aborting()) /* autocmds may abort script processing */
5149 return FAIL;
5150# endif
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005151 if (curbuf != buf)
5152 {
5153 /* We are in another buffer now, don't do the renaming. */
5154 EMSG(_(e_auchangedbuf));
5155 return FAIL;
5156 }
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005157#endif
5158
5159 if (setfname(curbuf, fname, sfname, FALSE) == OK)
5160 curbuf->b_flags |= BF_NOTEDITED;
5161
5162#ifdef FEAT_AUTOCMD
5163 /* ....and a new named one is created */
5164 apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, curbuf);
5165 if (curbuf->b_p_bl)
5166 apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf);
5167# ifdef FEAT_EVAL
5168 if (aborting()) /* autocmds may abort script processing */
5169 return FAIL;
5170# endif
5171
5172 /* Do filetype detection now if 'filetype' is empty. */
5173 if (*curbuf->b_p_ft == NUL)
5174 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005175 if (au_has_group((char_u *)"filetypedetect"))
Bram Moolenaar1610d052016-06-09 22:53:01 +02005176 (void)do_doautocmd((char_u *)"filetypedetect BufRead", FALSE, NULL);
Bram Moolenaara3227e22006-03-08 21:32:40 +00005177 do_modelines(0);
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005178 }
5179#endif
5180
5181 return OK;
5182}
5183
5184/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00005185 * Put file name into IObuff with quotes.
5186 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005187 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005188msg_add_fname(buf_T *buf, char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005189{
5190 if (fname == NULL)
5191 fname = (char_u *)"-stdin-";
5192 home_replace(buf, fname, IObuff + 1, IOSIZE - 4, TRUE);
5193 IObuff[0] = '"';
5194 STRCAT(IObuff, "\" ");
5195}
5196
5197/*
5198 * Append message for text mode to IObuff.
5199 * Return TRUE if something appended.
5200 */
5201 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005202msg_add_fileformat(int eol_type)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005203{
5204#ifndef USE_CRNL
5205 if (eol_type == EOL_DOS)
5206 {
5207 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[dos]") : _("[dos format]"));
5208 return TRUE;
5209 }
5210#endif
5211#ifndef USE_CR
5212 if (eol_type == EOL_MAC)
5213 {
5214 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[mac]") : _("[mac format]"));
5215 return TRUE;
5216 }
5217#endif
5218#if defined(USE_CRNL) || defined(USE_CR)
5219 if (eol_type == EOL_UNIX)
5220 {
5221 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[unix]") : _("[unix format]"));
5222 return TRUE;
5223 }
5224#endif
5225 return FALSE;
5226}
5227
5228/*
5229 * Append line and character count to IObuff.
5230 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005231 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005232msg_add_lines(
5233 int insert_space,
5234 long lnum,
Bram Moolenaar8767f522016-07-01 17:17:39 +02005235 off_T nchars)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005236{
5237 char_u *p;
5238
5239 p = IObuff + STRLEN(IObuff);
5240
5241 if (insert_space)
5242 *p++ = ' ';
5243 if (shortmess(SHM_LINES))
Bram Moolenaarbde98102016-07-01 20:03:42 +02005244 vim_snprintf((char *)p, IOSIZE - (p - IObuff),
5245 "%ldL, %lldC", lnum, (varnumber_T)nchars);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005246 else
5247 {
5248 if (lnum == 1)
5249 STRCPY(p, _("1 line, "));
5250 else
5251 sprintf((char *)p, _("%ld lines, "), lnum);
5252 p += STRLEN(p);
5253 if (nchars == 1)
5254 STRCPY(p, _("1 character"));
5255 else
Bram Moolenaarbde98102016-07-01 20:03:42 +02005256 vim_snprintf((char *)p, IOSIZE - (p - IObuff),
5257 _("%lld characters"), (varnumber_T)nchars);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005258 }
5259}
5260
5261/*
5262 * Append message for missing line separator to IObuff.
5263 */
5264 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005265msg_add_eol(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005266{
5267 STRCAT(IObuff, shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]"));
5268}
5269
5270/*
5271 * Check modification time of file, before writing to it.
5272 * The size isn't checked, because using a tool like "gzip" takes care of
5273 * using the same timestamp but can't set the size.
5274 */
5275 static int
Bram Moolenaar8767f522016-07-01 17:17:39 +02005276check_mtime(buf_T *buf, stat_T *st)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005277{
5278 if (buf->b_mtime_read != 0
5279 && time_differs((long)st->st_mtime, buf->b_mtime_read))
5280 {
5281 msg_scroll = TRUE; /* don't overwrite messages here */
5282 msg_silent = 0; /* must give this prompt */
5283 /* don't use emsg() here, don't want to flush the buffers */
5284 MSG_ATTR(_("WARNING: The file has been changed since reading it!!!"),
5285 hl_attr(HLF_E));
5286 if (ask_yesno((char_u *)_("Do you really want to write to it"),
5287 TRUE) == 'n')
5288 return FAIL;
5289 msg_scroll = FALSE; /* always overwrite the file message now */
5290 }
5291 return OK;
5292}
5293
5294 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005295time_differs(long t1, long t2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005296{
Bram Moolenaar48e330a2016-02-23 14:53:34 +01005297#if defined(__linux__) || defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005298 /* On a FAT filesystem, esp. under Linux, there are only 5 bits to store
5299 * the seconds. Since the roundoff is done when flushing the inode, the
5300 * time may change unexpectedly by one second!!! */
5301 return (t1 - t2 > 1 || t2 - t1 > 1);
5302#else
5303 return (t1 != t2);
5304#endif
5305}
5306
5307/*
5308 * Call write() to write a number of bytes to the file.
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005309 * Handles encryption and 'encoding' conversion.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005310 *
5311 * Return FAIL for failure, OK otherwise.
5312 */
5313 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005314buf_write_bytes(struct bw_info *ip)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005315{
5316 int wlen;
5317 char_u *buf = ip->bw_buf; /* data to write */
5318 int len = ip->bw_len; /* length of data */
5319#ifdef HAS_BW_FLAGS
5320 int flags = ip->bw_flags; /* extra flags */
5321#endif
5322
5323#ifdef FEAT_MBYTE
5324 /*
5325 * Skip conversion when writing the crypt magic number or the BOM.
5326 */
5327 if (!(flags & FIO_NOCONVERT))
5328 {
5329 char_u *p;
5330 unsigned c;
5331 int n;
5332
5333 if (flags & FIO_UTF8)
5334 {
5335 /*
5336 * Convert latin1 in the buffer to UTF-8 in the file.
5337 */
5338 p = ip->bw_conv_buf; /* translate to buffer */
5339 for (wlen = 0; wlen < len; ++wlen)
5340 p += utf_char2bytes(buf[wlen], p);
5341 buf = ip->bw_conv_buf;
5342 len = (int)(p - ip->bw_conv_buf);
5343 }
5344 else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1))
5345 {
5346 /*
5347 * Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
5348 * Latin1 chars in the file.
5349 */
5350 if (flags & FIO_LATIN1)
5351 p = buf; /* translate in-place (can only get shorter) */
5352 else
5353 p = ip->bw_conv_buf; /* translate to buffer */
5354 for (wlen = 0; wlen < len; wlen += n)
5355 {
5356 if (wlen == 0 && ip->bw_restlen != 0)
5357 {
5358 int l;
5359
5360 /* Use remainder of previous call. Append the start of
5361 * buf[] to get a full sequence. Might still be too
5362 * short! */
5363 l = CONV_RESTLEN - ip->bw_restlen;
5364 if (l > len)
5365 l = len;
5366 mch_memmove(ip->bw_rest + ip->bw_restlen, buf, (size_t)l);
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005367 n = utf_ptr2len_len(ip->bw_rest, ip->bw_restlen + l);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005368 if (n > ip->bw_restlen + len)
5369 {
5370 /* We have an incomplete byte sequence at the end to
5371 * be written. We can't convert it without the
5372 * remaining bytes. Keep them for the next call. */
5373 if (ip->bw_restlen + len > CONV_RESTLEN)
5374 return FAIL;
5375 ip->bw_restlen += len;
5376 break;
5377 }
5378 if (n > 1)
5379 c = utf_ptr2char(ip->bw_rest);
5380 else
5381 c = ip->bw_rest[0];
5382 if (n >= ip->bw_restlen)
5383 {
5384 n -= ip->bw_restlen;
5385 ip->bw_restlen = 0;
5386 }
5387 else
5388 {
5389 ip->bw_restlen -= n;
5390 mch_memmove(ip->bw_rest, ip->bw_rest + n,
5391 (size_t)ip->bw_restlen);
5392 n = 0;
5393 }
5394 }
5395 else
5396 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005397 n = utf_ptr2len_len(buf + wlen, len - wlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005398 if (n > len - wlen)
5399 {
5400 /* We have an incomplete byte sequence at the end to
5401 * be written. We can't convert it without the
5402 * remaining bytes. Keep them for the next call. */
5403 if (len - wlen > CONV_RESTLEN)
5404 return FAIL;
5405 ip->bw_restlen = len - wlen;
5406 mch_memmove(ip->bw_rest, buf + wlen,
5407 (size_t)ip->bw_restlen);
5408 break;
5409 }
5410 if (n > 1)
5411 c = utf_ptr2char(buf + wlen);
5412 else
5413 c = buf[wlen];
5414 }
5415
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005416 if (ucs2bytes(c, &p, flags) && !ip->bw_conv_error)
5417 {
5418 ip->bw_conv_error = TRUE;
5419 ip->bw_conv_error_lnum = ip->bw_start_lnum;
5420 }
5421 if (c == NL)
5422 ++ip->bw_start_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005423 }
5424 if (flags & FIO_LATIN1)
5425 len = (int)(p - buf);
5426 else
5427 {
5428 buf = ip->bw_conv_buf;
5429 len = (int)(p - ip->bw_conv_buf);
5430 }
5431 }
5432
5433# ifdef WIN3264
5434 else if (flags & FIO_CODEPAGE)
5435 {
5436 /*
5437 * Convert UTF-8 or codepage to UCS-2 and then to MS-Windows
5438 * codepage.
5439 */
5440 char_u *from;
5441 size_t fromlen;
5442 char_u *to;
5443 int u8c;
5444 BOOL bad = FALSE;
5445 int needed;
5446
5447 if (ip->bw_restlen > 0)
5448 {
5449 /* Need to concatenate the remainder of the previous call and
5450 * the bytes of the current call. Use the end of the
5451 * conversion buffer for this. */
5452 fromlen = len + ip->bw_restlen;
5453 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5454 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5455 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5456 }
5457 else
5458 {
5459 from = buf;
5460 fromlen = len;
5461 }
5462
5463 to = ip->bw_conv_buf;
5464 if (enc_utf8)
5465 {
5466 /* Convert from UTF-8 to UCS-2, to the start of the buffer.
5467 * The buffer has been allocated to be big enough. */
5468 while (fromlen > 0)
5469 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005470 n = (int)utf_ptr2len_len(from, (int)fromlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005471 if (n > (int)fromlen) /* incomplete byte sequence */
5472 break;
5473 u8c = utf_ptr2char(from);
5474 *to++ = (u8c & 0xff);
5475 *to++ = (u8c >> 8);
5476 fromlen -= n;
5477 from += n;
5478 }
5479
5480 /* Copy remainder to ip->bw_rest[] to be used for the next
5481 * call. */
5482 if (fromlen > CONV_RESTLEN)
5483 {
5484 /* weird overlong sequence */
5485 ip->bw_conv_error = TRUE;
5486 return FAIL;
5487 }
5488 mch_memmove(ip->bw_rest, from, fromlen);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005489 ip->bw_restlen = (int)fromlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005490 }
5491 else
5492 {
5493 /* Convert from enc_codepage to UCS-2, to the start of the
5494 * buffer. The buffer has been allocated to be big enough. */
5495 ip->bw_restlen = 0;
5496 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005497 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005498 NULL, 0);
5499 if (needed == 0)
5500 {
5501 /* When conversion fails there may be a trailing byte. */
5502 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005503 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen - 1,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005504 NULL, 0);
5505 if (needed == 0)
5506 {
5507 /* Conversion doesn't work. */
5508 ip->bw_conv_error = TRUE;
5509 return FAIL;
5510 }
5511 /* Save the trailing byte for the next call. */
5512 ip->bw_rest[0] = from[fromlen - 1];
5513 ip->bw_restlen = 1;
5514 }
5515 needed = MultiByteToWideChar(enc_codepage, MB_ERR_INVALID_CHARS,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005516 (LPCSTR)from, (int)(fromlen - ip->bw_restlen),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005517 (LPWSTR)to, needed);
5518 if (needed == 0)
5519 {
5520 /* Safety check: Conversion doesn't work. */
5521 ip->bw_conv_error = TRUE;
5522 return FAIL;
5523 }
5524 to += needed * 2;
5525 }
5526
5527 fromlen = to - ip->bw_conv_buf;
5528 buf = to;
5529# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5530 if (FIO_GET_CP(flags) == CP_UTF8)
5531 {
5532 /* Convert from UCS-2 to UTF-8, using the remainder of the
5533 * conversion buffer. Fails when out of space. */
5534 for (from = ip->bw_conv_buf; fromlen > 1; fromlen -= 2)
5535 {
5536 u8c = *from++;
5537 u8c += (*from++ << 8);
5538 to += utf_char2bytes(u8c, to);
5539 if (to + 6 >= ip->bw_conv_buf + ip->bw_conv_buflen)
5540 {
5541 ip->bw_conv_error = TRUE;
5542 return FAIL;
5543 }
5544 }
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005545 len = (int)(to - buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005546 }
5547 else
5548#endif
5549 {
5550 /* Convert from UCS-2 to the codepage, using the remainder of
5551 * the conversion buffer. If the conversion uses the default
5552 * character "0", the data doesn't fit in this encoding, so
5553 * fail. */
5554 len = WideCharToMultiByte(FIO_GET_CP(flags), 0,
5555 (LPCWSTR)ip->bw_conv_buf, (int)fromlen / sizeof(WCHAR),
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005556 (LPSTR)to, (int)(ip->bw_conv_buflen - fromlen), 0,
5557 &bad);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005558 if (bad)
5559 {
5560 ip->bw_conv_error = TRUE;
5561 return FAIL;
5562 }
5563 }
5564 }
5565# endif
5566
Bram Moolenaar56718732006-03-15 22:53:57 +00005567# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00005568 else if (flags & FIO_MACROMAN)
5569 {
5570 /*
5571 * Convert UTF-8 or latin1 to Apple MacRoman.
5572 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005573 char_u *from;
5574 size_t fromlen;
5575
5576 if (ip->bw_restlen > 0)
5577 {
5578 /* Need to concatenate the remainder of the previous call and
5579 * the bytes of the current call. Use the end of the
5580 * conversion buffer for this. */
5581 fromlen = len + ip->bw_restlen;
5582 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5583 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5584 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5585 }
5586 else
5587 {
5588 from = buf;
5589 fromlen = len;
5590 }
5591
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00005592 if (enc2macroman(from, fromlen,
5593 ip->bw_conv_buf, &len, ip->bw_conv_buflen,
5594 ip->bw_rest, &ip->bw_restlen) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005595 {
5596 ip->bw_conv_error = TRUE;
5597 return FAIL;
5598 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005599 buf = ip->bw_conv_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005600 }
5601# endif
5602
5603# ifdef USE_ICONV
5604 if (ip->bw_iconv_fd != (iconv_t)-1)
5605 {
5606 const char *from;
5607 size_t fromlen;
5608 char *to;
5609 size_t tolen;
5610
5611 /* Convert with iconv(). */
5612 if (ip->bw_restlen > 0)
5613 {
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005614 char *fp;
5615
Bram Moolenaar071d4272004-06-13 20:20:40 +00005616 /* Need to concatenate the remainder of the previous call and
5617 * the bytes of the current call. Use the end of the
5618 * conversion buffer for this. */
5619 fromlen = len + ip->bw_restlen;
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005620 fp = (char *)ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5621 mch_memmove(fp, ip->bw_rest, (size_t)ip->bw_restlen);
5622 mch_memmove(fp + ip->bw_restlen, buf, (size_t)len);
5623 from = fp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005624 tolen = ip->bw_conv_buflen - fromlen;
5625 }
5626 else
5627 {
5628 from = (const char *)buf;
5629 fromlen = len;
5630 tolen = ip->bw_conv_buflen;
5631 }
5632 to = (char *)ip->bw_conv_buf;
5633
5634 if (ip->bw_first)
5635 {
5636 size_t save_len = tolen;
5637
5638 /* output the initial shift state sequence */
5639 (void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen);
5640
5641 /* There is a bug in iconv() on Linux (which appears to be
5642 * wide-spread) which sets "to" to NULL and messes up "tolen".
5643 */
5644 if (to == NULL)
5645 {
5646 to = (char *)ip->bw_conv_buf;
5647 tolen = save_len;
5648 }
5649 ip->bw_first = FALSE;
5650 }
5651
5652 /*
5653 * If iconv() has an error or there is not enough room, fail.
5654 */
5655 if ((iconv(ip->bw_iconv_fd, (void *)&from, &fromlen, &to, &tolen)
5656 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
5657 || fromlen > CONV_RESTLEN)
5658 {
5659 ip->bw_conv_error = TRUE;
5660 return FAIL;
5661 }
5662
5663 /* copy remainder to ip->bw_rest[] to be used for the next call. */
5664 if (fromlen > 0)
5665 mch_memmove(ip->bw_rest, (void *)from, fromlen);
5666 ip->bw_restlen = (int)fromlen;
5667
5668 buf = ip->bw_conv_buf;
5669 len = (int)((char_u *)to - ip->bw_conv_buf);
5670 }
5671# endif
5672 }
5673#endif /* FEAT_MBYTE */
5674
5675#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02005676 if (flags & FIO_ENCRYPTED)
5677 {
5678 /* Encrypt the data. Do it in-place if possible, otherwise use an
5679 * allocated buffer. */
5680 if (crypt_works_inplace(ip->bw_buffer->b_cryptstate))
5681 {
5682 crypt_encode_inplace(ip->bw_buffer->b_cryptstate, buf, len);
5683 }
5684 else
5685 {
5686 char_u *outbuf;
5687
5688 len = crypt_encode_alloc(curbuf->b_cryptstate, buf, len, &outbuf);
5689 if (len == 0)
5690 return OK; /* Crypt layer is buffering, will flush later. */
5691 wlen = write_eintr(ip->bw_fd, outbuf, len);
5692 vim_free(outbuf);
5693 return (wlen < len) ? FAIL : OK;
5694 }
5695 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005696#endif
5697
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005698 wlen = write_eintr(ip->bw_fd, buf, len);
5699 return (wlen < len) ? FAIL : OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005700}
5701
5702#ifdef FEAT_MBYTE
5703/*
5704 * Convert a Unicode character to bytes.
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005705 * Return TRUE for an error, FALSE when it's OK.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005706 */
5707 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005708ucs2bytes(
5709 unsigned c, /* in: character */
5710 char_u **pp, /* in/out: pointer to result */
5711 int flags) /* FIO_ flags */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005712{
5713 char_u *p = *pp;
5714 int error = FALSE;
5715 int cc;
5716
5717
5718 if (flags & FIO_UCS4)
5719 {
5720 if (flags & FIO_ENDIAN_L)
5721 {
5722 *p++ = c;
5723 *p++ = (c >> 8);
5724 *p++ = (c >> 16);
5725 *p++ = (c >> 24);
5726 }
5727 else
5728 {
5729 *p++ = (c >> 24);
5730 *p++ = (c >> 16);
5731 *p++ = (c >> 8);
5732 *p++ = c;
5733 }
5734 }
5735 else if (flags & (FIO_UCS2 | FIO_UTF16))
5736 {
5737 if (c >= 0x10000)
5738 {
5739 if (flags & FIO_UTF16)
5740 {
5741 /* Make two words, ten bits of the character in each. First
5742 * word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff */
5743 c -= 0x10000;
5744 if (c >= 0x100000)
5745 error = TRUE;
5746 cc = ((c >> 10) & 0x3ff) + 0xd800;
5747 if (flags & FIO_ENDIAN_L)
5748 {
5749 *p++ = cc;
5750 *p++ = ((unsigned)cc >> 8);
5751 }
5752 else
5753 {
5754 *p++ = ((unsigned)cc >> 8);
5755 *p++ = cc;
5756 }
5757 c = (c & 0x3ff) + 0xdc00;
5758 }
5759 else
5760 error = TRUE;
5761 }
5762 if (flags & FIO_ENDIAN_L)
5763 {
5764 *p++ = c;
5765 *p++ = (c >> 8);
5766 }
5767 else
5768 {
5769 *p++ = (c >> 8);
5770 *p++ = c;
5771 }
5772 }
5773 else /* Latin1 */
5774 {
5775 if (c >= 0x100)
5776 {
5777 error = TRUE;
5778 *p++ = 0xBF;
5779 }
5780 else
5781 *p++ = c;
5782 }
5783
5784 *pp = p;
5785 return error;
5786}
5787
5788/*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005789 * Return TRUE if file encoding "fenc" requires conversion from or to
5790 * 'encoding'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005791 */
5792 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005793need_conversion(char_u *fenc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005794{
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005795 int same_encoding;
5796 int enc_flags;
5797 int fenc_flags;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005798
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005799 if (*fenc == NUL || STRCMP(p_enc, fenc) == 0)
Bram Moolenaar442b4222010-05-24 21:34:22 +02005800 {
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005801 same_encoding = TRUE;
Bram Moolenaar442b4222010-05-24 21:34:22 +02005802 fenc_flags = 0;
5803 }
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005804 else
5805 {
5806 /* Ignore difference between "ansi" and "latin1", "ucs-4" and
5807 * "ucs-4be", etc. */
5808 enc_flags = get_fio_flags(p_enc);
5809 fenc_flags = get_fio_flags(fenc);
5810 same_encoding = (enc_flags != 0 && fenc_flags == enc_flags);
5811 }
5812 if (same_encoding)
5813 {
5814 /* Specified encoding matches with 'encoding'. This requires
5815 * conversion when 'encoding' is Unicode but not UTF-8. */
5816 return enc_unicode != 0;
5817 }
5818
5819 /* Encodings differ. However, conversion is not needed when 'enc' is any
5820 * Unicode encoding and the file is UTF-8. */
5821 return !(enc_utf8 && fenc_flags == FIO_UTF8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005822}
5823
5824/*
5825 * Check "ptr" for a unicode encoding and return the FIO_ flags needed for the
5826 * internal conversion.
5827 * if "ptr" is an empty string, use 'encoding'.
5828 */
5829 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005830get_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005831{
5832 int prop;
5833
5834 if (*ptr == NUL)
5835 ptr = p_enc;
5836
5837 prop = enc_canon_props(ptr);
5838 if (prop & ENC_UNICODE)
5839 {
5840 if (prop & ENC_2BYTE)
5841 {
5842 if (prop & ENC_ENDIAN_L)
5843 return FIO_UCS2 | FIO_ENDIAN_L;
5844 return FIO_UCS2;
5845 }
5846 if (prop & ENC_4BYTE)
5847 {
5848 if (prop & ENC_ENDIAN_L)
5849 return FIO_UCS4 | FIO_ENDIAN_L;
5850 return FIO_UCS4;
5851 }
5852 if (prop & ENC_2WORD)
5853 {
5854 if (prop & ENC_ENDIAN_L)
5855 return FIO_UTF16 | FIO_ENDIAN_L;
5856 return FIO_UTF16;
5857 }
5858 return FIO_UTF8;
5859 }
5860 if (prop & ENC_LATIN1)
5861 return FIO_LATIN1;
5862 /* must be ENC_DBCS, requires iconv() */
5863 return 0;
5864}
5865
5866#ifdef WIN3264
5867/*
5868 * Check "ptr" for a MS-Windows codepage name and return the FIO_ flags needed
5869 * for the conversion MS-Windows can do for us. Also accept "utf-8".
5870 * Used for conversion between 'encoding' and 'fileencoding'.
5871 */
5872 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005873get_win_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005874{
5875 int cp;
5876
5877 /* Cannot do this when 'encoding' is not utf-8 and not a codepage. */
5878 if (!enc_utf8 && enc_codepage <= 0)
5879 return 0;
5880
5881 cp = encname2codepage(ptr);
5882 if (cp == 0)
5883 {
5884# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5885 if (STRCMP(ptr, "utf-8") == 0)
5886 cp = CP_UTF8;
5887 else
5888# endif
5889 return 0;
5890 }
5891 return FIO_PUT_CP(cp) | FIO_CODEPAGE;
5892}
5893#endif
5894
5895#ifdef MACOS_X
5896/*
5897 * Check "ptr" for a Carbon supported encoding and return the FIO_ flags
5898 * needed for the internal conversion to/from utf-8 or latin1.
5899 */
5900 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005901get_mac_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005902{
5903 if ((enc_utf8 || STRCMP(p_enc, "latin1") == 0)
5904 && (enc_canon_props(ptr) & ENC_MACROMAN))
5905 return FIO_MACROMAN;
5906 return 0;
5907}
5908#endif
5909
5910/*
5911 * Check for a Unicode BOM (Byte Order Mark) at the start of p[size].
5912 * "size" must be at least 2.
5913 * Return the name of the encoding and set "*lenp" to the length.
5914 * Returns NULL when no BOM found.
5915 */
5916 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005917check_for_bom(
5918 char_u *p,
5919 long size,
5920 int *lenp,
5921 int flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005922{
5923 char *name = NULL;
5924 int len = 2;
5925
5926 if (p[0] == 0xef && p[1] == 0xbb && size >= 3 && p[2] == 0xbf
Bram Moolenaaree0f5a62008-07-24 20:09:16 +00005927 && (flags == FIO_ALL || flags == FIO_UTF8 || flags == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005928 {
5929 name = "utf-8"; /* EF BB BF */
5930 len = 3;
5931 }
5932 else if (p[0] == 0xff && p[1] == 0xfe)
5933 {
5934 if (size >= 4 && p[2] == 0 && p[3] == 0
5935 && (flags == FIO_ALL || flags == (FIO_UCS4 | FIO_ENDIAN_L)))
5936 {
5937 name = "ucs-4le"; /* FF FE 00 00 */
5938 len = 4;
5939 }
Bram Moolenaar223a1892008-11-11 20:57:11 +00005940 else if (flags == (FIO_UCS2 | FIO_ENDIAN_L))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005941 name = "ucs-2le"; /* FF FE */
Bram Moolenaar223a1892008-11-11 20:57:11 +00005942 else if (flags == FIO_ALL || flags == (FIO_UTF16 | FIO_ENDIAN_L))
5943 /* utf-16le is preferred, it also works for ucs-2le text */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005944 name = "utf-16le"; /* FF FE */
5945 }
5946 else if (p[0] == 0xfe && p[1] == 0xff
5947 && (flags == FIO_ALL || flags == FIO_UCS2 || flags == FIO_UTF16))
5948 {
Bram Moolenaarffd82c52008-02-20 17:15:26 +00005949 /* Default to utf-16, it works also for ucs-2 text. */
5950 if (flags == FIO_UCS2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005951 name = "ucs-2"; /* FE FF */
Bram Moolenaarffd82c52008-02-20 17:15:26 +00005952 else
5953 name = "utf-16"; /* FE FF */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005954 }
5955 else if (size >= 4 && p[0] == 0 && p[1] == 0 && p[2] == 0xfe
5956 && p[3] == 0xff && (flags == FIO_ALL || flags == FIO_UCS4))
5957 {
5958 name = "ucs-4"; /* 00 00 FE FF */
5959 len = 4;
5960 }
5961
5962 *lenp = len;
5963 return (char_u *)name;
5964}
5965
5966/*
5967 * Generate a BOM in "buf[4]" for encoding "name".
5968 * Return the length of the BOM (zero when no BOM).
5969 */
5970 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005971make_bom(char_u *buf, char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005972{
5973 int flags;
5974 char_u *p;
5975
5976 flags = get_fio_flags(name);
5977
5978 /* Can't put a BOM in a non-Unicode file. */
5979 if (flags == FIO_LATIN1 || flags == 0)
5980 return 0;
5981
5982 if (flags == FIO_UTF8) /* UTF-8 */
5983 {
5984 buf[0] = 0xef;
5985 buf[1] = 0xbb;
5986 buf[2] = 0xbf;
5987 return 3;
5988 }
5989 p = buf;
5990 (void)ucs2bytes(0xfeff, &p, flags);
5991 return (int)(p - buf);
5992}
5993#endif
5994
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00005995#if defined(FEAT_VIMINFO) || defined(FEAT_BROWSE) || \
Bram Moolenaara0174af2008-01-02 20:08:25 +00005996 defined(FEAT_QUICKFIX) || defined(FEAT_AUTOCMD) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005997/*
5998 * Try to find a shortname by comparing the fullname with the current
5999 * directory.
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006000 * Returns "full_path" or pointer into "full_path" if shortened.
6001 */
6002 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006003shorten_fname1(char_u *full_path)
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006004{
Bram Moolenaard9462e32011-04-11 21:35:11 +02006005 char_u *dirname;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006006 char_u *p = full_path;
6007
Bram Moolenaard9462e32011-04-11 21:35:11 +02006008 dirname = alloc(MAXPATHL);
6009 if (dirname == NULL)
6010 return full_path;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006011 if (mch_dirname(dirname, MAXPATHL) == OK)
6012 {
6013 p = shorten_fname(full_path, dirname);
6014 if (p == NULL || *p == NUL)
6015 p = full_path;
6016 }
Bram Moolenaard9462e32011-04-11 21:35:11 +02006017 vim_free(dirname);
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006018 return p;
6019}
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00006020#endif
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006021
6022/*
6023 * Try to find a shortname by comparing the fullname with the current
6024 * directory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006025 * Returns NULL if not shorter name possible, pointer into "full_path"
6026 * otherwise.
6027 */
6028 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006029shorten_fname(char_u *full_path, char_u *dir_name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006030{
6031 int len;
6032 char_u *p;
6033
6034 if (full_path == NULL)
6035 return NULL;
6036 len = (int)STRLEN(dir_name);
6037 if (fnamencmp(dir_name, full_path, len) == 0)
6038 {
6039 p = full_path + len;
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006040#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006041 /*
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006042 * MSWIN: when a file is in the root directory, dir_name will end in a
Bram Moolenaar071d4272004-06-13 20:20:40 +00006043 * slash, since C: by itself does not define a specific dir. In this
6044 * case p may already be correct. <negri>
6045 */
6046 if (!((len > 2) && (*(p - 2) == ':')))
6047#endif
6048 {
6049 if (vim_ispathsep(*p))
6050 ++p;
6051#ifndef VMS /* the path separator is always part of the path */
6052 else
6053 p = NULL;
6054#endif
6055 }
6056 }
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006057#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006058 /*
6059 * When using a file in the current drive, remove the drive name:
6060 * "A:\dir\file" -> "\dir\file". This helps when moving a session file on
6061 * a floppy from "A:\dir" to "B:\dir".
6062 */
6063 else if (len > 3
6064 && TOUPPER_LOC(full_path[0]) == TOUPPER_LOC(dir_name[0])
6065 && full_path[1] == ':'
6066 && vim_ispathsep(full_path[2]))
6067 p = full_path + 2;
6068#endif
6069 else
6070 p = NULL;
6071 return p;
6072}
6073
6074/*
6075 * Shorten filenames for all buffers.
6076 * When "force" is TRUE: Use full path from now on for files currently being
6077 * edited, both for file name and swap file name. Try to shorten the file
6078 * names a bit, if safe to do so.
6079 * When "force" is FALSE: Only try to shorten absolute file names.
6080 * For buffers that have buftype "nofile" or "scratch": never change the file
6081 * name.
6082 */
6083 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006084shorten_fnames(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006085{
6086 char_u dirname[MAXPATHL];
6087 buf_T *buf;
6088 char_u *p;
6089
6090 mch_dirname(dirname, MAXPATHL);
6091 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
6092 {
6093 if (buf->b_fname != NULL
6094#ifdef FEAT_QUICKFIX
6095 && !bt_nofile(buf)
6096#endif
6097 && !path_with_url(buf->b_fname)
6098 && (force
6099 || buf->b_sfname == NULL
6100 || mch_isFullName(buf->b_sfname)))
6101 {
6102 vim_free(buf->b_sfname);
6103 buf->b_sfname = NULL;
6104 p = shorten_fname(buf->b_ffname, dirname);
6105 if (p != NULL)
6106 {
6107 buf->b_sfname = vim_strsave(p);
6108 buf->b_fname = buf->b_sfname;
6109 }
6110 if (p == NULL || buf->b_fname == NULL)
6111 buf->b_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006112 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00006113
6114 /* Always make the swap file name a full path, a "nofile" buffer may
6115 * also have a swap file. */
6116 mf_fullname(buf->b_ml.ml_mfp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006117 }
6118#ifdef FEAT_WINDOWS
6119 status_redraw_all();
Bram Moolenaar49d7bf12006-02-17 21:45:41 +00006120 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006121#endif
6122}
6123
6124#if (defined(FEAT_DND) && defined(FEAT_GUI_GTK)) \
6125 || defined(FEAT_GUI_MSWIN) \
6126 || defined(FEAT_GUI_MAC) \
6127 || defined(PROTO)
6128/*
6129 * Shorten all filenames in "fnames[count]" by current directory.
6130 */
6131 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006132shorten_filenames(char_u **fnames, int count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006133{
6134 int i;
6135 char_u dirname[MAXPATHL];
6136 char_u *p;
6137
6138 if (fnames == NULL || count < 1)
6139 return;
6140 mch_dirname(dirname, sizeof(dirname));
6141 for (i = 0; i < count; ++i)
6142 {
6143 if ((p = shorten_fname(fnames[i], dirname)) != NULL)
6144 {
6145 /* shorten_fname() returns pointer in given "fnames[i]". If free
6146 * "fnames[i]" first, "p" becomes invalid. So we need to copy
6147 * "p" first then free fnames[i]. */
6148 p = vim_strsave(p);
6149 vim_free(fnames[i]);
6150 fnames[i] = p;
6151 }
6152 }
6153}
6154#endif
6155
6156/*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006157 * add extension to file name - change path/fo.o.h to path/fo.o.h.ext or
Bram Moolenaar071d4272004-06-13 20:20:40 +00006158 * fo_o_h.ext for MSDOS or when shortname option set.
6159 *
6160 * Assumed that fname is a valid name found in the filesystem we assure that
6161 * the return value is a different name and ends in 'ext'.
6162 * "ext" MUST be at most 4 characters long if it starts with a dot, 3
6163 * characters otherwise.
6164 * Space for the returned name is allocated, must be freed later.
6165 * Returns NULL when out of memory.
6166 */
6167 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006168modname(
6169 char_u *fname,
6170 char_u *ext,
6171 int prepend_dot) /* may prepend a '.' to file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006172{
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006173 return buf_modname((curbuf->b_p_sn || curbuf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00006174 fname, ext, prepend_dot);
6175}
6176
6177 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006178buf_modname(
6179 int shortname, /* use 8.3 file name */
6180 char_u *fname,
6181 char_u *ext,
6182 int prepend_dot) /* may prepend a '.' to file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006183{
6184 char_u *retval;
6185 char_u *s;
6186 char_u *e;
6187 char_u *ptr;
6188 int fnamelen, extlen;
6189
6190 extlen = (int)STRLEN(ext);
6191
6192 /*
6193 * If there is no file name we must get the name of the current directory
6194 * (we need the full path in case :cd is used).
6195 */
6196 if (fname == NULL || *fname == NUL)
6197 {
6198 retval = alloc((unsigned)(MAXPATHL + extlen + 3));
6199 if (retval == NULL)
6200 return NULL;
6201 if (mch_dirname(retval, MAXPATHL) == FAIL ||
6202 (fnamelen = (int)STRLEN(retval)) == 0)
6203 {
6204 vim_free(retval);
6205 return NULL;
6206 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006207 if (!after_pathsep(retval, retval + fnamelen))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006208 {
6209 retval[fnamelen++] = PATHSEP;
6210 retval[fnamelen] = NUL;
6211 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006212 prepend_dot = FALSE; /* nothing to prepend a dot to */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006213 }
6214 else
6215 {
6216 fnamelen = (int)STRLEN(fname);
6217 retval = alloc((unsigned)(fnamelen + extlen + 3));
6218 if (retval == NULL)
6219 return NULL;
6220 STRCPY(retval, fname);
6221#ifdef VMS
6222 vms_remove_version(retval); /* we do not need versions here */
6223#endif
6224 }
6225
6226 /*
6227 * search backwards until we hit a '/', '\' or ':' replacing all '.'
6228 * by '_' for MSDOS or when shortname option set and ext starts with a dot.
6229 * Then truncate what is after the '/', '\' or ':' to 8 characters for
6230 * MSDOS and 26 characters for AMIGA, a lot more for UNIX.
6231 */
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006232 for (ptr = retval + fnamelen; ptr > retval; mb_ptr_back(retval, ptr))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006233 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006234 if (*ext == '.'
Bram Moolenaare60acc12011-05-10 16:41:25 +02006235#ifdef USE_LONG_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00006236 && (!USE_LONG_FNAME || shortname)
Bram Moolenaare60acc12011-05-10 16:41:25 +02006237#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006238 && shortname
Bram Moolenaare60acc12011-05-10 16:41:25 +02006239#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006240 )
6241 if (*ptr == '.') /* replace '.' by '_' */
6242 *ptr = '_';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006243 if (vim_ispathsep(*ptr))
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006244 {
6245 ++ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006246 break;
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006247 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006248 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006249
6250 /* the file name has at most BASENAMELEN characters. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006251 if (STRLEN(ptr) > (unsigned)BASENAMELEN)
6252 ptr[BASENAMELEN] = '\0';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006253
6254 s = ptr + STRLEN(ptr);
6255
6256 /*
6257 * For 8.3 file names we may have to reduce the length.
6258 */
6259#ifdef USE_LONG_FNAME
6260 if (!USE_LONG_FNAME || shortname)
6261#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006262 if (shortname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006263#endif
6264 {
6265 /*
6266 * If there is no file name, or the file name ends in '/', and the
6267 * extension starts with '.', put a '_' before the dot, because just
6268 * ".ext" is invalid.
6269 */
6270 if (fname == NULL || *fname == NUL
6271 || vim_ispathsep(fname[STRLEN(fname) - 1]))
6272 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006273 if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006274 *s++ = '_';
6275 }
6276 /*
6277 * If the extension starts with '.', truncate the base name at 8
6278 * characters
6279 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006280 else if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006281 {
Bram Moolenaar78a15312009-05-15 19:33:18 +00006282 if ((size_t)(s - ptr) > (size_t)8)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006283 {
6284 s = ptr + 8;
6285 *s = '\0';
6286 }
6287 }
6288 /*
6289 * If the extension doesn't start with '.', and the file name
6290 * doesn't have an extension yet, append a '.'
6291 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006292 else if ((e = vim_strchr(ptr, '.')) == NULL)
6293 *s++ = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006294 /*
6295 * If the extension doesn't start with '.', and there already is an
Bram Moolenaar7263a772007-05-10 17:35:54 +00006296 * extension, it may need to be truncated
Bram Moolenaar071d4272004-06-13 20:20:40 +00006297 */
6298 else if ((int)STRLEN(e) + extlen > 4)
6299 s = e + 4 - extlen;
6300 }
Bram Moolenaare7fedb62015-12-31 19:07:19 +01006301#if defined(USE_LONG_FNAME) || defined(WIN3264)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006302 /*
6303 * If there is no file name, and the extension starts with '.', put a
6304 * '_' before the dot, because just ".ext" may be invalid if it's on a
6305 * FAT partition, and on HPFS it doesn't matter.
6306 */
6307 else if ((fname == NULL || *fname == NUL) && *ext == '.')
6308 *s++ = '_';
6309#endif
6310
6311 /*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006312 * Append the extension.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006313 * ext can start with '.' and cannot exceed 3 more characters.
6314 */
6315 STRCPY(s, ext);
6316
Bram Moolenaar071d4272004-06-13 20:20:40 +00006317 /*
6318 * Prepend the dot.
6319 */
Bram Moolenaare60acc12011-05-10 16:41:25 +02006320 if (prepend_dot && !shortname && *(e = gettail(retval)) != '.'
Bram Moolenaar071d4272004-06-13 20:20:40 +00006321#ifdef USE_LONG_FNAME
6322 && USE_LONG_FNAME
6323#endif
6324 )
6325 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006326 STRMOVE(e + 1, e);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006327 *e = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006328 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006329
6330 /*
6331 * Check that, after appending the extension, the file name is really
6332 * different.
6333 */
6334 if (fname != NULL && STRCMP(fname, retval) == 0)
6335 {
6336 /* we search for a character that can be replaced by '_' */
6337 while (--s >= ptr)
6338 {
6339 if (*s != '_')
6340 {
6341 *s = '_';
6342 break;
6343 }
6344 }
6345 if (s < ptr) /* fname was "________.<ext>", how tricky! */
6346 *ptr = 'v';
6347 }
6348 return retval;
6349}
6350
6351/*
6352 * Like fgets(), but if the file line is too long, it is truncated and the
6353 * rest of the line is thrown away. Returns TRUE for end-of-file.
6354 */
6355 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006356vim_fgets(char_u *buf, int size, FILE *fp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006357{
6358 char *eof;
6359#define FGETS_SIZE 200
6360 char tbuf[FGETS_SIZE];
6361
6362 buf[size - 2] = NUL;
6363#ifdef USE_CR
6364 eof = fgets_cr((char *)buf, size, fp);
6365#else
6366 eof = fgets((char *)buf, size, fp);
6367#endif
6368 if (buf[size - 2] != NUL && buf[size - 2] != '\n')
6369 {
6370 buf[size - 1] = NUL; /* Truncate the line */
6371
6372 /* Now throw away the rest of the line: */
6373 do
6374 {
6375 tbuf[FGETS_SIZE - 2] = NUL;
6376#ifdef USE_CR
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006377 ignoredp = fgets_cr((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006378#else
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006379 ignoredp = fgets((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006380#endif
6381 } while (tbuf[FGETS_SIZE - 2] != NUL && tbuf[FGETS_SIZE - 2] != '\n');
6382 }
6383 return (eof == NULL);
6384}
6385
6386#if defined(USE_CR) || defined(PROTO)
6387/*
6388 * Like vim_fgets(), but accept any line terminator: CR, CR-LF or LF.
6389 * Returns TRUE for end-of-file.
6390 * Only used for the Mac, because it's much slower than vim_fgets().
6391 */
6392 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006393tag_fgets(char_u *buf, int size, FILE *fp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006394{
6395 int i = 0;
6396 int c;
6397 int eof = FALSE;
6398
6399 for (;;)
6400 {
6401 c = fgetc(fp);
6402 if (c == EOF)
6403 {
6404 eof = TRUE;
6405 break;
6406 }
6407 if (c == '\r')
6408 {
6409 /* Always store a NL for end-of-line. */
6410 if (i < size - 1)
6411 buf[i++] = '\n';
6412 c = fgetc(fp);
6413 if (c != '\n') /* Macintosh format: single CR. */
6414 ungetc(c, fp);
6415 break;
6416 }
6417 if (i < size - 1)
6418 buf[i++] = c;
6419 if (c == '\n')
6420 break;
6421 }
6422 buf[i] = NUL;
6423 return eof;
6424}
6425#endif
6426
6427/*
6428 * rename() only works if both files are on the same file system, this
6429 * function will (attempts to?) copy the file across if rename fails -- webb
6430 * Return -1 for failure, 0 for success.
6431 */
6432 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006433vim_rename(char_u *from, char_u *to)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006434{
6435 int fd_in;
6436 int fd_out;
6437 int n;
6438 char *errmsg = NULL;
6439 char *buffer;
6440#ifdef AMIGA
6441 BPTR flock;
6442#endif
Bram Moolenaar8767f522016-07-01 17:17:39 +02006443 stat_T st;
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006444 long perm;
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006445#ifdef HAVE_ACL
6446 vim_acl_T acl; /* ACL from original file */
6447#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006448 int use_tmp_file = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006449
6450 /*
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006451 * When the names are identical, there is nothing to do. When they refer
6452 * to the same file (ignoring case and slash/backslash differences) but
6453 * the file name differs we need to go through a temp file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006454 */
6455 if (fnamecmp(from, to) == 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006456 {
Bram Moolenaar71afbfe2013-03-19 16:49:16 +01006457 if (p_fic && STRCMP(gettail(from), gettail(to)) != 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006458 use_tmp_file = TRUE;
6459 else
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006460 return 0;
6461 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006462
6463 /*
6464 * Fail if the "from" file doesn't exist. Avoids that "to" is deleted.
6465 */
6466 if (mch_stat((char *)from, &st) < 0)
6467 return -1;
6468
Bram Moolenaar3576da72008-12-30 15:15:57 +00006469#ifdef UNIX
6470 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02006471 stat_T st_to;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006472
6473 /* It's possible for the source and destination to be the same file.
6474 * This happens when "from" and "to" differ in case and are on a FAT32
6475 * filesystem. In that case go through a temp file name. */
6476 if (mch_stat((char *)to, &st_to) >= 0
6477 && st.st_dev == st_to.st_dev
6478 && st.st_ino == st_to.st_ino)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006479 use_tmp_file = TRUE;
6480 }
6481#endif
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02006482#ifdef WIN3264
6483 {
6484 BY_HANDLE_FILE_INFORMATION info1, info2;
6485
6486 /* It's possible for the source and destination to be the same file.
6487 * In that case go through a temp file name. This makes rename("foo",
6488 * "./foo") a no-op (in a complicated way). */
6489 if (win32_fileinfo(from, &info1) == FILEINFO_OK
6490 && win32_fileinfo(to, &info2) == FILEINFO_OK
6491 && info1.dwVolumeSerialNumber == info2.dwVolumeSerialNumber
6492 && info1.nFileIndexHigh == info2.nFileIndexHigh
6493 && info1.nFileIndexLow == info2.nFileIndexLow)
6494 use_tmp_file = TRUE;
6495 }
6496#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006497
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006498 if (use_tmp_file)
6499 {
6500 char tempname[MAXPATHL + 1];
6501
6502 /*
6503 * Find a name that doesn't exist and is in the same directory.
6504 * Rename "from" to "tempname" and then rename "tempname" to "to".
6505 */
6506 if (STRLEN(from) >= MAXPATHL - 5)
6507 return -1;
6508 STRCPY(tempname, from);
6509 for (n = 123; n < 99999; ++n)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006510 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006511 sprintf((char *)gettail((char_u *)tempname), "%d", n);
6512 if (mch_stat(tempname, &st) < 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006513 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006514 if (mch_rename((char *)from, tempname) == 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006515 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006516 if (mch_rename(tempname, (char *)to) == 0)
6517 return 0;
6518 /* Strange, the second step failed. Try moving the
6519 * file back and return failure. */
6520 mch_rename(tempname, (char *)from);
Bram Moolenaar3576da72008-12-30 15:15:57 +00006521 return -1;
6522 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006523 /* If it fails for one temp name it will most likely fail
6524 * for any temp name, give up. */
6525 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006526 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006527 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006528 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006529 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006530
Bram Moolenaar071d4272004-06-13 20:20:40 +00006531 /*
6532 * Delete the "to" file, this is required on some systems to make the
6533 * mch_rename() work, on other systems it makes sure that we don't have
6534 * two files when the mch_rename() fails.
6535 */
6536
6537#ifdef AMIGA
6538 /*
6539 * With MSDOS-compatible filesystems (crossdos, messydos) it is possible
6540 * that the name of the "to" file is the same as the "from" file, even
Bram Moolenaar7263a772007-05-10 17:35:54 +00006541 * though the names are different. To avoid the chance of accidentally
Bram Moolenaar071d4272004-06-13 20:20:40 +00006542 * deleting the "from" file (horror!) we lock it during the remove.
6543 *
6544 * When used for making a backup before writing the file: This should not
6545 * happen with ":w", because startscript() should detect this problem and
6546 * set buf->b_shortname, causing modname() to return a correct ".bak" file
6547 * name. This problem does exist with ":w filename", but then the
6548 * original file will be somewhere else so the backup isn't really
6549 * important. If autoscripting is off the rename may fail.
6550 */
6551 flock = Lock((UBYTE *)from, (long)ACCESS_READ);
6552#endif
6553 mch_remove(to);
6554#ifdef AMIGA
6555 if (flock)
6556 UnLock(flock);
6557#endif
6558
6559 /*
6560 * First try a normal rename, return if it works.
6561 */
6562 if (mch_rename((char *)from, (char *)to) == 0)
6563 return 0;
6564
6565 /*
6566 * Rename() failed, try copying the file.
6567 */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006568 perm = mch_getperm(from);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006569#ifdef HAVE_ACL
6570 /* For systems that support ACL: get the ACL from the original file. */
6571 acl = mch_get_acl(from);
6572#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006573 fd_in = mch_open((char *)from, O_RDONLY|O_EXTRA, 0);
6574 if (fd_in == -1)
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006575 {
6576#ifdef HAVE_ACL
6577 mch_free_acl(acl);
6578#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006579 return -1;
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006580 }
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006581
6582 /* Create the new file with same permissions as the original. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00006583 fd_out = mch_open((char *)to,
6584 O_CREAT|O_EXCL|O_WRONLY|O_EXTRA|O_NOFOLLOW, (int)perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006585 if (fd_out == -1)
6586 {
6587 close(fd_in);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006588#ifdef HAVE_ACL
6589 mch_free_acl(acl);
6590#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006591 return -1;
6592 }
6593
6594 buffer = (char *)alloc(BUFSIZE);
6595 if (buffer == NULL)
6596 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006597 close(fd_out);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006598 close(fd_in);
6599#ifdef HAVE_ACL
6600 mch_free_acl(acl);
6601#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006602 return -1;
6603 }
6604
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01006605 while ((n = read_eintr(fd_in, buffer, BUFSIZE)) > 0)
6606 if (write_eintr(fd_out, buffer, n) != n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006607 {
6608 errmsg = _("E208: Error writing to \"%s\"");
6609 break;
6610 }
6611
6612 vim_free(buffer);
6613 close(fd_in);
6614 if (close(fd_out) < 0)
6615 errmsg = _("E209: Error closing \"%s\"");
6616 if (n < 0)
6617 {
6618 errmsg = _("E210: Error reading \"%s\"");
6619 to = from;
6620 }
Bram Moolenaar7263a772007-05-10 17:35:54 +00006621#ifndef UNIX /* for Unix mch_open() already set the permission */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006622 mch_setperm(to, perm);
Bram Moolenaarc6039d82005-12-02 00:44:04 +00006623#endif
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006624#ifdef HAVE_ACL
6625 mch_set_acl(to, acl);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006626 mch_free_acl(acl);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006627#endif
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02006628#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaare8747442013-11-12 18:09:29 +01006629 mch_copy_sec(from, to);
Bram Moolenaar0671de32013-11-12 05:12:03 +01006630#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006631 if (errmsg != NULL)
6632 {
6633 EMSG2(errmsg, to);
6634 return -1;
6635 }
6636 mch_remove(from);
6637 return 0;
6638}
6639
6640static int already_warned = FALSE;
6641
6642/*
6643 * Check if any not hidden buffer has been changed.
6644 * Postpone the check if there are characters in the stuff buffer, a global
6645 * command is being executed, a mapping is being executed or an autocommand is
6646 * busy.
6647 * Returns TRUE if some message was written (screen should be redrawn and
6648 * cursor positioned).
6649 */
6650 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006651check_timestamps(
6652 int focus) /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006653{
6654 buf_T *buf;
6655 int didit = 0;
6656 int n;
6657
6658 /* Don't check timestamps while system() or another low-level function may
6659 * cause us to lose and gain focus. */
6660 if (no_check_timestamps > 0)
6661 return FALSE;
6662
6663 /* Avoid doing a check twice. The OK/Reload dialog can cause a focus
6664 * event and we would keep on checking if the file is steadily growing.
6665 * Do check again after typing something. */
6666 if (focus && did_check_timestamps)
6667 {
6668 need_check_timestamps = TRUE;
6669 return FALSE;
6670 }
6671
6672 if (!stuff_empty() || global_busy || !typebuf_typed()
6673#ifdef FEAT_AUTOCMD
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006674 || autocmd_busy || curbuf_lock > 0 || allbuf_lock > 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00006675#endif
6676 )
6677 need_check_timestamps = TRUE; /* check later */
6678 else
6679 {
6680 ++no_wait_return;
6681 did_check_timestamps = TRUE;
6682 already_warned = FALSE;
6683 for (buf = firstbuf; buf != NULL; )
6684 {
6685 /* Only check buffers in a window. */
6686 if (buf->b_nwindows > 0)
6687 {
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006688 bufref_T bufref;
6689
6690 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006691 n = buf_check_timestamp(buf, focus);
6692 if (didit < n)
6693 didit = n;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006694 if (n > 0 && !bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006695 {
6696 /* Autocommands have removed the buffer, start at the
6697 * first one again. */
6698 buf = firstbuf;
6699 continue;
6700 }
6701 }
6702 buf = buf->b_next;
6703 }
6704 --no_wait_return;
6705 need_check_timestamps = FALSE;
6706 if (need_wait_return && didit == 2)
6707 {
6708 /* make sure msg isn't overwritten */
6709 msg_puts((char_u *)"\n");
6710 out_flush();
6711 }
6712 }
6713 return didit;
6714}
6715
6716/*
6717 * Move all the lines from buffer "frombuf" to buffer "tobuf".
6718 * Return OK or FAIL. When FAIL "tobuf" is incomplete and/or "frombuf" is not
6719 * empty.
6720 */
6721 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006722move_lines(buf_T *frombuf, buf_T *tobuf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006723{
6724 buf_T *tbuf = curbuf;
6725 int retval = OK;
6726 linenr_T lnum;
6727 char_u *p;
6728
6729 /* Copy the lines in "frombuf" to "tobuf". */
6730 curbuf = tobuf;
6731 for (lnum = 1; lnum <= frombuf->b_ml.ml_line_count; ++lnum)
6732 {
6733 p = vim_strsave(ml_get_buf(frombuf, lnum, FALSE));
6734 if (p == NULL || ml_append(lnum - 1, p, 0, FALSE) == FAIL)
6735 {
6736 vim_free(p);
6737 retval = FAIL;
6738 break;
6739 }
6740 vim_free(p);
6741 }
6742
6743 /* Delete all the lines in "frombuf". */
6744 if (retval != FAIL)
6745 {
6746 curbuf = frombuf;
Bram Moolenaar9460b9d2007-01-09 14:37:01 +00006747 for (lnum = curbuf->b_ml.ml_line_count; lnum > 0; --lnum)
6748 if (ml_delete(lnum, FALSE) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006749 {
6750 /* Oops! We could try putting back the saved lines, but that
6751 * might fail again... */
6752 retval = FAIL;
6753 break;
6754 }
6755 }
6756
6757 curbuf = tbuf;
6758 return retval;
6759}
6760
6761/*
6762 * Check if buffer "buf" has been changed.
6763 * Also check if the file for a new buffer unexpectedly appeared.
6764 * return 1 if a changed buffer was found.
6765 * return 2 if a message has been displayed.
6766 * return 0 otherwise.
6767 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006768 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006769buf_check_timestamp(
6770 buf_T *buf,
6771 int focus UNUSED) /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006772{
Bram Moolenaar8767f522016-07-01 17:17:39 +02006773 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006774 int stat_res;
6775 int retval = 0;
6776 char_u *path;
6777 char_u *tbuf;
6778 char *mesg = NULL;
Bram Moolenaar44ecf652005-03-07 23:09:59 +00006779 char *mesg2 = "";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006780 int helpmesg = FALSE;
6781 int reload = FALSE;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006782 char *reason;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006783#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6784 int can_reload = FALSE;
6785#endif
Bram Moolenaar8767f522016-07-01 17:17:39 +02006786 off_T orig_size = buf->b_orig_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006787 int orig_mode = buf->b_orig_mode;
6788#ifdef FEAT_GUI
6789 int save_mouse_correct = need_mouse_correct;
6790#endif
6791#ifdef FEAT_AUTOCMD
6792 static int busy = FALSE;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006793 int n;
6794 char_u *s;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006795 bufref_T bufref;
6796
6797 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006798#endif
6799
6800 /* If there is no file name, the buffer is not loaded, 'buftype' is
6801 * set, we are in the middle of a save or being called recursively: ignore
6802 * this buffer. */
6803 if (buf->b_ffname == NULL
6804 || buf->b_ml.ml_mfp == NULL
6805#if defined(FEAT_QUICKFIX)
6806 || *buf->b_p_bt != NUL
6807#endif
6808 || buf->b_saving
6809#ifdef FEAT_AUTOCMD
6810 || busy
6811#endif
Bram Moolenaar009b2592004-10-24 19:18:58 +00006812#ifdef FEAT_NETBEANS_INTG
6813 || isNetbeansBuffer(buf)
6814#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006815 )
6816 return 0;
6817
6818 if ( !(buf->b_flags & BF_NOTEDITED)
6819 && buf->b_mtime != 0
6820 && ((stat_res = mch_stat((char *)buf->b_ffname, &st)) < 0
6821 || time_differs((long)st.st_mtime, buf->b_mtime)
Bram Moolenaara7611f62014-05-02 15:46:14 +02006822 || st.st_size != buf->b_orig_size
Bram Moolenaar071d4272004-06-13 20:20:40 +00006823#ifdef HAVE_ST_MODE
6824 || (int)st.st_mode != buf->b_orig_mode
6825#else
6826 || mch_getperm(buf->b_ffname) != buf->b_orig_mode
6827#endif
6828 ))
6829 {
6830 retval = 1;
6831
Bram Moolenaar316059c2006-01-14 21:18:42 +00006832 /* set b_mtime to stop further warnings (e.g., when executing
6833 * FileChangedShell autocmd) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006834 if (stat_res < 0)
6835 {
6836 buf->b_mtime = 0;
6837 buf->b_orig_size = 0;
6838 buf->b_orig_mode = 0;
6839 }
6840 else
6841 buf_store_time(buf, &st, buf->b_ffname);
6842
6843 /* Don't do anything for a directory. Might contain the file
6844 * explorer. */
6845 if (mch_isdir(buf->b_fname))
6846 ;
6847
6848 /*
6849 * If 'autoread' is set, the buffer has no changes and the file still
6850 * exists, reload the buffer. Use the buffer-local option value if it
6851 * was set, the global option value otherwise.
6852 */
6853 else if ((buf->b_p_ar >= 0 ? buf->b_p_ar : p_ar)
6854 && !bufIsChanged(buf) && stat_res >= 0)
6855 reload = TRUE;
6856 else
6857 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006858 if (stat_res < 0)
6859 reason = "deleted";
6860 else if (bufIsChanged(buf))
6861 reason = "conflict";
6862 else if (orig_size != buf->b_orig_size || buf_contents_changed(buf))
6863 reason = "changed";
6864 else if (orig_mode != buf->b_orig_mode)
6865 reason = "mode";
6866 else
6867 reason = "time";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006868
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006869#ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006870 /*
6871 * Only give the warning if there are no FileChangedShell
6872 * autocommands.
6873 * Avoid being called recursively by setting "busy".
6874 */
6875 busy = TRUE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00006876# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006877 set_vim_var_string(VV_FCS_REASON, (char_u *)reason, -1);
6878 set_vim_var_string(VV_FCS_CHOICE, (char_u *)"", -1);
Bram Moolenaar1e015462005-09-25 22:16:38 +00006879# endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006880 ++allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006881 n = apply_autocmds(EVENT_FILECHANGEDSHELL,
6882 buf->b_fname, buf->b_fname, FALSE, buf);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006883 --allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006884 busy = FALSE;
6885 if (n)
6886 {
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006887 if (!bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006888 EMSG(_("E246: FileChangedShell autocommand deleted buffer"));
Bram Moolenaar1e015462005-09-25 22:16:38 +00006889# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006890 s = get_vim_var_str(VV_FCS_CHOICE);
6891 if (STRCMP(s, "reload") == 0 && *reason != 'd')
6892 reload = TRUE;
6893 else if (STRCMP(s, "ask") == 0)
6894 n = FALSE;
6895 else
Bram Moolenaar1e015462005-09-25 22:16:38 +00006896# endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006897 return 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006898 }
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006899 if (!n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006900#endif
6901 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006902 if (*reason == 'd')
6903 mesg = _("E211: File \"%s\" no longer available");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006904 else
6905 {
6906 helpmesg = TRUE;
6907#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6908 can_reload = TRUE;
6909#endif
6910 /*
6911 * Check if the file contents really changed to avoid
6912 * giving a warning when only the timestamp was set (e.g.,
6913 * checked out of CVS). Always warn when the buffer was
6914 * changed.
6915 */
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006916 if (reason[2] == 'n')
6917 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006918 mesg = _("W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006919 mesg2 = _("See \":help W12\" for more info.");
6920 }
6921 else if (reason[1] == 'h')
6922 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006923 mesg = _("W11: Warning: File \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006924 mesg2 = _("See \":help W11\" for more info.");
6925 }
6926 else if (*reason == 'm')
6927 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006928 mesg = _("W16: Warning: Mode of file \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006929 mesg2 = _("See \":help W16\" for more info.");
6930 }
Bram Moolenaar85388b52009-06-24 09:58:32 +00006931 else
6932 /* Only timestamp changed, store it to avoid a warning
6933 * in check_mtime() later. */
6934 buf->b_mtime_read = buf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006935 }
6936 }
6937 }
6938
6939 }
6940 else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W)
6941 && vim_fexists(buf->b_ffname))
6942 {
6943 retval = 1;
6944 mesg = _("W13: Warning: File \"%s\" has been created after editing started");
6945 buf->b_flags |= BF_NEW_W;
6946#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6947 can_reload = TRUE;
6948#endif
6949 }
6950
6951 if (mesg != NULL)
6952 {
6953 path = home_replace_save(buf, buf->b_fname);
6954 if (path != NULL)
6955 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006956 if (!helpmesg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006957 mesg2 = "";
6958 tbuf = alloc((unsigned)(STRLEN(path) + STRLEN(mesg)
6959 + STRLEN(mesg2) + 2));
6960 sprintf((char *)tbuf, mesg, path);
Bram Moolenaar496c5262009-03-18 14:42:00 +00006961#ifdef FEAT_EVAL
6962 /* Set warningmsg here, before the unimportant and output-specific
6963 * mesg2 has been appended. */
6964 set_vim_var_string(VV_WARNINGMSG, tbuf, -1);
6965#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006966#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6967 if (can_reload)
6968 {
6969 if (*mesg2 != NUL)
6970 {
6971 STRCAT(tbuf, "\n");
6972 STRCAT(tbuf, mesg2);
6973 }
6974 if (do_dialog(VIM_WARNING, (char_u *)_("Warning"), tbuf,
Bram Moolenaard2c340a2011-01-17 20:08:11 +01006975 (char_u *)_("&OK\n&Load File"), 1, NULL, TRUE) == 2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006976 reload = TRUE;
6977 }
6978 else
6979#endif
6980 if (State > NORMAL_BUSY || (State & CMDLINE) || already_warned)
6981 {
6982 if (*mesg2 != NUL)
6983 {
6984 STRCAT(tbuf, "; ");
6985 STRCAT(tbuf, mesg2);
6986 }
6987 EMSG(tbuf);
6988 retval = 2;
6989 }
6990 else
6991 {
Bram Moolenaared203462004-06-16 11:19:22 +00006992# ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006993 if (!autocmd_busy)
Bram Moolenaared203462004-06-16 11:19:22 +00006994# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006995 {
6996 msg_start();
6997 msg_puts_attr(tbuf, hl_attr(HLF_E) + MSG_HIST);
6998 if (*mesg2 != NUL)
6999 msg_puts_attr((char_u *)mesg2,
7000 hl_attr(HLF_W) + MSG_HIST);
7001 msg_clr_eos();
7002 (void)msg_end();
7003 if (emsg_silent == 0)
7004 {
7005 out_flush();
Bram Moolenaared203462004-06-16 11:19:22 +00007006# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00007007 if (!focus)
Bram Moolenaared203462004-06-16 11:19:22 +00007008# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007009 /* give the user some time to think about it */
7010 ui_delay(1000L, TRUE);
7011
7012 /* don't redraw and erase the message */
7013 redraw_cmdline = FALSE;
7014 }
7015 }
7016 already_warned = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007017 }
7018
7019 vim_free(path);
7020 vim_free(tbuf);
7021 }
7022 }
7023
7024 if (reload)
Bram Moolenaar465748e2012-08-29 18:50:54 +02007025 {
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007026 /* Reload the buffer. */
Bram Moolenaar316059c2006-01-14 21:18:42 +00007027 buf_reload(buf, orig_mode);
Bram Moolenaar465748e2012-08-29 18:50:54 +02007028#ifdef FEAT_PERSISTENT_UNDO
7029 if (buf->b_p_udf && buf->b_ffname != NULL)
7030 {
7031 char_u hash[UNDO_HASH_SIZE];
7032 buf_T *save_curbuf = curbuf;
7033
7034 /* Any existing undo file is unusable, write it now. */
7035 curbuf = buf;
7036 u_compute_hash(hash);
7037 u_write_undo(NULL, FALSE, buf, hash);
7038 curbuf = save_curbuf;
7039 }
7040#endif
7041 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007042
Bram Moolenaar56718732006-03-15 22:53:57 +00007043#ifdef FEAT_AUTOCMD
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00007044 /* Trigger FileChangedShell when the file was changed in any way. */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007045 if (bufref_valid(&bufref) && retval != 0)
Bram Moolenaar56718732006-03-15 22:53:57 +00007046 (void)apply_autocmds(EVENT_FILECHANGEDSHELLPOST,
7047 buf->b_fname, buf->b_fname, FALSE, buf);
7048#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007049#ifdef FEAT_GUI
7050 /* restore this in case an autocommand has set it; it would break
7051 * 'mousefocus' */
7052 need_mouse_correct = save_mouse_correct;
7053#endif
7054
7055 return retval;
7056}
7057
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007058/*
7059 * Reload a buffer that is already loaded.
7060 * Used when the file was changed outside of Vim.
Bram Moolenaar316059c2006-01-14 21:18:42 +00007061 * "orig_mode" is buf->b_orig_mode before the need for reloading was detected.
7062 * buf->b_orig_mode may have been reset already.
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007063 */
7064 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007065buf_reload(buf_T *buf, int orig_mode)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007066{
7067 exarg_T ea;
7068 pos_T old_cursor;
7069 linenr_T old_topline;
7070 int old_ro = buf->b_p_ro;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007071 buf_T *savebuf;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007072 bufref_T bufref;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007073 int saved = OK;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007074 aco_save_T aco;
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007075 int flags = READ_NEW;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007076
7077 /* set curwin/curbuf for "buf" and save some things */
7078 aucmd_prepbuf(&aco, buf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007079
7080 /* We only want to read the text from the file, not reset the syntax
7081 * highlighting, clear marks, diff status, etc. Force the fileformat
7082 * and encoding to be the same. */
7083 if (prep_exarg(&ea, buf) == OK)
7084 {
7085 old_cursor = curwin->w_cursor;
7086 old_topline = curwin->w_topline;
7087
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007088 if (p_ur < 0 || curbuf->b_ml.ml_line_count <= p_ur)
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007089 {
7090 /* Save all the text, so that the reload can be undone.
7091 * Sync first so that this is a separate undo-able action. */
7092 u_sync(FALSE);
7093 saved = u_savecommon(0, curbuf->b_ml.ml_line_count + 1, 0, TRUE);
7094 flags |= READ_KEEP_UNDO;
7095 }
7096
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007097 /*
7098 * To behave like when a new file is edited (matters for
7099 * BufReadPost autocommands) we first need to delete the current
7100 * buffer contents. But if reading the file fails we should keep
7101 * the old contents. Can't use memory only, the file might be
7102 * too big. Use a hidden buffer to move the buffer contents to.
7103 */
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007104 if (bufempty() || saved == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007105 savebuf = NULL;
7106 else
7107 {
7108 /* Allocate a buffer without putting it in the buffer list. */
7109 savebuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007110 set_bufref(&bufref, savebuf);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007111 if (savebuf != NULL && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007112 {
7113 /* Open the memline. */
7114 curbuf = savebuf;
7115 curwin->w_buffer = savebuf;
Bram Moolenaar4770d092006-01-12 23:22:24 +00007116 saved = ml_open(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007117 curbuf = buf;
7118 curwin->w_buffer = buf;
7119 }
Bram Moolenaar8424a622006-04-19 21:23:36 +00007120 if (savebuf == NULL || saved == FAIL || buf != curbuf
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007121 || move_lines(buf, savebuf) == FAIL)
7122 {
7123 EMSG2(_("E462: Could not prepare for reloading \"%s\""),
7124 buf->b_fname);
7125 saved = FAIL;
7126 }
7127 }
7128
7129 if (saved == OK)
7130 {
7131 curbuf->b_flags |= BF_CHECK_RO; /* check for RO again */
7132#ifdef FEAT_AUTOCMD
7133 keep_filetype = TRUE; /* don't detect 'filetype' */
7134#endif
7135 if (readfile(buf->b_ffname, buf->b_fname, (linenr_T)0,
7136 (linenr_T)0,
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007137 (linenr_T)MAXLNUM, &ea, flags) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007138 {
7139#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
7140 if (!aborting())
7141#endif
7142 EMSG2(_("E321: Could not reload \"%s\""), buf->b_fname);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007143 if (savebuf != NULL && bufref_valid(&bufref) && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007144 {
7145 /* Put the text back from the save buffer. First
7146 * delete any lines that readfile() added. */
7147 while (!bufempty())
Bram Moolenaar8424a622006-04-19 21:23:36 +00007148 if (ml_delete(buf->b_ml.ml_line_count, FALSE) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007149 break;
7150 (void)move_lines(savebuf, buf);
7151 }
7152 }
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007153 else if (buf == curbuf) /* "buf" still valid */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007154 {
7155 /* Mark the buffer as unmodified and free undo info. */
7156 unchanged(buf, TRUE);
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007157 if ((flags & READ_KEEP_UNDO) == 0)
7158 {
7159 u_blockfree(buf);
7160 u_clearall(buf);
7161 }
7162 else
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007163 {
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007164 /* Mark all undo states as changed. */
7165 u_unchanged(curbuf);
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007166 }
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007167 }
7168 }
7169 vim_free(ea.cmd);
7170
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007171 if (savebuf != NULL && bufref_valid(&bufref))
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007172 wipe_buffer(savebuf, FALSE);
7173
7174#ifdef FEAT_DIFF
7175 /* Invalidate diff info if necessary. */
Bram Moolenaar8424a622006-04-19 21:23:36 +00007176 diff_invalidate(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007177#endif
7178
7179 /* Restore the topline and cursor position and check it (lines may
7180 * have been removed). */
7181 if (old_topline > curbuf->b_ml.ml_line_count)
7182 curwin->w_topline = curbuf->b_ml.ml_line_count;
7183 else
7184 curwin->w_topline = old_topline;
7185 curwin->w_cursor = old_cursor;
7186 check_cursor();
7187 update_topline();
7188#ifdef FEAT_AUTOCMD
7189 keep_filetype = FALSE;
7190#endif
7191#ifdef FEAT_FOLDING
7192 {
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007193 win_T *wp;
7194 tabpage_T *tp;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007195
7196 /* Update folds unless they are defined manually. */
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007197 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007198 if (wp->w_buffer == curwin->w_buffer
7199 && !foldmethodIsManual(wp))
7200 foldUpdateAll(wp);
7201 }
7202#endif
7203 /* If the mode didn't change and 'readonly' was set, keep the old
7204 * value; the user probably used the ":view" command. But don't
7205 * reset it, might have had a read error. */
7206 if (orig_mode == curbuf->b_orig_mode)
7207 curbuf->b_p_ro |= old_ro;
Bram Moolenaar52f85b72013-01-30 14:13:56 +01007208
7209 /* Modelines must override settings done by autocommands. */
7210 do_modelines(0);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007211 }
7212
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007213 /* restore curwin/curbuf and a few other things */
7214 aucmd_restbuf(&aco);
7215 /* Careful: autocommands may have made "buf" invalid! */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007216}
7217
Bram Moolenaar071d4272004-06-13 20:20:40 +00007218 void
Bram Moolenaar8767f522016-07-01 17:17:39 +02007219buf_store_time(buf_T *buf, stat_T *st, char_u *fname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007220{
7221 buf->b_mtime = (long)st->st_mtime;
Bram Moolenaar914703b2010-05-31 21:59:46 +02007222 buf->b_orig_size = st->st_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007223#ifdef HAVE_ST_MODE
7224 buf->b_orig_mode = (int)st->st_mode;
7225#else
7226 buf->b_orig_mode = mch_getperm(fname);
7227#endif
7228}
7229
7230/*
7231 * Adjust the line with missing eol, used for the next write.
7232 * Used for do_filter(), when the input lines for the filter are deleted.
7233 */
7234 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007235write_lnum_adjust(linenr_T offset)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007236{
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01007237 if (curbuf->b_no_eol_lnum != 0) /* only if there is a missing eol */
7238 curbuf->b_no_eol_lnum += offset;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007239}
7240
Bram Moolenaarda440d22016-01-16 21:27:23 +01007241#if defined(TEMPDIRNAMES) || defined(FEAT_EVAL) || defined(PROTO)
7242/*
7243 * Delete "name" and everything in it, recursively.
7244 * return 0 for succes, -1 if some file was not deleted.
7245 */
7246 int
7247delete_recursive(char_u *name)
7248{
7249 int result = 0;
7250 char_u **files;
7251 int file_count;
7252 int i;
7253 char_u *exp;
7254
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007255 /* A symbolic link to a directory itself is deleted, not the directory it
7256 * points to. */
7257 if (
Bram Moolenaar203258c2016-01-17 22:15:16 +01007258# if defined(UNIX) || defined(WIN32)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007259 mch_isrealdir(name)
Bram Moolenaar203258c2016-01-17 22:15:16 +01007260# else
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007261 mch_isdir(name)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007262# endif
7263 )
Bram Moolenaarda440d22016-01-16 21:27:23 +01007264 {
7265 vim_snprintf((char *)NameBuff, MAXPATHL, "%s/*", name);
7266 exp = vim_strsave(NameBuff);
7267 if (exp == NULL)
7268 return -1;
7269 if (gen_expand_wildcards(1, &exp, &file_count, &files,
Bram Moolenaar336bd622016-01-17 18:23:58 +01007270 EW_DIR|EW_FILE|EW_SILENT|EW_ALLLINKS|EW_DODOT|EW_EMPTYOK) == OK)
Bram Moolenaarda440d22016-01-16 21:27:23 +01007271 {
7272 for (i = 0; i < file_count; ++i)
7273 if (delete_recursive(files[i]) != 0)
7274 result = -1;
7275 FreeWild(file_count, files);
7276 }
7277 else
7278 result = -1;
7279 vim_free(exp);
7280 (void)mch_rmdir(name);
7281 }
7282 else
7283 result = mch_remove(name) == 0 ? 0 : -1;
7284
7285 return result;
7286}
7287#endif
7288
Bram Moolenaar071d4272004-06-13 20:20:40 +00007289#if defined(TEMPDIRNAMES) || defined(PROTO)
7290static long temp_count = 0; /* Temp filename counter. */
7291
7292/*
7293 * Delete the temp directory and all files it contains.
7294 */
7295 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007296vim_deltempdir(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007297{
Bram Moolenaar071d4272004-06-13 20:20:40 +00007298 if (vim_tempdir != NULL)
7299 {
Bram Moolenaarda440d22016-01-16 21:27:23 +01007300 /* remove the trailing path separator */
7301 gettail(vim_tempdir)[-1] = NUL;
7302 delete_recursive(vim_tempdir);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007303 vim_free(vim_tempdir);
7304 vim_tempdir = NULL;
7305 }
7306}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007307
7308/*
Bram Moolenaareaf03392009-11-17 11:08:52 +00007309 * Directory "tempdir" was created. Expand this name to a full path and put
7310 * it in "vim_tempdir". This avoids that using ":cd" would confuse us.
7311 * "tempdir" must be no longer than MAXPATHL.
7312 */
7313 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007314vim_settempdir(char_u *tempdir)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007315{
7316 char_u *buf;
7317
7318 buf = alloc((unsigned)MAXPATHL + 2);
7319 if (buf != NULL)
7320 {
7321 if (vim_FullName(tempdir, buf, MAXPATHL, FALSE) == FAIL)
7322 STRCPY(buf, tempdir);
7323# ifdef __EMX__
7324 if (vim_strchr(buf, '/') != NULL)
7325 STRCAT(buf, "/");
7326 else
7327# endif
7328 add_pathsep(buf);
7329 vim_tempdir = vim_strsave(buf);
7330 vim_free(buf);
7331 }
7332}
Bram Moolenaar4592dee2009-11-18 19:11:58 +00007333#endif
Bram Moolenaareaf03392009-11-17 11:08:52 +00007334
7335/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007336 * vim_tempname(): Return a unique name that can be used for a temp file.
7337 *
Bram Moolenaar76ae22f2016-06-13 20:00:29 +02007338 * The temp file is NOT guaranteed to be created. If "keep" is FALSE it is
7339 * guaranteed to NOT be created.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007340 *
7341 * The returned pointer is to allocated memory.
7342 * The returned pointer is NULL if no valid name was found.
7343 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007344 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007345vim_tempname(
7346 int extra_char UNUSED, /* char to use in the name instead of '?' */
7347 int keep UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007348{
7349#ifdef USE_TMPNAM
7350 char_u itmp[L_tmpnam]; /* use tmpnam() */
7351#else
7352 char_u itmp[TEMPNAMELEN];
7353#endif
7354
7355#ifdef TEMPDIRNAMES
7356 static char *(tempdirs[]) = {TEMPDIRNAMES};
7357 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007358# ifndef EEXIST
Bram Moolenaar8767f522016-07-01 17:17:39 +02007359 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007360# endif
7361
7362 /*
7363 * This will create a directory for private use by this instance of Vim.
7364 * This is done once, and the same directory is used for all temp files.
7365 * This method avoids security problems because of symlink attacks et al.
7366 * It's also a bit faster, because we only need to check for an existing
7367 * file when creating the directory and not for each temp file.
7368 */
7369 if (vim_tempdir == NULL)
7370 {
7371 /*
7372 * Try the entries in TEMPDIRNAMES to create the temp directory.
7373 */
Bram Moolenaar78a15312009-05-15 19:33:18 +00007374 for (i = 0; i < (int)(sizeof(tempdirs) / sizeof(char *)); ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007375 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007376# ifndef HAVE_MKDTEMP
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007377 size_t itmplen;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007378 long nr;
7379 long off;
7380# endif
7381
Bram Moolenaare1a61992015-12-03 21:02:27 +01007382 /* Expand $TMP, leave room for "/v1100000/999999999".
7383 * Skip the directory check if the expansion fails. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007384 expand_env((char_u *)tempdirs[i], itmp, TEMPNAMELEN - 20);
Bram Moolenaare1a61992015-12-03 21:02:27 +01007385 if (itmp[0] != '$' && mch_isdir(itmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007386 {
Bram Moolenaare1a61992015-12-03 21:02:27 +01007387 /* directory exists */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007388# ifdef __EMX__
7389 /* If $TMP contains a forward slash (perhaps using bash or
7390 * tcsh), don't add a backslash, use a forward slash!
7391 * Adding 2 backslashes didn't work. */
7392 if (vim_strchr(itmp, '/') != NULL)
7393 STRCAT(itmp, "/");
7394 else
7395# endif
7396 add_pathsep(itmp);
7397
Bram Moolenaareaf03392009-11-17 11:08:52 +00007398# ifdef HAVE_MKDTEMP
Bram Moolenaar35d88f42016-06-04 14:52:00 +02007399 {
7400# if defined(UNIX) || defined(VMS)
7401 /* Make sure the umask doesn't remove the executable bit.
7402 * "repl" has been reported to use "177". */
7403 mode_t umask_save = umask(077);
7404# endif
7405 /* Leave room for filename */
7406 STRCAT(itmp, "vXXXXXX");
7407 if (mkdtemp((char *)itmp) != NULL)
7408 vim_settempdir(itmp);
7409# if defined(UNIX) || defined(VMS)
7410 (void)umask(umask_save);
7411# endif
7412 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007413# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007414 /* Get an arbitrary number of up to 6 digits. When it's
7415 * unlikely that it already exists it will be faster,
7416 * otherwise it doesn't matter. The use of mkdir() avoids any
7417 * security problems because of the predictable number. */
7418 nr = (mch_get_pid() + (long)time(NULL)) % 1000000L;
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007419 itmplen = STRLEN(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007420
7421 /* Try up to 10000 different values until we find a name that
7422 * doesn't exist. */
7423 for (off = 0; off < 10000L; ++off)
7424 {
7425 int r;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007426# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007427 mode_t umask_save;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007428# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007429
Bram Moolenaareaf03392009-11-17 11:08:52 +00007430 sprintf((char *)itmp + itmplen, "v%ld", nr + off);
7431# ifndef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007432 /* If mkdir() does not set errno to EEXIST, check for
7433 * existing file here. There is a race condition then,
7434 * although it's fail-safe. */
7435 if (mch_stat((char *)itmp, &st) >= 0)
7436 continue;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007437# endif
7438# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007439 /* Make sure the umask doesn't remove the executable bit.
7440 * "repl" has been reported to use "177". */
7441 umask_save = umask(077);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007442# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007443 r = vim_mkdir(itmp, 0700);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007444# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007445 (void)umask(umask_save);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007446# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007447 if (r == 0)
7448 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007449 vim_settempdir(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007450 break;
7451 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007452# ifdef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007453 /* If the mkdir() didn't fail because the file/dir exists,
7454 * we probably can't create any dir here, try another
7455 * place. */
7456 if (errno != EEXIST)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007457# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007458 break;
7459 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007460# endif /* HAVE_MKDTEMP */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007461 if (vim_tempdir != NULL)
7462 break;
7463 }
7464 }
7465 }
7466
7467 if (vim_tempdir != NULL)
7468 {
7469 /* There is no need to check if the file exists, because we own the
7470 * directory and nobody else creates a file in it. */
7471 sprintf((char *)itmp, "%s%ld", vim_tempdir, temp_count++);
7472 return vim_strsave(itmp);
7473 }
7474
7475 return NULL;
7476
7477#else /* TEMPDIRNAMES */
7478
7479# ifdef WIN3264
7480 char szTempFile[_MAX_PATH + 1];
7481 char buf4[4];
7482 char_u *retval;
7483 char_u *p;
7484
7485 STRCPY(itmp, "");
7486 if (GetTempPath(_MAX_PATH, szTempFile) == 0)
Bram Moolenaarb1891912011-02-09 14:47:03 +01007487 {
7488 szTempFile[0] = '.'; /* GetTempPath() failed, use current dir */
7489 szTempFile[1] = NUL;
7490 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007491 strcpy(buf4, "VIM");
7492 buf4[2] = extra_char; /* make it "VIa", "VIb", etc. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007493 if (GetTempFileName(szTempFile, buf4, 0, (LPSTR)itmp) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007494 return NULL;
Bram Moolenaare5c421c2015-03-31 13:33:08 +02007495 if (!keep)
7496 /* GetTempFileName() will create the file, we don't want that */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007497 (void)DeleteFile((LPSTR)itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007498
7499 /* Backslashes in a temp file name cause problems when filtering with
7500 * "sh". NOTE: This also checks 'shellcmdflag' to help those people who
7501 * didn't set 'shellslash'. */
7502 retval = vim_strsave(itmp);
7503 if (*p_shcf == '-' || p_ssl)
7504 for (p = retval; *p; ++p)
7505 if (*p == '\\')
7506 *p = '/';
7507 return retval;
7508
7509# else /* WIN3264 */
7510
7511# ifdef USE_TMPNAM
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007512 char_u *p;
7513
Bram Moolenaar071d4272004-06-13 20:20:40 +00007514 /* tmpnam() will make its own name */
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007515 p = tmpnam((char *)itmp);
7516 if (p == NULL || *p == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007517 return NULL;
7518# else
7519 char_u *p;
7520
7521# ifdef VMS_TEMPNAM
7522 /* mktemp() is not working on VMS. It seems to be
7523 * a do-nothing function. Therefore we use tempnam().
7524 */
7525 sprintf((char *)itmp, "VIM%c", extra_char);
7526 p = (char_u *)tempnam("tmp:", (char *)itmp);
7527 if (p != NULL)
7528 {
Bram Moolenaar206f0112014-03-12 16:51:55 +01007529 /* VMS will use '.LIS' if we don't explicitly specify an extension,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007530 * and VIM will then be unable to find the file later */
7531 STRCPY(itmp, p);
7532 STRCAT(itmp, ".txt");
7533 free(p);
7534 }
7535 else
7536 return NULL;
7537# else
7538 STRCPY(itmp, TEMPNAME);
7539 if ((p = vim_strchr(itmp, '?')) != NULL)
7540 *p = extra_char;
7541 if (mktemp((char *)itmp) == NULL)
7542 return NULL;
7543# endif
7544# endif
7545
7546 return vim_strsave(itmp);
7547# endif /* WIN3264 */
7548#endif /* TEMPDIRNAMES */
7549}
7550
7551#if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
7552/*
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02007553 * Convert all backslashes in fname to forward slashes in-place, unless when
7554 * it looks like a URL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007555 */
7556 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007557forward_slash(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007558{
7559 char_u *p;
7560
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02007561 if (path_with_url(fname))
7562 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007563 for (p = fname; *p != NUL; ++p)
7564# ifdef FEAT_MBYTE
7565 /* The Big5 encoding can have '\' in the trail byte. */
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00007566 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007567 ++p;
7568 else
7569# endif
7570 if (*p == '\\')
7571 *p = '/';
7572}
7573#endif
7574
7575
7576/*
7577 * Code for automatic commands.
7578 *
7579 * Only included when "FEAT_AUTOCMD" has been defined.
7580 */
7581
7582#if defined(FEAT_AUTOCMD) || defined(PROTO)
7583
7584/*
7585 * The autocommands are stored in a list for each event.
7586 * Autocommands for the same pattern, that are consecutive, are joined
7587 * together, to avoid having to match the pattern too often.
7588 * The result is an array of Autopat lists, which point to AutoCmd lists:
7589 *
7590 * first_autopat[0] --> Autopat.next --> Autopat.next --> NULL
7591 * Autopat.cmds Autopat.cmds
7592 * | |
7593 * V V
7594 * AutoCmd.next AutoCmd.next
7595 * | |
7596 * V V
7597 * AutoCmd.next NULL
7598 * |
7599 * V
7600 * NULL
7601 *
7602 * first_autopat[1] --> Autopat.next --> NULL
7603 * Autopat.cmds
7604 * |
7605 * V
7606 * AutoCmd.next
7607 * |
7608 * V
7609 * NULL
7610 * etc.
7611 *
7612 * The order of AutoCmds is important, this is the order in which they were
7613 * defined and will have to be executed.
7614 */
7615typedef struct AutoCmd
7616{
7617 char_u *cmd; /* The command to be executed (NULL
7618 when command has been removed) */
7619 char nested; /* If autocommands nest here */
7620 char last; /* last command in list */
7621#ifdef FEAT_EVAL
7622 scid_T scriptID; /* script ID where defined */
7623#endif
7624 struct AutoCmd *next; /* Next AutoCmd in list */
7625} AutoCmd;
7626
7627typedef struct AutoPat
7628{
Bram Moolenaar071d4272004-06-13 20:20:40 +00007629 char_u *pat; /* pattern as typed (NULL when pattern
7630 has been removed) */
Bram Moolenaar748bf032005-02-02 23:04:36 +00007631 regprog_T *reg_prog; /* compiled regprog for pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007632 AutoCmd *cmds; /* list of commands to do */
7633 struct AutoPat *next; /* next AutoPat in AutoPat list */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007634 int group; /* group ID */
7635 int patlen; /* strlen() of pat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007636 int buflocal_nr; /* !=0 for buffer-local AutoPat */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007637 char allow_dirs; /* Pattern may match whole path */
7638 char last; /* last pattern for apply_autocmds() */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007639} AutoPat;
7640
7641static struct event_name
7642{
7643 char *name; /* event name */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007644 event_T event; /* event number */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007645} event_names[] =
7646{
7647 {"BufAdd", EVENT_BUFADD},
7648 {"BufCreate", EVENT_BUFADD},
7649 {"BufDelete", EVENT_BUFDELETE},
7650 {"BufEnter", EVENT_BUFENTER},
7651 {"BufFilePost", EVENT_BUFFILEPOST},
7652 {"BufFilePre", EVENT_BUFFILEPRE},
7653 {"BufHidden", EVENT_BUFHIDDEN},
7654 {"BufLeave", EVENT_BUFLEAVE},
7655 {"BufNew", EVENT_BUFNEW},
7656 {"BufNewFile", EVENT_BUFNEWFILE},
7657 {"BufRead", EVENT_BUFREADPOST},
7658 {"BufReadCmd", EVENT_BUFREADCMD},
7659 {"BufReadPost", EVENT_BUFREADPOST},
7660 {"BufReadPre", EVENT_BUFREADPRE},
7661 {"BufUnload", EVENT_BUFUNLOAD},
7662 {"BufWinEnter", EVENT_BUFWINENTER},
7663 {"BufWinLeave", EVENT_BUFWINLEAVE},
7664 {"BufWipeout", EVENT_BUFWIPEOUT},
7665 {"BufWrite", EVENT_BUFWRITEPRE},
7666 {"BufWritePost", EVENT_BUFWRITEPOST},
7667 {"BufWritePre", EVENT_BUFWRITEPRE},
7668 {"BufWriteCmd", EVENT_BUFWRITECMD},
7669 {"CmdwinEnter", EVENT_CMDWINENTER},
7670 {"CmdwinLeave", EVENT_CMDWINLEAVE},
Bram Moolenaard5005162014-08-22 23:05:54 +02007671 {"CmdUndefined", EVENT_CMDUNDEFINED},
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007672 {"ColorScheme", EVENT_COLORSCHEME},
Bram Moolenaarcfa3cae2012-07-10 17:14:56 +02007673 {"CompleteDone", EVENT_COMPLETEDONE},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007674 {"CursorHold", EVENT_CURSORHOLD},
7675 {"CursorHoldI", EVENT_CURSORHOLDI},
7676 {"CursorMoved", EVENT_CURSORMOVED},
7677 {"CursorMovedI", EVENT_CURSORMOVEDI},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007678 {"EncodingChanged", EVENT_ENCODINGCHANGED},
7679 {"FileEncoding", EVENT_ENCODINGCHANGED},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007680 {"FileAppendPost", EVENT_FILEAPPENDPOST},
7681 {"FileAppendPre", EVENT_FILEAPPENDPRE},
7682 {"FileAppendCmd", EVENT_FILEAPPENDCMD},
7683 {"FileChangedShell",EVENT_FILECHANGEDSHELL},
Bram Moolenaar56718732006-03-15 22:53:57 +00007684 {"FileChangedShellPost",EVENT_FILECHANGEDSHELLPOST},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007685 {"FileChangedRO", EVENT_FILECHANGEDRO},
7686 {"FileReadPost", EVENT_FILEREADPOST},
7687 {"FileReadPre", EVENT_FILEREADPRE},
7688 {"FileReadCmd", EVENT_FILEREADCMD},
7689 {"FileType", EVENT_FILETYPE},
7690 {"FileWritePost", EVENT_FILEWRITEPOST},
7691 {"FileWritePre", EVENT_FILEWRITEPRE},
7692 {"FileWriteCmd", EVENT_FILEWRITECMD},
7693 {"FilterReadPost", EVENT_FILTERREADPOST},
7694 {"FilterReadPre", EVENT_FILTERREADPRE},
7695 {"FilterWritePost", EVENT_FILTERWRITEPOST},
7696 {"FilterWritePre", EVENT_FILTERWRITEPRE},
7697 {"FocusGained", EVENT_FOCUSGAINED},
7698 {"FocusLost", EVENT_FOCUSLOST},
7699 {"FuncUndefined", EVENT_FUNCUNDEFINED},
7700 {"GUIEnter", EVENT_GUIENTER},
Bram Moolenaar265e5072006-08-29 16:13:22 +00007701 {"GUIFailed", EVENT_GUIFAILED},
Bram Moolenaar843ee412004-06-30 16:16:41 +00007702 {"InsertChange", EVENT_INSERTCHANGE},
7703 {"InsertEnter", EVENT_INSERTENTER},
7704 {"InsertLeave", EVENT_INSERTLEAVE},
Bram Moolenaare659c952011-05-19 17:25:41 +02007705 {"InsertCharPre", EVENT_INSERTCHARPRE},
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00007706 {"MenuPopup", EVENT_MENUPOPUP},
Bram Moolenaar53744302015-07-17 17:38:22 +02007707 {"OptionSet", EVENT_OPTIONSET},
Bram Moolenaar7c626922005-02-07 22:01:03 +00007708 {"QuickFixCmdPost", EVENT_QUICKFIXCMDPOST},
7709 {"QuickFixCmdPre", EVENT_QUICKFIXCMDPRE},
Bram Moolenaar3b53dfb2012-06-06 18:03:07 +02007710 {"QuitPre", EVENT_QUITPRE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007711 {"RemoteReply", EVENT_REMOTEREPLY},
Bram Moolenaar9372a112005-12-06 19:59:18 +00007712 {"SessionLoadPost", EVENT_SESSIONLOADPOST},
Bram Moolenaar5c4bab02006-03-10 21:37:46 +00007713 {"ShellCmdPost", EVENT_SHELLCMDPOST},
7714 {"ShellFilterPost", EVENT_SHELLFILTERPOST},
Bram Moolenaara2031822006-03-07 22:29:51 +00007715 {"SourcePre", EVENT_SOURCEPRE},
Bram Moolenaar8dd1aa52007-01-16 20:33:19 +00007716 {"SourceCmd", EVENT_SOURCECMD},
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00007717 {"SpellFileMissing",EVENT_SPELLFILEMISSING},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007718 {"StdinReadPost", EVENT_STDINREADPOST},
7719 {"StdinReadPre", EVENT_STDINREADPRE},
Bram Moolenaarb815dac2005-12-07 20:59:24 +00007720 {"SwapExists", EVENT_SWAPEXISTS},
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00007721 {"Syntax", EVENT_SYNTAX},
Bram Moolenaar70836c82006-02-20 21:28:49 +00007722 {"TabEnter", EVENT_TABENTER},
7723 {"TabLeave", EVENT_TABLEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007724 {"TermChanged", EVENT_TERMCHANGED},
7725 {"TermResponse", EVENT_TERMRESPONSE},
Bram Moolenaar186628f2013-03-19 13:33:23 +01007726 {"TextChanged", EVENT_TEXTCHANGED},
7727 {"TextChangedI", EVENT_TEXTCHANGEDI},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007728 {"User", EVENT_USER},
7729 {"VimEnter", EVENT_VIMENTER},
7730 {"VimLeave", EVENT_VIMLEAVE},
7731 {"VimLeavePre", EVENT_VIMLEAVEPRE},
7732 {"WinEnter", EVENT_WINENTER},
7733 {"WinLeave", EVENT_WINLEAVE},
Bram Moolenaar56718732006-03-15 22:53:57 +00007734 {"VimResized", EVENT_VIMRESIZED},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007735 {NULL, (event_T)0}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007736};
7737
7738static AutoPat *first_autopat[NUM_EVENTS] =
7739{
7740 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7741 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7742 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7743 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00007744 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaar53744302015-07-17 17:38:22 +02007745 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007746};
7747
7748/*
7749 * struct used to keep status while executing autocommands for an event.
7750 */
7751typedef struct AutoPatCmd
7752{
7753 AutoPat *curpat; /* next AutoPat to examine */
7754 AutoCmd *nextcmd; /* next AutoCmd to execute */
7755 int group; /* group being used */
7756 char_u *fname; /* fname to match with */
7757 char_u *sfname; /* sfname to match with */
7758 char_u *tail; /* tail of fname */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007759 event_T event; /* current event */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007760 int arg_bufnr; /* initially equal to <abuf>, set to zero when
7761 buf is deleted */
7762 struct AutoPatCmd *next; /* chain of active apc-s for auto-invalidation*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00007763} AutoPatCmd;
7764
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007765static AutoPatCmd *active_apc_list = NULL; /* stack of active autocommands */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007766
Bram Moolenaar071d4272004-06-13 20:20:40 +00007767/*
7768 * augroups stores a list of autocmd group names.
7769 */
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007770static garray_T augroups = {0, 0, sizeof(char_u *), 10, NULL};
Bram Moolenaar071d4272004-06-13 20:20:40 +00007771#define AUGROUP_NAME(i) (((char_u **)augroups.ga_data)[i])
7772
7773/*
7774 * The ID of the current group. Group 0 is the default one.
7775 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007776static int current_augroup = AUGROUP_DEFAULT;
7777
7778static int au_need_clean = FALSE; /* need to delete marked patterns */
7779
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007780static void show_autocmd(AutoPat *ap, event_T event);
7781static void au_remove_pat(AutoPat *ap);
7782static void au_remove_cmds(AutoPat *ap);
7783static void au_cleanup(void);
7784static int au_new_group(char_u *name);
7785static void au_del_group(char_u *name);
7786static event_T event_name2nr(char_u *start, char_u **end);
7787static char_u *event_nr2name(event_T event);
7788static char_u *find_end_event(char_u *arg, int have_group);
7789static int event_ignored(event_T event);
7790static int au_get_grouparg(char_u **argp);
7791static int do_autocmd_event(event_T event, char_u *pat, int nested, char_u *cmd, int forceit, int group);
7792static int apply_autocmds_group(event_T event, char_u *fname, char_u *fname_io, int force, int group, buf_T *buf, exarg_T *eap);
7793static void auto_next_pat(AutoPatCmd *apc, int stop_at_last);
Bram Moolenaardffa5b82014-11-19 16:38:07 +01007794#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN)
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007795static 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 +01007796#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007797
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007798
Bram Moolenaar754b5602006-02-09 23:53:20 +00007799static event_T last_event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007800static int last_group;
Bram Moolenaar78ab3312007-09-29 12:16:41 +00007801static int autocmd_blocked = 0; /* block all autocmds */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007802
7803/*
7804 * Show the autocommands for one AutoPat.
7805 */
7806 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007807show_autocmd(AutoPat *ap, event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007808{
7809 AutoCmd *ac;
7810
7811 /* Check for "got_int" (here and at various places below), which is set
7812 * when "q" has been hit for the "--more--" prompt */
7813 if (got_int)
7814 return;
7815 if (ap->pat == NULL) /* pattern has been removed */
7816 return;
7817
7818 msg_putchar('\n');
7819 if (got_int)
7820 return;
7821 if (event != last_event || ap->group != last_group)
7822 {
7823 if (ap->group != AUGROUP_DEFAULT)
7824 {
7825 if (AUGROUP_NAME(ap->group) == NULL)
7826 msg_puts_attr((char_u *)_("--Deleted--"), hl_attr(HLF_E));
7827 else
7828 msg_puts_attr(AUGROUP_NAME(ap->group), hl_attr(HLF_T));
7829 msg_puts((char_u *)" ");
7830 }
7831 msg_puts_attr(event_nr2name(event), hl_attr(HLF_T));
7832 last_event = event;
7833 last_group = ap->group;
7834 msg_putchar('\n');
7835 if (got_int)
7836 return;
7837 }
7838 msg_col = 4;
7839 msg_outtrans(ap->pat);
7840
7841 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7842 {
7843 if (ac->cmd != NULL) /* skip removed commands */
7844 {
7845 if (msg_col >= 14)
7846 msg_putchar('\n');
7847 msg_col = 14;
7848 if (got_int)
7849 return;
7850 msg_outtrans(ac->cmd);
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00007851#ifdef FEAT_EVAL
7852 if (p_verbose > 0)
7853 last_set_msg(ac->scriptID);
7854#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007855 if (got_int)
7856 return;
7857 if (ac->next != NULL)
7858 {
7859 msg_putchar('\n');
7860 if (got_int)
7861 return;
7862 }
7863 }
7864 }
7865}
7866
7867/*
7868 * Mark an autocommand pattern for deletion.
7869 */
7870 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007871au_remove_pat(AutoPat *ap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007872{
7873 vim_free(ap->pat);
7874 ap->pat = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007875 ap->buflocal_nr = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007876 au_need_clean = TRUE;
7877}
7878
7879/*
7880 * Mark all commands for a pattern for deletion.
7881 */
7882 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007883au_remove_cmds(AutoPat *ap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007884{
7885 AutoCmd *ac;
7886
7887 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7888 {
7889 vim_free(ac->cmd);
7890 ac->cmd = NULL;
7891 }
7892 au_need_clean = TRUE;
7893}
7894
7895/*
7896 * Cleanup autocommands and patterns that have been deleted.
7897 * This is only done when not executing autocommands.
7898 */
7899 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007900au_cleanup(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007901{
7902 AutoPat *ap, **prev_ap;
7903 AutoCmd *ac, **prev_ac;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007904 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007905
7906 if (autocmd_busy || !au_need_clean)
7907 return;
7908
7909 /* loop over all events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007910 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7911 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007912 {
7913 /* loop over all autocommand patterns */
7914 prev_ap = &(first_autopat[(int)event]);
7915 for (ap = *prev_ap; ap != NULL; ap = *prev_ap)
7916 {
7917 /* loop over all commands for this pattern */
7918 prev_ac = &(ap->cmds);
7919 for (ac = *prev_ac; ac != NULL; ac = *prev_ac)
7920 {
7921 /* remove the command if the pattern is to be deleted or when
7922 * the command has been marked for deletion */
7923 if (ap->pat == NULL || ac->cmd == NULL)
7924 {
7925 *prev_ac = ac->next;
7926 vim_free(ac->cmd);
7927 vim_free(ac);
7928 }
7929 else
7930 prev_ac = &(ac->next);
7931 }
7932
7933 /* remove the pattern if it has been marked for deletion */
7934 if (ap->pat == NULL)
7935 {
7936 *prev_ap = ap->next;
Bram Moolenaar473de612013-06-08 18:19:48 +02007937 vim_regfree(ap->reg_prog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007938 vim_free(ap);
7939 }
7940 else
7941 prev_ap = &(ap->next);
7942 }
7943 }
7944
7945 au_need_clean = FALSE;
7946}
7947
7948/*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007949 * Called when buffer is freed, to remove/invalidate related buffer-local
7950 * autocmds.
7951 */
7952 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007953aubuflocal_remove(buf_T *buf)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007954{
7955 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007956 event_T event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007957 AutoPatCmd *apc;
7958
7959 /* invalidate currently executing autocommands */
7960 for (apc = active_apc_list; apc; apc = apc->next)
7961 if (buf->b_fnum == apc->arg_bufnr)
7962 apc->arg_bufnr = 0;
7963
7964 /* invalidate buflocals looping through events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007965 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7966 event = (event_T)((int)event + 1))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007967 /* loop over all autocommand patterns */
7968 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
7969 if (ap->buflocal_nr == buf->b_fnum)
7970 {
7971 au_remove_pat(ap);
7972 if (p_verbose >= 6)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007973 {
7974 verbose_enter();
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007975 smsg((char_u *)
7976 _("auto-removing autocommand: %s <buffer=%d>"),
7977 event_nr2name(event), buf->b_fnum);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007978 verbose_leave();
7979 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007980 }
7981 au_cleanup();
7982}
7983
7984/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007985 * Add an autocmd group name.
7986 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
7987 */
7988 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007989au_new_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007990{
7991 int i;
7992
7993 i = au_find_group(name);
7994 if (i == AUGROUP_ERROR) /* the group doesn't exist yet, add it */
7995 {
7996 /* First try using a free entry. */
7997 for (i = 0; i < augroups.ga_len; ++i)
7998 if (AUGROUP_NAME(i) == NULL)
7999 break;
8000 if (i == augroups.ga_len && ga_grow(&augroups, 1) == FAIL)
8001 return AUGROUP_ERROR;
8002
8003 AUGROUP_NAME(i) = vim_strsave(name);
8004 if (AUGROUP_NAME(i) == NULL)
8005 return AUGROUP_ERROR;
8006 if (i == augroups.ga_len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008007 ++augroups.ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008008 }
8009
8010 return i;
8011}
8012
8013 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008014au_del_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008015{
8016 int i;
8017
8018 i = au_find_group(name);
8019 if (i == AUGROUP_ERROR) /* the group doesn't exist */
8020 EMSG2(_("E367: No such group: \"%s\""), name);
8021 else
8022 {
8023 vim_free(AUGROUP_NAME(i));
8024 AUGROUP_NAME(i) = NULL;
8025 }
8026}
8027
8028/*
8029 * Find the ID of an autocmd group name.
8030 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
8031 */
8032 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008033au_find_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008034{
8035 int i;
8036
8037 for (i = 0; i < augroups.ga_len; ++i)
8038 if (AUGROUP_NAME(i) != NULL && STRCMP(AUGROUP_NAME(i), name) == 0)
8039 return i;
8040 return AUGROUP_ERROR;
8041}
8042
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008043/*
8044 * Return TRUE if augroup "name" exists.
8045 */
8046 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008047au_has_group(char_u *name)
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008048{
8049 return au_find_group(name) != AUGROUP_ERROR;
8050}
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008051
Bram Moolenaar071d4272004-06-13 20:20:40 +00008052/*
8053 * ":augroup {name}".
8054 */
8055 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008056do_augroup(char_u *arg, int del_group)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008057{
8058 int i;
8059
8060 if (del_group)
8061 {
8062 if (*arg == NUL)
8063 EMSG(_(e_argreq));
8064 else
8065 au_del_group(arg);
8066 }
8067 else if (STRICMP(arg, "end") == 0) /* ":aug end": back to group 0 */
8068 current_augroup = AUGROUP_DEFAULT;
8069 else if (*arg) /* ":aug xxx": switch to group xxx */
8070 {
8071 i = au_new_group(arg);
8072 if (i != AUGROUP_ERROR)
8073 current_augroup = i;
8074 }
8075 else /* ":aug": list the group names */
8076 {
8077 msg_start();
8078 for (i = 0; i < augroups.ga_len; ++i)
8079 {
8080 if (AUGROUP_NAME(i) != NULL)
8081 {
8082 msg_puts(AUGROUP_NAME(i));
8083 msg_puts((char_u *)" ");
8084 }
8085 }
8086 msg_clr_eos();
8087 msg_end();
8088 }
8089}
8090
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008091#if defined(EXITFREE) || defined(PROTO)
8092 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008093free_all_autocmds(void)
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008094{
8095 for (current_augroup = -1; current_augroup < augroups.ga_len;
8096 ++current_augroup)
8097 do_autocmd((char_u *)"", TRUE);
8098 ga_clear_strings(&augroups);
8099}
8100#endif
8101
Bram Moolenaar071d4272004-06-13 20:20:40 +00008102/*
8103 * Return the event number for event name "start".
8104 * Return NUM_EVENTS if the event name was not found.
8105 * Return a pointer to the next event name in "end".
8106 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008107 static event_T
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008108event_name2nr(char_u *start, char_u **end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008109{
8110 char_u *p;
8111 int i;
8112 int len;
8113
8114 /* the event name ends with end of line, a blank or a comma */
8115 for (p = start; *p && !vim_iswhite(*p) && *p != ','; ++p)
8116 ;
8117 for (i = 0; event_names[i].name != NULL; ++i)
8118 {
8119 len = (int)STRLEN(event_names[i].name);
8120 if (len == p - start && STRNICMP(event_names[i].name, start, len) == 0)
8121 break;
8122 }
8123 if (*p == ',')
8124 ++p;
8125 *end = p;
8126 if (event_names[i].name == NULL)
8127 return NUM_EVENTS;
8128 return event_names[i].event;
8129}
8130
8131/*
8132 * Return the name for event "event".
8133 */
8134 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008135event_nr2name(event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008136{
8137 int i;
8138
8139 for (i = 0; event_names[i].name != NULL; ++i)
8140 if (event_names[i].event == event)
8141 return (char_u *)event_names[i].name;
8142 return (char_u *)"Unknown";
8143}
8144
8145/*
8146 * Scan over the events. "*" stands for all events.
8147 */
8148 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008149find_end_event(
8150 char_u *arg,
8151 int have_group) /* TRUE when group name was found */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008152{
8153 char_u *pat;
8154 char_u *p;
8155
8156 if (*arg == '*')
8157 {
8158 if (arg[1] && !vim_iswhite(arg[1]))
8159 {
8160 EMSG2(_("E215: Illegal character after *: %s"), arg);
8161 return NULL;
8162 }
8163 pat = arg + 1;
8164 }
8165 else
8166 {
8167 for (pat = arg; *pat && !vim_iswhite(*pat); pat = p)
8168 {
8169 if ((int)event_name2nr(pat, &p) >= (int)NUM_EVENTS)
8170 {
8171 if (have_group)
8172 EMSG2(_("E216: No such event: %s"), pat);
8173 else
8174 EMSG2(_("E216: No such group or event: %s"), pat);
8175 return NULL;
8176 }
8177 }
8178 }
8179 return pat;
8180}
8181
8182/*
8183 * Return TRUE if "event" is included in 'eventignore'.
8184 */
8185 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008186event_ignored(event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008187{
8188 char_u *p = p_ei;
8189
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008190 while (*p != NUL)
8191 {
8192 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8193 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008194 if (event_name2nr(p, &p) == event)
8195 return TRUE;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008196 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008197
8198 return FALSE;
8199}
8200
8201/*
8202 * Return OK when the contents of p_ei is valid, FAIL otherwise.
8203 */
8204 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008205check_ei(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008206{
8207 char_u *p = p_ei;
8208
Bram Moolenaar071d4272004-06-13 20:20:40 +00008209 while (*p)
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008210 {
8211 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8212 {
8213 p += 3;
8214 if (*p == ',')
8215 ++p;
8216 }
8217 else if (event_name2nr(p, &p) == NUM_EVENTS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008218 return FAIL;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008219 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008220
8221 return OK;
8222}
8223
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008224# if defined(FEAT_SYN_HL) || defined(PROTO)
8225
8226/*
8227 * Add "what" to 'eventignore' to skip loading syntax highlighting for every
8228 * buffer loaded into the window. "what" must start with a comma.
8229 * Returns the old value of 'eventignore' in allocated memory.
8230 */
8231 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008232au_event_disable(char *what)
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008233{
8234 char_u *new_ei;
8235 char_u *save_ei;
8236
8237 save_ei = vim_strsave(p_ei);
8238 if (save_ei != NULL)
8239 {
Bram Moolenaara5792f52005-11-23 21:25:05 +00008240 new_ei = vim_strnsave(p_ei, (int)(STRLEN(p_ei) + STRLEN(what)));
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008241 if (new_ei != NULL)
8242 {
Bram Moolenaar8cac9fd2010-03-02 12:48:05 +01008243 if (*what == ',' && *p_ei == NUL)
8244 STRCPY(new_ei, what + 1);
8245 else
8246 STRCAT(new_ei, what);
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008247 set_string_option_direct((char_u *)"ei", -1, new_ei,
8248 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008249 vim_free(new_ei);
8250 }
8251 }
8252 return save_ei;
8253}
8254
8255 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008256au_event_restore(char_u *old_ei)
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008257{
8258 if (old_ei != NULL)
8259 {
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008260 set_string_option_direct((char_u *)"ei", -1, old_ei,
8261 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008262 vim_free(old_ei);
8263 }
8264}
8265# endif /* FEAT_SYN_HL */
8266
Bram Moolenaar071d4272004-06-13 20:20:40 +00008267/*
8268 * do_autocmd() -- implements the :autocmd command. Can be used in the
8269 * following ways:
8270 *
8271 * :autocmd <event> <pat> <cmd> Add <cmd> to the list of commands that
8272 * will be automatically executed for <event>
8273 * when editing a file matching <pat>, in
8274 * the current group.
8275 * :autocmd <event> <pat> Show the auto-commands associated with
8276 * <event> and <pat>.
8277 * :autocmd <event> Show the auto-commands associated with
8278 * <event>.
8279 * :autocmd Show all auto-commands.
8280 * :autocmd! <event> <pat> <cmd> Remove all auto-commands associated with
8281 * <event> and <pat>, and add the command
8282 * <cmd>, for the current group.
8283 * :autocmd! <event> <pat> Remove all auto-commands associated with
8284 * <event> and <pat> for the current group.
8285 * :autocmd! <event> Remove all auto-commands associated with
8286 * <event> for the current group.
8287 * :autocmd! Remove ALL auto-commands for the current
8288 * group.
8289 *
8290 * Multiple events and patterns may be given separated by commas. Here are
8291 * some examples:
8292 * :autocmd bufread,bufenter *.c,*.h set tw=0 smartindent noic
8293 * :autocmd bufleave * set tw=79 nosmartindent ic infercase
8294 *
8295 * :autocmd * *.c show all autocommands for *.c files.
Bram Moolenaard35f9712005-12-18 22:02:33 +00008296 *
8297 * Mostly a {group} argument can optionally appear before <event>.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008298 */
8299 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008300do_autocmd(char_u *arg, int forceit)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008301{
8302 char_u *pat;
8303 char_u *envpat = NULL;
8304 char_u *cmd;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008305 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008306 int need_free = FALSE;
8307 int nested = FALSE;
8308 int group;
8309
8310 /*
8311 * Check for a legal group name. If not, use AUGROUP_ALL.
8312 */
8313 group = au_get_grouparg(&arg);
8314 if (arg == NULL) /* out of memory */
8315 return;
8316
8317 /*
8318 * Scan over the events.
8319 * If we find an illegal name, return here, don't do anything.
8320 */
8321 pat = find_end_event(arg, group != AUGROUP_ALL);
8322 if (pat == NULL)
8323 return;
8324
8325 /*
8326 * Scan over the pattern. Put a NUL at the end.
8327 */
8328 pat = skipwhite(pat);
8329 cmd = pat;
8330 while (*cmd && (!vim_iswhite(*cmd) || cmd[-1] == '\\'))
8331 cmd++;
8332 if (*cmd)
8333 *cmd++ = NUL;
8334
8335 /* Expand environment variables in the pattern. Set 'shellslash', we want
8336 * forward slashes here. */
8337 if (vim_strchr(pat, '$') != NULL || vim_strchr(pat, '~') != NULL)
8338 {
8339#ifdef BACKSLASH_IN_FILENAME
8340 int p_ssl_save = p_ssl;
8341
8342 p_ssl = TRUE;
8343#endif
8344 envpat = expand_env_save(pat);
8345#ifdef BACKSLASH_IN_FILENAME
8346 p_ssl = p_ssl_save;
8347#endif
8348 if (envpat != NULL)
8349 pat = envpat;
8350 }
8351
8352 /*
8353 * Check for "nested" flag.
8354 */
8355 cmd = skipwhite(cmd);
8356 if (*cmd != NUL && STRNCMP(cmd, "nested", 6) == 0 && vim_iswhite(cmd[6]))
8357 {
8358 nested = TRUE;
8359 cmd = skipwhite(cmd + 6);
8360 }
8361
8362 /*
8363 * Find the start of the commands.
8364 * Expand <sfile> in it.
8365 */
8366 if (*cmd != NUL)
8367 {
8368 cmd = expand_sfile(cmd);
8369 if (cmd == NULL) /* some error */
8370 return;
8371 need_free = TRUE;
8372 }
8373
8374 /*
8375 * Print header when showing autocommands.
8376 */
8377 if (!forceit && *cmd == NUL)
8378 {
8379 /* Highlight title */
8380 MSG_PUTS_TITLE(_("\n--- Auto-Commands ---"));
8381 }
8382
8383 /*
8384 * Loop over the events.
8385 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008386 last_event = (event_T)-1; /* for listing the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008387 last_group = AUGROUP_ERROR; /* for listing the group name */
8388 if (*arg == '*' || *arg == NUL)
8389 {
Bram Moolenaar754b5602006-02-09 23:53:20 +00008390 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8391 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008392 if (do_autocmd_event(event, pat,
8393 nested, cmd, forceit, group) == FAIL)
8394 break;
8395 }
8396 else
8397 {
8398 while (*arg && !vim_iswhite(*arg))
8399 if (do_autocmd_event(event_name2nr(arg, &arg), pat,
8400 nested, cmd, forceit, group) == FAIL)
8401 break;
8402 }
8403
8404 if (need_free)
8405 vim_free(cmd);
8406 vim_free(envpat);
8407}
8408
8409/*
8410 * Find the group ID in a ":autocmd" or ":doautocmd" argument.
8411 * The "argp" argument is advanced to the following argument.
8412 *
8413 * Returns the group ID, AUGROUP_ERROR for error (out of memory).
8414 */
8415 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008416au_get_grouparg(char_u **argp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008417{
8418 char_u *group_name;
8419 char_u *p;
8420 char_u *arg = *argp;
8421 int group = AUGROUP_ALL;
8422
8423 p = skiptowhite(arg);
8424 if (p > arg)
8425 {
8426 group_name = vim_strnsave(arg, (int)(p - arg));
8427 if (group_name == NULL) /* out of memory */
8428 return AUGROUP_ERROR;
8429 group = au_find_group(group_name);
8430 if (group == AUGROUP_ERROR)
8431 group = AUGROUP_ALL; /* no match, use all groups */
8432 else
8433 *argp = skipwhite(p); /* match, skip over group name */
8434 vim_free(group_name);
8435 }
8436 return group;
8437}
8438
8439/*
8440 * do_autocmd() for one event.
8441 * If *pat == NUL do for all patterns.
8442 * If *cmd == NUL show entries.
8443 * If forceit == TRUE delete entries.
8444 * If group is not AUGROUP_ALL, only use this group.
8445 */
8446 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008447do_autocmd_event(
8448 event_T event,
8449 char_u *pat,
8450 int nested,
8451 char_u *cmd,
8452 int forceit,
8453 int group)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008454{
8455 AutoPat *ap;
8456 AutoPat **prev_ap;
8457 AutoCmd *ac;
8458 AutoCmd **prev_ac;
8459 int brace_level;
8460 char_u *endpat;
8461 int findgroup;
8462 int allgroups;
8463 int patlen;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00008464 int is_buflocal;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008465 int buflocal_nr;
8466 char_u buflocal_pat[25]; /* for "<buffer=X>" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008467
8468 if (group == AUGROUP_ALL)
8469 findgroup = current_augroup;
8470 else
8471 findgroup = group;
8472 allgroups = (group == AUGROUP_ALL && !forceit && *cmd == NUL);
8473
8474 /*
8475 * Show or delete all patterns for an event.
8476 */
8477 if (*pat == NUL)
8478 {
8479 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8480 {
8481 if (forceit) /* delete the AutoPat, if it's in the current group */
8482 {
8483 if (ap->group == findgroup)
8484 au_remove_pat(ap);
8485 }
8486 else if (group == AUGROUP_ALL || ap->group == group)
8487 show_autocmd(ap, event);
8488 }
8489 }
8490
8491 /*
8492 * Loop through all the specified patterns.
8493 */
8494 for ( ; *pat; pat = (*endpat == ',' ? endpat + 1 : endpat))
8495 {
8496 /*
8497 * Find end of the pattern.
8498 * Watch out for a comma in braces, like "*.\{obj,o\}".
8499 */
8500 brace_level = 0;
8501 for (endpat = pat; *endpat && (*endpat != ',' || brace_level
Bram Moolenaar6b9be1b2015-07-28 13:33:45 +02008502 || (endpat > pat && endpat[-1] == '\\')); ++endpat)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008503 {
8504 if (*endpat == '{')
8505 brace_level++;
8506 else if (*endpat == '}')
8507 brace_level--;
8508 }
8509 if (pat == endpat) /* ignore single comma */
8510 continue;
8511 patlen = (int)(endpat - pat);
8512
8513 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008514 * detect special <buflocal[=X]> buffer-local patterns
8515 */
8516 is_buflocal = FALSE;
8517 buflocal_nr = 0;
8518
Bram Moolenaar1e997822015-02-17 16:04:57 +01008519 if (patlen >= 8 && STRNCMP(pat, "<buffer", 7) == 0
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008520 && pat[patlen - 1] == '>')
8521 {
Bram Moolenaar1e997822015-02-17 16:04:57 +01008522 /* "<buffer...>": Error will be printed only for addition.
8523 * printing and removing will proceed silently. */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008524 is_buflocal = TRUE;
8525 if (patlen == 8)
Bram Moolenaar1e997822015-02-17 16:04:57 +01008526 /* "<buffer>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008527 buflocal_nr = curbuf->b_fnum;
8528 else if (patlen > 9 && pat[7] == '=')
8529 {
Bram Moolenaar1e997822015-02-17 16:04:57 +01008530 if (patlen == 13 && STRNICMP(pat, "<buffer=abuf>", 13) == 0)
8531 /* "<buffer=abuf>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008532 buflocal_nr = autocmd_bufnr;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008533 else if (skipdigits(pat + 8) == pat + patlen - 1)
Bram Moolenaar1e997822015-02-17 16:04:57 +01008534 /* "<buffer=123>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008535 buflocal_nr = atoi((char *)pat + 8);
8536 }
8537 }
8538
8539 if (is_buflocal)
8540 {
8541 /* normalize pat into standard "<buffer>#N" form */
8542 sprintf((char *)buflocal_pat, "<buffer=%d>", buflocal_nr);
8543 pat = buflocal_pat; /* can modify pat and patlen */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008544 patlen = (int)STRLEN(buflocal_pat); /* but not endpat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008545 }
8546
8547 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008548 * Find AutoPat entries with this pattern.
8549 */
8550 prev_ap = &first_autopat[(int)event];
8551 while ((ap = *prev_ap) != NULL)
8552 {
8553 if (ap->pat != NULL)
8554 {
8555 /* Accept a pattern when:
8556 * - a group was specified and it's that group, or a group was
8557 * not specified and it's the current group, or a group was
8558 * not specified and we are listing
8559 * - the length of the pattern matches
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008560 * - the pattern matches.
8561 * For <buffer[=X]>, this condition works because we normalize
8562 * all buffer-local patterns.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008563 */
8564 if ((allgroups || ap->group == findgroup)
8565 && ap->patlen == patlen
8566 && STRNCMP(pat, ap->pat, patlen) == 0)
8567 {
8568 /*
8569 * Remove existing autocommands.
8570 * If adding any new autocmd's for this AutoPat, don't
8571 * delete the pattern from the autopat list, append to
8572 * this list.
8573 */
8574 if (forceit)
8575 {
8576 if (*cmd != NUL && ap->next == NULL)
8577 {
8578 au_remove_cmds(ap);
8579 break;
8580 }
8581 au_remove_pat(ap);
8582 }
8583
8584 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008585 * Show autocmd's for this autopat, or buflocals <buffer=X>
Bram Moolenaar071d4272004-06-13 20:20:40 +00008586 */
8587 else if (*cmd == NUL)
8588 show_autocmd(ap, event);
8589
8590 /*
8591 * Add autocmd to this autopat, if it's the last one.
8592 */
8593 else if (ap->next == NULL)
8594 break;
8595 }
8596 }
8597 prev_ap = &ap->next;
8598 }
8599
8600 /*
8601 * Add a new command.
8602 */
8603 if (*cmd != NUL)
8604 {
8605 /*
8606 * If the pattern we want to add a command to does appear at the
8607 * end of the list (or not is not in the list at all), add the
8608 * pattern at the end of the list.
8609 */
8610 if (ap == NULL)
8611 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008612 /* refuse to add buffer-local ap if buffer number is invalid */
8613 if (is_buflocal && (buflocal_nr == 0
8614 || buflist_findnr(buflocal_nr) == NULL))
8615 {
8616 EMSGN(_("E680: <buffer=%d>: invalid buffer number "),
8617 buflocal_nr);
8618 return FAIL;
8619 }
8620
Bram Moolenaar071d4272004-06-13 20:20:40 +00008621 ap = (AutoPat *)alloc((unsigned)sizeof(AutoPat));
8622 if (ap == NULL)
8623 return FAIL;
8624 ap->pat = vim_strnsave(pat, patlen);
8625 ap->patlen = patlen;
8626 if (ap->pat == NULL)
8627 {
8628 vim_free(ap);
8629 return FAIL;
8630 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008631
8632 if (is_buflocal)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008633 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008634 ap->buflocal_nr = buflocal_nr;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008635 ap->reg_prog = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008636 }
8637 else
8638 {
Bram Moolenaar748bf032005-02-02 23:04:36 +00008639 char_u *reg_pat;
8640
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008641 ap->buflocal_nr = 0;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008642 reg_pat = file_pat_to_reg_pat(pat, endpat,
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008643 &ap->allow_dirs, TRUE);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008644 if (reg_pat != NULL)
8645 ap->reg_prog = vim_regcomp(reg_pat, RE_MAGIC);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008646 vim_free(reg_pat);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008647 if (reg_pat == NULL || ap->reg_prog == NULL)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008648 {
8649 vim_free(ap->pat);
8650 vim_free(ap);
8651 return FAIL;
8652 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008653 }
8654 ap->cmds = NULL;
8655 *prev_ap = ap;
8656 ap->next = NULL;
8657 if (group == AUGROUP_ALL)
8658 ap->group = current_augroup;
8659 else
8660 ap->group = group;
8661 }
8662
8663 /*
8664 * Add the autocmd at the end of the AutoCmd list.
8665 */
8666 prev_ac = &(ap->cmds);
8667 while ((ac = *prev_ac) != NULL)
8668 prev_ac = &ac->next;
8669 ac = (AutoCmd *)alloc((unsigned)sizeof(AutoCmd));
8670 if (ac == NULL)
8671 return FAIL;
8672 ac->cmd = vim_strsave(cmd);
8673#ifdef FEAT_EVAL
8674 ac->scriptID = current_SID;
8675#endif
8676 if (ac->cmd == NULL)
8677 {
8678 vim_free(ac);
8679 return FAIL;
8680 }
8681 ac->next = NULL;
8682 *prev_ac = ac;
8683 ac->nested = nested;
8684 }
8685 }
8686
8687 au_cleanup(); /* may really delete removed patterns/commands now */
8688 return OK;
8689}
8690
8691/*
8692 * Implementation of ":doautocmd [group] event [fname]".
8693 * Return OK for success, FAIL for failure;
8694 */
8695 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008696do_doautocmd(
8697 char_u *arg,
Bram Moolenaar1610d052016-06-09 22:53:01 +02008698 int do_msg, /* give message for no matching autocmds? */
8699 int *did_something)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008700{
8701 char_u *fname;
8702 int nothing_done = TRUE;
8703 int group;
8704
Bram Moolenaar1610d052016-06-09 22:53:01 +02008705 if (did_something != NULL)
Bram Moolenaar76ae22f2016-06-13 20:00:29 +02008706 *did_something = FALSE;
Bram Moolenaar1610d052016-06-09 22:53:01 +02008707
Bram Moolenaar071d4272004-06-13 20:20:40 +00008708 /*
8709 * Check for a legal group name. If not, use AUGROUP_ALL.
8710 */
8711 group = au_get_grouparg(&arg);
8712 if (arg == NULL) /* out of memory */
8713 return FAIL;
8714
8715 if (*arg == '*')
8716 {
8717 EMSG(_("E217: Can't execute autocommands for ALL events"));
8718 return FAIL;
8719 }
8720
8721 /*
8722 * Scan over the events.
8723 * If we find an illegal name, return here, don't do anything.
8724 */
8725 fname = find_end_event(arg, group != AUGROUP_ALL);
8726 if (fname == NULL)
8727 return FAIL;
8728
8729 fname = skipwhite(fname);
8730
8731 /*
8732 * Loop over the events.
8733 */
8734 while (*arg && !vim_iswhite(*arg))
8735 if (apply_autocmds_group(event_name2nr(arg, &arg),
8736 fname, NULL, TRUE, group, curbuf, NULL))
8737 nothing_done = FALSE;
8738
8739 if (nothing_done && do_msg)
8740 MSG(_("No matching autocommands"));
Bram Moolenaar1610d052016-06-09 22:53:01 +02008741 if (did_something != NULL)
8742 *did_something = !nothing_done;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008743
8744#ifdef FEAT_EVAL
8745 return aborting() ? FAIL : OK;
8746#else
8747 return OK;
8748#endif
8749}
8750
8751/*
8752 * ":doautoall": execute autocommands for each loaded buffer.
8753 */
8754 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008755ex_doautoall(exarg_T *eap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008756{
8757 int retval;
8758 aco_save_T aco;
8759 buf_T *buf;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008760 bufref_T bufref;
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008761 char_u *arg = eap->arg;
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008762 int call_do_modelines = check_nomodeline(&arg);
Bram Moolenaar1610d052016-06-09 22:53:01 +02008763 int did_aucmd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008764
8765 /*
8766 * This is a bit tricky: For some commands curwin->w_buffer needs to be
8767 * equal to curbuf, but for some buffers there may not be a window.
8768 * So we change the buffer for the current window for a moment. This
8769 * gives problems when the autocommands make changes to the list of
8770 * buffers or windows...
8771 */
8772 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8773 {
Bram Moolenaar3a847972008-07-08 09:36:58 +00008774 if (buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008775 {
8776 /* find a window for this buffer and save some values */
8777 aucmd_prepbuf(&aco, buf);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008778 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008779
8780 /* execute the autocommands for this buffer */
Bram Moolenaar1610d052016-06-09 22:53:01 +02008781 retval = do_doautocmd(arg, FALSE, &did_aucmd);
Bram Moolenaareeefcc72007-05-01 21:21:21 +00008782
Bram Moolenaar1610d052016-06-09 22:53:01 +02008783 if (call_do_modelines && did_aucmd)
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008784 {
8785 /* Execute the modeline settings, but don't set window-local
8786 * options if we are using the current window for another
8787 * buffer. */
8788 do_modelines(curwin == aucmd_win ? OPT_NOWIN : 0);
8789 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008790
8791 /* restore the current window */
8792 aucmd_restbuf(&aco);
8793
8794 /* stop if there is some error or buffer was deleted */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008795 if (retval == FAIL || !bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008796 break;
8797 }
8798 }
8799
8800 check_cursor(); /* just in case lines got deleted */
8801}
8802
8803/*
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008804 * Check *argp for <nomodeline>. When it is present return FALSE, otherwise
8805 * return TRUE and advance *argp to after it.
8806 * Thus return TRUE when do_modelines() should be called.
8807 */
8808 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008809check_nomodeline(char_u **argp)
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008810{
8811 if (STRNCMP(*argp, "<nomodeline>", 12) == 0)
8812 {
8813 *argp = skipwhite(*argp + 12);
8814 return FALSE;
8815 }
8816 return TRUE;
8817}
8818
8819/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008820 * Prepare for executing autocommands for (hidden) buffer "buf".
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008821 * Search for a visible window containing the current buffer. If there isn't
8822 * one then use "aucmd_win".
Bram Moolenaar071d4272004-06-13 20:20:40 +00008823 * Set "curbuf" and "curwin" to match "buf".
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00008824 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008825 */
8826 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008827aucmd_prepbuf(
8828 aco_save_T *aco, /* structure to save values in */
8829 buf_T *buf) /* new curbuf */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008830{
8831 win_T *win;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008832#ifdef FEAT_WINDOWS
8833 int save_ea;
8834#endif
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008835#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008836 int save_acd;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008837#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008838
8839 /* Find a window that is for the new buffer */
8840 if (buf == curbuf) /* be quick when buf is curbuf */
8841 win = curwin;
8842 else
8843#ifdef FEAT_WINDOWS
8844 for (win = firstwin; win != NULL; win = win->w_next)
8845 if (win->w_buffer == buf)
8846 break;
8847#else
8848 win = NULL;
8849#endif
8850
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008851 /* Allocate "aucmd_win" when needed. If this fails (out of memory) fall
8852 * back to using the current window. */
8853 if (win == NULL && aucmd_win == NULL)
8854 {
8855 win_alloc_aucmd_win();
8856 if (aucmd_win == NULL)
8857 win = curwin;
8858 }
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008859 if (win == NULL && aucmd_win_used)
8860 /* Strange recursive autocommand, fall back to using the current
8861 * window. Expect a few side effects... */
8862 win = curwin;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008863
8864 aco->save_curwin = curwin;
8865 aco->save_curbuf = curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008866 if (win != NULL)
8867 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008868 /* There is a window for "buf" in the current tab page, make it the
8869 * curwin. This is preferred, it has the least side effects (esp. if
8870 * "buf" is curbuf). */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008871 aco->use_aucmd_win = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008872 curwin = win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008873 }
8874 else
8875 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008876 /* There is no window for "buf", use "aucmd_win". To minimize the side
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02008877 * effects, insert it in the current tab page.
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008878 * Anything related to a window (e.g., setting folds) may have
8879 * unexpected results. */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008880 aco->use_aucmd_win = TRUE;
8881 aucmd_win_used = TRUE;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008882 aucmd_win->w_buffer = buf;
Bram Moolenaarcdddaa42010-06-07 23:07:44 +02008883 aucmd_win->w_s = &buf->b_s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008884 ++buf->b_nwindows;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008885 win_init_empty(aucmd_win); /* set cursor and topline to safe values */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008886
8887 /* Make sure w_localdir and globaldir are NULL to avoid a chdir() in
8888 * win_enter_ext(). */
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008889 vim_free(aucmd_win->w_localdir);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008890 aucmd_win->w_localdir = NULL;
8891 aco->globaldir = globaldir;
8892 globaldir = NULL;
8893
Bram Moolenaar071d4272004-06-13 20:20:40 +00008894
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008895#ifdef FEAT_WINDOWS
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008896 /* Split the current window, put the aucmd_win in the upper half.
8897 * We don't want the BufEnter or WinEnter autocommands. */
8898 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008899 make_snapshot(SNAP_AUCMD_IDX);
8900 save_ea = p_ea;
8901 p_ea = FALSE;
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008902
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008903# ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008904 /* Prevent chdir() call in win_enter_ext(), through do_autochdir(). */
8905 save_acd = p_acd;
8906 p_acd = FALSE;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008907# endif
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008908
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008909 (void)win_split_ins(0, WSP_TOP, aucmd_win, 0);
8910 (void)win_comp_pos(); /* recompute window positions */
8911 p_ea = save_ea;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008912# ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008913 p_acd = save_acd;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008914# endif
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008915 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008916#endif
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008917 curwin = aucmd_win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008918 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008919 curbuf = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008920 aco->new_curwin = curwin;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008921 set_bufref(&aco->new_curbuf, curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008922}
8923
8924/*
8925 * Cleanup after executing autocommands for a (hidden) buffer.
8926 * Restore the window as it was (if possible).
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00008927 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008928 */
8929 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008930aucmd_restbuf(
8931 aco_save_T *aco) /* structure holding saved values */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008932{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008933#ifdef FEAT_WINDOWS
8934 int dummy;
8935#endif
8936
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008937 if (aco->use_aucmd_win)
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008938 {
8939 --curbuf->b_nwindows;
8940#ifdef FEAT_WINDOWS
8941 /* Find "aucmd_win", it can't be closed, but it may be in another tab
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008942 * page. Do not trigger autocommands here. */
8943 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008944 if (curwin != aucmd_win)
8945 {
8946 tabpage_T *tp;
8947 win_T *wp;
8948
8949 FOR_ALL_TAB_WINDOWS(tp, wp)
8950 {
8951 if (wp == aucmd_win)
8952 {
8953 if (tp != curtab)
Bram Moolenaar49e649f2013-05-06 04:50:35 +02008954 goto_tabpage_tp(tp, TRUE, TRUE);
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008955 win_goto(aucmd_win);
Bram Moolenaar28f29082012-02-11 23:45:37 +01008956 goto win_found;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008957 }
8958 }
8959 }
Bram Moolenaar28f29082012-02-11 23:45:37 +01008960win_found:
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008961
8962 /* Remove the window and frame from the tree of frames. */
8963 (void)winframe_remove(curwin, &dummy, NULL);
8964 win_remove(curwin, NULL);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008965 aucmd_win_used = FALSE;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008966 last_status(FALSE); /* may need to remove last status line */
8967 restore_snapshot(SNAP_AUCMD_IDX, FALSE);
8968 (void)win_comp_pos(); /* recompute window positions */
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008969 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008970
8971 if (win_valid(aco->save_curwin))
8972 curwin = aco->save_curwin;
8973 else
8974 /* Hmm, original window disappeared. Just use the first one. */
8975 curwin = firstwin;
8976# ifdef FEAT_EVAL
Bram Moolenaar429fa852013-04-15 12:27:36 +02008977 vars_clear(&aucmd_win->w_vars->dv_hashtab); /* free all w: variables */
8978 hash_init(&aucmd_win->w_vars->dv_hashtab); /* re-use the hashtab */
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008979# endif
8980#else
8981 curwin = aco->save_curwin;
8982#endif
8983 curbuf = curwin->w_buffer;
8984
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008985 vim_free(globaldir);
8986 globaldir = aco->globaldir;
8987
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008988 /* the buffer contents may have changed */
8989 check_cursor();
8990 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
8991 {
8992 curwin->w_topline = curbuf->b_ml.ml_line_count;
8993#ifdef FEAT_DIFF
8994 curwin->w_topfill = 0;
8995#endif
8996 }
8997#if defined(FEAT_GUI)
8998 /* Hide the scrollbars from the aucmd_win and update. */
8999 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_LEFT], FALSE);
9000 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_RIGHT], FALSE);
9001 gui_may_update_scrollbars();
9002#endif
9003 }
9004 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00009005 {
9006 /* restore curwin */
9007#ifdef FEAT_WINDOWS
9008 if (win_valid(aco->save_curwin))
9009#endif
9010 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009011 /* Restore the buffer which was previously edited by curwin, if
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009012 * it was changed, we are still the same window and the buffer is
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009013 * valid. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009014 if (curwin == aco->new_curwin
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009015 && curbuf != aco->new_curbuf.br_buf
9016 && bufref_valid(&aco->new_curbuf)
9017 && aco->new_curbuf.br_buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009018 {
Bram Moolenaar7da9c372012-04-30 17:04:52 +02009019# if defined(FEAT_SYN_HL) || defined(FEAT_SPELL)
9020 if (curwin->w_s == &curbuf->b_s)
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009021 curwin->w_s = &aco->new_curbuf.br_buf->b_s;
Bram Moolenaar7da9c372012-04-30 17:04:52 +02009022# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009023 --curbuf->b_nwindows;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009024 curbuf = aco->new_curbuf.br_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009025 curwin->w_buffer = curbuf;
9026 ++curbuf->b_nwindows;
9027 }
9028
9029 curwin = aco->save_curwin;
9030 curbuf = curwin->w_buffer;
Bram Moolenaar371932a2014-09-09 16:59:38 +02009031 /* In case the autocommand move the cursor to a position that that
9032 * not exist in curbuf. */
9033 check_cursor();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009034 }
9035 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009036}
9037
9038static int autocmd_nested = FALSE;
9039
9040/*
9041 * Execute autocommands for "event" and file name "fname".
9042 * Return TRUE if some commands were executed.
9043 */
9044 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009045apply_autocmds(
9046 event_T event,
9047 char_u *fname, /* NULL or empty means use actual file name */
9048 char_u *fname_io, /* fname to use for <afile> on cmdline */
9049 int force, /* when TRUE, ignore autocmd_busy */
9050 buf_T *buf) /* buffer for <abuf> */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009051{
9052 return apply_autocmds_group(event, fname, fname_io, force,
9053 AUGROUP_ALL, buf, NULL);
9054}
9055
9056/*
9057 * Like apply_autocmds(), but with extra "eap" argument. This takes care of
9058 * setting v:filearg.
9059 */
9060 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009061apply_autocmds_exarg(
9062 event_T event,
9063 char_u *fname,
9064 char_u *fname_io,
9065 int force,
9066 buf_T *buf,
9067 exarg_T *eap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009068{
9069 return apply_autocmds_group(event, fname, fname_io, force,
9070 AUGROUP_ALL, buf, eap);
9071}
9072
9073/*
9074 * Like apply_autocmds(), but handles the caller's retval. If the script
9075 * processing is being aborted or if retval is FAIL when inside a try
9076 * conditional, no autocommands are executed. If otherwise the autocommands
9077 * cause the script to be aborted, retval is set to FAIL.
9078 */
9079 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009080apply_autocmds_retval(
9081 event_T event,
9082 char_u *fname, /* NULL or empty means use actual file name */
9083 char_u *fname_io, /* fname to use for <afile> on cmdline */
9084 int force, /* when TRUE, ignore autocmd_busy */
9085 buf_T *buf, /* buffer for <abuf> */
9086 int *retval) /* pointer to caller's retval */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009087{
9088 int did_cmd;
9089
Bram Moolenaar1e015462005-09-25 22:16:38 +00009090#ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00009091 if (should_abort(*retval))
9092 return FALSE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00009093#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009094
9095 did_cmd = apply_autocmds_group(event, fname, fname_io, force,
9096 AUGROUP_ALL, buf, NULL);
Bram Moolenaar1e015462005-09-25 22:16:38 +00009097 if (did_cmd
9098#ifdef FEAT_EVAL
9099 && aborting()
9100#endif
9101 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00009102 *retval = FAIL;
9103 return did_cmd;
9104}
9105
Bram Moolenaard35f9712005-12-18 22:02:33 +00009106/*
9107 * Return TRUE when there is a CursorHold autocommand defined.
9108 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009109 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009110has_cursorhold(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009111{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009112 return (first_autopat[(int)(get_real_state() == NORMAL_BUSY
9113 ? EVENT_CURSORHOLD : EVENT_CURSORHOLDI)] != NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009114}
Bram Moolenaard35f9712005-12-18 22:02:33 +00009115
9116/*
9117 * Return TRUE if the CursorHold event can be triggered.
9118 */
9119 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009120trigger_cursorhold(void)
Bram Moolenaard35f9712005-12-18 22:02:33 +00009121{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009122 int state;
9123
Bram Moolenaar05334432011-07-20 18:29:39 +02009124 if (!did_cursorhold
9125 && has_cursorhold()
9126 && !Recording
9127 && typebuf.tb_len == 0
Bram Moolenaard29a9ee2006-09-14 09:07:34 +00009128#ifdef FEAT_INS_EXPAND
9129 && !ins_compl_active()
9130#endif
9131 )
Bram Moolenaar754b5602006-02-09 23:53:20 +00009132 {
9133 state = get_real_state();
9134 if (state == NORMAL_BUSY || (state & INSERT) != 0)
9135 return TRUE;
9136 }
9137 return FALSE;
Bram Moolenaard35f9712005-12-18 22:02:33 +00009138}
Bram Moolenaar754b5602006-02-09 23:53:20 +00009139
9140/*
9141 * Return TRUE when there is a CursorMoved autocommand defined.
9142 */
9143 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009144has_cursormoved(void)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009145{
9146 return (first_autopat[(int)EVENT_CURSORMOVED] != NULL);
9147}
9148
9149/*
9150 * Return TRUE when there is a CursorMovedI autocommand defined.
9151 */
9152 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009153has_cursormovedI(void)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009154{
9155 return (first_autopat[(int)EVENT_CURSORMOVEDI] != NULL);
9156}
Bram Moolenaar071d4272004-06-13 20:20:40 +00009157
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009158/*
Bram Moolenaar186628f2013-03-19 13:33:23 +01009159 * Return TRUE when there is a TextChanged autocommand defined.
9160 */
9161 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009162has_textchanged(void)
Bram Moolenaar186628f2013-03-19 13:33:23 +01009163{
9164 return (first_autopat[(int)EVENT_TEXTCHANGED] != NULL);
9165}
9166
9167/*
9168 * Return TRUE when there is a TextChangedI autocommand defined.
9169 */
9170 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009171has_textchangedI(void)
Bram Moolenaar186628f2013-03-19 13:33:23 +01009172{
9173 return (first_autopat[(int)EVENT_TEXTCHANGEDI] != NULL);
9174}
9175
9176/*
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009177 * Return TRUE when there is an InsertCharPre autocommand defined.
9178 */
9179 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009180has_insertcharpre(void)
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009181{
9182 return (first_autopat[(int)EVENT_INSERTCHARPRE] != NULL);
9183}
9184
Bram Moolenaard5005162014-08-22 23:05:54 +02009185/*
9186 * Return TRUE when there is an CmdUndefined autocommand defined.
9187 */
9188 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009189has_cmdundefined(void)
Bram Moolenaard5005162014-08-22 23:05:54 +02009190{
9191 return (first_autopat[(int)EVENT_CMDUNDEFINED] != NULL);
9192}
9193
9194/*
9195 * Return TRUE when there is an FuncUndefined autocommand defined.
9196 */
9197 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009198has_funcundefined(void)
Bram Moolenaard5005162014-08-22 23:05:54 +02009199{
9200 return (first_autopat[(int)EVENT_FUNCUNDEFINED] != NULL);
9201}
9202
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009203/*
9204 * Execute autocommands for "event" and file name "fname".
9205 * Return TRUE if some commands were executed.
9206 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009207 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009208apply_autocmds_group(
9209 event_T event,
9210 char_u *fname, /* NULL or empty means use actual file name */
9211 char_u *fname_io, /* fname to use for <afile> on cmdline, NULL means
Bram Moolenaar071d4272004-06-13 20:20:40 +00009212 use fname */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009213 int force, /* when TRUE, ignore autocmd_busy */
9214 int group, /* group ID, or AUGROUP_ALL */
9215 buf_T *buf, /* buffer for <abuf> */
9216 exarg_T *eap) /* command arguments */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009217{
9218 char_u *sfname = NULL; /* short file name */
9219 char_u *tail;
9220 int save_changed;
9221 buf_T *old_curbuf;
9222 int retval = FALSE;
9223 char_u *save_sourcing_name;
9224 linenr_T save_sourcing_lnum;
9225 char_u *save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009226 int save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009227 int save_autocmd_bufnr;
9228 char_u *save_autocmd_match;
9229 int save_autocmd_busy;
9230 int save_autocmd_nested;
9231 static int nesting = 0;
9232 AutoPatCmd patcmd;
9233 AutoPat *ap;
9234#ifdef FEAT_EVAL
9235 scid_T save_current_SID;
9236 void *save_funccalp;
9237 char_u *save_cmdarg;
9238 long save_cmdbang;
9239#endif
9240 static int filechangeshell_busy = FALSE;
Bram Moolenaar05159a02005-02-26 23:04:13 +00009241#ifdef FEAT_PROFILE
9242 proftime_T wait_time;
9243#endif
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009244 int did_save_redobuff = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009245
9246 /*
9247 * Quickly return if there are no autocommands for this event or
9248 * autocommands are blocked.
9249 */
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009250 if (first_autopat[(int)event] == NULL || autocmd_blocked > 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009251 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009252
9253 /*
9254 * When autocommands are busy, new autocommands are only executed when
9255 * explicitly enabled with the "nested" flag.
9256 */
9257 if (autocmd_busy && !(force || autocmd_nested))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009258 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009259
9260#ifdef FEAT_EVAL
9261 /*
Bram Moolenaar7263a772007-05-10 17:35:54 +00009262 * Quickly return when immediately aborting on error, or when an interrupt
Bram Moolenaar071d4272004-06-13 20:20:40 +00009263 * occurred or an exception was thrown but not caught.
9264 */
9265 if (aborting())
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009266 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009267#endif
9268
9269 /*
9270 * FileChangedShell never nests, because it can create an endless loop.
9271 */
Bram Moolenaar56718732006-03-15 22:53:57 +00009272 if (filechangeshell_busy && (event == EVENT_FILECHANGEDSHELL
9273 || event == EVENT_FILECHANGEDSHELLPOST))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009274 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009275
9276 /*
9277 * Ignore events in 'eventignore'.
9278 */
9279 if (event_ignored(event))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009280 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009281
9282 /*
9283 * Allow nesting of autocommands, but restrict the depth, because it's
9284 * possible to create an endless loop.
9285 */
9286 if (nesting == 10)
9287 {
9288 EMSG(_("E218: autocommand nesting too deep"));
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009289 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009290 }
9291
9292 /*
9293 * Check if these autocommands are disabled. Used when doing ":all" or
9294 * ":ball".
9295 */
9296 if ( (autocmd_no_enter
9297 && (event == EVENT_WINENTER || event == EVENT_BUFENTER))
9298 || (autocmd_no_leave
9299 && (event == EVENT_WINLEAVE || event == EVENT_BUFLEAVE)))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009300 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009301
9302 /*
9303 * Save the autocmd_* variables and info about the current buffer.
9304 */
9305 save_autocmd_fname = autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009306 save_autocmd_fname_full = autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009307 save_autocmd_bufnr = autocmd_bufnr;
9308 save_autocmd_match = autocmd_match;
9309 save_autocmd_busy = autocmd_busy;
9310 save_autocmd_nested = autocmd_nested;
9311 save_changed = curbuf->b_changed;
9312 old_curbuf = curbuf;
9313
9314 /*
9315 * Set the file name to be used for <afile>.
Bram Moolenaara0174af2008-01-02 20:08:25 +00009316 * Make a copy to avoid that changing a buffer name or directory makes it
9317 * invalid.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009318 */
9319 if (fname_io == NULL)
9320 {
Bram Moolenaar53744302015-07-17 17:38:22 +02009321 if (event == EVENT_COLORSCHEME || event == EVENT_OPTIONSET)
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009322 autocmd_fname = NULL;
9323 else if (fname != NULL && *fname != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009324 autocmd_fname = fname;
9325 else if (buf != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009326 autocmd_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009327 else
9328 autocmd_fname = NULL;
9329 }
9330 else
9331 autocmd_fname = fname_io;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009332 if (autocmd_fname != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009333 autocmd_fname = vim_strsave(autocmd_fname);
9334 autocmd_fname_full = FALSE; /* call FullName_save() later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009335
9336 /*
9337 * Set the buffer number to be used for <abuf>.
9338 */
9339 if (buf == NULL)
9340 autocmd_bufnr = 0;
9341 else
9342 autocmd_bufnr = buf->b_fnum;
9343
9344 /*
9345 * When the file name is NULL or empty, use the file name of buffer "buf".
9346 * Always use the full path of the file name to match with, in case
9347 * "allow_dirs" is set.
9348 */
9349 if (fname == NULL || *fname == NUL)
9350 {
9351 if (buf == NULL)
9352 fname = NULL;
9353 else
9354 {
9355#ifdef FEAT_SYN_HL
9356 if (event == EVENT_SYNTAX)
9357 fname = buf->b_p_syn;
9358 else
9359#endif
9360 if (event == EVENT_FILETYPE)
9361 fname = buf->b_p_ft;
9362 else
9363 {
9364 if (buf->b_sfname != NULL)
9365 sfname = vim_strsave(buf->b_sfname);
9366 fname = buf->b_ffname;
9367 }
9368 }
9369 if (fname == NULL)
9370 fname = (char_u *)"";
9371 fname = vim_strsave(fname); /* make a copy, so we can change it */
9372 }
9373 else
9374 {
9375 sfname = vim_strsave(fname);
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009376 /* Don't try expanding FileType, Syntax, FuncUndefined, WindowID,
9377 * ColorScheme or QuickFixCmd* */
Bram Moolenaar7c626922005-02-07 22:01:03 +00009378 if (event == EVENT_FILETYPE
9379 || event == EVENT_SYNTAX
Bram Moolenaar5135d462009-04-29 16:03:38 +00009380 || event == EVENT_FUNCUNDEFINED
Bram Moolenaar7c626922005-02-07 22:01:03 +00009381 || event == EVENT_REMOTEREPLY
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00009382 || event == EVENT_SPELLFILEMISSING
Bram Moolenaar7c626922005-02-07 22:01:03 +00009383 || event == EVENT_QUICKFIXCMDPRE
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009384 || event == EVENT_COLORSCHEME
Bram Moolenaar53744302015-07-17 17:38:22 +02009385 || event == EVENT_OPTIONSET
Bram Moolenaar7c626922005-02-07 22:01:03 +00009386 || event == EVENT_QUICKFIXCMDPOST)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009387 fname = vim_strsave(fname);
9388 else
9389 fname = FullName_save(fname, FALSE);
9390 }
9391 if (fname == NULL) /* out of memory */
9392 {
9393 vim_free(sfname);
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009394 retval = FALSE;
9395 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009396 }
9397
9398#ifdef BACKSLASH_IN_FILENAME
9399 /*
9400 * Replace all backslashes with forward slashes. This makes the
9401 * autocommand patterns portable between Unix and MS-DOS.
9402 */
9403 if (sfname != NULL)
9404 forward_slash(sfname);
9405 forward_slash(fname);
9406#endif
9407
9408#ifdef VMS
9409 /* remove version for correct match */
9410 if (sfname != NULL)
9411 vms_remove_version(sfname);
9412 vms_remove_version(fname);
9413#endif
9414
9415 /*
9416 * Set the name to be used for <amatch>.
9417 */
9418 autocmd_match = fname;
9419
9420
9421 /* Don't redraw while doing auto commands. */
9422 ++RedrawingDisabled;
9423 save_sourcing_name = sourcing_name;
9424 sourcing_name = NULL; /* don't free this one */
9425 save_sourcing_lnum = sourcing_lnum;
9426 sourcing_lnum = 0; /* no line number here */
9427
9428#ifdef FEAT_EVAL
9429 save_current_SID = current_SID;
9430
Bram Moolenaar05159a02005-02-26 23:04:13 +00009431# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009432 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009433 prof_child_enter(&wait_time); /* doesn't count for the caller itself */
9434# endif
9435
Bram Moolenaar071d4272004-06-13 20:20:40 +00009436 /* Don't use local function variables, if called from a function */
9437 save_funccalp = save_funccal();
9438#endif
9439
9440 /*
9441 * When starting to execute autocommands, save the search patterns.
9442 */
9443 if (!autocmd_busy)
9444 {
9445 save_search_patterns();
Bram Moolenaar20ad69c2015-12-03 13:52:52 +01009446#ifdef FEAT_INS_EXPAND
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009447 if (!ins_compl_active())
Bram Moolenaar20ad69c2015-12-03 13:52:52 +01009448#endif
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009449 {
9450 saveRedobuff();
9451 did_save_redobuff = TRUE;
9452 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009453 did_filetype = keep_filetype;
9454 }
9455
9456 /*
9457 * Note that we are applying autocmds. Some commands need to know.
9458 */
9459 autocmd_busy = TRUE;
9460 filechangeshell_busy = (event == EVENT_FILECHANGEDSHELL);
9461 ++nesting; /* see matching decrement below */
9462
9463 /* Remember that FileType was triggered. Used for did_filetype(). */
9464 if (event == EVENT_FILETYPE)
9465 did_filetype = TRUE;
9466
9467 tail = gettail(fname);
9468
9469 /* Find first autocommand that matches */
9470 patcmd.curpat = first_autopat[(int)event];
9471 patcmd.nextcmd = NULL;
9472 patcmd.group = group;
9473 patcmd.fname = fname;
9474 patcmd.sfname = sfname;
9475 patcmd.tail = tail;
9476 patcmd.event = event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009477 patcmd.arg_bufnr = autocmd_bufnr;
9478 patcmd.next = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009479 auto_next_pat(&patcmd, FALSE);
9480
9481 /* found one, start executing the autocommands */
9482 if (patcmd.curpat != NULL)
9483 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009484 /* add to active_apc_list */
9485 patcmd.next = active_apc_list;
9486 active_apc_list = &patcmd;
9487
Bram Moolenaar071d4272004-06-13 20:20:40 +00009488#ifdef FEAT_EVAL
9489 /* set v:cmdarg (only when there is a matching pattern) */
Bram Moolenaar22fcfad2016-07-01 18:17:26 +02009490 save_cmdbang = (long)get_vim_var_nr(VV_CMDBANG);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009491 if (eap != NULL)
9492 {
9493 save_cmdarg = set_cmdarg(eap, NULL);
9494 set_vim_var_nr(VV_CMDBANG, (long)eap->forceit);
9495 }
9496 else
9497 save_cmdarg = NULL; /* avoid gcc warning */
9498#endif
9499 retval = TRUE;
9500 /* mark the last pattern, to avoid an endless loop when more patterns
9501 * are added when executing autocommands */
9502 for (ap = patcmd.curpat; ap->next != NULL; ap = ap->next)
9503 ap->last = FALSE;
9504 ap->last = TRUE;
9505 check_lnums(TRUE); /* make sure cursor and topline are valid */
9506 do_cmdline(NULL, getnextac, (void *)&patcmd,
9507 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
9508#ifdef FEAT_EVAL
9509 if (eap != NULL)
9510 {
9511 (void)set_cmdarg(NULL, save_cmdarg);
9512 set_vim_var_nr(VV_CMDBANG, save_cmdbang);
9513 }
9514#endif
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009515 /* delete from active_apc_list */
9516 if (active_apc_list == &patcmd) /* just in case */
9517 active_apc_list = patcmd.next;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009518 }
9519
9520 --RedrawingDisabled;
9521 autocmd_busy = save_autocmd_busy;
9522 filechangeshell_busy = FALSE;
9523 autocmd_nested = save_autocmd_nested;
9524 vim_free(sourcing_name);
9525 sourcing_name = save_sourcing_name;
9526 sourcing_lnum = save_sourcing_lnum;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009527 vim_free(autocmd_fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009528 autocmd_fname = save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009529 autocmd_fname_full = save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009530 autocmd_bufnr = save_autocmd_bufnr;
9531 autocmd_match = save_autocmd_match;
9532#ifdef FEAT_EVAL
9533 current_SID = save_current_SID;
9534 restore_funccal(save_funccalp);
Bram Moolenaar05159a02005-02-26 23:04:13 +00009535# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009536 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009537 prof_child_exit(&wait_time);
9538# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009539#endif
9540 vim_free(fname);
9541 vim_free(sfname);
9542 --nesting; /* see matching increment above */
9543
9544 /*
9545 * When stopping to execute autocommands, restore the search patterns and
Bram Moolenaar3be85852014-06-12 14:01:31 +02009546 * the redo buffer. Free any buffers in the au_pending_free_buf list and
9547 * free any windows in the au_pending_free_win list.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009548 */
9549 if (!autocmd_busy)
9550 {
9551 restore_search_patterns();
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009552 if (did_save_redobuff)
9553 restoreRedobuff();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009554 did_filetype = FALSE;
Bram Moolenaar4c7ab1b2014-04-06 20:45:43 +02009555 while (au_pending_free_buf != NULL)
9556 {
9557 buf_T *b = au_pending_free_buf->b_next;
9558 vim_free(au_pending_free_buf);
9559 au_pending_free_buf = b;
9560 }
Bram Moolenaar3be85852014-06-12 14:01:31 +02009561 while (au_pending_free_win != NULL)
9562 {
9563 win_T *w = au_pending_free_win->w_next;
9564 vim_free(au_pending_free_win);
9565 au_pending_free_win = w;
9566 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009567 }
9568
9569 /*
9570 * Some events don't set or reset the Changed flag.
9571 * Check if still in the same buffer!
9572 */
9573 if (curbuf == old_curbuf
9574 && (event == EVENT_BUFREADPOST
9575 || event == EVENT_BUFWRITEPOST
9576 || event == EVENT_FILEAPPENDPOST
9577 || event == EVENT_VIMLEAVE
9578 || event == EVENT_VIMLEAVEPRE))
9579 {
9580#ifdef FEAT_TITLE
9581 if (curbuf->b_changed != save_changed)
9582 need_maketitle = TRUE;
9583#endif
9584 curbuf->b_changed = save_changed;
9585 }
9586
9587 au_cleanup(); /* may really delete removed patterns/commands now */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009588
9589BYPASS_AU:
9590 /* When wiping out a buffer make sure all its buffer-local autocommands
9591 * are deleted. */
9592 if (event == EVENT_BUFWIPEOUT && buf != NULL)
9593 aubuflocal_remove(buf);
9594
Bram Moolenaarc3691332016-04-20 12:49:49 +02009595 if (retval == OK && event == EVENT_FILETYPE)
9596 au_did_filetype = TRUE;
9597
Bram Moolenaar071d4272004-06-13 20:20:40 +00009598 return retval;
9599}
9600
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009601# ifdef FEAT_EVAL
9602static char_u *old_termresponse = NULL;
9603# endif
9604
9605/*
9606 * Block triggering autocommands until unblock_autocmd() is called.
9607 * Can be used recursively, so long as it's symmetric.
9608 */
9609 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009610block_autocmds(void)
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009611{
9612# ifdef FEAT_EVAL
9613 /* Remember the value of v:termresponse. */
9614 if (autocmd_blocked == 0)
9615 old_termresponse = get_vim_var_str(VV_TERMRESPONSE);
9616# endif
9617 ++autocmd_blocked;
9618}
9619
9620 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009621unblock_autocmds(void)
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009622{
9623 --autocmd_blocked;
9624
9625# ifdef FEAT_EVAL
9626 /* When v:termresponse was set while autocommands were blocked, trigger
9627 * the autocommands now. Esp. useful when executing a shell command
9628 * during startup (vimdiff). */
9629 if (autocmd_blocked == 0
9630 && get_vim_var_str(VV_TERMRESPONSE) != old_termresponse)
9631 apply_autocmds(EVENT_TERMRESPONSE, NULL, NULL, FALSE, curbuf);
9632# endif
9633}
9634
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009635 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009636is_autocmd_blocked(void)
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009637{
9638 return autocmd_blocked != 0;
9639}
9640
Bram Moolenaar071d4272004-06-13 20:20:40 +00009641/*
9642 * Find next autocommand pattern that matches.
9643 */
9644 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009645auto_next_pat(
9646 AutoPatCmd *apc,
9647 int stop_at_last) /* stop when 'last' flag is set */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009648{
9649 AutoPat *ap;
9650 AutoCmd *cp;
9651 char_u *name;
9652 char *s;
9653
9654 vim_free(sourcing_name);
9655 sourcing_name = NULL;
9656
9657 for (ap = apc->curpat; ap != NULL && !got_int; ap = ap->next)
9658 {
9659 apc->curpat = NULL;
9660
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009661 /* Only use a pattern when it has not been removed, has commands and
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009662 * the group matches. For buffer-local autocommands only check the
9663 * buffer number. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009664 if (ap->pat != NULL && ap->cmds != NULL
9665 && (apc->group == AUGROUP_ALL || apc->group == ap->group))
9666 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009667 /* execution-condition */
9668 if (ap->buflocal_nr == 0
Bram Moolenaardffa5b82014-11-19 16:38:07 +01009669 ? (match_file_pat(NULL, &ap->reg_prog, apc->fname,
Bram Moolenaar748bf032005-02-02 23:04:36 +00009670 apc->sfname, apc->tail, ap->allow_dirs))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009671 : ap->buflocal_nr == apc->arg_bufnr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009672 {
9673 name = event_nr2name(apc->event);
9674 s = _("%s Auto commands for \"%s\"");
9675 sourcing_name = alloc((unsigned)(STRLEN(s)
9676 + STRLEN(name) + ap->patlen + 1));
9677 if (sourcing_name != NULL)
9678 {
9679 sprintf((char *)sourcing_name, s,
9680 (char *)name, (char *)ap->pat);
9681 if (p_verbose >= 8)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009682 {
9683 verbose_enter();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009684 smsg((char_u *)_("Executing %s"), sourcing_name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009685 verbose_leave();
9686 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009687 }
9688
9689 apc->curpat = ap;
9690 apc->nextcmd = ap->cmds;
9691 /* mark last command */
9692 for (cp = ap->cmds; cp->next != NULL; cp = cp->next)
9693 cp->last = FALSE;
9694 cp->last = TRUE;
9695 }
9696 line_breakcheck();
9697 if (apc->curpat != NULL) /* found a match */
9698 break;
9699 }
9700 if (stop_at_last && ap->last)
9701 break;
9702 }
9703}
9704
9705/*
9706 * Get next autocommand command.
9707 * Called by do_cmdline() to get the next line for ":if".
9708 * Returns allocated string, or NULL for end of autocommands.
9709 */
Bram Moolenaar21691f82012-12-05 19:13:18 +01009710 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009711getnextac(int c UNUSED, void *cookie, int indent UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009712{
9713 AutoPatCmd *acp = (AutoPatCmd *)cookie;
9714 char_u *retval;
9715 AutoCmd *ac;
9716
9717 /* Can be called again after returning the last line. */
9718 if (acp->curpat == NULL)
9719 return NULL;
9720
9721 /* repeat until we find an autocommand to execute */
9722 for (;;)
9723 {
9724 /* skip removed commands */
9725 while (acp->nextcmd != NULL && acp->nextcmd->cmd == NULL)
9726 if (acp->nextcmd->last)
9727 acp->nextcmd = NULL;
9728 else
9729 acp->nextcmd = acp->nextcmd->next;
9730
9731 if (acp->nextcmd != NULL)
9732 break;
9733
9734 /* at end of commands, find next pattern that matches */
9735 if (acp->curpat->last)
9736 acp->curpat = NULL;
9737 else
9738 acp->curpat = acp->curpat->next;
9739 if (acp->curpat != NULL)
9740 auto_next_pat(acp, TRUE);
9741 if (acp->curpat == NULL)
9742 return NULL;
9743 }
9744
9745 ac = acp->nextcmd;
9746
9747 if (p_verbose >= 9)
9748 {
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009749 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009750 smsg((char_u *)_("autocommand %s"), ac->cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009751 msg_puts((char_u *)"\n"); /* don't overwrite this either */
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009752 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009753 }
9754 retval = vim_strsave(ac->cmd);
9755 autocmd_nested = ac->nested;
9756#ifdef FEAT_EVAL
9757 current_SID = ac->scriptID;
9758#endif
9759 if (ac->last)
9760 acp->nextcmd = NULL;
9761 else
9762 acp->nextcmd = ac->next;
9763 return retval;
9764}
9765
9766/*
9767 * Return TRUE if there is a matching autocommand for "fname".
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009768 * To account for buffer-local autocommands, function needs to know
9769 * in which buffer the file will be opened.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009770 */
9771 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009772has_autocmd(event_T event, char_u *sfname, buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009773{
9774 AutoPat *ap;
9775 char_u *fname;
9776 char_u *tail = gettail(sfname);
9777 int retval = FALSE;
9778
9779 fname = FullName_save(sfname, FALSE);
9780 if (fname == NULL)
9781 return FALSE;
9782
9783#ifdef BACKSLASH_IN_FILENAME
9784 /*
9785 * Replace all backslashes with forward slashes. This makes the
9786 * autocommand patterns portable between Unix and MS-DOS.
9787 */
9788 sfname = vim_strsave(sfname);
9789 if (sfname != NULL)
9790 forward_slash(sfname);
9791 forward_slash(fname);
9792#endif
9793
9794 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
9795 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009796 && (ap->buflocal_nr == 0
Bram Moolenaardffa5b82014-11-19 16:38:07 +01009797 ? match_file_pat(NULL, &ap->reg_prog,
Bram Moolenaar748bf032005-02-02 23:04:36 +00009798 fname, sfname, tail, ap->allow_dirs)
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009799 : buf != NULL && ap->buflocal_nr == buf->b_fnum
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009800 ))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009801 {
9802 retval = TRUE;
9803 break;
9804 }
9805
9806 vim_free(fname);
9807#ifdef BACKSLASH_IN_FILENAME
9808 vim_free(sfname);
9809#endif
9810
9811 return retval;
9812}
9813
9814#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
9815/*
9816 * Function given to ExpandGeneric() to obtain the list of autocommand group
9817 * names.
9818 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009819 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009820get_augroup_name(expand_T *xp UNUSED, int idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009821{
9822 if (idx == augroups.ga_len) /* add "END" add the end */
9823 return (char_u *)"END";
9824 if (idx >= augroups.ga_len) /* end of list */
9825 return NULL;
9826 if (AUGROUP_NAME(idx) == NULL) /* skip deleted entries */
9827 return (char_u *)"";
9828 return AUGROUP_NAME(idx); /* return a name */
9829}
9830
9831static int include_groups = FALSE;
9832
9833 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009834set_context_in_autocmd(
9835 expand_T *xp,
9836 char_u *arg,
9837 int doautocmd) /* TRUE for :doauto*, FALSE for :autocmd */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009838{
9839 char_u *p;
9840 int group;
9841
9842 /* check for a group name, skip it if present */
9843 include_groups = FALSE;
9844 p = arg;
9845 group = au_get_grouparg(&arg);
9846 if (group == AUGROUP_ERROR)
9847 return NULL;
9848 /* If there only is a group name that's what we expand. */
9849 if (*arg == NUL && group != AUGROUP_ALL && !vim_iswhite(arg[-1]))
9850 {
9851 arg = p;
9852 group = AUGROUP_ALL;
9853 }
9854
9855 /* skip over event name */
9856 for (p = arg; *p != NUL && !vim_iswhite(*p); ++p)
9857 if (*p == ',')
9858 arg = p + 1;
9859 if (*p == NUL)
9860 {
9861 if (group == AUGROUP_ALL)
9862 include_groups = TRUE;
9863 xp->xp_context = EXPAND_EVENTS; /* expand event name */
9864 xp->xp_pattern = arg;
9865 return NULL;
9866 }
9867
9868 /* skip over pattern */
9869 arg = skipwhite(p);
9870 while (*arg && (!vim_iswhite(*arg) || arg[-1] == '\\'))
9871 arg++;
9872 if (*arg)
9873 return arg; /* expand (next) command */
9874
9875 if (doautocmd)
9876 xp->xp_context = EXPAND_FILES; /* expand file names */
9877 else
9878 xp->xp_context = EXPAND_NOTHING; /* pattern is not expanded */
9879 return NULL;
9880}
9881
9882/*
9883 * Function given to ExpandGeneric() to obtain the list of event names.
9884 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009885 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009886get_event_name(expand_T *xp UNUSED, int idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009887{
9888 if (idx < augroups.ga_len) /* First list group names, if wanted */
9889 {
9890 if (!include_groups || AUGROUP_NAME(idx) == NULL)
9891 return (char_u *)""; /* skip deleted entries */
9892 return AUGROUP_NAME(idx); /* return a name */
9893 }
9894 return (char_u *)event_names[idx - augroups.ga_len].name;
9895}
9896
9897#endif /* FEAT_CMDL_COMPL */
9898
9899/*
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009900 * Return TRUE if autocmd is supported.
9901 */
9902 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009903autocmd_supported(char_u *name)
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009904{
9905 char_u *p;
9906
9907 return (event_name2nr(name, &p) != NUM_EVENTS);
9908}
9909
9910/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00009911 * Return TRUE if an autocommand is defined for a group, event and
9912 * pattern: The group can be omitted to accept any group. "event" and "pattern"
9913 * can be NULL to accept any event and pattern. "pattern" can be NULL to accept
9914 * any pattern. Buffer-local patterns <buffer> or <buffer=N> are accepted.
9915 * Used for:
9916 * exists("#Group") or
9917 * exists("#Group#Event") or
9918 * exists("#Group#Event#pat") or
9919 * exists("#Event") or
9920 * exists("#Event#pat")
Bram Moolenaar071d4272004-06-13 20:20:40 +00009921 */
9922 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009923au_exists(char_u *arg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009924{
Bram Moolenaar195d6352005-12-19 22:08:24 +00009925 char_u *arg_save;
9926 char_u *pattern = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009927 char_u *event_name;
9928 char_u *p;
Bram Moolenaar754b5602006-02-09 23:53:20 +00009929 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009930 AutoPat *ap;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009931 buf_T *buflocal_buf = NULL;
Bram Moolenaar195d6352005-12-19 22:08:24 +00009932 int group;
9933 int retval = FALSE;
9934
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009935 /* Make a copy so that we can change the '#' chars to a NUL. */
Bram Moolenaar195d6352005-12-19 22:08:24 +00009936 arg_save = vim_strsave(arg);
9937 if (arg_save == NULL)
9938 return FALSE;
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009939 p = vim_strchr(arg_save, '#');
Bram Moolenaar195d6352005-12-19 22:08:24 +00009940 if (p != NULL)
9941 *p++ = NUL;
9942
9943 /* First, look for an autocmd group name */
9944 group = au_find_group(arg_save);
9945 if (group == AUGROUP_ERROR)
9946 {
9947 /* Didn't match a group name, assume the first argument is an event. */
9948 group = AUGROUP_ALL;
9949 event_name = arg_save;
9950 }
9951 else
9952 {
9953 if (p == NULL)
9954 {
9955 /* "Group": group name is present and it's recognized */
9956 retval = TRUE;
9957 goto theend;
9958 }
9959
9960 /* Must be "Group#Event" or "Group#Event#pat". */
9961 event_name = p;
9962 p = vim_strchr(event_name, '#');
9963 if (p != NULL)
9964 *p++ = NUL; /* "Group#Event#pat" */
9965 }
9966
9967 pattern = p; /* "pattern" is NULL when there is no pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009968
9969 /* find the index (enum) for the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009970 event = event_name2nr(event_name, &p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009971
9972 /* return FALSE if the event name is not recognized */
Bram Moolenaar195d6352005-12-19 22:08:24 +00009973 if (event == NUM_EVENTS)
9974 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009975
9976 /* Find the first autocommand for this event.
9977 * If there isn't any, return FALSE;
9978 * If there is one and no pattern given, return TRUE; */
9979 ap = first_autopat[(int)event];
9980 if (ap == NULL)
Bram Moolenaar195d6352005-12-19 22:08:24 +00009981 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009982
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009983 /* if pattern is "<buffer>", special handling is needed which uses curbuf */
9984 /* for pattern "<buffer=N>, fnamecmp() will work fine */
Bram Moolenaar5b7880d2009-09-11 15:24:31 +00009985 if (pattern != NULL && STRICMP(pattern, "<buffer>") == 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009986 buflocal_buf = curbuf;
9987
Bram Moolenaar071d4272004-06-13 20:20:40 +00009988 /* Check if there is an autocommand with the given pattern. */
9989 for ( ; ap != NULL; ap = ap->next)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009990 /* only use a pattern when it has not been removed and has commands. */
9991 /* For buffer-local autocommands, fnamecmp() works fine. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009992 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaar195d6352005-12-19 22:08:24 +00009993 && (group == AUGROUP_ALL || ap->group == group)
Bram Moolenaar5b7880d2009-09-11 15:24:31 +00009994 && (pattern == NULL
9995 || (buflocal_buf == NULL
9996 ? fnamecmp(ap->pat, pattern) == 0
9997 : ap->buflocal_nr == buflocal_buf->b_fnum)))
Bram Moolenaar195d6352005-12-19 22:08:24 +00009998 {
9999 retval = TRUE;
10000 break;
10001 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010002
Bram Moolenaar195d6352005-12-19 22:08:24 +000010003theend:
10004 vim_free(arg_save);
10005 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010006}
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010007
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010008#else /* FEAT_AUTOCMD */
10009
10010/*
10011 * Prepare for executing commands for (hidden) buffer "buf".
10012 * This is the non-autocommand version, it simply saves "curbuf" and sets
10013 * "curbuf" and "curwin" to match "buf".
10014 */
10015 void
Bram Moolenaard14e00e2016-01-31 17:30:51 +010010016aucmd_prepbuf(
10017 aco_save_T *aco, /* structure to save values in */
10018 buf_T *buf) /* new curbuf */
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010019{
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010020 aco->save_curbuf = curbuf;
10021 --curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010022 curbuf = buf;
10023 curwin->w_buffer = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010024 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010025}
10026
10027/*
10028 * Restore after executing commands for a (hidden) buffer.
10029 * This is the non-autocommand version.
10030 */
10031 void
Bram Moolenaard14e00e2016-01-31 17:30:51 +010010032aucmd_restbuf(
10033 aco_save_T *aco) /* structure holding saved values */
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010034{
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010035 --curbuf->b_nwindows;
10036 curbuf = aco->save_curbuf;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010037 curwin->w_buffer = curbuf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010038 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010039}
10040
Bram Moolenaar071d4272004-06-13 20:20:40 +000010041#endif /* FEAT_AUTOCMD */
10042
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010043
Bram Moolenaar071d4272004-06-13 20:20:40 +000010044#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN) || defined(PROTO)
10045/*
Bram Moolenaar748bf032005-02-02 23:04:36 +000010046 * Try matching a filename with a "pattern" ("prog" is NULL), or use the
10047 * precompiled regprog "prog" ("pattern" is NULL). That avoids calling
10048 * vim_regcomp() often.
Bram Moolenaar071d4272004-06-13 20:20:40 +000010049 * Used for autocommands and 'wildignore'.
10050 * Returns TRUE if there is a match, FALSE otherwise.
10051 */
Bram Moolenaardffa5b82014-11-19 16:38:07 +010010052 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010053match_file_pat(
10054 char_u *pattern, /* pattern to match with */
10055 regprog_T **prog, /* pre-compiled regprog or NULL */
10056 char_u *fname, /* full path of file name */
10057 char_u *sfname, /* short file name or NULL */
10058 char_u *tail, /* tail of path */
10059 int allow_dirs) /* allow matching with dir */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010060{
10061 regmatch_T regmatch;
10062 int result = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010063
Bram Moolenaar71afbfe2013-03-19 16:49:16 +010010064 regmatch.rm_ic = p_fic; /* ignore case if 'fileignorecase' is set */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010065 if (prog != NULL)
10066 regmatch.regprog = *prog;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010067 else
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010068 regmatch.regprog = vim_regcomp(pattern, RE_MAGIC);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010069
10070 /*
10071 * Try for a match with the pattern with:
10072 * 1. the full file name, when the pattern has a '/'.
10073 * 2. the short file name, when the pattern has a '/'.
10074 * 3. the tail of the file name, when the pattern has no '/'.
10075 */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010076 if (regmatch.regprog != NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +000010077 && ((allow_dirs
10078 && (vim_regexec(&regmatch, fname, (colnr_T)0)
10079 || (sfname != NULL
10080 && vim_regexec(&regmatch, sfname, (colnr_T)0))))
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010081 || (!allow_dirs && vim_regexec(&regmatch, tail, (colnr_T)0))))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010082 result = TRUE;
10083
Bram Moolenaardffa5b82014-11-19 16:38:07 +010010084 if (prog != NULL)
10085 *prog = regmatch.regprog;
10086 else
Bram Moolenaar473de612013-06-08 18:19:48 +020010087 vim_regfree(regmatch.regprog);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010088 return result;
10089}
10090#endif
10091
10092#if defined(FEAT_WILDIGN) || defined(PROTO)
10093/*
10094 * Return TRUE if a file matches with a pattern in "list".
10095 * "list" is a comma-separated list of patterns, like 'wildignore'.
10096 * "sfname" is the short file name or NULL, "ffname" the long file name.
10097 */
10098 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010099match_file_list(char_u *list, char_u *sfname, char_u *ffname)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010100{
10101 char_u buf[100];
10102 char_u *tail;
10103 char_u *regpat;
10104 char allow_dirs;
10105 int match;
10106 char_u *p;
10107
10108 tail = gettail(sfname);
10109
10110 /* try all patterns in 'wildignore' */
10111 p = list;
10112 while (*p)
10113 {
10114 copy_option_part(&p, buf, 100, ",");
10115 regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, FALSE);
10116 if (regpat == NULL)
10117 break;
Bram Moolenaar748bf032005-02-02 23:04:36 +000010118 match = match_file_pat(regpat, NULL, ffname, sfname,
10119 tail, (int)allow_dirs);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010120 vim_free(regpat);
10121 if (match)
10122 return TRUE;
10123 }
10124 return FALSE;
10125}
10126#endif
10127
10128/*
10129 * Convert the given pattern "pat" which has shell style wildcards in it, into
10130 * a regular expression, and return the result in allocated memory. If there
10131 * is a directory path separator to be matched, then TRUE is put in
10132 * allow_dirs, otherwise FALSE is put there -- webb.
10133 * Handle backslashes before special characters, like "\*" and "\ ".
10134 *
Bram Moolenaar071d4272004-06-13 20:20:40 +000010135 * Returns NULL when out of memory.
10136 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010137 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010138file_pat_to_reg_pat(
10139 char_u *pat,
10140 char_u *pat_end, /* first char after pattern or NULL */
10141 char *allow_dirs, /* Result passed back out in here */
10142 int no_bslash UNUSED) /* Don't use a backward slash as pathsep */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010143{
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010144 int size = 2; /* '^' at start, '$' at end */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010145 char_u *endp;
10146 char_u *reg_pat;
10147 char_u *p;
10148 int i;
10149 int nested = 0;
10150 int add_dollar = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010151
10152 if (allow_dirs != NULL)
10153 *allow_dirs = FALSE;
10154 if (pat_end == NULL)
10155 pat_end = pat + STRLEN(pat);
10156
Bram Moolenaar071d4272004-06-13 20:20:40 +000010157 for (p = pat; p < pat_end; p++)
10158 {
10159 switch (*p)
10160 {
10161 case '*':
10162 case '.':
10163 case ',':
10164 case '{':
10165 case '}':
10166 case '~':
10167 size += 2; /* extra backslash */
10168 break;
10169#ifdef BACKSLASH_IN_FILENAME
10170 case '\\':
10171 case '/':
10172 size += 4; /* could become "[\/]" */
10173 break;
10174#endif
10175 default:
10176 size++;
Bram Moolenaar2288afe2015-08-11 16:20:05 +020010177# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010178 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010179 {
10180 ++p;
10181 ++size;
10182 }
10183# endif
10184 break;
10185 }
10186 }
10187 reg_pat = alloc(size + 1);
10188 if (reg_pat == NULL)
10189 return NULL;
10190
Bram Moolenaar071d4272004-06-13 20:20:40 +000010191 i = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010192
10193 if (pat[0] == '*')
10194 while (pat[0] == '*' && pat < pat_end - 1)
10195 pat++;
10196 else
10197 reg_pat[i++] = '^';
10198 endp = pat_end - 1;
Bram Moolenaar8fee8782015-08-11 18:45:48 +020010199 if (endp >= pat && *endp == '*')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010200 {
10201 while (endp - pat > 0 && *endp == '*')
10202 endp--;
10203 add_dollar = FALSE;
10204 }
10205 for (p = pat; *p && nested >= 0 && p <= endp; p++)
10206 {
10207 switch (*p)
10208 {
10209 case '*':
10210 reg_pat[i++] = '.';
10211 reg_pat[i++] = '*';
Bram Moolenaar02743632005-07-25 20:42:36 +000010212 while (p[1] == '*') /* "**" matches like "*" */
10213 ++p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010214 break;
10215 case '.':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010216 case '~':
10217 reg_pat[i++] = '\\';
10218 reg_pat[i++] = *p;
10219 break;
10220 case '?':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010221 reg_pat[i++] = '.';
10222 break;
10223 case '\\':
10224 if (p[1] == NUL)
10225 break;
10226#ifdef BACKSLASH_IN_FILENAME
10227 if (!no_bslash)
10228 {
10229 /* translate:
10230 * "\x" to "\\x" e.g., "dir\file"
10231 * "\*" to "\\.*" e.g., "dir\*.c"
10232 * "\?" to "\\." e.g., "dir\??.c"
10233 * "\+" to "\+" e.g., "fileX\+.c"
10234 */
10235 if ((vim_isfilec(p[1]) || p[1] == '*' || p[1] == '?')
10236 && p[1] != '+')
10237 {
10238 reg_pat[i++] = '[';
10239 reg_pat[i++] = '\\';
10240 reg_pat[i++] = '/';
10241 reg_pat[i++] = ']';
10242 if (allow_dirs != NULL)
10243 *allow_dirs = TRUE;
10244 break;
10245 }
10246 }
10247#endif
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010248 /* Undo escaping from ExpandEscape():
10249 * foo\?bar -> foo?bar
10250 * foo\%bar -> foo%bar
10251 * foo\,bar -> foo,bar
10252 * foo\ bar -> foo bar
10253 * Don't unescape \, * and others that are also special in a
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010254 * regexp.
10255 * An escaped { must be unescaped since we use magic not
Bram Moolenaara946afe2013-08-02 15:22:39 +020010256 * verymagic. Use "\\\{n,m\}"" to get "\{n,m}".
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010257 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010258 if (*++p == '?'
10259#ifdef BACKSLASH_IN_FILENAME
10260 && no_bslash
10261#endif
10262 )
10263 reg_pat[i++] = '?';
10264 else
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010265 if (*p == ',' || *p == '%' || *p == '#'
Bram Moolenaar2288afe2015-08-11 16:20:05 +020010266 || vim_isspace(*p) || *p == '{' || *p == '}')
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010267 reg_pat[i++] = *p;
Bram Moolenaara946afe2013-08-02 15:22:39 +020010268 else if (*p == '\\' && p[1] == '\\' && p[2] == '{')
10269 {
10270 reg_pat[i++] = '\\';
10271 reg_pat[i++] = '{';
10272 p += 2;
10273 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010274 else
10275 {
10276 if (allow_dirs != NULL && vim_ispathsep(*p)
10277#ifdef BACKSLASH_IN_FILENAME
10278 && (!no_bslash || *p != '\\')
10279#endif
10280 )
10281 *allow_dirs = TRUE;
10282 reg_pat[i++] = '\\';
10283 reg_pat[i++] = *p;
10284 }
10285 break;
10286#ifdef BACKSLASH_IN_FILENAME
10287 case '/':
10288 reg_pat[i++] = '[';
10289 reg_pat[i++] = '\\';
10290 reg_pat[i++] = '/';
10291 reg_pat[i++] = ']';
10292 if (allow_dirs != NULL)
10293 *allow_dirs = TRUE;
10294 break;
10295#endif
10296 case '{':
10297 reg_pat[i++] = '\\';
10298 reg_pat[i++] = '(';
10299 nested++;
10300 break;
10301 case '}':
10302 reg_pat[i++] = '\\';
10303 reg_pat[i++] = ')';
10304 --nested;
10305 break;
10306 case ',':
10307 if (nested)
10308 {
10309 reg_pat[i++] = '\\';
10310 reg_pat[i++] = '|';
10311 }
10312 else
10313 reg_pat[i++] = ',';
10314 break;
10315 default:
10316# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010317 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010318 reg_pat[i++] = *p++;
10319 else
10320# endif
10321 if (allow_dirs != NULL && vim_ispathsep(*p))
10322 *allow_dirs = TRUE;
10323 reg_pat[i++] = *p;
10324 break;
10325 }
10326 }
10327 if (add_dollar)
10328 reg_pat[i++] = '$';
10329 reg_pat[i] = NUL;
10330 if (nested != 0)
10331 {
10332 if (nested < 0)
10333 EMSG(_("E219: Missing {."));
10334 else
10335 EMSG(_("E220: Missing }."));
10336 vim_free(reg_pat);
10337 reg_pat = NULL;
10338 }
10339 return reg_pat;
10340}
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010341
10342#if defined(EINTR) || defined(PROTO)
10343/*
10344 * Version of read() that retries when interrupted by EINTR (possibly
10345 * by a SIGWINCH).
10346 */
10347 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010348read_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010349{
10350 long ret;
10351
10352 for (;;)
10353 {
10354 ret = vim_read(fd, buf, bufsize);
10355 if (ret >= 0 || errno != EINTR)
10356 break;
10357 }
10358 return ret;
10359}
10360
10361/*
10362 * Version of write() that retries when interrupted by EINTR (possibly
10363 * by a SIGWINCH).
10364 */
10365 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010366write_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010367{
10368 long ret = 0;
10369 long wlen;
10370
10371 /* Repeat the write() so long it didn't fail, other than being interrupted
10372 * by a signal. */
10373 while (ret < (long)bufsize)
10374 {
Bram Moolenaar9c263032010-12-17 18:06:06 +010010375 wlen = vim_write(fd, (char *)buf + ret, bufsize - ret);
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010376 if (wlen < 0)
10377 {
10378 if (errno != EINTR)
10379 break;
10380 }
10381 else
10382 ret += wlen;
10383 }
10384 return ret;
10385}
10386#endif