blob: 042bbec6e108d11324e7ebb7381d16b72669e655 [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;
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200370#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000371 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')";
Bram Moolenaara06ecab2016-07-16 14:47:36 +02003153#if defined(UNIX) /*XXX fix me sometime? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003154 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);
Bram Moolenaar29323592016-07-24 22:04:11 +02006091 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006092 {
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;
Bram Moolenaar29323592016-07-24 22:04:11 +02006683 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006684 {
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 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006702 }
6703 --no_wait_return;
6704 need_check_timestamps = FALSE;
6705 if (need_wait_return && didit == 2)
6706 {
6707 /* make sure msg isn't overwritten */
6708 msg_puts((char_u *)"\n");
6709 out_flush();
6710 }
6711 }
6712 return didit;
6713}
6714
6715/*
6716 * Move all the lines from buffer "frombuf" to buffer "tobuf".
6717 * Return OK or FAIL. When FAIL "tobuf" is incomplete and/or "frombuf" is not
6718 * empty.
6719 */
6720 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006721move_lines(buf_T *frombuf, buf_T *tobuf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006722{
6723 buf_T *tbuf = curbuf;
6724 int retval = OK;
6725 linenr_T lnum;
6726 char_u *p;
6727
6728 /* Copy the lines in "frombuf" to "tobuf". */
6729 curbuf = tobuf;
6730 for (lnum = 1; lnum <= frombuf->b_ml.ml_line_count; ++lnum)
6731 {
6732 p = vim_strsave(ml_get_buf(frombuf, lnum, FALSE));
6733 if (p == NULL || ml_append(lnum - 1, p, 0, FALSE) == FAIL)
6734 {
6735 vim_free(p);
6736 retval = FAIL;
6737 break;
6738 }
6739 vim_free(p);
6740 }
6741
6742 /* Delete all the lines in "frombuf". */
6743 if (retval != FAIL)
6744 {
6745 curbuf = frombuf;
Bram Moolenaar9460b9d2007-01-09 14:37:01 +00006746 for (lnum = curbuf->b_ml.ml_line_count; lnum > 0; --lnum)
6747 if (ml_delete(lnum, FALSE) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006748 {
6749 /* Oops! We could try putting back the saved lines, but that
6750 * might fail again... */
6751 retval = FAIL;
6752 break;
6753 }
6754 }
6755
6756 curbuf = tbuf;
6757 return retval;
6758}
6759
6760/*
6761 * Check if buffer "buf" has been changed.
6762 * Also check if the file for a new buffer unexpectedly appeared.
6763 * return 1 if a changed buffer was found.
6764 * return 2 if a message has been displayed.
6765 * return 0 otherwise.
6766 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006767 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006768buf_check_timestamp(
6769 buf_T *buf,
6770 int focus UNUSED) /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006771{
Bram Moolenaar8767f522016-07-01 17:17:39 +02006772 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006773 int stat_res;
6774 int retval = 0;
6775 char_u *path;
6776 char_u *tbuf;
6777 char *mesg = NULL;
Bram Moolenaar44ecf652005-03-07 23:09:59 +00006778 char *mesg2 = "";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006779 int helpmesg = FALSE;
6780 int reload = FALSE;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006781 char *reason;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006782#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6783 int can_reload = FALSE;
6784#endif
Bram Moolenaar8767f522016-07-01 17:17:39 +02006785 off_T orig_size = buf->b_orig_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006786 int orig_mode = buf->b_orig_mode;
6787#ifdef FEAT_GUI
6788 int save_mouse_correct = need_mouse_correct;
6789#endif
6790#ifdef FEAT_AUTOCMD
6791 static int busy = FALSE;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006792 int n;
6793 char_u *s;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006794 bufref_T bufref;
6795
6796 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006797#endif
6798
6799 /* If there is no file name, the buffer is not loaded, 'buftype' is
6800 * set, we are in the middle of a save or being called recursively: ignore
6801 * this buffer. */
6802 if (buf->b_ffname == NULL
6803 || buf->b_ml.ml_mfp == NULL
6804#if defined(FEAT_QUICKFIX)
6805 || *buf->b_p_bt != NUL
6806#endif
6807 || buf->b_saving
6808#ifdef FEAT_AUTOCMD
6809 || busy
6810#endif
Bram Moolenaar009b2592004-10-24 19:18:58 +00006811#ifdef FEAT_NETBEANS_INTG
6812 || isNetbeansBuffer(buf)
6813#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006814 )
6815 return 0;
6816
6817 if ( !(buf->b_flags & BF_NOTEDITED)
6818 && buf->b_mtime != 0
6819 && ((stat_res = mch_stat((char *)buf->b_ffname, &st)) < 0
6820 || time_differs((long)st.st_mtime, buf->b_mtime)
Bram Moolenaara7611f62014-05-02 15:46:14 +02006821 || st.st_size != buf->b_orig_size
Bram Moolenaar071d4272004-06-13 20:20:40 +00006822#ifdef HAVE_ST_MODE
6823 || (int)st.st_mode != buf->b_orig_mode
6824#else
6825 || mch_getperm(buf->b_ffname) != buf->b_orig_mode
6826#endif
6827 ))
6828 {
6829 retval = 1;
6830
Bram Moolenaar316059c2006-01-14 21:18:42 +00006831 /* set b_mtime to stop further warnings (e.g., when executing
6832 * FileChangedShell autocmd) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006833 if (stat_res < 0)
6834 {
6835 buf->b_mtime = 0;
6836 buf->b_orig_size = 0;
6837 buf->b_orig_mode = 0;
6838 }
6839 else
6840 buf_store_time(buf, &st, buf->b_ffname);
6841
6842 /* Don't do anything for a directory. Might contain the file
6843 * explorer. */
6844 if (mch_isdir(buf->b_fname))
6845 ;
6846
6847 /*
6848 * If 'autoread' is set, the buffer has no changes and the file still
6849 * exists, reload the buffer. Use the buffer-local option value if it
6850 * was set, the global option value otherwise.
6851 */
6852 else if ((buf->b_p_ar >= 0 ? buf->b_p_ar : p_ar)
6853 && !bufIsChanged(buf) && stat_res >= 0)
6854 reload = TRUE;
6855 else
6856 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006857 if (stat_res < 0)
6858 reason = "deleted";
6859 else if (bufIsChanged(buf))
6860 reason = "conflict";
6861 else if (orig_size != buf->b_orig_size || buf_contents_changed(buf))
6862 reason = "changed";
6863 else if (orig_mode != buf->b_orig_mode)
6864 reason = "mode";
6865 else
6866 reason = "time";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006867
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006868#ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006869 /*
6870 * Only give the warning if there are no FileChangedShell
6871 * autocommands.
6872 * Avoid being called recursively by setting "busy".
6873 */
6874 busy = TRUE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00006875# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006876 set_vim_var_string(VV_FCS_REASON, (char_u *)reason, -1);
6877 set_vim_var_string(VV_FCS_CHOICE, (char_u *)"", -1);
Bram Moolenaar1e015462005-09-25 22:16:38 +00006878# endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006879 ++allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006880 n = apply_autocmds(EVENT_FILECHANGEDSHELL,
6881 buf->b_fname, buf->b_fname, FALSE, buf);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006882 --allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006883 busy = FALSE;
6884 if (n)
6885 {
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006886 if (!bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006887 EMSG(_("E246: FileChangedShell autocommand deleted buffer"));
Bram Moolenaar1e015462005-09-25 22:16:38 +00006888# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006889 s = get_vim_var_str(VV_FCS_CHOICE);
6890 if (STRCMP(s, "reload") == 0 && *reason != 'd')
6891 reload = TRUE;
6892 else if (STRCMP(s, "ask") == 0)
6893 n = FALSE;
6894 else
Bram Moolenaar1e015462005-09-25 22:16:38 +00006895# endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006896 return 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006897 }
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006898 if (!n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006899#endif
6900 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006901 if (*reason == 'd')
6902 mesg = _("E211: File \"%s\" no longer available");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006903 else
6904 {
6905 helpmesg = TRUE;
6906#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6907 can_reload = TRUE;
6908#endif
6909 /*
6910 * Check if the file contents really changed to avoid
6911 * giving a warning when only the timestamp was set (e.g.,
6912 * checked out of CVS). Always warn when the buffer was
6913 * changed.
6914 */
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006915 if (reason[2] == 'n')
6916 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006917 mesg = _("W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006918 mesg2 = _("See \":help W12\" for more info.");
6919 }
6920 else if (reason[1] == 'h')
6921 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006922 mesg = _("W11: Warning: File \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006923 mesg2 = _("See \":help W11\" for more info.");
6924 }
6925 else if (*reason == 'm')
6926 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006927 mesg = _("W16: Warning: Mode of file \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006928 mesg2 = _("See \":help W16\" for more info.");
6929 }
Bram Moolenaar85388b52009-06-24 09:58:32 +00006930 else
6931 /* Only timestamp changed, store it to avoid a warning
6932 * in check_mtime() later. */
6933 buf->b_mtime_read = buf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006934 }
6935 }
6936 }
6937
6938 }
6939 else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W)
6940 && vim_fexists(buf->b_ffname))
6941 {
6942 retval = 1;
6943 mesg = _("W13: Warning: File \"%s\" has been created after editing started");
6944 buf->b_flags |= BF_NEW_W;
6945#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6946 can_reload = TRUE;
6947#endif
6948 }
6949
6950 if (mesg != NULL)
6951 {
6952 path = home_replace_save(buf, buf->b_fname);
6953 if (path != NULL)
6954 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006955 if (!helpmesg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006956 mesg2 = "";
6957 tbuf = alloc((unsigned)(STRLEN(path) + STRLEN(mesg)
6958 + STRLEN(mesg2) + 2));
6959 sprintf((char *)tbuf, mesg, path);
Bram Moolenaar496c5262009-03-18 14:42:00 +00006960#ifdef FEAT_EVAL
6961 /* Set warningmsg here, before the unimportant and output-specific
6962 * mesg2 has been appended. */
6963 set_vim_var_string(VV_WARNINGMSG, tbuf, -1);
6964#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006965#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6966 if (can_reload)
6967 {
6968 if (*mesg2 != NUL)
6969 {
6970 STRCAT(tbuf, "\n");
6971 STRCAT(tbuf, mesg2);
6972 }
6973 if (do_dialog(VIM_WARNING, (char_u *)_("Warning"), tbuf,
Bram Moolenaard2c340a2011-01-17 20:08:11 +01006974 (char_u *)_("&OK\n&Load File"), 1, NULL, TRUE) == 2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006975 reload = TRUE;
6976 }
6977 else
6978#endif
6979 if (State > NORMAL_BUSY || (State & CMDLINE) || already_warned)
6980 {
6981 if (*mesg2 != NUL)
6982 {
6983 STRCAT(tbuf, "; ");
6984 STRCAT(tbuf, mesg2);
6985 }
6986 EMSG(tbuf);
6987 retval = 2;
6988 }
6989 else
6990 {
Bram Moolenaared203462004-06-16 11:19:22 +00006991# ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006992 if (!autocmd_busy)
Bram Moolenaared203462004-06-16 11:19:22 +00006993# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006994 {
6995 msg_start();
6996 msg_puts_attr(tbuf, hl_attr(HLF_E) + MSG_HIST);
6997 if (*mesg2 != NUL)
6998 msg_puts_attr((char_u *)mesg2,
6999 hl_attr(HLF_W) + MSG_HIST);
7000 msg_clr_eos();
7001 (void)msg_end();
7002 if (emsg_silent == 0)
7003 {
7004 out_flush();
Bram Moolenaared203462004-06-16 11:19:22 +00007005# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00007006 if (!focus)
Bram Moolenaared203462004-06-16 11:19:22 +00007007# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007008 /* give the user some time to think about it */
7009 ui_delay(1000L, TRUE);
7010
7011 /* don't redraw and erase the message */
7012 redraw_cmdline = FALSE;
7013 }
7014 }
7015 already_warned = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007016 }
7017
7018 vim_free(path);
7019 vim_free(tbuf);
7020 }
7021 }
7022
7023 if (reload)
Bram Moolenaar465748e2012-08-29 18:50:54 +02007024 {
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007025 /* Reload the buffer. */
Bram Moolenaar316059c2006-01-14 21:18:42 +00007026 buf_reload(buf, orig_mode);
Bram Moolenaar465748e2012-08-29 18:50:54 +02007027#ifdef FEAT_PERSISTENT_UNDO
7028 if (buf->b_p_udf && buf->b_ffname != NULL)
7029 {
7030 char_u hash[UNDO_HASH_SIZE];
7031 buf_T *save_curbuf = curbuf;
7032
7033 /* Any existing undo file is unusable, write it now. */
7034 curbuf = buf;
7035 u_compute_hash(hash);
7036 u_write_undo(NULL, FALSE, buf, hash);
7037 curbuf = save_curbuf;
7038 }
7039#endif
7040 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007041
Bram Moolenaar56718732006-03-15 22:53:57 +00007042#ifdef FEAT_AUTOCMD
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00007043 /* Trigger FileChangedShell when the file was changed in any way. */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007044 if (bufref_valid(&bufref) && retval != 0)
Bram Moolenaar56718732006-03-15 22:53:57 +00007045 (void)apply_autocmds(EVENT_FILECHANGEDSHELLPOST,
7046 buf->b_fname, buf->b_fname, FALSE, buf);
7047#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007048#ifdef FEAT_GUI
7049 /* restore this in case an autocommand has set it; it would break
7050 * 'mousefocus' */
7051 need_mouse_correct = save_mouse_correct;
7052#endif
7053
7054 return retval;
7055}
7056
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007057/*
7058 * Reload a buffer that is already loaded.
7059 * Used when the file was changed outside of Vim.
Bram Moolenaar316059c2006-01-14 21:18:42 +00007060 * "orig_mode" is buf->b_orig_mode before the need for reloading was detected.
7061 * buf->b_orig_mode may have been reset already.
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007062 */
7063 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007064buf_reload(buf_T *buf, int orig_mode)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007065{
7066 exarg_T ea;
7067 pos_T old_cursor;
7068 linenr_T old_topline;
7069 int old_ro = buf->b_p_ro;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007070 buf_T *savebuf;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007071 bufref_T bufref;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007072 int saved = OK;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007073 aco_save_T aco;
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007074 int flags = READ_NEW;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007075
7076 /* set curwin/curbuf for "buf" and save some things */
7077 aucmd_prepbuf(&aco, buf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007078
7079 /* We only want to read the text from the file, not reset the syntax
7080 * highlighting, clear marks, diff status, etc. Force the fileformat
7081 * and encoding to be the same. */
7082 if (prep_exarg(&ea, buf) == OK)
7083 {
7084 old_cursor = curwin->w_cursor;
7085 old_topline = curwin->w_topline;
7086
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007087 if (p_ur < 0 || curbuf->b_ml.ml_line_count <= p_ur)
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007088 {
7089 /* Save all the text, so that the reload can be undone.
7090 * Sync first so that this is a separate undo-able action. */
7091 u_sync(FALSE);
7092 saved = u_savecommon(0, curbuf->b_ml.ml_line_count + 1, 0, TRUE);
7093 flags |= READ_KEEP_UNDO;
7094 }
7095
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007096 /*
7097 * To behave like when a new file is edited (matters for
7098 * BufReadPost autocommands) we first need to delete the current
7099 * buffer contents. But if reading the file fails we should keep
7100 * the old contents. Can't use memory only, the file might be
7101 * too big. Use a hidden buffer to move the buffer contents to.
7102 */
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007103 if (bufempty() || saved == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007104 savebuf = NULL;
7105 else
7106 {
7107 /* Allocate a buffer without putting it in the buffer list. */
7108 savebuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007109 set_bufref(&bufref, savebuf);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007110 if (savebuf != NULL && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007111 {
7112 /* Open the memline. */
7113 curbuf = savebuf;
7114 curwin->w_buffer = savebuf;
Bram Moolenaar4770d092006-01-12 23:22:24 +00007115 saved = ml_open(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007116 curbuf = buf;
7117 curwin->w_buffer = buf;
7118 }
Bram Moolenaar8424a622006-04-19 21:23:36 +00007119 if (savebuf == NULL || saved == FAIL || buf != curbuf
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007120 || move_lines(buf, savebuf) == FAIL)
7121 {
7122 EMSG2(_("E462: Could not prepare for reloading \"%s\""),
7123 buf->b_fname);
7124 saved = FAIL;
7125 }
7126 }
7127
7128 if (saved == OK)
7129 {
7130 curbuf->b_flags |= BF_CHECK_RO; /* check for RO again */
7131#ifdef FEAT_AUTOCMD
7132 keep_filetype = TRUE; /* don't detect 'filetype' */
7133#endif
7134 if (readfile(buf->b_ffname, buf->b_fname, (linenr_T)0,
7135 (linenr_T)0,
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007136 (linenr_T)MAXLNUM, &ea, flags) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007137 {
7138#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
7139 if (!aborting())
7140#endif
7141 EMSG2(_("E321: Could not reload \"%s\""), buf->b_fname);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007142 if (savebuf != NULL && bufref_valid(&bufref) && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007143 {
7144 /* Put the text back from the save buffer. First
7145 * delete any lines that readfile() added. */
7146 while (!bufempty())
Bram Moolenaar8424a622006-04-19 21:23:36 +00007147 if (ml_delete(buf->b_ml.ml_line_count, FALSE) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007148 break;
7149 (void)move_lines(savebuf, buf);
7150 }
7151 }
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007152 else if (buf == curbuf) /* "buf" still valid */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007153 {
7154 /* Mark the buffer as unmodified and free undo info. */
7155 unchanged(buf, TRUE);
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007156 if ((flags & READ_KEEP_UNDO) == 0)
7157 {
7158 u_blockfree(buf);
7159 u_clearall(buf);
7160 }
7161 else
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007162 {
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007163 /* Mark all undo states as changed. */
7164 u_unchanged(curbuf);
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007165 }
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007166 }
7167 }
7168 vim_free(ea.cmd);
7169
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007170 if (savebuf != NULL && bufref_valid(&bufref))
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007171 wipe_buffer(savebuf, FALSE);
7172
7173#ifdef FEAT_DIFF
7174 /* Invalidate diff info if necessary. */
Bram Moolenaar8424a622006-04-19 21:23:36 +00007175 diff_invalidate(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007176#endif
7177
7178 /* Restore the topline and cursor position and check it (lines may
7179 * have been removed). */
7180 if (old_topline > curbuf->b_ml.ml_line_count)
7181 curwin->w_topline = curbuf->b_ml.ml_line_count;
7182 else
7183 curwin->w_topline = old_topline;
7184 curwin->w_cursor = old_cursor;
7185 check_cursor();
7186 update_topline();
7187#ifdef FEAT_AUTOCMD
7188 keep_filetype = FALSE;
7189#endif
7190#ifdef FEAT_FOLDING
7191 {
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007192 win_T *wp;
7193 tabpage_T *tp;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007194
7195 /* Update folds unless they are defined manually. */
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007196 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007197 if (wp->w_buffer == curwin->w_buffer
7198 && !foldmethodIsManual(wp))
7199 foldUpdateAll(wp);
7200 }
7201#endif
7202 /* If the mode didn't change and 'readonly' was set, keep the old
7203 * value; the user probably used the ":view" command. But don't
7204 * reset it, might have had a read error. */
7205 if (orig_mode == curbuf->b_orig_mode)
7206 curbuf->b_p_ro |= old_ro;
Bram Moolenaar52f85b72013-01-30 14:13:56 +01007207
7208 /* Modelines must override settings done by autocommands. */
7209 do_modelines(0);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007210 }
7211
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007212 /* restore curwin/curbuf and a few other things */
7213 aucmd_restbuf(&aco);
7214 /* Careful: autocommands may have made "buf" invalid! */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007215}
7216
Bram Moolenaar071d4272004-06-13 20:20:40 +00007217 void
Bram Moolenaar8767f522016-07-01 17:17:39 +02007218buf_store_time(buf_T *buf, stat_T *st, char_u *fname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007219{
7220 buf->b_mtime = (long)st->st_mtime;
Bram Moolenaar914703b2010-05-31 21:59:46 +02007221 buf->b_orig_size = st->st_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007222#ifdef HAVE_ST_MODE
7223 buf->b_orig_mode = (int)st->st_mode;
7224#else
7225 buf->b_orig_mode = mch_getperm(fname);
7226#endif
7227}
7228
7229/*
7230 * Adjust the line with missing eol, used for the next write.
7231 * Used for do_filter(), when the input lines for the filter are deleted.
7232 */
7233 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007234write_lnum_adjust(linenr_T offset)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007235{
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01007236 if (curbuf->b_no_eol_lnum != 0) /* only if there is a missing eol */
7237 curbuf->b_no_eol_lnum += offset;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007238}
7239
Bram Moolenaarda440d22016-01-16 21:27:23 +01007240#if defined(TEMPDIRNAMES) || defined(FEAT_EVAL) || defined(PROTO)
7241/*
7242 * Delete "name" and everything in it, recursively.
7243 * return 0 for succes, -1 if some file was not deleted.
7244 */
7245 int
7246delete_recursive(char_u *name)
7247{
7248 int result = 0;
7249 char_u **files;
7250 int file_count;
7251 int i;
7252 char_u *exp;
7253
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007254 /* A symbolic link to a directory itself is deleted, not the directory it
7255 * points to. */
7256 if (
Bram Moolenaar203258c2016-01-17 22:15:16 +01007257# if defined(UNIX) || defined(WIN32)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007258 mch_isrealdir(name)
Bram Moolenaar203258c2016-01-17 22:15:16 +01007259# else
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007260 mch_isdir(name)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007261# endif
7262 )
Bram Moolenaarda440d22016-01-16 21:27:23 +01007263 {
7264 vim_snprintf((char *)NameBuff, MAXPATHL, "%s/*", name);
7265 exp = vim_strsave(NameBuff);
7266 if (exp == NULL)
7267 return -1;
7268 if (gen_expand_wildcards(1, &exp, &file_count, &files,
Bram Moolenaar336bd622016-01-17 18:23:58 +01007269 EW_DIR|EW_FILE|EW_SILENT|EW_ALLLINKS|EW_DODOT|EW_EMPTYOK) == OK)
Bram Moolenaarda440d22016-01-16 21:27:23 +01007270 {
7271 for (i = 0; i < file_count; ++i)
7272 if (delete_recursive(files[i]) != 0)
7273 result = -1;
7274 FreeWild(file_count, files);
7275 }
7276 else
7277 result = -1;
7278 vim_free(exp);
7279 (void)mch_rmdir(name);
7280 }
7281 else
7282 result = mch_remove(name) == 0 ? 0 : -1;
7283
7284 return result;
7285}
7286#endif
7287
Bram Moolenaar071d4272004-06-13 20:20:40 +00007288#if defined(TEMPDIRNAMES) || defined(PROTO)
7289static long temp_count = 0; /* Temp filename counter. */
7290
7291/*
7292 * Delete the temp directory and all files it contains.
7293 */
7294 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007295vim_deltempdir(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007296{
Bram Moolenaar071d4272004-06-13 20:20:40 +00007297 if (vim_tempdir != NULL)
7298 {
Bram Moolenaarda440d22016-01-16 21:27:23 +01007299 /* remove the trailing path separator */
7300 gettail(vim_tempdir)[-1] = NUL;
7301 delete_recursive(vim_tempdir);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007302 vim_free(vim_tempdir);
7303 vim_tempdir = NULL;
7304 }
7305}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007306
7307/*
Bram Moolenaareaf03392009-11-17 11:08:52 +00007308 * Directory "tempdir" was created. Expand this name to a full path and put
7309 * it in "vim_tempdir". This avoids that using ":cd" would confuse us.
7310 * "tempdir" must be no longer than MAXPATHL.
7311 */
7312 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007313vim_settempdir(char_u *tempdir)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007314{
7315 char_u *buf;
7316
7317 buf = alloc((unsigned)MAXPATHL + 2);
7318 if (buf != NULL)
7319 {
7320 if (vim_FullName(tempdir, buf, MAXPATHL, FALSE) == FAIL)
7321 STRCPY(buf, tempdir);
Bram Moolenaara06ecab2016-07-16 14:47:36 +02007322 add_pathsep(buf);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007323 vim_tempdir = vim_strsave(buf);
7324 vim_free(buf);
7325 }
7326}
Bram Moolenaar4592dee2009-11-18 19:11:58 +00007327#endif
Bram Moolenaareaf03392009-11-17 11:08:52 +00007328
7329/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007330 * vim_tempname(): Return a unique name that can be used for a temp file.
7331 *
Bram Moolenaar76ae22f2016-06-13 20:00:29 +02007332 * The temp file is NOT guaranteed to be created. If "keep" is FALSE it is
7333 * guaranteed to NOT be created.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007334 *
7335 * The returned pointer is to allocated memory.
7336 * The returned pointer is NULL if no valid name was found.
7337 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007338 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007339vim_tempname(
7340 int extra_char UNUSED, /* char to use in the name instead of '?' */
7341 int keep UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007342{
7343#ifdef USE_TMPNAM
7344 char_u itmp[L_tmpnam]; /* use tmpnam() */
7345#else
7346 char_u itmp[TEMPNAMELEN];
7347#endif
7348
7349#ifdef TEMPDIRNAMES
7350 static char *(tempdirs[]) = {TEMPDIRNAMES};
7351 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007352# ifndef EEXIST
Bram Moolenaar8767f522016-07-01 17:17:39 +02007353 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007354# endif
7355
7356 /*
7357 * This will create a directory for private use by this instance of Vim.
7358 * This is done once, and the same directory is used for all temp files.
7359 * This method avoids security problems because of symlink attacks et al.
7360 * It's also a bit faster, because we only need to check for an existing
7361 * file when creating the directory and not for each temp file.
7362 */
7363 if (vim_tempdir == NULL)
7364 {
7365 /*
7366 * Try the entries in TEMPDIRNAMES to create the temp directory.
7367 */
Bram Moolenaar78a15312009-05-15 19:33:18 +00007368 for (i = 0; i < (int)(sizeof(tempdirs) / sizeof(char *)); ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007369 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007370# ifndef HAVE_MKDTEMP
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007371 size_t itmplen;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007372 long nr;
7373 long off;
7374# endif
7375
Bram Moolenaare1a61992015-12-03 21:02:27 +01007376 /* Expand $TMP, leave room for "/v1100000/999999999".
7377 * Skip the directory check if the expansion fails. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007378 expand_env((char_u *)tempdirs[i], itmp, TEMPNAMELEN - 20);
Bram Moolenaare1a61992015-12-03 21:02:27 +01007379 if (itmp[0] != '$' && mch_isdir(itmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007380 {
Bram Moolenaare1a61992015-12-03 21:02:27 +01007381 /* directory exists */
Bram Moolenaara06ecab2016-07-16 14:47:36 +02007382 add_pathsep(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007383
Bram Moolenaareaf03392009-11-17 11:08:52 +00007384# ifdef HAVE_MKDTEMP
Bram Moolenaar35d88f42016-06-04 14:52:00 +02007385 {
7386# if defined(UNIX) || defined(VMS)
7387 /* Make sure the umask doesn't remove the executable bit.
7388 * "repl" has been reported to use "177". */
7389 mode_t umask_save = umask(077);
7390# endif
7391 /* Leave room for filename */
7392 STRCAT(itmp, "vXXXXXX");
7393 if (mkdtemp((char *)itmp) != NULL)
7394 vim_settempdir(itmp);
7395# if defined(UNIX) || defined(VMS)
7396 (void)umask(umask_save);
7397# endif
7398 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007399# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007400 /* Get an arbitrary number of up to 6 digits. When it's
7401 * unlikely that it already exists it will be faster,
7402 * otherwise it doesn't matter. The use of mkdir() avoids any
7403 * security problems because of the predictable number. */
7404 nr = (mch_get_pid() + (long)time(NULL)) % 1000000L;
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007405 itmplen = STRLEN(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007406
7407 /* Try up to 10000 different values until we find a name that
7408 * doesn't exist. */
7409 for (off = 0; off < 10000L; ++off)
7410 {
7411 int r;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007412# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007413 mode_t umask_save;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007414# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007415
Bram Moolenaareaf03392009-11-17 11:08:52 +00007416 sprintf((char *)itmp + itmplen, "v%ld", nr + off);
7417# ifndef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007418 /* If mkdir() does not set errno to EEXIST, check for
7419 * existing file here. There is a race condition then,
7420 * although it's fail-safe. */
7421 if (mch_stat((char *)itmp, &st) >= 0)
7422 continue;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007423# endif
7424# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007425 /* Make sure the umask doesn't remove the executable bit.
7426 * "repl" has been reported to use "177". */
7427 umask_save = umask(077);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007428# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007429 r = vim_mkdir(itmp, 0700);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007430# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007431 (void)umask(umask_save);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007432# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007433 if (r == 0)
7434 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007435 vim_settempdir(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007436 break;
7437 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007438# ifdef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007439 /* If the mkdir() didn't fail because the file/dir exists,
7440 * we probably can't create any dir here, try another
7441 * place. */
7442 if (errno != EEXIST)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007443# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007444 break;
7445 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007446# endif /* HAVE_MKDTEMP */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007447 if (vim_tempdir != NULL)
7448 break;
7449 }
7450 }
7451 }
7452
7453 if (vim_tempdir != NULL)
7454 {
7455 /* There is no need to check if the file exists, because we own the
7456 * directory and nobody else creates a file in it. */
7457 sprintf((char *)itmp, "%s%ld", vim_tempdir, temp_count++);
7458 return vim_strsave(itmp);
7459 }
7460
7461 return NULL;
7462
7463#else /* TEMPDIRNAMES */
7464
7465# ifdef WIN3264
7466 char szTempFile[_MAX_PATH + 1];
7467 char buf4[4];
7468 char_u *retval;
7469 char_u *p;
7470
7471 STRCPY(itmp, "");
7472 if (GetTempPath(_MAX_PATH, szTempFile) == 0)
Bram Moolenaarb1891912011-02-09 14:47:03 +01007473 {
7474 szTempFile[0] = '.'; /* GetTempPath() failed, use current dir */
7475 szTempFile[1] = NUL;
7476 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007477 strcpy(buf4, "VIM");
7478 buf4[2] = extra_char; /* make it "VIa", "VIb", etc. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007479 if (GetTempFileName(szTempFile, buf4, 0, (LPSTR)itmp) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007480 return NULL;
Bram Moolenaare5c421c2015-03-31 13:33:08 +02007481 if (!keep)
7482 /* GetTempFileName() will create the file, we don't want that */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007483 (void)DeleteFile((LPSTR)itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007484
7485 /* Backslashes in a temp file name cause problems when filtering with
7486 * "sh". NOTE: This also checks 'shellcmdflag' to help those people who
7487 * didn't set 'shellslash'. */
7488 retval = vim_strsave(itmp);
7489 if (*p_shcf == '-' || p_ssl)
7490 for (p = retval; *p; ++p)
7491 if (*p == '\\')
7492 *p = '/';
7493 return retval;
7494
7495# else /* WIN3264 */
7496
7497# ifdef USE_TMPNAM
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007498 char_u *p;
7499
Bram Moolenaar071d4272004-06-13 20:20:40 +00007500 /* tmpnam() will make its own name */
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007501 p = tmpnam((char *)itmp);
7502 if (p == NULL || *p == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007503 return NULL;
7504# else
7505 char_u *p;
7506
7507# ifdef VMS_TEMPNAM
7508 /* mktemp() is not working on VMS. It seems to be
7509 * a do-nothing function. Therefore we use tempnam().
7510 */
7511 sprintf((char *)itmp, "VIM%c", extra_char);
7512 p = (char_u *)tempnam("tmp:", (char *)itmp);
7513 if (p != NULL)
7514 {
Bram Moolenaar206f0112014-03-12 16:51:55 +01007515 /* VMS will use '.LIS' if we don't explicitly specify an extension,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007516 * and VIM will then be unable to find the file later */
7517 STRCPY(itmp, p);
7518 STRCAT(itmp, ".txt");
7519 free(p);
7520 }
7521 else
7522 return NULL;
7523# else
7524 STRCPY(itmp, TEMPNAME);
7525 if ((p = vim_strchr(itmp, '?')) != NULL)
7526 *p = extra_char;
7527 if (mktemp((char *)itmp) == NULL)
7528 return NULL;
7529# endif
7530# endif
7531
7532 return vim_strsave(itmp);
7533# endif /* WIN3264 */
7534#endif /* TEMPDIRNAMES */
7535}
7536
7537#if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
7538/*
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02007539 * Convert all backslashes in fname to forward slashes in-place, unless when
7540 * it looks like a URL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007541 */
7542 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007543forward_slash(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007544{
7545 char_u *p;
7546
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02007547 if (path_with_url(fname))
7548 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007549 for (p = fname; *p != NUL; ++p)
7550# ifdef FEAT_MBYTE
7551 /* The Big5 encoding can have '\' in the trail byte. */
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00007552 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007553 ++p;
7554 else
7555# endif
7556 if (*p == '\\')
7557 *p = '/';
7558}
7559#endif
7560
7561
7562/*
7563 * Code for automatic commands.
7564 *
7565 * Only included when "FEAT_AUTOCMD" has been defined.
7566 */
7567
7568#if defined(FEAT_AUTOCMD) || defined(PROTO)
7569
7570/*
7571 * The autocommands are stored in a list for each event.
7572 * Autocommands for the same pattern, that are consecutive, are joined
7573 * together, to avoid having to match the pattern too often.
7574 * The result is an array of Autopat lists, which point to AutoCmd lists:
7575 *
7576 * first_autopat[0] --> Autopat.next --> Autopat.next --> NULL
7577 * Autopat.cmds Autopat.cmds
7578 * | |
7579 * V V
7580 * AutoCmd.next AutoCmd.next
7581 * | |
7582 * V V
7583 * AutoCmd.next NULL
7584 * |
7585 * V
7586 * NULL
7587 *
7588 * first_autopat[1] --> Autopat.next --> NULL
7589 * Autopat.cmds
7590 * |
7591 * V
7592 * AutoCmd.next
7593 * |
7594 * V
7595 * NULL
7596 * etc.
7597 *
7598 * The order of AutoCmds is important, this is the order in which they were
7599 * defined and will have to be executed.
7600 */
7601typedef struct AutoCmd
7602{
7603 char_u *cmd; /* The command to be executed (NULL
7604 when command has been removed) */
7605 char nested; /* If autocommands nest here */
7606 char last; /* last command in list */
7607#ifdef FEAT_EVAL
7608 scid_T scriptID; /* script ID where defined */
7609#endif
7610 struct AutoCmd *next; /* Next AutoCmd in list */
7611} AutoCmd;
7612
7613typedef struct AutoPat
7614{
Bram Moolenaar071d4272004-06-13 20:20:40 +00007615 char_u *pat; /* pattern as typed (NULL when pattern
7616 has been removed) */
Bram Moolenaar748bf032005-02-02 23:04:36 +00007617 regprog_T *reg_prog; /* compiled regprog for pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007618 AutoCmd *cmds; /* list of commands to do */
7619 struct AutoPat *next; /* next AutoPat in AutoPat list */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007620 int group; /* group ID */
7621 int patlen; /* strlen() of pat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007622 int buflocal_nr; /* !=0 for buffer-local AutoPat */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007623 char allow_dirs; /* Pattern may match whole path */
7624 char last; /* last pattern for apply_autocmds() */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007625} AutoPat;
7626
7627static struct event_name
7628{
7629 char *name; /* event name */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007630 event_T event; /* event number */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007631} event_names[] =
7632{
7633 {"BufAdd", EVENT_BUFADD},
7634 {"BufCreate", EVENT_BUFADD},
7635 {"BufDelete", EVENT_BUFDELETE},
7636 {"BufEnter", EVENT_BUFENTER},
7637 {"BufFilePost", EVENT_BUFFILEPOST},
7638 {"BufFilePre", EVENT_BUFFILEPRE},
7639 {"BufHidden", EVENT_BUFHIDDEN},
7640 {"BufLeave", EVENT_BUFLEAVE},
7641 {"BufNew", EVENT_BUFNEW},
7642 {"BufNewFile", EVENT_BUFNEWFILE},
7643 {"BufRead", EVENT_BUFREADPOST},
7644 {"BufReadCmd", EVENT_BUFREADCMD},
7645 {"BufReadPost", EVENT_BUFREADPOST},
7646 {"BufReadPre", EVENT_BUFREADPRE},
7647 {"BufUnload", EVENT_BUFUNLOAD},
7648 {"BufWinEnter", EVENT_BUFWINENTER},
7649 {"BufWinLeave", EVENT_BUFWINLEAVE},
7650 {"BufWipeout", EVENT_BUFWIPEOUT},
7651 {"BufWrite", EVENT_BUFWRITEPRE},
7652 {"BufWritePost", EVENT_BUFWRITEPOST},
7653 {"BufWritePre", EVENT_BUFWRITEPRE},
7654 {"BufWriteCmd", EVENT_BUFWRITECMD},
7655 {"CmdwinEnter", EVENT_CMDWINENTER},
7656 {"CmdwinLeave", EVENT_CMDWINLEAVE},
Bram Moolenaard5005162014-08-22 23:05:54 +02007657 {"CmdUndefined", EVENT_CMDUNDEFINED},
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007658 {"ColorScheme", EVENT_COLORSCHEME},
Bram Moolenaarcfa3cae2012-07-10 17:14:56 +02007659 {"CompleteDone", EVENT_COMPLETEDONE},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007660 {"CursorHold", EVENT_CURSORHOLD},
7661 {"CursorHoldI", EVENT_CURSORHOLDI},
7662 {"CursorMoved", EVENT_CURSORMOVED},
7663 {"CursorMovedI", EVENT_CURSORMOVEDI},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007664 {"EncodingChanged", EVENT_ENCODINGCHANGED},
7665 {"FileEncoding", EVENT_ENCODINGCHANGED},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007666 {"FileAppendPost", EVENT_FILEAPPENDPOST},
7667 {"FileAppendPre", EVENT_FILEAPPENDPRE},
7668 {"FileAppendCmd", EVENT_FILEAPPENDCMD},
7669 {"FileChangedShell",EVENT_FILECHANGEDSHELL},
Bram Moolenaar56718732006-03-15 22:53:57 +00007670 {"FileChangedShellPost",EVENT_FILECHANGEDSHELLPOST},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007671 {"FileChangedRO", EVENT_FILECHANGEDRO},
7672 {"FileReadPost", EVENT_FILEREADPOST},
7673 {"FileReadPre", EVENT_FILEREADPRE},
7674 {"FileReadCmd", EVENT_FILEREADCMD},
7675 {"FileType", EVENT_FILETYPE},
7676 {"FileWritePost", EVENT_FILEWRITEPOST},
7677 {"FileWritePre", EVENT_FILEWRITEPRE},
7678 {"FileWriteCmd", EVENT_FILEWRITECMD},
7679 {"FilterReadPost", EVENT_FILTERREADPOST},
7680 {"FilterReadPre", EVENT_FILTERREADPRE},
7681 {"FilterWritePost", EVENT_FILTERWRITEPOST},
7682 {"FilterWritePre", EVENT_FILTERWRITEPRE},
7683 {"FocusGained", EVENT_FOCUSGAINED},
7684 {"FocusLost", EVENT_FOCUSLOST},
7685 {"FuncUndefined", EVENT_FUNCUNDEFINED},
7686 {"GUIEnter", EVENT_GUIENTER},
Bram Moolenaar265e5072006-08-29 16:13:22 +00007687 {"GUIFailed", EVENT_GUIFAILED},
Bram Moolenaar843ee412004-06-30 16:16:41 +00007688 {"InsertChange", EVENT_INSERTCHANGE},
7689 {"InsertEnter", EVENT_INSERTENTER},
7690 {"InsertLeave", EVENT_INSERTLEAVE},
Bram Moolenaare659c952011-05-19 17:25:41 +02007691 {"InsertCharPre", EVENT_INSERTCHARPRE},
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00007692 {"MenuPopup", EVENT_MENUPOPUP},
Bram Moolenaar53744302015-07-17 17:38:22 +02007693 {"OptionSet", EVENT_OPTIONSET},
Bram Moolenaar7c626922005-02-07 22:01:03 +00007694 {"QuickFixCmdPost", EVENT_QUICKFIXCMDPOST},
7695 {"QuickFixCmdPre", EVENT_QUICKFIXCMDPRE},
Bram Moolenaar3b53dfb2012-06-06 18:03:07 +02007696 {"QuitPre", EVENT_QUITPRE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007697 {"RemoteReply", EVENT_REMOTEREPLY},
Bram Moolenaar9372a112005-12-06 19:59:18 +00007698 {"SessionLoadPost", EVENT_SESSIONLOADPOST},
Bram Moolenaar5c4bab02006-03-10 21:37:46 +00007699 {"ShellCmdPost", EVENT_SHELLCMDPOST},
7700 {"ShellFilterPost", EVENT_SHELLFILTERPOST},
Bram Moolenaara2031822006-03-07 22:29:51 +00007701 {"SourcePre", EVENT_SOURCEPRE},
Bram Moolenaar8dd1aa52007-01-16 20:33:19 +00007702 {"SourceCmd", EVENT_SOURCECMD},
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00007703 {"SpellFileMissing",EVENT_SPELLFILEMISSING},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007704 {"StdinReadPost", EVENT_STDINREADPOST},
7705 {"StdinReadPre", EVENT_STDINREADPRE},
Bram Moolenaarb815dac2005-12-07 20:59:24 +00007706 {"SwapExists", EVENT_SWAPEXISTS},
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00007707 {"Syntax", EVENT_SYNTAX},
Bram Moolenaarc917da42016-07-19 22:31:36 +02007708 {"TabNew", EVENT_TABNEW},
Bram Moolenaar12c11d52016-07-19 23:13:03 +02007709 {"TabClosed", EVENT_TABCLOSED},
Bram Moolenaar70836c82006-02-20 21:28:49 +00007710 {"TabEnter", EVENT_TABENTER},
7711 {"TabLeave", EVENT_TABLEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007712 {"TermChanged", EVENT_TERMCHANGED},
7713 {"TermResponse", EVENT_TERMRESPONSE},
Bram Moolenaar186628f2013-03-19 13:33:23 +01007714 {"TextChanged", EVENT_TEXTCHANGED},
7715 {"TextChangedI", EVENT_TEXTCHANGEDI},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007716 {"User", EVENT_USER},
7717 {"VimEnter", EVENT_VIMENTER},
7718 {"VimLeave", EVENT_VIMLEAVE},
7719 {"VimLeavePre", EVENT_VIMLEAVEPRE},
Bram Moolenaarc917da42016-07-19 22:31:36 +02007720 {"WinNew", EVENT_WINNEW},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007721 {"WinEnter", EVENT_WINENTER},
7722 {"WinLeave", EVENT_WINLEAVE},
Bram Moolenaar56718732006-03-15 22:53:57 +00007723 {"VimResized", EVENT_VIMRESIZED},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007724 {NULL, (event_T)0}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007725};
7726
7727static AutoPat *first_autopat[NUM_EVENTS] =
7728{
7729 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7730 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7731 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7732 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00007733 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaar53744302015-07-17 17:38:22 +02007734 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007735};
7736
7737/*
7738 * struct used to keep status while executing autocommands for an event.
7739 */
7740typedef struct AutoPatCmd
7741{
7742 AutoPat *curpat; /* next AutoPat to examine */
7743 AutoCmd *nextcmd; /* next AutoCmd to execute */
7744 int group; /* group being used */
7745 char_u *fname; /* fname to match with */
7746 char_u *sfname; /* sfname to match with */
7747 char_u *tail; /* tail of fname */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007748 event_T event; /* current event */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007749 int arg_bufnr; /* initially equal to <abuf>, set to zero when
7750 buf is deleted */
7751 struct AutoPatCmd *next; /* chain of active apc-s for auto-invalidation*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00007752} AutoPatCmd;
7753
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007754static AutoPatCmd *active_apc_list = NULL; /* stack of active autocommands */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007755
Bram Moolenaar071d4272004-06-13 20:20:40 +00007756/*
7757 * augroups stores a list of autocmd group names.
7758 */
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007759static garray_T augroups = {0, 0, sizeof(char_u *), 10, NULL};
Bram Moolenaar071d4272004-06-13 20:20:40 +00007760#define AUGROUP_NAME(i) (((char_u **)augroups.ga_data)[i])
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02007761static char_u *deleted_augroup = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007762
7763/*
7764 * The ID of the current group. Group 0 is the default one.
7765 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007766static int current_augroup = AUGROUP_DEFAULT;
7767
7768static int au_need_clean = FALSE; /* need to delete marked patterns */
7769
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007770static void show_autocmd(AutoPat *ap, event_T event);
7771static void au_remove_pat(AutoPat *ap);
7772static void au_remove_cmds(AutoPat *ap);
7773static void au_cleanup(void);
7774static int au_new_group(char_u *name);
7775static void au_del_group(char_u *name);
7776static event_T event_name2nr(char_u *start, char_u **end);
7777static char_u *event_nr2name(event_T event);
7778static char_u *find_end_event(char_u *arg, int have_group);
7779static int event_ignored(event_T event);
7780static int au_get_grouparg(char_u **argp);
7781static int do_autocmd_event(event_T event, char_u *pat, int nested, char_u *cmd, int forceit, int group);
7782static int apply_autocmds_group(event_T event, char_u *fname, char_u *fname_io, int force, int group, buf_T *buf, exarg_T *eap);
7783static void auto_next_pat(AutoPatCmd *apc, int stop_at_last);
Bram Moolenaardffa5b82014-11-19 16:38:07 +01007784#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN)
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007785static int match_file_pat(char_u *pattern, regprog_T **prog, char_u *fname, char_u *sfname, char_u *tail, int allow_dirs);
Bram Moolenaardffa5b82014-11-19 16:38:07 +01007786#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007787
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007788
Bram Moolenaar754b5602006-02-09 23:53:20 +00007789static event_T last_event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007790static int last_group;
Bram Moolenaar78ab3312007-09-29 12:16:41 +00007791static int autocmd_blocked = 0; /* block all autocmds */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007792
7793/*
7794 * Show the autocommands for one AutoPat.
7795 */
7796 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007797show_autocmd(AutoPat *ap, event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007798{
7799 AutoCmd *ac;
7800
7801 /* Check for "got_int" (here and at various places below), which is set
7802 * when "q" has been hit for the "--more--" prompt */
7803 if (got_int)
7804 return;
7805 if (ap->pat == NULL) /* pattern has been removed */
7806 return;
7807
7808 msg_putchar('\n');
7809 if (got_int)
7810 return;
7811 if (event != last_event || ap->group != last_group)
7812 {
7813 if (ap->group != AUGROUP_DEFAULT)
7814 {
7815 if (AUGROUP_NAME(ap->group) == NULL)
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02007816 msg_puts_attr(deleted_augroup, hl_attr(HLF_E));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007817 else
7818 msg_puts_attr(AUGROUP_NAME(ap->group), hl_attr(HLF_T));
7819 msg_puts((char_u *)" ");
7820 }
7821 msg_puts_attr(event_nr2name(event), hl_attr(HLF_T));
7822 last_event = event;
7823 last_group = ap->group;
7824 msg_putchar('\n');
7825 if (got_int)
7826 return;
7827 }
7828 msg_col = 4;
7829 msg_outtrans(ap->pat);
7830
7831 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7832 {
7833 if (ac->cmd != NULL) /* skip removed commands */
7834 {
7835 if (msg_col >= 14)
7836 msg_putchar('\n');
7837 msg_col = 14;
7838 if (got_int)
7839 return;
7840 msg_outtrans(ac->cmd);
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00007841#ifdef FEAT_EVAL
7842 if (p_verbose > 0)
7843 last_set_msg(ac->scriptID);
7844#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007845 if (got_int)
7846 return;
7847 if (ac->next != NULL)
7848 {
7849 msg_putchar('\n');
7850 if (got_int)
7851 return;
7852 }
7853 }
7854 }
7855}
7856
7857/*
7858 * Mark an autocommand pattern for deletion.
7859 */
7860 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007861au_remove_pat(AutoPat *ap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007862{
7863 vim_free(ap->pat);
7864 ap->pat = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007865 ap->buflocal_nr = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007866 au_need_clean = TRUE;
7867}
7868
7869/*
7870 * Mark all commands for a pattern for deletion.
7871 */
7872 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007873au_remove_cmds(AutoPat *ap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007874{
7875 AutoCmd *ac;
7876
7877 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7878 {
7879 vim_free(ac->cmd);
7880 ac->cmd = NULL;
7881 }
7882 au_need_clean = TRUE;
7883}
7884
7885/*
7886 * Cleanup autocommands and patterns that have been deleted.
7887 * This is only done when not executing autocommands.
7888 */
7889 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007890au_cleanup(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007891{
7892 AutoPat *ap, **prev_ap;
7893 AutoCmd *ac, **prev_ac;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007894 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007895
7896 if (autocmd_busy || !au_need_clean)
7897 return;
7898
7899 /* loop over all events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007900 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7901 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007902 {
7903 /* loop over all autocommand patterns */
7904 prev_ap = &(first_autopat[(int)event]);
7905 for (ap = *prev_ap; ap != NULL; ap = *prev_ap)
7906 {
7907 /* loop over all commands for this pattern */
7908 prev_ac = &(ap->cmds);
7909 for (ac = *prev_ac; ac != NULL; ac = *prev_ac)
7910 {
7911 /* remove the command if the pattern is to be deleted or when
7912 * the command has been marked for deletion */
7913 if (ap->pat == NULL || ac->cmd == NULL)
7914 {
7915 *prev_ac = ac->next;
7916 vim_free(ac->cmd);
7917 vim_free(ac);
7918 }
7919 else
7920 prev_ac = &(ac->next);
7921 }
7922
7923 /* remove the pattern if it has been marked for deletion */
7924 if (ap->pat == NULL)
7925 {
7926 *prev_ap = ap->next;
Bram Moolenaar473de612013-06-08 18:19:48 +02007927 vim_regfree(ap->reg_prog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007928 vim_free(ap);
7929 }
7930 else
7931 prev_ap = &(ap->next);
7932 }
7933 }
7934
7935 au_need_clean = FALSE;
7936}
7937
7938/*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007939 * Called when buffer is freed, to remove/invalidate related buffer-local
7940 * autocmds.
7941 */
7942 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007943aubuflocal_remove(buf_T *buf)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007944{
7945 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007946 event_T event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007947 AutoPatCmd *apc;
7948
7949 /* invalidate currently executing autocommands */
7950 for (apc = active_apc_list; apc; apc = apc->next)
7951 if (buf->b_fnum == apc->arg_bufnr)
7952 apc->arg_bufnr = 0;
7953
7954 /* invalidate buflocals looping through events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007955 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7956 event = (event_T)((int)event + 1))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007957 /* loop over all autocommand patterns */
7958 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
7959 if (ap->buflocal_nr == buf->b_fnum)
7960 {
7961 au_remove_pat(ap);
7962 if (p_verbose >= 6)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007963 {
7964 verbose_enter();
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007965 smsg((char_u *)
7966 _("auto-removing autocommand: %s <buffer=%d>"),
7967 event_nr2name(event), buf->b_fnum);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007968 verbose_leave();
7969 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007970 }
7971 au_cleanup();
7972}
7973
7974/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007975 * Add an autocmd group name.
7976 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
7977 */
7978 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007979au_new_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007980{
7981 int i;
7982
7983 i = au_find_group(name);
7984 if (i == AUGROUP_ERROR) /* the group doesn't exist yet, add it */
7985 {
7986 /* First try using a free entry. */
7987 for (i = 0; i < augroups.ga_len; ++i)
7988 if (AUGROUP_NAME(i) == NULL)
7989 break;
7990 if (i == augroups.ga_len && ga_grow(&augroups, 1) == FAIL)
7991 return AUGROUP_ERROR;
7992
7993 AUGROUP_NAME(i) = vim_strsave(name);
7994 if (AUGROUP_NAME(i) == NULL)
7995 return AUGROUP_ERROR;
7996 if (i == augroups.ga_len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007997 ++augroups.ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007998 }
7999
8000 return i;
8001}
8002
8003 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008004au_del_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008005{
8006 int i;
8007
8008 i = au_find_group(name);
8009 if (i == AUGROUP_ERROR) /* the group doesn't exist */
8010 EMSG2(_("E367: No such group: \"%s\""), name);
8011 else
8012 {
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008013 event_T event;
8014 AutoPat *ap;
8015 int in_use = FALSE;
8016
8017 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8018 event = (event_T)((int)event + 1))
8019 {
8020 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8021 if (ap->group == i)
8022 {
8023 give_warning((char_u *)_("W19: Deleting augroup that is still in use"), TRUE);
8024 in_use = TRUE;
8025 event = NUM_EVENTS;
8026 break;
8027 }
8028 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008029 vim_free(AUGROUP_NAME(i));
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008030 if (in_use)
8031 {
8032 if (deleted_augroup == NULL)
8033 deleted_augroup = (char_u *)_("--Deleted--");
8034 AUGROUP_NAME(i) = deleted_augroup;
8035 }
8036 else
8037 AUGROUP_NAME(i) = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008038 }
8039}
8040
8041/*
8042 * Find the ID of an autocmd group name.
8043 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
8044 */
8045 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008046au_find_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008047{
8048 int i;
8049
8050 for (i = 0; i < augroups.ga_len; ++i)
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008051 if (AUGROUP_NAME(i) != NULL && AUGROUP_NAME(i) != deleted_augroup
8052 && STRCMP(AUGROUP_NAME(i), name) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008053 return i;
8054 return AUGROUP_ERROR;
8055}
8056
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008057/*
8058 * Return TRUE if augroup "name" exists.
8059 */
8060 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008061au_has_group(char_u *name)
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008062{
8063 return au_find_group(name) != AUGROUP_ERROR;
8064}
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008065
Bram Moolenaar071d4272004-06-13 20:20:40 +00008066/*
8067 * ":augroup {name}".
8068 */
8069 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008070do_augroup(char_u *arg, int del_group)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008071{
8072 int i;
8073
8074 if (del_group)
8075 {
8076 if (*arg == NUL)
8077 EMSG(_(e_argreq));
8078 else
8079 au_del_group(arg);
8080 }
8081 else if (STRICMP(arg, "end") == 0) /* ":aug end": back to group 0 */
8082 current_augroup = AUGROUP_DEFAULT;
8083 else if (*arg) /* ":aug xxx": switch to group xxx */
8084 {
8085 i = au_new_group(arg);
8086 if (i != AUGROUP_ERROR)
8087 current_augroup = i;
8088 }
8089 else /* ":aug": list the group names */
8090 {
8091 msg_start();
8092 for (i = 0; i < augroups.ga_len; ++i)
8093 {
8094 if (AUGROUP_NAME(i) != NULL)
8095 {
8096 msg_puts(AUGROUP_NAME(i));
8097 msg_puts((char_u *)" ");
8098 }
8099 }
8100 msg_clr_eos();
8101 msg_end();
8102 }
8103}
8104
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008105#if defined(EXITFREE) || defined(PROTO)
8106 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008107free_all_autocmds(void)
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008108{
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008109 int i;
8110 char_u *s;
8111
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008112 for (current_augroup = -1; current_augroup < augroups.ga_len;
8113 ++current_augroup)
8114 do_autocmd((char_u *)"", TRUE);
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008115
8116 for (i = 0; i < augroups.ga_len; ++i)
8117 {
8118 s = ((char_u **)(augroups.ga_data))[i];
8119 if (s != deleted_augroup)
8120 vim_free(s);
8121 }
8122 ga_clear(&augroups);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008123}
8124#endif
8125
Bram Moolenaar071d4272004-06-13 20:20:40 +00008126/*
8127 * Return the event number for event name "start".
8128 * Return NUM_EVENTS if the event name was not found.
8129 * Return a pointer to the next event name in "end".
8130 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008131 static event_T
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008132event_name2nr(char_u *start, char_u **end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008133{
8134 char_u *p;
8135 int i;
8136 int len;
8137
Bram Moolenaare99e8442016-07-26 20:43:40 +02008138 /* the event name ends with end of line, '|', a blank or a comma */
8139 for (p = start; *p && !vim_iswhite(*p) && *p != ',' && *p != '|'; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008140 ;
8141 for (i = 0; event_names[i].name != NULL; ++i)
8142 {
8143 len = (int)STRLEN(event_names[i].name);
8144 if (len == p - start && STRNICMP(event_names[i].name, start, len) == 0)
8145 break;
8146 }
8147 if (*p == ',')
8148 ++p;
8149 *end = p;
8150 if (event_names[i].name == NULL)
8151 return NUM_EVENTS;
8152 return event_names[i].event;
8153}
8154
8155/*
8156 * Return the name for event "event".
8157 */
8158 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008159event_nr2name(event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008160{
8161 int i;
8162
8163 for (i = 0; event_names[i].name != NULL; ++i)
8164 if (event_names[i].event == event)
8165 return (char_u *)event_names[i].name;
8166 return (char_u *)"Unknown";
8167}
8168
8169/*
8170 * Scan over the events. "*" stands for all events.
8171 */
8172 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008173find_end_event(
8174 char_u *arg,
8175 int have_group) /* TRUE when group name was found */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008176{
8177 char_u *pat;
8178 char_u *p;
8179
8180 if (*arg == '*')
8181 {
8182 if (arg[1] && !vim_iswhite(arg[1]))
8183 {
8184 EMSG2(_("E215: Illegal character after *: %s"), arg);
8185 return NULL;
8186 }
8187 pat = arg + 1;
8188 }
8189 else
8190 {
Bram Moolenaare99e8442016-07-26 20:43:40 +02008191 for (pat = arg; *pat && *pat != '|' && !vim_iswhite(*pat); pat = p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008192 {
8193 if ((int)event_name2nr(pat, &p) >= (int)NUM_EVENTS)
8194 {
8195 if (have_group)
8196 EMSG2(_("E216: No such event: %s"), pat);
8197 else
8198 EMSG2(_("E216: No such group or event: %s"), pat);
8199 return NULL;
8200 }
8201 }
8202 }
8203 return pat;
8204}
8205
8206/*
8207 * Return TRUE if "event" is included in 'eventignore'.
8208 */
8209 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008210event_ignored(event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008211{
8212 char_u *p = p_ei;
8213
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008214 while (*p != NUL)
8215 {
8216 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8217 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008218 if (event_name2nr(p, &p) == event)
8219 return TRUE;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008220 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008221
8222 return FALSE;
8223}
8224
8225/*
8226 * Return OK when the contents of p_ei is valid, FAIL otherwise.
8227 */
8228 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008229check_ei(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008230{
8231 char_u *p = p_ei;
8232
Bram Moolenaar071d4272004-06-13 20:20:40 +00008233 while (*p)
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008234 {
8235 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8236 {
8237 p += 3;
8238 if (*p == ',')
8239 ++p;
8240 }
8241 else if (event_name2nr(p, &p) == NUM_EVENTS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008242 return FAIL;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008243 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008244
8245 return OK;
8246}
8247
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008248# if defined(FEAT_SYN_HL) || defined(PROTO)
8249
8250/*
8251 * Add "what" to 'eventignore' to skip loading syntax highlighting for every
8252 * buffer loaded into the window. "what" must start with a comma.
8253 * Returns the old value of 'eventignore' in allocated memory.
8254 */
8255 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008256au_event_disable(char *what)
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008257{
8258 char_u *new_ei;
8259 char_u *save_ei;
8260
8261 save_ei = vim_strsave(p_ei);
8262 if (save_ei != NULL)
8263 {
Bram Moolenaara5792f52005-11-23 21:25:05 +00008264 new_ei = vim_strnsave(p_ei, (int)(STRLEN(p_ei) + STRLEN(what)));
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008265 if (new_ei != NULL)
8266 {
Bram Moolenaar8cac9fd2010-03-02 12:48:05 +01008267 if (*what == ',' && *p_ei == NUL)
8268 STRCPY(new_ei, what + 1);
8269 else
8270 STRCAT(new_ei, what);
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008271 set_string_option_direct((char_u *)"ei", -1, new_ei,
8272 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008273 vim_free(new_ei);
8274 }
8275 }
8276 return save_ei;
8277}
8278
8279 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008280au_event_restore(char_u *old_ei)
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008281{
8282 if (old_ei != NULL)
8283 {
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008284 set_string_option_direct((char_u *)"ei", -1, old_ei,
8285 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008286 vim_free(old_ei);
8287 }
8288}
8289# endif /* FEAT_SYN_HL */
8290
Bram Moolenaar071d4272004-06-13 20:20:40 +00008291/*
8292 * do_autocmd() -- implements the :autocmd command. Can be used in the
8293 * following ways:
8294 *
8295 * :autocmd <event> <pat> <cmd> Add <cmd> to the list of commands that
8296 * will be automatically executed for <event>
8297 * when editing a file matching <pat>, in
8298 * the current group.
8299 * :autocmd <event> <pat> Show the auto-commands associated with
8300 * <event> and <pat>.
8301 * :autocmd <event> Show the auto-commands associated with
8302 * <event>.
8303 * :autocmd Show all auto-commands.
8304 * :autocmd! <event> <pat> <cmd> Remove all auto-commands associated with
8305 * <event> and <pat>, and add the command
8306 * <cmd>, for the current group.
8307 * :autocmd! <event> <pat> Remove all auto-commands associated with
8308 * <event> and <pat> for the current group.
8309 * :autocmd! <event> Remove all auto-commands associated with
8310 * <event> for the current group.
8311 * :autocmd! Remove ALL auto-commands for the current
8312 * group.
8313 *
8314 * Multiple events and patterns may be given separated by commas. Here are
8315 * some examples:
8316 * :autocmd bufread,bufenter *.c,*.h set tw=0 smartindent noic
8317 * :autocmd bufleave * set tw=79 nosmartindent ic infercase
8318 *
8319 * :autocmd * *.c show all autocommands for *.c files.
Bram Moolenaard35f9712005-12-18 22:02:33 +00008320 *
8321 * Mostly a {group} argument can optionally appear before <event>.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008322 */
8323 void
Bram Moolenaare99e8442016-07-26 20:43:40 +02008324do_autocmd(char_u *arg_in, int forceit)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008325{
Bram Moolenaare99e8442016-07-26 20:43:40 +02008326 char_u *arg = arg_in;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008327 char_u *pat;
8328 char_u *envpat = NULL;
8329 char_u *cmd;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008330 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008331 int need_free = FALSE;
8332 int nested = FALSE;
8333 int group;
8334
Bram Moolenaare99e8442016-07-26 20:43:40 +02008335 if (*arg == '|')
8336 {
8337 arg = (char_u *)"";
8338 group = AUGROUP_ALL; /* no argument, use all groups */
8339 }
8340 else
8341 {
8342 /*
8343 * Check for a legal group name. If not, use AUGROUP_ALL.
8344 */
8345 group = au_get_grouparg(&arg);
8346 if (arg == NULL) /* out of memory */
8347 return;
8348 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008349
8350 /*
8351 * Scan over the events.
8352 * If we find an illegal name, return here, don't do anything.
8353 */
8354 pat = find_end_event(arg, group != AUGROUP_ALL);
8355 if (pat == NULL)
8356 return;
8357
Bram Moolenaar071d4272004-06-13 20:20:40 +00008358 pat = skipwhite(pat);
Bram Moolenaare99e8442016-07-26 20:43:40 +02008359 if (*pat == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008360 {
Bram Moolenaare99e8442016-07-26 20:43:40 +02008361 pat = (char_u *)"";
8362 cmd = (char_u *)"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00008363 }
Bram Moolenaare99e8442016-07-26 20:43:40 +02008364 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00008365 {
Bram Moolenaare99e8442016-07-26 20:43:40 +02008366 /*
8367 * Scan over the pattern. Put a NUL at the end.
8368 */
8369 cmd = pat;
8370 while (*cmd && (!vim_iswhite(*cmd) || cmd[-1] == '\\'))
8371 cmd++;
8372 if (*cmd)
8373 *cmd++ = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008374
Bram Moolenaare99e8442016-07-26 20:43:40 +02008375 /* Expand environment variables in the pattern. Set 'shellslash', we want
8376 * forward slashes here. */
8377 if (vim_strchr(pat, '$') != NULL || vim_strchr(pat, '~') != NULL)
8378 {
8379#ifdef BACKSLASH_IN_FILENAME
8380 int p_ssl_save = p_ssl;
8381
8382 p_ssl = TRUE;
8383#endif
8384 envpat = expand_env_save(pat);
8385#ifdef BACKSLASH_IN_FILENAME
8386 p_ssl = p_ssl_save;
8387#endif
8388 if (envpat != NULL)
8389 pat = envpat;
8390 }
8391
8392 /*
8393 * Check for "nested" flag.
8394 */
8395 cmd = skipwhite(cmd);
8396 if (*cmd != NUL && STRNCMP(cmd, "nested", 6) == 0 && vim_iswhite(cmd[6]))
8397 {
8398 nested = TRUE;
8399 cmd = skipwhite(cmd + 6);
8400 }
8401
8402 /*
8403 * Find the start of the commands.
8404 * Expand <sfile> in it.
8405 */
8406 if (*cmd != NUL)
8407 {
8408 cmd = expand_sfile(cmd);
8409 if (cmd == NULL) /* some error */
8410 return;
8411 need_free = TRUE;
8412 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008413 }
8414
8415 /*
8416 * Print header when showing autocommands.
8417 */
8418 if (!forceit && *cmd == NUL)
8419 {
8420 /* Highlight title */
8421 MSG_PUTS_TITLE(_("\n--- Auto-Commands ---"));
8422 }
8423
8424 /*
8425 * Loop over the events.
8426 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008427 last_event = (event_T)-1; /* for listing the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008428 last_group = AUGROUP_ERROR; /* for listing the group name */
Bram Moolenaare99e8442016-07-26 20:43:40 +02008429 if (*arg == '*' || *arg == NUL || *arg == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008430 {
Bram Moolenaar754b5602006-02-09 23:53:20 +00008431 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8432 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008433 if (do_autocmd_event(event, pat,
8434 nested, cmd, forceit, group) == FAIL)
8435 break;
8436 }
8437 else
8438 {
Bram Moolenaare99e8442016-07-26 20:43:40 +02008439 while (*arg && *arg != '|' && !vim_iswhite(*arg))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008440 if (do_autocmd_event(event_name2nr(arg, &arg), pat,
8441 nested, cmd, forceit, group) == FAIL)
8442 break;
8443 }
8444
8445 if (need_free)
8446 vim_free(cmd);
8447 vim_free(envpat);
8448}
8449
8450/*
8451 * Find the group ID in a ":autocmd" or ":doautocmd" argument.
8452 * The "argp" argument is advanced to the following argument.
8453 *
8454 * Returns the group ID, AUGROUP_ERROR for error (out of memory).
8455 */
8456 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008457au_get_grouparg(char_u **argp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008458{
8459 char_u *group_name;
8460 char_u *p;
8461 char_u *arg = *argp;
8462 int group = AUGROUP_ALL;
8463
Bram Moolenaare99e8442016-07-26 20:43:40 +02008464 for (p = arg; *p && !vim_iswhite(*p) && *p != '|'; ++p)
8465 ;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008466 if (p > arg)
8467 {
8468 group_name = vim_strnsave(arg, (int)(p - arg));
8469 if (group_name == NULL) /* out of memory */
8470 return AUGROUP_ERROR;
8471 group = au_find_group(group_name);
8472 if (group == AUGROUP_ERROR)
8473 group = AUGROUP_ALL; /* no match, use all groups */
8474 else
8475 *argp = skipwhite(p); /* match, skip over group name */
8476 vim_free(group_name);
8477 }
8478 return group;
8479}
8480
8481/*
8482 * do_autocmd() for one event.
8483 * If *pat == NUL do for all patterns.
8484 * If *cmd == NUL show entries.
8485 * If forceit == TRUE delete entries.
8486 * If group is not AUGROUP_ALL, only use this group.
8487 */
8488 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008489do_autocmd_event(
8490 event_T event,
8491 char_u *pat,
8492 int nested,
8493 char_u *cmd,
8494 int forceit,
8495 int group)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008496{
8497 AutoPat *ap;
8498 AutoPat **prev_ap;
8499 AutoCmd *ac;
8500 AutoCmd **prev_ac;
8501 int brace_level;
8502 char_u *endpat;
8503 int findgroup;
8504 int allgroups;
8505 int patlen;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00008506 int is_buflocal;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008507 int buflocal_nr;
8508 char_u buflocal_pat[25]; /* for "<buffer=X>" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008509
8510 if (group == AUGROUP_ALL)
8511 findgroup = current_augroup;
8512 else
8513 findgroup = group;
8514 allgroups = (group == AUGROUP_ALL && !forceit && *cmd == NUL);
8515
8516 /*
8517 * Show or delete all patterns for an event.
8518 */
8519 if (*pat == NUL)
8520 {
8521 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8522 {
8523 if (forceit) /* delete the AutoPat, if it's in the current group */
8524 {
8525 if (ap->group == findgroup)
8526 au_remove_pat(ap);
8527 }
8528 else if (group == AUGROUP_ALL || ap->group == group)
8529 show_autocmd(ap, event);
8530 }
8531 }
8532
8533 /*
8534 * Loop through all the specified patterns.
8535 */
8536 for ( ; *pat; pat = (*endpat == ',' ? endpat + 1 : endpat))
8537 {
8538 /*
8539 * Find end of the pattern.
8540 * Watch out for a comma in braces, like "*.\{obj,o\}".
8541 */
8542 brace_level = 0;
8543 for (endpat = pat; *endpat && (*endpat != ',' || brace_level
Bram Moolenaar6b9be1b2015-07-28 13:33:45 +02008544 || (endpat > pat && endpat[-1] == '\\')); ++endpat)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008545 {
8546 if (*endpat == '{')
8547 brace_level++;
8548 else if (*endpat == '}')
8549 brace_level--;
8550 }
8551 if (pat == endpat) /* ignore single comma */
8552 continue;
8553 patlen = (int)(endpat - pat);
8554
8555 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008556 * detect special <buflocal[=X]> buffer-local patterns
8557 */
8558 is_buflocal = FALSE;
8559 buflocal_nr = 0;
8560
Bram Moolenaar1e997822015-02-17 16:04:57 +01008561 if (patlen >= 8 && STRNCMP(pat, "<buffer", 7) == 0
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008562 && pat[patlen - 1] == '>')
8563 {
Bram Moolenaar1e997822015-02-17 16:04:57 +01008564 /* "<buffer...>": Error will be printed only for addition.
8565 * printing and removing will proceed silently. */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008566 is_buflocal = TRUE;
8567 if (patlen == 8)
Bram Moolenaar1e997822015-02-17 16:04:57 +01008568 /* "<buffer>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008569 buflocal_nr = curbuf->b_fnum;
8570 else if (patlen > 9 && pat[7] == '=')
8571 {
Bram Moolenaar1e997822015-02-17 16:04:57 +01008572 if (patlen == 13 && STRNICMP(pat, "<buffer=abuf>", 13) == 0)
8573 /* "<buffer=abuf>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008574 buflocal_nr = autocmd_bufnr;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008575 else if (skipdigits(pat + 8) == pat + patlen - 1)
Bram Moolenaar1e997822015-02-17 16:04:57 +01008576 /* "<buffer=123>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008577 buflocal_nr = atoi((char *)pat + 8);
8578 }
8579 }
8580
8581 if (is_buflocal)
8582 {
8583 /* normalize pat into standard "<buffer>#N" form */
8584 sprintf((char *)buflocal_pat, "<buffer=%d>", buflocal_nr);
8585 pat = buflocal_pat; /* can modify pat and patlen */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008586 patlen = (int)STRLEN(buflocal_pat); /* but not endpat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008587 }
8588
8589 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008590 * Find AutoPat entries with this pattern.
8591 */
8592 prev_ap = &first_autopat[(int)event];
8593 while ((ap = *prev_ap) != NULL)
8594 {
8595 if (ap->pat != NULL)
8596 {
8597 /* Accept a pattern when:
8598 * - a group was specified and it's that group, or a group was
8599 * not specified and it's the current group, or a group was
8600 * not specified and we are listing
8601 * - the length of the pattern matches
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008602 * - the pattern matches.
8603 * For <buffer[=X]>, this condition works because we normalize
8604 * all buffer-local patterns.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008605 */
8606 if ((allgroups || ap->group == findgroup)
8607 && ap->patlen == patlen
8608 && STRNCMP(pat, ap->pat, patlen) == 0)
8609 {
8610 /*
8611 * Remove existing autocommands.
8612 * If adding any new autocmd's for this AutoPat, don't
8613 * delete the pattern from the autopat list, append to
8614 * this list.
8615 */
8616 if (forceit)
8617 {
8618 if (*cmd != NUL && ap->next == NULL)
8619 {
8620 au_remove_cmds(ap);
8621 break;
8622 }
8623 au_remove_pat(ap);
8624 }
8625
8626 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008627 * Show autocmd's for this autopat, or buflocals <buffer=X>
Bram Moolenaar071d4272004-06-13 20:20:40 +00008628 */
8629 else if (*cmd == NUL)
8630 show_autocmd(ap, event);
8631
8632 /*
8633 * Add autocmd to this autopat, if it's the last one.
8634 */
8635 else if (ap->next == NULL)
8636 break;
8637 }
8638 }
8639 prev_ap = &ap->next;
8640 }
8641
8642 /*
8643 * Add a new command.
8644 */
8645 if (*cmd != NUL)
8646 {
8647 /*
8648 * If the pattern we want to add a command to does appear at the
8649 * end of the list (or not is not in the list at all), add the
8650 * pattern at the end of the list.
8651 */
8652 if (ap == NULL)
8653 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008654 /* refuse to add buffer-local ap if buffer number is invalid */
8655 if (is_buflocal && (buflocal_nr == 0
8656 || buflist_findnr(buflocal_nr) == NULL))
8657 {
8658 EMSGN(_("E680: <buffer=%d>: invalid buffer number "),
8659 buflocal_nr);
8660 return FAIL;
8661 }
8662
Bram Moolenaar071d4272004-06-13 20:20:40 +00008663 ap = (AutoPat *)alloc((unsigned)sizeof(AutoPat));
8664 if (ap == NULL)
8665 return FAIL;
8666 ap->pat = vim_strnsave(pat, patlen);
8667 ap->patlen = patlen;
8668 if (ap->pat == NULL)
8669 {
8670 vim_free(ap);
8671 return FAIL;
8672 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008673
8674 if (is_buflocal)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008675 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008676 ap->buflocal_nr = buflocal_nr;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008677 ap->reg_prog = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008678 }
8679 else
8680 {
Bram Moolenaar748bf032005-02-02 23:04:36 +00008681 char_u *reg_pat;
8682
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008683 ap->buflocal_nr = 0;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008684 reg_pat = file_pat_to_reg_pat(pat, endpat,
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008685 &ap->allow_dirs, TRUE);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008686 if (reg_pat != NULL)
8687 ap->reg_prog = vim_regcomp(reg_pat, RE_MAGIC);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008688 vim_free(reg_pat);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008689 if (reg_pat == NULL || ap->reg_prog == NULL)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008690 {
8691 vim_free(ap->pat);
8692 vim_free(ap);
8693 return FAIL;
8694 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008695 }
8696 ap->cmds = NULL;
8697 *prev_ap = ap;
8698 ap->next = NULL;
8699 if (group == AUGROUP_ALL)
8700 ap->group = current_augroup;
8701 else
8702 ap->group = group;
8703 }
8704
8705 /*
8706 * Add the autocmd at the end of the AutoCmd list.
8707 */
8708 prev_ac = &(ap->cmds);
8709 while ((ac = *prev_ac) != NULL)
8710 prev_ac = &ac->next;
8711 ac = (AutoCmd *)alloc((unsigned)sizeof(AutoCmd));
8712 if (ac == NULL)
8713 return FAIL;
8714 ac->cmd = vim_strsave(cmd);
8715#ifdef FEAT_EVAL
8716 ac->scriptID = current_SID;
8717#endif
8718 if (ac->cmd == NULL)
8719 {
8720 vim_free(ac);
8721 return FAIL;
8722 }
8723 ac->next = NULL;
8724 *prev_ac = ac;
8725 ac->nested = nested;
8726 }
8727 }
8728
8729 au_cleanup(); /* may really delete removed patterns/commands now */
8730 return OK;
8731}
8732
8733/*
8734 * Implementation of ":doautocmd [group] event [fname]".
8735 * Return OK for success, FAIL for failure;
8736 */
8737 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008738do_doautocmd(
8739 char_u *arg,
Bram Moolenaar1610d052016-06-09 22:53:01 +02008740 int do_msg, /* give message for no matching autocmds? */
8741 int *did_something)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008742{
8743 char_u *fname;
8744 int nothing_done = TRUE;
8745 int group;
8746
Bram Moolenaar1610d052016-06-09 22:53:01 +02008747 if (did_something != NULL)
Bram Moolenaar76ae22f2016-06-13 20:00:29 +02008748 *did_something = FALSE;
Bram Moolenaar1610d052016-06-09 22:53:01 +02008749
Bram Moolenaar071d4272004-06-13 20:20:40 +00008750 /*
8751 * Check for a legal group name. If not, use AUGROUP_ALL.
8752 */
8753 group = au_get_grouparg(&arg);
8754 if (arg == NULL) /* out of memory */
8755 return FAIL;
8756
8757 if (*arg == '*')
8758 {
8759 EMSG(_("E217: Can't execute autocommands for ALL events"));
8760 return FAIL;
8761 }
8762
8763 /*
8764 * Scan over the events.
8765 * If we find an illegal name, return here, don't do anything.
8766 */
8767 fname = find_end_event(arg, group != AUGROUP_ALL);
8768 if (fname == NULL)
8769 return FAIL;
8770
8771 fname = skipwhite(fname);
8772
8773 /*
8774 * Loop over the events.
8775 */
8776 while (*arg && !vim_iswhite(*arg))
8777 if (apply_autocmds_group(event_name2nr(arg, &arg),
8778 fname, NULL, TRUE, group, curbuf, NULL))
8779 nothing_done = FALSE;
8780
8781 if (nothing_done && do_msg)
8782 MSG(_("No matching autocommands"));
Bram Moolenaar1610d052016-06-09 22:53:01 +02008783 if (did_something != NULL)
8784 *did_something = !nothing_done;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008785
8786#ifdef FEAT_EVAL
8787 return aborting() ? FAIL : OK;
8788#else
8789 return OK;
8790#endif
8791}
8792
8793/*
8794 * ":doautoall": execute autocommands for each loaded buffer.
8795 */
8796 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008797ex_doautoall(exarg_T *eap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008798{
8799 int retval;
8800 aco_save_T aco;
8801 buf_T *buf;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008802 bufref_T bufref;
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008803 char_u *arg = eap->arg;
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008804 int call_do_modelines = check_nomodeline(&arg);
Bram Moolenaar1610d052016-06-09 22:53:01 +02008805 int did_aucmd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008806
8807 /*
8808 * This is a bit tricky: For some commands curwin->w_buffer needs to be
8809 * equal to curbuf, but for some buffers there may not be a window.
8810 * So we change the buffer for the current window for a moment. This
8811 * gives problems when the autocommands make changes to the list of
8812 * buffers or windows...
8813 */
Bram Moolenaar29323592016-07-24 22:04:11 +02008814 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008815 {
Bram Moolenaar3a847972008-07-08 09:36:58 +00008816 if (buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008817 {
8818 /* find a window for this buffer and save some values */
8819 aucmd_prepbuf(&aco, buf);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008820 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008821
8822 /* execute the autocommands for this buffer */
Bram Moolenaar1610d052016-06-09 22:53:01 +02008823 retval = do_doautocmd(arg, FALSE, &did_aucmd);
Bram Moolenaareeefcc72007-05-01 21:21:21 +00008824
Bram Moolenaar1610d052016-06-09 22:53:01 +02008825 if (call_do_modelines && did_aucmd)
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008826 {
8827 /* Execute the modeline settings, but don't set window-local
8828 * options if we are using the current window for another
8829 * buffer. */
8830 do_modelines(curwin == aucmd_win ? OPT_NOWIN : 0);
8831 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008832
8833 /* restore the current window */
8834 aucmd_restbuf(&aco);
8835
8836 /* stop if there is some error or buffer was deleted */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008837 if (retval == FAIL || !bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008838 break;
8839 }
8840 }
8841
8842 check_cursor(); /* just in case lines got deleted */
8843}
8844
8845/*
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008846 * Check *argp for <nomodeline>. When it is present return FALSE, otherwise
8847 * return TRUE and advance *argp to after it.
8848 * Thus return TRUE when do_modelines() should be called.
8849 */
8850 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008851check_nomodeline(char_u **argp)
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008852{
8853 if (STRNCMP(*argp, "<nomodeline>", 12) == 0)
8854 {
8855 *argp = skipwhite(*argp + 12);
8856 return FALSE;
8857 }
8858 return TRUE;
8859}
8860
8861/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008862 * Prepare for executing autocommands for (hidden) buffer "buf".
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008863 * Search for a visible window containing the current buffer. If there isn't
8864 * one then use "aucmd_win".
Bram Moolenaar071d4272004-06-13 20:20:40 +00008865 * Set "curbuf" and "curwin" to match "buf".
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00008866 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008867 */
8868 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008869aucmd_prepbuf(
8870 aco_save_T *aco, /* structure to save values in */
8871 buf_T *buf) /* new curbuf */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008872{
8873 win_T *win;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008874#ifdef FEAT_WINDOWS
8875 int save_ea;
8876#endif
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008877#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008878 int save_acd;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008879#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008880
8881 /* Find a window that is for the new buffer */
8882 if (buf == curbuf) /* be quick when buf is curbuf */
8883 win = curwin;
8884 else
8885#ifdef FEAT_WINDOWS
Bram Moolenaar29323592016-07-24 22:04:11 +02008886 FOR_ALL_WINDOWS(win)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008887 if (win->w_buffer == buf)
8888 break;
8889#else
8890 win = NULL;
8891#endif
8892
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008893 /* Allocate "aucmd_win" when needed. If this fails (out of memory) fall
8894 * back to using the current window. */
8895 if (win == NULL && aucmd_win == NULL)
8896 {
8897 win_alloc_aucmd_win();
8898 if (aucmd_win == NULL)
8899 win = curwin;
8900 }
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008901 if (win == NULL && aucmd_win_used)
8902 /* Strange recursive autocommand, fall back to using the current
8903 * window. Expect a few side effects... */
8904 win = curwin;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008905
8906 aco->save_curwin = curwin;
8907 aco->save_curbuf = curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008908 if (win != NULL)
8909 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008910 /* There is a window for "buf" in the current tab page, make it the
8911 * curwin. This is preferred, it has the least side effects (esp. if
8912 * "buf" is curbuf). */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008913 aco->use_aucmd_win = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008914 curwin = win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008915 }
8916 else
8917 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008918 /* There is no window for "buf", use "aucmd_win". To minimize the side
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02008919 * effects, insert it in the current tab page.
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008920 * Anything related to a window (e.g., setting folds) may have
8921 * unexpected results. */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008922 aco->use_aucmd_win = TRUE;
8923 aucmd_win_used = TRUE;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008924 aucmd_win->w_buffer = buf;
Bram Moolenaarcdddaa42010-06-07 23:07:44 +02008925 aucmd_win->w_s = &buf->b_s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008926 ++buf->b_nwindows;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008927 win_init_empty(aucmd_win); /* set cursor and topline to safe values */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008928
8929 /* Make sure w_localdir and globaldir are NULL to avoid a chdir() in
8930 * win_enter_ext(). */
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008931 vim_free(aucmd_win->w_localdir);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008932 aucmd_win->w_localdir = NULL;
8933 aco->globaldir = globaldir;
8934 globaldir = NULL;
8935
Bram Moolenaar071d4272004-06-13 20:20:40 +00008936
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008937#ifdef FEAT_WINDOWS
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008938 /* Split the current window, put the aucmd_win in the upper half.
8939 * We don't want the BufEnter or WinEnter autocommands. */
8940 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008941 make_snapshot(SNAP_AUCMD_IDX);
8942 save_ea = p_ea;
8943 p_ea = FALSE;
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008944
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008945# ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008946 /* Prevent chdir() call in win_enter_ext(), through do_autochdir(). */
8947 save_acd = p_acd;
8948 p_acd = FALSE;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008949# endif
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008950
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008951 (void)win_split_ins(0, WSP_TOP, aucmd_win, 0);
8952 (void)win_comp_pos(); /* recompute window positions */
8953 p_ea = save_ea;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008954# ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008955 p_acd = save_acd;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008956# endif
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008957 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008958#endif
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008959 curwin = aucmd_win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008960 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008961 curbuf = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008962 aco->new_curwin = curwin;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008963 set_bufref(&aco->new_curbuf, curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008964}
8965
8966/*
8967 * Cleanup after executing autocommands for a (hidden) buffer.
8968 * Restore the window as it was (if possible).
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00008969 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008970 */
8971 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008972aucmd_restbuf(
8973 aco_save_T *aco) /* structure holding saved values */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008974{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008975#ifdef FEAT_WINDOWS
8976 int dummy;
8977#endif
8978
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008979 if (aco->use_aucmd_win)
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008980 {
8981 --curbuf->b_nwindows;
8982#ifdef FEAT_WINDOWS
8983 /* Find "aucmd_win", it can't be closed, but it may be in another tab
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008984 * page. Do not trigger autocommands here. */
8985 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008986 if (curwin != aucmd_win)
8987 {
8988 tabpage_T *tp;
8989 win_T *wp;
8990
8991 FOR_ALL_TAB_WINDOWS(tp, wp)
8992 {
8993 if (wp == aucmd_win)
8994 {
8995 if (tp != curtab)
Bram Moolenaar49e649f2013-05-06 04:50:35 +02008996 goto_tabpage_tp(tp, TRUE, TRUE);
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008997 win_goto(aucmd_win);
Bram Moolenaar28f29082012-02-11 23:45:37 +01008998 goto win_found;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008999 }
9000 }
9001 }
Bram Moolenaar28f29082012-02-11 23:45:37 +01009002win_found:
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009003
9004 /* Remove the window and frame from the tree of frames. */
9005 (void)winframe_remove(curwin, &dummy, NULL);
9006 win_remove(curwin, NULL);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009007 aucmd_win_used = FALSE;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009008 last_status(FALSE); /* may need to remove last status line */
9009 restore_snapshot(SNAP_AUCMD_IDX, FALSE);
9010 (void)win_comp_pos(); /* recompute window positions */
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00009011 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009012
9013 if (win_valid(aco->save_curwin))
9014 curwin = aco->save_curwin;
9015 else
9016 /* Hmm, original window disappeared. Just use the first one. */
9017 curwin = firstwin;
9018# ifdef FEAT_EVAL
Bram Moolenaar429fa852013-04-15 12:27:36 +02009019 vars_clear(&aucmd_win->w_vars->dv_hashtab); /* free all w: variables */
9020 hash_init(&aucmd_win->w_vars->dv_hashtab); /* re-use the hashtab */
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009021# endif
9022#else
9023 curwin = aco->save_curwin;
9024#endif
9025 curbuf = curwin->w_buffer;
9026
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009027 vim_free(globaldir);
9028 globaldir = aco->globaldir;
9029
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009030 /* the buffer contents may have changed */
9031 check_cursor();
9032 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
9033 {
9034 curwin->w_topline = curbuf->b_ml.ml_line_count;
9035#ifdef FEAT_DIFF
9036 curwin->w_topfill = 0;
9037#endif
9038 }
9039#if defined(FEAT_GUI)
9040 /* Hide the scrollbars from the aucmd_win and update. */
9041 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_LEFT], FALSE);
9042 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_RIGHT], FALSE);
9043 gui_may_update_scrollbars();
9044#endif
9045 }
9046 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00009047 {
9048 /* restore curwin */
9049#ifdef FEAT_WINDOWS
9050 if (win_valid(aco->save_curwin))
9051#endif
9052 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009053 /* Restore the buffer which was previously edited by curwin, if
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009054 * it was changed, we are still the same window and the buffer is
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009055 * valid. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009056 if (curwin == aco->new_curwin
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009057 && curbuf != aco->new_curbuf.br_buf
9058 && bufref_valid(&aco->new_curbuf)
9059 && aco->new_curbuf.br_buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009060 {
Bram Moolenaar7da9c372012-04-30 17:04:52 +02009061# if defined(FEAT_SYN_HL) || defined(FEAT_SPELL)
9062 if (curwin->w_s == &curbuf->b_s)
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009063 curwin->w_s = &aco->new_curbuf.br_buf->b_s;
Bram Moolenaar7da9c372012-04-30 17:04:52 +02009064# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009065 --curbuf->b_nwindows;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009066 curbuf = aco->new_curbuf.br_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009067 curwin->w_buffer = curbuf;
9068 ++curbuf->b_nwindows;
9069 }
9070
9071 curwin = aco->save_curwin;
9072 curbuf = curwin->w_buffer;
Bram Moolenaar371932a2014-09-09 16:59:38 +02009073 /* In case the autocommand move the cursor to a position that that
9074 * not exist in curbuf. */
9075 check_cursor();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009076 }
9077 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009078}
9079
9080static int autocmd_nested = FALSE;
9081
9082/*
9083 * Execute autocommands for "event" and file name "fname".
9084 * Return TRUE if some commands were executed.
9085 */
9086 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009087apply_autocmds(
9088 event_T event,
9089 char_u *fname, /* NULL or empty means use actual file name */
9090 char_u *fname_io, /* fname to use for <afile> on cmdline */
9091 int force, /* when TRUE, ignore autocmd_busy */
9092 buf_T *buf) /* buffer for <abuf> */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009093{
9094 return apply_autocmds_group(event, fname, fname_io, force,
9095 AUGROUP_ALL, buf, NULL);
9096}
9097
9098/*
9099 * Like apply_autocmds(), but with extra "eap" argument. This takes care of
9100 * setting v:filearg.
9101 */
9102 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009103apply_autocmds_exarg(
9104 event_T event,
9105 char_u *fname,
9106 char_u *fname_io,
9107 int force,
9108 buf_T *buf,
9109 exarg_T *eap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009110{
9111 return apply_autocmds_group(event, fname, fname_io, force,
9112 AUGROUP_ALL, buf, eap);
9113}
9114
9115/*
9116 * Like apply_autocmds(), but handles the caller's retval. If the script
9117 * processing is being aborted or if retval is FAIL when inside a try
9118 * conditional, no autocommands are executed. If otherwise the autocommands
9119 * cause the script to be aborted, retval is set to FAIL.
9120 */
9121 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009122apply_autocmds_retval(
9123 event_T event,
9124 char_u *fname, /* NULL or empty means use actual file name */
9125 char_u *fname_io, /* fname to use for <afile> on cmdline */
9126 int force, /* when TRUE, ignore autocmd_busy */
9127 buf_T *buf, /* buffer for <abuf> */
9128 int *retval) /* pointer to caller's retval */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009129{
9130 int did_cmd;
9131
Bram Moolenaar1e015462005-09-25 22:16:38 +00009132#ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00009133 if (should_abort(*retval))
9134 return FALSE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00009135#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009136
9137 did_cmd = apply_autocmds_group(event, fname, fname_io, force,
9138 AUGROUP_ALL, buf, NULL);
Bram Moolenaar1e015462005-09-25 22:16:38 +00009139 if (did_cmd
9140#ifdef FEAT_EVAL
9141 && aborting()
9142#endif
9143 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00009144 *retval = FAIL;
9145 return did_cmd;
9146}
9147
Bram Moolenaard35f9712005-12-18 22:02:33 +00009148/*
9149 * Return TRUE when there is a CursorHold autocommand defined.
9150 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009151 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009152has_cursorhold(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009153{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009154 return (first_autopat[(int)(get_real_state() == NORMAL_BUSY
9155 ? EVENT_CURSORHOLD : EVENT_CURSORHOLDI)] != NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009156}
Bram Moolenaard35f9712005-12-18 22:02:33 +00009157
9158/*
9159 * Return TRUE if the CursorHold event can be triggered.
9160 */
9161 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009162trigger_cursorhold(void)
Bram Moolenaard35f9712005-12-18 22:02:33 +00009163{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009164 int state;
9165
Bram Moolenaar05334432011-07-20 18:29:39 +02009166 if (!did_cursorhold
9167 && has_cursorhold()
9168 && !Recording
9169 && typebuf.tb_len == 0
Bram Moolenaard29a9ee2006-09-14 09:07:34 +00009170#ifdef FEAT_INS_EXPAND
9171 && !ins_compl_active()
9172#endif
9173 )
Bram Moolenaar754b5602006-02-09 23:53:20 +00009174 {
9175 state = get_real_state();
9176 if (state == NORMAL_BUSY || (state & INSERT) != 0)
9177 return TRUE;
9178 }
9179 return FALSE;
Bram Moolenaard35f9712005-12-18 22:02:33 +00009180}
Bram Moolenaar754b5602006-02-09 23:53:20 +00009181
9182/*
9183 * Return TRUE when there is a CursorMoved autocommand defined.
9184 */
9185 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009186has_cursormoved(void)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009187{
9188 return (first_autopat[(int)EVENT_CURSORMOVED] != NULL);
9189}
9190
9191/*
9192 * Return TRUE when there is a CursorMovedI autocommand defined.
9193 */
9194 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009195has_cursormovedI(void)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009196{
9197 return (first_autopat[(int)EVENT_CURSORMOVEDI] != NULL);
9198}
Bram Moolenaar071d4272004-06-13 20:20:40 +00009199
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009200/*
Bram Moolenaar186628f2013-03-19 13:33:23 +01009201 * Return TRUE when there is a TextChanged autocommand defined.
9202 */
9203 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009204has_textchanged(void)
Bram Moolenaar186628f2013-03-19 13:33:23 +01009205{
9206 return (first_autopat[(int)EVENT_TEXTCHANGED] != NULL);
9207}
9208
9209/*
9210 * Return TRUE when there is a TextChangedI autocommand defined.
9211 */
9212 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009213has_textchangedI(void)
Bram Moolenaar186628f2013-03-19 13:33:23 +01009214{
9215 return (first_autopat[(int)EVENT_TEXTCHANGEDI] != NULL);
9216}
9217
9218/*
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009219 * Return TRUE when there is an InsertCharPre autocommand defined.
9220 */
9221 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009222has_insertcharpre(void)
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009223{
9224 return (first_autopat[(int)EVENT_INSERTCHARPRE] != NULL);
9225}
9226
Bram Moolenaard5005162014-08-22 23:05:54 +02009227/*
9228 * Return TRUE when there is an CmdUndefined autocommand defined.
9229 */
9230 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009231has_cmdundefined(void)
Bram Moolenaard5005162014-08-22 23:05:54 +02009232{
9233 return (first_autopat[(int)EVENT_CMDUNDEFINED] != NULL);
9234}
9235
9236/*
9237 * Return TRUE when there is an FuncUndefined autocommand defined.
9238 */
9239 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009240has_funcundefined(void)
Bram Moolenaard5005162014-08-22 23:05:54 +02009241{
9242 return (first_autopat[(int)EVENT_FUNCUNDEFINED] != NULL);
9243}
9244
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009245/*
9246 * Execute autocommands for "event" and file name "fname".
9247 * Return TRUE if some commands were executed.
9248 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009249 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009250apply_autocmds_group(
9251 event_T event,
9252 char_u *fname, /* NULL or empty means use actual file name */
9253 char_u *fname_io, /* fname to use for <afile> on cmdline, NULL means
Bram Moolenaar071d4272004-06-13 20:20:40 +00009254 use fname */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009255 int force, /* when TRUE, ignore autocmd_busy */
9256 int group, /* group ID, or AUGROUP_ALL */
9257 buf_T *buf, /* buffer for <abuf> */
9258 exarg_T *eap) /* command arguments */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009259{
9260 char_u *sfname = NULL; /* short file name */
9261 char_u *tail;
9262 int save_changed;
9263 buf_T *old_curbuf;
9264 int retval = FALSE;
9265 char_u *save_sourcing_name;
9266 linenr_T save_sourcing_lnum;
9267 char_u *save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009268 int save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009269 int save_autocmd_bufnr;
9270 char_u *save_autocmd_match;
9271 int save_autocmd_busy;
9272 int save_autocmd_nested;
9273 static int nesting = 0;
9274 AutoPatCmd patcmd;
9275 AutoPat *ap;
9276#ifdef FEAT_EVAL
9277 scid_T save_current_SID;
9278 void *save_funccalp;
9279 char_u *save_cmdarg;
9280 long save_cmdbang;
9281#endif
9282 static int filechangeshell_busy = FALSE;
Bram Moolenaar05159a02005-02-26 23:04:13 +00009283#ifdef FEAT_PROFILE
9284 proftime_T wait_time;
9285#endif
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009286 int did_save_redobuff = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009287
9288 /*
9289 * Quickly return if there are no autocommands for this event or
9290 * autocommands are blocked.
9291 */
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009292 if (first_autopat[(int)event] == NULL || autocmd_blocked > 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009293 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009294
9295 /*
9296 * When autocommands are busy, new autocommands are only executed when
9297 * explicitly enabled with the "nested" flag.
9298 */
9299 if (autocmd_busy && !(force || autocmd_nested))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009300 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009301
9302#ifdef FEAT_EVAL
9303 /*
Bram Moolenaar7263a772007-05-10 17:35:54 +00009304 * Quickly return when immediately aborting on error, or when an interrupt
Bram Moolenaar071d4272004-06-13 20:20:40 +00009305 * occurred or an exception was thrown but not caught.
9306 */
9307 if (aborting())
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009308 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009309#endif
9310
9311 /*
9312 * FileChangedShell never nests, because it can create an endless loop.
9313 */
Bram Moolenaar56718732006-03-15 22:53:57 +00009314 if (filechangeshell_busy && (event == EVENT_FILECHANGEDSHELL
9315 || event == EVENT_FILECHANGEDSHELLPOST))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009316 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009317
9318 /*
9319 * Ignore events in 'eventignore'.
9320 */
9321 if (event_ignored(event))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009322 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009323
9324 /*
9325 * Allow nesting of autocommands, but restrict the depth, because it's
9326 * possible to create an endless loop.
9327 */
9328 if (nesting == 10)
9329 {
9330 EMSG(_("E218: autocommand nesting too deep"));
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009331 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009332 }
9333
9334 /*
9335 * Check if these autocommands are disabled. Used when doing ":all" or
9336 * ":ball".
9337 */
9338 if ( (autocmd_no_enter
9339 && (event == EVENT_WINENTER || event == EVENT_BUFENTER))
9340 || (autocmd_no_leave
9341 && (event == EVENT_WINLEAVE || event == EVENT_BUFLEAVE)))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009342 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009343
9344 /*
9345 * Save the autocmd_* variables and info about the current buffer.
9346 */
9347 save_autocmd_fname = autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009348 save_autocmd_fname_full = autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009349 save_autocmd_bufnr = autocmd_bufnr;
9350 save_autocmd_match = autocmd_match;
9351 save_autocmd_busy = autocmd_busy;
9352 save_autocmd_nested = autocmd_nested;
9353 save_changed = curbuf->b_changed;
9354 old_curbuf = curbuf;
9355
9356 /*
9357 * Set the file name to be used for <afile>.
Bram Moolenaara0174af2008-01-02 20:08:25 +00009358 * Make a copy to avoid that changing a buffer name or directory makes it
9359 * invalid.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009360 */
9361 if (fname_io == NULL)
9362 {
Bram Moolenaar53744302015-07-17 17:38:22 +02009363 if (event == EVENT_COLORSCHEME || event == EVENT_OPTIONSET)
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009364 autocmd_fname = NULL;
9365 else if (fname != NULL && *fname != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009366 autocmd_fname = fname;
9367 else if (buf != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009368 autocmd_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009369 else
9370 autocmd_fname = NULL;
9371 }
9372 else
9373 autocmd_fname = fname_io;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009374 if (autocmd_fname != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009375 autocmd_fname = vim_strsave(autocmd_fname);
9376 autocmd_fname_full = FALSE; /* call FullName_save() later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009377
9378 /*
9379 * Set the buffer number to be used for <abuf>.
9380 */
9381 if (buf == NULL)
9382 autocmd_bufnr = 0;
9383 else
9384 autocmd_bufnr = buf->b_fnum;
9385
9386 /*
9387 * When the file name is NULL or empty, use the file name of buffer "buf".
9388 * Always use the full path of the file name to match with, in case
9389 * "allow_dirs" is set.
9390 */
9391 if (fname == NULL || *fname == NUL)
9392 {
9393 if (buf == NULL)
9394 fname = NULL;
9395 else
9396 {
9397#ifdef FEAT_SYN_HL
9398 if (event == EVENT_SYNTAX)
9399 fname = buf->b_p_syn;
9400 else
9401#endif
9402 if (event == EVENT_FILETYPE)
9403 fname = buf->b_p_ft;
9404 else
9405 {
9406 if (buf->b_sfname != NULL)
9407 sfname = vim_strsave(buf->b_sfname);
9408 fname = buf->b_ffname;
9409 }
9410 }
9411 if (fname == NULL)
9412 fname = (char_u *)"";
9413 fname = vim_strsave(fname); /* make a copy, so we can change it */
9414 }
9415 else
9416 {
9417 sfname = vim_strsave(fname);
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009418 /* Don't try expanding FileType, Syntax, FuncUndefined, WindowID,
9419 * ColorScheme or QuickFixCmd* */
Bram Moolenaar7c626922005-02-07 22:01:03 +00009420 if (event == EVENT_FILETYPE
9421 || event == EVENT_SYNTAX
Bram Moolenaar5135d462009-04-29 16:03:38 +00009422 || event == EVENT_FUNCUNDEFINED
Bram Moolenaar7c626922005-02-07 22:01:03 +00009423 || event == EVENT_REMOTEREPLY
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00009424 || event == EVENT_SPELLFILEMISSING
Bram Moolenaar7c626922005-02-07 22:01:03 +00009425 || event == EVENT_QUICKFIXCMDPRE
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009426 || event == EVENT_COLORSCHEME
Bram Moolenaar53744302015-07-17 17:38:22 +02009427 || event == EVENT_OPTIONSET
Bram Moolenaar7c626922005-02-07 22:01:03 +00009428 || event == EVENT_QUICKFIXCMDPOST)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009429 fname = vim_strsave(fname);
9430 else
9431 fname = FullName_save(fname, FALSE);
9432 }
9433 if (fname == NULL) /* out of memory */
9434 {
9435 vim_free(sfname);
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009436 retval = FALSE;
9437 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009438 }
9439
9440#ifdef BACKSLASH_IN_FILENAME
9441 /*
9442 * Replace all backslashes with forward slashes. This makes the
9443 * autocommand patterns portable between Unix and MS-DOS.
9444 */
9445 if (sfname != NULL)
9446 forward_slash(sfname);
9447 forward_slash(fname);
9448#endif
9449
9450#ifdef VMS
9451 /* remove version for correct match */
9452 if (sfname != NULL)
9453 vms_remove_version(sfname);
9454 vms_remove_version(fname);
9455#endif
9456
9457 /*
9458 * Set the name to be used for <amatch>.
9459 */
9460 autocmd_match = fname;
9461
9462
9463 /* Don't redraw while doing auto commands. */
9464 ++RedrawingDisabled;
9465 save_sourcing_name = sourcing_name;
9466 sourcing_name = NULL; /* don't free this one */
9467 save_sourcing_lnum = sourcing_lnum;
9468 sourcing_lnum = 0; /* no line number here */
9469
9470#ifdef FEAT_EVAL
9471 save_current_SID = current_SID;
9472
Bram Moolenaar05159a02005-02-26 23:04:13 +00009473# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009474 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009475 prof_child_enter(&wait_time); /* doesn't count for the caller itself */
9476# endif
9477
Bram Moolenaar071d4272004-06-13 20:20:40 +00009478 /* Don't use local function variables, if called from a function */
9479 save_funccalp = save_funccal();
9480#endif
9481
9482 /*
9483 * When starting to execute autocommands, save the search patterns.
9484 */
9485 if (!autocmd_busy)
9486 {
9487 save_search_patterns();
Bram Moolenaar20ad69c2015-12-03 13:52:52 +01009488#ifdef FEAT_INS_EXPAND
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009489 if (!ins_compl_active())
Bram Moolenaar20ad69c2015-12-03 13:52:52 +01009490#endif
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009491 {
9492 saveRedobuff();
9493 did_save_redobuff = TRUE;
9494 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009495 did_filetype = keep_filetype;
9496 }
9497
9498 /*
9499 * Note that we are applying autocmds. Some commands need to know.
9500 */
9501 autocmd_busy = TRUE;
9502 filechangeshell_busy = (event == EVENT_FILECHANGEDSHELL);
9503 ++nesting; /* see matching decrement below */
9504
9505 /* Remember that FileType was triggered. Used for did_filetype(). */
9506 if (event == EVENT_FILETYPE)
9507 did_filetype = TRUE;
9508
9509 tail = gettail(fname);
9510
9511 /* Find first autocommand that matches */
9512 patcmd.curpat = first_autopat[(int)event];
9513 patcmd.nextcmd = NULL;
9514 patcmd.group = group;
9515 patcmd.fname = fname;
9516 patcmd.sfname = sfname;
9517 patcmd.tail = tail;
9518 patcmd.event = event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009519 patcmd.arg_bufnr = autocmd_bufnr;
9520 patcmd.next = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009521 auto_next_pat(&patcmd, FALSE);
9522
9523 /* found one, start executing the autocommands */
9524 if (patcmd.curpat != NULL)
9525 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009526 /* add to active_apc_list */
9527 patcmd.next = active_apc_list;
9528 active_apc_list = &patcmd;
9529
Bram Moolenaar071d4272004-06-13 20:20:40 +00009530#ifdef FEAT_EVAL
9531 /* set v:cmdarg (only when there is a matching pattern) */
Bram Moolenaar22fcfad2016-07-01 18:17:26 +02009532 save_cmdbang = (long)get_vim_var_nr(VV_CMDBANG);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009533 if (eap != NULL)
9534 {
9535 save_cmdarg = set_cmdarg(eap, NULL);
9536 set_vim_var_nr(VV_CMDBANG, (long)eap->forceit);
9537 }
9538 else
9539 save_cmdarg = NULL; /* avoid gcc warning */
9540#endif
9541 retval = TRUE;
9542 /* mark the last pattern, to avoid an endless loop when more patterns
9543 * are added when executing autocommands */
9544 for (ap = patcmd.curpat; ap->next != NULL; ap = ap->next)
9545 ap->last = FALSE;
9546 ap->last = TRUE;
9547 check_lnums(TRUE); /* make sure cursor and topline are valid */
9548 do_cmdline(NULL, getnextac, (void *)&patcmd,
9549 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
9550#ifdef FEAT_EVAL
9551 if (eap != NULL)
9552 {
9553 (void)set_cmdarg(NULL, save_cmdarg);
9554 set_vim_var_nr(VV_CMDBANG, save_cmdbang);
9555 }
9556#endif
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009557 /* delete from active_apc_list */
9558 if (active_apc_list == &patcmd) /* just in case */
9559 active_apc_list = patcmd.next;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009560 }
9561
9562 --RedrawingDisabled;
9563 autocmd_busy = save_autocmd_busy;
9564 filechangeshell_busy = FALSE;
9565 autocmd_nested = save_autocmd_nested;
9566 vim_free(sourcing_name);
9567 sourcing_name = save_sourcing_name;
9568 sourcing_lnum = save_sourcing_lnum;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009569 vim_free(autocmd_fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009570 autocmd_fname = save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009571 autocmd_fname_full = save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009572 autocmd_bufnr = save_autocmd_bufnr;
9573 autocmd_match = save_autocmd_match;
9574#ifdef FEAT_EVAL
9575 current_SID = save_current_SID;
9576 restore_funccal(save_funccalp);
Bram Moolenaar05159a02005-02-26 23:04:13 +00009577# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009578 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009579 prof_child_exit(&wait_time);
9580# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009581#endif
9582 vim_free(fname);
9583 vim_free(sfname);
9584 --nesting; /* see matching increment above */
9585
9586 /*
9587 * When stopping to execute autocommands, restore the search patterns and
Bram Moolenaar3be85852014-06-12 14:01:31 +02009588 * the redo buffer. Free any buffers in the au_pending_free_buf list and
9589 * free any windows in the au_pending_free_win list.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009590 */
9591 if (!autocmd_busy)
9592 {
9593 restore_search_patterns();
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009594 if (did_save_redobuff)
9595 restoreRedobuff();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009596 did_filetype = FALSE;
Bram Moolenaar4c7ab1b2014-04-06 20:45:43 +02009597 while (au_pending_free_buf != NULL)
9598 {
9599 buf_T *b = au_pending_free_buf->b_next;
9600 vim_free(au_pending_free_buf);
9601 au_pending_free_buf = b;
9602 }
Bram Moolenaar3be85852014-06-12 14:01:31 +02009603 while (au_pending_free_win != NULL)
9604 {
9605 win_T *w = au_pending_free_win->w_next;
9606 vim_free(au_pending_free_win);
9607 au_pending_free_win = w;
9608 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009609 }
9610
9611 /*
9612 * Some events don't set or reset the Changed flag.
9613 * Check if still in the same buffer!
9614 */
9615 if (curbuf == old_curbuf
9616 && (event == EVENT_BUFREADPOST
9617 || event == EVENT_BUFWRITEPOST
9618 || event == EVENT_FILEAPPENDPOST
9619 || event == EVENT_VIMLEAVE
9620 || event == EVENT_VIMLEAVEPRE))
9621 {
9622#ifdef FEAT_TITLE
9623 if (curbuf->b_changed != save_changed)
9624 need_maketitle = TRUE;
9625#endif
9626 curbuf->b_changed = save_changed;
9627 }
9628
9629 au_cleanup(); /* may really delete removed patterns/commands now */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009630
9631BYPASS_AU:
9632 /* When wiping out a buffer make sure all its buffer-local autocommands
9633 * are deleted. */
9634 if (event == EVENT_BUFWIPEOUT && buf != NULL)
9635 aubuflocal_remove(buf);
9636
Bram Moolenaarc3691332016-04-20 12:49:49 +02009637 if (retval == OK && event == EVENT_FILETYPE)
9638 au_did_filetype = TRUE;
9639
Bram Moolenaar071d4272004-06-13 20:20:40 +00009640 return retval;
9641}
9642
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009643# ifdef FEAT_EVAL
9644static char_u *old_termresponse = NULL;
9645# endif
9646
9647/*
9648 * Block triggering autocommands until unblock_autocmd() is called.
9649 * Can be used recursively, so long as it's symmetric.
9650 */
9651 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009652block_autocmds(void)
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009653{
9654# ifdef FEAT_EVAL
9655 /* Remember the value of v:termresponse. */
9656 if (autocmd_blocked == 0)
9657 old_termresponse = get_vim_var_str(VV_TERMRESPONSE);
9658# endif
9659 ++autocmd_blocked;
9660}
9661
9662 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009663unblock_autocmds(void)
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009664{
9665 --autocmd_blocked;
9666
9667# ifdef FEAT_EVAL
9668 /* When v:termresponse was set while autocommands were blocked, trigger
9669 * the autocommands now. Esp. useful when executing a shell command
9670 * during startup (vimdiff). */
9671 if (autocmd_blocked == 0
9672 && get_vim_var_str(VV_TERMRESPONSE) != old_termresponse)
9673 apply_autocmds(EVENT_TERMRESPONSE, NULL, NULL, FALSE, curbuf);
9674# endif
9675}
9676
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009677 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009678is_autocmd_blocked(void)
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009679{
9680 return autocmd_blocked != 0;
9681}
9682
Bram Moolenaar071d4272004-06-13 20:20:40 +00009683/*
9684 * Find next autocommand pattern that matches.
9685 */
9686 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009687auto_next_pat(
9688 AutoPatCmd *apc,
9689 int stop_at_last) /* stop when 'last' flag is set */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009690{
9691 AutoPat *ap;
9692 AutoCmd *cp;
9693 char_u *name;
9694 char *s;
9695
9696 vim_free(sourcing_name);
9697 sourcing_name = NULL;
9698
9699 for (ap = apc->curpat; ap != NULL && !got_int; ap = ap->next)
9700 {
9701 apc->curpat = NULL;
9702
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009703 /* Only use a pattern when it has not been removed, has commands and
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009704 * the group matches. For buffer-local autocommands only check the
9705 * buffer number. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009706 if (ap->pat != NULL && ap->cmds != NULL
9707 && (apc->group == AUGROUP_ALL || apc->group == ap->group))
9708 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009709 /* execution-condition */
9710 if (ap->buflocal_nr == 0
Bram Moolenaardffa5b82014-11-19 16:38:07 +01009711 ? (match_file_pat(NULL, &ap->reg_prog, apc->fname,
Bram Moolenaar748bf032005-02-02 23:04:36 +00009712 apc->sfname, apc->tail, ap->allow_dirs))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009713 : ap->buflocal_nr == apc->arg_bufnr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009714 {
9715 name = event_nr2name(apc->event);
9716 s = _("%s Auto commands for \"%s\"");
9717 sourcing_name = alloc((unsigned)(STRLEN(s)
9718 + STRLEN(name) + ap->patlen + 1));
9719 if (sourcing_name != NULL)
9720 {
9721 sprintf((char *)sourcing_name, s,
9722 (char *)name, (char *)ap->pat);
9723 if (p_verbose >= 8)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009724 {
9725 verbose_enter();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009726 smsg((char_u *)_("Executing %s"), sourcing_name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009727 verbose_leave();
9728 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009729 }
9730
9731 apc->curpat = ap;
9732 apc->nextcmd = ap->cmds;
9733 /* mark last command */
9734 for (cp = ap->cmds; cp->next != NULL; cp = cp->next)
9735 cp->last = FALSE;
9736 cp->last = TRUE;
9737 }
9738 line_breakcheck();
9739 if (apc->curpat != NULL) /* found a match */
9740 break;
9741 }
9742 if (stop_at_last && ap->last)
9743 break;
9744 }
9745}
9746
9747/*
9748 * Get next autocommand command.
9749 * Called by do_cmdline() to get the next line for ":if".
9750 * Returns allocated string, or NULL for end of autocommands.
9751 */
Bram Moolenaar21691f82012-12-05 19:13:18 +01009752 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009753getnextac(int c UNUSED, void *cookie, int indent UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009754{
9755 AutoPatCmd *acp = (AutoPatCmd *)cookie;
9756 char_u *retval;
9757 AutoCmd *ac;
9758
9759 /* Can be called again after returning the last line. */
9760 if (acp->curpat == NULL)
9761 return NULL;
9762
9763 /* repeat until we find an autocommand to execute */
9764 for (;;)
9765 {
9766 /* skip removed commands */
9767 while (acp->nextcmd != NULL && acp->nextcmd->cmd == NULL)
9768 if (acp->nextcmd->last)
9769 acp->nextcmd = NULL;
9770 else
9771 acp->nextcmd = acp->nextcmd->next;
9772
9773 if (acp->nextcmd != NULL)
9774 break;
9775
9776 /* at end of commands, find next pattern that matches */
9777 if (acp->curpat->last)
9778 acp->curpat = NULL;
9779 else
9780 acp->curpat = acp->curpat->next;
9781 if (acp->curpat != NULL)
9782 auto_next_pat(acp, TRUE);
9783 if (acp->curpat == NULL)
9784 return NULL;
9785 }
9786
9787 ac = acp->nextcmd;
9788
9789 if (p_verbose >= 9)
9790 {
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009791 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009792 smsg((char_u *)_("autocommand %s"), ac->cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009793 msg_puts((char_u *)"\n"); /* don't overwrite this either */
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009794 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009795 }
9796 retval = vim_strsave(ac->cmd);
9797 autocmd_nested = ac->nested;
9798#ifdef FEAT_EVAL
9799 current_SID = ac->scriptID;
9800#endif
9801 if (ac->last)
9802 acp->nextcmd = NULL;
9803 else
9804 acp->nextcmd = ac->next;
9805 return retval;
9806}
9807
9808/*
9809 * Return TRUE if there is a matching autocommand for "fname".
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009810 * To account for buffer-local autocommands, function needs to know
9811 * in which buffer the file will be opened.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009812 */
9813 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009814has_autocmd(event_T event, char_u *sfname, buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009815{
9816 AutoPat *ap;
9817 char_u *fname;
9818 char_u *tail = gettail(sfname);
9819 int retval = FALSE;
9820
9821 fname = FullName_save(sfname, FALSE);
9822 if (fname == NULL)
9823 return FALSE;
9824
9825#ifdef BACKSLASH_IN_FILENAME
9826 /*
9827 * Replace all backslashes with forward slashes. This makes the
9828 * autocommand patterns portable between Unix and MS-DOS.
9829 */
9830 sfname = vim_strsave(sfname);
9831 if (sfname != NULL)
9832 forward_slash(sfname);
9833 forward_slash(fname);
9834#endif
9835
9836 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
9837 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009838 && (ap->buflocal_nr == 0
Bram Moolenaardffa5b82014-11-19 16:38:07 +01009839 ? match_file_pat(NULL, &ap->reg_prog,
Bram Moolenaar748bf032005-02-02 23:04:36 +00009840 fname, sfname, tail, ap->allow_dirs)
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009841 : buf != NULL && ap->buflocal_nr == buf->b_fnum
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009842 ))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009843 {
9844 retval = TRUE;
9845 break;
9846 }
9847
9848 vim_free(fname);
9849#ifdef BACKSLASH_IN_FILENAME
9850 vim_free(sfname);
9851#endif
9852
9853 return retval;
9854}
9855
9856#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
9857/*
9858 * Function given to ExpandGeneric() to obtain the list of autocommand group
9859 * names.
9860 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009861 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009862get_augroup_name(expand_T *xp UNUSED, int idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009863{
9864 if (idx == augroups.ga_len) /* add "END" add the end */
9865 return (char_u *)"END";
9866 if (idx >= augroups.ga_len) /* end of list */
9867 return NULL;
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02009868 if (AUGROUP_NAME(idx) == NULL || AUGROUP_NAME(idx) == deleted_augroup)
9869 /* skip deleted entries */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009870 return (char_u *)"";
9871 return AUGROUP_NAME(idx); /* return a name */
9872}
9873
9874static int include_groups = FALSE;
9875
9876 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009877set_context_in_autocmd(
9878 expand_T *xp,
9879 char_u *arg,
9880 int doautocmd) /* TRUE for :doauto*, FALSE for :autocmd */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009881{
9882 char_u *p;
9883 int group;
9884
9885 /* check for a group name, skip it if present */
9886 include_groups = FALSE;
9887 p = arg;
9888 group = au_get_grouparg(&arg);
9889 if (group == AUGROUP_ERROR)
9890 return NULL;
9891 /* If there only is a group name that's what we expand. */
9892 if (*arg == NUL && group != AUGROUP_ALL && !vim_iswhite(arg[-1]))
9893 {
9894 arg = p;
9895 group = AUGROUP_ALL;
9896 }
9897
9898 /* skip over event name */
9899 for (p = arg; *p != NUL && !vim_iswhite(*p); ++p)
9900 if (*p == ',')
9901 arg = p + 1;
9902 if (*p == NUL)
9903 {
9904 if (group == AUGROUP_ALL)
9905 include_groups = TRUE;
9906 xp->xp_context = EXPAND_EVENTS; /* expand event name */
9907 xp->xp_pattern = arg;
9908 return NULL;
9909 }
9910
9911 /* skip over pattern */
9912 arg = skipwhite(p);
9913 while (*arg && (!vim_iswhite(*arg) || arg[-1] == '\\'))
9914 arg++;
9915 if (*arg)
9916 return arg; /* expand (next) command */
9917
9918 if (doautocmd)
9919 xp->xp_context = EXPAND_FILES; /* expand file names */
9920 else
9921 xp->xp_context = EXPAND_NOTHING; /* pattern is not expanded */
9922 return NULL;
9923}
9924
9925/*
9926 * Function given to ExpandGeneric() to obtain the list of event names.
9927 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009928 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009929get_event_name(expand_T *xp UNUSED, int idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009930{
9931 if (idx < augroups.ga_len) /* First list group names, if wanted */
9932 {
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02009933 if (!include_groups || AUGROUP_NAME(idx) == NULL
9934 || AUGROUP_NAME(idx) == deleted_augroup)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009935 return (char_u *)""; /* skip deleted entries */
9936 return AUGROUP_NAME(idx); /* return a name */
9937 }
9938 return (char_u *)event_names[idx - augroups.ga_len].name;
9939}
9940
9941#endif /* FEAT_CMDL_COMPL */
9942
9943/*
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009944 * Return TRUE if autocmd is supported.
9945 */
9946 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009947autocmd_supported(char_u *name)
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009948{
9949 char_u *p;
9950
9951 return (event_name2nr(name, &p) != NUM_EVENTS);
9952}
9953
9954/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00009955 * Return TRUE if an autocommand is defined for a group, event and
9956 * pattern: The group can be omitted to accept any group. "event" and "pattern"
9957 * can be NULL to accept any event and pattern. "pattern" can be NULL to accept
9958 * any pattern. Buffer-local patterns <buffer> or <buffer=N> are accepted.
9959 * Used for:
9960 * exists("#Group") or
9961 * exists("#Group#Event") or
9962 * exists("#Group#Event#pat") or
9963 * exists("#Event") or
9964 * exists("#Event#pat")
Bram Moolenaar071d4272004-06-13 20:20:40 +00009965 */
9966 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009967au_exists(char_u *arg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009968{
Bram Moolenaar195d6352005-12-19 22:08:24 +00009969 char_u *arg_save;
9970 char_u *pattern = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009971 char_u *event_name;
9972 char_u *p;
Bram Moolenaar754b5602006-02-09 23:53:20 +00009973 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009974 AutoPat *ap;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009975 buf_T *buflocal_buf = NULL;
Bram Moolenaar195d6352005-12-19 22:08:24 +00009976 int group;
9977 int retval = FALSE;
9978
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009979 /* Make a copy so that we can change the '#' chars to a NUL. */
Bram Moolenaar195d6352005-12-19 22:08:24 +00009980 arg_save = vim_strsave(arg);
9981 if (arg_save == NULL)
9982 return FALSE;
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009983 p = vim_strchr(arg_save, '#');
Bram Moolenaar195d6352005-12-19 22:08:24 +00009984 if (p != NULL)
9985 *p++ = NUL;
9986
9987 /* First, look for an autocmd group name */
9988 group = au_find_group(arg_save);
9989 if (group == AUGROUP_ERROR)
9990 {
9991 /* Didn't match a group name, assume the first argument is an event. */
9992 group = AUGROUP_ALL;
9993 event_name = arg_save;
9994 }
9995 else
9996 {
9997 if (p == NULL)
9998 {
9999 /* "Group": group name is present and it's recognized */
10000 retval = TRUE;
10001 goto theend;
10002 }
10003
10004 /* Must be "Group#Event" or "Group#Event#pat". */
10005 event_name = p;
10006 p = vim_strchr(event_name, '#');
10007 if (p != NULL)
10008 *p++ = NUL; /* "Group#Event#pat" */
10009 }
10010
10011 pattern = p; /* "pattern" is NULL when there is no pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010012
10013 /* find the index (enum) for the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010014 event = event_name2nr(event_name, &p);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010015
10016 /* return FALSE if the event name is not recognized */
Bram Moolenaar195d6352005-12-19 22:08:24 +000010017 if (event == NUM_EVENTS)
10018 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010019
10020 /* Find the first autocommand for this event.
10021 * If there isn't any, return FALSE;
10022 * If there is one and no pattern given, return TRUE; */
10023 ap = first_autopat[(int)event];
10024 if (ap == NULL)
Bram Moolenaar195d6352005-12-19 22:08:24 +000010025 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010026
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010027 /* if pattern is "<buffer>", special handling is needed which uses curbuf */
10028 /* for pattern "<buffer=N>, fnamecmp() will work fine */
Bram Moolenaar5b7880d2009-09-11 15:24:31 +000010029 if (pattern != NULL && STRICMP(pattern, "<buffer>") == 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010030 buflocal_buf = curbuf;
10031
Bram Moolenaar071d4272004-06-13 20:20:40 +000010032 /* Check if there is an autocommand with the given pattern. */
10033 for ( ; ap != NULL; ap = ap->next)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010034 /* only use a pattern when it has not been removed and has commands. */
10035 /* For buffer-local autocommands, fnamecmp() works fine. */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010036 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaar195d6352005-12-19 22:08:24 +000010037 && (group == AUGROUP_ALL || ap->group == group)
Bram Moolenaar5b7880d2009-09-11 15:24:31 +000010038 && (pattern == NULL
10039 || (buflocal_buf == NULL
10040 ? fnamecmp(ap->pat, pattern) == 0
10041 : ap->buflocal_nr == buflocal_buf->b_fnum)))
Bram Moolenaar195d6352005-12-19 22:08:24 +000010042 {
10043 retval = TRUE;
10044 break;
10045 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010046
Bram Moolenaar195d6352005-12-19 22:08:24 +000010047theend:
10048 vim_free(arg_save);
10049 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010050}
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010051
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010052#else /* FEAT_AUTOCMD */
10053
10054/*
10055 * Prepare for executing commands for (hidden) buffer "buf".
10056 * This is the non-autocommand version, it simply saves "curbuf" and sets
10057 * "curbuf" and "curwin" to match "buf".
10058 */
10059 void
Bram Moolenaard14e00e2016-01-31 17:30:51 +010010060aucmd_prepbuf(
10061 aco_save_T *aco, /* structure to save values in */
10062 buf_T *buf) /* new curbuf */
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010063{
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010064 aco->save_curbuf = curbuf;
10065 --curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010066 curbuf = buf;
10067 curwin->w_buffer = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010068 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010069}
10070
10071/*
10072 * Restore after executing commands for a (hidden) buffer.
10073 * This is the non-autocommand version.
10074 */
10075 void
Bram Moolenaard14e00e2016-01-31 17:30:51 +010010076aucmd_restbuf(
10077 aco_save_T *aco) /* structure holding saved values */
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010078{
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010079 --curbuf->b_nwindows;
10080 curbuf = aco->save_curbuf;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010081 curwin->w_buffer = curbuf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010082 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010083}
10084
Bram Moolenaar071d4272004-06-13 20:20:40 +000010085#endif /* FEAT_AUTOCMD */
10086
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010087
Bram Moolenaar071d4272004-06-13 20:20:40 +000010088#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN) || defined(PROTO)
10089/*
Bram Moolenaar748bf032005-02-02 23:04:36 +000010090 * Try matching a filename with a "pattern" ("prog" is NULL), or use the
10091 * precompiled regprog "prog" ("pattern" is NULL). That avoids calling
10092 * vim_regcomp() often.
Bram Moolenaar071d4272004-06-13 20:20:40 +000010093 * Used for autocommands and 'wildignore'.
10094 * Returns TRUE if there is a match, FALSE otherwise.
10095 */
Bram Moolenaardffa5b82014-11-19 16:38:07 +010010096 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010097match_file_pat(
10098 char_u *pattern, /* pattern to match with */
10099 regprog_T **prog, /* pre-compiled regprog or NULL */
10100 char_u *fname, /* full path of file name */
10101 char_u *sfname, /* short file name or NULL */
10102 char_u *tail, /* tail of path */
10103 int allow_dirs) /* allow matching with dir */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010104{
10105 regmatch_T regmatch;
10106 int result = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010107
Bram Moolenaar71afbfe2013-03-19 16:49:16 +010010108 regmatch.rm_ic = p_fic; /* ignore case if 'fileignorecase' is set */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010109 if (prog != NULL)
10110 regmatch.regprog = *prog;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010111 else
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010112 regmatch.regprog = vim_regcomp(pattern, RE_MAGIC);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010113
10114 /*
10115 * Try for a match with the pattern with:
10116 * 1. the full file name, when the pattern has a '/'.
10117 * 2. the short file name, when the pattern has a '/'.
10118 * 3. the tail of the file name, when the pattern has no '/'.
10119 */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010120 if (regmatch.regprog != NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +000010121 && ((allow_dirs
10122 && (vim_regexec(&regmatch, fname, (colnr_T)0)
10123 || (sfname != NULL
10124 && vim_regexec(&regmatch, sfname, (colnr_T)0))))
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010125 || (!allow_dirs && vim_regexec(&regmatch, tail, (colnr_T)0))))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010126 result = TRUE;
10127
Bram Moolenaardffa5b82014-11-19 16:38:07 +010010128 if (prog != NULL)
10129 *prog = regmatch.regprog;
10130 else
Bram Moolenaar473de612013-06-08 18:19:48 +020010131 vim_regfree(regmatch.regprog);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010132 return result;
10133}
10134#endif
10135
10136#if defined(FEAT_WILDIGN) || defined(PROTO)
10137/*
10138 * Return TRUE if a file matches with a pattern in "list".
10139 * "list" is a comma-separated list of patterns, like 'wildignore'.
10140 * "sfname" is the short file name or NULL, "ffname" the long file name.
10141 */
10142 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010143match_file_list(char_u *list, char_u *sfname, char_u *ffname)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010144{
10145 char_u buf[100];
10146 char_u *tail;
10147 char_u *regpat;
10148 char allow_dirs;
10149 int match;
10150 char_u *p;
10151
10152 tail = gettail(sfname);
10153
10154 /* try all patterns in 'wildignore' */
10155 p = list;
10156 while (*p)
10157 {
10158 copy_option_part(&p, buf, 100, ",");
10159 regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, FALSE);
10160 if (regpat == NULL)
10161 break;
Bram Moolenaar748bf032005-02-02 23:04:36 +000010162 match = match_file_pat(regpat, NULL, ffname, sfname,
10163 tail, (int)allow_dirs);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010164 vim_free(regpat);
10165 if (match)
10166 return TRUE;
10167 }
10168 return FALSE;
10169}
10170#endif
10171
10172/*
10173 * Convert the given pattern "pat" which has shell style wildcards in it, into
10174 * a regular expression, and return the result in allocated memory. If there
10175 * is a directory path separator to be matched, then TRUE is put in
10176 * allow_dirs, otherwise FALSE is put there -- webb.
10177 * Handle backslashes before special characters, like "\*" and "\ ".
10178 *
Bram Moolenaar071d4272004-06-13 20:20:40 +000010179 * Returns NULL when out of memory.
10180 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010181 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010182file_pat_to_reg_pat(
10183 char_u *pat,
10184 char_u *pat_end, /* first char after pattern or NULL */
10185 char *allow_dirs, /* Result passed back out in here */
10186 int no_bslash UNUSED) /* Don't use a backward slash as pathsep */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010187{
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010188 int size = 2; /* '^' at start, '$' at end */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010189 char_u *endp;
10190 char_u *reg_pat;
10191 char_u *p;
10192 int i;
10193 int nested = 0;
10194 int add_dollar = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010195
10196 if (allow_dirs != NULL)
10197 *allow_dirs = FALSE;
10198 if (pat_end == NULL)
10199 pat_end = pat + STRLEN(pat);
10200
Bram Moolenaar071d4272004-06-13 20:20:40 +000010201 for (p = pat; p < pat_end; p++)
10202 {
10203 switch (*p)
10204 {
10205 case '*':
10206 case '.':
10207 case ',':
10208 case '{':
10209 case '}':
10210 case '~':
10211 size += 2; /* extra backslash */
10212 break;
10213#ifdef BACKSLASH_IN_FILENAME
10214 case '\\':
10215 case '/':
10216 size += 4; /* could become "[\/]" */
10217 break;
10218#endif
10219 default:
10220 size++;
Bram Moolenaar2288afe2015-08-11 16:20:05 +020010221# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010222 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010223 {
10224 ++p;
10225 ++size;
10226 }
10227# endif
10228 break;
10229 }
10230 }
10231 reg_pat = alloc(size + 1);
10232 if (reg_pat == NULL)
10233 return NULL;
10234
Bram Moolenaar071d4272004-06-13 20:20:40 +000010235 i = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010236
10237 if (pat[0] == '*')
10238 while (pat[0] == '*' && pat < pat_end - 1)
10239 pat++;
10240 else
10241 reg_pat[i++] = '^';
10242 endp = pat_end - 1;
Bram Moolenaar8fee8782015-08-11 18:45:48 +020010243 if (endp >= pat && *endp == '*')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010244 {
10245 while (endp - pat > 0 && *endp == '*')
10246 endp--;
10247 add_dollar = FALSE;
10248 }
10249 for (p = pat; *p && nested >= 0 && p <= endp; p++)
10250 {
10251 switch (*p)
10252 {
10253 case '*':
10254 reg_pat[i++] = '.';
10255 reg_pat[i++] = '*';
Bram Moolenaar02743632005-07-25 20:42:36 +000010256 while (p[1] == '*') /* "**" matches like "*" */
10257 ++p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010258 break;
10259 case '.':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010260 case '~':
10261 reg_pat[i++] = '\\';
10262 reg_pat[i++] = *p;
10263 break;
10264 case '?':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010265 reg_pat[i++] = '.';
10266 break;
10267 case '\\':
10268 if (p[1] == NUL)
10269 break;
10270#ifdef BACKSLASH_IN_FILENAME
10271 if (!no_bslash)
10272 {
10273 /* translate:
10274 * "\x" to "\\x" e.g., "dir\file"
10275 * "\*" to "\\.*" e.g., "dir\*.c"
10276 * "\?" to "\\." e.g., "dir\??.c"
10277 * "\+" to "\+" e.g., "fileX\+.c"
10278 */
10279 if ((vim_isfilec(p[1]) || p[1] == '*' || p[1] == '?')
10280 && p[1] != '+')
10281 {
10282 reg_pat[i++] = '[';
10283 reg_pat[i++] = '\\';
10284 reg_pat[i++] = '/';
10285 reg_pat[i++] = ']';
10286 if (allow_dirs != NULL)
10287 *allow_dirs = TRUE;
10288 break;
10289 }
10290 }
10291#endif
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010292 /* Undo escaping from ExpandEscape():
10293 * foo\?bar -> foo?bar
10294 * foo\%bar -> foo%bar
10295 * foo\,bar -> foo,bar
10296 * foo\ bar -> foo bar
10297 * Don't unescape \, * and others that are also special in a
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010298 * regexp.
10299 * An escaped { must be unescaped since we use magic not
Bram Moolenaara946afe2013-08-02 15:22:39 +020010300 * verymagic. Use "\\\{n,m\}"" to get "\{n,m}".
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010301 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010302 if (*++p == '?'
10303#ifdef BACKSLASH_IN_FILENAME
10304 && no_bslash
10305#endif
10306 )
10307 reg_pat[i++] = '?';
10308 else
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010309 if (*p == ',' || *p == '%' || *p == '#'
Bram Moolenaar2288afe2015-08-11 16:20:05 +020010310 || vim_isspace(*p) || *p == '{' || *p == '}')
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010311 reg_pat[i++] = *p;
Bram Moolenaara946afe2013-08-02 15:22:39 +020010312 else if (*p == '\\' && p[1] == '\\' && p[2] == '{')
10313 {
10314 reg_pat[i++] = '\\';
10315 reg_pat[i++] = '{';
10316 p += 2;
10317 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010318 else
10319 {
10320 if (allow_dirs != NULL && vim_ispathsep(*p)
10321#ifdef BACKSLASH_IN_FILENAME
10322 && (!no_bslash || *p != '\\')
10323#endif
10324 )
10325 *allow_dirs = TRUE;
10326 reg_pat[i++] = '\\';
10327 reg_pat[i++] = *p;
10328 }
10329 break;
10330#ifdef BACKSLASH_IN_FILENAME
10331 case '/':
10332 reg_pat[i++] = '[';
10333 reg_pat[i++] = '\\';
10334 reg_pat[i++] = '/';
10335 reg_pat[i++] = ']';
10336 if (allow_dirs != NULL)
10337 *allow_dirs = TRUE;
10338 break;
10339#endif
10340 case '{':
10341 reg_pat[i++] = '\\';
10342 reg_pat[i++] = '(';
10343 nested++;
10344 break;
10345 case '}':
10346 reg_pat[i++] = '\\';
10347 reg_pat[i++] = ')';
10348 --nested;
10349 break;
10350 case ',':
10351 if (nested)
10352 {
10353 reg_pat[i++] = '\\';
10354 reg_pat[i++] = '|';
10355 }
10356 else
10357 reg_pat[i++] = ',';
10358 break;
10359 default:
10360# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010361 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010362 reg_pat[i++] = *p++;
10363 else
10364# endif
10365 if (allow_dirs != NULL && vim_ispathsep(*p))
10366 *allow_dirs = TRUE;
10367 reg_pat[i++] = *p;
10368 break;
10369 }
10370 }
10371 if (add_dollar)
10372 reg_pat[i++] = '$';
10373 reg_pat[i] = NUL;
10374 if (nested != 0)
10375 {
10376 if (nested < 0)
10377 EMSG(_("E219: Missing {."));
10378 else
10379 EMSG(_("E220: Missing }."));
10380 vim_free(reg_pat);
10381 reg_pat = NULL;
10382 }
10383 return reg_pat;
10384}
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010385
10386#if defined(EINTR) || defined(PROTO)
10387/*
10388 * Version of read() that retries when interrupted by EINTR (possibly
10389 * by a SIGWINCH).
10390 */
10391 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010392read_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010393{
10394 long ret;
10395
10396 for (;;)
10397 {
10398 ret = vim_read(fd, buf, bufsize);
10399 if (ret >= 0 || errno != EINTR)
10400 break;
10401 }
10402 return ret;
10403}
10404
10405/*
10406 * Version of write() that retries when interrupted by EINTR (possibly
10407 * by a SIGWINCH).
10408 */
10409 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010410write_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010411{
10412 long ret = 0;
10413 long wlen;
10414
10415 /* Repeat the write() so long it didn't fail, other than being interrupted
10416 * by a signal. */
10417 while (ret < (long)bufsize)
10418 {
Bram Moolenaar9c263032010-12-17 18:06:06 +010010419 wlen = vim_write(fd, (char *)buf + ret, bufsize - ret);
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010420 if (wlen < 0)
10421 {
10422 if (errno != EINTR)
10423 break;
10424 }
10425 else
10426 ret += wlen;
10427 }
10428 return ret;
10429}
10430#endif