blob: bcb8fef8b1a90ae433d8256e0302fdbcc8efe247 [file] [log] [blame]
Bram Moolenaaredf3f972016-08-29 22:49:24 +02001/* vi:set ts=8 sts=4 sw=4 noet:
Bram Moolenaar071d4272004-06-13 20:20:40 +00002 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
11 * fileio.c: read from and write to a file
12 */
13
Bram Moolenaar071d4272004-06-13 20:20:40 +000014#include "vim.h"
15
Bram Moolenaarf4888d02009-12-02 12:31:27 +000016#if defined(__TANDEM) || defined(__MINT__)
Bram Moolenaar071d4272004-06-13 20:20:40 +000017# include <limits.h> /* for SSIZE_MAX */
18#endif
19
20#if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
21# include <utime.h> /* for struct utimbuf */
22#endif
23
24#define BUFSIZE 8192 /* size of normal write buffer */
25#define SMBUFSIZE 256 /* size of emergency write buffer */
26
Bram Moolenaar071d4272004-06-13 20:20:40 +000027/* Is there any system that doesn't have access()? */
Bram Moolenaar9372a112005-12-06 19:59:18 +000028#define USE_MCH_ACCESS
Bram Moolenaar071d4272004-06-13 20:20:40 +000029
30#ifdef FEAT_MBYTE
Bram Moolenaard25c16e2016-01-29 22:13:30 +010031static char_u *next_fenc(char_u **pp);
Bram Moolenaar071d4272004-06-13 20:20:40 +000032# ifdef FEAT_EVAL
Bram Moolenaard25c16e2016-01-29 22:13:30 +010033static char_u *readfile_charconvert(char_u *fname, char_u *fenc, int *fdp);
Bram Moolenaar071d4272004-06-13 20:20:40 +000034# endif
35#endif
36#ifdef FEAT_VIMINFO
Bram Moolenaard25c16e2016-01-29 22:13:30 +010037static void check_marks_read(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +000038#endif
39#ifdef FEAT_CRYPT
Bram Moolenaar8767f522016-07-01 17:17:39 +020040static char_u *check_for_cryptkey(char_u *cryptkey, char_u *ptr, long *sizep, off_T *filesizep, int newfile, char_u *fname, int *did_ask);
Bram Moolenaar071d4272004-06-13 20:20:40 +000041#endif
42#ifdef UNIX
Bram Moolenaard25c16e2016-01-29 22:13:30 +010043static void set_file_time(char_u *fname, time_t atime, time_t mtime);
Bram Moolenaar071d4272004-06-13 20:20:40 +000044#endif
Bram Moolenaard25c16e2016-01-29 22:13:30 +010045static int set_rw_fname(char_u *fname, char_u *sfname);
46static int msg_add_fileformat(int eol_type);
47static void msg_add_eol(void);
Bram Moolenaar8767f522016-07-01 17:17:39 +020048static int check_mtime(buf_T *buf, stat_T *s);
Bram Moolenaard25c16e2016-01-29 22:13:30 +010049static int time_differs(long t1, long t2);
Bram Moolenaar071d4272004-06-13 20:20:40 +000050#ifdef FEAT_AUTOCMD
Bram Moolenaard25c16e2016-01-29 22:13:30 +010051static int apply_autocmds_exarg(event_T event, char_u *fname, char_u *fname_io, int force, buf_T *buf, exarg_T *eap);
52static int au_find_group(char_u *name);
Bram Moolenaar70836c82006-02-20 21:28:49 +000053
54# define AUGROUP_DEFAULT -1 /* default autocmd group */
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +000055# define AUGROUP_ERROR -2 /* erroneous autocmd group */
Bram Moolenaar70836c82006-02-20 21:28:49 +000056# define AUGROUP_ALL -3 /* all autocmd groups */
Bram Moolenaar071d4272004-06-13 20:20:40 +000057#endif
58
59#if defined(FEAT_CRYPT) || defined(FEAT_MBYTE)
60# define HAS_BW_FLAGS
61# define FIO_LATIN1 0x01 /* convert Latin1 */
62# define FIO_UTF8 0x02 /* convert UTF-8 */
63# define FIO_UCS2 0x04 /* convert UCS-2 */
64# define FIO_UCS4 0x08 /* convert UCS-4 */
65# define FIO_UTF16 0x10 /* convert UTF-16 */
66# ifdef WIN3264
67# define FIO_CODEPAGE 0x20 /* convert MS-Windows codepage */
68# define FIO_PUT_CP(x) (((x) & 0xffff) << 16) /* put codepage in top word */
69# define FIO_GET_CP(x) (((x)>>16) & 0xffff) /* get codepage from top word */
70# endif
71# ifdef MACOS_X
72# define FIO_MACROMAN 0x20 /* convert MacRoman */
73# endif
74# define FIO_ENDIAN_L 0x80 /* little endian */
75# define FIO_ENCRYPTED 0x1000 /* encrypt written bytes */
76# define FIO_NOCONVERT 0x2000 /* skip encoding conversion */
77# define FIO_UCSBOM 0x4000 /* check for BOM at start of file */
78# define FIO_ALL -1 /* allow all formats */
79#endif
80
81/* When converting, a read() or write() may leave some bytes to be converted
82 * for the next call. The value is guessed... */
83#define CONV_RESTLEN 30
84
85/* We have to guess how much a sequence of bytes may expand when converting
86 * with iconv() to be able to allocate a buffer. */
87#define ICONV_MULT 8
88
89/*
90 * Structure to pass arguments from buf_write() to buf_write_bytes().
91 */
92struct bw_info
93{
94 int bw_fd; /* file descriptor */
95 char_u *bw_buf; /* buffer with data to be written */
Bram Moolenaard089d9b2007-09-30 12:02:55 +000096 int bw_len; /* length of data */
Bram Moolenaar071d4272004-06-13 20:20:40 +000097#ifdef HAS_BW_FLAGS
98 int bw_flags; /* FIO_ flags */
99#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +0200100#ifdef FEAT_CRYPT
101 buf_T *bw_buffer; /* buffer being written */
102#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000103#ifdef FEAT_MBYTE
104 char_u bw_rest[CONV_RESTLEN]; /* not converted bytes */
105 int bw_restlen; /* nr of bytes in bw_rest[] */
106 int bw_first; /* first write call */
107 char_u *bw_conv_buf; /* buffer for writing converted chars */
108 int bw_conv_buflen; /* size of bw_conv_buf */
109 int bw_conv_error; /* set for conversion error */
Bram Moolenaar32b485f2009-07-29 16:06:27 +0000110 linenr_T bw_conv_error_lnum; /* first line with error or zero */
111 linenr_T bw_start_lnum; /* line number at start of buffer */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000112# ifdef USE_ICONV
113 iconv_t bw_iconv_fd; /* descriptor for iconv() or -1 */
114# endif
115#endif
116};
117
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100118static int buf_write_bytes(struct bw_info *ip);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000119
120#ifdef FEAT_MBYTE
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100121static linenr_T readfile_linenr(linenr_T linecnt, char_u *p, char_u *endp);
122static int ucs2bytes(unsigned c, char_u **pp, int flags);
123static int need_conversion(char_u *fenc);
124static int get_fio_flags(char_u *ptr);
125static char_u *check_for_bom(char_u *p, long size, int *lenp, int flags);
126static int make_bom(char_u *buf, char_u *name);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000127# ifdef WIN3264
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100128static int get_win_fio_flags(char_u *ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000129# endif
130# ifdef MACOS_X
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100131static int get_mac_fio_flags(char_u *ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000132# endif
133#endif
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100134static int move_lines(buf_T *frombuf, buf_T *tobuf);
Bram Moolenaar4592dee2009-11-18 19:11:58 +0000135#ifdef TEMPDIRNAMES
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100136static void vim_settempdir(char_u *tempdir);
Bram Moolenaar4592dee2009-11-18 19:11:58 +0000137#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000138#ifdef FEAT_AUTOCMD
139static char *e_auchangedbuf = N_("E812: Autocommands changed buffer or buffer name");
140#endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000141
Bram Moolenaarc3691332016-04-20 12:49:49 +0200142#ifdef FEAT_AUTOCMD
143/*
144 * Set by the apply_autocmds_group function if the given event is equal to
145 * EVENT_FILETYPE. Used by the readfile function in order to determine if
146 * EVENT_BUFREADPOST triggered the EVENT_FILETYPE.
147 *
148 * Relying on this value requires one to reset it prior calling
149 * apply_autocmds_group.
150 */
151static int au_did_filetype INIT(= FALSE);
152#endif
153
Bram Moolenaar071d4272004-06-13 20:20:40 +0000154 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +0100155filemess(
156 buf_T *buf,
157 char_u *name,
158 char_u *s,
159 int attr)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000160{
161 int msg_scroll_save;
162
163 if (msg_silent != 0)
164 return;
165 msg_add_fname(buf, name); /* put file name in IObuff with quotes */
166 /* If it's extremely long, truncate it. */
167 if (STRLEN(IObuff) > IOSIZE - 80)
168 IObuff[IOSIZE - 80] = NUL;
169 STRCAT(IObuff, s);
170 /*
171 * For the first message may have to start a new line.
172 * For further ones overwrite the previous one, reset msg_scroll before
173 * calling filemess().
174 */
175 msg_scroll_save = msg_scroll;
176 if (shortmess(SHM_OVERALL) && !exiting && p_verbose == 0)
177 msg_scroll = FALSE;
178 if (!msg_scroll) /* wait a bit when overwriting an error msg */
179 check_for_delay(FALSE);
180 msg_start();
181 msg_scroll = msg_scroll_save;
182 msg_scrolled_ign = TRUE;
183 /* may truncate the message to avoid a hit-return prompt */
184 msg_outtrans_attr(msg_may_trunc(FALSE, IObuff), attr);
185 msg_clr_eos();
186 out_flush();
187 msg_scrolled_ign = FALSE;
188}
189
190/*
191 * Read lines from file "fname" into the buffer after line "from".
192 *
193 * 1. We allocate blocks with lalloc, as big as possible.
194 * 2. Each block is filled with characters from the file with a single read().
195 * 3. The lines are inserted in the buffer with ml_append().
196 *
197 * (caller must check that fname != NULL, unless READ_STDIN is used)
198 *
199 * "lines_to_skip" is the number of lines that must be skipped
200 * "lines_to_read" is the number of lines that are appended
201 * When not recovering lines_to_skip is 0 and lines_to_read MAXLNUM.
202 *
203 * flags:
204 * READ_NEW starting to edit a new buffer
205 * READ_FILTER reading filter output
206 * READ_STDIN read from stdin instead of a file
207 * READ_BUFFER read from curbuf instead of a file (converting after reading
208 * stdin)
209 * READ_DUMMY read into a dummy buffer (to check if file contents changed)
Bram Moolenaar59f931e2010-07-24 20:27:03 +0200210 * READ_KEEP_UNDO don't clear undo info or read it from a file
Bram Moolenaarf71d7b92016-08-09 22:14:05 +0200211 * READ_FIFO read from fifo/socket instead of a file
Bram Moolenaar071d4272004-06-13 20:20:40 +0000212 *
213 * return FAIL for failure, OK otherwise
214 */
215 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +0100216readfile(
217 char_u *fname,
218 char_u *sfname,
219 linenr_T from,
220 linenr_T lines_to_skip,
221 linenr_T lines_to_read,
222 exarg_T *eap, /* can be NULL! */
223 int flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000224{
225 int fd = 0;
226 int newfile = (flags & READ_NEW);
227 int check_readonly;
228 int filtering = (flags & READ_FILTER);
229 int read_stdin = (flags & READ_STDIN);
230 int read_buffer = (flags & READ_BUFFER);
Bram Moolenaarf71d7b92016-08-09 22:14:05 +0200231 int read_fifo = (flags & READ_FIFO);
Bram Moolenaar690ffc02008-01-04 15:31:21 +0000232 int set_options = newfile || read_buffer
233 || (eap != NULL && eap->read_edit);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000234 linenr_T read_buf_lnum = 1; /* next line to read from curbuf */
235 colnr_T read_buf_col = 0; /* next char to read from this line */
236 char_u c;
237 linenr_T lnum = from;
238 char_u *ptr = NULL; /* pointer into read buffer */
239 char_u *buffer = NULL; /* read buffer */
240 char_u *new_buffer = NULL; /* init to shut up gcc */
241 char_u *line_start = NULL; /* init to shut up gcc */
242 int wasempty; /* buffer was empty before reading */
243 colnr_T len;
244 long size = 0;
245 char_u *p;
Bram Moolenaar8767f522016-07-01 17:17:39 +0200246 off_T filesize = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000247 int skip_read = FALSE;
248#ifdef FEAT_CRYPT
249 char_u *cryptkey = NULL;
Bram Moolenaarf50a2532010-05-21 15:36:08 +0200250 int did_ask_for_key = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000251#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +0200252#ifdef FEAT_PERSISTENT_UNDO
253 context_sha256_T sha_ctx;
254 int read_undo_file = FALSE;
255#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000256 int split = 0; /* number of split lines */
257#define UNKNOWN 0x0fffffff /* file size is unknown */
258 linenr_T linecnt;
259 int error = FALSE; /* errors encountered */
260 int ff_error = EOL_UNKNOWN; /* file format with errors */
261 long linerest = 0; /* remaining chars in line */
262#ifdef UNIX
263 int perm = 0;
264 int swap_mode = -1; /* protection bits for swap file */
265#else
266 int perm;
267#endif
268 int fileformat = 0; /* end-of-line format */
269 int keep_fileformat = FALSE;
Bram Moolenaar8767f522016-07-01 17:17:39 +0200270 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000271 int file_readonly;
272 linenr_T skip_count = 0;
273 linenr_T read_count = 0;
274 int msg_save = msg_scroll;
275 linenr_T read_no_eol_lnum = 0; /* non-zero lnum when last line of
276 * last read was missing the eol */
277 int try_mac = (vim_strchr(p_ffs, 'm') != NULL);
278 int try_dos = (vim_strchr(p_ffs, 'd') != NULL);
279 int try_unix = (vim_strchr(p_ffs, 'x') != NULL);
280 int file_rewind = FALSE;
281#ifdef FEAT_MBYTE
282 int can_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000283 linenr_T conv_error = 0; /* line nr with conversion error */
284 linenr_T illegal_byte = 0; /* line nr with illegal byte */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000285 int keep_dest_enc = FALSE; /* don't retry when char doesn't fit
286 in destination encoding */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000287 int bad_char_behavior = BAD_REPLACE;
288 /* BAD_KEEP, BAD_DROP or character to
289 * replace with */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000290 char_u *tmpname = NULL; /* name of 'charconvert' output file */
291 int fio_flags = 0;
292 char_u *fenc; /* fileencoding to use */
293 int fenc_alloced; /* fenc_next is in allocated memory */
294 char_u *fenc_next = NULL; /* next item in 'fencs' or NULL */
295 int advance_fenc = FALSE;
296 long real_size = 0;
297# ifdef USE_ICONV
298 iconv_t iconv_fd = (iconv_t)-1; /* descriptor for iconv() or -1 */
299# ifdef FEAT_EVAL
300 int did_iconv = FALSE; /* TRUE when iconv() failed and trying
301 'charconvert' next */
302# endif
303# endif
304 int converted = FALSE; /* TRUE if conversion done */
305 int notconverted = FALSE; /* TRUE if conversion wanted but it
306 wasn't possible */
307 char_u conv_rest[CONV_RESTLEN];
308 int conv_restlen = 0; /* nr of bytes in conv_rest[] */
309#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000310#ifdef FEAT_AUTOCMD
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200311 buf_T *old_curbuf;
312 char_u *old_b_ffname;
313 char_u *old_b_fname;
314 int using_b_ffname;
315 int using_b_fname;
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000316#endif
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200317
Bram Moolenaarc3691332016-04-20 12:49:49 +0200318#ifdef FEAT_AUTOCMD
319 au_did_filetype = FALSE; /* reset before triggering any autocommands */
320#endif
321
Bram Moolenaarcab35ad2011-02-15 17:39:22 +0100322 curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000323
324 /*
325 * If there is no file name yet, use the one for the read file.
326 * BF_NOTEDITED is set to reflect this.
327 * Don't do this for a read from a filter.
328 * Only do this when 'cpoptions' contains the 'f' flag.
329 */
330 if (curbuf->b_ffname == NULL
331 && !filtering
332 && fname != NULL
333 && vim_strchr(p_cpo, CPO_FNAMER) != NULL
334 && !(flags & READ_DUMMY))
335 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000336 if (set_rw_fname(fname, sfname) == FAIL)
337 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000338 }
339
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200340#ifdef FEAT_AUTOCMD
341 /* Remember the initial values of curbuf, curbuf->b_ffname and
342 * curbuf->b_fname to detect whether they are altered as a result of
343 * executing nasty autocommands. Also check if "fname" and "sfname"
344 * point to one of these values. */
345 old_curbuf = curbuf;
346 old_b_ffname = curbuf->b_ffname;
347 old_b_fname = curbuf->b_fname;
348 using_b_ffname = (fname == curbuf->b_ffname)
349 || (sfname == curbuf->b_ffname);
350 using_b_fname = (fname == curbuf->b_fname) || (sfname == curbuf->b_fname);
351#endif
352
Bram Moolenaardf177f62005-02-22 08:39:57 +0000353 /* After reading a file the cursor line changes but we don't want to
354 * display the line. */
355 ex_no_reprint = TRUE;
356
Bram Moolenaar55b7cf82006-09-09 12:52:42 +0000357 /* don't display the file info for another buffer now */
358 need_fileinfo = FALSE;
359
Bram Moolenaar071d4272004-06-13 20:20:40 +0000360 /*
361 * For Unix: Use the short file name whenever possible.
362 * Avoids problems with networks and when directory names are changed.
363 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
364 * another directory, which we don't detect.
365 */
366 if (sfname == NULL)
367 sfname = fname;
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200368#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000369 fname = sfname;
370#endif
371
372#ifdef FEAT_AUTOCMD
373 /*
374 * The BufReadCmd and FileReadCmd events intercept the reading process by
375 * executing the associated commands instead.
376 */
377 if (!filtering && !read_stdin && !read_buffer)
378 {
379 pos_T pos;
380
381 pos = curbuf->b_op_start;
382
383 /* Set '[ mark to the line above where the lines go (line 1 if zero). */
384 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
385 curbuf->b_op_start.col = 0;
386
387 if (newfile)
388 {
389 if (apply_autocmds_exarg(EVENT_BUFREADCMD, NULL, sfname,
390 FALSE, curbuf, eap))
391#ifdef FEAT_EVAL
392 return aborting() ? FAIL : OK;
393#else
394 return OK;
395#endif
396 }
397 else if (apply_autocmds_exarg(EVENT_FILEREADCMD, sfname, sfname,
398 FALSE, NULL, eap))
399#ifdef FEAT_EVAL
400 return aborting() ? FAIL : OK;
401#else
402 return OK;
403#endif
404
405 curbuf->b_op_start = pos;
406 }
407#endif
408
409 if ((shortmess(SHM_OVER) || curbuf->b_help) && p_verbose == 0)
410 msg_scroll = FALSE; /* overwrite previous file message */
411 else
412 msg_scroll = TRUE; /* don't overwrite previous file message */
413
414 /*
415 * If the name ends in a path separator, we can't open it. Check here,
416 * because reading the file may actually work, but then creating the swap
417 * file may destroy it! Reported on MS-DOS and Win 95.
418 * If the name is too long we might crash further on, quit here.
419 */
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000420 if (fname != NULL && *fname != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000421 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000422 p = fname + STRLEN(fname);
423 if (after_pathsep(fname, p) || STRLEN(fname) >= MAXPATHL)
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000424 {
425 filemess(curbuf, fname, (char_u *)_("Illegal file name"), 0);
426 msg_end();
427 msg_scroll = msg_save;
428 return FAIL;
429 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000430 }
431
Bram Moolenaarf71d7b92016-08-09 22:14:05 +0200432 if (!read_stdin && !read_buffer && !read_fifo)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000433 {
Bram Moolenaar4e4f5292013-08-30 17:07:01 +0200434#ifdef UNIX
435 /*
436 * On Unix it is possible to read a directory, so we have to
437 * check for it before the mch_open().
438 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000439 perm = mch_getperm(fname);
440 if (perm >= 0 && !S_ISREG(perm) /* not a regular file ... */
441# ifdef S_ISFIFO
442 && !S_ISFIFO(perm) /* ... or fifo */
443# endif
444# ifdef S_ISSOCK
445 && !S_ISSOCK(perm) /* ... or socket */
446# endif
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +0000447# ifdef OPEN_CHR_FILES
448 && !(S_ISCHR(perm) && is_dev_fd_file(fname))
449 /* ... or a character special file named /dev/fd/<n> */
450# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000451 )
452 {
453 if (S_ISDIR(perm))
454 filemess(curbuf, fname, (char_u *)_("is a directory"), 0);
455 else
456 filemess(curbuf, fname, (char_u *)_("is not a file"), 0);
457 msg_end();
458 msg_scroll = msg_save;
459 return FAIL;
460 }
Bram Moolenaar4e4f5292013-08-30 17:07:01 +0200461#endif
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100462#if defined(MSWIN)
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000463 /*
464 * MS-Windows allows opening a device, but we will probably get stuck
465 * trying to read it.
466 */
467 if (!p_odev && mch_nodetype(fname) == NODE_WRITABLE)
468 {
Bram Moolenaar5386a122007-06-28 20:02:32 +0000469 filemess(curbuf, fname, (char_u *)_("is a device (disabled with 'opendevice' option)"), 0);
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000470 msg_end();
471 msg_scroll = msg_save;
472 return FAIL;
473 }
Bram Moolenaar043545e2006-10-10 16:44:07 +0000474#endif
Bram Moolenaar4e4f5292013-08-30 17:07:01 +0200475 }
Bram Moolenaar043545e2006-10-10 16:44:07 +0000476
Bram Moolenaarad875fb2013-07-24 15:02:03 +0200477 /* Set default or forced 'fileformat' and 'binary'. */
478 set_file_options(set_options, eap);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000479
480 /*
481 * When opening a new file we take the readonly flag from the file.
482 * Default is r/w, can be set to r/o below.
483 * Don't reset it when in readonly mode
484 * Only set/reset b_p_ro when BF_CHECK_RO is set.
485 */
486 check_readonly = (newfile && (curbuf->b_flags & BF_CHECK_RO));
Bram Moolenaar4399ef42005-02-12 14:29:27 +0000487 if (check_readonly && !readonlymode)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000488 curbuf->b_p_ro = FALSE;
489
Bram Moolenaarf71d7b92016-08-09 22:14:05 +0200490 if (newfile && !read_stdin && !read_buffer && !read_fifo)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000491 {
Bram Moolenaare60acc12011-05-10 16:41:25 +0200492 /* Remember time of file. */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000493 if (mch_stat((char *)fname, &st) >= 0)
494 {
495 buf_store_time(curbuf, &st, fname);
496 curbuf->b_mtime_read = curbuf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000497#ifdef UNIX
498 /*
499 * Use the protection bits of the original file for the swap file.
500 * This makes it possible for others to read the name of the
501 * edited file from the swapfile, but only if they can read the
502 * edited file.
503 * Remove the "write" and "execute" bits for group and others
504 * (they must not write the swapfile).
505 * Add the "read" and "write" bits for the user, otherwise we may
506 * not be able to write to the file ourselves.
507 * Setting the bits is done below, after creating the swap file.
508 */
509 swap_mode = (st.st_mode & 0644) | 0600;
510#endif
511#ifdef FEAT_CW_EDITOR
512 /* Get the FSSpec on MacOS
513 * TODO: Update it properly when the buffer name changes
514 */
515 (void)GetFSSpecFromPath(curbuf->b_ffname, &curbuf->b_FSSpec);
516#endif
517#ifdef VMS
518 curbuf->b_fab_rfm = st.st_fab_rfm;
Bram Moolenaard4755bb2004-09-02 19:12:26 +0000519 curbuf->b_fab_rat = st.st_fab_rat;
520 curbuf->b_fab_mrs = st.st_fab_mrs;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000521#endif
522 }
523 else
524 {
525 curbuf->b_mtime = 0;
526 curbuf->b_mtime_read = 0;
527 curbuf->b_orig_size = 0;
528 curbuf->b_orig_mode = 0;
529 }
530
531 /* Reset the "new file" flag. It will be set again below when the
532 * file doesn't exist. */
533 curbuf->b_flags &= ~(BF_NEW | BF_NEW_W);
534 }
535
536/*
537 * for UNIX: check readonly with perm and mch_access()
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100538 * for Amiga: check readonly by trying to open the file for writing
Bram Moolenaar071d4272004-06-13 20:20:40 +0000539 */
540 file_readonly = FALSE;
541 if (read_stdin)
542 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100543#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000544 /* Force binary I/O on stdin to avoid CR-LF -> LF conversion. */
545 setmode(0, O_BINARY);
546#endif
547 }
548 else if (!read_buffer)
549 {
550#ifdef USE_MCH_ACCESS
551 if (
552# ifdef UNIX
553 !(perm & 0222) ||
554# endif
555 mch_access((char *)fname, W_OK))
556 file_readonly = TRUE;
557 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
558#else
559 if (!newfile
560 || readonlymode
561 || (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0)
562 {
563 file_readonly = TRUE;
564 /* try to open ro */
565 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
566 }
567#endif
568 }
569
570 if (fd < 0) /* cannot open at all */
571 {
572#ifndef UNIX
573 int isdir_f;
574#endif
575 msg_scroll = msg_save;
576#ifndef UNIX
577 /*
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100578 * On Amiga we can't open a directory, check here.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000579 */
580 isdir_f = (mch_isdir(fname));
581 perm = mch_getperm(fname); /* check if the file exists */
582 if (isdir_f)
583 {
584 filemess(curbuf, sfname, (char_u *)_("is a directory"), 0);
585 curbuf->b_p_ro = TRUE; /* must use "w!" now */
586 }
587 else
588#endif
589 if (newfile)
590 {
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200591 if (perm < 0
592#ifdef ENOENT
593 && errno == ENOENT
594#endif
595 )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000596 {
597 /*
598 * Set the 'new-file' flag, so that when the file has
599 * been created by someone else, a ":w" will complain.
600 */
601 curbuf->b_flags |= BF_NEW;
602
603 /* Create a swap file now, so that other Vims are warned
604 * that we are editing this file. Don't do this for a
605 * "nofile" or "nowrite" buffer type. */
606#ifdef FEAT_QUICKFIX
607 if (!bt_dontwrite(curbuf))
608#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000609 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000610 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000611#ifdef FEAT_AUTOCMD
612 /* SwapExists autocommand may mess things up */
613 if (curbuf != old_curbuf
614 || (using_b_ffname
615 && (old_b_ffname != curbuf->b_ffname))
616 || (using_b_fname
617 && (old_b_fname != curbuf->b_fname)))
618 {
619 EMSG(_(e_auchangedbuf));
620 return FAIL;
621 }
622#endif
623 }
Bram Moolenaar5b962cf2005-12-12 21:58:40 +0000624 if (dir_of_file_exists(fname))
625 filemess(curbuf, sfname, (char_u *)_("[New File]"), 0);
626 else
627 filemess(curbuf, sfname,
628 (char_u *)_("[New DIRECTORY]"), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000629#ifdef FEAT_VIMINFO
630 /* Even though this is a new file, it might have been
631 * edited before and deleted. Get the old marks. */
632 check_marks_read();
633#endif
634#ifdef FEAT_MBYTE
Bram Moolenaarad875fb2013-07-24 15:02:03 +0200635 /* Set forced 'fileencoding'. */
636 if (eap != NULL)
637 set_forced_fenc(eap);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000638#endif
639#ifdef FEAT_AUTOCMD
640 apply_autocmds_exarg(EVENT_BUFNEWFILE, sfname, sfname,
641 FALSE, curbuf, eap);
642#endif
643 /* remember the current fileformat */
644 save_file_ff(curbuf);
645
646#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
647 if (aborting()) /* autocmds may abort script processing */
648 return FAIL;
649#endif
650 return OK; /* a new file is not an error */
651 }
652 else
653 {
Bram Moolenaar202795b2005-10-11 20:29:39 +0000654 filemess(curbuf, sfname, (char_u *)(
655# ifdef EFBIG
656 (errno == EFBIG) ? _("[File too big]") :
657# endif
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200658# ifdef EOVERFLOW
659 (errno == EOVERFLOW) ? _("[File too big]") :
660# endif
Bram Moolenaar202795b2005-10-11 20:29:39 +0000661 _("[Permission Denied]")), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000662 curbuf->b_p_ro = TRUE; /* must use "w!" now */
663 }
664 }
665
666 return FAIL;
667 }
668
669 /*
670 * Only set the 'ro' flag for readonly files the first time they are
671 * loaded. Help files always get readonly mode
672 */
673 if ((check_readonly && file_readonly) || curbuf->b_help)
674 curbuf->b_p_ro = TRUE;
675
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000676 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000677 {
Bram Moolenaar690ffc02008-01-04 15:31:21 +0000678 /* Don't change 'eol' if reading from buffer as it will already be
679 * correctly set when reading stdin. */
680 if (!read_buffer)
681 {
682 curbuf->b_p_eol = TRUE;
683 curbuf->b_start_eol = TRUE;
684 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000685#ifdef FEAT_MBYTE
686 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000687 curbuf->b_start_bomb = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000688#endif
689 }
690
691 /* Create a swap file now, so that other Vims are warned that we are
692 * editing this file.
693 * Don't do this for a "nofile" or "nowrite" buffer type. */
694#ifdef FEAT_QUICKFIX
695 if (!bt_dontwrite(curbuf))
696#endif
697 {
698 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000699#ifdef FEAT_AUTOCMD
700 if (!read_stdin && (curbuf != old_curbuf
701 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
702 || (using_b_fname && (old_b_fname != curbuf->b_fname))))
703 {
704 EMSG(_(e_auchangedbuf));
705 if (!read_buffer)
706 close(fd);
707 return FAIL;
708 }
709#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000710#ifdef UNIX
711 /* Set swap file protection bits after creating it. */
Bram Moolenaarf061e0b2009-06-24 15:32:01 +0000712 if (swap_mode > 0 && curbuf->b_ml.ml_mfp != NULL
713 && curbuf->b_ml.ml_mfp->mf_fname != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000714 (void)mch_setperm(curbuf->b_ml.ml_mfp->mf_fname, (long)swap_mode);
715#endif
716 }
717
Bram Moolenaarb815dac2005-12-07 20:59:24 +0000718#if defined(HAS_SWAP_EXISTS_ACTION)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000719 /* If "Quit" selected at ATTENTION dialog, don't load the file */
720 if (swap_exists_action == SEA_QUIT)
721 {
722 if (!read_buffer && !read_stdin)
723 close(fd);
724 return FAIL;
725 }
726#endif
727
728 ++no_wait_return; /* don't wait for return yet */
729
730 /*
731 * Set '[ mark to the line above where the lines go (line 1 if zero).
732 */
733 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
734 curbuf->b_op_start.col = 0;
735
736#ifdef FEAT_AUTOCMD
737 if (!read_buffer)
738 {
739 int m = msg_scroll;
740 int n = msg_scrolled;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000741
742 /*
743 * The file must be closed again, the autocommands may want to change
744 * the file before reading it.
745 */
746 if (!read_stdin)
747 close(fd); /* ignore errors */
748
749 /*
750 * The output from the autocommands should not overwrite anything and
751 * should not be overwritten: Set msg_scroll, restore its value if no
752 * output was done.
753 */
754 msg_scroll = TRUE;
755 if (filtering)
756 apply_autocmds_exarg(EVENT_FILTERREADPRE, NULL, sfname,
757 FALSE, curbuf, eap);
758 else if (read_stdin)
759 apply_autocmds_exarg(EVENT_STDINREADPRE, NULL, sfname,
760 FALSE, curbuf, eap);
761 else if (newfile)
762 apply_autocmds_exarg(EVENT_BUFREADPRE, NULL, sfname,
763 FALSE, curbuf, eap);
764 else
765 apply_autocmds_exarg(EVENT_FILEREADPRE, sfname, sfname,
766 FALSE, NULL, eap);
767 if (msg_scrolled == n)
768 msg_scroll = m;
769
770#ifdef FEAT_EVAL
771 if (aborting()) /* autocmds may abort script processing */
772 {
773 --no_wait_return;
774 msg_scroll = msg_save;
775 curbuf->b_p_ro = TRUE; /* must use "w!" now */
776 return FAIL;
777 }
778#endif
779 /*
780 * Don't allow the autocommands to change the current buffer.
781 * Try to re-open the file.
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000782 *
783 * Don't allow the autocommands to change the buffer name either
784 * (cd for example) if it invalidates fname or sfname.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000785 */
786 if (!read_stdin && (curbuf != old_curbuf
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000787 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
788 || (using_b_fname && (old_b_fname != curbuf->b_fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000789 || (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) < 0))
790 {
791 --no_wait_return;
792 msg_scroll = msg_save;
793 if (fd < 0)
794 EMSG(_("E200: *ReadPre autocommands made the file unreadable"));
795 else
796 EMSG(_("E201: *ReadPre autocommands must not change current buffer"));
797 curbuf->b_p_ro = TRUE; /* must use "w!" now */
798 return FAIL;
799 }
800 }
801#endif /* FEAT_AUTOCMD */
802
803 /* Autocommands may add lines to the file, need to check if it is empty */
804 wasempty = (curbuf->b_ml.ml_flags & ML_EMPTY);
805
806 if (!recoverymode && !filtering && !(flags & READ_DUMMY))
807 {
808 /*
809 * Show the user that we are busy reading the input. Sometimes this
810 * may take a while. When reading from stdin another program may
811 * still be running, don't move the cursor to the last line, unless
812 * always using the GUI.
813 */
814 if (read_stdin)
815 {
816#ifndef ALWAYS_USE_GUI
817 mch_msg(_("Vim: Reading from stdin...\n"));
818#endif
819#ifdef FEAT_GUI
820 /* Also write a message in the GUI window, if there is one. */
821 if (gui.in_use && !gui.dying && !gui.starting)
822 {
823 p = (char_u *)_("Reading from stdin...");
824 gui_write(p, (int)STRLEN(p));
825 }
826#endif
827 }
828 else if (!read_buffer)
829 filemess(curbuf, sfname, (char_u *)"", 0);
830 }
831
832 msg_scroll = FALSE; /* overwrite the file message */
833
834 /*
835 * Set linecnt now, before the "retry" caused by a wrong guess for
836 * fileformat, and after the autocommands, which may change them.
837 */
838 linecnt = curbuf->b_ml.ml_line_count;
839
840#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000841 /* "++bad=" argument. */
842 if (eap != NULL && eap->bad_char != 0)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000843 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000844 bad_char_behavior = eap->bad_char;
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000845 if (set_options)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000846 curbuf->b_bad_char = eap->bad_char;
847 }
848 else
849 curbuf->b_bad_char = 0;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000850
Bram Moolenaar071d4272004-06-13 20:20:40 +0000851 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000852 * Decide which 'encoding' to use or use first.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000853 */
854 if (eap != NULL && eap->force_enc != 0)
855 {
856 fenc = enc_canonize(eap->cmd + eap->force_enc);
857 fenc_alloced = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000858 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000859 }
860 else if (curbuf->b_p_bin)
861 {
862 fenc = (char_u *)""; /* binary: don't convert */
863 fenc_alloced = FALSE;
864 }
865 else if (curbuf->b_help)
866 {
867 char_u firstline[80];
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000868 int fc;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000869
870 /* Help files are either utf-8 or latin1. Try utf-8 first, if this
871 * fails it must be latin1.
872 * Always do this when 'encoding' is "utf-8". Otherwise only do
873 * this when needed to avoid [converted] remarks all the time.
874 * It is needed when the first line contains non-ASCII characters.
875 * That is only in *.??x files. */
876 fenc = (char_u *)"latin1";
877 c = enc_utf8;
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000878 if (!c && !read_stdin)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000879 {
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000880 fc = fname[STRLEN(fname) - 1];
881 if (TOLOWER_ASC(fc) == 'x')
882 {
883 /* Read the first line (and a bit more). Immediately rewind to
884 * the start of the file. If the read() fails "len" is -1. */
Bram Moolenaar540fc6f2010-12-17 16:27:16 +0100885 len = read_eintr(fd, firstline, 80);
Bram Moolenaar8767f522016-07-01 17:17:39 +0200886 vim_lseek(fd, (off_T)0L, SEEK_SET);
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000887 for (p = firstline; p < firstline + len; ++p)
888 if (*p >= 0x80)
889 {
890 c = TRUE;
891 break;
892 }
893 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000894 }
895
896 if (c)
897 {
898 fenc_next = fenc;
899 fenc = (char_u *)"utf-8";
900
901 /* When the file is utf-8 but a character doesn't fit in
902 * 'encoding' don't retry. In help text editing utf-8 bytes
903 * doesn't make sense. */
Bram Moolenaarf193fff2006-04-27 00:02:13 +0000904 if (!enc_utf8)
905 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000906 }
907 fenc_alloced = FALSE;
908 }
909 else if (*p_fencs == NUL)
910 {
911 fenc = curbuf->b_p_fenc; /* use format from buffer */
912 fenc_alloced = FALSE;
913 }
914 else
915 {
916 fenc_next = p_fencs; /* try items in 'fileencodings' */
917 fenc = next_fenc(&fenc_next);
918 fenc_alloced = TRUE;
919 }
920#endif
921
922 /*
923 * Jump back here to retry reading the file in different ways.
924 * Reasons to retry:
925 * - encoding conversion failed: try another one from "fenc_next"
926 * - BOM detected and fenc was set, need to setup conversion
927 * - "fileformat" check failed: try another
928 *
929 * Variables set for special retry actions:
930 * "file_rewind" Rewind the file to start reading it again.
931 * "advance_fenc" Advance "fenc" using "fenc_next".
932 * "skip_read" Re-use already read bytes (BOM detected).
933 * "did_iconv" iconv() conversion failed, try 'charconvert'.
934 * "keep_fileformat" Don't reset "fileformat".
935 *
936 * Other status indicators:
937 * "tmpname" When != NULL did conversion with 'charconvert'.
938 * Output file has to be deleted afterwards.
939 * "iconv_fd" When != -1 did conversion with iconv().
940 */
941retry:
942
943 if (file_rewind)
944 {
945 if (read_buffer)
946 {
947 read_buf_lnum = 1;
948 read_buf_col = 0;
949 }
Bram Moolenaar8767f522016-07-01 17:17:39 +0200950 else if (read_stdin || vim_lseek(fd, (off_T)0L, SEEK_SET) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000951 {
952 /* Can't rewind the file, give up. */
953 error = TRUE;
954 goto failed;
955 }
956 /* Delete the previously read lines. */
957 while (lnum > from)
958 ml_delete(lnum--, FALSE);
959 file_rewind = FALSE;
960#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000961 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000962 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000963 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000964 curbuf->b_start_bomb = FALSE;
965 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000966 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000967#endif
968 }
969
970 /*
971 * When retrying with another "fenc" and the first time "fileformat"
972 * will be reset.
973 */
974 if (keep_fileformat)
975 keep_fileformat = FALSE;
976 else
977 {
978 if (eap != NULL && eap->force_ff != 0)
Bram Moolenaar1c860362008-11-12 15:05:21 +0000979 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000980 fileformat = get_fileformat_force(curbuf, eap);
Bram Moolenaar1c860362008-11-12 15:05:21 +0000981 try_unix = try_dos = try_mac = FALSE;
982 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000983 else if (curbuf->b_p_bin)
984 fileformat = EOL_UNIX; /* binary: use Unix format */
985 else if (*p_ffs == NUL)
986 fileformat = get_fileformat(curbuf);/* use format from buffer */
987 else
988 fileformat = EOL_UNKNOWN; /* detect from file */
989 }
990
991#ifdef FEAT_MBYTE
992# ifdef USE_ICONV
993 if (iconv_fd != (iconv_t)-1)
994 {
995 /* aborted conversion with iconv(), close the descriptor */
996 iconv_close(iconv_fd);
997 iconv_fd = (iconv_t)-1;
998 }
999# endif
1000
1001 if (advance_fenc)
1002 {
1003 /*
1004 * Try the next entry in 'fileencodings'.
1005 */
1006 advance_fenc = FALSE;
1007
1008 if (eap != NULL && eap->force_enc != 0)
1009 {
1010 /* Conversion given with "++cc=" wasn't possible, read
1011 * without conversion. */
1012 notconverted = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001013 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001014 if (fenc_alloced)
1015 vim_free(fenc);
1016 fenc = (char_u *)"";
1017 fenc_alloced = FALSE;
1018 }
1019 else
1020 {
1021 if (fenc_alloced)
1022 vim_free(fenc);
1023 if (fenc_next != NULL)
1024 {
1025 fenc = next_fenc(&fenc_next);
1026 fenc_alloced = (fenc_next != NULL);
1027 }
1028 else
1029 {
1030 fenc = (char_u *)"";
1031 fenc_alloced = FALSE;
1032 }
1033 }
1034 if (tmpname != NULL)
1035 {
1036 mch_remove(tmpname); /* delete converted file */
1037 vim_free(tmpname);
1038 tmpname = NULL;
1039 }
1040 }
1041
1042 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001043 * Conversion may be required when the encoding of the file is different
1044 * from 'encoding' or 'encoding' is UTF-16, UCS-2 or UCS-4.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001045 */
1046 fio_flags = 0;
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001047 converted = need_conversion(fenc);
1048 if (converted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001049 {
1050
1051 /* "ucs-bom" means we need to check the first bytes of the file
1052 * for a BOM. */
1053 if (STRCMP(fenc, ENC_UCSBOM) == 0)
1054 fio_flags = FIO_UCSBOM;
1055
1056 /*
1057 * Check if UCS-2/4 or Latin1 to UTF-8 conversion needs to be
1058 * done. This is handled below after read(). Prepare the
1059 * fio_flags to avoid having to parse the string each time.
1060 * Also check for Unicode to Latin1 conversion, because iconv()
1061 * appears not to handle this correctly. This works just like
1062 * conversion to UTF-8 except how the resulting character is put in
1063 * the buffer.
1064 */
1065 else if (enc_utf8 || STRCMP(p_enc, "latin1") == 0)
1066 fio_flags = get_fio_flags(fenc);
1067
1068# ifdef WIN3264
1069 /*
1070 * Conversion from an MS-Windows codepage to UTF-8 or another codepage
1071 * is handled with MultiByteToWideChar().
1072 */
1073 if (fio_flags == 0)
1074 fio_flags = get_win_fio_flags(fenc);
1075# endif
1076
1077# ifdef MACOS_X
1078 /* Conversion from Apple MacRoman to latin1 or UTF-8 */
1079 if (fio_flags == 0)
1080 fio_flags = get_mac_fio_flags(fenc);
1081# endif
1082
1083# ifdef USE_ICONV
1084 /*
1085 * Try using iconv() if we can't convert internally.
1086 */
1087 if (fio_flags == 0
1088# ifdef FEAT_EVAL
1089 && !did_iconv
1090# endif
1091 )
1092 iconv_fd = (iconv_t)my_iconv_open(
1093 enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc);
1094# endif
1095
1096# ifdef FEAT_EVAL
1097 /*
1098 * Use the 'charconvert' expression when conversion is required
1099 * and we can't do it internally or with iconv().
1100 */
1101 if (fio_flags == 0 && !read_stdin && !read_buffer && *p_ccv != NUL
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02001102 && !read_fifo
Bram Moolenaar071d4272004-06-13 20:20:40 +00001103# ifdef USE_ICONV
1104 && iconv_fd == (iconv_t)-1
1105# endif
1106 )
1107 {
1108# ifdef USE_ICONV
1109 did_iconv = FALSE;
1110# endif
1111 /* Skip conversion when it's already done (retry for wrong
1112 * "fileformat"). */
1113 if (tmpname == NULL)
1114 {
1115 tmpname = readfile_charconvert(fname, fenc, &fd);
1116 if (tmpname == NULL)
1117 {
1118 /* Conversion failed. Try another one. */
1119 advance_fenc = TRUE;
1120 if (fd < 0)
1121 {
1122 /* Re-opening the original file failed! */
1123 EMSG(_("E202: Conversion made file unreadable!"));
1124 error = TRUE;
1125 goto failed;
1126 }
1127 goto retry;
1128 }
1129 }
1130 }
1131 else
1132# endif
1133 {
1134 if (fio_flags == 0
1135# ifdef USE_ICONV
1136 && iconv_fd == (iconv_t)-1
1137# endif
1138 )
1139 {
1140 /* Conversion wanted but we can't.
1141 * Try the next conversion in 'fileencodings' */
1142 advance_fenc = TRUE;
1143 goto retry;
1144 }
1145 }
1146 }
1147
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001148 /* Set "can_retry" when it's possible to rewind the file and try with
Bram Moolenaar071d4272004-06-13 20:20:40 +00001149 * another "fenc" value. It's FALSE when no other "fenc" to try, reading
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001150 * stdin or fixed at a specific encoding. */
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02001151 can_retry = (*fenc != NUL && !read_stdin && !read_fifo && !keep_dest_enc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001152#endif
1153
1154 if (!skip_read)
1155 {
1156 linerest = 0;
1157 filesize = 0;
1158 skip_count = lines_to_skip;
1159 read_count = lines_to_read;
1160#ifdef FEAT_MBYTE
1161 conv_restlen = 0;
1162#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001163#ifdef FEAT_PERSISTENT_UNDO
Bram Moolenaar59f931e2010-07-24 20:27:03 +02001164 read_undo_file = (newfile && (flags & READ_KEEP_UNDO) == 0
1165 && curbuf->b_ffname != NULL
1166 && curbuf->b_p_udf
1167 && !filtering
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02001168 && !read_fifo
Bram Moolenaar59f931e2010-07-24 20:27:03 +02001169 && !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 Moolenaarf71d7b92016-08-09 22:14:05 +02002669 if (!read_stdin && !read_fifo && (!read_buffer || sfname != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002670 {
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);
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02002688 else if (newfile || (read_buffer && sfname != NULL))
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 Moolenaarf04507d2016-08-20 15:05:39 +02002717#if defined(OPEN_CHR_FILES) || defined(PROTO)
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002718/*
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 */
Bram Moolenaarf04507d2016-08-20 15:05:39 +02002724 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);
Bram Moolenaar680e0152016-09-25 20:54:11 +02003014 if (*sizep <= header_len)
3015 /* invalid header, buffer can't be encrypted */
3016 return NULL;
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003017 *filesizep += header_len;
3018 *sizep -= header_len;
3019 mch_memmove(ptr, ptr + header_len, (size_t)*sizep);
3020
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02003021 /* Restore the read-only flag. */
3022 curbuf->b_p_ro = b_p_ro;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003023 }
3024 }
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003025 /* When starting to edit a new file which does not have encryption, clear
3026 * the 'key' option, except when starting up (called with -x argument) */
Bram Moolenaarfa0ff9a2010-07-25 16:05:19 +02003027 else if (newfile && *curbuf->b_p_key != NUL && !starting)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003028 set_option_value((char_u *)"key", 0L, (char_u *)"", OPT_LOCAL);
3029
3030 return cryptkey;
3031}
Bram Moolenaar80794b12010-06-13 05:20:42 +02003032#endif /* FEAT_CRYPT */
3033
Bram Moolenaar071d4272004-06-13 20:20:40 +00003034#ifdef UNIX
3035 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003036set_file_time(
3037 char_u *fname,
3038 time_t atime, /* access time */
3039 time_t mtime) /* modification time */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003040{
3041# if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
3042 struct utimbuf buf;
3043
3044 buf.actime = atime;
3045 buf.modtime = mtime;
3046 (void)utime((char *)fname, &buf);
3047# else
3048# if defined(HAVE_UTIMES)
3049 struct timeval tvp[2];
3050
3051 tvp[0].tv_sec = atime;
3052 tvp[0].tv_usec = 0;
3053 tvp[1].tv_sec = mtime;
3054 tvp[1].tv_usec = 0;
3055# ifdef NeXT
3056 (void)utimes((char *)fname, tvp);
3057# else
3058 (void)utimes((char *)fname, (const struct timeval *)&tvp);
3059# endif
3060# endif
3061# endif
3062}
3063#endif /* UNIX */
3064
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003065#if defined(VMS) && !defined(MIN)
3066/* Older DECC compiler for VAX doesn't define MIN() */
3067# define MIN(a, b) ((a) < (b) ? (a) : (b))
3068#endif
3069
Bram Moolenaar071d4272004-06-13 20:20:40 +00003070/*
Bram Moolenaar5386a122007-06-28 20:02:32 +00003071 * Return TRUE if a file appears to be read-only from the file permissions.
3072 */
3073 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003074check_file_readonly(
3075 char_u *fname, /* full path to file */
3076 int perm) /* known permissions on file */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003077{
3078#ifndef USE_MCH_ACCESS
3079 int fd = 0;
3080#endif
3081
3082 return (
3083#ifdef USE_MCH_ACCESS
3084# ifdef UNIX
3085 (perm & 0222) == 0 ||
3086# endif
3087 mch_access((char *)fname, W_OK)
3088#else
3089 (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0
3090 ? TRUE : (close(fd), FALSE)
3091#endif
3092 );
3093}
3094
3095
3096/*
Bram Moolenaar292ad192005-12-11 21:29:51 +00003097 * buf_write() - write to file "fname" lines "start" through "end"
Bram Moolenaar071d4272004-06-13 20:20:40 +00003098 *
3099 * We do our own buffering here because fwrite() is so slow.
3100 *
Bram Moolenaar292ad192005-12-11 21:29:51 +00003101 * If "forceit" is true, we don't care for errors when attempting backups.
3102 * In case of an error everything possible is done to restore the original
Bram Moolenaare37d50a2008-08-06 17:06:04 +00003103 * file. But when "forceit" is TRUE, we risk losing it.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003104 *
3105 * When "reset_changed" is TRUE and "append" == FALSE and "start" == 1 and
3106 * "end" == curbuf->b_ml.ml_line_count, reset curbuf->b_changed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003107 *
3108 * This function must NOT use NameBuff (because it's called by autowrite()).
3109 *
3110 * return FAIL for failure, OK otherwise
3111 */
3112 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003113buf_write(
3114 buf_T *buf,
3115 char_u *fname,
3116 char_u *sfname,
3117 linenr_T start,
3118 linenr_T end,
3119 exarg_T *eap, /* for forced 'ff' and 'fenc', can be
Bram Moolenaar071d4272004-06-13 20:20:40 +00003120 NULL! */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003121 int append, /* append to the file */
3122 int forceit,
3123 int reset_changed,
3124 int filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003125{
3126 int fd;
3127 char_u *backup = NULL;
3128 int backup_copy = FALSE; /* copy the original file? */
3129 int dobackup;
3130 char_u *ffname;
3131 char_u *wfname = NULL; /* name of file to write to */
3132 char_u *s;
3133 char_u *ptr;
3134 char_u c;
3135 int len;
3136 linenr_T lnum;
3137 long nchars;
3138 char_u *errmsg = NULL;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003139 int errmsg_allocated = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003140 char_u *errnum = NULL;
3141 char_u *buffer;
3142 char_u smallbuf[SMBUFSIZE];
3143 char_u *backup_ext;
3144 int bufsize;
3145 long perm; /* file permissions */
3146 int retval = OK;
3147 int newfile = FALSE; /* TRUE if file doesn't exist yet */
3148 int msg_save = msg_scroll;
3149 int overwriting; /* TRUE if writing over original */
3150 int no_eol = FALSE; /* no end-of-line written */
3151 int device = FALSE; /* writing to a device */
Bram Moolenaar8767f522016-07-01 17:17:39 +02003152 stat_T st_old;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003153 int prev_got_int = got_int;
3154 int file_readonly = FALSE; /* overwritten file is read-only */
3155 static char *err_readonly = "is read-only (cannot override: \"W\" in 'cpoptions')";
Bram Moolenaara06ecab2016-07-16 14:47:36 +02003156#if defined(UNIX) /*XXX fix me sometime? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003157 int made_writable = FALSE; /* 'w' bit has been set */
3158#endif
3159 /* writing everything */
3160 int whole = (start == 1 && end == buf->b_ml.ml_line_count);
3161#ifdef FEAT_AUTOCMD
3162 linenr_T old_line_count = buf->b_ml.ml_line_count;
3163#endif
3164 int attr;
3165 int fileformat;
3166 int write_bin;
3167 struct bw_info write_info; /* info for buf_write_bytes() */
3168#ifdef FEAT_MBYTE
3169 int converted = FALSE;
3170 int notconverted = FALSE;
3171 char_u *fenc; /* effective 'fileencoding' */
3172 char_u *fenc_tofree = NULL; /* allocated "fenc" */
3173#endif
3174#ifdef HAS_BW_FLAGS
3175 int wb_flags = 0;
3176#endif
3177#ifdef HAVE_ACL
3178 vim_acl_T acl = NULL; /* ACL copied from original file to
3179 backup or new file */
3180#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003181#ifdef FEAT_PERSISTENT_UNDO
3182 int write_undo_file = FALSE;
3183 context_sha256_T sha_ctx;
3184#endif
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003185 unsigned int bkc = get_bkc_value(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003186
3187 if (fname == NULL || *fname == NUL) /* safety check */
3188 return FAIL;
Bram Moolenaar70d60e92009-12-31 13:53:33 +00003189 if (buf->b_ml.ml_mfp == NULL)
3190 {
3191 /* This can happen during startup when there is a stray "w" in the
3192 * vimrc file. */
3193 EMSG(_(e_emptybuf));
3194 return FAIL;
3195 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003196
3197 /*
3198 * Disallow writing from .exrc and .vimrc in current directory for
3199 * security reasons.
3200 */
3201 if (check_secure())
3202 return FAIL;
3203
3204 /* Avoid a crash for a long name. */
3205 if (STRLEN(fname) >= MAXPATHL)
3206 {
3207 EMSG(_(e_longname));
3208 return FAIL;
3209 }
3210
3211#ifdef FEAT_MBYTE
3212 /* must init bw_conv_buf and bw_iconv_fd before jumping to "fail" */
3213 write_info.bw_conv_buf = NULL;
3214 write_info.bw_conv_error = FALSE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003215 write_info.bw_conv_error_lnum = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003216 write_info.bw_restlen = 0;
3217# ifdef USE_ICONV
3218 write_info.bw_iconv_fd = (iconv_t)-1;
3219# endif
3220#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003221#ifdef FEAT_CRYPT
3222 write_info.bw_buffer = buf;
3223#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003224
Bram Moolenaardf177f62005-02-22 08:39:57 +00003225 /* After writing a file changedtick changes but we don't want to display
3226 * the line. */
3227 ex_no_reprint = TRUE;
3228
Bram Moolenaar071d4272004-06-13 20:20:40 +00003229 /*
3230 * If there is no file name yet, use the one for the written file.
3231 * BF_NOTEDITED is set to reflect this (in case the write fails).
3232 * Don't do this when the write is for a filter command.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003233 * Don't do this when appending.
3234 * Only do this when 'cpoptions' contains the 'F' flag.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003235 */
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003236 if (buf->b_ffname == NULL
3237 && reset_changed
Bram Moolenaar071d4272004-06-13 20:20:40 +00003238 && whole
3239 && buf == curbuf
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00003240#ifdef FEAT_QUICKFIX
3241 && !bt_nofile(buf)
3242#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003243 && !filtering
Bram Moolenaar292ad192005-12-11 21:29:51 +00003244 && (!append || vim_strchr(p_cpo, CPO_FNAMEAPP) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003245 && vim_strchr(p_cpo, CPO_FNAMEW) != NULL)
3246 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003247 if (set_rw_fname(fname, sfname) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003248 return FAIL;
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003249 buf = curbuf; /* just in case autocmds made "buf" invalid */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003250 }
3251
3252 if (sfname == NULL)
3253 sfname = fname;
3254 /*
3255 * For Unix: Use the short file name whenever possible.
3256 * Avoids problems with networks and when directory names are changed.
3257 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
3258 * another directory, which we don't detect
3259 */
3260 ffname = fname; /* remember full fname */
3261#ifdef UNIX
3262 fname = sfname;
3263#endif
3264
3265 if (buf->b_ffname != NULL && fnamecmp(ffname, buf->b_ffname) == 0)
3266 overwriting = TRUE;
3267 else
3268 overwriting = FALSE;
3269
3270 if (exiting)
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003271 settmode(TMODE_COOK); /* when exiting allow typeahead now */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003272
3273 ++no_wait_return; /* don't wait for return yet */
3274
3275 /*
3276 * Set '[ and '] marks to the lines to be written.
3277 */
3278 buf->b_op_start.lnum = start;
3279 buf->b_op_start.col = 0;
3280 buf->b_op_end.lnum = end;
3281 buf->b_op_end.col = 0;
3282
3283#ifdef FEAT_AUTOCMD
3284 {
3285 aco_save_T aco;
3286 int buf_ffname = FALSE;
3287 int buf_sfname = FALSE;
3288 int buf_fname_f = FALSE;
3289 int buf_fname_s = FALSE;
3290 int did_cmd = FALSE;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003291 int nofile_err = FALSE;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003292 int empty_memline = (buf->b_ml.ml_mfp == NULL);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003293 bufref_T bufref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003294
3295 /*
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003296 * Apply PRE autocommands.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003297 * Set curbuf to the buffer to be written.
3298 * Careful: The autocommands may call buf_write() recursively!
3299 */
3300 if (ffname == buf->b_ffname)
3301 buf_ffname = TRUE;
3302 if (sfname == buf->b_sfname)
3303 buf_sfname = TRUE;
3304 if (fname == buf->b_ffname)
3305 buf_fname_f = TRUE;
3306 if (fname == buf->b_sfname)
3307 buf_fname_s = TRUE;
3308
3309 /* set curwin/curbuf to buf and save a few things */
3310 aucmd_prepbuf(&aco, buf);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003311 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003312
3313 if (append)
3314 {
3315 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD,
3316 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003317 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003318#ifdef FEAT_QUICKFIX
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00003319 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003320 nofile_err = TRUE;
3321 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003322#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003323 apply_autocmds_exarg(EVENT_FILEAPPENDPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003324 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003325 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003326 }
3327 else if (filtering)
3328 {
3329 apply_autocmds_exarg(EVENT_FILTERWRITEPRE,
3330 NULL, sfname, FALSE, curbuf, eap);
3331 }
3332 else if (reset_changed && whole)
3333 {
Bram Moolenaar39fc42e2011-09-02 11:56:20 +02003334 int was_changed = curbufIsChanged();
3335
3336 did_cmd = apply_autocmds_exarg(EVENT_BUFWRITECMD,
3337 sfname, sfname, FALSE, curbuf, eap);
3338 if (did_cmd)
3339 {
3340 if (was_changed && !curbufIsChanged())
3341 {
3342 /* Written everything correctly and BufWriteCmd has reset
3343 * 'modified': Correct the undo information so that an
3344 * undo now sets 'modified'. */
3345 u_unchanged(curbuf);
3346 u_update_save_nr(curbuf);
3347 }
3348 }
3349 else
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003350 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003351#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003352 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003353 nofile_err = TRUE;
3354 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003355#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003356 apply_autocmds_exarg(EVENT_BUFWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003357 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003358 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003359 }
3360 else
3361 {
3362 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD,
3363 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003364 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003365#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003366 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003367 nofile_err = TRUE;
3368 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003369#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003370 apply_autocmds_exarg(EVENT_FILEWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003371 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003372 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003373 }
3374
3375 /* restore curwin/curbuf and a few other things */
3376 aucmd_restbuf(&aco);
3377
3378 /*
3379 * In three situations we return here and don't write the file:
3380 * 1. the autocommands deleted or unloaded the buffer.
3381 * 2. The autocommands abort script processing.
3382 * 3. If one of the "Cmd" autocommands was executed.
3383 */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003384 if (!bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003385 buf = NULL;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003386 if (buf == NULL || (buf->b_ml.ml_mfp == NULL && !empty_memline)
Bram Moolenaar1e015462005-09-25 22:16:38 +00003387 || did_cmd || nofile_err
3388#ifdef FEAT_EVAL
3389 || aborting()
3390#endif
3391 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003392 {
3393 --no_wait_return;
3394 msg_scroll = msg_save;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003395 if (nofile_err)
3396 EMSG(_("E676: No matching autocommands for acwrite buffer"));
3397
Bram Moolenaar1e015462005-09-25 22:16:38 +00003398 if (nofile_err
3399#ifdef FEAT_EVAL
3400 || aborting()
3401#endif
3402 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003403 /* An aborting error, interrupt or exception in the
3404 * autocommands. */
3405 return FAIL;
3406 if (did_cmd)
3407 {
3408 if (buf == NULL)
3409 /* The buffer was deleted. We assume it was written
3410 * (can't retry anyway). */
3411 return OK;
3412 if (overwriting)
3413 {
3414 /* Assume the buffer was written, update the timestamp. */
3415 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00003416 if (append)
3417 buf->b_flags &= ~BF_NEW;
3418 else
3419 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003420 }
Bram Moolenaar292ad192005-12-11 21:29:51 +00003421 if (reset_changed && buf->b_changed && !append
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003422 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003423 /* Buffer still changed, the autocommands didn't work
3424 * properly. */
3425 return FAIL;
3426 return OK;
3427 }
3428#ifdef FEAT_EVAL
3429 if (!aborting())
3430#endif
3431 EMSG(_("E203: Autocommands deleted or unloaded buffer to be written"));
3432 return FAIL;
3433 }
3434
3435 /*
3436 * The autocommands may have changed the number of lines in the file.
3437 * When writing the whole file, adjust the end.
3438 * When writing part of the file, assume that the autocommands only
3439 * changed the number of lines that are to be written (tricky!).
3440 */
3441 if (buf->b_ml.ml_line_count != old_line_count)
3442 {
3443 if (whole) /* write all */
3444 end = buf->b_ml.ml_line_count;
3445 else if (buf->b_ml.ml_line_count > old_line_count) /* more lines */
3446 end += buf->b_ml.ml_line_count - old_line_count;
3447 else /* less lines */
3448 {
3449 end -= old_line_count - buf->b_ml.ml_line_count;
3450 if (end < start)
3451 {
3452 --no_wait_return;
3453 msg_scroll = msg_save;
3454 EMSG(_("E204: Autocommand changed number of lines in unexpected way"));
3455 return FAIL;
3456 }
3457 }
3458 }
3459
3460 /*
3461 * The autocommands may have changed the name of the buffer, which may
3462 * be kept in fname, ffname and sfname.
3463 */
3464 if (buf_ffname)
3465 ffname = buf->b_ffname;
3466 if (buf_sfname)
3467 sfname = buf->b_sfname;
3468 if (buf_fname_f)
3469 fname = buf->b_ffname;
3470 if (buf_fname_s)
3471 fname = buf->b_sfname;
3472 }
3473#endif
3474
3475#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003476 if (netbeans_active() && isNetbeansBuffer(buf))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003477 {
3478 if (whole)
3479 {
3480 /*
3481 * b_changed can be 0 after an undo, but we still need to write
3482 * the buffer to NetBeans.
3483 */
3484 if (buf->b_changed || isNetbeansModified(buf))
3485 {
Bram Moolenaar009b2592004-10-24 19:18:58 +00003486 --no_wait_return; /* may wait for return now */
3487 msg_scroll = msg_save;
3488 netbeans_save_buffer(buf); /* no error checking... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003489 return retval;
3490 }
3491 else
3492 {
3493 errnum = (char_u *)"E656: ";
Bram Moolenaared0e7452008-06-27 19:17:34 +00003494 errmsg = (char_u *)_("NetBeans disallows writes of unmodified buffers");
Bram Moolenaar071d4272004-06-13 20:20:40 +00003495 buffer = NULL;
3496 goto fail;
3497 }
3498 }
3499 else
3500 {
3501 errnum = (char_u *)"E657: ";
3502 errmsg = (char_u *)_("Partial writes disallowed for NetBeans buffers");
3503 buffer = NULL;
3504 goto fail;
3505 }
3506 }
3507#endif
3508
3509 if (shortmess(SHM_OVER) && !exiting)
3510 msg_scroll = FALSE; /* overwrite previous file message */
3511 else
3512 msg_scroll = TRUE; /* don't overwrite previous file message */
3513 if (!filtering)
3514 filemess(buf,
3515#ifndef UNIX
3516 sfname,
3517#else
3518 fname,
3519#endif
3520 (char_u *)"", 0); /* show that we are busy */
3521 msg_scroll = FALSE; /* always overwrite the file message now */
3522
3523 buffer = alloc(BUFSIZE);
3524 if (buffer == NULL) /* can't allocate big buffer, use small
3525 * one (to be able to write when out of
3526 * memory) */
3527 {
3528 buffer = smallbuf;
3529 bufsize = SMBUFSIZE;
3530 }
3531 else
3532 bufsize = BUFSIZE;
3533
3534 /*
3535 * Get information about original file (if there is one).
3536 */
Bram Moolenaar53076832015-12-31 19:53:21 +01003537#if defined(UNIX)
Bram Moolenaar6f192452007-11-08 19:49:02 +00003538 st_old.st_dev = 0;
3539 st_old.st_ino = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003540 perm = -1;
3541 if (mch_stat((char *)fname, &st_old) < 0)
3542 newfile = TRUE;
3543 else
3544 {
3545 perm = st_old.st_mode;
3546 if (!S_ISREG(st_old.st_mode)) /* not a file */
3547 {
3548 if (S_ISDIR(st_old.st_mode))
3549 {
3550 errnum = (char_u *)"E502: ";
3551 errmsg = (char_u *)_("is a directory");
3552 goto fail;
3553 }
3554 if (mch_nodetype(fname) != NODE_WRITABLE)
3555 {
3556 errnum = (char_u *)"E503: ";
3557 errmsg = (char_u *)_("is not a file or writable device");
3558 goto fail;
3559 }
3560 /* It's a device of some kind (or a fifo) which we can write to
3561 * but for which we can't make a backup. */
3562 device = TRUE;
3563 newfile = TRUE;
3564 perm = -1;
3565 }
3566 }
3567#else /* !UNIX */
3568 /*
3569 * Check for a writable device name.
3570 */
3571 c = mch_nodetype(fname);
3572 if (c == NODE_OTHER)
3573 {
3574 errnum = (char_u *)"E503: ";
3575 errmsg = (char_u *)_("is not a file or writable device");
3576 goto fail;
3577 }
3578 if (c == NODE_WRITABLE)
3579 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003580# if defined(MSWIN)
Bram Moolenaar043545e2006-10-10 16:44:07 +00003581 /* MS-Windows allows opening a device, but we will probably get stuck
3582 * trying to write to it. */
3583 if (!p_odev)
3584 {
3585 errnum = (char_u *)"E796: ";
3586 errmsg = (char_u *)_("writing to device disabled with 'opendevice' option");
3587 goto fail;
3588 }
3589# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003590 device = TRUE;
3591 newfile = TRUE;
3592 perm = -1;
3593 }
3594 else
3595 {
3596 perm = mch_getperm(fname);
3597 if (perm < 0)
3598 newfile = TRUE;
3599 else if (mch_isdir(fname))
3600 {
3601 errnum = (char_u *)"E502: ";
3602 errmsg = (char_u *)_("is a directory");
3603 goto fail;
3604 }
3605 if (overwriting)
3606 (void)mch_stat((char *)fname, &st_old);
3607 }
3608#endif /* !UNIX */
3609
3610 if (!device && !newfile)
3611 {
3612 /*
3613 * Check if the file is really writable (when renaming the file to
3614 * make a backup we won't discover it later).
3615 */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003616 file_readonly = check_file_readonly(fname, (int)perm);
3617
Bram Moolenaar071d4272004-06-13 20:20:40 +00003618 if (!forceit && file_readonly)
3619 {
3620 if (vim_strchr(p_cpo, CPO_FWRITE) != NULL)
3621 {
3622 errnum = (char_u *)"E504: ";
3623 errmsg = (char_u *)_(err_readonly);
3624 }
3625 else
3626 {
3627 errnum = (char_u *)"E505: ";
3628 errmsg = (char_u *)_("is read-only (add ! to override)");
3629 }
3630 goto fail;
3631 }
3632
3633 /*
3634 * Check if the timestamp hasn't changed since reading the file.
3635 */
3636 if (overwriting)
3637 {
3638 retval = check_mtime(buf, &st_old);
3639 if (retval == FAIL)
3640 goto fail;
3641 }
3642 }
3643
3644#ifdef HAVE_ACL
3645 /*
3646 * For systems that support ACL: get the ACL from the original file.
3647 */
3648 if (!newfile)
3649 acl = mch_get_acl(fname);
3650#endif
3651
3652 /*
3653 * If 'backupskip' is not empty, don't make a backup for some files.
3654 */
3655 dobackup = (p_wb || p_bk || *p_pm != NUL);
3656#ifdef FEAT_WILDIGN
3657 if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname))
3658 dobackup = FALSE;
3659#endif
3660
3661 /*
3662 * Save the value of got_int and reset it. We don't want a previous
3663 * interruption cancel writing, only hitting CTRL-C while writing should
3664 * abort it.
3665 */
3666 prev_got_int = got_int;
3667 got_int = FALSE;
3668
3669 /* Mark the buffer as 'being saved' to prevent changed buffer warnings */
3670 buf->b_saving = TRUE;
3671
3672 /*
3673 * If we are not appending or filtering, the file exists, and the
3674 * 'writebackup', 'backup' or 'patchmode' option is set, need a backup.
3675 * When 'patchmode' is set also make a backup when appending.
3676 *
3677 * Do not make any backup, if 'writebackup' and 'backup' are both switched
3678 * off. This helps when editing large files on almost-full disks.
3679 */
3680 if (!(append && *p_pm == NUL) && !filtering && perm >= 0 && dobackup)
3681 {
3682#if defined(UNIX) || defined(WIN32)
Bram Moolenaar8767f522016-07-01 17:17:39 +02003683 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003684#endif
3685
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003686 if ((bkc & BKC_YES) || append) /* "yes" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003687 backup_copy = TRUE;
3688#if defined(UNIX) || defined(WIN32)
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003689 else if ((bkc & BKC_AUTO)) /* "auto" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003690 {
3691 int i;
3692
3693# ifdef UNIX
3694 /*
3695 * Don't rename the file when:
3696 * - it's a hard link
3697 * - it's a symbolic link
3698 * - we don't have write permission in the directory
3699 * - we can't set the owner/group of the new file
3700 */
3701 if (st_old.st_nlink > 1
3702 || mch_lstat((char *)fname, &st) < 0
3703 || st.st_dev != st_old.st_dev
Bram Moolenaara5792f52005-11-23 21:25:05 +00003704 || st.st_ino != st_old.st_ino
3705# ifndef HAVE_FCHOWN
3706 || st.st_uid != st_old.st_uid
3707 || st.st_gid != st_old.st_gid
3708# endif
3709 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003710 backup_copy = TRUE;
3711 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003712# else
3713# ifdef WIN32
3714 /* On NTFS file systems hard links are possible. */
3715 if (mch_is_linked(fname))
3716 backup_copy = TRUE;
3717 else
3718# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003719# endif
3720 {
3721 /*
3722 * Check if we can create a file and set the owner/group to
3723 * the ones from the original file.
3724 * First find a file name that doesn't exist yet (use some
3725 * arbitrary numbers).
3726 */
3727 STRCPY(IObuff, fname);
3728 for (i = 4913; ; i += 123)
3729 {
3730 sprintf((char *)gettail(IObuff), "%d", i);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003731 if (mch_lstat((char *)IObuff, &st) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003732 break;
3733 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00003734 fd = mch_open((char *)IObuff,
3735 O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003736 if (fd < 0) /* can't write in directory */
3737 backup_copy = TRUE;
3738 else
3739 {
3740# ifdef UNIX
Bram Moolenaara5792f52005-11-23 21:25:05 +00003741# ifdef HAVE_FCHOWN
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00003742 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003743# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003744 if (mch_stat((char *)IObuff, &st) < 0
3745 || st.st_uid != st_old.st_uid
3746 || st.st_gid != st_old.st_gid
Bram Moolenaar78a15312009-05-15 19:33:18 +00003747 || (long)st.st_mode != perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003748 backup_copy = TRUE;
3749# endif
Bram Moolenaar98358622005-11-28 22:58:23 +00003750 /* Close the file before removing it, on MS-Windows we
3751 * can't delete an open file. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003752 close(fd);
Bram Moolenaar98358622005-11-28 22:58:23 +00003753 mch_remove(IObuff);
Bram Moolenaar3479c5d2010-08-08 18:46:06 +02003754# ifdef MSWIN
3755 /* MS-Windows may trigger a virus scanner to open the
3756 * file, we can't delete it then. Keep trying for half a
3757 * second. */
3758 {
3759 int try;
3760
3761 for (try = 0; try < 10; ++try)
3762 {
3763 if (mch_lstat((char *)IObuff, &st) < 0)
3764 break;
3765 ui_delay(50L, TRUE); /* wait 50 msec */
3766 mch_remove(IObuff);
3767 }
3768 }
3769# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003770 }
3771 }
3772 }
3773
Bram Moolenaar071d4272004-06-13 20:20:40 +00003774 /*
3775 * Break symlinks and/or hardlinks if we've been asked to.
3776 */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003777 if ((bkc & BKC_BREAKSYMLINK) || (bkc & BKC_BREAKHARDLINK))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003778 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003779# ifdef UNIX
Bram Moolenaar071d4272004-06-13 20:20:40 +00003780 int lstat_res;
3781
3782 lstat_res = mch_lstat((char *)fname, &st);
3783
3784 /* Symlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003785 if ((bkc & BKC_BREAKSYMLINK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003786 && lstat_res == 0
3787 && st.st_ino != st_old.st_ino)
3788 backup_copy = FALSE;
3789
3790 /* Hardlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003791 if ((bkc & BKC_BREAKHARDLINK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003792 && st_old.st_nlink > 1
3793 && (lstat_res != 0 || st.st_ino == st_old.st_ino))
3794 backup_copy = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003795# else
3796# if defined(WIN32)
3797 /* Symlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003798 if ((bkc & BKC_BREAKSYMLINK) && mch_is_symbolic_link(fname))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003799 backup_copy = FALSE;
3800
3801 /* Hardlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003802 if ((bkc & BKC_BREAKHARDLINK) && mch_is_hard_link(fname))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003803 backup_copy = FALSE;
3804# endif
3805# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003806 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003807
3808#endif
3809
3810 /* make sure we have a valid backup extension to use */
3811 if (*p_bex == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003812 backup_ext = (char_u *)".bak";
Bram Moolenaar071d4272004-06-13 20:20:40 +00003813 else
3814 backup_ext = p_bex;
3815
3816 if (backup_copy
3817 && (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) >= 0)
3818 {
3819 int bfd;
3820 char_u *copybuf, *wp;
3821 int some_error = FALSE;
Bram Moolenaar8767f522016-07-01 17:17:39 +02003822 stat_T st_new;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003823 char_u *dirp;
3824 char_u *rootname;
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003825#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003826 int did_set_shortname;
3827#endif
3828
3829 copybuf = alloc(BUFSIZE + 1);
3830 if (copybuf == NULL)
3831 {
3832 some_error = TRUE; /* out of memory */
3833 goto nobackup;
3834 }
3835
3836 /*
3837 * Try to make the backup in each directory in the 'bdir' option.
3838 *
3839 * Unix semantics has it, that we may have a writable file,
3840 * that cannot be recreated with a simple open(..., O_CREAT, ) e.g:
3841 * - the directory is not writable,
3842 * - the file may be a symbolic link,
3843 * - the file may belong to another user/group, etc.
3844 *
3845 * For these reasons, the existing writable file must be truncated
3846 * and reused. Creation of a backup COPY will be attempted.
3847 */
3848 dirp = p_bdir;
3849 while (*dirp)
3850 {
3851#ifdef UNIX
3852 st_new.st_ino = 0;
3853 st_new.st_dev = 0;
3854 st_new.st_gid = 0;
3855#endif
3856
3857 /*
3858 * Isolate one directory name, using an entry in 'bdir'.
3859 */
3860 (void)copy_option_part(&dirp, copybuf, BUFSIZE, ",");
3861 rootname = get_file_in_dir(fname, copybuf);
3862 if (rootname == NULL)
3863 {
3864 some_error = TRUE; /* out of memory */
3865 goto nobackup;
3866 }
3867
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003868#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003869 did_set_shortname = FALSE;
3870#endif
3871
3872 /*
3873 * May try twice if 'shortname' not set.
3874 */
3875 for (;;)
3876 {
3877 /*
3878 * Make backup file name.
3879 */
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003880 backup = buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003881 rootname, backup_ext, FALSE);
3882 if (backup == NULL)
3883 {
3884 vim_free(rootname);
3885 some_error = TRUE; /* out of memory */
3886 goto nobackup;
3887 }
3888
3889 /*
3890 * Check if backup file already exists.
3891 */
3892 if (mch_stat((char *)backup, &st_new) >= 0)
3893 {
3894#ifdef UNIX
3895 /*
3896 * Check if backup file is same as original file.
3897 * May happen when modname() gave the same file back.
3898 * E.g. silly link, or file name-length reached.
3899 * If we don't check here, we either ruin the file
3900 * when copying or erase it after writing. jw.
3901 */
3902 if (st_new.st_dev == st_old.st_dev
3903 && st_new.st_ino == st_old.st_ino)
3904 {
3905 vim_free(backup);
3906 backup = NULL; /* no backup file to delete */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003907 /*
3908 * may try again with 'shortname' set
3909 */
3910 if (!(buf->b_shortname || buf->b_p_sn))
3911 {
3912 buf->b_shortname = TRUE;
3913 did_set_shortname = TRUE;
3914 continue;
3915 }
3916 /* setting shortname didn't help */
3917 if (did_set_shortname)
3918 buf->b_shortname = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003919 break;
3920 }
3921#endif
3922
3923 /*
3924 * If we are not going to keep the backup file, don't
3925 * delete an existing one, try to use another name.
3926 * Change one character, just before the extension.
3927 */
3928 if (!p_bk)
3929 {
3930 wp = backup + STRLEN(backup) - 1
3931 - STRLEN(backup_ext);
3932 if (wp < backup) /* empty file name ??? */
3933 wp = backup;
3934 *wp = 'z';
3935 while (*wp > 'a'
3936 && mch_stat((char *)backup, &st_new) >= 0)
3937 --*wp;
3938 /* They all exist??? Must be something wrong. */
3939 if (*wp == 'a')
3940 {
3941 vim_free(backup);
3942 backup = NULL;
3943 }
3944 }
3945 }
3946 break;
3947 }
3948 vim_free(rootname);
3949
3950 /*
3951 * Try to create the backup file
3952 */
3953 if (backup != NULL)
3954 {
3955 /* remove old backup, if present */
3956 mch_remove(backup);
3957 /* Open with O_EXCL to avoid the file being created while
3958 * we were sleeping (symlink hacker attack?) */
3959 bfd = mch_open((char *)backup,
Bram Moolenaara5792f52005-11-23 21:25:05 +00003960 O_WRONLY|O_CREAT|O_EXTRA|O_EXCL|O_NOFOLLOW,
3961 perm & 0777);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003962 if (bfd < 0)
3963 {
3964 vim_free(backup);
3965 backup = NULL;
3966 }
3967 else
3968 {
3969 /* set file protection same as original file, but
3970 * strip s-bit */
3971 (void)mch_setperm(backup, perm & 0777);
3972
3973#ifdef UNIX
3974 /*
3975 * Try to set the group of the backup same as the
3976 * original file. If this fails, set the protection
3977 * bits for the group same as the protection bits for
3978 * others.
3979 */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003980 if (st_new.st_gid != st_old.st_gid
Bram Moolenaar071d4272004-06-13 20:20:40 +00003981# ifdef HAVE_FCHOWN /* sequent-ptx lacks fchown() */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003982 && fchown(bfd, (uid_t)-1, st_old.st_gid) != 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00003983# endif
3984 )
3985 mch_setperm(backup,
3986 (perm & 0707) | ((perm & 07) << 3));
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02003987# if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00003988 mch_copy_sec(fname, backup);
3989# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003990#endif
3991
3992 /*
3993 * copy the file.
3994 */
3995 write_info.bw_fd = bfd;
3996 write_info.bw_buf = copybuf;
3997#ifdef HAS_BW_FLAGS
3998 write_info.bw_flags = FIO_NOCONVERT;
3999#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004000 while ((write_info.bw_len = read_eintr(fd, copybuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004001 BUFSIZE)) > 0)
4002 {
4003 if (buf_write_bytes(&write_info) == FAIL)
4004 {
4005 errmsg = (char_u *)_("E506: Can't write to backup file (add ! to override)");
4006 break;
4007 }
4008 ui_breakcheck();
4009 if (got_int)
4010 {
4011 errmsg = (char_u *)_(e_interr);
4012 break;
4013 }
4014 }
4015
4016 if (close(bfd) < 0 && errmsg == NULL)
4017 errmsg = (char_u *)_("E507: Close error for backup file (add ! to override)");
4018 if (write_info.bw_len < 0)
4019 errmsg = (char_u *)_("E508: Can't read file for backup (add ! to override)");
4020#ifdef UNIX
4021 set_file_time(backup, st_old.st_atime, st_old.st_mtime);
4022#endif
4023#ifdef HAVE_ACL
4024 mch_set_acl(backup, acl);
4025#endif
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004026#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004027 mch_copy_sec(fname, backup);
4028#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004029 break;
4030 }
4031 }
4032 }
4033 nobackup:
4034 close(fd); /* ignore errors for closing read file */
4035 vim_free(copybuf);
4036
4037 if (backup == NULL && errmsg == NULL)
4038 errmsg = (char_u *)_("E509: Cannot create backup file (add ! to override)");
4039 /* ignore errors when forceit is TRUE */
4040 if ((some_error || errmsg != NULL) && !forceit)
4041 {
4042 retval = FAIL;
4043 goto fail;
4044 }
4045 errmsg = NULL;
4046 }
4047 else
4048 {
4049 char_u *dirp;
4050 char_u *p;
4051 char_u *rootname;
4052
4053 /*
4054 * Make a backup by renaming the original file.
4055 */
4056 /*
4057 * If 'cpoptions' includes the "W" flag, we don't want to
4058 * overwrite a read-only file. But rename may be possible
4059 * anyway, thus we need an extra check here.
4060 */
4061 if (file_readonly && vim_strchr(p_cpo, CPO_FWRITE) != NULL)
4062 {
4063 errnum = (char_u *)"E504: ";
4064 errmsg = (char_u *)_(err_readonly);
4065 goto fail;
4066 }
4067
4068 /*
4069 *
4070 * Form the backup file name - change path/fo.o.h to
4071 * path/fo.o.h.bak Try all directories in 'backupdir', first one
4072 * that works is used.
4073 */
4074 dirp = p_bdir;
4075 while (*dirp)
4076 {
4077 /*
4078 * Isolate one directory name and make the backup file name.
4079 */
4080 (void)copy_option_part(&dirp, IObuff, IOSIZE, ",");
4081 rootname = get_file_in_dir(fname, IObuff);
4082 if (rootname == NULL)
4083 backup = NULL;
4084 else
4085 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01004086 backup = buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00004087 rootname, backup_ext, FALSE);
4088 vim_free(rootname);
4089 }
4090
4091 if (backup != NULL)
4092 {
4093 /*
4094 * If we are not going to keep the backup file, don't
4095 * delete an existing one, try to use another name.
4096 * Change one character, just before the extension.
4097 */
4098 if (!p_bk && mch_getperm(backup) >= 0)
4099 {
4100 p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext);
4101 if (p < backup) /* empty file name ??? */
4102 p = backup;
4103 *p = 'z';
4104 while (*p > 'a' && mch_getperm(backup) >= 0)
4105 --*p;
4106 /* They all exist??? Must be something wrong! */
4107 if (*p == 'a')
4108 {
4109 vim_free(backup);
4110 backup = NULL;
4111 }
4112 }
4113 }
4114 if (backup != NULL)
4115 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004116 /*
Bram Moolenaarbfd8fc02005-09-20 23:22:24 +00004117 * Delete any existing backup and move the current version
4118 * to the backup. For safety, we don't remove the backup
4119 * until the write has finished successfully. And if the
4120 * 'backup' option is set, leave it around.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004121 */
4122 /*
4123 * If the renaming of the original file to the backup file
4124 * works, quit here.
4125 */
4126 if (vim_rename(fname, backup) == 0)
4127 break;
4128
4129 vim_free(backup); /* don't do the rename below */
4130 backup = NULL;
4131 }
4132 }
4133 if (backup == NULL && !forceit)
4134 {
4135 errmsg = (char_u *)_("E510: Can't make backup file (add ! to override)");
4136 goto fail;
4137 }
4138 }
4139 }
4140
Bram Moolenaar53076832015-12-31 19:53:21 +01004141#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004142 /* When using ":w!" and the file was read-only: make it writable */
4143 if (forceit && perm >= 0 && !(perm & 0200) && st_old.st_uid == getuid()
4144 && vim_strchr(p_cpo, CPO_FWRITE) == NULL)
4145 {
4146 perm |= 0200;
4147 (void)mch_setperm(fname, perm);
4148 made_writable = TRUE;
4149 }
4150#endif
4151
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004152 /* When using ":w!" and writing to the current file, 'readonly' makes no
Bram Moolenaar4399ef42005-02-12 14:29:27 +00004153 * sense, reset it, unless 'Z' appears in 'cpoptions'. */
4154 if (forceit && overwriting && vim_strchr(p_cpo, CPO_KEEPRO) == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004155 {
4156 buf->b_p_ro = FALSE;
4157#ifdef FEAT_TITLE
4158 need_maketitle = TRUE; /* set window title later */
4159#endif
4160#ifdef FEAT_WINDOWS
4161 status_redraw_all(); /* redraw status lines later */
4162#endif
4163 }
4164
4165 if (end > buf->b_ml.ml_line_count)
4166 end = buf->b_ml.ml_line_count;
4167 if (buf->b_ml.ml_flags & ML_EMPTY)
4168 start = end + 1;
4169
4170 /*
4171 * If the original file is being overwritten, there is a small chance that
4172 * we crash in the middle of writing. Therefore the file is preserved now.
4173 * This makes all block numbers positive so that recovery does not need
4174 * the original file.
4175 * Don't do this if there is a backup file and we are exiting.
4176 */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004177 if (reset_changed && !newfile && overwriting
Bram Moolenaar071d4272004-06-13 20:20:40 +00004178 && !(exiting && backup != NULL))
4179 {
4180 ml_preserve(buf, FALSE);
4181 if (got_int)
4182 {
4183 errmsg = (char_u *)_(e_interr);
4184 goto restore_backup;
4185 }
4186 }
4187
4188#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
4189 /*
4190 * Before risking to lose the original file verify if there's
4191 * a resource fork to preserve, and if cannot be done warn
4192 * the users. This happens when overwriting without backups.
4193 */
4194 if (backup == NULL && overwriting && !append)
4195 if (mch_has_resource_fork(fname))
4196 {
4197 errmsg = (char_u *)_("E460: The resource fork would be lost (add ! to override)");
4198 goto restore_backup;
4199 }
4200#endif
4201
4202#ifdef VMS
4203 vms_remove_version(fname); /* remove version */
4204#endif
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00004205 /* Default: write the file directly. May write to a temp file for
Bram Moolenaar071d4272004-06-13 20:20:40 +00004206 * multi-byte conversion. */
4207 wfname = fname;
4208
4209#ifdef FEAT_MBYTE
4210 /* Check for forced 'fileencoding' from "++opt=val" argument. */
4211 if (eap != NULL && eap->force_enc != 0)
4212 {
4213 fenc = eap->cmd + eap->force_enc;
4214 fenc = enc_canonize(fenc);
4215 fenc_tofree = fenc;
4216 }
4217 else
4218 fenc = buf->b_p_fenc;
4219
4220 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004221 * Check if the file needs to be converted.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004222 */
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004223 converted = need_conversion(fenc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004224
4225 /*
4226 * Check if UTF-8 to UCS-2/4 or Latin1 conversion needs to be done. Or
4227 * Latin1 to Unicode conversion. This is handled in buf_write_bytes().
4228 * Prepare the flags for it and allocate bw_conv_buf when needed.
4229 */
4230 if (converted && (enc_utf8 || STRCMP(p_enc, "latin1") == 0))
4231 {
4232 wb_flags = get_fio_flags(fenc);
4233 if (wb_flags & (FIO_UCS2 | FIO_UCS4 | FIO_UTF16 | FIO_UTF8))
4234 {
4235 /* Need to allocate a buffer to translate into. */
4236 if (wb_flags & (FIO_UCS2 | FIO_UTF16 | FIO_UTF8))
4237 write_info.bw_conv_buflen = bufsize * 2;
4238 else /* FIO_UCS4 */
4239 write_info.bw_conv_buflen = bufsize * 4;
4240 write_info.bw_conv_buf
4241 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4242 if (write_info.bw_conv_buf == NULL)
4243 end = 0;
4244 }
4245 }
4246
4247# ifdef WIN3264
4248 if (converted && wb_flags == 0 && (wb_flags = get_win_fio_flags(fenc)) != 0)
4249 {
4250 /* Convert UTF-8 -> UCS-2 and UCS-2 -> DBCS. Worst-case * 4: */
4251 write_info.bw_conv_buflen = bufsize * 4;
4252 write_info.bw_conv_buf
4253 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4254 if (write_info.bw_conv_buf == NULL)
4255 end = 0;
4256 }
4257# endif
4258
4259# ifdef MACOS_X
4260 if (converted && wb_flags == 0 && (wb_flags = get_mac_fio_flags(fenc)) != 0)
4261 {
4262 write_info.bw_conv_buflen = bufsize * 3;
4263 write_info.bw_conv_buf
4264 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4265 if (write_info.bw_conv_buf == NULL)
4266 end = 0;
4267 }
4268# endif
4269
4270# if defined(FEAT_EVAL) || defined(USE_ICONV)
4271 if (converted && wb_flags == 0)
4272 {
4273# ifdef USE_ICONV
4274 /*
4275 * Use iconv() conversion when conversion is needed and it's not done
4276 * internally.
4277 */
4278 write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc,
4279 enc_utf8 ? (char_u *)"utf-8" : p_enc);
4280 if (write_info.bw_iconv_fd != (iconv_t)-1)
4281 {
4282 /* We're going to use iconv(), allocate a buffer to convert in. */
4283 write_info.bw_conv_buflen = bufsize * ICONV_MULT;
4284 write_info.bw_conv_buf
4285 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4286 if (write_info.bw_conv_buf == NULL)
4287 end = 0;
4288 write_info.bw_first = TRUE;
4289 }
4290# ifdef FEAT_EVAL
4291 else
4292# endif
4293# endif
4294
4295# ifdef FEAT_EVAL
4296 /*
4297 * When the file needs to be converted with 'charconvert' after
4298 * writing, write to a temp file instead and let the conversion
4299 * overwrite the original file.
4300 */
4301 if (*p_ccv != NUL)
4302 {
Bram Moolenaare5c421c2015-03-31 13:33:08 +02004303 wfname = vim_tempname('w', FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004304 if (wfname == NULL) /* Can't write without a tempfile! */
4305 {
4306 errmsg = (char_u *)_("E214: Can't find temp file for writing");
4307 goto restore_backup;
4308 }
4309 }
4310# endif
4311 }
4312# endif
4313 if (converted && wb_flags == 0
4314# ifdef USE_ICONV
4315 && write_info.bw_iconv_fd == (iconv_t)-1
4316# endif
4317# ifdef FEAT_EVAL
4318 && wfname == fname
4319# endif
4320 )
4321 {
4322 if (!forceit)
4323 {
4324 errmsg = (char_u *)_("E213: Cannot convert (add ! to write without conversion)");
4325 goto restore_backup;
4326 }
4327 notconverted = TRUE;
4328 }
4329#endif
4330
4331 /*
4332 * Open the file "wfname" for writing.
4333 * We may try to open the file twice: If we can't write to the
4334 * file and forceit is TRUE we delete the existing file and try to create
4335 * a new one. If this still fails we may have lost the original file!
4336 * (this may happen when the user reached his quotum for number of files).
4337 * Appending will fail if the file does not exist and forceit is FALSE.
4338 */
4339 while ((fd = mch_open((char *)wfname, O_WRONLY | O_EXTRA | (append
4340 ? (forceit ? (O_APPEND | O_CREAT) : O_APPEND)
4341 : (O_CREAT | O_TRUNC))
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00004342 , perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004343 {
4344 /*
4345 * A forced write will try to create a new file if the old one is
4346 * still readonly. This may also happen when the directory is
4347 * read-only. In that case the mch_remove() will fail.
4348 */
4349 if (errmsg == NULL)
4350 {
4351#ifdef UNIX
Bram Moolenaar8767f522016-07-01 17:17:39 +02004352 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004353
4354 /* Don't delete the file when it's a hard or symbolic link. */
4355 if ((!newfile && st_old.st_nlink > 1)
4356 || (mch_lstat((char *)fname, &st) == 0
4357 && (st.st_dev != st_old.st_dev
4358 || st.st_ino != st_old.st_ino)))
4359 errmsg = (char_u *)_("E166: Can't open linked file for writing");
4360 else
4361#endif
4362 {
4363 errmsg = (char_u *)_("E212: Can't open file for writing");
4364 if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL
4365 && perm >= 0)
4366 {
4367#ifdef UNIX
4368 /* we write to the file, thus it should be marked
4369 writable after all */
4370 if (!(perm & 0200))
4371 made_writable = TRUE;
4372 perm |= 0200;
4373 if (st_old.st_uid != getuid() || st_old.st_gid != getgid())
4374 perm &= 0777;
4375#endif
4376 if (!append) /* don't remove when appending */
4377 mch_remove(wfname);
4378 continue;
4379 }
4380 }
4381 }
4382
4383restore_backup:
4384 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02004385 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004386
4387 /*
4388 * If we failed to open the file, we don't need a backup. Throw it
4389 * away. If we moved or removed the original file try to put the
4390 * backup in its place.
4391 */
4392 if (backup != NULL && wfname == fname)
4393 {
4394 if (backup_copy)
4395 {
4396 /*
4397 * There is a small chance that we removed the original,
4398 * try to move the copy in its place.
4399 * This may not work if the vim_rename() fails.
4400 * In that case we leave the copy around.
4401 */
4402 /* If file does not exist, put the copy in its place */
4403 if (mch_stat((char *)fname, &st) < 0)
4404 vim_rename(backup, fname);
4405 /* if original file does exist throw away the copy */
4406 if (mch_stat((char *)fname, &st) >= 0)
4407 mch_remove(backup);
4408 }
4409 else
4410 {
4411 /* try to put the original file back */
4412 vim_rename(backup, fname);
4413 }
4414 }
4415
4416 /* if original file no longer exists give an extra warning */
4417 if (!newfile && mch_stat((char *)fname, &st) < 0)
4418 end = 0;
4419 }
4420
4421#ifdef FEAT_MBYTE
4422 if (wfname != fname)
4423 vim_free(wfname);
4424#endif
4425 goto fail;
4426 }
4427 errmsg = NULL;
4428
4429#if defined(MACOS_CLASSIC) || defined(WIN3264)
4430 /* TODO: Is it need for MACOS_X? (Dany) */
4431 /*
4432 * On macintosh copy the original files attributes (i.e. the backup)
Bram Moolenaar7263a772007-05-10 17:35:54 +00004433 * This is done in order to preserve the resource fork and the
4434 * Finder attribute (label, comments, custom icons, file creator)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004435 */
4436 if (backup != NULL && overwriting && !append)
4437 {
4438 if (backup_copy)
4439 (void)mch_copy_file_attribute(wfname, backup);
4440 else
4441 (void)mch_copy_file_attribute(backup, wfname);
4442 }
4443
4444 if (!overwriting && !append)
4445 {
4446 if (buf->b_ffname != NULL)
4447 (void)mch_copy_file_attribute(buf->b_ffname, wfname);
Bram Moolenaar7263a772007-05-10 17:35:54 +00004448 /* Should copy resource fork */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004449 }
4450#endif
4451
4452 write_info.bw_fd = fd;
4453
4454#ifdef FEAT_CRYPT
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004455 if (*buf->b_p_key != NUL && !filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004456 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004457 char_u *header;
4458 int header_len;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004459
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004460 buf->b_cryptstate = crypt_create_for_writing(crypt_get_method_nr(buf),
4461 buf->b_p_key, &header, &header_len);
4462 if (buf->b_cryptstate == NULL || header == NULL)
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02004463 end = 0;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004464 else
4465 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004466 /* Write magic number, so that Vim knows how this file is
4467 * encrypted when reading it back. */
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02004468 write_info.bw_buf = header;
4469 write_info.bw_len = header_len;
4470 write_info.bw_flags = FIO_NOCONVERT;
4471 if (buf_write_bytes(&write_info) == FAIL)
4472 end = 0;
4473 wb_flags |= FIO_ENCRYPTED;
4474 vim_free(header);
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004475 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004476 }
4477#endif
4478
4479 write_info.bw_buf = buffer;
4480 nchars = 0;
4481
4482 /* use "++bin", "++nobin" or 'binary' */
4483 if (eap != NULL && eap->force_bin != 0)
4484 write_bin = (eap->force_bin == FORCE_BIN);
4485 else
4486 write_bin = buf->b_p_bin;
4487
4488#ifdef FEAT_MBYTE
4489 /*
4490 * The BOM is written just after the encryption magic number.
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004491 * Skip it when appending and the file already existed, the BOM only makes
4492 * sense at the start of the file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004493 */
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004494 if (buf->b_p_bomb && !write_bin && (!append || perm < 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004495 {
4496 write_info.bw_len = make_bom(buffer, fenc);
4497 if (write_info.bw_len > 0)
4498 {
4499 /* don't convert, do encryption */
4500 write_info.bw_flags = FIO_NOCONVERT | wb_flags;
4501 if (buf_write_bytes(&write_info) == FAIL)
4502 end = 0;
4503 else
4504 nchars += write_info.bw_len;
4505 }
4506 }
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004507 write_info.bw_start_lnum = start;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004508#endif
4509
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004510#ifdef FEAT_PERSISTENT_UNDO
4511 write_undo_file = (buf->b_p_udf && overwriting && !append
4512 && !filtering && reset_changed);
4513 if (write_undo_file)
4514 /* Prepare for computing the hash value of the text. */
4515 sha256_start(&sha_ctx);
4516#endif
4517
Bram Moolenaar071d4272004-06-13 20:20:40 +00004518 write_info.bw_len = bufsize;
4519#ifdef HAS_BW_FLAGS
4520 write_info.bw_flags = wb_flags;
4521#endif
4522 fileformat = get_fileformat_force(buf, eap);
4523 s = buffer;
4524 len = 0;
4525 for (lnum = start; lnum <= end; ++lnum)
4526 {
4527 /*
4528 * The next while loop is done once for each character written.
4529 * Keep it fast!
4530 */
4531 ptr = ml_get_buf(buf, lnum, FALSE) - 1;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004532#ifdef FEAT_PERSISTENT_UNDO
4533 if (write_undo_file)
Bram Moolenaar442b4222010-05-24 21:34:22 +02004534 sha256_update(&sha_ctx, ptr + 1, (UINT32_T)(STRLEN(ptr + 1) + 1));
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004535#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004536 while ((c = *++ptr) != NUL)
4537 {
4538 if (c == NL)
4539 *s = NUL; /* replace newlines with NULs */
4540 else if (c == CAR && fileformat == EOL_MAC)
4541 *s = NL; /* Mac: replace CRs with NLs */
4542 else
4543 *s = c;
4544 ++s;
4545 if (++len != bufsize)
4546 continue;
4547 if (buf_write_bytes(&write_info) == FAIL)
4548 {
4549 end = 0; /* write error: break loop */
4550 break;
4551 }
4552 nchars += bufsize;
4553 s = buffer;
4554 len = 0;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004555#ifdef FEAT_MBYTE
4556 write_info.bw_start_lnum = lnum;
4557#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004558 }
4559 /* write failed or last line has no EOL: stop here */
4560 if (end == 0
4561 || (lnum == end
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004562 && (write_bin || !buf->b_p_fixeol)
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004563 && (lnum == buf->b_no_eol_lnum
Bram Moolenaar071d4272004-06-13 20:20:40 +00004564 || (lnum == buf->b_ml.ml_line_count && !buf->b_p_eol))))
4565 {
4566 ++lnum; /* written the line, count it */
4567 no_eol = TRUE;
4568 break;
4569 }
4570 if (fileformat == EOL_UNIX)
4571 *s++ = NL;
4572 else
4573 {
4574 *s++ = CAR; /* EOL_MAC or EOL_DOS: write CR */
4575 if (fileformat == EOL_DOS) /* write CR-NL */
4576 {
4577 if (++len == bufsize)
4578 {
4579 if (buf_write_bytes(&write_info) == FAIL)
4580 {
4581 end = 0; /* write error: break loop */
4582 break;
4583 }
4584 nchars += bufsize;
4585 s = buffer;
4586 len = 0;
4587 }
4588 *s++ = NL;
4589 }
4590 }
4591 if (++len == bufsize && end)
4592 {
4593 if (buf_write_bytes(&write_info) == FAIL)
4594 {
4595 end = 0; /* write error: break loop */
4596 break;
4597 }
4598 nchars += bufsize;
4599 s = buffer;
4600 len = 0;
4601
4602 ui_breakcheck();
4603 if (got_int)
4604 {
4605 end = 0; /* Interrupted, break loop */
4606 break;
4607 }
4608 }
4609#ifdef VMS
4610 /*
4611 * On VMS there is a problem: newlines get added when writing blocks
4612 * at a time. Fix it by writing a line at a time.
4613 * This is much slower!
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004614 * Explanation: VAX/DECC RTL insists that records in some RMS
4615 * structures end with a newline (carriage return) character, and if
4616 * they don't it adds one.
4617 * With other RMS structures it works perfect without this fix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004618 */
Bram Moolenaarb52e2602007-10-29 21:38:54 +00004619 if (buf->b_fab_rfm == FAB$C_VFC
4620 || ((buf->b_fab_rat & (FAB$M_FTN | FAB$M_CR)) != 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004621 {
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004622 int b2write;
4623
4624 buf->b_fab_mrs = (buf->b_fab_mrs == 0
4625 ? MIN(4096, bufsize)
4626 : MIN(buf->b_fab_mrs, bufsize));
4627
4628 b2write = len;
4629 while (b2write > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004630 {
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004631 write_info.bw_len = MIN(b2write, buf->b_fab_mrs);
4632 if (buf_write_bytes(&write_info) == FAIL)
4633 {
4634 end = 0;
4635 break;
4636 }
4637 b2write -= MIN(b2write, buf->b_fab_mrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004638 }
4639 write_info.bw_len = bufsize;
4640 nchars += len;
4641 s = buffer;
4642 len = 0;
4643 }
4644#endif
4645 }
4646 if (len > 0 && end > 0)
4647 {
4648 write_info.bw_len = len;
4649 if (buf_write_bytes(&write_info) == FAIL)
4650 end = 0; /* write error */
4651 nchars += len;
4652 }
4653
4654#if defined(UNIX) && defined(HAVE_FSYNC)
4655 /* On many journalling file systems there is a bug that causes both the
4656 * original and the backup file to be lost when halting the system right
4657 * after writing the file. That's because only the meta-data is
4658 * journalled. Syncing the file slows down the system, but assures it has
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004659 * been written to disk and we don't lose it.
4660 * For a device do try the fsync() but don't complain if it does not work
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00004661 * (could be a pipe).
4662 * If the 'fsync' option is FALSE, don't fsync(). Useful for laptops. */
4663 if (p_fs && fsync(fd) != 0 && !device)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004664 {
4665 errmsg = (char_u *)_("E667: Fsync failed");
4666 end = 0;
4667 }
4668#endif
4669
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004670#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004671 /* Probably need to set the security context. */
4672 if (!backup_copy)
4673 mch_copy_sec(backup, wfname);
4674#endif
4675
Bram Moolenaara5792f52005-11-23 21:25:05 +00004676#ifdef UNIX
4677 /* When creating a new file, set its owner/group to that of the original
4678 * file. Get the new device and inode number. */
4679 if (backup != NULL && !backup_copy)
4680 {
4681# ifdef HAVE_FCHOWN
Bram Moolenaar8767f522016-07-01 17:17:39 +02004682 stat_T st;
Bram Moolenaara5792f52005-11-23 21:25:05 +00004683
4684 /* don't change the owner when it's already OK, some systems remove
4685 * permission or ACL stuff */
4686 if (mch_stat((char *)wfname, &st) < 0
4687 || st.st_uid != st_old.st_uid
4688 || st.st_gid != st_old.st_gid)
4689 {
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004690 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004691 if (perm >= 0) /* set permission again, may have changed */
4692 (void)mch_setperm(wfname, perm);
4693 }
4694# endif
4695 buf_setino(buf);
4696 }
Bram Moolenaarf1726cc2009-05-13 18:48:16 +00004697 else if (!buf->b_dev_valid)
Bram Moolenaar8fa04452005-12-23 22:13:51 +00004698 /* Set the inode when creating a new file. */
4699 buf_setino(buf);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004700#endif
4701
Bram Moolenaar071d4272004-06-13 20:20:40 +00004702 if (close(fd) != 0)
4703 {
4704 errmsg = (char_u *)_("E512: Close failed");
4705 end = 0;
4706 }
4707
4708#ifdef UNIX
4709 if (made_writable)
4710 perm &= ~0200; /* reset 'w' bit for security reasons */
4711#endif
4712 if (perm >= 0) /* set perm. of new file same as old file */
4713 (void)mch_setperm(wfname, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004714#ifdef HAVE_ACL
Bram Moolenaarda412772016-07-14 20:37:07 +02004715 /*
4716 * Probably need to set the ACL before changing the user (can't set the
4717 * ACL on a file the user doesn't own).
4718 * On Solaris, with ZFS and the aclmode property set to "discard" (the
4719 * default), chmod() discards all part of a file's ACL that don't represent
4720 * the mode of the file. It's non-trivial for us to discover whether we're
4721 * in that situation, so we simply always re-set the ACL.
4722 */
4723# ifndef HAVE_SOLARIS_ZFS_ACL
Bram Moolenaar071d4272004-06-13 20:20:40 +00004724 if (!backup_copy)
Bram Moolenaarda412772016-07-14 20:37:07 +02004725# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004726 mch_set_acl(wfname, acl);
4727#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004728#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004729 if (buf->b_cryptstate != NULL)
4730 {
4731 crypt_free_state(buf->b_cryptstate);
4732 buf->b_cryptstate = NULL;
4733 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004734#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004735
Bram Moolenaar071d4272004-06-13 20:20:40 +00004736#if defined(FEAT_MBYTE) && defined(FEAT_EVAL)
4737 if (wfname != fname)
4738 {
4739 /*
4740 * The file was written to a temp file, now it needs to be converted
4741 * with 'charconvert' to (overwrite) the output file.
4742 */
4743 if (end != 0)
4744 {
4745 if (eval_charconvert(enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc,
4746 wfname, fname) == FAIL)
4747 {
4748 write_info.bw_conv_error = TRUE;
4749 end = 0;
4750 }
4751 }
4752 mch_remove(wfname);
4753 vim_free(wfname);
4754 }
4755#endif
4756
4757 if (end == 0)
4758 {
4759 if (errmsg == NULL)
4760 {
4761#ifdef FEAT_MBYTE
4762 if (write_info.bw_conv_error)
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004763 {
4764 if (write_info.bw_conv_error_lnum == 0)
4765 errmsg = (char_u *)_("E513: write error, conversion failed (make 'fenc' empty to override)");
4766 else
4767 {
4768 errmsg_allocated = TRUE;
4769 errmsg = alloc(300);
4770 vim_snprintf((char *)errmsg, 300, _("E513: write error, conversion failed in line %ld (make 'fenc' empty to override)"),
4771 (long)write_info.bw_conv_error_lnum);
4772 }
4773 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004774 else
4775#endif
4776 if (got_int)
4777 errmsg = (char_u *)_(e_interr);
4778 else
4779 errmsg = (char_u *)_("E514: write error (file system full?)");
4780 }
4781
4782 /*
4783 * If we have a backup file, try to put it in place of the new file,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004784 * because the new file is probably corrupt. This avoids losing the
Bram Moolenaar071d4272004-06-13 20:20:40 +00004785 * original file when trying to make a backup when writing the file a
4786 * second time.
4787 * When "backup_copy" is set we need to copy the backup over the new
4788 * file. Otherwise rename the backup file.
4789 * If this is OK, don't give the extra warning message.
4790 */
4791 if (backup != NULL)
4792 {
4793 if (backup_copy)
4794 {
4795 /* This may take a while, if we were interrupted let the user
4796 * know we got the message. */
4797 if (got_int)
4798 {
4799 MSG(_(e_interr));
4800 out_flush();
4801 }
4802 if ((fd = mch_open((char *)backup, O_RDONLY | O_EXTRA, 0)) >= 0)
4803 {
4804 if ((write_info.bw_fd = mch_open((char *)fname,
Bram Moolenaar9be038d2005-03-08 22:34:32 +00004805 O_WRONLY | O_CREAT | O_TRUNC | O_EXTRA,
4806 perm & 0777)) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004807 {
4808 /* copy the file. */
4809 write_info.bw_buf = smallbuf;
4810#ifdef HAS_BW_FLAGS
4811 write_info.bw_flags = FIO_NOCONVERT;
4812#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004813 while ((write_info.bw_len = read_eintr(fd, smallbuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004814 SMBUFSIZE)) > 0)
4815 if (buf_write_bytes(&write_info) == FAIL)
4816 break;
4817
4818 if (close(write_info.bw_fd) >= 0
4819 && write_info.bw_len == 0)
4820 end = 1; /* success */
4821 }
4822 close(fd); /* ignore errors for closing read file */
4823 }
4824 }
4825 else
4826 {
4827 if (vim_rename(backup, fname) == 0)
4828 end = 1;
4829 }
4830 }
4831 goto fail;
4832 }
4833
4834 lnum -= start; /* compute number of written lines */
4835 --no_wait_return; /* may wait for return now */
4836
4837#if !(defined(UNIX) || defined(VMS))
4838 fname = sfname; /* use shortname now, for the messages */
4839#endif
4840 if (!filtering)
4841 {
4842 msg_add_fname(buf, fname); /* put fname in IObuff with quotes */
4843 c = FALSE;
4844#ifdef FEAT_MBYTE
4845 if (write_info.bw_conv_error)
4846 {
4847 STRCAT(IObuff, _(" CONVERSION ERROR"));
4848 c = TRUE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004849 if (write_info.bw_conv_error_lnum != 0)
Bram Moolenaara800b422010-06-27 01:15:55 +02004850 vim_snprintf_add((char *)IObuff, IOSIZE, _(" in line %ld;"),
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004851 (long)write_info.bw_conv_error_lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004852 }
4853 else if (notconverted)
4854 {
4855 STRCAT(IObuff, _("[NOT converted]"));
4856 c = TRUE;
4857 }
4858 else if (converted)
4859 {
4860 STRCAT(IObuff, _("[converted]"));
4861 c = TRUE;
4862 }
4863#endif
4864 if (device)
4865 {
4866 STRCAT(IObuff, _("[Device]"));
4867 c = TRUE;
4868 }
4869 else if (newfile)
4870 {
4871 STRCAT(IObuff, shortmess(SHM_NEW) ? _("[New]") : _("[New File]"));
4872 c = TRUE;
4873 }
4874 if (no_eol)
4875 {
4876 msg_add_eol();
4877 c = TRUE;
4878 }
4879 /* may add [unix/dos/mac] */
4880 if (msg_add_fileformat(fileformat))
4881 c = TRUE;
4882#ifdef FEAT_CRYPT
4883 if (wb_flags & FIO_ENCRYPTED)
4884 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004885 crypt_append_msg(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004886 c = TRUE;
4887 }
4888#endif
4889 msg_add_lines(c, (long)lnum, nchars); /* add line/char count */
4890 if (!shortmess(SHM_WRITE))
4891 {
4892 if (append)
4893 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended"));
4894 else
4895 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written"));
4896 }
4897
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00004898 set_keep_msg(msg_trunc_attr(IObuff, FALSE, 0), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004899 }
4900
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004901 /* When written everything correctly: reset 'modified'. Unless not
4902 * writing to the original file and '+' is not in 'cpoptions'. */
Bram Moolenaar292ad192005-12-11 21:29:51 +00004903 if (reset_changed && whole && !append
Bram Moolenaar071d4272004-06-13 20:20:40 +00004904#ifdef FEAT_MBYTE
4905 && !write_info.bw_conv_error
4906#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004907 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL)
4908 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004909 {
4910 unchanged(buf, TRUE);
Bram Moolenaar086329d2014-10-31 19:51:36 +01004911#ifdef FEAT_AUTOCMD
4912 /* buf->b_changedtick is always incremented in unchanged() but that
4913 * should not trigger a TextChanged event. */
4914 if (last_changedtick + 1 == buf->b_changedtick
4915 && last_changedtick_buf == buf)
4916 last_changedtick = buf->b_changedtick;
4917#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004918 u_unchanged(buf);
Bram Moolenaar730cde92010-06-27 05:18:54 +02004919 u_update_save_nr(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004920 }
4921
4922 /*
4923 * If written to the current file, update the timestamp of the swap file
4924 * and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
4925 */
4926 if (overwriting)
4927 {
4928 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00004929 if (append)
4930 buf->b_flags &= ~BF_NEW;
4931 else
4932 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004933 }
4934
4935 /*
4936 * If we kept a backup until now, and we are in patch mode, then we make
4937 * the backup file our 'original' file.
4938 */
4939 if (*p_pm && dobackup)
4940 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01004941 char *org = (char *)buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00004942 fname, p_pm, FALSE);
4943
4944 if (backup != NULL)
4945 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02004946 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004947
4948 /*
4949 * If the original file does not exist yet
4950 * the current backup file becomes the original file
4951 */
4952 if (org == NULL)
4953 EMSG(_("E205: Patchmode: can't save original file"));
4954 else if (mch_stat(org, &st) < 0)
4955 {
4956 vim_rename(backup, (char_u *)org);
4957 vim_free(backup); /* don't delete the file */
4958 backup = NULL;
4959#ifdef UNIX
4960 set_file_time((char_u *)org, st_old.st_atime, st_old.st_mtime);
4961#endif
4962 }
4963 }
4964 /*
4965 * If there is no backup file, remember that a (new) file was
4966 * created.
4967 */
4968 else
4969 {
4970 int empty_fd;
4971
4972 if (org == NULL
Bram Moolenaara5792f52005-11-23 21:25:05 +00004973 || (empty_fd = mch_open(org,
4974 O_CREAT | O_EXTRA | O_EXCL | O_NOFOLLOW,
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00004975 perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004976 EMSG(_("E206: patchmode: can't touch empty original file"));
4977 else
4978 close(empty_fd);
4979 }
4980 if (org != NULL)
4981 {
4982 mch_setperm((char_u *)org, mch_getperm(fname) & 0777);
4983 vim_free(org);
4984 }
4985 }
4986
4987 /*
4988 * Remove the backup unless 'backup' option is set
4989 */
4990 if (!p_bk && backup != NULL && mch_remove(backup) != 0)
4991 EMSG(_("E207: Can't delete backup file"));
4992
4993#ifdef FEAT_SUN_WORKSHOP
4994 if (usingSunWorkShop)
4995 workshop_file_saved((char *) ffname);
4996#endif
4997
4998 goto nofail;
4999
5000 /*
5001 * Finish up. We get here either after failure or success.
5002 */
5003fail:
5004 --no_wait_return; /* may wait for return now */
5005nofail:
5006
5007 /* Done saving, we accept changed buffer warnings again */
5008 buf->b_saving = FALSE;
5009
5010 vim_free(backup);
5011 if (buffer != smallbuf)
5012 vim_free(buffer);
5013#ifdef FEAT_MBYTE
5014 vim_free(fenc_tofree);
5015 vim_free(write_info.bw_conv_buf);
5016# ifdef USE_ICONV
5017 if (write_info.bw_iconv_fd != (iconv_t)-1)
5018 {
5019 iconv_close(write_info.bw_iconv_fd);
5020 write_info.bw_iconv_fd = (iconv_t)-1;
5021 }
5022# endif
5023#endif
5024#ifdef HAVE_ACL
5025 mch_free_acl(acl);
5026#endif
5027
5028 if (errmsg != NULL)
5029 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005030 int numlen = errnum != NULL ? (int)STRLEN(errnum) : 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005031
5032 attr = hl_attr(HLF_E); /* set highlight for error messages */
5033 msg_add_fname(buf,
5034#ifndef UNIX
5035 sfname
5036#else
5037 fname
5038#endif
5039 ); /* put file name in IObuff with quotes */
5040 if (STRLEN(IObuff) + STRLEN(errmsg) + numlen >= IOSIZE)
5041 IObuff[IOSIZE - STRLEN(errmsg) - numlen - 1] = NUL;
5042 /* If the error message has the form "is ...", put the error number in
5043 * front of the file name. */
5044 if (errnum != NULL)
5045 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00005046 STRMOVE(IObuff + numlen, IObuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005047 mch_memmove(IObuff, errnum, (size_t)numlen);
5048 }
5049 STRCAT(IObuff, errmsg);
5050 emsg(IObuff);
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005051 if (errmsg_allocated)
5052 vim_free(errmsg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005053
5054 retval = FAIL;
5055 if (end == 0)
5056 {
5057 MSG_PUTS_ATTR(_("\nWARNING: Original file may be lost or damaged\n"),
5058 attr | MSG_HIST);
5059 MSG_PUTS_ATTR(_("don't quit the editor until the file is successfully written!"),
5060 attr | MSG_HIST);
5061
5062 /* Update the timestamp to avoid an "overwrite changed file"
5063 * prompt when writing again. */
5064 if (mch_stat((char *)fname, &st_old) >= 0)
5065 {
5066 buf_store_time(buf, &st_old, fname);
5067 buf->b_mtime_read = buf->b_mtime;
5068 }
5069 }
5070 }
5071 msg_scroll = msg_save;
5072
Bram Moolenaar55debbe2010-05-23 23:34:36 +02005073#ifdef FEAT_PERSISTENT_UNDO
5074 /*
5075 * When writing the whole file and 'undofile' is set, also write the undo
5076 * file.
5077 */
5078 if (retval == OK && write_undo_file)
5079 {
5080 char_u hash[UNDO_HASH_SIZE];
5081
5082 sha256_finish(&sha_ctx, hash);
5083 u_write_undo(NULL, FALSE, buf, hash);
5084 }
5085#endif
5086
Bram Moolenaar071d4272004-06-13 20:20:40 +00005087#ifdef FEAT_AUTOCMD
5088#ifdef FEAT_EVAL
5089 if (!should_abort(retval))
5090#else
5091 if (!got_int)
5092#endif
5093 {
5094 aco_save_T aco;
5095
Bram Moolenaar68a33fc2012-04-25 16:50:48 +02005096 curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */
5097
Bram Moolenaar071d4272004-06-13 20:20:40 +00005098 /*
5099 * Apply POST autocommands.
5100 * Careful: The autocommands may call buf_write() recursively!
5101 */
5102 aucmd_prepbuf(&aco, buf);
5103
5104 if (append)
5105 apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname,
5106 FALSE, curbuf, eap);
5107 else if (filtering)
5108 apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname,
5109 FALSE, curbuf, eap);
5110 else if (reset_changed && whole)
5111 apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname,
5112 FALSE, curbuf, eap);
5113 else
5114 apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname,
5115 FALSE, curbuf, eap);
5116
5117 /* restore curwin/curbuf and a few other things */
5118 aucmd_restbuf(&aco);
5119
5120#ifdef FEAT_EVAL
5121 if (aborting()) /* autocmds may abort script processing */
5122 retval = FALSE;
5123#endif
5124 }
5125#endif
5126
5127 got_int |= prev_got_int;
5128
5129#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
5130 /* Update machine specific information. */
5131 mch_post_buffer_write(buf);
5132#endif
5133 return retval;
5134}
5135
5136/*
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005137 * Set the name of the current buffer. Use when the buffer doesn't have a
5138 * name and a ":r" or ":w" command with a file name is used.
5139 */
5140 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005141set_rw_fname(char_u *fname, char_u *sfname)
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005142{
5143#ifdef FEAT_AUTOCMD
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005144 buf_T *buf = curbuf;
5145
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005146 /* It's like the unnamed buffer is deleted.... */
5147 if (curbuf->b_p_bl)
5148 apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
5149 apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf);
5150# ifdef FEAT_EVAL
5151 if (aborting()) /* autocmds may abort script processing */
5152 return FAIL;
5153# endif
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005154 if (curbuf != buf)
5155 {
5156 /* We are in another buffer now, don't do the renaming. */
5157 EMSG(_(e_auchangedbuf));
5158 return FAIL;
5159 }
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005160#endif
5161
5162 if (setfname(curbuf, fname, sfname, FALSE) == OK)
5163 curbuf->b_flags |= BF_NOTEDITED;
5164
5165#ifdef FEAT_AUTOCMD
5166 /* ....and a new named one is created */
5167 apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, curbuf);
5168 if (curbuf->b_p_bl)
5169 apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf);
5170# ifdef FEAT_EVAL
5171 if (aborting()) /* autocmds may abort script processing */
5172 return FAIL;
5173# endif
5174
5175 /* Do filetype detection now if 'filetype' is empty. */
5176 if (*curbuf->b_p_ft == NUL)
5177 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005178 if (au_has_group((char_u *)"filetypedetect"))
Bram Moolenaar1610d052016-06-09 22:53:01 +02005179 (void)do_doautocmd((char_u *)"filetypedetect BufRead", FALSE, NULL);
Bram Moolenaara3227e22006-03-08 21:32:40 +00005180 do_modelines(0);
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005181 }
5182#endif
5183
5184 return OK;
5185}
5186
5187/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00005188 * Put file name into IObuff with quotes.
5189 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005190 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005191msg_add_fname(buf_T *buf, char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005192{
5193 if (fname == NULL)
5194 fname = (char_u *)"-stdin-";
5195 home_replace(buf, fname, IObuff + 1, IOSIZE - 4, TRUE);
5196 IObuff[0] = '"';
5197 STRCAT(IObuff, "\" ");
5198}
5199
5200/*
5201 * Append message for text mode to IObuff.
5202 * Return TRUE if something appended.
5203 */
5204 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005205msg_add_fileformat(int eol_type)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005206{
5207#ifndef USE_CRNL
5208 if (eol_type == EOL_DOS)
5209 {
5210 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[dos]") : _("[dos format]"));
5211 return TRUE;
5212 }
5213#endif
5214#ifndef USE_CR
5215 if (eol_type == EOL_MAC)
5216 {
5217 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[mac]") : _("[mac format]"));
5218 return TRUE;
5219 }
5220#endif
5221#if defined(USE_CRNL) || defined(USE_CR)
5222 if (eol_type == EOL_UNIX)
5223 {
5224 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[unix]") : _("[unix format]"));
5225 return TRUE;
5226 }
5227#endif
5228 return FALSE;
5229}
5230
5231/*
5232 * Append line and character count to IObuff.
5233 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005234 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005235msg_add_lines(
5236 int insert_space,
5237 long lnum,
Bram Moolenaar8767f522016-07-01 17:17:39 +02005238 off_T nchars)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005239{
5240 char_u *p;
5241
5242 p = IObuff + STRLEN(IObuff);
5243
5244 if (insert_space)
5245 *p++ = ' ';
5246 if (shortmess(SHM_LINES))
Bram Moolenaarbde98102016-07-01 20:03:42 +02005247 vim_snprintf((char *)p, IOSIZE - (p - IObuff),
5248 "%ldL, %lldC", lnum, (varnumber_T)nchars);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005249 else
5250 {
5251 if (lnum == 1)
5252 STRCPY(p, _("1 line, "));
5253 else
5254 sprintf((char *)p, _("%ld lines, "), lnum);
5255 p += STRLEN(p);
5256 if (nchars == 1)
5257 STRCPY(p, _("1 character"));
5258 else
Bram Moolenaarbde98102016-07-01 20:03:42 +02005259 vim_snprintf((char *)p, IOSIZE - (p - IObuff),
5260 _("%lld characters"), (varnumber_T)nchars);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005261 }
5262}
5263
5264/*
5265 * Append message for missing line separator to IObuff.
5266 */
5267 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005268msg_add_eol(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005269{
5270 STRCAT(IObuff, shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]"));
5271}
5272
5273/*
5274 * Check modification time of file, before writing to it.
5275 * The size isn't checked, because using a tool like "gzip" takes care of
5276 * using the same timestamp but can't set the size.
5277 */
5278 static int
Bram Moolenaar8767f522016-07-01 17:17:39 +02005279check_mtime(buf_T *buf, stat_T *st)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005280{
5281 if (buf->b_mtime_read != 0
5282 && time_differs((long)st->st_mtime, buf->b_mtime_read))
5283 {
5284 msg_scroll = TRUE; /* don't overwrite messages here */
5285 msg_silent = 0; /* must give this prompt */
5286 /* don't use emsg() here, don't want to flush the buffers */
5287 MSG_ATTR(_("WARNING: The file has been changed since reading it!!!"),
5288 hl_attr(HLF_E));
5289 if (ask_yesno((char_u *)_("Do you really want to write to it"),
5290 TRUE) == 'n')
5291 return FAIL;
5292 msg_scroll = FALSE; /* always overwrite the file message now */
5293 }
5294 return OK;
5295}
5296
5297 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005298time_differs(long t1, long t2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005299{
Bram Moolenaar48e330a2016-02-23 14:53:34 +01005300#if defined(__linux__) || defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005301 /* On a FAT filesystem, esp. under Linux, there are only 5 bits to store
5302 * the seconds. Since the roundoff is done when flushing the inode, the
5303 * time may change unexpectedly by one second!!! */
5304 return (t1 - t2 > 1 || t2 - t1 > 1);
5305#else
5306 return (t1 != t2);
5307#endif
5308}
5309
5310/*
5311 * Call write() to write a number of bytes to the file.
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005312 * Handles encryption and 'encoding' conversion.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005313 *
5314 * Return FAIL for failure, OK otherwise.
5315 */
5316 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005317buf_write_bytes(struct bw_info *ip)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005318{
5319 int wlen;
5320 char_u *buf = ip->bw_buf; /* data to write */
5321 int len = ip->bw_len; /* length of data */
5322#ifdef HAS_BW_FLAGS
5323 int flags = ip->bw_flags; /* extra flags */
5324#endif
5325
5326#ifdef FEAT_MBYTE
5327 /*
5328 * Skip conversion when writing the crypt magic number or the BOM.
5329 */
5330 if (!(flags & FIO_NOCONVERT))
5331 {
5332 char_u *p;
5333 unsigned c;
5334 int n;
5335
5336 if (flags & FIO_UTF8)
5337 {
5338 /*
5339 * Convert latin1 in the buffer to UTF-8 in the file.
5340 */
5341 p = ip->bw_conv_buf; /* translate to buffer */
5342 for (wlen = 0; wlen < len; ++wlen)
5343 p += utf_char2bytes(buf[wlen], p);
5344 buf = ip->bw_conv_buf;
5345 len = (int)(p - ip->bw_conv_buf);
5346 }
5347 else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1))
5348 {
5349 /*
5350 * Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
5351 * Latin1 chars in the file.
5352 */
5353 if (flags & FIO_LATIN1)
5354 p = buf; /* translate in-place (can only get shorter) */
5355 else
5356 p = ip->bw_conv_buf; /* translate to buffer */
5357 for (wlen = 0; wlen < len; wlen += n)
5358 {
5359 if (wlen == 0 && ip->bw_restlen != 0)
5360 {
5361 int l;
5362
5363 /* Use remainder of previous call. Append the start of
5364 * buf[] to get a full sequence. Might still be too
5365 * short! */
5366 l = CONV_RESTLEN - ip->bw_restlen;
5367 if (l > len)
5368 l = len;
5369 mch_memmove(ip->bw_rest + ip->bw_restlen, buf, (size_t)l);
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005370 n = utf_ptr2len_len(ip->bw_rest, ip->bw_restlen + l);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005371 if (n > ip->bw_restlen + len)
5372 {
5373 /* We have an incomplete byte sequence at the end to
5374 * be written. We can't convert it without the
5375 * remaining bytes. Keep them for the next call. */
5376 if (ip->bw_restlen + len > CONV_RESTLEN)
5377 return FAIL;
5378 ip->bw_restlen += len;
5379 break;
5380 }
5381 if (n > 1)
5382 c = utf_ptr2char(ip->bw_rest);
5383 else
5384 c = ip->bw_rest[0];
5385 if (n >= ip->bw_restlen)
5386 {
5387 n -= ip->bw_restlen;
5388 ip->bw_restlen = 0;
5389 }
5390 else
5391 {
5392 ip->bw_restlen -= n;
5393 mch_memmove(ip->bw_rest, ip->bw_rest + n,
5394 (size_t)ip->bw_restlen);
5395 n = 0;
5396 }
5397 }
5398 else
5399 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005400 n = utf_ptr2len_len(buf + wlen, len - wlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005401 if (n > len - wlen)
5402 {
5403 /* We have an incomplete byte sequence at the end to
5404 * be written. We can't convert it without the
5405 * remaining bytes. Keep them for the next call. */
5406 if (len - wlen > CONV_RESTLEN)
5407 return FAIL;
5408 ip->bw_restlen = len - wlen;
5409 mch_memmove(ip->bw_rest, buf + wlen,
5410 (size_t)ip->bw_restlen);
5411 break;
5412 }
5413 if (n > 1)
5414 c = utf_ptr2char(buf + wlen);
5415 else
5416 c = buf[wlen];
5417 }
5418
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005419 if (ucs2bytes(c, &p, flags) && !ip->bw_conv_error)
5420 {
5421 ip->bw_conv_error = TRUE;
5422 ip->bw_conv_error_lnum = ip->bw_start_lnum;
5423 }
5424 if (c == NL)
5425 ++ip->bw_start_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005426 }
5427 if (flags & FIO_LATIN1)
5428 len = (int)(p - buf);
5429 else
5430 {
5431 buf = ip->bw_conv_buf;
5432 len = (int)(p - ip->bw_conv_buf);
5433 }
5434 }
5435
5436# ifdef WIN3264
5437 else if (flags & FIO_CODEPAGE)
5438 {
5439 /*
5440 * Convert UTF-8 or codepage to UCS-2 and then to MS-Windows
5441 * codepage.
5442 */
5443 char_u *from;
5444 size_t fromlen;
5445 char_u *to;
5446 int u8c;
5447 BOOL bad = FALSE;
5448 int needed;
5449
5450 if (ip->bw_restlen > 0)
5451 {
5452 /* Need to concatenate the remainder of the previous call and
5453 * the bytes of the current call. Use the end of the
5454 * conversion buffer for this. */
5455 fromlen = len + ip->bw_restlen;
5456 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5457 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5458 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5459 }
5460 else
5461 {
5462 from = buf;
5463 fromlen = len;
5464 }
5465
5466 to = ip->bw_conv_buf;
5467 if (enc_utf8)
5468 {
5469 /* Convert from UTF-8 to UCS-2, to the start of the buffer.
5470 * The buffer has been allocated to be big enough. */
5471 while (fromlen > 0)
5472 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005473 n = (int)utf_ptr2len_len(from, (int)fromlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005474 if (n > (int)fromlen) /* incomplete byte sequence */
5475 break;
5476 u8c = utf_ptr2char(from);
5477 *to++ = (u8c & 0xff);
5478 *to++ = (u8c >> 8);
5479 fromlen -= n;
5480 from += n;
5481 }
5482
5483 /* Copy remainder to ip->bw_rest[] to be used for the next
5484 * call. */
5485 if (fromlen > CONV_RESTLEN)
5486 {
5487 /* weird overlong sequence */
5488 ip->bw_conv_error = TRUE;
5489 return FAIL;
5490 }
5491 mch_memmove(ip->bw_rest, from, fromlen);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005492 ip->bw_restlen = (int)fromlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005493 }
5494 else
5495 {
5496 /* Convert from enc_codepage to UCS-2, to the start of the
5497 * buffer. The buffer has been allocated to be big enough. */
5498 ip->bw_restlen = 0;
5499 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005500 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005501 NULL, 0);
5502 if (needed == 0)
5503 {
5504 /* When conversion fails there may be a trailing byte. */
5505 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005506 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen - 1,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005507 NULL, 0);
5508 if (needed == 0)
5509 {
5510 /* Conversion doesn't work. */
5511 ip->bw_conv_error = TRUE;
5512 return FAIL;
5513 }
5514 /* Save the trailing byte for the next call. */
5515 ip->bw_rest[0] = from[fromlen - 1];
5516 ip->bw_restlen = 1;
5517 }
5518 needed = MultiByteToWideChar(enc_codepage, MB_ERR_INVALID_CHARS,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005519 (LPCSTR)from, (int)(fromlen - ip->bw_restlen),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005520 (LPWSTR)to, needed);
5521 if (needed == 0)
5522 {
5523 /* Safety check: Conversion doesn't work. */
5524 ip->bw_conv_error = TRUE;
5525 return FAIL;
5526 }
5527 to += needed * 2;
5528 }
5529
5530 fromlen = to - ip->bw_conv_buf;
5531 buf = to;
5532# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5533 if (FIO_GET_CP(flags) == CP_UTF8)
5534 {
5535 /* Convert from UCS-2 to UTF-8, using the remainder of the
5536 * conversion buffer. Fails when out of space. */
5537 for (from = ip->bw_conv_buf; fromlen > 1; fromlen -= 2)
5538 {
5539 u8c = *from++;
5540 u8c += (*from++ << 8);
5541 to += utf_char2bytes(u8c, to);
5542 if (to + 6 >= ip->bw_conv_buf + ip->bw_conv_buflen)
5543 {
5544 ip->bw_conv_error = TRUE;
5545 return FAIL;
5546 }
5547 }
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005548 len = (int)(to - buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005549 }
5550 else
5551#endif
5552 {
5553 /* Convert from UCS-2 to the codepage, using the remainder of
5554 * the conversion buffer. If the conversion uses the default
5555 * character "0", the data doesn't fit in this encoding, so
5556 * fail. */
5557 len = WideCharToMultiByte(FIO_GET_CP(flags), 0,
5558 (LPCWSTR)ip->bw_conv_buf, (int)fromlen / sizeof(WCHAR),
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005559 (LPSTR)to, (int)(ip->bw_conv_buflen - fromlen), 0,
5560 &bad);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005561 if (bad)
5562 {
5563 ip->bw_conv_error = TRUE;
5564 return FAIL;
5565 }
5566 }
5567 }
5568# endif
5569
Bram Moolenaar56718732006-03-15 22:53:57 +00005570# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00005571 else if (flags & FIO_MACROMAN)
5572 {
5573 /*
5574 * Convert UTF-8 or latin1 to Apple MacRoman.
5575 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005576 char_u *from;
5577 size_t fromlen;
5578
5579 if (ip->bw_restlen > 0)
5580 {
5581 /* Need to concatenate the remainder of the previous call and
5582 * the bytes of the current call. Use the end of the
5583 * conversion buffer for this. */
5584 fromlen = len + ip->bw_restlen;
5585 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5586 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5587 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5588 }
5589 else
5590 {
5591 from = buf;
5592 fromlen = len;
5593 }
5594
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00005595 if (enc2macroman(from, fromlen,
5596 ip->bw_conv_buf, &len, ip->bw_conv_buflen,
5597 ip->bw_rest, &ip->bw_restlen) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005598 {
5599 ip->bw_conv_error = TRUE;
5600 return FAIL;
5601 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005602 buf = ip->bw_conv_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005603 }
5604# endif
5605
5606# ifdef USE_ICONV
5607 if (ip->bw_iconv_fd != (iconv_t)-1)
5608 {
5609 const char *from;
5610 size_t fromlen;
5611 char *to;
5612 size_t tolen;
5613
5614 /* Convert with iconv(). */
5615 if (ip->bw_restlen > 0)
5616 {
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005617 char *fp;
5618
Bram Moolenaar071d4272004-06-13 20:20:40 +00005619 /* Need to concatenate the remainder of the previous call and
5620 * the bytes of the current call. Use the end of the
5621 * conversion buffer for this. */
5622 fromlen = len + ip->bw_restlen;
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005623 fp = (char *)ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5624 mch_memmove(fp, ip->bw_rest, (size_t)ip->bw_restlen);
5625 mch_memmove(fp + ip->bw_restlen, buf, (size_t)len);
5626 from = fp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005627 tolen = ip->bw_conv_buflen - fromlen;
5628 }
5629 else
5630 {
5631 from = (const char *)buf;
5632 fromlen = len;
5633 tolen = ip->bw_conv_buflen;
5634 }
5635 to = (char *)ip->bw_conv_buf;
5636
5637 if (ip->bw_first)
5638 {
5639 size_t save_len = tolen;
5640
5641 /* output the initial shift state sequence */
5642 (void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen);
5643
5644 /* There is a bug in iconv() on Linux (which appears to be
5645 * wide-spread) which sets "to" to NULL and messes up "tolen".
5646 */
5647 if (to == NULL)
5648 {
5649 to = (char *)ip->bw_conv_buf;
5650 tolen = save_len;
5651 }
5652 ip->bw_first = FALSE;
5653 }
5654
5655 /*
5656 * If iconv() has an error or there is not enough room, fail.
5657 */
5658 if ((iconv(ip->bw_iconv_fd, (void *)&from, &fromlen, &to, &tolen)
5659 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
5660 || fromlen > CONV_RESTLEN)
5661 {
5662 ip->bw_conv_error = TRUE;
5663 return FAIL;
5664 }
5665
5666 /* copy remainder to ip->bw_rest[] to be used for the next call. */
5667 if (fromlen > 0)
5668 mch_memmove(ip->bw_rest, (void *)from, fromlen);
5669 ip->bw_restlen = (int)fromlen;
5670
5671 buf = ip->bw_conv_buf;
5672 len = (int)((char_u *)to - ip->bw_conv_buf);
5673 }
5674# endif
5675 }
5676#endif /* FEAT_MBYTE */
5677
5678#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02005679 if (flags & FIO_ENCRYPTED)
5680 {
5681 /* Encrypt the data. Do it in-place if possible, otherwise use an
5682 * allocated buffer. */
5683 if (crypt_works_inplace(ip->bw_buffer->b_cryptstate))
5684 {
5685 crypt_encode_inplace(ip->bw_buffer->b_cryptstate, buf, len);
5686 }
5687 else
5688 {
5689 char_u *outbuf;
5690
5691 len = crypt_encode_alloc(curbuf->b_cryptstate, buf, len, &outbuf);
5692 if (len == 0)
5693 return OK; /* Crypt layer is buffering, will flush later. */
5694 wlen = write_eintr(ip->bw_fd, outbuf, len);
5695 vim_free(outbuf);
5696 return (wlen < len) ? FAIL : OK;
5697 }
5698 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005699#endif
5700
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005701 wlen = write_eintr(ip->bw_fd, buf, len);
5702 return (wlen < len) ? FAIL : OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005703}
5704
5705#ifdef FEAT_MBYTE
5706/*
5707 * Convert a Unicode character to bytes.
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005708 * Return TRUE for an error, FALSE when it's OK.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005709 */
5710 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005711ucs2bytes(
5712 unsigned c, /* in: character */
5713 char_u **pp, /* in/out: pointer to result */
5714 int flags) /* FIO_ flags */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005715{
5716 char_u *p = *pp;
5717 int error = FALSE;
5718 int cc;
5719
5720
5721 if (flags & FIO_UCS4)
5722 {
5723 if (flags & FIO_ENDIAN_L)
5724 {
5725 *p++ = c;
5726 *p++ = (c >> 8);
5727 *p++ = (c >> 16);
5728 *p++ = (c >> 24);
5729 }
5730 else
5731 {
5732 *p++ = (c >> 24);
5733 *p++ = (c >> 16);
5734 *p++ = (c >> 8);
5735 *p++ = c;
5736 }
5737 }
5738 else if (flags & (FIO_UCS2 | FIO_UTF16))
5739 {
5740 if (c >= 0x10000)
5741 {
5742 if (flags & FIO_UTF16)
5743 {
5744 /* Make two words, ten bits of the character in each. First
5745 * word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff */
5746 c -= 0x10000;
5747 if (c >= 0x100000)
5748 error = TRUE;
5749 cc = ((c >> 10) & 0x3ff) + 0xd800;
5750 if (flags & FIO_ENDIAN_L)
5751 {
5752 *p++ = cc;
5753 *p++ = ((unsigned)cc >> 8);
5754 }
5755 else
5756 {
5757 *p++ = ((unsigned)cc >> 8);
5758 *p++ = cc;
5759 }
5760 c = (c & 0x3ff) + 0xdc00;
5761 }
5762 else
5763 error = TRUE;
5764 }
5765 if (flags & FIO_ENDIAN_L)
5766 {
5767 *p++ = c;
5768 *p++ = (c >> 8);
5769 }
5770 else
5771 {
5772 *p++ = (c >> 8);
5773 *p++ = c;
5774 }
5775 }
5776 else /* Latin1 */
5777 {
5778 if (c >= 0x100)
5779 {
5780 error = TRUE;
5781 *p++ = 0xBF;
5782 }
5783 else
5784 *p++ = c;
5785 }
5786
5787 *pp = p;
5788 return error;
5789}
5790
5791/*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005792 * Return TRUE if file encoding "fenc" requires conversion from or to
5793 * 'encoding'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005794 */
5795 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005796need_conversion(char_u *fenc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005797{
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005798 int same_encoding;
5799 int enc_flags;
5800 int fenc_flags;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005801
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005802 if (*fenc == NUL || STRCMP(p_enc, fenc) == 0)
Bram Moolenaar442b4222010-05-24 21:34:22 +02005803 {
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005804 same_encoding = TRUE;
Bram Moolenaar442b4222010-05-24 21:34:22 +02005805 fenc_flags = 0;
5806 }
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005807 else
5808 {
5809 /* Ignore difference between "ansi" and "latin1", "ucs-4" and
5810 * "ucs-4be", etc. */
5811 enc_flags = get_fio_flags(p_enc);
5812 fenc_flags = get_fio_flags(fenc);
5813 same_encoding = (enc_flags != 0 && fenc_flags == enc_flags);
5814 }
5815 if (same_encoding)
5816 {
5817 /* Specified encoding matches with 'encoding'. This requires
5818 * conversion when 'encoding' is Unicode but not UTF-8. */
5819 return enc_unicode != 0;
5820 }
5821
5822 /* Encodings differ. However, conversion is not needed when 'enc' is any
5823 * Unicode encoding and the file is UTF-8. */
5824 return !(enc_utf8 && fenc_flags == FIO_UTF8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005825}
5826
5827/*
5828 * Check "ptr" for a unicode encoding and return the FIO_ flags needed for the
5829 * internal conversion.
5830 * if "ptr" is an empty string, use 'encoding'.
5831 */
5832 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005833get_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005834{
5835 int prop;
5836
5837 if (*ptr == NUL)
5838 ptr = p_enc;
5839
5840 prop = enc_canon_props(ptr);
5841 if (prop & ENC_UNICODE)
5842 {
5843 if (prop & ENC_2BYTE)
5844 {
5845 if (prop & ENC_ENDIAN_L)
5846 return FIO_UCS2 | FIO_ENDIAN_L;
5847 return FIO_UCS2;
5848 }
5849 if (prop & ENC_4BYTE)
5850 {
5851 if (prop & ENC_ENDIAN_L)
5852 return FIO_UCS4 | FIO_ENDIAN_L;
5853 return FIO_UCS4;
5854 }
5855 if (prop & ENC_2WORD)
5856 {
5857 if (prop & ENC_ENDIAN_L)
5858 return FIO_UTF16 | FIO_ENDIAN_L;
5859 return FIO_UTF16;
5860 }
5861 return FIO_UTF8;
5862 }
5863 if (prop & ENC_LATIN1)
5864 return FIO_LATIN1;
5865 /* must be ENC_DBCS, requires iconv() */
5866 return 0;
5867}
5868
5869#ifdef WIN3264
5870/*
5871 * Check "ptr" for a MS-Windows codepage name and return the FIO_ flags needed
5872 * for the conversion MS-Windows can do for us. Also accept "utf-8".
5873 * Used for conversion between 'encoding' and 'fileencoding'.
5874 */
5875 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005876get_win_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005877{
5878 int cp;
5879
5880 /* Cannot do this when 'encoding' is not utf-8 and not a codepage. */
5881 if (!enc_utf8 && enc_codepage <= 0)
5882 return 0;
5883
5884 cp = encname2codepage(ptr);
5885 if (cp == 0)
5886 {
5887# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5888 if (STRCMP(ptr, "utf-8") == 0)
5889 cp = CP_UTF8;
5890 else
5891# endif
5892 return 0;
5893 }
5894 return FIO_PUT_CP(cp) | FIO_CODEPAGE;
5895}
5896#endif
5897
5898#ifdef MACOS_X
5899/*
5900 * Check "ptr" for a Carbon supported encoding and return the FIO_ flags
5901 * needed for the internal conversion to/from utf-8 or latin1.
5902 */
5903 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005904get_mac_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005905{
5906 if ((enc_utf8 || STRCMP(p_enc, "latin1") == 0)
5907 && (enc_canon_props(ptr) & ENC_MACROMAN))
5908 return FIO_MACROMAN;
5909 return 0;
5910}
5911#endif
5912
5913/*
5914 * Check for a Unicode BOM (Byte Order Mark) at the start of p[size].
5915 * "size" must be at least 2.
5916 * Return the name of the encoding and set "*lenp" to the length.
5917 * Returns NULL when no BOM found.
5918 */
5919 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005920check_for_bom(
5921 char_u *p,
5922 long size,
5923 int *lenp,
5924 int flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005925{
5926 char *name = NULL;
5927 int len = 2;
5928
5929 if (p[0] == 0xef && p[1] == 0xbb && size >= 3 && p[2] == 0xbf
Bram Moolenaaree0f5a62008-07-24 20:09:16 +00005930 && (flags == FIO_ALL || flags == FIO_UTF8 || flags == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005931 {
5932 name = "utf-8"; /* EF BB BF */
5933 len = 3;
5934 }
5935 else if (p[0] == 0xff && p[1] == 0xfe)
5936 {
5937 if (size >= 4 && p[2] == 0 && p[3] == 0
5938 && (flags == FIO_ALL || flags == (FIO_UCS4 | FIO_ENDIAN_L)))
5939 {
5940 name = "ucs-4le"; /* FF FE 00 00 */
5941 len = 4;
5942 }
Bram Moolenaar223a1892008-11-11 20:57:11 +00005943 else if (flags == (FIO_UCS2 | FIO_ENDIAN_L))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005944 name = "ucs-2le"; /* FF FE */
Bram Moolenaar223a1892008-11-11 20:57:11 +00005945 else if (flags == FIO_ALL || flags == (FIO_UTF16 | FIO_ENDIAN_L))
5946 /* utf-16le is preferred, it also works for ucs-2le text */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005947 name = "utf-16le"; /* FF FE */
5948 }
5949 else if (p[0] == 0xfe && p[1] == 0xff
5950 && (flags == FIO_ALL || flags == FIO_UCS2 || flags == FIO_UTF16))
5951 {
Bram Moolenaarffd82c52008-02-20 17:15:26 +00005952 /* Default to utf-16, it works also for ucs-2 text. */
5953 if (flags == FIO_UCS2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005954 name = "ucs-2"; /* FE FF */
Bram Moolenaarffd82c52008-02-20 17:15:26 +00005955 else
5956 name = "utf-16"; /* FE FF */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005957 }
5958 else if (size >= 4 && p[0] == 0 && p[1] == 0 && p[2] == 0xfe
5959 && p[3] == 0xff && (flags == FIO_ALL || flags == FIO_UCS4))
5960 {
5961 name = "ucs-4"; /* 00 00 FE FF */
5962 len = 4;
5963 }
5964
5965 *lenp = len;
5966 return (char_u *)name;
5967}
5968
5969/*
5970 * Generate a BOM in "buf[4]" for encoding "name".
5971 * Return the length of the BOM (zero when no BOM).
5972 */
5973 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005974make_bom(char_u *buf, char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005975{
5976 int flags;
5977 char_u *p;
5978
5979 flags = get_fio_flags(name);
5980
5981 /* Can't put a BOM in a non-Unicode file. */
5982 if (flags == FIO_LATIN1 || flags == 0)
5983 return 0;
5984
5985 if (flags == FIO_UTF8) /* UTF-8 */
5986 {
5987 buf[0] = 0xef;
5988 buf[1] = 0xbb;
5989 buf[2] = 0xbf;
5990 return 3;
5991 }
5992 p = buf;
5993 (void)ucs2bytes(0xfeff, &p, flags);
5994 return (int)(p - buf);
5995}
5996#endif
5997
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00005998#if defined(FEAT_VIMINFO) || defined(FEAT_BROWSE) || \
Bram Moolenaara0174af2008-01-02 20:08:25 +00005999 defined(FEAT_QUICKFIX) || defined(FEAT_AUTOCMD) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006000/*
6001 * Try to find a shortname by comparing the fullname with the current
6002 * directory.
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006003 * Returns "full_path" or pointer into "full_path" if shortened.
6004 */
6005 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006006shorten_fname1(char_u *full_path)
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006007{
Bram Moolenaard9462e32011-04-11 21:35:11 +02006008 char_u *dirname;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006009 char_u *p = full_path;
6010
Bram Moolenaard9462e32011-04-11 21:35:11 +02006011 dirname = alloc(MAXPATHL);
6012 if (dirname == NULL)
6013 return full_path;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006014 if (mch_dirname(dirname, MAXPATHL) == OK)
6015 {
6016 p = shorten_fname(full_path, dirname);
6017 if (p == NULL || *p == NUL)
6018 p = full_path;
6019 }
Bram Moolenaard9462e32011-04-11 21:35:11 +02006020 vim_free(dirname);
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006021 return p;
6022}
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00006023#endif
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006024
6025/*
6026 * Try to find a shortname by comparing the fullname with the current
6027 * directory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006028 * Returns NULL if not shorter name possible, pointer into "full_path"
6029 * otherwise.
6030 */
6031 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006032shorten_fname(char_u *full_path, char_u *dir_name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006033{
6034 int len;
6035 char_u *p;
6036
6037 if (full_path == NULL)
6038 return NULL;
6039 len = (int)STRLEN(dir_name);
6040 if (fnamencmp(dir_name, full_path, len) == 0)
6041 {
6042 p = full_path + len;
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006043#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006044 /*
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006045 * MSWIN: when a file is in the root directory, dir_name will end in a
Bram Moolenaar071d4272004-06-13 20:20:40 +00006046 * slash, since C: by itself does not define a specific dir. In this
6047 * case p may already be correct. <negri>
6048 */
6049 if (!((len > 2) && (*(p - 2) == ':')))
6050#endif
6051 {
6052 if (vim_ispathsep(*p))
6053 ++p;
6054#ifndef VMS /* the path separator is always part of the path */
6055 else
6056 p = NULL;
6057#endif
6058 }
6059 }
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006060#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006061 /*
6062 * When using a file in the current drive, remove the drive name:
6063 * "A:\dir\file" -> "\dir\file". This helps when moving a session file on
6064 * a floppy from "A:\dir" to "B:\dir".
6065 */
6066 else if (len > 3
6067 && TOUPPER_LOC(full_path[0]) == TOUPPER_LOC(dir_name[0])
6068 && full_path[1] == ':'
6069 && vim_ispathsep(full_path[2]))
6070 p = full_path + 2;
6071#endif
6072 else
6073 p = NULL;
6074 return p;
6075}
6076
6077/*
6078 * Shorten filenames for all buffers.
6079 * When "force" is TRUE: Use full path from now on for files currently being
6080 * edited, both for file name and swap file name. Try to shorten the file
6081 * names a bit, if safe to do so.
6082 * When "force" is FALSE: Only try to shorten absolute file names.
6083 * For buffers that have buftype "nofile" or "scratch": never change the file
6084 * name.
6085 */
6086 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006087shorten_fnames(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006088{
6089 char_u dirname[MAXPATHL];
6090 buf_T *buf;
6091 char_u *p;
6092
6093 mch_dirname(dirname, MAXPATHL);
Bram Moolenaar29323592016-07-24 22:04:11 +02006094 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006095 {
6096 if (buf->b_fname != NULL
6097#ifdef FEAT_QUICKFIX
6098 && !bt_nofile(buf)
6099#endif
6100 && !path_with_url(buf->b_fname)
6101 && (force
6102 || buf->b_sfname == NULL
6103 || mch_isFullName(buf->b_sfname)))
6104 {
6105 vim_free(buf->b_sfname);
6106 buf->b_sfname = NULL;
6107 p = shorten_fname(buf->b_ffname, dirname);
6108 if (p != NULL)
6109 {
6110 buf->b_sfname = vim_strsave(p);
6111 buf->b_fname = buf->b_sfname;
6112 }
6113 if (p == NULL || buf->b_fname == NULL)
6114 buf->b_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006115 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00006116
6117 /* Always make the swap file name a full path, a "nofile" buffer may
6118 * also have a swap file. */
6119 mf_fullname(buf->b_ml.ml_mfp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006120 }
6121#ifdef FEAT_WINDOWS
6122 status_redraw_all();
Bram Moolenaar49d7bf12006-02-17 21:45:41 +00006123 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006124#endif
6125}
6126
6127#if (defined(FEAT_DND) && defined(FEAT_GUI_GTK)) \
6128 || defined(FEAT_GUI_MSWIN) \
6129 || defined(FEAT_GUI_MAC) \
6130 || defined(PROTO)
6131/*
6132 * Shorten all filenames in "fnames[count]" by current directory.
6133 */
6134 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006135shorten_filenames(char_u **fnames, int count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006136{
6137 int i;
6138 char_u dirname[MAXPATHL];
6139 char_u *p;
6140
6141 if (fnames == NULL || count < 1)
6142 return;
6143 mch_dirname(dirname, sizeof(dirname));
6144 for (i = 0; i < count; ++i)
6145 {
6146 if ((p = shorten_fname(fnames[i], dirname)) != NULL)
6147 {
6148 /* shorten_fname() returns pointer in given "fnames[i]". If free
6149 * "fnames[i]" first, "p" becomes invalid. So we need to copy
6150 * "p" first then free fnames[i]. */
6151 p = vim_strsave(p);
6152 vim_free(fnames[i]);
6153 fnames[i] = p;
6154 }
6155 }
6156}
6157#endif
6158
6159/*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006160 * add extension to file name - change path/fo.o.h to path/fo.o.h.ext or
Bram Moolenaar071d4272004-06-13 20:20:40 +00006161 * fo_o_h.ext for MSDOS or when shortname option set.
6162 *
6163 * Assumed that fname is a valid name found in the filesystem we assure that
6164 * the return value is a different name and ends in 'ext'.
6165 * "ext" MUST be at most 4 characters long if it starts with a dot, 3
6166 * characters otherwise.
6167 * Space for the returned name is allocated, must be freed later.
6168 * Returns NULL when out of memory.
6169 */
6170 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006171modname(
6172 char_u *fname,
6173 char_u *ext,
6174 int prepend_dot) /* may prepend a '.' to file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006175{
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006176 return buf_modname((curbuf->b_p_sn || curbuf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00006177 fname, ext, prepend_dot);
6178}
6179
6180 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006181buf_modname(
6182 int shortname, /* use 8.3 file name */
6183 char_u *fname,
6184 char_u *ext,
6185 int prepend_dot) /* may prepend a '.' to file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006186{
6187 char_u *retval;
6188 char_u *s;
6189 char_u *e;
6190 char_u *ptr;
6191 int fnamelen, extlen;
6192
6193 extlen = (int)STRLEN(ext);
6194
6195 /*
6196 * If there is no file name we must get the name of the current directory
6197 * (we need the full path in case :cd is used).
6198 */
6199 if (fname == NULL || *fname == NUL)
6200 {
6201 retval = alloc((unsigned)(MAXPATHL + extlen + 3));
6202 if (retval == NULL)
6203 return NULL;
6204 if (mch_dirname(retval, MAXPATHL) == FAIL ||
6205 (fnamelen = (int)STRLEN(retval)) == 0)
6206 {
6207 vim_free(retval);
6208 return NULL;
6209 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006210 if (!after_pathsep(retval, retval + fnamelen))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006211 {
6212 retval[fnamelen++] = PATHSEP;
6213 retval[fnamelen] = NUL;
6214 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006215 prepend_dot = FALSE; /* nothing to prepend a dot to */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006216 }
6217 else
6218 {
6219 fnamelen = (int)STRLEN(fname);
6220 retval = alloc((unsigned)(fnamelen + extlen + 3));
6221 if (retval == NULL)
6222 return NULL;
6223 STRCPY(retval, fname);
6224#ifdef VMS
6225 vms_remove_version(retval); /* we do not need versions here */
6226#endif
6227 }
6228
6229 /*
6230 * search backwards until we hit a '/', '\' or ':' replacing all '.'
6231 * by '_' for MSDOS or when shortname option set and ext starts with a dot.
6232 * Then truncate what is after the '/', '\' or ':' to 8 characters for
6233 * MSDOS and 26 characters for AMIGA, a lot more for UNIX.
6234 */
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006235 for (ptr = retval + fnamelen; ptr > retval; mb_ptr_back(retval, ptr))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006236 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006237 if (*ext == '.'
Bram Moolenaare60acc12011-05-10 16:41:25 +02006238#ifdef USE_LONG_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00006239 && (!USE_LONG_FNAME || shortname)
Bram Moolenaare60acc12011-05-10 16:41:25 +02006240#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006241 && shortname
Bram Moolenaare60acc12011-05-10 16:41:25 +02006242#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006243 )
6244 if (*ptr == '.') /* replace '.' by '_' */
6245 *ptr = '_';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006246 if (vim_ispathsep(*ptr))
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006247 {
6248 ++ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006249 break;
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006250 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006251 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006252
6253 /* the file name has at most BASENAMELEN characters. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006254 if (STRLEN(ptr) > (unsigned)BASENAMELEN)
6255 ptr[BASENAMELEN] = '\0';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006256
6257 s = ptr + STRLEN(ptr);
6258
6259 /*
6260 * For 8.3 file names we may have to reduce the length.
6261 */
6262#ifdef USE_LONG_FNAME
6263 if (!USE_LONG_FNAME || shortname)
6264#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006265 if (shortname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006266#endif
6267 {
6268 /*
6269 * If there is no file name, or the file name ends in '/', and the
6270 * extension starts with '.', put a '_' before the dot, because just
6271 * ".ext" is invalid.
6272 */
6273 if (fname == NULL || *fname == NUL
6274 || vim_ispathsep(fname[STRLEN(fname) - 1]))
6275 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006276 if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006277 *s++ = '_';
6278 }
6279 /*
6280 * If the extension starts with '.', truncate the base name at 8
6281 * characters
6282 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006283 else if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006284 {
Bram Moolenaar78a15312009-05-15 19:33:18 +00006285 if ((size_t)(s - ptr) > (size_t)8)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006286 {
6287 s = ptr + 8;
6288 *s = '\0';
6289 }
6290 }
6291 /*
6292 * If the extension doesn't start with '.', and the file name
6293 * doesn't have an extension yet, append a '.'
6294 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006295 else if ((e = vim_strchr(ptr, '.')) == NULL)
6296 *s++ = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006297 /*
6298 * If the extension doesn't start with '.', and there already is an
Bram Moolenaar7263a772007-05-10 17:35:54 +00006299 * extension, it may need to be truncated
Bram Moolenaar071d4272004-06-13 20:20:40 +00006300 */
6301 else if ((int)STRLEN(e) + extlen > 4)
6302 s = e + 4 - extlen;
6303 }
Bram Moolenaare7fedb62015-12-31 19:07:19 +01006304#if defined(USE_LONG_FNAME) || defined(WIN3264)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006305 /*
6306 * If there is no file name, and the extension starts with '.', put a
6307 * '_' before the dot, because just ".ext" may be invalid if it's on a
6308 * FAT partition, and on HPFS it doesn't matter.
6309 */
6310 else if ((fname == NULL || *fname == NUL) && *ext == '.')
6311 *s++ = '_';
6312#endif
6313
6314 /*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006315 * Append the extension.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006316 * ext can start with '.' and cannot exceed 3 more characters.
6317 */
6318 STRCPY(s, ext);
6319
Bram Moolenaar071d4272004-06-13 20:20:40 +00006320 /*
6321 * Prepend the dot.
6322 */
Bram Moolenaare60acc12011-05-10 16:41:25 +02006323 if (prepend_dot && !shortname && *(e = gettail(retval)) != '.'
Bram Moolenaar071d4272004-06-13 20:20:40 +00006324#ifdef USE_LONG_FNAME
6325 && USE_LONG_FNAME
6326#endif
6327 )
6328 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006329 STRMOVE(e + 1, e);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006330 *e = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006331 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006332
6333 /*
6334 * Check that, after appending the extension, the file name is really
6335 * different.
6336 */
6337 if (fname != NULL && STRCMP(fname, retval) == 0)
6338 {
6339 /* we search for a character that can be replaced by '_' */
6340 while (--s >= ptr)
6341 {
6342 if (*s != '_')
6343 {
6344 *s = '_';
6345 break;
6346 }
6347 }
6348 if (s < ptr) /* fname was "________.<ext>", how tricky! */
6349 *ptr = 'v';
6350 }
6351 return retval;
6352}
6353
6354/*
6355 * Like fgets(), but if the file line is too long, it is truncated and the
6356 * rest of the line is thrown away. Returns TRUE for end-of-file.
6357 */
6358 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006359vim_fgets(char_u *buf, int size, FILE *fp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006360{
6361 char *eof;
6362#define FGETS_SIZE 200
6363 char tbuf[FGETS_SIZE];
6364
6365 buf[size - 2] = NUL;
6366#ifdef USE_CR
6367 eof = fgets_cr((char *)buf, size, fp);
6368#else
6369 eof = fgets((char *)buf, size, fp);
6370#endif
6371 if (buf[size - 2] != NUL && buf[size - 2] != '\n')
6372 {
6373 buf[size - 1] = NUL; /* Truncate the line */
6374
6375 /* Now throw away the rest of the line: */
6376 do
6377 {
6378 tbuf[FGETS_SIZE - 2] = NUL;
6379#ifdef USE_CR
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006380 ignoredp = fgets_cr((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006381#else
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006382 ignoredp = fgets((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006383#endif
6384 } while (tbuf[FGETS_SIZE - 2] != NUL && tbuf[FGETS_SIZE - 2] != '\n');
6385 }
6386 return (eof == NULL);
6387}
6388
6389#if defined(USE_CR) || defined(PROTO)
6390/*
6391 * Like vim_fgets(), but accept any line terminator: CR, CR-LF or LF.
6392 * Returns TRUE for end-of-file.
6393 * Only used for the Mac, because it's much slower than vim_fgets().
6394 */
6395 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006396tag_fgets(char_u *buf, int size, FILE *fp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006397{
6398 int i = 0;
6399 int c;
6400 int eof = FALSE;
6401
6402 for (;;)
6403 {
6404 c = fgetc(fp);
6405 if (c == EOF)
6406 {
6407 eof = TRUE;
6408 break;
6409 }
6410 if (c == '\r')
6411 {
6412 /* Always store a NL for end-of-line. */
6413 if (i < size - 1)
6414 buf[i++] = '\n';
6415 c = fgetc(fp);
6416 if (c != '\n') /* Macintosh format: single CR. */
6417 ungetc(c, fp);
6418 break;
6419 }
6420 if (i < size - 1)
6421 buf[i++] = c;
6422 if (c == '\n')
6423 break;
6424 }
6425 buf[i] = NUL;
6426 return eof;
6427}
6428#endif
6429
6430/*
6431 * rename() only works if both files are on the same file system, this
6432 * function will (attempts to?) copy the file across if rename fails -- webb
6433 * Return -1 for failure, 0 for success.
6434 */
6435 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006436vim_rename(char_u *from, char_u *to)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006437{
6438 int fd_in;
6439 int fd_out;
6440 int n;
6441 char *errmsg = NULL;
6442 char *buffer;
6443#ifdef AMIGA
6444 BPTR flock;
6445#endif
Bram Moolenaar8767f522016-07-01 17:17:39 +02006446 stat_T st;
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006447 long perm;
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006448#ifdef HAVE_ACL
6449 vim_acl_T acl; /* ACL from original file */
6450#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006451 int use_tmp_file = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006452
6453 /*
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006454 * When the names are identical, there is nothing to do. When they refer
6455 * to the same file (ignoring case and slash/backslash differences) but
6456 * the file name differs we need to go through a temp file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006457 */
6458 if (fnamecmp(from, to) == 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006459 {
Bram Moolenaar71afbfe2013-03-19 16:49:16 +01006460 if (p_fic && STRCMP(gettail(from), gettail(to)) != 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006461 use_tmp_file = TRUE;
6462 else
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006463 return 0;
6464 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006465
6466 /*
6467 * Fail if the "from" file doesn't exist. Avoids that "to" is deleted.
6468 */
6469 if (mch_stat((char *)from, &st) < 0)
6470 return -1;
6471
Bram Moolenaar3576da72008-12-30 15:15:57 +00006472#ifdef UNIX
6473 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02006474 stat_T st_to;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006475
6476 /* It's possible for the source and destination to be the same file.
6477 * This happens when "from" and "to" differ in case and are on a FAT32
6478 * filesystem. In that case go through a temp file name. */
6479 if (mch_stat((char *)to, &st_to) >= 0
6480 && st.st_dev == st_to.st_dev
6481 && st.st_ino == st_to.st_ino)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006482 use_tmp_file = TRUE;
6483 }
6484#endif
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02006485#ifdef WIN3264
6486 {
6487 BY_HANDLE_FILE_INFORMATION info1, info2;
6488
6489 /* It's possible for the source and destination to be the same file.
6490 * In that case go through a temp file name. This makes rename("foo",
6491 * "./foo") a no-op (in a complicated way). */
6492 if (win32_fileinfo(from, &info1) == FILEINFO_OK
6493 && win32_fileinfo(to, &info2) == FILEINFO_OK
6494 && info1.dwVolumeSerialNumber == info2.dwVolumeSerialNumber
6495 && info1.nFileIndexHigh == info2.nFileIndexHigh
6496 && info1.nFileIndexLow == info2.nFileIndexLow)
6497 use_tmp_file = TRUE;
6498 }
6499#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006500
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006501 if (use_tmp_file)
6502 {
6503 char tempname[MAXPATHL + 1];
6504
6505 /*
6506 * Find a name that doesn't exist and is in the same directory.
6507 * Rename "from" to "tempname" and then rename "tempname" to "to".
6508 */
6509 if (STRLEN(from) >= MAXPATHL - 5)
6510 return -1;
6511 STRCPY(tempname, from);
6512 for (n = 123; n < 99999; ++n)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006513 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006514 sprintf((char *)gettail((char_u *)tempname), "%d", n);
6515 if (mch_stat(tempname, &st) < 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006516 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006517 if (mch_rename((char *)from, tempname) == 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006518 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006519 if (mch_rename(tempname, (char *)to) == 0)
6520 return 0;
6521 /* Strange, the second step failed. Try moving the
6522 * file back and return failure. */
6523 mch_rename(tempname, (char *)from);
Bram Moolenaar3576da72008-12-30 15:15:57 +00006524 return -1;
6525 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006526 /* If it fails for one temp name it will most likely fail
6527 * for any temp name, give up. */
6528 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006529 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006530 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006531 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006532 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006533
Bram Moolenaar071d4272004-06-13 20:20:40 +00006534 /*
6535 * Delete the "to" file, this is required on some systems to make the
6536 * mch_rename() work, on other systems it makes sure that we don't have
6537 * two files when the mch_rename() fails.
6538 */
6539
6540#ifdef AMIGA
6541 /*
6542 * With MSDOS-compatible filesystems (crossdos, messydos) it is possible
6543 * that the name of the "to" file is the same as the "from" file, even
Bram Moolenaar7263a772007-05-10 17:35:54 +00006544 * though the names are different. To avoid the chance of accidentally
Bram Moolenaar071d4272004-06-13 20:20:40 +00006545 * deleting the "from" file (horror!) we lock it during the remove.
6546 *
6547 * When used for making a backup before writing the file: This should not
6548 * happen with ":w", because startscript() should detect this problem and
6549 * set buf->b_shortname, causing modname() to return a correct ".bak" file
6550 * name. This problem does exist with ":w filename", but then the
6551 * original file will be somewhere else so the backup isn't really
6552 * important. If autoscripting is off the rename may fail.
6553 */
6554 flock = Lock((UBYTE *)from, (long)ACCESS_READ);
6555#endif
6556 mch_remove(to);
6557#ifdef AMIGA
6558 if (flock)
6559 UnLock(flock);
6560#endif
6561
6562 /*
6563 * First try a normal rename, return if it works.
6564 */
6565 if (mch_rename((char *)from, (char *)to) == 0)
6566 return 0;
6567
6568 /*
6569 * Rename() failed, try copying the file.
6570 */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006571 perm = mch_getperm(from);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006572#ifdef HAVE_ACL
6573 /* For systems that support ACL: get the ACL from the original file. */
6574 acl = mch_get_acl(from);
6575#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006576 fd_in = mch_open((char *)from, O_RDONLY|O_EXTRA, 0);
6577 if (fd_in == -1)
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006578 {
6579#ifdef HAVE_ACL
6580 mch_free_acl(acl);
6581#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006582 return -1;
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006583 }
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006584
6585 /* Create the new file with same permissions as the original. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00006586 fd_out = mch_open((char *)to,
6587 O_CREAT|O_EXCL|O_WRONLY|O_EXTRA|O_NOFOLLOW, (int)perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006588 if (fd_out == -1)
6589 {
6590 close(fd_in);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006591#ifdef HAVE_ACL
6592 mch_free_acl(acl);
6593#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006594 return -1;
6595 }
6596
6597 buffer = (char *)alloc(BUFSIZE);
6598 if (buffer == NULL)
6599 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006600 close(fd_out);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006601 close(fd_in);
6602#ifdef HAVE_ACL
6603 mch_free_acl(acl);
6604#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006605 return -1;
6606 }
6607
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01006608 while ((n = read_eintr(fd_in, buffer, BUFSIZE)) > 0)
6609 if (write_eintr(fd_out, buffer, n) != n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006610 {
6611 errmsg = _("E208: Error writing to \"%s\"");
6612 break;
6613 }
6614
6615 vim_free(buffer);
6616 close(fd_in);
6617 if (close(fd_out) < 0)
6618 errmsg = _("E209: Error closing \"%s\"");
6619 if (n < 0)
6620 {
6621 errmsg = _("E210: Error reading \"%s\"");
6622 to = from;
6623 }
Bram Moolenaar7263a772007-05-10 17:35:54 +00006624#ifndef UNIX /* for Unix mch_open() already set the permission */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006625 mch_setperm(to, perm);
Bram Moolenaarc6039d82005-12-02 00:44:04 +00006626#endif
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006627#ifdef HAVE_ACL
6628 mch_set_acl(to, acl);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006629 mch_free_acl(acl);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006630#endif
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02006631#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaare8747442013-11-12 18:09:29 +01006632 mch_copy_sec(from, to);
Bram Moolenaar0671de32013-11-12 05:12:03 +01006633#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006634 if (errmsg != NULL)
6635 {
6636 EMSG2(errmsg, to);
6637 return -1;
6638 }
6639 mch_remove(from);
6640 return 0;
6641}
6642
6643static int already_warned = FALSE;
6644
6645/*
6646 * Check if any not hidden buffer has been changed.
6647 * Postpone the check if there are characters in the stuff buffer, a global
6648 * command is being executed, a mapping is being executed or an autocommand is
6649 * busy.
6650 * Returns TRUE if some message was written (screen should be redrawn and
6651 * cursor positioned).
6652 */
6653 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006654check_timestamps(
6655 int focus) /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006656{
6657 buf_T *buf;
6658 int didit = 0;
6659 int n;
6660
6661 /* Don't check timestamps while system() or another low-level function may
6662 * cause us to lose and gain focus. */
6663 if (no_check_timestamps > 0)
6664 return FALSE;
6665
6666 /* Avoid doing a check twice. The OK/Reload dialog can cause a focus
6667 * event and we would keep on checking if the file is steadily growing.
6668 * Do check again after typing something. */
6669 if (focus && did_check_timestamps)
6670 {
6671 need_check_timestamps = TRUE;
6672 return FALSE;
6673 }
6674
6675 if (!stuff_empty() || global_busy || !typebuf_typed()
6676#ifdef FEAT_AUTOCMD
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006677 || autocmd_busy || curbuf_lock > 0 || allbuf_lock > 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00006678#endif
6679 )
6680 need_check_timestamps = TRUE; /* check later */
6681 else
6682 {
6683 ++no_wait_return;
6684 did_check_timestamps = TRUE;
6685 already_warned = FALSE;
Bram Moolenaar29323592016-07-24 22:04:11 +02006686 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006687 {
6688 /* Only check buffers in a window. */
6689 if (buf->b_nwindows > 0)
6690 {
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006691 bufref_T bufref;
6692
6693 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006694 n = buf_check_timestamp(buf, focus);
6695 if (didit < n)
6696 didit = n;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006697 if (n > 0 && !bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006698 {
6699 /* Autocommands have removed the buffer, start at the
6700 * first one again. */
6701 buf = firstbuf;
6702 continue;
6703 }
6704 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006705 }
6706 --no_wait_return;
6707 need_check_timestamps = FALSE;
6708 if (need_wait_return && didit == 2)
6709 {
6710 /* make sure msg isn't overwritten */
6711 msg_puts((char_u *)"\n");
6712 out_flush();
6713 }
6714 }
6715 return didit;
6716}
6717
6718/*
6719 * Move all the lines from buffer "frombuf" to buffer "tobuf".
6720 * Return OK or FAIL. When FAIL "tobuf" is incomplete and/or "frombuf" is not
6721 * empty.
6722 */
6723 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006724move_lines(buf_T *frombuf, buf_T *tobuf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006725{
6726 buf_T *tbuf = curbuf;
6727 int retval = OK;
6728 linenr_T lnum;
6729 char_u *p;
6730
6731 /* Copy the lines in "frombuf" to "tobuf". */
6732 curbuf = tobuf;
6733 for (lnum = 1; lnum <= frombuf->b_ml.ml_line_count; ++lnum)
6734 {
6735 p = vim_strsave(ml_get_buf(frombuf, lnum, FALSE));
6736 if (p == NULL || ml_append(lnum - 1, p, 0, FALSE) == FAIL)
6737 {
6738 vim_free(p);
6739 retval = FAIL;
6740 break;
6741 }
6742 vim_free(p);
6743 }
6744
6745 /* Delete all the lines in "frombuf". */
6746 if (retval != FAIL)
6747 {
6748 curbuf = frombuf;
Bram Moolenaar9460b9d2007-01-09 14:37:01 +00006749 for (lnum = curbuf->b_ml.ml_line_count; lnum > 0; --lnum)
6750 if (ml_delete(lnum, FALSE) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006751 {
6752 /* Oops! We could try putting back the saved lines, but that
6753 * might fail again... */
6754 retval = FAIL;
6755 break;
6756 }
6757 }
6758
6759 curbuf = tbuf;
6760 return retval;
6761}
6762
6763/*
6764 * Check if buffer "buf" has been changed.
6765 * Also check if the file for a new buffer unexpectedly appeared.
6766 * return 1 if a changed buffer was found.
6767 * return 2 if a message has been displayed.
6768 * return 0 otherwise.
6769 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006770 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006771buf_check_timestamp(
6772 buf_T *buf,
6773 int focus UNUSED) /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006774{
Bram Moolenaar8767f522016-07-01 17:17:39 +02006775 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006776 int stat_res;
6777 int retval = 0;
6778 char_u *path;
6779 char_u *tbuf;
6780 char *mesg = NULL;
Bram Moolenaar44ecf652005-03-07 23:09:59 +00006781 char *mesg2 = "";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006782 int helpmesg = FALSE;
6783 int reload = FALSE;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006784 char *reason;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006785#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6786 int can_reload = FALSE;
6787#endif
Bram Moolenaar8767f522016-07-01 17:17:39 +02006788 off_T orig_size = buf->b_orig_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006789 int orig_mode = buf->b_orig_mode;
6790#ifdef FEAT_GUI
6791 int save_mouse_correct = need_mouse_correct;
6792#endif
6793#ifdef FEAT_AUTOCMD
6794 static int busy = FALSE;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006795 int n;
6796 char_u *s;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006797 bufref_T bufref;
6798
6799 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006800#endif
6801
6802 /* If there is no file name, the buffer is not loaded, 'buftype' is
6803 * set, we are in the middle of a save or being called recursively: ignore
6804 * this buffer. */
6805 if (buf->b_ffname == NULL
6806 || buf->b_ml.ml_mfp == NULL
6807#if defined(FEAT_QUICKFIX)
6808 || *buf->b_p_bt != NUL
6809#endif
6810 || buf->b_saving
6811#ifdef FEAT_AUTOCMD
6812 || busy
6813#endif
Bram Moolenaar009b2592004-10-24 19:18:58 +00006814#ifdef FEAT_NETBEANS_INTG
6815 || isNetbeansBuffer(buf)
6816#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006817 )
6818 return 0;
6819
6820 if ( !(buf->b_flags & BF_NOTEDITED)
6821 && buf->b_mtime != 0
6822 && ((stat_res = mch_stat((char *)buf->b_ffname, &st)) < 0
6823 || time_differs((long)st.st_mtime, buf->b_mtime)
Bram Moolenaara7611f62014-05-02 15:46:14 +02006824 || st.st_size != buf->b_orig_size
Bram Moolenaar071d4272004-06-13 20:20:40 +00006825#ifdef HAVE_ST_MODE
6826 || (int)st.st_mode != buf->b_orig_mode
6827#else
6828 || mch_getperm(buf->b_ffname) != buf->b_orig_mode
6829#endif
6830 ))
6831 {
6832 retval = 1;
6833
Bram Moolenaar316059c2006-01-14 21:18:42 +00006834 /* set b_mtime to stop further warnings (e.g., when executing
6835 * FileChangedShell autocmd) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006836 if (stat_res < 0)
6837 {
6838 buf->b_mtime = 0;
6839 buf->b_orig_size = 0;
6840 buf->b_orig_mode = 0;
6841 }
6842 else
6843 buf_store_time(buf, &st, buf->b_ffname);
6844
6845 /* Don't do anything for a directory. Might contain the file
6846 * explorer. */
6847 if (mch_isdir(buf->b_fname))
6848 ;
6849
6850 /*
6851 * If 'autoread' is set, the buffer has no changes and the file still
6852 * exists, reload the buffer. Use the buffer-local option value if it
6853 * was set, the global option value otherwise.
6854 */
6855 else if ((buf->b_p_ar >= 0 ? buf->b_p_ar : p_ar)
6856 && !bufIsChanged(buf) && stat_res >= 0)
6857 reload = TRUE;
6858 else
6859 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006860 if (stat_res < 0)
6861 reason = "deleted";
6862 else if (bufIsChanged(buf))
6863 reason = "conflict";
6864 else if (orig_size != buf->b_orig_size || buf_contents_changed(buf))
6865 reason = "changed";
6866 else if (orig_mode != buf->b_orig_mode)
6867 reason = "mode";
6868 else
6869 reason = "time";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006870
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006871#ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006872 /*
6873 * Only give the warning if there are no FileChangedShell
6874 * autocommands.
6875 * Avoid being called recursively by setting "busy".
6876 */
6877 busy = TRUE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00006878# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006879 set_vim_var_string(VV_FCS_REASON, (char_u *)reason, -1);
6880 set_vim_var_string(VV_FCS_CHOICE, (char_u *)"", -1);
Bram Moolenaar1e015462005-09-25 22:16:38 +00006881# endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006882 ++allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006883 n = apply_autocmds(EVENT_FILECHANGEDSHELL,
6884 buf->b_fname, buf->b_fname, FALSE, buf);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006885 --allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006886 busy = FALSE;
6887 if (n)
6888 {
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006889 if (!bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006890 EMSG(_("E246: FileChangedShell autocommand deleted buffer"));
Bram Moolenaar1e015462005-09-25 22:16:38 +00006891# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006892 s = get_vim_var_str(VV_FCS_CHOICE);
6893 if (STRCMP(s, "reload") == 0 && *reason != 'd')
6894 reload = TRUE;
6895 else if (STRCMP(s, "ask") == 0)
6896 n = FALSE;
6897 else
Bram Moolenaar1e015462005-09-25 22:16:38 +00006898# endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006899 return 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006900 }
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006901 if (!n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006902#endif
6903 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006904 if (*reason == 'd')
6905 mesg = _("E211: File \"%s\" no longer available");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006906 else
6907 {
6908 helpmesg = TRUE;
6909#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6910 can_reload = TRUE;
6911#endif
6912 /*
6913 * Check if the file contents really changed to avoid
6914 * giving a warning when only the timestamp was set (e.g.,
6915 * checked out of CVS). Always warn when the buffer was
6916 * changed.
6917 */
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006918 if (reason[2] == 'n')
6919 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006920 mesg = _("W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006921 mesg2 = _("See \":help W12\" for more info.");
6922 }
6923 else if (reason[1] == 'h')
6924 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006925 mesg = _("W11: Warning: File \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006926 mesg2 = _("See \":help W11\" for more info.");
6927 }
6928 else if (*reason == 'm')
6929 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006930 mesg = _("W16: Warning: Mode of file \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006931 mesg2 = _("See \":help W16\" for more info.");
6932 }
Bram Moolenaar85388b52009-06-24 09:58:32 +00006933 else
6934 /* Only timestamp changed, store it to avoid a warning
6935 * in check_mtime() later. */
6936 buf->b_mtime_read = buf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006937 }
6938 }
6939 }
6940
6941 }
6942 else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W)
6943 && vim_fexists(buf->b_ffname))
6944 {
6945 retval = 1;
6946 mesg = _("W13: Warning: File \"%s\" has been created after editing started");
6947 buf->b_flags |= BF_NEW_W;
6948#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6949 can_reload = TRUE;
6950#endif
6951 }
6952
6953 if (mesg != NULL)
6954 {
6955 path = home_replace_save(buf, buf->b_fname);
6956 if (path != NULL)
6957 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006958 if (!helpmesg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006959 mesg2 = "";
6960 tbuf = alloc((unsigned)(STRLEN(path) + STRLEN(mesg)
6961 + STRLEN(mesg2) + 2));
6962 sprintf((char *)tbuf, mesg, path);
Bram Moolenaar496c5262009-03-18 14:42:00 +00006963#ifdef FEAT_EVAL
6964 /* Set warningmsg here, before the unimportant and output-specific
6965 * mesg2 has been appended. */
6966 set_vim_var_string(VV_WARNINGMSG, tbuf, -1);
6967#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006968#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6969 if (can_reload)
6970 {
6971 if (*mesg2 != NUL)
6972 {
6973 STRCAT(tbuf, "\n");
6974 STRCAT(tbuf, mesg2);
6975 }
6976 if (do_dialog(VIM_WARNING, (char_u *)_("Warning"), tbuf,
Bram Moolenaard2c340a2011-01-17 20:08:11 +01006977 (char_u *)_("&OK\n&Load File"), 1, NULL, TRUE) == 2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006978 reload = TRUE;
6979 }
6980 else
6981#endif
6982 if (State > NORMAL_BUSY || (State & CMDLINE) || already_warned)
6983 {
6984 if (*mesg2 != NUL)
6985 {
6986 STRCAT(tbuf, "; ");
6987 STRCAT(tbuf, mesg2);
6988 }
6989 EMSG(tbuf);
6990 retval = 2;
6991 }
6992 else
6993 {
Bram Moolenaared203462004-06-16 11:19:22 +00006994# ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006995 if (!autocmd_busy)
Bram Moolenaared203462004-06-16 11:19:22 +00006996# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006997 {
6998 msg_start();
6999 msg_puts_attr(tbuf, hl_attr(HLF_E) + MSG_HIST);
7000 if (*mesg2 != NUL)
7001 msg_puts_attr((char_u *)mesg2,
7002 hl_attr(HLF_W) + MSG_HIST);
7003 msg_clr_eos();
7004 (void)msg_end();
7005 if (emsg_silent == 0)
7006 {
7007 out_flush();
Bram Moolenaared203462004-06-16 11:19:22 +00007008# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00007009 if (!focus)
Bram Moolenaared203462004-06-16 11:19:22 +00007010# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007011 /* give the user some time to think about it */
7012 ui_delay(1000L, TRUE);
7013
7014 /* don't redraw and erase the message */
7015 redraw_cmdline = FALSE;
7016 }
7017 }
7018 already_warned = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007019 }
7020
7021 vim_free(path);
7022 vim_free(tbuf);
7023 }
7024 }
7025
7026 if (reload)
Bram Moolenaar465748e2012-08-29 18:50:54 +02007027 {
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007028 /* Reload the buffer. */
Bram Moolenaar316059c2006-01-14 21:18:42 +00007029 buf_reload(buf, orig_mode);
Bram Moolenaar465748e2012-08-29 18:50:54 +02007030#ifdef FEAT_PERSISTENT_UNDO
7031 if (buf->b_p_udf && buf->b_ffname != NULL)
7032 {
7033 char_u hash[UNDO_HASH_SIZE];
7034 buf_T *save_curbuf = curbuf;
7035
7036 /* Any existing undo file is unusable, write it now. */
7037 curbuf = buf;
7038 u_compute_hash(hash);
7039 u_write_undo(NULL, FALSE, buf, hash);
7040 curbuf = save_curbuf;
7041 }
7042#endif
7043 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007044
Bram Moolenaar56718732006-03-15 22:53:57 +00007045#ifdef FEAT_AUTOCMD
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00007046 /* Trigger FileChangedShell when the file was changed in any way. */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007047 if (bufref_valid(&bufref) && retval != 0)
Bram Moolenaar56718732006-03-15 22:53:57 +00007048 (void)apply_autocmds(EVENT_FILECHANGEDSHELLPOST,
7049 buf->b_fname, buf->b_fname, FALSE, buf);
7050#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007051#ifdef FEAT_GUI
7052 /* restore this in case an autocommand has set it; it would break
7053 * 'mousefocus' */
7054 need_mouse_correct = save_mouse_correct;
7055#endif
7056
7057 return retval;
7058}
7059
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007060/*
7061 * Reload a buffer that is already loaded.
7062 * Used when the file was changed outside of Vim.
Bram Moolenaar316059c2006-01-14 21:18:42 +00007063 * "orig_mode" is buf->b_orig_mode before the need for reloading was detected.
7064 * buf->b_orig_mode may have been reset already.
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007065 */
7066 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007067buf_reload(buf_T *buf, int orig_mode)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007068{
7069 exarg_T ea;
7070 pos_T old_cursor;
7071 linenr_T old_topline;
7072 int old_ro = buf->b_p_ro;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007073 buf_T *savebuf;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007074 bufref_T bufref;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007075 int saved = OK;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007076 aco_save_T aco;
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007077 int flags = READ_NEW;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007078
7079 /* set curwin/curbuf for "buf" and save some things */
7080 aucmd_prepbuf(&aco, buf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007081
7082 /* We only want to read the text from the file, not reset the syntax
7083 * highlighting, clear marks, diff status, etc. Force the fileformat
7084 * and encoding to be the same. */
7085 if (prep_exarg(&ea, buf) == OK)
7086 {
7087 old_cursor = curwin->w_cursor;
7088 old_topline = curwin->w_topline;
7089
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007090 if (p_ur < 0 || curbuf->b_ml.ml_line_count <= p_ur)
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007091 {
7092 /* Save all the text, so that the reload can be undone.
7093 * Sync first so that this is a separate undo-able action. */
7094 u_sync(FALSE);
7095 saved = u_savecommon(0, curbuf->b_ml.ml_line_count + 1, 0, TRUE);
7096 flags |= READ_KEEP_UNDO;
7097 }
7098
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007099 /*
7100 * To behave like when a new file is edited (matters for
7101 * BufReadPost autocommands) we first need to delete the current
7102 * buffer contents. But if reading the file fails we should keep
7103 * the old contents. Can't use memory only, the file might be
7104 * too big. Use a hidden buffer to move the buffer contents to.
7105 */
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007106 if (bufempty() || saved == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007107 savebuf = NULL;
7108 else
7109 {
7110 /* Allocate a buffer without putting it in the buffer list. */
7111 savebuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007112 set_bufref(&bufref, savebuf);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007113 if (savebuf != NULL && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007114 {
7115 /* Open the memline. */
7116 curbuf = savebuf;
7117 curwin->w_buffer = savebuf;
Bram Moolenaar4770d092006-01-12 23:22:24 +00007118 saved = ml_open(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007119 curbuf = buf;
7120 curwin->w_buffer = buf;
7121 }
Bram Moolenaar8424a622006-04-19 21:23:36 +00007122 if (savebuf == NULL || saved == FAIL || buf != curbuf
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007123 || move_lines(buf, savebuf) == FAIL)
7124 {
7125 EMSG2(_("E462: Could not prepare for reloading \"%s\""),
7126 buf->b_fname);
7127 saved = FAIL;
7128 }
7129 }
7130
7131 if (saved == OK)
7132 {
7133 curbuf->b_flags |= BF_CHECK_RO; /* check for RO again */
7134#ifdef FEAT_AUTOCMD
7135 keep_filetype = TRUE; /* don't detect 'filetype' */
7136#endif
7137 if (readfile(buf->b_ffname, buf->b_fname, (linenr_T)0,
7138 (linenr_T)0,
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007139 (linenr_T)MAXLNUM, &ea, flags) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007140 {
7141#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
7142 if (!aborting())
7143#endif
7144 EMSG2(_("E321: Could not reload \"%s\""), buf->b_fname);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007145 if (savebuf != NULL && bufref_valid(&bufref) && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007146 {
7147 /* Put the text back from the save buffer. First
7148 * delete any lines that readfile() added. */
7149 while (!bufempty())
Bram Moolenaar8424a622006-04-19 21:23:36 +00007150 if (ml_delete(buf->b_ml.ml_line_count, FALSE) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007151 break;
7152 (void)move_lines(savebuf, buf);
7153 }
7154 }
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007155 else if (buf == curbuf) /* "buf" still valid */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007156 {
7157 /* Mark the buffer as unmodified and free undo info. */
7158 unchanged(buf, TRUE);
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007159 if ((flags & READ_KEEP_UNDO) == 0)
7160 {
7161 u_blockfree(buf);
7162 u_clearall(buf);
7163 }
7164 else
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007165 {
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007166 /* Mark all undo states as changed. */
7167 u_unchanged(curbuf);
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007168 }
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007169 }
7170 }
7171 vim_free(ea.cmd);
7172
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007173 if (savebuf != NULL && bufref_valid(&bufref))
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007174 wipe_buffer(savebuf, FALSE);
7175
7176#ifdef FEAT_DIFF
7177 /* Invalidate diff info if necessary. */
Bram Moolenaar8424a622006-04-19 21:23:36 +00007178 diff_invalidate(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007179#endif
7180
7181 /* Restore the topline and cursor position and check it (lines may
7182 * have been removed). */
7183 if (old_topline > curbuf->b_ml.ml_line_count)
7184 curwin->w_topline = curbuf->b_ml.ml_line_count;
7185 else
7186 curwin->w_topline = old_topline;
7187 curwin->w_cursor = old_cursor;
7188 check_cursor();
7189 update_topline();
7190#ifdef FEAT_AUTOCMD
7191 keep_filetype = FALSE;
7192#endif
7193#ifdef FEAT_FOLDING
7194 {
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007195 win_T *wp;
7196 tabpage_T *tp;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007197
7198 /* Update folds unless they are defined manually. */
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007199 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007200 if (wp->w_buffer == curwin->w_buffer
7201 && !foldmethodIsManual(wp))
7202 foldUpdateAll(wp);
7203 }
7204#endif
7205 /* If the mode didn't change and 'readonly' was set, keep the old
7206 * value; the user probably used the ":view" command. But don't
7207 * reset it, might have had a read error. */
7208 if (orig_mode == curbuf->b_orig_mode)
7209 curbuf->b_p_ro |= old_ro;
Bram Moolenaar52f85b72013-01-30 14:13:56 +01007210
7211 /* Modelines must override settings done by autocommands. */
7212 do_modelines(0);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007213 }
7214
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007215 /* restore curwin/curbuf and a few other things */
7216 aucmd_restbuf(&aco);
7217 /* Careful: autocommands may have made "buf" invalid! */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007218}
7219
Bram Moolenaar071d4272004-06-13 20:20:40 +00007220 void
Bram Moolenaar8767f522016-07-01 17:17:39 +02007221buf_store_time(buf_T *buf, stat_T *st, char_u *fname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007222{
7223 buf->b_mtime = (long)st->st_mtime;
Bram Moolenaar914703b2010-05-31 21:59:46 +02007224 buf->b_orig_size = st->st_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007225#ifdef HAVE_ST_MODE
7226 buf->b_orig_mode = (int)st->st_mode;
7227#else
7228 buf->b_orig_mode = mch_getperm(fname);
7229#endif
7230}
7231
7232/*
7233 * Adjust the line with missing eol, used for the next write.
7234 * Used for do_filter(), when the input lines for the filter are deleted.
7235 */
7236 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007237write_lnum_adjust(linenr_T offset)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007238{
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01007239 if (curbuf->b_no_eol_lnum != 0) /* only if there is a missing eol */
7240 curbuf->b_no_eol_lnum += offset;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007241}
7242
Bram Moolenaarda440d22016-01-16 21:27:23 +01007243#if defined(TEMPDIRNAMES) || defined(FEAT_EVAL) || defined(PROTO)
7244/*
7245 * Delete "name" and everything in it, recursively.
7246 * return 0 for succes, -1 if some file was not deleted.
7247 */
7248 int
7249delete_recursive(char_u *name)
7250{
7251 int result = 0;
7252 char_u **files;
7253 int file_count;
7254 int i;
7255 char_u *exp;
7256
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007257 /* A symbolic link to a directory itself is deleted, not the directory it
7258 * points to. */
7259 if (
Bram Moolenaar203258c2016-01-17 22:15:16 +01007260# if defined(UNIX) || defined(WIN32)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007261 mch_isrealdir(name)
Bram Moolenaar203258c2016-01-17 22:15:16 +01007262# else
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007263 mch_isdir(name)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007264# endif
7265 )
Bram Moolenaarda440d22016-01-16 21:27:23 +01007266 {
7267 vim_snprintf((char *)NameBuff, MAXPATHL, "%s/*", name);
7268 exp = vim_strsave(NameBuff);
7269 if (exp == NULL)
7270 return -1;
7271 if (gen_expand_wildcards(1, &exp, &file_count, &files,
Bram Moolenaar336bd622016-01-17 18:23:58 +01007272 EW_DIR|EW_FILE|EW_SILENT|EW_ALLLINKS|EW_DODOT|EW_EMPTYOK) == OK)
Bram Moolenaarda440d22016-01-16 21:27:23 +01007273 {
7274 for (i = 0; i < file_count; ++i)
7275 if (delete_recursive(files[i]) != 0)
7276 result = -1;
7277 FreeWild(file_count, files);
7278 }
7279 else
7280 result = -1;
7281 vim_free(exp);
7282 (void)mch_rmdir(name);
7283 }
7284 else
7285 result = mch_remove(name) == 0 ? 0 : -1;
7286
7287 return result;
7288}
7289#endif
7290
Bram Moolenaar071d4272004-06-13 20:20:40 +00007291#if defined(TEMPDIRNAMES) || defined(PROTO)
7292static long temp_count = 0; /* Temp filename counter. */
7293
7294/*
7295 * Delete the temp directory and all files it contains.
7296 */
7297 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007298vim_deltempdir(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007299{
Bram Moolenaar071d4272004-06-13 20:20:40 +00007300 if (vim_tempdir != NULL)
7301 {
Bram Moolenaarda440d22016-01-16 21:27:23 +01007302 /* remove the trailing path separator */
7303 gettail(vim_tempdir)[-1] = NUL;
7304 delete_recursive(vim_tempdir);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007305 vim_free(vim_tempdir);
7306 vim_tempdir = NULL;
7307 }
7308}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007309
7310/*
Bram Moolenaareaf03392009-11-17 11:08:52 +00007311 * Directory "tempdir" was created. Expand this name to a full path and put
7312 * it in "vim_tempdir". This avoids that using ":cd" would confuse us.
7313 * "tempdir" must be no longer than MAXPATHL.
7314 */
7315 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007316vim_settempdir(char_u *tempdir)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007317{
7318 char_u *buf;
7319
7320 buf = alloc((unsigned)MAXPATHL + 2);
7321 if (buf != NULL)
7322 {
7323 if (vim_FullName(tempdir, buf, MAXPATHL, FALSE) == FAIL)
7324 STRCPY(buf, tempdir);
Bram Moolenaara06ecab2016-07-16 14:47:36 +02007325 add_pathsep(buf);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007326 vim_tempdir = vim_strsave(buf);
7327 vim_free(buf);
7328 }
7329}
Bram Moolenaar4592dee2009-11-18 19:11:58 +00007330#endif
Bram Moolenaareaf03392009-11-17 11:08:52 +00007331
7332/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007333 * vim_tempname(): Return a unique name that can be used for a temp file.
7334 *
Bram Moolenaar76ae22f2016-06-13 20:00:29 +02007335 * The temp file is NOT guaranteed to be created. If "keep" is FALSE it is
7336 * guaranteed to NOT be created.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007337 *
7338 * The returned pointer is to allocated memory.
7339 * The returned pointer is NULL if no valid name was found.
7340 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007341 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007342vim_tempname(
7343 int extra_char UNUSED, /* char to use in the name instead of '?' */
7344 int keep UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007345{
7346#ifdef USE_TMPNAM
7347 char_u itmp[L_tmpnam]; /* use tmpnam() */
7348#else
7349 char_u itmp[TEMPNAMELEN];
7350#endif
7351
7352#ifdef TEMPDIRNAMES
7353 static char *(tempdirs[]) = {TEMPDIRNAMES};
7354 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007355# ifndef EEXIST
Bram Moolenaar8767f522016-07-01 17:17:39 +02007356 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007357# endif
7358
7359 /*
7360 * This will create a directory for private use by this instance of Vim.
7361 * This is done once, and the same directory is used for all temp files.
7362 * This method avoids security problems because of symlink attacks et al.
7363 * It's also a bit faster, because we only need to check for an existing
7364 * file when creating the directory and not for each temp file.
7365 */
7366 if (vim_tempdir == NULL)
7367 {
7368 /*
7369 * Try the entries in TEMPDIRNAMES to create the temp directory.
7370 */
Bram Moolenaar78a15312009-05-15 19:33:18 +00007371 for (i = 0; i < (int)(sizeof(tempdirs) / sizeof(char *)); ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007372 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007373# ifndef HAVE_MKDTEMP
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007374 size_t itmplen;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007375 long nr;
7376 long off;
7377# endif
7378
Bram Moolenaare1a61992015-12-03 21:02:27 +01007379 /* Expand $TMP, leave room for "/v1100000/999999999".
7380 * Skip the directory check if the expansion fails. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007381 expand_env((char_u *)tempdirs[i], itmp, TEMPNAMELEN - 20);
Bram Moolenaare1a61992015-12-03 21:02:27 +01007382 if (itmp[0] != '$' && mch_isdir(itmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007383 {
Bram Moolenaare1a61992015-12-03 21:02:27 +01007384 /* directory exists */
Bram Moolenaara06ecab2016-07-16 14:47:36 +02007385 add_pathsep(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007386
Bram Moolenaareaf03392009-11-17 11:08:52 +00007387# ifdef HAVE_MKDTEMP
Bram Moolenaar35d88f42016-06-04 14:52:00 +02007388 {
7389# if defined(UNIX) || defined(VMS)
7390 /* Make sure the umask doesn't remove the executable bit.
7391 * "repl" has been reported to use "177". */
7392 mode_t umask_save = umask(077);
7393# endif
7394 /* Leave room for filename */
7395 STRCAT(itmp, "vXXXXXX");
7396 if (mkdtemp((char *)itmp) != NULL)
7397 vim_settempdir(itmp);
7398# if defined(UNIX) || defined(VMS)
7399 (void)umask(umask_save);
7400# endif
7401 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007402# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007403 /* Get an arbitrary number of up to 6 digits. When it's
7404 * unlikely that it already exists it will be faster,
7405 * otherwise it doesn't matter. The use of mkdir() avoids any
7406 * security problems because of the predictable number. */
7407 nr = (mch_get_pid() + (long)time(NULL)) % 1000000L;
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007408 itmplen = STRLEN(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007409
7410 /* Try up to 10000 different values until we find a name that
7411 * doesn't exist. */
7412 for (off = 0; off < 10000L; ++off)
7413 {
7414 int r;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007415# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007416 mode_t umask_save;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007417# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007418
Bram Moolenaareaf03392009-11-17 11:08:52 +00007419 sprintf((char *)itmp + itmplen, "v%ld", nr + off);
7420# ifndef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007421 /* If mkdir() does not set errno to EEXIST, check for
7422 * existing file here. There is a race condition then,
7423 * although it's fail-safe. */
7424 if (mch_stat((char *)itmp, &st) >= 0)
7425 continue;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007426# endif
7427# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007428 /* Make sure the umask doesn't remove the executable bit.
7429 * "repl" has been reported to use "177". */
7430 umask_save = umask(077);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007431# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007432 r = vim_mkdir(itmp, 0700);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007433# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007434 (void)umask(umask_save);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007435# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007436 if (r == 0)
7437 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007438 vim_settempdir(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007439 break;
7440 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007441# ifdef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007442 /* If the mkdir() didn't fail because the file/dir exists,
7443 * we probably can't create any dir here, try another
7444 * place. */
7445 if (errno != EEXIST)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007446# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007447 break;
7448 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007449# endif /* HAVE_MKDTEMP */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007450 if (vim_tempdir != NULL)
7451 break;
7452 }
7453 }
7454 }
7455
7456 if (vim_tempdir != NULL)
7457 {
7458 /* There is no need to check if the file exists, because we own the
7459 * directory and nobody else creates a file in it. */
7460 sprintf((char *)itmp, "%s%ld", vim_tempdir, temp_count++);
7461 return vim_strsave(itmp);
7462 }
7463
7464 return NULL;
7465
7466#else /* TEMPDIRNAMES */
7467
7468# ifdef WIN3264
7469 char szTempFile[_MAX_PATH + 1];
7470 char buf4[4];
7471 char_u *retval;
7472 char_u *p;
7473
7474 STRCPY(itmp, "");
7475 if (GetTempPath(_MAX_PATH, szTempFile) == 0)
Bram Moolenaarb1891912011-02-09 14:47:03 +01007476 {
7477 szTempFile[0] = '.'; /* GetTempPath() failed, use current dir */
7478 szTempFile[1] = NUL;
7479 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007480 strcpy(buf4, "VIM");
7481 buf4[2] = extra_char; /* make it "VIa", "VIb", etc. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007482 if (GetTempFileName(szTempFile, buf4, 0, (LPSTR)itmp) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007483 return NULL;
Bram Moolenaare5c421c2015-03-31 13:33:08 +02007484 if (!keep)
7485 /* GetTempFileName() will create the file, we don't want that */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007486 (void)DeleteFile((LPSTR)itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007487
7488 /* Backslashes in a temp file name cause problems when filtering with
7489 * "sh". NOTE: This also checks 'shellcmdflag' to help those people who
7490 * didn't set 'shellslash'. */
7491 retval = vim_strsave(itmp);
7492 if (*p_shcf == '-' || p_ssl)
7493 for (p = retval; *p; ++p)
7494 if (*p == '\\')
7495 *p = '/';
7496 return retval;
7497
7498# else /* WIN3264 */
7499
7500# ifdef USE_TMPNAM
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007501 char_u *p;
7502
Bram Moolenaar071d4272004-06-13 20:20:40 +00007503 /* tmpnam() will make its own name */
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007504 p = tmpnam((char *)itmp);
7505 if (p == NULL || *p == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007506 return NULL;
7507# else
7508 char_u *p;
7509
7510# ifdef VMS_TEMPNAM
7511 /* mktemp() is not working on VMS. It seems to be
7512 * a do-nothing function. Therefore we use tempnam().
7513 */
7514 sprintf((char *)itmp, "VIM%c", extra_char);
7515 p = (char_u *)tempnam("tmp:", (char *)itmp);
7516 if (p != NULL)
7517 {
Bram Moolenaar206f0112014-03-12 16:51:55 +01007518 /* VMS will use '.LIS' if we don't explicitly specify an extension,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007519 * and VIM will then be unable to find the file later */
7520 STRCPY(itmp, p);
7521 STRCAT(itmp, ".txt");
7522 free(p);
7523 }
7524 else
7525 return NULL;
7526# else
7527 STRCPY(itmp, TEMPNAME);
7528 if ((p = vim_strchr(itmp, '?')) != NULL)
7529 *p = extra_char;
7530 if (mktemp((char *)itmp) == NULL)
7531 return NULL;
7532# endif
7533# endif
7534
7535 return vim_strsave(itmp);
7536# endif /* WIN3264 */
7537#endif /* TEMPDIRNAMES */
7538}
7539
7540#if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
7541/*
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02007542 * Convert all backslashes in fname to forward slashes in-place, unless when
7543 * it looks like a URL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007544 */
7545 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007546forward_slash(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007547{
7548 char_u *p;
7549
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02007550 if (path_with_url(fname))
7551 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007552 for (p = fname; *p != NUL; ++p)
7553# ifdef FEAT_MBYTE
7554 /* The Big5 encoding can have '\' in the trail byte. */
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00007555 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007556 ++p;
7557 else
7558# endif
7559 if (*p == '\\')
7560 *p = '/';
7561}
7562#endif
7563
7564
7565/*
7566 * Code for automatic commands.
7567 *
7568 * Only included when "FEAT_AUTOCMD" has been defined.
7569 */
7570
7571#if defined(FEAT_AUTOCMD) || defined(PROTO)
7572
7573/*
7574 * The autocommands are stored in a list for each event.
7575 * Autocommands for the same pattern, that are consecutive, are joined
7576 * together, to avoid having to match the pattern too often.
7577 * The result is an array of Autopat lists, which point to AutoCmd lists:
7578 *
7579 * first_autopat[0] --> Autopat.next --> Autopat.next --> NULL
7580 * Autopat.cmds Autopat.cmds
7581 * | |
7582 * V V
7583 * AutoCmd.next AutoCmd.next
7584 * | |
7585 * V V
7586 * AutoCmd.next NULL
7587 * |
7588 * V
7589 * NULL
7590 *
7591 * first_autopat[1] --> Autopat.next --> NULL
7592 * Autopat.cmds
7593 * |
7594 * V
7595 * AutoCmd.next
7596 * |
7597 * V
7598 * NULL
7599 * etc.
7600 *
7601 * The order of AutoCmds is important, this is the order in which they were
7602 * defined and will have to be executed.
7603 */
7604typedef struct AutoCmd
7605{
7606 char_u *cmd; /* The command to be executed (NULL
7607 when command has been removed) */
7608 char nested; /* If autocommands nest here */
7609 char last; /* last command in list */
7610#ifdef FEAT_EVAL
7611 scid_T scriptID; /* script ID where defined */
7612#endif
7613 struct AutoCmd *next; /* Next AutoCmd in list */
7614} AutoCmd;
7615
7616typedef struct AutoPat
7617{
Bram Moolenaar071d4272004-06-13 20:20:40 +00007618 char_u *pat; /* pattern as typed (NULL when pattern
7619 has been removed) */
Bram Moolenaar748bf032005-02-02 23:04:36 +00007620 regprog_T *reg_prog; /* compiled regprog for pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007621 AutoCmd *cmds; /* list of commands to do */
7622 struct AutoPat *next; /* next AutoPat in AutoPat list */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007623 int group; /* group ID */
7624 int patlen; /* strlen() of pat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007625 int buflocal_nr; /* !=0 for buffer-local AutoPat */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007626 char allow_dirs; /* Pattern may match whole path */
7627 char last; /* last pattern for apply_autocmds() */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007628} AutoPat;
7629
7630static struct event_name
7631{
7632 char *name; /* event name */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007633 event_T event; /* event number */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007634} event_names[] =
7635{
7636 {"BufAdd", EVENT_BUFADD},
7637 {"BufCreate", EVENT_BUFADD},
7638 {"BufDelete", EVENT_BUFDELETE},
7639 {"BufEnter", EVENT_BUFENTER},
7640 {"BufFilePost", EVENT_BUFFILEPOST},
7641 {"BufFilePre", EVENT_BUFFILEPRE},
7642 {"BufHidden", EVENT_BUFHIDDEN},
7643 {"BufLeave", EVENT_BUFLEAVE},
7644 {"BufNew", EVENT_BUFNEW},
7645 {"BufNewFile", EVENT_BUFNEWFILE},
7646 {"BufRead", EVENT_BUFREADPOST},
7647 {"BufReadCmd", EVENT_BUFREADCMD},
7648 {"BufReadPost", EVENT_BUFREADPOST},
7649 {"BufReadPre", EVENT_BUFREADPRE},
7650 {"BufUnload", EVENT_BUFUNLOAD},
7651 {"BufWinEnter", EVENT_BUFWINENTER},
7652 {"BufWinLeave", EVENT_BUFWINLEAVE},
7653 {"BufWipeout", EVENT_BUFWIPEOUT},
7654 {"BufWrite", EVENT_BUFWRITEPRE},
7655 {"BufWritePost", EVENT_BUFWRITEPOST},
7656 {"BufWritePre", EVENT_BUFWRITEPRE},
7657 {"BufWriteCmd", EVENT_BUFWRITECMD},
7658 {"CmdwinEnter", EVENT_CMDWINENTER},
7659 {"CmdwinLeave", EVENT_CMDWINLEAVE},
Bram Moolenaard5005162014-08-22 23:05:54 +02007660 {"CmdUndefined", EVENT_CMDUNDEFINED},
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007661 {"ColorScheme", EVENT_COLORSCHEME},
Bram Moolenaarcfa3cae2012-07-10 17:14:56 +02007662 {"CompleteDone", EVENT_COMPLETEDONE},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007663 {"CursorHold", EVENT_CURSORHOLD},
7664 {"CursorHoldI", EVENT_CURSORHOLDI},
7665 {"CursorMoved", EVENT_CURSORMOVED},
7666 {"CursorMovedI", EVENT_CURSORMOVEDI},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007667 {"EncodingChanged", EVENT_ENCODINGCHANGED},
7668 {"FileEncoding", EVENT_ENCODINGCHANGED},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007669 {"FileAppendPost", EVENT_FILEAPPENDPOST},
7670 {"FileAppendPre", EVENT_FILEAPPENDPRE},
7671 {"FileAppendCmd", EVENT_FILEAPPENDCMD},
7672 {"FileChangedShell",EVENT_FILECHANGEDSHELL},
Bram Moolenaar56718732006-03-15 22:53:57 +00007673 {"FileChangedShellPost",EVENT_FILECHANGEDSHELLPOST},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007674 {"FileChangedRO", EVENT_FILECHANGEDRO},
7675 {"FileReadPost", EVENT_FILEREADPOST},
7676 {"FileReadPre", EVENT_FILEREADPRE},
7677 {"FileReadCmd", EVENT_FILEREADCMD},
7678 {"FileType", EVENT_FILETYPE},
7679 {"FileWritePost", EVENT_FILEWRITEPOST},
7680 {"FileWritePre", EVENT_FILEWRITEPRE},
7681 {"FileWriteCmd", EVENT_FILEWRITECMD},
7682 {"FilterReadPost", EVENT_FILTERREADPOST},
7683 {"FilterReadPre", EVENT_FILTERREADPRE},
7684 {"FilterWritePost", EVENT_FILTERWRITEPOST},
7685 {"FilterWritePre", EVENT_FILTERWRITEPRE},
7686 {"FocusGained", EVENT_FOCUSGAINED},
7687 {"FocusLost", EVENT_FOCUSLOST},
7688 {"FuncUndefined", EVENT_FUNCUNDEFINED},
7689 {"GUIEnter", EVENT_GUIENTER},
Bram Moolenaar265e5072006-08-29 16:13:22 +00007690 {"GUIFailed", EVENT_GUIFAILED},
Bram Moolenaar843ee412004-06-30 16:16:41 +00007691 {"InsertChange", EVENT_INSERTCHANGE},
7692 {"InsertEnter", EVENT_INSERTENTER},
7693 {"InsertLeave", EVENT_INSERTLEAVE},
Bram Moolenaare659c952011-05-19 17:25:41 +02007694 {"InsertCharPre", EVENT_INSERTCHARPRE},
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00007695 {"MenuPopup", EVENT_MENUPOPUP},
Bram Moolenaar53744302015-07-17 17:38:22 +02007696 {"OptionSet", EVENT_OPTIONSET},
Bram Moolenaar7c626922005-02-07 22:01:03 +00007697 {"QuickFixCmdPost", EVENT_QUICKFIXCMDPOST},
7698 {"QuickFixCmdPre", EVENT_QUICKFIXCMDPRE},
Bram Moolenaar3b53dfb2012-06-06 18:03:07 +02007699 {"QuitPre", EVENT_QUITPRE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007700 {"RemoteReply", EVENT_REMOTEREPLY},
Bram Moolenaar9372a112005-12-06 19:59:18 +00007701 {"SessionLoadPost", EVENT_SESSIONLOADPOST},
Bram Moolenaar5c4bab02006-03-10 21:37:46 +00007702 {"ShellCmdPost", EVENT_SHELLCMDPOST},
7703 {"ShellFilterPost", EVENT_SHELLFILTERPOST},
Bram Moolenaara2031822006-03-07 22:29:51 +00007704 {"SourcePre", EVENT_SOURCEPRE},
Bram Moolenaar8dd1aa52007-01-16 20:33:19 +00007705 {"SourceCmd", EVENT_SOURCECMD},
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00007706 {"SpellFileMissing",EVENT_SPELLFILEMISSING},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007707 {"StdinReadPost", EVENT_STDINREADPOST},
7708 {"StdinReadPre", EVENT_STDINREADPRE},
Bram Moolenaarb815dac2005-12-07 20:59:24 +00007709 {"SwapExists", EVENT_SWAPEXISTS},
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00007710 {"Syntax", EVENT_SYNTAX},
Bram Moolenaarc917da42016-07-19 22:31:36 +02007711 {"TabNew", EVENT_TABNEW},
Bram Moolenaar12c11d52016-07-19 23:13:03 +02007712 {"TabClosed", EVENT_TABCLOSED},
Bram Moolenaar70836c82006-02-20 21:28:49 +00007713 {"TabEnter", EVENT_TABENTER},
7714 {"TabLeave", EVENT_TABLEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007715 {"TermChanged", EVENT_TERMCHANGED},
7716 {"TermResponse", EVENT_TERMRESPONSE},
Bram Moolenaar186628f2013-03-19 13:33:23 +01007717 {"TextChanged", EVENT_TEXTCHANGED},
7718 {"TextChangedI", EVENT_TEXTCHANGEDI},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007719 {"User", EVENT_USER},
7720 {"VimEnter", EVENT_VIMENTER},
7721 {"VimLeave", EVENT_VIMLEAVE},
7722 {"VimLeavePre", EVENT_VIMLEAVEPRE},
Bram Moolenaarc917da42016-07-19 22:31:36 +02007723 {"WinNew", EVENT_WINNEW},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007724 {"WinEnter", EVENT_WINENTER},
7725 {"WinLeave", EVENT_WINLEAVE},
Bram Moolenaar56718732006-03-15 22:53:57 +00007726 {"VimResized", EVENT_VIMRESIZED},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007727 {NULL, (event_T)0}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007728};
7729
7730static AutoPat *first_autopat[NUM_EVENTS] =
7731{
7732 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7733 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7734 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7735 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00007736 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaar53744302015-07-17 17:38:22 +02007737 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007738};
7739
7740/*
7741 * struct used to keep status while executing autocommands for an event.
7742 */
7743typedef struct AutoPatCmd
7744{
7745 AutoPat *curpat; /* next AutoPat to examine */
7746 AutoCmd *nextcmd; /* next AutoCmd to execute */
7747 int group; /* group being used */
7748 char_u *fname; /* fname to match with */
7749 char_u *sfname; /* sfname to match with */
7750 char_u *tail; /* tail of fname */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007751 event_T event; /* current event */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007752 int arg_bufnr; /* initially equal to <abuf>, set to zero when
7753 buf is deleted */
7754 struct AutoPatCmd *next; /* chain of active apc-s for auto-invalidation*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00007755} AutoPatCmd;
7756
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007757static AutoPatCmd *active_apc_list = NULL; /* stack of active autocommands */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007758
Bram Moolenaar071d4272004-06-13 20:20:40 +00007759/*
7760 * augroups stores a list of autocmd group names.
7761 */
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007762static garray_T augroups = {0, 0, sizeof(char_u *), 10, NULL};
Bram Moolenaar071d4272004-06-13 20:20:40 +00007763#define AUGROUP_NAME(i) (((char_u **)augroups.ga_data)[i])
Bram Moolenaarb62cc362016-09-03 16:43:53 +02007764/* use get_deleted_augroup() to get this */
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02007765static char_u *deleted_augroup = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007766
7767/*
7768 * The ID of the current group. Group 0 is the default one.
7769 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007770static int current_augroup = AUGROUP_DEFAULT;
7771
7772static int au_need_clean = FALSE; /* need to delete marked patterns */
7773
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007774static void show_autocmd(AutoPat *ap, event_T event);
7775static void au_remove_pat(AutoPat *ap);
7776static void au_remove_cmds(AutoPat *ap);
7777static void au_cleanup(void);
7778static int au_new_group(char_u *name);
7779static void au_del_group(char_u *name);
7780static event_T event_name2nr(char_u *start, char_u **end);
7781static char_u *event_nr2name(event_T event);
7782static char_u *find_end_event(char_u *arg, int have_group);
7783static int event_ignored(event_T event);
7784static int au_get_grouparg(char_u **argp);
7785static int do_autocmd_event(event_T event, char_u *pat, int nested, char_u *cmd, int forceit, int group);
7786static int apply_autocmds_group(event_T event, char_u *fname, char_u *fname_io, int force, int group, buf_T *buf, exarg_T *eap);
7787static void auto_next_pat(AutoPatCmd *apc, int stop_at_last);
Bram Moolenaardffa5b82014-11-19 16:38:07 +01007788#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN)
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007789static 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 +01007790#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007791
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007792
Bram Moolenaar754b5602006-02-09 23:53:20 +00007793static event_T last_event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007794static int last_group;
Bram Moolenaar78ab3312007-09-29 12:16:41 +00007795static int autocmd_blocked = 0; /* block all autocmds */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007796
Bram Moolenaarb62cc362016-09-03 16:43:53 +02007797 static char_u *
7798get_deleted_augroup(void)
7799{
7800 if (deleted_augroup == NULL)
7801 deleted_augroup = (char_u *)_("--Deleted--");
7802 return deleted_augroup;
7803}
7804
Bram Moolenaar071d4272004-06-13 20:20:40 +00007805/*
7806 * Show the autocommands for one AutoPat.
7807 */
7808 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007809show_autocmd(AutoPat *ap, event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007810{
7811 AutoCmd *ac;
7812
7813 /* Check for "got_int" (here and at various places below), which is set
7814 * when "q" has been hit for the "--more--" prompt */
7815 if (got_int)
7816 return;
7817 if (ap->pat == NULL) /* pattern has been removed */
7818 return;
7819
7820 msg_putchar('\n');
7821 if (got_int)
7822 return;
7823 if (event != last_event || ap->group != last_group)
7824 {
7825 if (ap->group != AUGROUP_DEFAULT)
7826 {
7827 if (AUGROUP_NAME(ap->group) == NULL)
Bram Moolenaarb62cc362016-09-03 16:43:53 +02007828 msg_puts_attr(get_deleted_augroup(), hl_attr(HLF_E));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007829 else
7830 msg_puts_attr(AUGROUP_NAME(ap->group), hl_attr(HLF_T));
7831 msg_puts((char_u *)" ");
7832 }
7833 msg_puts_attr(event_nr2name(event), hl_attr(HLF_T));
7834 last_event = event;
7835 last_group = ap->group;
7836 msg_putchar('\n');
7837 if (got_int)
7838 return;
7839 }
7840 msg_col = 4;
7841 msg_outtrans(ap->pat);
7842
7843 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7844 {
7845 if (ac->cmd != NULL) /* skip removed commands */
7846 {
7847 if (msg_col >= 14)
7848 msg_putchar('\n');
7849 msg_col = 14;
7850 if (got_int)
7851 return;
7852 msg_outtrans(ac->cmd);
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00007853#ifdef FEAT_EVAL
7854 if (p_verbose > 0)
7855 last_set_msg(ac->scriptID);
7856#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007857 if (got_int)
7858 return;
7859 if (ac->next != NULL)
7860 {
7861 msg_putchar('\n');
7862 if (got_int)
7863 return;
7864 }
7865 }
7866 }
7867}
7868
7869/*
7870 * Mark an autocommand pattern for deletion.
7871 */
7872 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007873au_remove_pat(AutoPat *ap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007874{
7875 vim_free(ap->pat);
7876 ap->pat = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007877 ap->buflocal_nr = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007878 au_need_clean = TRUE;
7879}
7880
7881/*
7882 * Mark all commands for a pattern for deletion.
7883 */
7884 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007885au_remove_cmds(AutoPat *ap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007886{
7887 AutoCmd *ac;
7888
7889 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7890 {
7891 vim_free(ac->cmd);
7892 ac->cmd = NULL;
7893 }
7894 au_need_clean = TRUE;
7895}
7896
7897/*
7898 * Cleanup autocommands and patterns that have been deleted.
7899 * This is only done when not executing autocommands.
7900 */
7901 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007902au_cleanup(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007903{
7904 AutoPat *ap, **prev_ap;
7905 AutoCmd *ac, **prev_ac;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007906 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007907
7908 if (autocmd_busy || !au_need_clean)
7909 return;
7910
7911 /* loop over all events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007912 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7913 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007914 {
7915 /* loop over all autocommand patterns */
7916 prev_ap = &(first_autopat[(int)event]);
7917 for (ap = *prev_ap; ap != NULL; ap = *prev_ap)
7918 {
7919 /* loop over all commands for this pattern */
7920 prev_ac = &(ap->cmds);
7921 for (ac = *prev_ac; ac != NULL; ac = *prev_ac)
7922 {
7923 /* remove the command if the pattern is to be deleted or when
7924 * the command has been marked for deletion */
7925 if (ap->pat == NULL || ac->cmd == NULL)
7926 {
7927 *prev_ac = ac->next;
7928 vim_free(ac->cmd);
7929 vim_free(ac);
7930 }
7931 else
7932 prev_ac = &(ac->next);
7933 }
7934
7935 /* remove the pattern if it has been marked for deletion */
7936 if (ap->pat == NULL)
7937 {
7938 *prev_ap = ap->next;
Bram Moolenaar473de612013-06-08 18:19:48 +02007939 vim_regfree(ap->reg_prog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007940 vim_free(ap);
7941 }
7942 else
7943 prev_ap = &(ap->next);
7944 }
7945 }
7946
7947 au_need_clean = FALSE;
7948}
7949
7950/*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007951 * Called when buffer is freed, to remove/invalidate related buffer-local
7952 * autocmds.
7953 */
7954 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007955aubuflocal_remove(buf_T *buf)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007956{
7957 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007958 event_T event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007959 AutoPatCmd *apc;
7960
7961 /* invalidate currently executing autocommands */
7962 for (apc = active_apc_list; apc; apc = apc->next)
7963 if (buf->b_fnum == apc->arg_bufnr)
7964 apc->arg_bufnr = 0;
7965
7966 /* invalidate buflocals looping through events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007967 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7968 event = (event_T)((int)event + 1))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007969 /* loop over all autocommand patterns */
7970 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
7971 if (ap->buflocal_nr == buf->b_fnum)
7972 {
7973 au_remove_pat(ap);
7974 if (p_verbose >= 6)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007975 {
7976 verbose_enter();
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007977 smsg((char_u *)
7978 _("auto-removing autocommand: %s <buffer=%d>"),
7979 event_nr2name(event), buf->b_fnum);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007980 verbose_leave();
7981 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007982 }
7983 au_cleanup();
7984}
7985
7986/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007987 * Add an autocmd group name.
7988 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
7989 */
7990 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007991au_new_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007992{
7993 int i;
7994
7995 i = au_find_group(name);
7996 if (i == AUGROUP_ERROR) /* the group doesn't exist yet, add it */
7997 {
7998 /* First try using a free entry. */
7999 for (i = 0; i < augroups.ga_len; ++i)
8000 if (AUGROUP_NAME(i) == NULL)
8001 break;
8002 if (i == augroups.ga_len && ga_grow(&augroups, 1) == FAIL)
8003 return AUGROUP_ERROR;
8004
8005 AUGROUP_NAME(i) = vim_strsave(name);
8006 if (AUGROUP_NAME(i) == NULL)
8007 return AUGROUP_ERROR;
8008 if (i == augroups.ga_len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008009 ++augroups.ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008010 }
8011
8012 return i;
8013}
8014
8015 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008016au_del_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008017{
8018 int i;
8019
8020 i = au_find_group(name);
8021 if (i == AUGROUP_ERROR) /* the group doesn't exist */
8022 EMSG2(_("E367: No such group: \"%s\""), name);
Bram Moolenaarde653f02016-09-03 16:59:06 +02008023 else if (i == current_augroup)
8024 EMSG(_("E936: Cannot delete the current group"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008025 else
8026 {
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008027 event_T event;
8028 AutoPat *ap;
8029 int in_use = FALSE;
8030
8031 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8032 event = (event_T)((int)event + 1))
8033 {
8034 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
Bram Moolenaar5c809082016-09-01 16:21:48 +02008035 if (ap->group == i && ap->pat != NULL)
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008036 {
8037 give_warning((char_u *)_("W19: Deleting augroup that is still in use"), TRUE);
8038 in_use = TRUE;
8039 event = NUM_EVENTS;
8040 break;
8041 }
8042 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008043 vim_free(AUGROUP_NAME(i));
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008044 if (in_use)
8045 {
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008046 AUGROUP_NAME(i) = get_deleted_augroup();
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008047 }
8048 else
8049 AUGROUP_NAME(i) = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008050 }
8051}
8052
8053/*
8054 * Find the ID of an autocmd group name.
8055 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
8056 */
8057 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008058au_find_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008059{
8060 int i;
8061
8062 for (i = 0; i < augroups.ga_len; ++i)
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008063 if (AUGROUP_NAME(i) != NULL && AUGROUP_NAME(i) != get_deleted_augroup()
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008064 && STRCMP(AUGROUP_NAME(i), name) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008065 return i;
8066 return AUGROUP_ERROR;
8067}
8068
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008069/*
8070 * Return TRUE if augroup "name" exists.
8071 */
8072 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008073au_has_group(char_u *name)
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008074{
8075 return au_find_group(name) != AUGROUP_ERROR;
8076}
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008077
Bram Moolenaar071d4272004-06-13 20:20:40 +00008078/*
8079 * ":augroup {name}".
8080 */
8081 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008082do_augroup(char_u *arg, int del_group)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008083{
8084 int i;
8085
8086 if (del_group)
8087 {
8088 if (*arg == NUL)
8089 EMSG(_(e_argreq));
8090 else
8091 au_del_group(arg);
8092 }
8093 else if (STRICMP(arg, "end") == 0) /* ":aug end": back to group 0 */
8094 current_augroup = AUGROUP_DEFAULT;
8095 else if (*arg) /* ":aug xxx": switch to group xxx */
8096 {
8097 i = au_new_group(arg);
8098 if (i != AUGROUP_ERROR)
8099 current_augroup = i;
8100 }
8101 else /* ":aug": list the group names */
8102 {
8103 msg_start();
8104 for (i = 0; i < augroups.ga_len; ++i)
8105 {
8106 if (AUGROUP_NAME(i) != NULL)
8107 {
8108 msg_puts(AUGROUP_NAME(i));
8109 msg_puts((char_u *)" ");
8110 }
8111 }
8112 msg_clr_eos();
8113 msg_end();
8114 }
8115}
8116
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008117#if defined(EXITFREE) || defined(PROTO)
8118 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008119free_all_autocmds(void)
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008120{
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008121 int i;
8122 char_u *s;
8123
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008124 for (current_augroup = -1; current_augroup < augroups.ga_len;
8125 ++current_augroup)
8126 do_autocmd((char_u *)"", TRUE);
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008127
8128 for (i = 0; i < augroups.ga_len; ++i)
8129 {
8130 s = ((char_u **)(augroups.ga_data))[i];
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008131 if (s != get_deleted_augroup())
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008132 vim_free(s);
8133 }
8134 ga_clear(&augroups);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008135}
8136#endif
8137
Bram Moolenaar071d4272004-06-13 20:20:40 +00008138/*
8139 * Return the event number for event name "start".
8140 * Return NUM_EVENTS if the event name was not found.
8141 * Return a pointer to the next event name in "end".
8142 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008143 static event_T
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008144event_name2nr(char_u *start, char_u **end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008145{
8146 char_u *p;
8147 int i;
8148 int len;
8149
Bram Moolenaare99e8442016-07-26 20:43:40 +02008150 /* the event name ends with end of line, '|', a blank or a comma */
8151 for (p = start; *p && !vim_iswhite(*p) && *p != ',' && *p != '|'; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008152 ;
8153 for (i = 0; event_names[i].name != NULL; ++i)
8154 {
8155 len = (int)STRLEN(event_names[i].name);
8156 if (len == p - start && STRNICMP(event_names[i].name, start, len) == 0)
8157 break;
8158 }
8159 if (*p == ',')
8160 ++p;
8161 *end = p;
8162 if (event_names[i].name == NULL)
8163 return NUM_EVENTS;
8164 return event_names[i].event;
8165}
8166
8167/*
8168 * Return the name for event "event".
8169 */
8170 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008171event_nr2name(event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008172{
8173 int i;
8174
8175 for (i = 0; event_names[i].name != NULL; ++i)
8176 if (event_names[i].event == event)
8177 return (char_u *)event_names[i].name;
8178 return (char_u *)"Unknown";
8179}
8180
8181/*
8182 * Scan over the events. "*" stands for all events.
8183 */
8184 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008185find_end_event(
8186 char_u *arg,
8187 int have_group) /* TRUE when group name was found */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008188{
8189 char_u *pat;
8190 char_u *p;
8191
8192 if (*arg == '*')
8193 {
8194 if (arg[1] && !vim_iswhite(arg[1]))
8195 {
8196 EMSG2(_("E215: Illegal character after *: %s"), arg);
8197 return NULL;
8198 }
8199 pat = arg + 1;
8200 }
8201 else
8202 {
Bram Moolenaare99e8442016-07-26 20:43:40 +02008203 for (pat = arg; *pat && *pat != '|' && !vim_iswhite(*pat); pat = p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008204 {
8205 if ((int)event_name2nr(pat, &p) >= (int)NUM_EVENTS)
8206 {
8207 if (have_group)
8208 EMSG2(_("E216: No such event: %s"), pat);
8209 else
8210 EMSG2(_("E216: No such group or event: %s"), pat);
8211 return NULL;
8212 }
8213 }
8214 }
8215 return pat;
8216}
8217
8218/*
8219 * Return TRUE if "event" is included in 'eventignore'.
8220 */
8221 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008222event_ignored(event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008223{
8224 char_u *p = p_ei;
8225
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008226 while (*p != NUL)
8227 {
8228 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8229 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008230 if (event_name2nr(p, &p) == event)
8231 return TRUE;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008232 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008233
8234 return FALSE;
8235}
8236
8237/*
8238 * Return OK when the contents of p_ei is valid, FAIL otherwise.
8239 */
8240 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008241check_ei(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008242{
8243 char_u *p = p_ei;
8244
Bram Moolenaar071d4272004-06-13 20:20:40 +00008245 while (*p)
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008246 {
8247 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8248 {
8249 p += 3;
8250 if (*p == ',')
8251 ++p;
8252 }
8253 else if (event_name2nr(p, &p) == NUM_EVENTS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008254 return FAIL;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008255 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008256
8257 return OK;
8258}
8259
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008260# if defined(FEAT_SYN_HL) || defined(PROTO)
8261
8262/*
8263 * Add "what" to 'eventignore' to skip loading syntax highlighting for every
8264 * buffer loaded into the window. "what" must start with a comma.
8265 * Returns the old value of 'eventignore' in allocated memory.
8266 */
8267 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008268au_event_disable(char *what)
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008269{
8270 char_u *new_ei;
8271 char_u *save_ei;
8272
8273 save_ei = vim_strsave(p_ei);
8274 if (save_ei != NULL)
8275 {
Bram Moolenaara5792f52005-11-23 21:25:05 +00008276 new_ei = vim_strnsave(p_ei, (int)(STRLEN(p_ei) + STRLEN(what)));
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008277 if (new_ei != NULL)
8278 {
Bram Moolenaar8cac9fd2010-03-02 12:48:05 +01008279 if (*what == ',' && *p_ei == NUL)
8280 STRCPY(new_ei, what + 1);
8281 else
8282 STRCAT(new_ei, what);
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008283 set_string_option_direct((char_u *)"ei", -1, new_ei,
8284 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008285 vim_free(new_ei);
8286 }
8287 }
8288 return save_ei;
8289}
8290
8291 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008292au_event_restore(char_u *old_ei)
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008293{
8294 if (old_ei != NULL)
8295 {
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008296 set_string_option_direct((char_u *)"ei", -1, old_ei,
8297 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008298 vim_free(old_ei);
8299 }
8300}
8301# endif /* FEAT_SYN_HL */
8302
Bram Moolenaar071d4272004-06-13 20:20:40 +00008303/*
8304 * do_autocmd() -- implements the :autocmd command. Can be used in the
8305 * following ways:
8306 *
8307 * :autocmd <event> <pat> <cmd> Add <cmd> to the list of commands that
8308 * will be automatically executed for <event>
8309 * when editing a file matching <pat>, in
8310 * the current group.
8311 * :autocmd <event> <pat> Show the auto-commands associated with
8312 * <event> and <pat>.
8313 * :autocmd <event> Show the auto-commands associated with
8314 * <event>.
8315 * :autocmd Show all auto-commands.
8316 * :autocmd! <event> <pat> <cmd> Remove all auto-commands associated with
8317 * <event> and <pat>, and add the command
8318 * <cmd>, for the current group.
8319 * :autocmd! <event> <pat> Remove all auto-commands associated with
8320 * <event> and <pat> for the current group.
8321 * :autocmd! <event> Remove all auto-commands associated with
8322 * <event> for the current group.
8323 * :autocmd! Remove ALL auto-commands for the current
8324 * group.
8325 *
8326 * Multiple events and patterns may be given separated by commas. Here are
8327 * some examples:
8328 * :autocmd bufread,bufenter *.c,*.h set tw=0 smartindent noic
8329 * :autocmd bufleave * set tw=79 nosmartindent ic infercase
8330 *
8331 * :autocmd * *.c show all autocommands for *.c files.
Bram Moolenaard35f9712005-12-18 22:02:33 +00008332 *
8333 * Mostly a {group} argument can optionally appear before <event>.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008334 */
8335 void
Bram Moolenaare99e8442016-07-26 20:43:40 +02008336do_autocmd(char_u *arg_in, int forceit)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008337{
Bram Moolenaare99e8442016-07-26 20:43:40 +02008338 char_u *arg = arg_in;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008339 char_u *pat;
8340 char_u *envpat = NULL;
8341 char_u *cmd;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008342 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008343 int need_free = FALSE;
8344 int nested = FALSE;
8345 int group;
8346
Bram Moolenaare99e8442016-07-26 20:43:40 +02008347 if (*arg == '|')
8348 {
8349 arg = (char_u *)"";
8350 group = AUGROUP_ALL; /* no argument, use all groups */
8351 }
8352 else
8353 {
8354 /*
8355 * Check for a legal group name. If not, use AUGROUP_ALL.
8356 */
8357 group = au_get_grouparg(&arg);
8358 if (arg == NULL) /* out of memory */
8359 return;
8360 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008361
8362 /*
8363 * Scan over the events.
8364 * If we find an illegal name, return here, don't do anything.
8365 */
8366 pat = find_end_event(arg, group != AUGROUP_ALL);
8367 if (pat == NULL)
8368 return;
8369
Bram Moolenaar071d4272004-06-13 20:20:40 +00008370 pat = skipwhite(pat);
Bram Moolenaare99e8442016-07-26 20:43:40 +02008371 if (*pat == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008372 {
Bram Moolenaare99e8442016-07-26 20:43:40 +02008373 pat = (char_u *)"";
8374 cmd = (char_u *)"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00008375 }
Bram Moolenaare99e8442016-07-26 20:43:40 +02008376 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00008377 {
Bram Moolenaare99e8442016-07-26 20:43:40 +02008378 /*
8379 * Scan over the pattern. Put a NUL at the end.
8380 */
8381 cmd = pat;
8382 while (*cmd && (!vim_iswhite(*cmd) || cmd[-1] == '\\'))
8383 cmd++;
8384 if (*cmd)
8385 *cmd++ = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008386
Bram Moolenaare99e8442016-07-26 20:43:40 +02008387 /* Expand environment variables in the pattern. Set 'shellslash', we want
8388 * forward slashes here. */
8389 if (vim_strchr(pat, '$') != NULL || vim_strchr(pat, '~') != NULL)
8390 {
8391#ifdef BACKSLASH_IN_FILENAME
8392 int p_ssl_save = p_ssl;
8393
8394 p_ssl = TRUE;
8395#endif
8396 envpat = expand_env_save(pat);
8397#ifdef BACKSLASH_IN_FILENAME
8398 p_ssl = p_ssl_save;
8399#endif
8400 if (envpat != NULL)
8401 pat = envpat;
8402 }
8403
8404 /*
8405 * Check for "nested" flag.
8406 */
8407 cmd = skipwhite(cmd);
8408 if (*cmd != NUL && STRNCMP(cmd, "nested", 6) == 0 && vim_iswhite(cmd[6]))
8409 {
8410 nested = TRUE;
8411 cmd = skipwhite(cmd + 6);
8412 }
8413
8414 /*
8415 * Find the start of the commands.
8416 * Expand <sfile> in it.
8417 */
8418 if (*cmd != NUL)
8419 {
8420 cmd = expand_sfile(cmd);
8421 if (cmd == NULL) /* some error */
8422 return;
8423 need_free = TRUE;
8424 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008425 }
8426
8427 /*
8428 * Print header when showing autocommands.
8429 */
8430 if (!forceit && *cmd == NUL)
8431 {
8432 /* Highlight title */
8433 MSG_PUTS_TITLE(_("\n--- Auto-Commands ---"));
8434 }
8435
8436 /*
8437 * Loop over the events.
8438 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008439 last_event = (event_T)-1; /* for listing the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008440 last_group = AUGROUP_ERROR; /* for listing the group name */
Bram Moolenaare99e8442016-07-26 20:43:40 +02008441 if (*arg == '*' || *arg == NUL || *arg == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008442 {
Bram Moolenaar754b5602006-02-09 23:53:20 +00008443 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8444 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008445 if (do_autocmd_event(event, pat,
8446 nested, cmd, forceit, group) == FAIL)
8447 break;
8448 }
8449 else
8450 {
Bram Moolenaare99e8442016-07-26 20:43:40 +02008451 while (*arg && *arg != '|' && !vim_iswhite(*arg))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008452 if (do_autocmd_event(event_name2nr(arg, &arg), pat,
8453 nested, cmd, forceit, group) == FAIL)
8454 break;
8455 }
8456
8457 if (need_free)
8458 vim_free(cmd);
8459 vim_free(envpat);
8460}
8461
8462/*
8463 * Find the group ID in a ":autocmd" or ":doautocmd" argument.
8464 * The "argp" argument is advanced to the following argument.
8465 *
8466 * Returns the group ID, AUGROUP_ERROR for error (out of memory).
8467 */
8468 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008469au_get_grouparg(char_u **argp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008470{
8471 char_u *group_name;
8472 char_u *p;
8473 char_u *arg = *argp;
8474 int group = AUGROUP_ALL;
8475
Bram Moolenaare99e8442016-07-26 20:43:40 +02008476 for (p = arg; *p && !vim_iswhite(*p) && *p != '|'; ++p)
8477 ;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008478 if (p > arg)
8479 {
8480 group_name = vim_strnsave(arg, (int)(p - arg));
8481 if (group_name == NULL) /* out of memory */
8482 return AUGROUP_ERROR;
8483 group = au_find_group(group_name);
8484 if (group == AUGROUP_ERROR)
8485 group = AUGROUP_ALL; /* no match, use all groups */
8486 else
8487 *argp = skipwhite(p); /* match, skip over group name */
8488 vim_free(group_name);
8489 }
8490 return group;
8491}
8492
8493/*
8494 * do_autocmd() for one event.
8495 * If *pat == NUL do for all patterns.
8496 * If *cmd == NUL show entries.
8497 * If forceit == TRUE delete entries.
8498 * If group is not AUGROUP_ALL, only use this group.
8499 */
8500 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008501do_autocmd_event(
8502 event_T event,
8503 char_u *pat,
8504 int nested,
8505 char_u *cmd,
8506 int forceit,
8507 int group)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008508{
8509 AutoPat *ap;
8510 AutoPat **prev_ap;
8511 AutoCmd *ac;
8512 AutoCmd **prev_ac;
8513 int brace_level;
8514 char_u *endpat;
8515 int findgroup;
8516 int allgroups;
8517 int patlen;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00008518 int is_buflocal;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008519 int buflocal_nr;
8520 char_u buflocal_pat[25]; /* for "<buffer=X>" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008521
8522 if (group == AUGROUP_ALL)
8523 findgroup = current_augroup;
8524 else
8525 findgroup = group;
8526 allgroups = (group == AUGROUP_ALL && !forceit && *cmd == NUL);
8527
8528 /*
8529 * Show or delete all patterns for an event.
8530 */
8531 if (*pat == NUL)
8532 {
8533 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8534 {
8535 if (forceit) /* delete the AutoPat, if it's in the current group */
8536 {
8537 if (ap->group == findgroup)
8538 au_remove_pat(ap);
8539 }
8540 else if (group == AUGROUP_ALL || ap->group == group)
8541 show_autocmd(ap, event);
8542 }
8543 }
8544
8545 /*
8546 * Loop through all the specified patterns.
8547 */
8548 for ( ; *pat; pat = (*endpat == ',' ? endpat + 1 : endpat))
8549 {
8550 /*
8551 * Find end of the pattern.
8552 * Watch out for a comma in braces, like "*.\{obj,o\}".
8553 */
8554 brace_level = 0;
8555 for (endpat = pat; *endpat && (*endpat != ',' || brace_level
Bram Moolenaar6b9be1b2015-07-28 13:33:45 +02008556 || (endpat > pat && endpat[-1] == '\\')); ++endpat)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008557 {
8558 if (*endpat == '{')
8559 brace_level++;
8560 else if (*endpat == '}')
8561 brace_level--;
8562 }
8563 if (pat == endpat) /* ignore single comma */
8564 continue;
8565 patlen = (int)(endpat - pat);
8566
8567 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008568 * detect special <buflocal[=X]> buffer-local patterns
8569 */
8570 is_buflocal = FALSE;
8571 buflocal_nr = 0;
8572
Bram Moolenaar1e997822015-02-17 16:04:57 +01008573 if (patlen >= 8 && STRNCMP(pat, "<buffer", 7) == 0
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008574 && pat[patlen - 1] == '>')
8575 {
Bram Moolenaar1e997822015-02-17 16:04:57 +01008576 /* "<buffer...>": Error will be printed only for addition.
8577 * printing and removing will proceed silently. */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008578 is_buflocal = TRUE;
8579 if (patlen == 8)
Bram Moolenaar1e997822015-02-17 16:04:57 +01008580 /* "<buffer>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008581 buflocal_nr = curbuf->b_fnum;
8582 else if (patlen > 9 && pat[7] == '=')
8583 {
Bram Moolenaar1e997822015-02-17 16:04:57 +01008584 if (patlen == 13 && STRNICMP(pat, "<buffer=abuf>", 13) == 0)
8585 /* "<buffer=abuf>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008586 buflocal_nr = autocmd_bufnr;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008587 else if (skipdigits(pat + 8) == pat + patlen - 1)
Bram Moolenaar1e997822015-02-17 16:04:57 +01008588 /* "<buffer=123>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008589 buflocal_nr = atoi((char *)pat + 8);
8590 }
8591 }
8592
8593 if (is_buflocal)
8594 {
8595 /* normalize pat into standard "<buffer>#N" form */
8596 sprintf((char *)buflocal_pat, "<buffer=%d>", buflocal_nr);
8597 pat = buflocal_pat; /* can modify pat and patlen */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008598 patlen = (int)STRLEN(buflocal_pat); /* but not endpat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008599 }
8600
8601 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008602 * Find AutoPat entries with this pattern.
8603 */
8604 prev_ap = &first_autopat[(int)event];
8605 while ((ap = *prev_ap) != NULL)
8606 {
8607 if (ap->pat != NULL)
8608 {
8609 /* Accept a pattern when:
8610 * - a group was specified and it's that group, or a group was
8611 * not specified and it's the current group, or a group was
8612 * not specified and we are listing
8613 * - the length of the pattern matches
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008614 * - the pattern matches.
8615 * For <buffer[=X]>, this condition works because we normalize
8616 * all buffer-local patterns.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008617 */
8618 if ((allgroups || ap->group == findgroup)
8619 && ap->patlen == patlen
8620 && STRNCMP(pat, ap->pat, patlen) == 0)
8621 {
8622 /*
8623 * Remove existing autocommands.
8624 * If adding any new autocmd's for this AutoPat, don't
8625 * delete the pattern from the autopat list, append to
8626 * this list.
8627 */
8628 if (forceit)
8629 {
8630 if (*cmd != NUL && ap->next == NULL)
8631 {
8632 au_remove_cmds(ap);
8633 break;
8634 }
8635 au_remove_pat(ap);
8636 }
8637
8638 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008639 * Show autocmd's for this autopat, or buflocals <buffer=X>
Bram Moolenaar071d4272004-06-13 20:20:40 +00008640 */
8641 else if (*cmd == NUL)
8642 show_autocmd(ap, event);
8643
8644 /*
8645 * Add autocmd to this autopat, if it's the last one.
8646 */
8647 else if (ap->next == NULL)
8648 break;
8649 }
8650 }
8651 prev_ap = &ap->next;
8652 }
8653
8654 /*
8655 * Add a new command.
8656 */
8657 if (*cmd != NUL)
8658 {
8659 /*
8660 * If the pattern we want to add a command to does appear at the
8661 * end of the list (or not is not in the list at all), add the
8662 * pattern at the end of the list.
8663 */
8664 if (ap == NULL)
8665 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008666 /* refuse to add buffer-local ap if buffer number is invalid */
8667 if (is_buflocal && (buflocal_nr == 0
8668 || buflist_findnr(buflocal_nr) == NULL))
8669 {
8670 EMSGN(_("E680: <buffer=%d>: invalid buffer number "),
8671 buflocal_nr);
8672 return FAIL;
8673 }
8674
Bram Moolenaar071d4272004-06-13 20:20:40 +00008675 ap = (AutoPat *)alloc((unsigned)sizeof(AutoPat));
8676 if (ap == NULL)
8677 return FAIL;
8678 ap->pat = vim_strnsave(pat, patlen);
8679 ap->patlen = patlen;
8680 if (ap->pat == NULL)
8681 {
8682 vim_free(ap);
8683 return FAIL;
8684 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008685
8686 if (is_buflocal)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008687 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008688 ap->buflocal_nr = buflocal_nr;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008689 ap->reg_prog = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008690 }
8691 else
8692 {
Bram Moolenaar748bf032005-02-02 23:04:36 +00008693 char_u *reg_pat;
8694
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008695 ap->buflocal_nr = 0;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008696 reg_pat = file_pat_to_reg_pat(pat, endpat,
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008697 &ap->allow_dirs, TRUE);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008698 if (reg_pat != NULL)
8699 ap->reg_prog = vim_regcomp(reg_pat, RE_MAGIC);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008700 vim_free(reg_pat);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008701 if (reg_pat == NULL || ap->reg_prog == NULL)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008702 {
8703 vim_free(ap->pat);
8704 vim_free(ap);
8705 return FAIL;
8706 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008707 }
8708 ap->cmds = NULL;
8709 *prev_ap = ap;
8710 ap->next = NULL;
8711 if (group == AUGROUP_ALL)
8712 ap->group = current_augroup;
8713 else
8714 ap->group = group;
8715 }
8716
8717 /*
8718 * Add the autocmd at the end of the AutoCmd list.
8719 */
8720 prev_ac = &(ap->cmds);
8721 while ((ac = *prev_ac) != NULL)
8722 prev_ac = &ac->next;
8723 ac = (AutoCmd *)alloc((unsigned)sizeof(AutoCmd));
8724 if (ac == NULL)
8725 return FAIL;
8726 ac->cmd = vim_strsave(cmd);
8727#ifdef FEAT_EVAL
8728 ac->scriptID = current_SID;
8729#endif
8730 if (ac->cmd == NULL)
8731 {
8732 vim_free(ac);
8733 return FAIL;
8734 }
8735 ac->next = NULL;
8736 *prev_ac = ac;
8737 ac->nested = nested;
8738 }
8739 }
8740
8741 au_cleanup(); /* may really delete removed patterns/commands now */
8742 return OK;
8743}
8744
8745/*
8746 * Implementation of ":doautocmd [group] event [fname]".
8747 * Return OK for success, FAIL for failure;
8748 */
8749 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008750do_doautocmd(
8751 char_u *arg,
Bram Moolenaar1610d052016-06-09 22:53:01 +02008752 int do_msg, /* give message for no matching autocmds? */
8753 int *did_something)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008754{
8755 char_u *fname;
8756 int nothing_done = TRUE;
8757 int group;
8758
Bram Moolenaar1610d052016-06-09 22:53:01 +02008759 if (did_something != NULL)
Bram Moolenaar76ae22f2016-06-13 20:00:29 +02008760 *did_something = FALSE;
Bram Moolenaar1610d052016-06-09 22:53:01 +02008761
Bram Moolenaar071d4272004-06-13 20:20:40 +00008762 /*
8763 * Check for a legal group name. If not, use AUGROUP_ALL.
8764 */
8765 group = au_get_grouparg(&arg);
8766 if (arg == NULL) /* out of memory */
8767 return FAIL;
8768
8769 if (*arg == '*')
8770 {
8771 EMSG(_("E217: Can't execute autocommands for ALL events"));
8772 return FAIL;
8773 }
8774
8775 /*
8776 * Scan over the events.
8777 * If we find an illegal name, return here, don't do anything.
8778 */
8779 fname = find_end_event(arg, group != AUGROUP_ALL);
8780 if (fname == NULL)
8781 return FAIL;
8782
8783 fname = skipwhite(fname);
8784
8785 /*
8786 * Loop over the events.
8787 */
8788 while (*arg && !vim_iswhite(*arg))
8789 if (apply_autocmds_group(event_name2nr(arg, &arg),
8790 fname, NULL, TRUE, group, curbuf, NULL))
8791 nothing_done = FALSE;
8792
8793 if (nothing_done && do_msg)
8794 MSG(_("No matching autocommands"));
Bram Moolenaar1610d052016-06-09 22:53:01 +02008795 if (did_something != NULL)
8796 *did_something = !nothing_done;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008797
8798#ifdef FEAT_EVAL
8799 return aborting() ? FAIL : OK;
8800#else
8801 return OK;
8802#endif
8803}
8804
8805/*
8806 * ":doautoall": execute autocommands for each loaded buffer.
8807 */
8808 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008809ex_doautoall(exarg_T *eap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008810{
8811 int retval;
8812 aco_save_T aco;
8813 buf_T *buf;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008814 bufref_T bufref;
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008815 char_u *arg = eap->arg;
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008816 int call_do_modelines = check_nomodeline(&arg);
Bram Moolenaar1610d052016-06-09 22:53:01 +02008817 int did_aucmd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008818
8819 /*
8820 * This is a bit tricky: For some commands curwin->w_buffer needs to be
8821 * equal to curbuf, but for some buffers there may not be a window.
8822 * So we change the buffer for the current window for a moment. This
8823 * gives problems when the autocommands make changes to the list of
8824 * buffers or windows...
8825 */
Bram Moolenaar29323592016-07-24 22:04:11 +02008826 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008827 {
Bram Moolenaar3a847972008-07-08 09:36:58 +00008828 if (buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008829 {
8830 /* find a window for this buffer and save some values */
8831 aucmd_prepbuf(&aco, buf);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008832 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008833
8834 /* execute the autocommands for this buffer */
Bram Moolenaar1610d052016-06-09 22:53:01 +02008835 retval = do_doautocmd(arg, FALSE, &did_aucmd);
Bram Moolenaareeefcc72007-05-01 21:21:21 +00008836
Bram Moolenaar1610d052016-06-09 22:53:01 +02008837 if (call_do_modelines && did_aucmd)
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008838 {
8839 /* Execute the modeline settings, but don't set window-local
8840 * options if we are using the current window for another
8841 * buffer. */
8842 do_modelines(curwin == aucmd_win ? OPT_NOWIN : 0);
8843 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008844
8845 /* restore the current window */
8846 aucmd_restbuf(&aco);
8847
8848 /* stop if there is some error or buffer was deleted */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008849 if (retval == FAIL || !bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008850 break;
8851 }
8852 }
8853
8854 check_cursor(); /* just in case lines got deleted */
8855}
8856
8857/*
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008858 * Check *argp for <nomodeline>. When it is present return FALSE, otherwise
8859 * return TRUE and advance *argp to after it.
8860 * Thus return TRUE when do_modelines() should be called.
8861 */
8862 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008863check_nomodeline(char_u **argp)
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008864{
8865 if (STRNCMP(*argp, "<nomodeline>", 12) == 0)
8866 {
8867 *argp = skipwhite(*argp + 12);
8868 return FALSE;
8869 }
8870 return TRUE;
8871}
8872
8873/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008874 * Prepare for executing autocommands for (hidden) buffer "buf".
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008875 * Search for a visible window containing the current buffer. If there isn't
8876 * one then use "aucmd_win".
Bram Moolenaar071d4272004-06-13 20:20:40 +00008877 * Set "curbuf" and "curwin" to match "buf".
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00008878 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008879 */
8880 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008881aucmd_prepbuf(
8882 aco_save_T *aco, /* structure to save values in */
8883 buf_T *buf) /* new curbuf */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008884{
8885 win_T *win;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008886#ifdef FEAT_WINDOWS
8887 int save_ea;
8888#endif
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008889#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008890 int save_acd;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008891#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008892
8893 /* Find a window that is for the new buffer */
8894 if (buf == curbuf) /* be quick when buf is curbuf */
8895 win = curwin;
8896 else
8897#ifdef FEAT_WINDOWS
Bram Moolenaar29323592016-07-24 22:04:11 +02008898 FOR_ALL_WINDOWS(win)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008899 if (win->w_buffer == buf)
8900 break;
8901#else
8902 win = NULL;
8903#endif
8904
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008905 /* Allocate "aucmd_win" when needed. If this fails (out of memory) fall
8906 * back to using the current window. */
8907 if (win == NULL && aucmd_win == NULL)
8908 {
8909 win_alloc_aucmd_win();
8910 if (aucmd_win == NULL)
8911 win = curwin;
8912 }
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008913 if (win == NULL && aucmd_win_used)
8914 /* Strange recursive autocommand, fall back to using the current
8915 * window. Expect a few side effects... */
8916 win = curwin;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008917
8918 aco->save_curwin = curwin;
8919 aco->save_curbuf = curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008920 if (win != NULL)
8921 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008922 /* There is a window for "buf" in the current tab page, make it the
8923 * curwin. This is preferred, it has the least side effects (esp. if
8924 * "buf" is curbuf). */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008925 aco->use_aucmd_win = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008926 curwin = win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008927 }
8928 else
8929 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008930 /* There is no window for "buf", use "aucmd_win". To minimize the side
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02008931 * effects, insert it in the current tab page.
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008932 * Anything related to a window (e.g., setting folds) may have
8933 * unexpected results. */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008934 aco->use_aucmd_win = TRUE;
8935 aucmd_win_used = TRUE;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008936 aucmd_win->w_buffer = buf;
Bram Moolenaarcdddaa42010-06-07 23:07:44 +02008937 aucmd_win->w_s = &buf->b_s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008938 ++buf->b_nwindows;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008939 win_init_empty(aucmd_win); /* set cursor and topline to safe values */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008940
8941 /* Make sure w_localdir and globaldir are NULL to avoid a chdir() in
8942 * win_enter_ext(). */
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008943 vim_free(aucmd_win->w_localdir);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008944 aucmd_win->w_localdir = NULL;
8945 aco->globaldir = globaldir;
8946 globaldir = NULL;
8947
Bram Moolenaar071d4272004-06-13 20:20:40 +00008948
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008949#ifdef FEAT_WINDOWS
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008950 /* Split the current window, put the aucmd_win in the upper half.
8951 * We don't want the BufEnter or WinEnter autocommands. */
8952 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008953 make_snapshot(SNAP_AUCMD_IDX);
8954 save_ea = p_ea;
8955 p_ea = FALSE;
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008956
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008957# ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008958 /* Prevent chdir() call in win_enter_ext(), through do_autochdir(). */
8959 save_acd = p_acd;
8960 p_acd = FALSE;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008961# endif
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008962
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008963 (void)win_split_ins(0, WSP_TOP, aucmd_win, 0);
8964 (void)win_comp_pos(); /* recompute window positions */
8965 p_ea = save_ea;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008966# ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008967 p_acd = save_acd;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008968# endif
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008969 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008970#endif
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008971 curwin = aucmd_win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008972 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008973 curbuf = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008974 aco->new_curwin = curwin;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008975 set_bufref(&aco->new_curbuf, curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008976}
8977
8978/*
8979 * Cleanup after executing autocommands for a (hidden) buffer.
8980 * Restore the window as it was (if possible).
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00008981 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008982 */
8983 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008984aucmd_restbuf(
8985 aco_save_T *aco) /* structure holding saved values */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008986{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008987#ifdef FEAT_WINDOWS
8988 int dummy;
8989#endif
8990
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008991 if (aco->use_aucmd_win)
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008992 {
8993 --curbuf->b_nwindows;
8994#ifdef FEAT_WINDOWS
8995 /* Find "aucmd_win", it can't be closed, but it may be in another tab
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008996 * page. Do not trigger autocommands here. */
8997 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008998 if (curwin != aucmd_win)
8999 {
9000 tabpage_T *tp;
9001 win_T *wp;
9002
9003 FOR_ALL_TAB_WINDOWS(tp, wp)
9004 {
9005 if (wp == aucmd_win)
9006 {
9007 if (tp != curtab)
Bram Moolenaar49e649f2013-05-06 04:50:35 +02009008 goto_tabpage_tp(tp, TRUE, TRUE);
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009009 win_goto(aucmd_win);
Bram Moolenaar28f29082012-02-11 23:45:37 +01009010 goto win_found;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009011 }
9012 }
9013 }
Bram Moolenaar28f29082012-02-11 23:45:37 +01009014win_found:
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009015
9016 /* Remove the window and frame from the tree of frames. */
9017 (void)winframe_remove(curwin, &dummy, NULL);
9018 win_remove(curwin, NULL);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009019 aucmd_win_used = FALSE;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009020 last_status(FALSE); /* may need to remove last status line */
9021 restore_snapshot(SNAP_AUCMD_IDX, FALSE);
9022 (void)win_comp_pos(); /* recompute window positions */
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00009023 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009024
9025 if (win_valid(aco->save_curwin))
9026 curwin = aco->save_curwin;
9027 else
9028 /* Hmm, original window disappeared. Just use the first one. */
9029 curwin = firstwin;
9030# ifdef FEAT_EVAL
Bram Moolenaar429fa852013-04-15 12:27:36 +02009031 vars_clear(&aucmd_win->w_vars->dv_hashtab); /* free all w: variables */
9032 hash_init(&aucmd_win->w_vars->dv_hashtab); /* re-use the hashtab */
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009033# endif
9034#else
9035 curwin = aco->save_curwin;
9036#endif
9037 curbuf = curwin->w_buffer;
9038
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009039 vim_free(globaldir);
9040 globaldir = aco->globaldir;
9041
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009042 /* the buffer contents may have changed */
9043 check_cursor();
9044 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
9045 {
9046 curwin->w_topline = curbuf->b_ml.ml_line_count;
9047#ifdef FEAT_DIFF
9048 curwin->w_topfill = 0;
9049#endif
9050 }
9051#if defined(FEAT_GUI)
9052 /* Hide the scrollbars from the aucmd_win and update. */
9053 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_LEFT], FALSE);
9054 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_RIGHT], FALSE);
9055 gui_may_update_scrollbars();
9056#endif
9057 }
9058 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00009059 {
9060 /* restore curwin */
9061#ifdef FEAT_WINDOWS
9062 if (win_valid(aco->save_curwin))
9063#endif
9064 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009065 /* Restore the buffer which was previously edited by curwin, if
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009066 * it was changed, we are still the same window and the buffer is
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009067 * valid. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009068 if (curwin == aco->new_curwin
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009069 && curbuf != aco->new_curbuf.br_buf
9070 && bufref_valid(&aco->new_curbuf)
9071 && aco->new_curbuf.br_buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009072 {
Bram Moolenaar7da9c372012-04-30 17:04:52 +02009073# if defined(FEAT_SYN_HL) || defined(FEAT_SPELL)
9074 if (curwin->w_s == &curbuf->b_s)
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009075 curwin->w_s = &aco->new_curbuf.br_buf->b_s;
Bram Moolenaar7da9c372012-04-30 17:04:52 +02009076# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009077 --curbuf->b_nwindows;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009078 curbuf = aco->new_curbuf.br_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009079 curwin->w_buffer = curbuf;
9080 ++curbuf->b_nwindows;
9081 }
9082
9083 curwin = aco->save_curwin;
9084 curbuf = curwin->w_buffer;
Bram Moolenaar371932a2014-09-09 16:59:38 +02009085 /* In case the autocommand move the cursor to a position that that
9086 * not exist in curbuf. */
9087 check_cursor();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009088 }
9089 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009090}
9091
9092static int autocmd_nested = FALSE;
9093
9094/*
9095 * Execute autocommands for "event" and file name "fname".
9096 * Return TRUE if some commands were executed.
9097 */
9098 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009099apply_autocmds(
9100 event_T event,
9101 char_u *fname, /* NULL or empty means use actual file name */
9102 char_u *fname_io, /* fname to use for <afile> on cmdline */
9103 int force, /* when TRUE, ignore autocmd_busy */
9104 buf_T *buf) /* buffer for <abuf> */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009105{
9106 return apply_autocmds_group(event, fname, fname_io, force,
9107 AUGROUP_ALL, buf, NULL);
9108}
9109
9110/*
9111 * Like apply_autocmds(), but with extra "eap" argument. This takes care of
9112 * setting v:filearg.
9113 */
9114 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009115apply_autocmds_exarg(
9116 event_T event,
9117 char_u *fname,
9118 char_u *fname_io,
9119 int force,
9120 buf_T *buf,
9121 exarg_T *eap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009122{
9123 return apply_autocmds_group(event, fname, fname_io, force,
9124 AUGROUP_ALL, buf, eap);
9125}
9126
9127/*
9128 * Like apply_autocmds(), but handles the caller's retval. If the script
9129 * processing is being aborted or if retval is FAIL when inside a try
9130 * conditional, no autocommands are executed. If otherwise the autocommands
9131 * cause the script to be aborted, retval is set to FAIL.
9132 */
9133 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009134apply_autocmds_retval(
9135 event_T event,
9136 char_u *fname, /* NULL or empty means use actual file name */
9137 char_u *fname_io, /* fname to use for <afile> on cmdline */
9138 int force, /* when TRUE, ignore autocmd_busy */
9139 buf_T *buf, /* buffer for <abuf> */
9140 int *retval) /* pointer to caller's retval */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009141{
9142 int did_cmd;
9143
Bram Moolenaar1e015462005-09-25 22:16:38 +00009144#ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00009145 if (should_abort(*retval))
9146 return FALSE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00009147#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009148
9149 did_cmd = apply_autocmds_group(event, fname, fname_io, force,
9150 AUGROUP_ALL, buf, NULL);
Bram Moolenaar1e015462005-09-25 22:16:38 +00009151 if (did_cmd
9152#ifdef FEAT_EVAL
9153 && aborting()
9154#endif
9155 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00009156 *retval = FAIL;
9157 return did_cmd;
9158}
9159
Bram Moolenaard35f9712005-12-18 22:02:33 +00009160/*
9161 * Return TRUE when there is a CursorHold autocommand defined.
9162 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009163 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009164has_cursorhold(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009165{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009166 return (first_autopat[(int)(get_real_state() == NORMAL_BUSY
9167 ? EVENT_CURSORHOLD : EVENT_CURSORHOLDI)] != NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009168}
Bram Moolenaard35f9712005-12-18 22:02:33 +00009169
9170/*
9171 * Return TRUE if the CursorHold event can be triggered.
9172 */
9173 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009174trigger_cursorhold(void)
Bram Moolenaard35f9712005-12-18 22:02:33 +00009175{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009176 int state;
9177
Bram Moolenaar05334432011-07-20 18:29:39 +02009178 if (!did_cursorhold
9179 && has_cursorhold()
9180 && !Recording
9181 && typebuf.tb_len == 0
Bram Moolenaard29a9ee2006-09-14 09:07:34 +00009182#ifdef FEAT_INS_EXPAND
9183 && !ins_compl_active()
9184#endif
9185 )
Bram Moolenaar754b5602006-02-09 23:53:20 +00009186 {
9187 state = get_real_state();
9188 if (state == NORMAL_BUSY || (state & INSERT) != 0)
9189 return TRUE;
9190 }
9191 return FALSE;
Bram Moolenaard35f9712005-12-18 22:02:33 +00009192}
Bram Moolenaar754b5602006-02-09 23:53:20 +00009193
9194/*
9195 * Return TRUE when there is a CursorMoved autocommand defined.
9196 */
9197 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009198has_cursormoved(void)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009199{
9200 return (first_autopat[(int)EVENT_CURSORMOVED] != NULL);
9201}
9202
9203/*
9204 * Return TRUE when there is a CursorMovedI autocommand defined.
9205 */
9206 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009207has_cursormovedI(void)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009208{
9209 return (first_autopat[(int)EVENT_CURSORMOVEDI] != NULL);
9210}
Bram Moolenaar071d4272004-06-13 20:20:40 +00009211
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009212/*
Bram Moolenaar186628f2013-03-19 13:33:23 +01009213 * Return TRUE when there is a TextChanged autocommand defined.
9214 */
9215 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009216has_textchanged(void)
Bram Moolenaar186628f2013-03-19 13:33:23 +01009217{
9218 return (first_autopat[(int)EVENT_TEXTCHANGED] != NULL);
9219}
9220
9221/*
9222 * Return TRUE when there is a TextChangedI autocommand defined.
9223 */
9224 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009225has_textchangedI(void)
Bram Moolenaar186628f2013-03-19 13:33:23 +01009226{
9227 return (first_autopat[(int)EVENT_TEXTCHANGEDI] != NULL);
9228}
9229
9230/*
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009231 * Return TRUE when there is an InsertCharPre autocommand defined.
9232 */
9233 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009234has_insertcharpre(void)
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009235{
9236 return (first_autopat[(int)EVENT_INSERTCHARPRE] != NULL);
9237}
9238
Bram Moolenaard5005162014-08-22 23:05:54 +02009239/*
9240 * Return TRUE when there is an CmdUndefined autocommand defined.
9241 */
9242 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009243has_cmdundefined(void)
Bram Moolenaard5005162014-08-22 23:05:54 +02009244{
9245 return (first_autopat[(int)EVENT_CMDUNDEFINED] != NULL);
9246}
9247
9248/*
9249 * Return TRUE when there is an FuncUndefined autocommand defined.
9250 */
9251 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009252has_funcundefined(void)
Bram Moolenaard5005162014-08-22 23:05:54 +02009253{
9254 return (first_autopat[(int)EVENT_FUNCUNDEFINED] != NULL);
9255}
9256
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009257/*
9258 * Execute autocommands for "event" and file name "fname".
9259 * Return TRUE if some commands were executed.
9260 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009261 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009262apply_autocmds_group(
9263 event_T event,
9264 char_u *fname, /* NULL or empty means use actual file name */
9265 char_u *fname_io, /* fname to use for <afile> on cmdline, NULL means
Bram Moolenaar071d4272004-06-13 20:20:40 +00009266 use fname */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009267 int force, /* when TRUE, ignore autocmd_busy */
9268 int group, /* group ID, or AUGROUP_ALL */
9269 buf_T *buf, /* buffer for <abuf> */
9270 exarg_T *eap) /* command arguments */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009271{
9272 char_u *sfname = NULL; /* short file name */
9273 char_u *tail;
9274 int save_changed;
9275 buf_T *old_curbuf;
9276 int retval = FALSE;
9277 char_u *save_sourcing_name;
9278 linenr_T save_sourcing_lnum;
9279 char_u *save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009280 int save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009281 int save_autocmd_bufnr;
9282 char_u *save_autocmd_match;
9283 int save_autocmd_busy;
9284 int save_autocmd_nested;
9285 static int nesting = 0;
9286 AutoPatCmd patcmd;
9287 AutoPat *ap;
9288#ifdef FEAT_EVAL
9289 scid_T save_current_SID;
9290 void *save_funccalp;
9291 char_u *save_cmdarg;
9292 long save_cmdbang;
9293#endif
9294 static int filechangeshell_busy = FALSE;
Bram Moolenaar05159a02005-02-26 23:04:13 +00009295#ifdef FEAT_PROFILE
9296 proftime_T wait_time;
9297#endif
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009298 int did_save_redobuff = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009299
9300 /*
9301 * Quickly return if there are no autocommands for this event or
9302 * autocommands are blocked.
9303 */
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009304 if (first_autopat[(int)event] == NULL || autocmd_blocked > 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009305 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009306
9307 /*
9308 * When autocommands are busy, new autocommands are only executed when
9309 * explicitly enabled with the "nested" flag.
9310 */
9311 if (autocmd_busy && !(force || autocmd_nested))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009312 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009313
9314#ifdef FEAT_EVAL
9315 /*
Bram Moolenaar7263a772007-05-10 17:35:54 +00009316 * Quickly return when immediately aborting on error, or when an interrupt
Bram Moolenaar071d4272004-06-13 20:20:40 +00009317 * occurred or an exception was thrown but not caught.
9318 */
9319 if (aborting())
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009320 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009321#endif
9322
9323 /*
9324 * FileChangedShell never nests, because it can create an endless loop.
9325 */
Bram Moolenaar56718732006-03-15 22:53:57 +00009326 if (filechangeshell_busy && (event == EVENT_FILECHANGEDSHELL
9327 || event == EVENT_FILECHANGEDSHELLPOST))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009328 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009329
9330 /*
9331 * Ignore events in 'eventignore'.
9332 */
9333 if (event_ignored(event))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009334 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009335
9336 /*
9337 * Allow nesting of autocommands, but restrict the depth, because it's
9338 * possible to create an endless loop.
9339 */
9340 if (nesting == 10)
9341 {
9342 EMSG(_("E218: autocommand nesting too deep"));
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009343 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009344 }
9345
9346 /*
9347 * Check if these autocommands are disabled. Used when doing ":all" or
9348 * ":ball".
9349 */
9350 if ( (autocmd_no_enter
9351 && (event == EVENT_WINENTER || event == EVENT_BUFENTER))
9352 || (autocmd_no_leave
9353 && (event == EVENT_WINLEAVE || event == EVENT_BUFLEAVE)))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009354 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009355
9356 /*
9357 * Save the autocmd_* variables and info about the current buffer.
9358 */
9359 save_autocmd_fname = autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009360 save_autocmd_fname_full = autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009361 save_autocmd_bufnr = autocmd_bufnr;
9362 save_autocmd_match = autocmd_match;
9363 save_autocmd_busy = autocmd_busy;
9364 save_autocmd_nested = autocmd_nested;
9365 save_changed = curbuf->b_changed;
9366 old_curbuf = curbuf;
9367
9368 /*
9369 * Set the file name to be used for <afile>.
Bram Moolenaara0174af2008-01-02 20:08:25 +00009370 * Make a copy to avoid that changing a buffer name or directory makes it
9371 * invalid.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009372 */
9373 if (fname_io == NULL)
9374 {
Bram Moolenaar53744302015-07-17 17:38:22 +02009375 if (event == EVENT_COLORSCHEME || event == EVENT_OPTIONSET)
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009376 autocmd_fname = NULL;
9377 else if (fname != NULL && *fname != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009378 autocmd_fname = fname;
9379 else if (buf != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009380 autocmd_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009381 else
9382 autocmd_fname = NULL;
9383 }
9384 else
9385 autocmd_fname = fname_io;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009386 if (autocmd_fname != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009387 autocmd_fname = vim_strsave(autocmd_fname);
9388 autocmd_fname_full = FALSE; /* call FullName_save() later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009389
9390 /*
9391 * Set the buffer number to be used for <abuf>.
9392 */
9393 if (buf == NULL)
9394 autocmd_bufnr = 0;
9395 else
9396 autocmd_bufnr = buf->b_fnum;
9397
9398 /*
9399 * When the file name is NULL or empty, use the file name of buffer "buf".
9400 * Always use the full path of the file name to match with, in case
9401 * "allow_dirs" is set.
9402 */
9403 if (fname == NULL || *fname == NUL)
9404 {
9405 if (buf == NULL)
9406 fname = NULL;
9407 else
9408 {
9409#ifdef FEAT_SYN_HL
9410 if (event == EVENT_SYNTAX)
9411 fname = buf->b_p_syn;
9412 else
9413#endif
9414 if (event == EVENT_FILETYPE)
9415 fname = buf->b_p_ft;
9416 else
9417 {
9418 if (buf->b_sfname != NULL)
9419 sfname = vim_strsave(buf->b_sfname);
9420 fname = buf->b_ffname;
9421 }
9422 }
9423 if (fname == NULL)
9424 fname = (char_u *)"";
9425 fname = vim_strsave(fname); /* make a copy, so we can change it */
9426 }
9427 else
9428 {
9429 sfname = vim_strsave(fname);
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009430 /* Don't try expanding FileType, Syntax, FuncUndefined, WindowID,
9431 * ColorScheme or QuickFixCmd* */
Bram Moolenaar7c626922005-02-07 22:01:03 +00009432 if (event == EVENT_FILETYPE
9433 || event == EVENT_SYNTAX
Bram Moolenaar5135d462009-04-29 16:03:38 +00009434 || event == EVENT_FUNCUNDEFINED
Bram Moolenaar7c626922005-02-07 22:01:03 +00009435 || event == EVENT_REMOTEREPLY
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00009436 || event == EVENT_SPELLFILEMISSING
Bram Moolenaar7c626922005-02-07 22:01:03 +00009437 || event == EVENT_QUICKFIXCMDPRE
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009438 || event == EVENT_COLORSCHEME
Bram Moolenaar53744302015-07-17 17:38:22 +02009439 || event == EVENT_OPTIONSET
Bram Moolenaar7c626922005-02-07 22:01:03 +00009440 || event == EVENT_QUICKFIXCMDPOST)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009441 fname = vim_strsave(fname);
9442 else
9443 fname = FullName_save(fname, FALSE);
9444 }
9445 if (fname == NULL) /* out of memory */
9446 {
9447 vim_free(sfname);
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009448 retval = FALSE;
9449 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009450 }
9451
9452#ifdef BACKSLASH_IN_FILENAME
9453 /*
9454 * Replace all backslashes with forward slashes. This makes the
9455 * autocommand patterns portable between Unix and MS-DOS.
9456 */
9457 if (sfname != NULL)
9458 forward_slash(sfname);
9459 forward_slash(fname);
9460#endif
9461
9462#ifdef VMS
9463 /* remove version for correct match */
9464 if (sfname != NULL)
9465 vms_remove_version(sfname);
9466 vms_remove_version(fname);
9467#endif
9468
9469 /*
9470 * Set the name to be used for <amatch>.
9471 */
9472 autocmd_match = fname;
9473
9474
9475 /* Don't redraw while doing auto commands. */
9476 ++RedrawingDisabled;
9477 save_sourcing_name = sourcing_name;
9478 sourcing_name = NULL; /* don't free this one */
9479 save_sourcing_lnum = sourcing_lnum;
9480 sourcing_lnum = 0; /* no line number here */
9481
9482#ifdef FEAT_EVAL
9483 save_current_SID = current_SID;
9484
Bram Moolenaar05159a02005-02-26 23:04:13 +00009485# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009486 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009487 prof_child_enter(&wait_time); /* doesn't count for the caller itself */
9488# endif
9489
Bram Moolenaar071d4272004-06-13 20:20:40 +00009490 /* Don't use local function variables, if called from a function */
9491 save_funccalp = save_funccal();
9492#endif
9493
9494 /*
9495 * When starting to execute autocommands, save the search patterns.
9496 */
9497 if (!autocmd_busy)
9498 {
9499 save_search_patterns();
Bram Moolenaar20ad69c2015-12-03 13:52:52 +01009500#ifdef FEAT_INS_EXPAND
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009501 if (!ins_compl_active())
Bram Moolenaar20ad69c2015-12-03 13:52:52 +01009502#endif
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009503 {
9504 saveRedobuff();
9505 did_save_redobuff = TRUE;
9506 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009507 did_filetype = keep_filetype;
9508 }
9509
9510 /*
9511 * Note that we are applying autocmds. Some commands need to know.
9512 */
9513 autocmd_busy = TRUE;
9514 filechangeshell_busy = (event == EVENT_FILECHANGEDSHELL);
9515 ++nesting; /* see matching decrement below */
9516
9517 /* Remember that FileType was triggered. Used for did_filetype(). */
9518 if (event == EVENT_FILETYPE)
9519 did_filetype = TRUE;
9520
9521 tail = gettail(fname);
9522
9523 /* Find first autocommand that matches */
9524 patcmd.curpat = first_autopat[(int)event];
9525 patcmd.nextcmd = NULL;
9526 patcmd.group = group;
9527 patcmd.fname = fname;
9528 patcmd.sfname = sfname;
9529 patcmd.tail = tail;
9530 patcmd.event = event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009531 patcmd.arg_bufnr = autocmd_bufnr;
9532 patcmd.next = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009533 auto_next_pat(&patcmd, FALSE);
9534
9535 /* found one, start executing the autocommands */
9536 if (patcmd.curpat != NULL)
9537 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009538 /* add to active_apc_list */
9539 patcmd.next = active_apc_list;
9540 active_apc_list = &patcmd;
9541
Bram Moolenaar071d4272004-06-13 20:20:40 +00009542#ifdef FEAT_EVAL
9543 /* set v:cmdarg (only when there is a matching pattern) */
Bram Moolenaar22fcfad2016-07-01 18:17:26 +02009544 save_cmdbang = (long)get_vim_var_nr(VV_CMDBANG);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009545 if (eap != NULL)
9546 {
9547 save_cmdarg = set_cmdarg(eap, NULL);
9548 set_vim_var_nr(VV_CMDBANG, (long)eap->forceit);
9549 }
9550 else
9551 save_cmdarg = NULL; /* avoid gcc warning */
9552#endif
9553 retval = TRUE;
9554 /* mark the last pattern, to avoid an endless loop when more patterns
9555 * are added when executing autocommands */
9556 for (ap = patcmd.curpat; ap->next != NULL; ap = ap->next)
9557 ap->last = FALSE;
9558 ap->last = TRUE;
9559 check_lnums(TRUE); /* make sure cursor and topline are valid */
9560 do_cmdline(NULL, getnextac, (void *)&patcmd,
9561 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
9562#ifdef FEAT_EVAL
9563 if (eap != NULL)
9564 {
9565 (void)set_cmdarg(NULL, save_cmdarg);
9566 set_vim_var_nr(VV_CMDBANG, save_cmdbang);
9567 }
9568#endif
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009569 /* delete from active_apc_list */
9570 if (active_apc_list == &patcmd) /* just in case */
9571 active_apc_list = patcmd.next;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009572 }
9573
9574 --RedrawingDisabled;
9575 autocmd_busy = save_autocmd_busy;
9576 filechangeshell_busy = FALSE;
9577 autocmd_nested = save_autocmd_nested;
9578 vim_free(sourcing_name);
9579 sourcing_name = save_sourcing_name;
9580 sourcing_lnum = save_sourcing_lnum;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009581 vim_free(autocmd_fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009582 autocmd_fname = save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009583 autocmd_fname_full = save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009584 autocmd_bufnr = save_autocmd_bufnr;
9585 autocmd_match = save_autocmd_match;
9586#ifdef FEAT_EVAL
9587 current_SID = save_current_SID;
9588 restore_funccal(save_funccalp);
Bram Moolenaar05159a02005-02-26 23:04:13 +00009589# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009590 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009591 prof_child_exit(&wait_time);
9592# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009593#endif
9594 vim_free(fname);
9595 vim_free(sfname);
9596 --nesting; /* see matching increment above */
9597
9598 /*
9599 * When stopping to execute autocommands, restore the search patterns and
Bram Moolenaar3be85852014-06-12 14:01:31 +02009600 * the redo buffer. Free any buffers in the au_pending_free_buf list and
9601 * free any windows in the au_pending_free_win list.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009602 */
9603 if (!autocmd_busy)
9604 {
9605 restore_search_patterns();
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009606 if (did_save_redobuff)
9607 restoreRedobuff();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009608 did_filetype = FALSE;
Bram Moolenaar4c7ab1b2014-04-06 20:45:43 +02009609 while (au_pending_free_buf != NULL)
9610 {
9611 buf_T *b = au_pending_free_buf->b_next;
9612 vim_free(au_pending_free_buf);
9613 au_pending_free_buf = b;
9614 }
Bram Moolenaar3be85852014-06-12 14:01:31 +02009615 while (au_pending_free_win != NULL)
9616 {
9617 win_T *w = au_pending_free_win->w_next;
9618 vim_free(au_pending_free_win);
9619 au_pending_free_win = w;
9620 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009621 }
9622
9623 /*
9624 * Some events don't set or reset the Changed flag.
9625 * Check if still in the same buffer!
9626 */
9627 if (curbuf == old_curbuf
9628 && (event == EVENT_BUFREADPOST
9629 || event == EVENT_BUFWRITEPOST
9630 || event == EVENT_FILEAPPENDPOST
9631 || event == EVENT_VIMLEAVE
9632 || event == EVENT_VIMLEAVEPRE))
9633 {
9634#ifdef FEAT_TITLE
9635 if (curbuf->b_changed != save_changed)
9636 need_maketitle = TRUE;
9637#endif
9638 curbuf->b_changed = save_changed;
9639 }
9640
9641 au_cleanup(); /* may really delete removed patterns/commands now */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009642
9643BYPASS_AU:
9644 /* When wiping out a buffer make sure all its buffer-local autocommands
9645 * are deleted. */
9646 if (event == EVENT_BUFWIPEOUT && buf != NULL)
9647 aubuflocal_remove(buf);
9648
Bram Moolenaarc3691332016-04-20 12:49:49 +02009649 if (retval == OK && event == EVENT_FILETYPE)
9650 au_did_filetype = TRUE;
9651
Bram Moolenaar071d4272004-06-13 20:20:40 +00009652 return retval;
9653}
9654
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009655# ifdef FEAT_EVAL
9656static char_u *old_termresponse = NULL;
9657# endif
9658
9659/*
9660 * Block triggering autocommands until unblock_autocmd() is called.
9661 * Can be used recursively, so long as it's symmetric.
9662 */
9663 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009664block_autocmds(void)
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009665{
9666# ifdef FEAT_EVAL
9667 /* Remember the value of v:termresponse. */
9668 if (autocmd_blocked == 0)
9669 old_termresponse = get_vim_var_str(VV_TERMRESPONSE);
9670# endif
9671 ++autocmd_blocked;
9672}
9673
9674 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009675unblock_autocmds(void)
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009676{
9677 --autocmd_blocked;
9678
9679# ifdef FEAT_EVAL
9680 /* When v:termresponse was set while autocommands were blocked, trigger
9681 * the autocommands now. Esp. useful when executing a shell command
9682 * during startup (vimdiff). */
9683 if (autocmd_blocked == 0
9684 && get_vim_var_str(VV_TERMRESPONSE) != old_termresponse)
9685 apply_autocmds(EVENT_TERMRESPONSE, NULL, NULL, FALSE, curbuf);
9686# endif
9687}
9688
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009689 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009690is_autocmd_blocked(void)
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009691{
9692 return autocmd_blocked != 0;
9693}
9694
Bram Moolenaar071d4272004-06-13 20:20:40 +00009695/*
9696 * Find next autocommand pattern that matches.
9697 */
9698 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009699auto_next_pat(
9700 AutoPatCmd *apc,
9701 int stop_at_last) /* stop when 'last' flag is set */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009702{
9703 AutoPat *ap;
9704 AutoCmd *cp;
9705 char_u *name;
9706 char *s;
9707
9708 vim_free(sourcing_name);
9709 sourcing_name = NULL;
9710
9711 for (ap = apc->curpat; ap != NULL && !got_int; ap = ap->next)
9712 {
9713 apc->curpat = NULL;
9714
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009715 /* Only use a pattern when it has not been removed, has commands and
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009716 * the group matches. For buffer-local autocommands only check the
9717 * buffer number. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009718 if (ap->pat != NULL && ap->cmds != NULL
9719 && (apc->group == AUGROUP_ALL || apc->group == ap->group))
9720 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009721 /* execution-condition */
9722 if (ap->buflocal_nr == 0
Bram Moolenaardffa5b82014-11-19 16:38:07 +01009723 ? (match_file_pat(NULL, &ap->reg_prog, apc->fname,
Bram Moolenaar748bf032005-02-02 23:04:36 +00009724 apc->sfname, apc->tail, ap->allow_dirs))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009725 : ap->buflocal_nr == apc->arg_bufnr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009726 {
9727 name = event_nr2name(apc->event);
9728 s = _("%s Auto commands for \"%s\"");
9729 sourcing_name = alloc((unsigned)(STRLEN(s)
9730 + STRLEN(name) + ap->patlen + 1));
9731 if (sourcing_name != NULL)
9732 {
9733 sprintf((char *)sourcing_name, s,
9734 (char *)name, (char *)ap->pat);
9735 if (p_verbose >= 8)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009736 {
9737 verbose_enter();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009738 smsg((char_u *)_("Executing %s"), sourcing_name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009739 verbose_leave();
9740 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009741 }
9742
9743 apc->curpat = ap;
9744 apc->nextcmd = ap->cmds;
9745 /* mark last command */
9746 for (cp = ap->cmds; cp->next != NULL; cp = cp->next)
9747 cp->last = FALSE;
9748 cp->last = TRUE;
9749 }
9750 line_breakcheck();
9751 if (apc->curpat != NULL) /* found a match */
9752 break;
9753 }
9754 if (stop_at_last && ap->last)
9755 break;
9756 }
9757}
9758
9759/*
9760 * Get next autocommand command.
9761 * Called by do_cmdline() to get the next line for ":if".
9762 * Returns allocated string, or NULL for end of autocommands.
9763 */
Bram Moolenaar21691f82012-12-05 19:13:18 +01009764 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009765getnextac(int c UNUSED, void *cookie, int indent UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009766{
9767 AutoPatCmd *acp = (AutoPatCmd *)cookie;
9768 char_u *retval;
9769 AutoCmd *ac;
9770
9771 /* Can be called again after returning the last line. */
9772 if (acp->curpat == NULL)
9773 return NULL;
9774
9775 /* repeat until we find an autocommand to execute */
9776 for (;;)
9777 {
9778 /* skip removed commands */
9779 while (acp->nextcmd != NULL && acp->nextcmd->cmd == NULL)
9780 if (acp->nextcmd->last)
9781 acp->nextcmd = NULL;
9782 else
9783 acp->nextcmd = acp->nextcmd->next;
9784
9785 if (acp->nextcmd != NULL)
9786 break;
9787
9788 /* at end of commands, find next pattern that matches */
9789 if (acp->curpat->last)
9790 acp->curpat = NULL;
9791 else
9792 acp->curpat = acp->curpat->next;
9793 if (acp->curpat != NULL)
9794 auto_next_pat(acp, TRUE);
9795 if (acp->curpat == NULL)
9796 return NULL;
9797 }
9798
9799 ac = acp->nextcmd;
9800
9801 if (p_verbose >= 9)
9802 {
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009803 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009804 smsg((char_u *)_("autocommand %s"), ac->cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009805 msg_puts((char_u *)"\n"); /* don't overwrite this either */
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009806 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009807 }
9808 retval = vim_strsave(ac->cmd);
9809 autocmd_nested = ac->nested;
9810#ifdef FEAT_EVAL
9811 current_SID = ac->scriptID;
9812#endif
9813 if (ac->last)
9814 acp->nextcmd = NULL;
9815 else
9816 acp->nextcmd = ac->next;
9817 return retval;
9818}
9819
9820/*
9821 * Return TRUE if there is a matching autocommand for "fname".
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009822 * To account for buffer-local autocommands, function needs to know
9823 * in which buffer the file will be opened.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009824 */
9825 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009826has_autocmd(event_T event, char_u *sfname, buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009827{
9828 AutoPat *ap;
9829 char_u *fname;
9830 char_u *tail = gettail(sfname);
9831 int retval = FALSE;
9832
9833 fname = FullName_save(sfname, FALSE);
9834 if (fname == NULL)
9835 return FALSE;
9836
9837#ifdef BACKSLASH_IN_FILENAME
9838 /*
9839 * Replace all backslashes with forward slashes. This makes the
9840 * autocommand patterns portable between Unix and MS-DOS.
9841 */
9842 sfname = vim_strsave(sfname);
9843 if (sfname != NULL)
9844 forward_slash(sfname);
9845 forward_slash(fname);
9846#endif
9847
9848 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
9849 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009850 && (ap->buflocal_nr == 0
Bram Moolenaardffa5b82014-11-19 16:38:07 +01009851 ? match_file_pat(NULL, &ap->reg_prog,
Bram Moolenaar748bf032005-02-02 23:04:36 +00009852 fname, sfname, tail, ap->allow_dirs)
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009853 : buf != NULL && ap->buflocal_nr == buf->b_fnum
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009854 ))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009855 {
9856 retval = TRUE;
9857 break;
9858 }
9859
9860 vim_free(fname);
9861#ifdef BACKSLASH_IN_FILENAME
9862 vim_free(sfname);
9863#endif
9864
9865 return retval;
9866}
9867
9868#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
9869/*
9870 * Function given to ExpandGeneric() to obtain the list of autocommand group
9871 * names.
9872 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009873 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009874get_augroup_name(expand_T *xp UNUSED, int idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009875{
9876 if (idx == augroups.ga_len) /* add "END" add the end */
9877 return (char_u *)"END";
9878 if (idx >= augroups.ga_len) /* end of list */
9879 return NULL;
Bram Moolenaarb62cc362016-09-03 16:43:53 +02009880 if (AUGROUP_NAME(idx) == NULL || AUGROUP_NAME(idx) == get_deleted_augroup())
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02009881 /* skip deleted entries */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009882 return (char_u *)"";
9883 return AUGROUP_NAME(idx); /* return a name */
9884}
9885
9886static int include_groups = FALSE;
9887
9888 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009889set_context_in_autocmd(
9890 expand_T *xp,
9891 char_u *arg,
9892 int doautocmd) /* TRUE for :doauto*, FALSE for :autocmd */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009893{
9894 char_u *p;
9895 int group;
9896
9897 /* check for a group name, skip it if present */
9898 include_groups = FALSE;
9899 p = arg;
9900 group = au_get_grouparg(&arg);
9901 if (group == AUGROUP_ERROR)
9902 return NULL;
9903 /* If there only is a group name that's what we expand. */
9904 if (*arg == NUL && group != AUGROUP_ALL && !vim_iswhite(arg[-1]))
9905 {
9906 arg = p;
9907 group = AUGROUP_ALL;
9908 }
9909
9910 /* skip over event name */
9911 for (p = arg; *p != NUL && !vim_iswhite(*p); ++p)
9912 if (*p == ',')
9913 arg = p + 1;
9914 if (*p == NUL)
9915 {
9916 if (group == AUGROUP_ALL)
9917 include_groups = TRUE;
9918 xp->xp_context = EXPAND_EVENTS; /* expand event name */
9919 xp->xp_pattern = arg;
9920 return NULL;
9921 }
9922
9923 /* skip over pattern */
9924 arg = skipwhite(p);
9925 while (*arg && (!vim_iswhite(*arg) || arg[-1] == '\\'))
9926 arg++;
9927 if (*arg)
9928 return arg; /* expand (next) command */
9929
9930 if (doautocmd)
9931 xp->xp_context = EXPAND_FILES; /* expand file names */
9932 else
9933 xp->xp_context = EXPAND_NOTHING; /* pattern is not expanded */
9934 return NULL;
9935}
9936
9937/*
9938 * Function given to ExpandGeneric() to obtain the list of event names.
9939 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009940 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009941get_event_name(expand_T *xp UNUSED, int idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009942{
9943 if (idx < augroups.ga_len) /* First list group names, if wanted */
9944 {
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02009945 if (!include_groups || AUGROUP_NAME(idx) == NULL
Bram Moolenaarb62cc362016-09-03 16:43:53 +02009946 || AUGROUP_NAME(idx) == get_deleted_augroup())
Bram Moolenaar071d4272004-06-13 20:20:40 +00009947 return (char_u *)""; /* skip deleted entries */
9948 return AUGROUP_NAME(idx); /* return a name */
9949 }
9950 return (char_u *)event_names[idx - augroups.ga_len].name;
9951}
9952
9953#endif /* FEAT_CMDL_COMPL */
9954
9955/*
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009956 * Return TRUE if autocmd is supported.
9957 */
9958 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009959autocmd_supported(char_u *name)
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009960{
9961 char_u *p;
9962
9963 return (event_name2nr(name, &p) != NUM_EVENTS);
9964}
9965
9966/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00009967 * Return TRUE if an autocommand is defined for a group, event and
9968 * pattern: The group can be omitted to accept any group. "event" and "pattern"
9969 * can be NULL to accept any event and pattern. "pattern" can be NULL to accept
9970 * any pattern. Buffer-local patterns <buffer> or <buffer=N> are accepted.
9971 * Used for:
9972 * exists("#Group") or
9973 * exists("#Group#Event") or
9974 * exists("#Group#Event#pat") or
9975 * exists("#Event") or
9976 * exists("#Event#pat")
Bram Moolenaar071d4272004-06-13 20:20:40 +00009977 */
9978 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009979au_exists(char_u *arg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009980{
Bram Moolenaar195d6352005-12-19 22:08:24 +00009981 char_u *arg_save;
9982 char_u *pattern = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009983 char_u *event_name;
9984 char_u *p;
Bram Moolenaar754b5602006-02-09 23:53:20 +00009985 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009986 AutoPat *ap;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009987 buf_T *buflocal_buf = NULL;
Bram Moolenaar195d6352005-12-19 22:08:24 +00009988 int group;
9989 int retval = FALSE;
9990
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009991 /* Make a copy so that we can change the '#' chars to a NUL. */
Bram Moolenaar195d6352005-12-19 22:08:24 +00009992 arg_save = vim_strsave(arg);
9993 if (arg_save == NULL)
9994 return FALSE;
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009995 p = vim_strchr(arg_save, '#');
Bram Moolenaar195d6352005-12-19 22:08:24 +00009996 if (p != NULL)
9997 *p++ = NUL;
9998
9999 /* First, look for an autocmd group name */
10000 group = au_find_group(arg_save);
10001 if (group == AUGROUP_ERROR)
10002 {
10003 /* Didn't match a group name, assume the first argument is an event. */
10004 group = AUGROUP_ALL;
10005 event_name = arg_save;
10006 }
10007 else
10008 {
10009 if (p == NULL)
10010 {
10011 /* "Group": group name is present and it's recognized */
10012 retval = TRUE;
10013 goto theend;
10014 }
10015
10016 /* Must be "Group#Event" or "Group#Event#pat". */
10017 event_name = p;
10018 p = vim_strchr(event_name, '#');
10019 if (p != NULL)
10020 *p++ = NUL; /* "Group#Event#pat" */
10021 }
10022
10023 pattern = p; /* "pattern" is NULL when there is no pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010024
10025 /* find the index (enum) for the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010026 event = event_name2nr(event_name, &p);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010027
10028 /* return FALSE if the event name is not recognized */
Bram Moolenaar195d6352005-12-19 22:08:24 +000010029 if (event == NUM_EVENTS)
10030 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010031
10032 /* Find the first autocommand for this event.
10033 * If there isn't any, return FALSE;
10034 * If there is one and no pattern given, return TRUE; */
10035 ap = first_autopat[(int)event];
10036 if (ap == NULL)
Bram Moolenaar195d6352005-12-19 22:08:24 +000010037 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010038
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010039 /* if pattern is "<buffer>", special handling is needed which uses curbuf */
10040 /* for pattern "<buffer=N>, fnamecmp() will work fine */
Bram Moolenaar5b7880d2009-09-11 15:24:31 +000010041 if (pattern != NULL && STRICMP(pattern, "<buffer>") == 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010042 buflocal_buf = curbuf;
10043
Bram Moolenaar071d4272004-06-13 20:20:40 +000010044 /* Check if there is an autocommand with the given pattern. */
10045 for ( ; ap != NULL; ap = ap->next)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010046 /* only use a pattern when it has not been removed and has commands. */
10047 /* For buffer-local autocommands, fnamecmp() works fine. */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010048 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaar195d6352005-12-19 22:08:24 +000010049 && (group == AUGROUP_ALL || ap->group == group)
Bram Moolenaar5b7880d2009-09-11 15:24:31 +000010050 && (pattern == NULL
10051 || (buflocal_buf == NULL
10052 ? fnamecmp(ap->pat, pattern) == 0
10053 : ap->buflocal_nr == buflocal_buf->b_fnum)))
Bram Moolenaar195d6352005-12-19 22:08:24 +000010054 {
10055 retval = TRUE;
10056 break;
10057 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010058
Bram Moolenaar195d6352005-12-19 22:08:24 +000010059theend:
10060 vim_free(arg_save);
10061 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010062}
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010063
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010064#else /* FEAT_AUTOCMD */
10065
10066/*
10067 * Prepare for executing commands for (hidden) buffer "buf".
10068 * This is the non-autocommand version, it simply saves "curbuf" and sets
10069 * "curbuf" and "curwin" to match "buf".
10070 */
10071 void
Bram Moolenaard14e00e2016-01-31 17:30:51 +010010072aucmd_prepbuf(
10073 aco_save_T *aco, /* structure to save values in */
10074 buf_T *buf) /* new curbuf */
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010075{
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010076 aco->save_curbuf = curbuf;
10077 --curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010078 curbuf = buf;
10079 curwin->w_buffer = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010080 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010081}
10082
10083/*
10084 * Restore after executing commands for a (hidden) buffer.
10085 * This is the non-autocommand version.
10086 */
10087 void
Bram Moolenaard14e00e2016-01-31 17:30:51 +010010088aucmd_restbuf(
10089 aco_save_T *aco) /* structure holding saved values */
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010090{
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010091 --curbuf->b_nwindows;
10092 curbuf = aco->save_curbuf;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010093 curwin->w_buffer = curbuf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010094 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010095}
10096
Bram Moolenaar071d4272004-06-13 20:20:40 +000010097#endif /* FEAT_AUTOCMD */
10098
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010099
Bram Moolenaar071d4272004-06-13 20:20:40 +000010100#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN) || defined(PROTO)
10101/*
Bram Moolenaar748bf032005-02-02 23:04:36 +000010102 * Try matching a filename with a "pattern" ("prog" is NULL), or use the
10103 * precompiled regprog "prog" ("pattern" is NULL). That avoids calling
10104 * vim_regcomp() often.
Bram Moolenaar071d4272004-06-13 20:20:40 +000010105 * Used for autocommands and 'wildignore'.
10106 * Returns TRUE if there is a match, FALSE otherwise.
10107 */
Bram Moolenaardffa5b82014-11-19 16:38:07 +010010108 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010109match_file_pat(
10110 char_u *pattern, /* pattern to match with */
10111 regprog_T **prog, /* pre-compiled regprog or NULL */
10112 char_u *fname, /* full path of file name */
10113 char_u *sfname, /* short file name or NULL */
10114 char_u *tail, /* tail of path */
10115 int allow_dirs) /* allow matching with dir */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010116{
10117 regmatch_T regmatch;
10118 int result = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010119
Bram Moolenaar71afbfe2013-03-19 16:49:16 +010010120 regmatch.rm_ic = p_fic; /* ignore case if 'fileignorecase' is set */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010121 if (prog != NULL)
10122 regmatch.regprog = *prog;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010123 else
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010124 regmatch.regprog = vim_regcomp(pattern, RE_MAGIC);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010125
10126 /*
10127 * Try for a match with the pattern with:
10128 * 1. the full file name, when the pattern has a '/'.
10129 * 2. the short file name, when the pattern has a '/'.
10130 * 3. the tail of the file name, when the pattern has no '/'.
10131 */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010132 if (regmatch.regprog != NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +000010133 && ((allow_dirs
10134 && (vim_regexec(&regmatch, fname, (colnr_T)0)
10135 || (sfname != NULL
10136 && vim_regexec(&regmatch, sfname, (colnr_T)0))))
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010137 || (!allow_dirs && vim_regexec(&regmatch, tail, (colnr_T)0))))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010138 result = TRUE;
10139
Bram Moolenaardffa5b82014-11-19 16:38:07 +010010140 if (prog != NULL)
10141 *prog = regmatch.regprog;
10142 else
Bram Moolenaar473de612013-06-08 18:19:48 +020010143 vim_regfree(regmatch.regprog);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010144 return result;
10145}
10146#endif
10147
10148#if defined(FEAT_WILDIGN) || defined(PROTO)
10149/*
10150 * Return TRUE if a file matches with a pattern in "list".
10151 * "list" is a comma-separated list of patterns, like 'wildignore'.
10152 * "sfname" is the short file name or NULL, "ffname" the long file name.
10153 */
10154 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010155match_file_list(char_u *list, char_u *sfname, char_u *ffname)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010156{
10157 char_u buf[100];
10158 char_u *tail;
10159 char_u *regpat;
10160 char allow_dirs;
10161 int match;
10162 char_u *p;
10163
10164 tail = gettail(sfname);
10165
10166 /* try all patterns in 'wildignore' */
10167 p = list;
10168 while (*p)
10169 {
10170 copy_option_part(&p, buf, 100, ",");
10171 regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, FALSE);
10172 if (regpat == NULL)
10173 break;
Bram Moolenaar748bf032005-02-02 23:04:36 +000010174 match = match_file_pat(regpat, NULL, ffname, sfname,
10175 tail, (int)allow_dirs);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010176 vim_free(regpat);
10177 if (match)
10178 return TRUE;
10179 }
10180 return FALSE;
10181}
10182#endif
10183
10184/*
10185 * Convert the given pattern "pat" which has shell style wildcards in it, into
10186 * a regular expression, and return the result in allocated memory. If there
10187 * is a directory path separator to be matched, then TRUE is put in
10188 * allow_dirs, otherwise FALSE is put there -- webb.
10189 * Handle backslashes before special characters, like "\*" and "\ ".
10190 *
Bram Moolenaar071d4272004-06-13 20:20:40 +000010191 * Returns NULL when out of memory.
10192 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010193 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010194file_pat_to_reg_pat(
10195 char_u *pat,
10196 char_u *pat_end, /* first char after pattern or NULL */
10197 char *allow_dirs, /* Result passed back out in here */
10198 int no_bslash UNUSED) /* Don't use a backward slash as pathsep */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010199{
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010200 int size = 2; /* '^' at start, '$' at end */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010201 char_u *endp;
10202 char_u *reg_pat;
10203 char_u *p;
10204 int i;
10205 int nested = 0;
10206 int add_dollar = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010207
10208 if (allow_dirs != NULL)
10209 *allow_dirs = FALSE;
10210 if (pat_end == NULL)
10211 pat_end = pat + STRLEN(pat);
10212
Bram Moolenaar071d4272004-06-13 20:20:40 +000010213 for (p = pat; p < pat_end; p++)
10214 {
10215 switch (*p)
10216 {
10217 case '*':
10218 case '.':
10219 case ',':
10220 case '{':
10221 case '}':
10222 case '~':
10223 size += 2; /* extra backslash */
10224 break;
10225#ifdef BACKSLASH_IN_FILENAME
10226 case '\\':
10227 case '/':
10228 size += 4; /* could become "[\/]" */
10229 break;
10230#endif
10231 default:
10232 size++;
Bram Moolenaar2288afe2015-08-11 16:20:05 +020010233# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010234 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010235 {
10236 ++p;
10237 ++size;
10238 }
10239# endif
10240 break;
10241 }
10242 }
10243 reg_pat = alloc(size + 1);
10244 if (reg_pat == NULL)
10245 return NULL;
10246
Bram Moolenaar071d4272004-06-13 20:20:40 +000010247 i = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010248
10249 if (pat[0] == '*')
10250 while (pat[0] == '*' && pat < pat_end - 1)
10251 pat++;
10252 else
10253 reg_pat[i++] = '^';
10254 endp = pat_end - 1;
Bram Moolenaar8fee8782015-08-11 18:45:48 +020010255 if (endp >= pat && *endp == '*')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010256 {
10257 while (endp - pat > 0 && *endp == '*')
10258 endp--;
10259 add_dollar = FALSE;
10260 }
10261 for (p = pat; *p && nested >= 0 && p <= endp; p++)
10262 {
10263 switch (*p)
10264 {
10265 case '*':
10266 reg_pat[i++] = '.';
10267 reg_pat[i++] = '*';
Bram Moolenaar02743632005-07-25 20:42:36 +000010268 while (p[1] == '*') /* "**" matches like "*" */
10269 ++p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010270 break;
10271 case '.':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010272 case '~':
10273 reg_pat[i++] = '\\';
10274 reg_pat[i++] = *p;
10275 break;
10276 case '?':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010277 reg_pat[i++] = '.';
10278 break;
10279 case '\\':
10280 if (p[1] == NUL)
10281 break;
10282#ifdef BACKSLASH_IN_FILENAME
10283 if (!no_bslash)
10284 {
10285 /* translate:
10286 * "\x" to "\\x" e.g., "dir\file"
10287 * "\*" to "\\.*" e.g., "dir\*.c"
10288 * "\?" to "\\." e.g., "dir\??.c"
10289 * "\+" to "\+" e.g., "fileX\+.c"
10290 */
10291 if ((vim_isfilec(p[1]) || p[1] == '*' || p[1] == '?')
10292 && p[1] != '+')
10293 {
10294 reg_pat[i++] = '[';
10295 reg_pat[i++] = '\\';
10296 reg_pat[i++] = '/';
10297 reg_pat[i++] = ']';
10298 if (allow_dirs != NULL)
10299 *allow_dirs = TRUE;
10300 break;
10301 }
10302 }
10303#endif
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010304 /* Undo escaping from ExpandEscape():
10305 * foo\?bar -> foo?bar
10306 * foo\%bar -> foo%bar
10307 * foo\,bar -> foo,bar
10308 * foo\ bar -> foo bar
10309 * Don't unescape \, * and others that are also special in a
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010310 * regexp.
10311 * An escaped { must be unescaped since we use magic not
Bram Moolenaara946afe2013-08-02 15:22:39 +020010312 * verymagic. Use "\\\{n,m\}"" to get "\{n,m}".
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010313 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010314 if (*++p == '?'
10315#ifdef BACKSLASH_IN_FILENAME
10316 && no_bslash
10317#endif
10318 )
10319 reg_pat[i++] = '?';
10320 else
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010321 if (*p == ',' || *p == '%' || *p == '#'
Bram Moolenaar2288afe2015-08-11 16:20:05 +020010322 || vim_isspace(*p) || *p == '{' || *p == '}')
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010323 reg_pat[i++] = *p;
Bram Moolenaara946afe2013-08-02 15:22:39 +020010324 else if (*p == '\\' && p[1] == '\\' && p[2] == '{')
10325 {
10326 reg_pat[i++] = '\\';
10327 reg_pat[i++] = '{';
10328 p += 2;
10329 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010330 else
10331 {
10332 if (allow_dirs != NULL && vim_ispathsep(*p)
10333#ifdef BACKSLASH_IN_FILENAME
10334 && (!no_bslash || *p != '\\')
10335#endif
10336 )
10337 *allow_dirs = TRUE;
10338 reg_pat[i++] = '\\';
10339 reg_pat[i++] = *p;
10340 }
10341 break;
10342#ifdef BACKSLASH_IN_FILENAME
10343 case '/':
10344 reg_pat[i++] = '[';
10345 reg_pat[i++] = '\\';
10346 reg_pat[i++] = '/';
10347 reg_pat[i++] = ']';
10348 if (allow_dirs != NULL)
10349 *allow_dirs = TRUE;
10350 break;
10351#endif
10352 case '{':
10353 reg_pat[i++] = '\\';
10354 reg_pat[i++] = '(';
10355 nested++;
10356 break;
10357 case '}':
10358 reg_pat[i++] = '\\';
10359 reg_pat[i++] = ')';
10360 --nested;
10361 break;
10362 case ',':
10363 if (nested)
10364 {
10365 reg_pat[i++] = '\\';
10366 reg_pat[i++] = '|';
10367 }
10368 else
10369 reg_pat[i++] = ',';
10370 break;
10371 default:
10372# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010373 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010374 reg_pat[i++] = *p++;
10375 else
10376# endif
10377 if (allow_dirs != NULL && vim_ispathsep(*p))
10378 *allow_dirs = TRUE;
10379 reg_pat[i++] = *p;
10380 break;
10381 }
10382 }
10383 if (add_dollar)
10384 reg_pat[i++] = '$';
10385 reg_pat[i] = NUL;
10386 if (nested != 0)
10387 {
10388 if (nested < 0)
10389 EMSG(_("E219: Missing {."));
10390 else
10391 EMSG(_("E220: Missing }."));
10392 vim_free(reg_pat);
10393 reg_pat = NULL;
10394 }
10395 return reg_pat;
10396}
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010397
10398#if defined(EINTR) || defined(PROTO)
10399/*
10400 * Version of read() that retries when interrupted by EINTR (possibly
10401 * by a SIGWINCH).
10402 */
10403 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010404read_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010405{
10406 long ret;
10407
10408 for (;;)
10409 {
10410 ret = vim_read(fd, buf, bufsize);
10411 if (ret >= 0 || errno != EINTR)
10412 break;
10413 }
10414 return ret;
10415}
10416
10417/*
10418 * Version of write() that retries when interrupted by EINTR (possibly
10419 * by a SIGWINCH).
10420 */
10421 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010422write_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010423{
10424 long ret = 0;
10425 long wlen;
10426
10427 /* Repeat the write() so long it didn't fail, other than being interrupted
10428 * by a signal. */
10429 while (ret < (long)bufsize)
10430 {
Bram Moolenaar9c263032010-12-17 18:06:06 +010010431 wlen = vim_write(fd, (char *)buf + ret, bufsize - ret);
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010432 if (wlen < 0)
10433 {
10434 if (errno != EINTR)
10435 break;
10436 }
10437 else
10438 ret += wlen;
10439 }
10440 return ret;
10441}
10442#endif