blob: 82659be07b814f21cfc3a33728a7658b90eb0602 [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 *
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100213 * return FAIL for failure, NOTDONE for directory (failure), or OK
Bram Moolenaar071d4272004-06-13 20:20:40 +0000214 */
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 */
Bram Moolenaar7a2699e2017-01-23 21:31:09 +0100277 int try_mac;
278 int try_dos;
279 int try_unix;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000280 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 {
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100453 int retval = FAIL;
454
Bram Moolenaar071d4272004-06-13 20:20:40 +0000455 if (S_ISDIR(perm))
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100456 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000457 filemess(curbuf, fname, (char_u *)_("is a directory"), 0);
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100458 retval = NOTDONE;
459 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000460 else
461 filemess(curbuf, fname, (char_u *)_("is not a file"), 0);
462 msg_end();
463 msg_scroll = msg_save;
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100464 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000465 }
Bram Moolenaar4e4f5292013-08-30 17:07:01 +0200466#endif
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100467#if defined(MSWIN)
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000468 /*
469 * MS-Windows allows opening a device, but we will probably get stuck
470 * trying to read it.
471 */
472 if (!p_odev && mch_nodetype(fname) == NODE_WRITABLE)
473 {
Bram Moolenaar5386a122007-06-28 20:02:32 +0000474 filemess(curbuf, fname, (char_u *)_("is a device (disabled with 'opendevice' option)"), 0);
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000475 msg_end();
476 msg_scroll = msg_save;
477 return FAIL;
478 }
Bram Moolenaar043545e2006-10-10 16:44:07 +0000479#endif
Bram Moolenaar4e4f5292013-08-30 17:07:01 +0200480 }
Bram Moolenaar043545e2006-10-10 16:44:07 +0000481
Bram Moolenaarad875fb2013-07-24 15:02:03 +0200482 /* Set default or forced 'fileformat' and 'binary'. */
483 set_file_options(set_options, eap);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000484
485 /*
486 * When opening a new file we take the readonly flag from the file.
487 * Default is r/w, can be set to r/o below.
488 * Don't reset it when in readonly mode
489 * Only set/reset b_p_ro when BF_CHECK_RO is set.
490 */
491 check_readonly = (newfile && (curbuf->b_flags & BF_CHECK_RO));
Bram Moolenaar4399ef42005-02-12 14:29:27 +0000492 if (check_readonly && !readonlymode)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000493 curbuf->b_p_ro = FALSE;
494
Bram Moolenaarf71d7b92016-08-09 22:14:05 +0200495 if (newfile && !read_stdin && !read_buffer && !read_fifo)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000496 {
Bram Moolenaare60acc12011-05-10 16:41:25 +0200497 /* Remember time of file. */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000498 if (mch_stat((char *)fname, &st) >= 0)
499 {
500 buf_store_time(curbuf, &st, fname);
501 curbuf->b_mtime_read = curbuf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000502#ifdef UNIX
503 /*
504 * Use the protection bits of the original file for the swap file.
505 * This makes it possible for others to read the name of the
506 * edited file from the swapfile, but only if they can read the
507 * edited file.
508 * Remove the "write" and "execute" bits for group and others
509 * (they must not write the swapfile).
510 * Add the "read" and "write" bits for the user, otherwise we may
511 * not be able to write to the file ourselves.
512 * Setting the bits is done below, after creating the swap file.
513 */
514 swap_mode = (st.st_mode & 0644) | 0600;
515#endif
516#ifdef FEAT_CW_EDITOR
517 /* Get the FSSpec on MacOS
518 * TODO: Update it properly when the buffer name changes
519 */
520 (void)GetFSSpecFromPath(curbuf->b_ffname, &curbuf->b_FSSpec);
521#endif
522#ifdef VMS
523 curbuf->b_fab_rfm = st.st_fab_rfm;
Bram Moolenaard4755bb2004-09-02 19:12:26 +0000524 curbuf->b_fab_rat = st.st_fab_rat;
525 curbuf->b_fab_mrs = st.st_fab_mrs;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000526#endif
527 }
528 else
529 {
530 curbuf->b_mtime = 0;
531 curbuf->b_mtime_read = 0;
532 curbuf->b_orig_size = 0;
533 curbuf->b_orig_mode = 0;
534 }
535
536 /* Reset the "new file" flag. It will be set again below when the
537 * file doesn't exist. */
538 curbuf->b_flags &= ~(BF_NEW | BF_NEW_W);
539 }
540
541/*
542 * for UNIX: check readonly with perm and mch_access()
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100543 * for Amiga: check readonly by trying to open the file for writing
Bram Moolenaar071d4272004-06-13 20:20:40 +0000544 */
545 file_readonly = FALSE;
546 if (read_stdin)
547 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100548#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000549 /* Force binary I/O on stdin to avoid CR-LF -> LF conversion. */
550 setmode(0, O_BINARY);
551#endif
552 }
553 else if (!read_buffer)
554 {
555#ifdef USE_MCH_ACCESS
556 if (
557# ifdef UNIX
558 !(perm & 0222) ||
559# endif
560 mch_access((char *)fname, W_OK))
561 file_readonly = TRUE;
562 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
563#else
564 if (!newfile
565 || readonlymode
566 || (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0)
567 {
568 file_readonly = TRUE;
569 /* try to open ro */
570 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
571 }
572#endif
573 }
574
575 if (fd < 0) /* cannot open at all */
576 {
577#ifndef UNIX
578 int isdir_f;
579#endif
580 msg_scroll = msg_save;
581#ifndef UNIX
582 /*
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100583 * On Amiga we can't open a directory, check here.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000584 */
585 isdir_f = (mch_isdir(fname));
586 perm = mch_getperm(fname); /* check if the file exists */
587 if (isdir_f)
588 {
589 filemess(curbuf, sfname, (char_u *)_("is a directory"), 0);
590 curbuf->b_p_ro = TRUE; /* must use "w!" now */
591 }
592 else
593#endif
594 if (newfile)
595 {
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200596 if (perm < 0
597#ifdef ENOENT
598 && errno == ENOENT
599#endif
600 )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000601 {
602 /*
603 * Set the 'new-file' flag, so that when the file has
604 * been created by someone else, a ":w" will complain.
605 */
606 curbuf->b_flags |= BF_NEW;
607
608 /* Create a swap file now, so that other Vims are warned
609 * that we are editing this file. Don't do this for a
610 * "nofile" or "nowrite" buffer type. */
611#ifdef FEAT_QUICKFIX
612 if (!bt_dontwrite(curbuf))
613#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000614 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000615 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000616#ifdef FEAT_AUTOCMD
617 /* SwapExists autocommand may mess things up */
618 if (curbuf != old_curbuf
619 || (using_b_ffname
620 && (old_b_ffname != curbuf->b_ffname))
621 || (using_b_fname
622 && (old_b_fname != curbuf->b_fname)))
623 {
624 EMSG(_(e_auchangedbuf));
625 return FAIL;
626 }
627#endif
628 }
Bram Moolenaar5b962cf2005-12-12 21:58:40 +0000629 if (dir_of_file_exists(fname))
630 filemess(curbuf, sfname, (char_u *)_("[New File]"), 0);
631 else
632 filemess(curbuf, sfname,
633 (char_u *)_("[New DIRECTORY]"), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000634#ifdef FEAT_VIMINFO
635 /* Even though this is a new file, it might have been
636 * edited before and deleted. Get the old marks. */
637 check_marks_read();
638#endif
639#ifdef FEAT_MBYTE
Bram Moolenaarad875fb2013-07-24 15:02:03 +0200640 /* Set forced 'fileencoding'. */
641 if (eap != NULL)
642 set_forced_fenc(eap);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000643#endif
644#ifdef FEAT_AUTOCMD
645 apply_autocmds_exarg(EVENT_BUFNEWFILE, sfname, sfname,
646 FALSE, curbuf, eap);
647#endif
648 /* remember the current fileformat */
649 save_file_ff(curbuf);
650
651#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
652 if (aborting()) /* autocmds may abort script processing */
653 return FAIL;
654#endif
655 return OK; /* a new file is not an error */
656 }
657 else
658 {
Bram Moolenaar202795b2005-10-11 20:29:39 +0000659 filemess(curbuf, sfname, (char_u *)(
660# ifdef EFBIG
661 (errno == EFBIG) ? _("[File too big]") :
662# endif
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200663# ifdef EOVERFLOW
664 (errno == EOVERFLOW) ? _("[File too big]") :
665# endif
Bram Moolenaar202795b2005-10-11 20:29:39 +0000666 _("[Permission Denied]")), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000667 curbuf->b_p_ro = TRUE; /* must use "w!" now */
668 }
669 }
670
671 return FAIL;
672 }
673
674 /*
675 * Only set the 'ro' flag for readonly files the first time they are
676 * loaded. Help files always get readonly mode
677 */
678 if ((check_readonly && file_readonly) || curbuf->b_help)
679 curbuf->b_p_ro = TRUE;
680
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000681 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000682 {
Bram Moolenaar690ffc02008-01-04 15:31:21 +0000683 /* Don't change 'eol' if reading from buffer as it will already be
684 * correctly set when reading stdin. */
685 if (!read_buffer)
686 {
687 curbuf->b_p_eol = TRUE;
688 curbuf->b_start_eol = TRUE;
689 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000690#ifdef FEAT_MBYTE
691 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000692 curbuf->b_start_bomb = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000693#endif
694 }
695
696 /* Create a swap file now, so that other Vims are warned that we are
697 * editing this file.
698 * Don't do this for a "nofile" or "nowrite" buffer type. */
699#ifdef FEAT_QUICKFIX
700 if (!bt_dontwrite(curbuf))
701#endif
702 {
703 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000704#ifdef FEAT_AUTOCMD
705 if (!read_stdin && (curbuf != old_curbuf
706 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
707 || (using_b_fname && (old_b_fname != curbuf->b_fname))))
708 {
709 EMSG(_(e_auchangedbuf));
710 if (!read_buffer)
711 close(fd);
712 return FAIL;
713 }
714#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000715#ifdef UNIX
716 /* Set swap file protection bits after creating it. */
Bram Moolenaarf061e0b2009-06-24 15:32:01 +0000717 if (swap_mode > 0 && curbuf->b_ml.ml_mfp != NULL
718 && curbuf->b_ml.ml_mfp->mf_fname != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000719 (void)mch_setperm(curbuf->b_ml.ml_mfp->mf_fname, (long)swap_mode);
720#endif
721 }
722
Bram Moolenaarb815dac2005-12-07 20:59:24 +0000723#if defined(HAS_SWAP_EXISTS_ACTION)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000724 /* If "Quit" selected at ATTENTION dialog, don't load the file */
725 if (swap_exists_action == SEA_QUIT)
726 {
727 if (!read_buffer && !read_stdin)
728 close(fd);
729 return FAIL;
730 }
731#endif
732
733 ++no_wait_return; /* don't wait for return yet */
734
735 /*
736 * Set '[ mark to the line above where the lines go (line 1 if zero).
737 */
738 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
739 curbuf->b_op_start.col = 0;
740
Bram Moolenaar7a2699e2017-01-23 21:31:09 +0100741 try_mac = (vim_strchr(p_ffs, 'm') != NULL);
742 try_dos = (vim_strchr(p_ffs, 'd') != NULL);
743 try_unix = (vim_strchr(p_ffs, 'x') != NULL);
744
Bram Moolenaar071d4272004-06-13 20:20:40 +0000745#ifdef FEAT_AUTOCMD
746 if (!read_buffer)
747 {
748 int m = msg_scroll;
749 int n = msg_scrolled;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000750
751 /*
752 * The file must be closed again, the autocommands may want to change
753 * the file before reading it.
754 */
755 if (!read_stdin)
756 close(fd); /* ignore errors */
757
758 /*
759 * The output from the autocommands should not overwrite anything and
760 * should not be overwritten: Set msg_scroll, restore its value if no
761 * output was done.
762 */
763 msg_scroll = TRUE;
764 if (filtering)
765 apply_autocmds_exarg(EVENT_FILTERREADPRE, NULL, sfname,
766 FALSE, curbuf, eap);
767 else if (read_stdin)
768 apply_autocmds_exarg(EVENT_STDINREADPRE, NULL, sfname,
769 FALSE, curbuf, eap);
770 else if (newfile)
771 apply_autocmds_exarg(EVENT_BUFREADPRE, NULL, sfname,
772 FALSE, curbuf, eap);
773 else
774 apply_autocmds_exarg(EVENT_FILEREADPRE, sfname, sfname,
775 FALSE, NULL, eap);
Bram Moolenaar7a2699e2017-01-23 21:31:09 +0100776 /* autocommands may have changed it */
777 try_mac = (vim_strchr(p_ffs, 'm') != NULL);
778 try_dos = (vim_strchr(p_ffs, 'd') != NULL);
779 try_unix = (vim_strchr(p_ffs, 'x') != NULL);
780
Bram Moolenaar071d4272004-06-13 20:20:40 +0000781 if (msg_scrolled == n)
782 msg_scroll = m;
783
784#ifdef FEAT_EVAL
785 if (aborting()) /* autocmds may abort script processing */
786 {
787 --no_wait_return;
788 msg_scroll = msg_save;
789 curbuf->b_p_ro = TRUE; /* must use "w!" now */
790 return FAIL;
791 }
792#endif
793 /*
794 * Don't allow the autocommands to change the current buffer.
795 * Try to re-open the file.
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000796 *
797 * Don't allow the autocommands to change the buffer name either
798 * (cd for example) if it invalidates fname or sfname.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000799 */
800 if (!read_stdin && (curbuf != old_curbuf
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000801 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
802 || (using_b_fname && (old_b_fname != curbuf->b_fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000803 || (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) < 0))
804 {
805 --no_wait_return;
806 msg_scroll = msg_save;
807 if (fd < 0)
808 EMSG(_("E200: *ReadPre autocommands made the file unreadable"));
809 else
810 EMSG(_("E201: *ReadPre autocommands must not change current buffer"));
811 curbuf->b_p_ro = TRUE; /* must use "w!" now */
812 return FAIL;
813 }
814 }
815#endif /* FEAT_AUTOCMD */
816
817 /* Autocommands may add lines to the file, need to check if it is empty */
818 wasempty = (curbuf->b_ml.ml_flags & ML_EMPTY);
819
820 if (!recoverymode && !filtering && !(flags & READ_DUMMY))
821 {
822 /*
823 * Show the user that we are busy reading the input. Sometimes this
824 * may take a while. When reading from stdin another program may
825 * still be running, don't move the cursor to the last line, unless
826 * always using the GUI.
827 */
828 if (read_stdin)
829 {
830#ifndef ALWAYS_USE_GUI
831 mch_msg(_("Vim: Reading from stdin...\n"));
832#endif
833#ifdef FEAT_GUI
834 /* Also write a message in the GUI window, if there is one. */
835 if (gui.in_use && !gui.dying && !gui.starting)
836 {
837 p = (char_u *)_("Reading from stdin...");
838 gui_write(p, (int)STRLEN(p));
839 }
840#endif
841 }
842 else if (!read_buffer)
843 filemess(curbuf, sfname, (char_u *)"", 0);
844 }
845
846 msg_scroll = FALSE; /* overwrite the file message */
847
848 /*
849 * Set linecnt now, before the "retry" caused by a wrong guess for
850 * fileformat, and after the autocommands, which may change them.
851 */
852 linecnt = curbuf->b_ml.ml_line_count;
853
854#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000855 /* "++bad=" argument. */
856 if (eap != NULL && eap->bad_char != 0)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000857 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000858 bad_char_behavior = eap->bad_char;
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000859 if (set_options)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000860 curbuf->b_bad_char = eap->bad_char;
861 }
862 else
863 curbuf->b_bad_char = 0;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000864
Bram Moolenaar071d4272004-06-13 20:20:40 +0000865 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000866 * Decide which 'encoding' to use or use first.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000867 */
868 if (eap != NULL && eap->force_enc != 0)
869 {
870 fenc = enc_canonize(eap->cmd + eap->force_enc);
871 fenc_alloced = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000872 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000873 }
874 else if (curbuf->b_p_bin)
875 {
876 fenc = (char_u *)""; /* binary: don't convert */
877 fenc_alloced = FALSE;
878 }
879 else if (curbuf->b_help)
880 {
881 char_u firstline[80];
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000882 int fc;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000883
884 /* Help files are either utf-8 or latin1. Try utf-8 first, if this
885 * fails it must be latin1.
886 * Always do this when 'encoding' is "utf-8". Otherwise only do
887 * this when needed to avoid [converted] remarks all the time.
888 * It is needed when the first line contains non-ASCII characters.
889 * That is only in *.??x files. */
890 fenc = (char_u *)"latin1";
891 c = enc_utf8;
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000892 if (!c && !read_stdin)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000893 {
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000894 fc = fname[STRLEN(fname) - 1];
895 if (TOLOWER_ASC(fc) == 'x')
896 {
897 /* Read the first line (and a bit more). Immediately rewind to
898 * the start of the file. If the read() fails "len" is -1. */
Bram Moolenaar540fc6f2010-12-17 16:27:16 +0100899 len = read_eintr(fd, firstline, 80);
Bram Moolenaar8767f522016-07-01 17:17:39 +0200900 vim_lseek(fd, (off_T)0L, SEEK_SET);
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000901 for (p = firstline; p < firstline + len; ++p)
902 if (*p >= 0x80)
903 {
904 c = TRUE;
905 break;
906 }
907 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000908 }
909
910 if (c)
911 {
912 fenc_next = fenc;
913 fenc = (char_u *)"utf-8";
914
915 /* When the file is utf-8 but a character doesn't fit in
916 * 'encoding' don't retry. In help text editing utf-8 bytes
917 * doesn't make sense. */
Bram Moolenaarf193fff2006-04-27 00:02:13 +0000918 if (!enc_utf8)
919 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000920 }
921 fenc_alloced = FALSE;
922 }
923 else if (*p_fencs == NUL)
924 {
925 fenc = curbuf->b_p_fenc; /* use format from buffer */
926 fenc_alloced = FALSE;
927 }
928 else
929 {
930 fenc_next = p_fencs; /* try items in 'fileencodings' */
931 fenc = next_fenc(&fenc_next);
932 fenc_alloced = TRUE;
933 }
934#endif
935
936 /*
937 * Jump back here to retry reading the file in different ways.
938 * Reasons to retry:
939 * - encoding conversion failed: try another one from "fenc_next"
940 * - BOM detected and fenc was set, need to setup conversion
941 * - "fileformat" check failed: try another
942 *
943 * Variables set for special retry actions:
944 * "file_rewind" Rewind the file to start reading it again.
945 * "advance_fenc" Advance "fenc" using "fenc_next".
946 * "skip_read" Re-use already read bytes (BOM detected).
947 * "did_iconv" iconv() conversion failed, try 'charconvert'.
948 * "keep_fileformat" Don't reset "fileformat".
949 *
950 * Other status indicators:
951 * "tmpname" When != NULL did conversion with 'charconvert'.
952 * Output file has to be deleted afterwards.
953 * "iconv_fd" When != -1 did conversion with iconv().
954 */
955retry:
956
957 if (file_rewind)
958 {
959 if (read_buffer)
960 {
961 read_buf_lnum = 1;
962 read_buf_col = 0;
963 }
Bram Moolenaar8767f522016-07-01 17:17:39 +0200964 else if (read_stdin || vim_lseek(fd, (off_T)0L, SEEK_SET) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000965 {
966 /* Can't rewind the file, give up. */
967 error = TRUE;
968 goto failed;
969 }
970 /* Delete the previously read lines. */
971 while (lnum > from)
972 ml_delete(lnum--, FALSE);
973 file_rewind = FALSE;
974#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000975 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000976 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000977 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000978 curbuf->b_start_bomb = FALSE;
979 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000980 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000981#endif
982 }
983
984 /*
985 * When retrying with another "fenc" and the first time "fileformat"
986 * will be reset.
987 */
988 if (keep_fileformat)
989 keep_fileformat = FALSE;
990 else
991 {
992 if (eap != NULL && eap->force_ff != 0)
Bram Moolenaar1c860362008-11-12 15:05:21 +0000993 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000994 fileformat = get_fileformat_force(curbuf, eap);
Bram Moolenaar1c860362008-11-12 15:05:21 +0000995 try_unix = try_dos = try_mac = FALSE;
996 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000997 else if (curbuf->b_p_bin)
998 fileformat = EOL_UNIX; /* binary: use Unix format */
999 else if (*p_ffs == NUL)
1000 fileformat = get_fileformat(curbuf);/* use format from buffer */
1001 else
1002 fileformat = EOL_UNKNOWN; /* detect from file */
1003 }
1004
1005#ifdef FEAT_MBYTE
1006# ifdef USE_ICONV
1007 if (iconv_fd != (iconv_t)-1)
1008 {
1009 /* aborted conversion with iconv(), close the descriptor */
1010 iconv_close(iconv_fd);
1011 iconv_fd = (iconv_t)-1;
1012 }
1013# endif
1014
1015 if (advance_fenc)
1016 {
1017 /*
1018 * Try the next entry in 'fileencodings'.
1019 */
1020 advance_fenc = FALSE;
1021
1022 if (eap != NULL && eap->force_enc != 0)
1023 {
1024 /* Conversion given with "++cc=" wasn't possible, read
1025 * without conversion. */
1026 notconverted = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001027 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001028 if (fenc_alloced)
1029 vim_free(fenc);
1030 fenc = (char_u *)"";
1031 fenc_alloced = FALSE;
1032 }
1033 else
1034 {
1035 if (fenc_alloced)
1036 vim_free(fenc);
1037 if (fenc_next != NULL)
1038 {
1039 fenc = next_fenc(&fenc_next);
1040 fenc_alloced = (fenc_next != NULL);
1041 }
1042 else
1043 {
1044 fenc = (char_u *)"";
1045 fenc_alloced = FALSE;
1046 }
1047 }
1048 if (tmpname != NULL)
1049 {
1050 mch_remove(tmpname); /* delete converted file */
1051 vim_free(tmpname);
1052 tmpname = NULL;
1053 }
1054 }
1055
1056 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001057 * Conversion may be required when the encoding of the file is different
1058 * from 'encoding' or 'encoding' is UTF-16, UCS-2 or UCS-4.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001059 */
1060 fio_flags = 0;
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001061 converted = need_conversion(fenc);
1062 if (converted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001063 {
1064
1065 /* "ucs-bom" means we need to check the first bytes of the file
1066 * for a BOM. */
1067 if (STRCMP(fenc, ENC_UCSBOM) == 0)
1068 fio_flags = FIO_UCSBOM;
1069
1070 /*
1071 * Check if UCS-2/4 or Latin1 to UTF-8 conversion needs to be
1072 * done. This is handled below after read(). Prepare the
1073 * fio_flags to avoid having to parse the string each time.
1074 * Also check for Unicode to Latin1 conversion, because iconv()
1075 * appears not to handle this correctly. This works just like
1076 * conversion to UTF-8 except how the resulting character is put in
1077 * the buffer.
1078 */
1079 else if (enc_utf8 || STRCMP(p_enc, "latin1") == 0)
1080 fio_flags = get_fio_flags(fenc);
1081
1082# ifdef WIN3264
1083 /*
1084 * Conversion from an MS-Windows codepage to UTF-8 or another codepage
1085 * is handled with MultiByteToWideChar().
1086 */
1087 if (fio_flags == 0)
1088 fio_flags = get_win_fio_flags(fenc);
1089# endif
1090
1091# ifdef MACOS_X
1092 /* Conversion from Apple MacRoman to latin1 or UTF-8 */
1093 if (fio_flags == 0)
1094 fio_flags = get_mac_fio_flags(fenc);
1095# endif
1096
1097# ifdef USE_ICONV
1098 /*
1099 * Try using iconv() if we can't convert internally.
1100 */
1101 if (fio_flags == 0
1102# ifdef FEAT_EVAL
1103 && !did_iconv
1104# endif
1105 )
1106 iconv_fd = (iconv_t)my_iconv_open(
1107 enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc);
1108# endif
1109
1110# ifdef FEAT_EVAL
1111 /*
1112 * Use the 'charconvert' expression when conversion is required
1113 * and we can't do it internally or with iconv().
1114 */
1115 if (fio_flags == 0 && !read_stdin && !read_buffer && *p_ccv != NUL
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02001116 && !read_fifo
Bram Moolenaar071d4272004-06-13 20:20:40 +00001117# ifdef USE_ICONV
1118 && iconv_fd == (iconv_t)-1
1119# endif
1120 )
1121 {
1122# ifdef USE_ICONV
1123 did_iconv = FALSE;
1124# endif
1125 /* Skip conversion when it's already done (retry for wrong
1126 * "fileformat"). */
1127 if (tmpname == NULL)
1128 {
1129 tmpname = readfile_charconvert(fname, fenc, &fd);
1130 if (tmpname == NULL)
1131 {
1132 /* Conversion failed. Try another one. */
1133 advance_fenc = TRUE;
1134 if (fd < 0)
1135 {
1136 /* Re-opening the original file failed! */
1137 EMSG(_("E202: Conversion made file unreadable!"));
1138 error = TRUE;
1139 goto failed;
1140 }
1141 goto retry;
1142 }
1143 }
1144 }
1145 else
1146# endif
1147 {
1148 if (fio_flags == 0
1149# ifdef USE_ICONV
1150 && iconv_fd == (iconv_t)-1
1151# endif
1152 )
1153 {
1154 /* Conversion wanted but we can't.
1155 * Try the next conversion in 'fileencodings' */
1156 advance_fenc = TRUE;
1157 goto retry;
1158 }
1159 }
1160 }
1161
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001162 /* Set "can_retry" when it's possible to rewind the file and try with
Bram Moolenaar071d4272004-06-13 20:20:40 +00001163 * another "fenc" value. It's FALSE when no other "fenc" to try, reading
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001164 * stdin or fixed at a specific encoding. */
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02001165 can_retry = (*fenc != NUL && !read_stdin && !read_fifo && !keep_dest_enc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001166#endif
1167
1168 if (!skip_read)
1169 {
1170 linerest = 0;
1171 filesize = 0;
1172 skip_count = lines_to_skip;
1173 read_count = lines_to_read;
1174#ifdef FEAT_MBYTE
1175 conv_restlen = 0;
1176#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001177#ifdef FEAT_PERSISTENT_UNDO
Bram Moolenaar59f931e2010-07-24 20:27:03 +02001178 read_undo_file = (newfile && (flags & READ_KEEP_UNDO) == 0
1179 && curbuf->b_ffname != NULL
1180 && curbuf->b_p_udf
1181 && !filtering
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02001182 && !read_fifo
Bram Moolenaar59f931e2010-07-24 20:27:03 +02001183 && !read_stdin
1184 && !read_buffer);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001185 if (read_undo_file)
1186 sha256_start(&sha_ctx);
1187#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001188#ifdef FEAT_CRYPT
1189 if (curbuf->b_cryptstate != NULL)
1190 {
1191 /* Need to free the state, but keep the key, don't want to ask for
1192 * it again. */
1193 crypt_free_state(curbuf->b_cryptstate);
1194 curbuf->b_cryptstate = NULL;
1195 }
1196#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001197 }
1198
1199 while (!error && !got_int)
1200 {
1201 /*
1202 * We allocate as much space for the file as we can get, plus
1203 * space for the old line plus room for one terminating NUL.
1204 * The amount is limited by the fact that read() only can read
1205 * upto max_unsigned characters (and other things).
1206 */
Bram Moolenaara2aa31a2014-02-23 22:52:40 +01001207#if VIM_SIZEOF_INT <= 2
Bram Moolenaar071d4272004-06-13 20:20:40 +00001208 if (linerest >= 0x7ff0)
1209 {
1210 ++split;
1211 *ptr = NL; /* split line by inserting a NL */
1212 size = 1;
1213 }
1214 else
1215#endif
1216 {
1217 if (!skip_read)
1218 {
Bram Moolenaara2aa31a2014-02-23 22:52:40 +01001219#if VIM_SIZEOF_INT > 2
Bram Moolenaar311d9822007-02-27 15:48:28 +00001220# if defined(SSIZE_MAX) && (SSIZE_MAX < 0x10000L)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001221 size = SSIZE_MAX; /* use max I/O size, 52K */
1222# else
1223 size = 0x10000L; /* use buffer >= 64K */
1224# endif
1225#else
1226 size = 0x7ff0L - linerest; /* limit buffer to 32K */
1227#endif
1228
Bram Moolenaarc1e37902006-04-18 21:55:01 +00001229 for ( ; size >= 10; size = (long)((long_u)size >> 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001230 {
1231 if ((new_buffer = lalloc((long_u)(size + linerest + 1),
1232 FALSE)) != NULL)
1233 break;
1234 }
1235 if (new_buffer == NULL)
1236 {
1237 do_outofmem_msg((long_u)(size * 2 + linerest + 1));
1238 error = TRUE;
1239 break;
1240 }
1241 if (linerest) /* copy characters from the previous buffer */
1242 mch_memmove(new_buffer, ptr - linerest, (size_t)linerest);
1243 vim_free(buffer);
1244 buffer = new_buffer;
1245 ptr = buffer + linerest;
1246 line_start = buffer;
1247
1248#ifdef FEAT_MBYTE
1249 /* May need room to translate into.
1250 * For iconv() we don't really know the required space, use a
1251 * factor ICONV_MULT.
1252 * latin1 to utf-8: 1 byte becomes up to 2 bytes
1253 * utf-16 to utf-8: 2 bytes become up to 3 bytes, 4 bytes
1254 * become up to 4 bytes, size must be multiple of 2
1255 * ucs-2 to utf-8: 2 bytes become up to 3 bytes, size must be
1256 * multiple of 2
1257 * ucs-4 to utf-8: 4 bytes become up to 6 bytes, size must be
1258 * multiple of 4 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001259 real_size = (int)size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001260# ifdef USE_ICONV
1261 if (iconv_fd != (iconv_t)-1)
1262 size = size / ICONV_MULT;
1263 else
1264# endif
1265 if (fio_flags & FIO_LATIN1)
1266 size = size / 2;
1267 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1268 size = (size * 2 / 3) & ~1;
1269 else if (fio_flags & FIO_UCS4)
1270 size = (size * 2 / 3) & ~3;
1271 else if (fio_flags == FIO_UCSBOM)
1272 size = size / ICONV_MULT; /* worst case */
1273# ifdef WIN3264
1274 else if (fio_flags & FIO_CODEPAGE)
1275 size = size / ICONV_MULT; /* also worst case */
1276# endif
1277# ifdef MACOS_X
1278 else if (fio_flags & FIO_MACROMAN)
1279 size = size / ICONV_MULT; /* also worst case */
1280# endif
1281#endif
1282
1283#ifdef FEAT_MBYTE
1284 if (conv_restlen > 0)
1285 {
1286 /* Insert unconverted bytes from previous line. */
1287 mch_memmove(ptr, conv_rest, conv_restlen);
1288 ptr += conv_restlen;
1289 size -= conv_restlen;
1290 }
1291#endif
1292
1293 if (read_buffer)
1294 {
1295 /*
1296 * Read bytes from curbuf. Used for converting text read
1297 * from stdin.
1298 */
1299 if (read_buf_lnum > from)
1300 size = 0;
1301 else
1302 {
1303 int n, ni;
1304 long tlen;
1305
1306 tlen = 0;
1307 for (;;)
1308 {
1309 p = ml_get(read_buf_lnum) + read_buf_col;
1310 n = (int)STRLEN(p);
1311 if ((int)tlen + n + 1 > size)
1312 {
1313 /* Filled up to "size", append partial line.
1314 * Change NL to NUL to reverse the effect done
1315 * below. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001316 n = (int)(size - tlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001317 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 read_buf_col += n;
1325 break;
1326 }
1327 else
1328 {
1329 /* Append whole line and new-line. Change NL
1330 * to NUL to reverse the effect done below. */
1331 for (ni = 0; ni < n; ++ni)
1332 {
1333 if (p[ni] == NL)
1334 ptr[tlen++] = NUL;
1335 else
1336 ptr[tlen++] = p[ni];
1337 }
1338 ptr[tlen++] = NL;
1339 read_buf_col = 0;
1340 if (++read_buf_lnum > from)
1341 {
1342 /* When the last line didn't have an
1343 * end-of-line don't add it now either. */
1344 if (!curbuf->b_p_eol)
1345 --tlen;
1346 size = tlen;
1347 break;
1348 }
1349 }
1350 }
1351 }
1352 }
1353 else
1354 {
1355 /*
1356 * Read bytes from the file.
1357 */
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01001358 size = read_eintr(fd, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001359 }
1360
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001361#ifdef FEAT_CRYPT
1362 /*
1363 * At start of file: Check for magic number of encryption.
1364 */
1365 if (filesize == 0 && size > 0)
1366 cryptkey = check_for_cryptkey(cryptkey, ptr, &size,
1367 &filesize, newfile, sfname,
1368 &did_ask_for_key);
1369 /*
1370 * Decrypt the read bytes. This is done before checking for
1371 * EOF because the crypt layer may be buffering.
1372 */
Bram Moolenaar829aa642017-08-23 22:32:35 +02001373 if (cryptkey != NULL && curbuf->b_cryptstate != NULL
1374 && size > 0)
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001375 {
1376 if (crypt_works_inplace(curbuf->b_cryptstate))
1377 {
1378 crypt_decode_inplace(curbuf->b_cryptstate, ptr, size);
1379 }
1380 else
1381 {
1382 char_u *newptr = NULL;
1383 int decrypted_size;
1384
1385 decrypted_size = crypt_decode_alloc(
1386 curbuf->b_cryptstate, ptr, size, &newptr);
1387
1388 /* If the crypt layer is buffering, not producing
1389 * anything yet, need to read more. */
1390 if (size > 0 && decrypted_size == 0)
1391 continue;
1392
1393 if (linerest == 0)
1394 {
1395 /* Simple case: reuse returned buffer (may be
1396 * NULL, checked later). */
1397 new_buffer = newptr;
1398 }
1399 else
1400 {
1401 long_u new_size;
1402
1403 /* Need new buffer to add bytes carried over. */
1404 new_size = (long_u)(decrypted_size + linerest + 1);
1405 new_buffer = lalloc(new_size, FALSE);
1406 if (new_buffer == NULL)
1407 {
1408 do_outofmem_msg(new_size);
1409 error = TRUE;
1410 break;
1411 }
1412
1413 mch_memmove(new_buffer, buffer, linerest);
1414 if (newptr != NULL)
1415 mch_memmove(new_buffer + linerest, newptr,
1416 decrypted_size);
1417 }
1418
1419 if (new_buffer != NULL)
1420 {
1421 vim_free(buffer);
1422 buffer = new_buffer;
1423 new_buffer = NULL;
1424 line_start = buffer;
1425 ptr = buffer + linerest;
1426 }
1427 size = decrypted_size;
1428 }
1429 }
1430#endif
1431
Bram Moolenaar071d4272004-06-13 20:20:40 +00001432 if (size <= 0)
1433 {
1434 if (size < 0) /* read error */
1435 error = TRUE;
1436#ifdef FEAT_MBYTE
1437 else if (conv_restlen > 0)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001438 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001439 /*
1440 * Reached end-of-file but some trailing bytes could
1441 * not be converted. Truncated file?
1442 */
1443
1444 /* When we did a conversion report an error. */
1445 if (fio_flags != 0
1446# ifdef USE_ICONV
1447 || iconv_fd != (iconv_t)-1
1448# endif
1449 )
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001450 {
Bram Moolenaare8d95302013-04-24 16:34:02 +02001451 if (can_retry)
1452 goto rewind_retry;
Bram Moolenaarf453d352008-06-04 17:37:34 +00001453 if (conv_error == 0)
1454 conv_error = curbuf->b_ml.ml_line_count
1455 - linecnt + 1;
1456 }
1457 /* Remember the first linenr with an illegal byte */
1458 else if (illegal_byte == 0)
1459 illegal_byte = curbuf->b_ml.ml_line_count
1460 - linecnt + 1;
1461 if (bad_char_behavior == BAD_DROP)
1462 {
1463 *(ptr - conv_restlen) = NUL;
1464 conv_restlen = 0;
1465 }
1466 else
1467 {
1468 /* Replace the trailing bytes with the replacement
1469 * character if we were converting; if we weren't,
1470 * leave the UTF8 checking code to do it, as it
1471 * works slightly differently. */
1472 if (bad_char_behavior != BAD_KEEP && (fio_flags != 0
1473# ifdef USE_ICONV
1474 || iconv_fd != (iconv_t)-1
1475# endif
1476 ))
1477 {
1478 while (conv_restlen > 0)
1479 {
1480 *(--ptr) = bad_char_behavior;
1481 --conv_restlen;
1482 }
1483 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001484 fio_flags = 0; /* don't convert this */
Bram Moolenaarb21e5842006-04-16 18:30:08 +00001485# ifdef USE_ICONV
1486 if (iconv_fd != (iconv_t)-1)
1487 {
1488 iconv_close(iconv_fd);
1489 iconv_fd = (iconv_t)-1;
1490 }
1491# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001492 }
1493 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001494#endif
1495 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001496 }
1497 skip_read = FALSE;
1498
1499#ifdef FEAT_MBYTE
1500 /*
1501 * At start of file (or after crypt magic number): Check for BOM.
1502 * Also check for a BOM for other Unicode encodings, but not after
1503 * converting with 'charconvert' or when a BOM has already been
1504 * found.
1505 */
1506 if ((filesize == 0
1507# ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001508 || (cryptkey != NULL
1509 && filesize == crypt_get_header_len(
1510 crypt_get_method_nr(curbuf)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001511# endif
1512 )
1513 && (fio_flags == FIO_UCSBOM
1514 || (!curbuf->b_p_bomb
1515 && tmpname == NULL
1516 && (*fenc == 'u' || (*fenc == NUL && enc_utf8)))))
1517 {
1518 char_u *ccname;
1519 int blen;
1520
1521 /* no BOM detection in a short file or in binary mode */
1522 if (size < 2 || curbuf->b_p_bin)
1523 ccname = NULL;
1524 else
1525 ccname = check_for_bom(ptr, size, &blen,
1526 fio_flags == FIO_UCSBOM ? FIO_ALL : get_fio_flags(fenc));
1527 if (ccname != NULL)
1528 {
1529 /* Remove BOM from the text */
1530 filesize += blen;
1531 size -= blen;
1532 mch_memmove(ptr, ptr + blen, (size_t)size);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00001533 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001534 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001535 curbuf->b_p_bomb = TRUE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001536 curbuf->b_start_bomb = TRUE;
1537 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001538 }
1539
1540 if (fio_flags == FIO_UCSBOM)
1541 {
1542 if (ccname == NULL)
1543 {
1544 /* No BOM detected: retry with next encoding. */
1545 advance_fenc = TRUE;
1546 }
1547 else
1548 {
1549 /* BOM detected: set "fenc" and jump back */
1550 if (fenc_alloced)
1551 vim_free(fenc);
1552 fenc = ccname;
1553 fenc_alloced = FALSE;
1554 }
1555 /* retry reading without getting new bytes or rewinding */
1556 skip_read = TRUE;
1557 goto retry;
1558 }
1559 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001560
1561 /* Include not converted bytes. */
1562 ptr -= conv_restlen;
1563 size += conv_restlen;
1564 conv_restlen = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001565#endif
1566 /*
1567 * Break here for a read error or end-of-file.
1568 */
1569 if (size <= 0)
1570 break;
1571
1572#ifdef FEAT_MBYTE
1573
Bram Moolenaar071d4272004-06-13 20:20:40 +00001574# ifdef USE_ICONV
1575 if (iconv_fd != (iconv_t)-1)
1576 {
1577 /*
1578 * Attempt conversion of the read bytes to 'encoding' using
1579 * iconv().
1580 */
1581 const char *fromp;
1582 char *top;
1583 size_t from_size;
1584 size_t to_size;
1585
1586 fromp = (char *)ptr;
1587 from_size = size;
1588 ptr += size;
1589 top = (char *)ptr;
1590 to_size = real_size - size;
1591
1592 /*
1593 * If there is conversion error or not enough room try using
Bram Moolenaar19a09a12005-03-04 23:39:37 +00001594 * another conversion. Except for when there is no
1595 * alternative (help files).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001596 */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001597 while ((iconv(iconv_fd, (void *)&fromp, &from_size,
1598 &top, &to_size)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001599 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
1600 || from_size > CONV_RESTLEN)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001601 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001602 if (can_retry)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001603 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001604 if (conv_error == 0)
1605 conv_error = readfile_linenr(linecnt,
1606 ptr, (char_u *)top);
Bram Moolenaar42eeac32005-06-29 22:40:58 +00001607
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001608 /* Deal with a bad byte and continue with the next. */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001609 ++fromp;
1610 --from_size;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001611 if (bad_char_behavior == BAD_KEEP)
1612 {
1613 *top++ = *(fromp - 1);
1614 --to_size;
1615 }
1616 else if (bad_char_behavior != BAD_DROP)
1617 {
1618 *top++ = bad_char_behavior;
1619 --to_size;
1620 }
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001621 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001622
1623 if (from_size > 0)
1624 {
1625 /* Some remaining characters, keep them for the next
1626 * round. */
1627 mch_memmove(conv_rest, (char_u *)fromp, from_size);
1628 conv_restlen = (int)from_size;
1629 }
1630
1631 /* move the linerest to before the converted characters */
1632 line_start = ptr - linerest;
1633 mch_memmove(line_start, buffer, (size_t)linerest);
1634 size = (long)((char_u *)top - ptr);
1635 }
1636# endif
1637
1638# ifdef WIN3264
1639 if (fio_flags & FIO_CODEPAGE)
1640 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001641 char_u *src, *dst;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001642 WCHAR ucs2buf[3];
1643 int ucs2len;
1644 int codepage = FIO_GET_CP(fio_flags);
1645 int bytelen;
1646 int found_bad;
1647 char replstr[2];
1648
Bram Moolenaar071d4272004-06-13 20:20:40 +00001649 /*
1650 * Conversion from an MS-Windows codepage or UTF-8 to UTF-8 or
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001651 * a codepage, using standard MS-Windows functions. This
1652 * requires two steps:
1653 * 1. convert from 'fileencoding' to ucs-2
1654 * 2. convert from ucs-2 to 'encoding'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001655 *
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001656 * Because there may be illegal bytes AND an incomplete byte
1657 * sequence at the end, we may have to do the conversion one
1658 * character at a time to get it right.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001659 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001660
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001661 /* Replacement string for WideCharToMultiByte(). */
1662 if (bad_char_behavior > 0)
1663 replstr[0] = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001664 else
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001665 replstr[0] = '?';
1666 replstr[1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001667
1668 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001669 * Move the bytes to the end of the buffer, so that we have
1670 * room to put the result at the start.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001671 */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001672 src = ptr + real_size - size;
1673 mch_memmove(src, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001674
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001675 /*
1676 * Do the conversion.
1677 */
1678 dst = ptr;
1679 size = size;
1680 while (size > 0)
1681 {
1682 found_bad = FALSE;
1683
1684# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
1685 if (codepage == CP_UTF8)
1686 {
1687 /* Handle CP_UTF8 input ourselves to be able to handle
1688 * trailing bytes properly.
1689 * Get one UTF-8 character from src. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001690 bytelen = (int)utf_ptr2len_len(src, size);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001691 if (bytelen > size)
1692 {
1693 /* Only got some bytes of a character. Normally
1694 * it's put in "conv_rest", but if it's too long
1695 * deal with it as if they were illegal bytes. */
1696 if (bytelen <= CONV_RESTLEN)
1697 break;
1698
1699 /* weird overlong byte sequence */
1700 bytelen = size;
1701 found_bad = TRUE;
1702 }
1703 else
1704 {
Bram Moolenaarc01140a2006-03-24 22:21:52 +00001705 int u8c = utf_ptr2char(src);
1706
Bram Moolenaar86e01082005-12-29 22:45:34 +00001707 if (u8c > 0xffff || (*src >= 0x80 && bytelen == 1))
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001708 found_bad = TRUE;
1709 ucs2buf[0] = u8c;
1710 ucs2len = 1;
1711 }
1712 }
1713 else
1714# endif
1715 {
1716 /* We don't know how long the byte sequence is, try
1717 * from one to three bytes. */
1718 for (bytelen = 1; bytelen <= size && bytelen <= 3;
1719 ++bytelen)
1720 {
1721 ucs2len = MultiByteToWideChar(codepage,
1722 MB_ERR_INVALID_CHARS,
1723 (LPCSTR)src, bytelen,
1724 ucs2buf, 3);
1725 if (ucs2len > 0)
1726 break;
1727 }
1728 if (ucs2len == 0)
1729 {
1730 /* If we have only one byte then it's probably an
1731 * incomplete byte sequence. Otherwise discard
1732 * one byte as a bad character. */
1733 if (size == 1)
1734 break;
1735 found_bad = TRUE;
1736 bytelen = 1;
1737 }
1738 }
1739
1740 if (!found_bad)
1741 {
1742 int i;
1743
1744 /* Convert "ucs2buf[ucs2len]" to 'enc' in "dst". */
1745 if (enc_utf8)
1746 {
1747 /* From UCS-2 to UTF-8. Cannot fail. */
1748 for (i = 0; i < ucs2len; ++i)
1749 dst += utf_char2bytes(ucs2buf[i], dst);
1750 }
1751 else
1752 {
1753 BOOL bad = FALSE;
1754 int dstlen;
1755
1756 /* From UCS-2 to "enc_codepage". If the
1757 * conversion uses the default character "?",
1758 * the data doesn't fit in this encoding. */
1759 dstlen = WideCharToMultiByte(enc_codepage, 0,
1760 (LPCWSTR)ucs2buf, ucs2len,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001761 (LPSTR)dst, (int)(src - dst),
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001762 replstr, &bad);
1763 if (bad)
1764 found_bad = TRUE;
1765 else
1766 dst += dstlen;
1767 }
1768 }
1769
1770 if (found_bad)
1771 {
1772 /* Deal with bytes we can't convert. */
1773 if (can_retry)
1774 goto rewind_retry;
1775 if (conv_error == 0)
1776 conv_error = readfile_linenr(linecnt, ptr, dst);
1777 if (bad_char_behavior != BAD_DROP)
1778 {
1779 if (bad_char_behavior == BAD_KEEP)
1780 {
1781 mch_memmove(dst, src, bytelen);
1782 dst += bytelen;
1783 }
1784 else
1785 *dst++ = bad_char_behavior;
1786 }
1787 }
1788
1789 src += bytelen;
1790 size -= bytelen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001791 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001792
1793 if (size > 0)
1794 {
1795 /* An incomplete byte sequence remaining. */
1796 mch_memmove(conv_rest, src, size);
1797 conv_restlen = size;
1798 }
1799
1800 /* The new size is equal to how much "dst" was advanced. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001801 size = (long)(dst - ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001802 }
1803 else
1804# endif
Bram Moolenaar56718732006-03-15 22:53:57 +00001805# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001806 if (fio_flags & FIO_MACROMAN)
1807 {
1808 /*
1809 * Conversion from Apple MacRoman char encoding to UTF-8 or
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001810 * latin1. This is in os_mac_conv.c.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001811 */
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001812 if (macroman2enc(ptr, &size, real_size) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001813 goto rewind_retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001814 }
1815 else
1816# endif
1817 if (fio_flags != 0)
1818 {
1819 int u8c;
1820 char_u *dest;
1821 char_u *tail = NULL;
1822
1823 /*
1824 * "enc_utf8" set: Convert Unicode or Latin1 to UTF-8.
1825 * "enc_utf8" not set: Convert Unicode to Latin1.
1826 * Go from end to start through the buffer, because the number
1827 * of bytes may increase.
1828 * "dest" points to after where the UTF-8 bytes go, "p" points
1829 * to after the next character to convert.
1830 */
1831 dest = ptr + real_size;
1832 if (fio_flags == FIO_LATIN1 || fio_flags == FIO_UTF8)
1833 {
1834 p = ptr + size;
1835 if (fio_flags == FIO_UTF8)
1836 {
1837 /* Check for a trailing incomplete UTF-8 sequence */
1838 tail = ptr + size - 1;
1839 while (tail > ptr && (*tail & 0xc0) == 0x80)
1840 --tail;
1841 if (tail + utf_byte2len(*tail) <= ptr + size)
1842 tail = NULL;
1843 else
1844 p = tail;
1845 }
1846 }
1847 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1848 {
1849 /* Check for a trailing byte */
1850 p = ptr + (size & ~1);
1851 if (size & 1)
1852 tail = p;
1853 if ((fio_flags & FIO_UTF16) && p > ptr)
1854 {
1855 /* Check for a trailing leading word */
1856 if (fio_flags & FIO_ENDIAN_L)
1857 {
1858 u8c = (*--p << 8);
1859 u8c += *--p;
1860 }
1861 else
1862 {
1863 u8c = *--p;
1864 u8c += (*--p << 8);
1865 }
1866 if (u8c >= 0xd800 && u8c <= 0xdbff)
1867 tail = p;
1868 else
1869 p += 2;
1870 }
1871 }
1872 else /* FIO_UCS4 */
1873 {
1874 /* Check for trailing 1, 2 or 3 bytes */
1875 p = ptr + (size & ~3);
1876 if (size & 3)
1877 tail = p;
1878 }
1879
1880 /* If there is a trailing incomplete sequence move it to
1881 * conv_rest[]. */
1882 if (tail != NULL)
1883 {
1884 conv_restlen = (int)((ptr + size) - tail);
1885 mch_memmove(conv_rest, (char_u *)tail, conv_restlen);
1886 size -= conv_restlen;
1887 }
1888
1889
1890 while (p > ptr)
1891 {
1892 if (fio_flags & FIO_LATIN1)
1893 u8c = *--p;
1894 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1895 {
1896 if (fio_flags & FIO_ENDIAN_L)
1897 {
1898 u8c = (*--p << 8);
1899 u8c += *--p;
1900 }
1901 else
1902 {
1903 u8c = *--p;
1904 u8c += (*--p << 8);
1905 }
1906 if ((fio_flags & FIO_UTF16)
1907 && u8c >= 0xdc00 && u8c <= 0xdfff)
1908 {
1909 int u16c;
1910
1911 if (p == ptr)
1912 {
1913 /* Missing leading word. */
1914 if (can_retry)
1915 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001916 if (conv_error == 0)
1917 conv_error = readfile_linenr(linecnt,
1918 ptr, p);
1919 if (bad_char_behavior == BAD_DROP)
1920 continue;
1921 if (bad_char_behavior != BAD_KEEP)
1922 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001923 }
1924
1925 /* found second word of double-word, get the first
1926 * word and compute the resulting character */
1927 if (fio_flags & FIO_ENDIAN_L)
1928 {
1929 u16c = (*--p << 8);
1930 u16c += *--p;
1931 }
1932 else
1933 {
1934 u16c = *--p;
1935 u16c += (*--p << 8);
1936 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001937 u8c = 0x10000 + ((u16c & 0x3ff) << 10)
1938 + (u8c & 0x3ff);
1939
Bram Moolenaar071d4272004-06-13 20:20:40 +00001940 /* Check if the word is indeed a leading word. */
1941 if (u16c < 0xd800 || u16c > 0xdbff)
1942 {
1943 if (can_retry)
1944 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001945 if (conv_error == 0)
1946 conv_error = readfile_linenr(linecnt,
1947 ptr, p);
1948 if (bad_char_behavior == BAD_DROP)
1949 continue;
1950 if (bad_char_behavior != BAD_KEEP)
1951 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001952 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001953 }
1954 }
1955 else if (fio_flags & FIO_UCS4)
1956 {
1957 if (fio_flags & FIO_ENDIAN_L)
1958 {
Bram Moolenaardc1c9812017-10-27 22:15:24 +02001959 u8c = (unsigned)*--p << 24;
1960 u8c += (unsigned)*--p << 16;
1961 u8c += (unsigned)*--p << 8;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001962 u8c += *--p;
1963 }
1964 else /* big endian */
1965 {
1966 u8c = *--p;
Bram Moolenaardc1c9812017-10-27 22:15:24 +02001967 u8c += (unsigned)*--p << 8;
1968 u8c += (unsigned)*--p << 16;
1969 u8c += (unsigned)*--p << 24;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001970 }
1971 }
1972 else /* UTF-8 */
1973 {
1974 if (*--p < 0x80)
1975 u8c = *p;
1976 else
1977 {
1978 len = utf_head_off(ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001979 p -= len;
1980 u8c = utf_ptr2char(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001981 if (len == 0)
1982 {
1983 /* Not a valid UTF-8 character, retry with
1984 * another fenc when possible, otherwise just
1985 * report the error. */
1986 if (can_retry)
1987 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001988 if (conv_error == 0)
1989 conv_error = readfile_linenr(linecnt,
1990 ptr, p);
1991 if (bad_char_behavior == BAD_DROP)
1992 continue;
1993 if (bad_char_behavior != BAD_KEEP)
1994 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001995 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001996 }
1997 }
1998 if (enc_utf8) /* produce UTF-8 */
1999 {
2000 dest -= utf_char2len(u8c);
2001 (void)utf_char2bytes(u8c, dest);
2002 }
2003 else /* produce Latin1 */
2004 {
2005 --dest;
2006 if (u8c >= 0x100)
2007 {
2008 /* character doesn't fit in latin1, retry with
2009 * another fenc when possible, otherwise just
2010 * report the error. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002011 if (can_retry)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002012 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002013 if (conv_error == 0)
2014 conv_error = readfile_linenr(linecnt, ptr, p);
2015 if (bad_char_behavior == BAD_DROP)
2016 ++dest;
2017 else if (bad_char_behavior == BAD_KEEP)
2018 *dest = u8c;
2019 else if (eap != NULL && eap->bad_char != 0)
2020 *dest = bad_char_behavior;
2021 else
2022 *dest = 0xBF;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002023 }
2024 else
2025 *dest = u8c;
2026 }
2027 }
2028
2029 /* move the linerest to before the converted characters */
2030 line_start = dest - linerest;
2031 mch_memmove(line_start, buffer, (size_t)linerest);
2032 size = (long)((ptr + real_size) - dest);
2033 ptr = dest;
2034 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002035 else if (enc_utf8 && !curbuf->b_p_bin)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002036 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002037 int incomplete_tail = FALSE;
2038
2039 /* Reading UTF-8: Check if the bytes are valid UTF-8. */
2040 for (p = ptr; ; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002041 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002042 int todo = (int)((ptr + size) - p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002043 int l;
2044
2045 if (todo <= 0)
2046 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002047 if (*p >= 0x80)
2048 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002049 /* A length of 1 means it's an illegal byte. Accept
2050 * an incomplete character at the end though, the next
2051 * read() will get the next bytes, we'll check it
2052 * then. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002053 l = utf_ptr2len_len(p, todo);
Bram Moolenaarf453d352008-06-04 17:37:34 +00002054 if (l > todo && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002055 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002056 /* Avoid retrying with a different encoding when
2057 * a truncated file is more likely, or attempting
2058 * to read the rest of an incomplete sequence when
2059 * we have already done so. */
2060 if (p > ptr || filesize > 0)
2061 incomplete_tail = TRUE;
2062 /* Incomplete byte sequence, move it to conv_rest[]
2063 * and try to read the rest of it, unless we've
2064 * already done so. */
2065 if (p > ptr)
2066 {
2067 conv_restlen = todo;
2068 mch_memmove(conv_rest, p, conv_restlen);
2069 size -= conv_restlen;
2070 break;
2071 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002072 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002073 if (l == 1 || l > todo)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002074 {
2075 /* Illegal byte. If we can try another encoding
Bram Moolenaarf453d352008-06-04 17:37:34 +00002076 * do that, unless at EOF where a truncated
2077 * file is more likely than a conversion error. */
2078 if (can_retry && !incomplete_tail)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002079 break;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002080# ifdef USE_ICONV
2081 /* When we did a conversion report an error. */
2082 if (iconv_fd != (iconv_t)-1 && conv_error == 0)
2083 conv_error = readfile_linenr(linecnt, ptr, p);
2084# endif
Bram Moolenaarf453d352008-06-04 17:37:34 +00002085 /* Remember the first linenr with an illegal byte */
2086 if (conv_error == 0 && illegal_byte == 0)
2087 illegal_byte = readfile_linenr(linecnt, ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002088
2089 /* Drop, keep or replace the bad byte. */
2090 if (bad_char_behavior == BAD_DROP)
2091 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002092 mch_memmove(p, p + 1, todo - 1);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002093 --p;
2094 --size;
2095 }
2096 else if (bad_char_behavior != BAD_KEEP)
2097 *p = bad_char_behavior;
2098 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002099 else
2100 p += l - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002101 }
2102 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002103 if (p < ptr + size && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002104 {
2105 /* Detected a UTF-8 error. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002106rewind_retry:
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002107 /* Retry reading with another conversion. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002108# if defined(FEAT_EVAL) && defined(USE_ICONV)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002109 if (*p_ccv != NUL && iconv_fd != (iconv_t)-1)
2110 /* iconv() failed, try 'charconvert' */
2111 did_iconv = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002112 else
2113# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002114 /* use next item from 'fileencodings' */
2115 advance_fenc = TRUE;
2116 file_rewind = TRUE;
2117 goto retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002118 }
2119 }
2120#endif
2121
2122 /* count the number of characters (after conversion!) */
2123 filesize += size;
2124
2125 /*
2126 * when reading the first part of a file: guess EOL type
2127 */
2128 if (fileformat == EOL_UNKNOWN)
2129 {
2130 /* First try finding a NL, for Dos and Unix */
2131 if (try_dos || try_unix)
2132 {
Bram Moolenaarc6b72172015-02-27 17:48:09 +01002133 /* Reset the carriage return counter. */
2134 if (try_mac)
2135 try_mac = 1;
2136
Bram Moolenaar071d4272004-06-13 20:20:40 +00002137 for (p = ptr; p < ptr + size; ++p)
2138 {
2139 if (*p == NL)
2140 {
2141 if (!try_unix
2142 || (try_dos && p > ptr && p[-1] == CAR))
2143 fileformat = EOL_DOS;
2144 else
2145 fileformat = EOL_UNIX;
2146 break;
2147 }
Bram Moolenaar05eb6122015-02-17 14:15:19 +01002148 else if (*p == CAR && try_mac)
2149 try_mac++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002150 }
2151
2152 /* Don't give in to EOL_UNIX if EOL_MAC is more likely */
2153 if (fileformat == EOL_UNIX && try_mac)
2154 {
2155 /* Need to reset the counters when retrying fenc. */
2156 try_mac = 1;
2157 try_unix = 1;
2158 for (; p >= ptr && *p != CAR; p--)
2159 ;
2160 if (p >= ptr)
2161 {
2162 for (p = ptr; p < ptr + size; ++p)
2163 {
2164 if (*p == NL)
2165 try_unix++;
2166 else if (*p == CAR)
2167 try_mac++;
2168 }
2169 if (try_mac > try_unix)
2170 fileformat = EOL_MAC;
2171 }
2172 }
Bram Moolenaar05eb6122015-02-17 14:15:19 +01002173 else if (fileformat == EOL_UNKNOWN && try_mac == 1)
2174 /* Looking for CR but found no end-of-line markers at
2175 * all: use the default format. */
2176 fileformat = default_fileformat();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002177 }
2178
2179 /* No NL found: may use Mac format */
2180 if (fileformat == EOL_UNKNOWN && try_mac)
2181 fileformat = EOL_MAC;
2182
2183 /* Still nothing found? Use first format in 'ffs' */
2184 if (fileformat == EOL_UNKNOWN)
2185 fileformat = default_fileformat();
2186
2187 /* if editing a new file: may set p_tx and p_ff */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002188 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002189 set_fileformat(fileformat, OPT_LOCAL);
2190 }
2191 }
2192
2193 /*
2194 * This loop is executed once for every character read.
2195 * Keep it fast!
2196 */
2197 if (fileformat == EOL_MAC)
2198 {
2199 --ptr;
2200 while (++ptr, --size >= 0)
2201 {
2202 /* catch most common case first */
2203 if ((c = *ptr) != NUL && c != CAR && c != NL)
2204 continue;
2205 if (c == NUL)
2206 *ptr = NL; /* NULs are replaced by newlines! */
2207 else if (c == NL)
2208 *ptr = CAR; /* NLs are replaced by CRs! */
2209 else
2210 {
2211 if (skip_count == 0)
2212 {
2213 *ptr = NUL; /* end of line */
2214 len = (colnr_T) (ptr - line_start + 1);
2215 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2216 {
2217 error = TRUE;
2218 break;
2219 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002220#ifdef FEAT_PERSISTENT_UNDO
2221 if (read_undo_file)
2222 sha256_update(&sha_ctx, line_start, len);
2223#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002224 ++lnum;
2225 if (--read_count == 0)
2226 {
2227 error = TRUE; /* break loop */
2228 line_start = ptr; /* nothing left to write */
2229 break;
2230 }
2231 }
2232 else
2233 --skip_count;
2234 line_start = ptr + 1;
2235 }
2236 }
2237 }
2238 else
2239 {
2240 --ptr;
2241 while (++ptr, --size >= 0)
2242 {
2243 if ((c = *ptr) != NUL && c != NL) /* catch most common case */
2244 continue;
2245 if (c == NUL)
2246 *ptr = NL; /* NULs are replaced by newlines! */
2247 else
2248 {
2249 if (skip_count == 0)
2250 {
2251 *ptr = NUL; /* end of line */
2252 len = (colnr_T)(ptr - line_start + 1);
2253 if (fileformat == EOL_DOS)
2254 {
Bram Moolenaar2aa5f692017-01-24 15:46:48 +01002255 if (ptr > line_start && ptr[-1] == CAR)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002256 {
Bram Moolenaar2aa5f692017-01-24 15:46:48 +01002257 /* remove CR before NL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002258 ptr[-1] = NUL;
2259 --len;
2260 }
2261 /*
2262 * Reading in Dos format, but no CR-LF found!
2263 * When 'fileformats' includes "unix", delete all
2264 * the lines read so far and start all over again.
2265 * Otherwise give an error message later.
2266 */
2267 else if (ff_error != EOL_DOS)
2268 {
2269 if ( try_unix
2270 && !read_stdin
2271 && (read_buffer
Bram Moolenaar8767f522016-07-01 17:17:39 +02002272 || vim_lseek(fd, (off_T)0L, SEEK_SET)
2273 == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002274 {
2275 fileformat = EOL_UNIX;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002276 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002277 set_fileformat(EOL_UNIX, OPT_LOCAL);
2278 file_rewind = TRUE;
2279 keep_fileformat = TRUE;
2280 goto retry;
2281 }
2282 ff_error = EOL_DOS;
2283 }
2284 }
2285 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2286 {
2287 error = TRUE;
2288 break;
2289 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002290#ifdef FEAT_PERSISTENT_UNDO
2291 if (read_undo_file)
2292 sha256_update(&sha_ctx, line_start, len);
2293#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002294 ++lnum;
2295 if (--read_count == 0)
2296 {
2297 error = TRUE; /* break loop */
2298 line_start = ptr; /* nothing left to write */
2299 break;
2300 }
2301 }
2302 else
2303 --skip_count;
2304 line_start = ptr + 1;
2305 }
2306 }
2307 }
2308 linerest = (long)(ptr - line_start);
2309 ui_breakcheck();
2310 }
2311
2312failed:
2313 /* not an error, max. number of lines reached */
2314 if (error && read_count == 0)
2315 error = FALSE;
2316
2317 /*
2318 * If we get EOF in the middle of a line, note the fact and
2319 * complete the line ourselves.
2320 * In Dos format ignore a trailing CTRL-Z, unless 'binary' set.
2321 */
2322 if (!error
2323 && !got_int
2324 && linerest != 0
2325 && !(!curbuf->b_p_bin
2326 && fileformat == EOL_DOS
2327 && *line_start == Ctrl_Z
2328 && ptr == line_start + 1))
2329 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002330 /* remember for when writing */
2331 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002332 curbuf->b_p_eol = FALSE;
2333 *ptr = NUL;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002334 len = (colnr_T)(ptr - line_start + 1);
2335 if (ml_append(lnum, line_start, len, newfile) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002336 error = TRUE;
2337 else
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002338 {
2339#ifdef FEAT_PERSISTENT_UNDO
2340 if (read_undo_file)
2341 sha256_update(&sha_ctx, line_start, len);
2342#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002343 read_no_eol_lnum = ++lnum;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002344 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002345 }
2346
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002347 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002348 save_file_ff(curbuf); /* remember the current file format */
2349
2350#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002351 if (curbuf->b_cryptstate != NULL)
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002352 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002353 crypt_free_state(curbuf->b_cryptstate);
2354 curbuf->b_cryptstate = NULL;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002355 }
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002356 if (cryptkey != NULL && cryptkey != curbuf->b_p_key)
2357 crypt_free_key(cryptkey);
2358 /* Don't set cryptkey to NULL, it's used below as a flag that
2359 * encryption was used. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002360#endif
2361
2362#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002363 /* If editing a new file: set 'fenc' for the current buffer.
2364 * Also for ":read ++edit file". */
2365 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002366 set_string_option_direct((char_u *)"fenc", -1, fenc,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00002367 OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002368 if (fenc_alloced)
2369 vim_free(fenc);
2370# ifdef USE_ICONV
2371 if (iconv_fd != (iconv_t)-1)
2372 {
2373 iconv_close(iconv_fd);
2374 iconv_fd = (iconv_t)-1;
2375 }
2376# endif
2377#endif
2378
2379 if (!read_buffer && !read_stdin)
2380 close(fd); /* errors are ignored */
Bram Moolenaarf05da212009-11-17 16:13:15 +00002381#ifdef HAVE_FD_CLOEXEC
2382 else
2383 {
2384 int fdflags = fcntl(fd, F_GETFD);
2385 if (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0)
Bram Moolenaarfbc4b4d2016-02-07 15:14:01 +01002386 (void)fcntl(fd, F_SETFD, fdflags | FD_CLOEXEC);
Bram Moolenaarf05da212009-11-17 16:13:15 +00002387 }
2388#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002389 vim_free(buffer);
2390
2391#ifdef HAVE_DUP
2392 if (read_stdin)
2393 {
2394 /* Use stderr for stdin, makes shell commands work. */
2395 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00002396 ignored = dup(2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002397 }
2398#endif
2399
2400#ifdef FEAT_MBYTE
2401 if (tmpname != NULL)
2402 {
2403 mch_remove(tmpname); /* delete converted file */
2404 vim_free(tmpname);
2405 }
2406#endif
2407 --no_wait_return; /* may wait for return now */
2408
2409 /*
2410 * In recovery mode everything but autocommands is skipped.
2411 */
2412 if (!recoverymode)
2413 {
2414 /* need to delete the last line, which comes from the empty buffer */
2415 if (newfile && wasempty && !(curbuf->b_ml.ml_flags & ML_EMPTY))
2416 {
2417#ifdef FEAT_NETBEANS_INTG
2418 netbeansFireChanges = 0;
2419#endif
2420 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
2421#ifdef FEAT_NETBEANS_INTG
2422 netbeansFireChanges = 1;
2423#endif
2424 --linecnt;
2425 }
2426 linecnt = curbuf->b_ml.ml_line_count - linecnt;
2427 if (filesize == 0)
2428 linecnt = 0;
2429 if (newfile || read_buffer)
Bram Moolenaar7263a772007-05-10 17:35:54 +00002430 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002431 redraw_curbuf_later(NOT_VALID);
Bram Moolenaar7263a772007-05-10 17:35:54 +00002432#ifdef FEAT_DIFF
2433 /* After reading the text into the buffer the diff info needs to
2434 * be updated. */
2435 diff_invalidate(curbuf);
2436#endif
2437#ifdef FEAT_FOLDING
2438 /* All folds in the window are invalid now. Mark them for update
2439 * before triggering autocommands. */
2440 foldUpdateAll(curwin);
2441#endif
2442 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002443 else if (linecnt) /* appended at least one line */
2444 appended_lines_mark(from, linecnt);
2445
Bram Moolenaar071d4272004-06-13 20:20:40 +00002446#ifndef ALWAYS_USE_GUI
2447 /*
2448 * If we were reading from the same terminal as where messages go,
2449 * the screen will have been messed up.
2450 * Switch on raw mode now and clear the screen.
2451 */
2452 if (read_stdin)
2453 {
2454 settmode(TMODE_RAW); /* set to raw mode */
2455 starttermcap();
2456 screenclear();
2457 }
2458#endif
2459
2460 if (got_int)
2461 {
2462 if (!(flags & READ_DUMMY))
2463 {
2464 filemess(curbuf, sfname, (char_u *)_(e_interr), 0);
2465 if (newfile)
2466 curbuf->b_p_ro = TRUE; /* must use "w!" now */
2467 }
2468 msg_scroll = msg_save;
2469#ifdef FEAT_VIMINFO
2470 check_marks_read();
2471#endif
2472 return OK; /* an interrupt isn't really an error */
2473 }
2474
2475 if (!filtering && !(flags & READ_DUMMY))
2476 {
2477 msg_add_fname(curbuf, sfname); /* fname in IObuff with quotes */
2478 c = FALSE;
2479
2480#ifdef UNIX
2481# ifdef S_ISFIFO
2482 if (S_ISFIFO(perm)) /* fifo or socket */
2483 {
2484 STRCAT(IObuff, _("[fifo/socket]"));
2485 c = TRUE;
2486 }
2487# else
2488# ifdef S_IFIFO
2489 if ((perm & S_IFMT) == S_IFIFO) /* fifo */
2490 {
2491 STRCAT(IObuff, _("[fifo]"));
2492 c = TRUE;
2493 }
2494# endif
2495# ifdef S_IFSOCK
2496 if ((perm & S_IFMT) == S_IFSOCK) /* or socket */
2497 {
2498 STRCAT(IObuff, _("[socket]"));
2499 c = TRUE;
2500 }
2501# endif
2502# endif
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002503# ifdef OPEN_CHR_FILES
2504 if (S_ISCHR(perm)) /* or character special */
2505 {
2506 STRCAT(IObuff, _("[character special]"));
2507 c = TRUE;
2508 }
2509# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002510#endif
2511 if (curbuf->b_p_ro)
2512 {
2513 STRCAT(IObuff, shortmess(SHM_RO) ? _("[RO]") : _("[readonly]"));
2514 c = TRUE;
2515 }
2516 if (read_no_eol_lnum)
2517 {
2518 msg_add_eol();
2519 c = TRUE;
2520 }
2521 if (ff_error == EOL_DOS)
2522 {
2523 STRCAT(IObuff, _("[CR missing]"));
2524 c = TRUE;
2525 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002526 if (split)
2527 {
2528 STRCAT(IObuff, _("[long lines split]"));
2529 c = TRUE;
2530 }
2531#ifdef FEAT_MBYTE
2532 if (notconverted)
2533 {
2534 STRCAT(IObuff, _("[NOT converted]"));
2535 c = TRUE;
2536 }
2537 else if (converted)
2538 {
2539 STRCAT(IObuff, _("[converted]"));
2540 c = TRUE;
2541 }
2542#endif
2543#ifdef FEAT_CRYPT
2544 if (cryptkey != NULL)
2545 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002546 crypt_append_msg(curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002547 c = TRUE;
2548 }
2549#endif
2550#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002551 if (conv_error != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002552 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002553 sprintf((char *)IObuff + STRLEN(IObuff),
2554 _("[CONVERSION ERROR in line %ld]"), (long)conv_error);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002555 c = TRUE;
2556 }
2557 else if (illegal_byte > 0)
2558 {
2559 sprintf((char *)IObuff + STRLEN(IObuff),
2560 _("[ILLEGAL BYTE in line %ld]"), (long)illegal_byte);
2561 c = TRUE;
2562 }
2563 else
2564#endif
2565 if (error)
2566 {
2567 STRCAT(IObuff, _("[READ ERRORS]"));
2568 c = TRUE;
2569 }
2570 if (msg_add_fileformat(fileformat))
2571 c = TRUE;
2572#ifdef FEAT_CRYPT
2573 if (cryptkey != NULL)
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002574 msg_add_lines(c, (long)linecnt, filesize
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002575 - crypt_get_header_len(crypt_get_method_nr(curbuf)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002576 else
2577#endif
2578 msg_add_lines(c, (long)linecnt, filesize);
2579
2580 vim_free(keep_msg);
2581 keep_msg = NULL;
2582 msg_scrolled_ign = TRUE;
2583#ifdef ALWAYS_USE_GUI
2584 /* Don't show the message when reading stdin, it would end up in a
2585 * message box (which might be shown when exiting!) */
2586 if (read_stdin || read_buffer)
2587 p = msg_may_trunc(FALSE, IObuff);
2588 else
2589#endif
2590 p = msg_trunc_attr(IObuff, FALSE, 0);
2591 if (read_stdin || read_buffer || restart_edit != 0
Bram Moolenaar1c7715d2005-10-03 22:02:18 +00002592 || (msg_scrolled != 0 && !need_wait_return))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002593 /* Need to repeat the message after redrawing when:
2594 * - When reading from stdin (the screen will be cleared next).
2595 * - When restart_edit is set (otherwise there will be a delay
2596 * before redrawing).
2597 * - When the screen was scrolled but there is no wait-return
2598 * prompt. */
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002599 set_keep_msg(p, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002600 msg_scrolled_ign = FALSE;
2601 }
2602
2603 /* with errors writing the file requires ":w!" */
2604 if (newfile && (error
2605#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002606 || conv_error != 0
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002607 || (illegal_byte > 0 && bad_char_behavior != BAD_KEEP)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002608#endif
2609 ))
2610 curbuf->b_p_ro = TRUE;
2611
2612 u_clearline(); /* cannot use "U" command after adding lines */
2613
2614 /*
2615 * In Ex mode: cursor at last new line.
2616 * Otherwise: cursor at first new line.
2617 */
2618 if (exmode_active)
2619 curwin->w_cursor.lnum = from + linecnt;
2620 else
2621 curwin->w_cursor.lnum = from + 1;
2622 check_cursor_lnum();
2623 beginline(BL_WHITE | BL_FIX); /* on first non-blank */
2624
2625 /*
2626 * Set '[ and '] marks to the newly read lines.
2627 */
2628 curbuf->b_op_start.lnum = from + 1;
2629 curbuf->b_op_start.col = 0;
2630 curbuf->b_op_end.lnum = from + linecnt;
2631 curbuf->b_op_end.col = 0;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002632
2633#ifdef WIN32
2634 /*
2635 * Work around a weird problem: When a file has two links (only
2636 * possible on NTFS) and we write through one link, then stat() it
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00002637 * through the other link, the timestamp information may be wrong.
Bram Moolenaar03f48552006-02-28 23:52:23 +00002638 * It's correct again after reading the file, thus reset the timestamp
2639 * here.
2640 */
2641 if (newfile && !read_stdin && !read_buffer
2642 && mch_stat((char *)fname, &st) >= 0)
2643 {
2644 buf_store_time(curbuf, &st, fname);
2645 curbuf->b_mtime_read = curbuf->b_mtime;
2646 }
2647#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002648 }
2649 msg_scroll = msg_save;
2650
2651#ifdef FEAT_VIMINFO
2652 /*
2653 * Get the marks before executing autocommands, so they can be used there.
2654 */
2655 check_marks_read();
2656#endif
2657
Bram Moolenaar071d4272004-06-13 20:20:40 +00002658 /*
Bram Moolenaar34d72d42015-07-17 14:18:08 +02002659 * We remember if the last line of the read didn't have
2660 * an eol even when 'binary' is off, to support turning 'fixeol' off,
2661 * or writing the read again with 'binary' on. The latter is required
2662 * for ":autocmd FileReadPost *.gz set bin|'[,']!gunzip" to work.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002663 */
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002664 curbuf->b_no_eol_lnum = read_no_eol_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002665
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02002666 /* When reloading a buffer put the cursor at the first line that is
2667 * different. */
2668 if (flags & READ_KEEP_UNDO)
2669 u_find_first_changed();
2670
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002671#ifdef FEAT_PERSISTENT_UNDO
2672 /*
2673 * When opening a new file locate undo info and read it.
2674 */
2675 if (read_undo_file)
2676 {
2677 char_u hash[UNDO_HASH_SIZE];
2678
2679 sha256_finish(&sha_ctx, hash);
Bram Moolenaar6ed8ed82010-05-30 20:40:11 +02002680 u_read_undo(NULL, hash, fname);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002681 }
2682#endif
2683
Bram Moolenaardf177f62005-02-22 08:39:57 +00002684#ifdef FEAT_AUTOCMD
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02002685 if (!read_stdin && !read_fifo && (!read_buffer || sfname != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002686 {
2687 int m = msg_scroll;
2688 int n = msg_scrolled;
2689
2690 /* Save the fileformat now, otherwise the buffer will be considered
2691 * modified if the format/encoding was automatically detected. */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002692 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002693 save_file_ff(curbuf);
2694
2695 /*
2696 * The output from the autocommands should not overwrite anything and
2697 * should not be overwritten: Set msg_scroll, restore its value if no
2698 * output was done.
2699 */
2700 msg_scroll = TRUE;
2701 if (filtering)
2702 apply_autocmds_exarg(EVENT_FILTERREADPOST, NULL, sfname,
2703 FALSE, curbuf, eap);
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02002704 else if (newfile || (read_buffer && sfname != NULL))
Bram Moolenaarc3691332016-04-20 12:49:49 +02002705 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002706 apply_autocmds_exarg(EVENT_BUFREADPOST, NULL, sfname,
2707 FALSE, curbuf, eap);
Bram Moolenaarc3691332016-04-20 12:49:49 +02002708 if (!au_did_filetype && *curbuf->b_p_ft != NUL)
2709 /*
2710 * EVENT_FILETYPE was not triggered but the buffer already has a
2711 * filetype. Trigger EVENT_FILETYPE using the existing filetype.
2712 */
2713 apply_autocmds(EVENT_FILETYPE, curbuf->b_p_ft, curbuf->b_fname,
2714 TRUE, curbuf);
2715 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002716 else
2717 apply_autocmds_exarg(EVENT_FILEREADPOST, sfname, sfname,
2718 FALSE, NULL, eap);
2719 if (msg_scrolled == n)
2720 msg_scroll = m;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002721# ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002722 if (aborting()) /* autocmds may abort script processing */
2723 return FAIL;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002724# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002725 }
2726#endif
2727
2728 if (recoverymode && error)
2729 return FAIL;
2730 return OK;
2731}
2732
Bram Moolenaarf04507d2016-08-20 15:05:39 +02002733#if defined(OPEN_CHR_FILES) || defined(PROTO)
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002734/*
2735 * Returns TRUE if the file name argument is of the form "/dev/fd/\d\+",
2736 * which is the name of files used for process substitution output by
2737 * some shells on some operating systems, e.g., bash on SunOS.
2738 * Do not accept "/dev/fd/[012]", opening these may hang Vim.
2739 */
Bram Moolenaarf04507d2016-08-20 15:05:39 +02002740 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002741is_dev_fd_file(char_u *fname)
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002742{
2743 return (STRNCMP(fname, "/dev/fd/", 8) == 0
2744 && VIM_ISDIGIT(fname[8])
2745 && *skipdigits(fname + 9) == NUL
2746 && (fname[9] != NUL
2747 || (fname[8] != '0' && fname[8] != '1' && fname[8] != '2')));
2748}
2749#endif
2750
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002751#ifdef FEAT_MBYTE
2752
2753/*
2754 * From the current line count and characters read after that, estimate the
2755 * line number where we are now.
2756 * Used for error messages that include a line number.
2757 */
2758 static linenr_T
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002759readfile_linenr(
2760 linenr_T linecnt, /* line count before reading more bytes */
2761 char_u *p, /* start of more bytes read */
2762 char_u *endp) /* end of more bytes read */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002763{
2764 char_u *s;
2765 linenr_T lnum;
2766
2767 lnum = curbuf->b_ml.ml_line_count - linecnt + 1;
2768 for (s = p; s < endp; ++s)
2769 if (*s == '\n')
2770 ++lnum;
2771 return lnum;
2772}
2773#endif
2774
Bram Moolenaar071d4272004-06-13 20:20:40 +00002775/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00002776 * Fill "*eap" to force the 'fileencoding', 'fileformat' and 'binary to be
2777 * equal to the buffer "buf". Used for calling readfile().
Bram Moolenaar071d4272004-06-13 20:20:40 +00002778 * Returns OK or FAIL.
2779 */
2780 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002781prep_exarg(exarg_T *eap, buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002782{
2783 eap->cmd = alloc((unsigned)(STRLEN(buf->b_p_ff)
2784#ifdef FEAT_MBYTE
2785 + STRLEN(buf->b_p_fenc)
2786#endif
2787 + 15));
2788 if (eap->cmd == NULL)
2789 return FAIL;
2790
2791#ifdef FEAT_MBYTE
2792 sprintf((char *)eap->cmd, "e ++ff=%s ++enc=%s", buf->b_p_ff, buf->b_p_fenc);
2793 eap->force_enc = 14 + (int)STRLEN(buf->b_p_ff);
Bram Moolenaar195d6352005-12-19 22:08:24 +00002794 eap->bad_char = buf->b_bad_char;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002795#else
2796 sprintf((char *)eap->cmd, "e ++ff=%s", buf->b_p_ff);
2797#endif
2798 eap->force_ff = 7;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002799
2800 eap->force_bin = buf->b_p_bin ? FORCE_BIN : FORCE_NOBIN;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002801 eap->read_edit = FALSE;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002802 eap->forceit = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002803 return OK;
2804}
2805
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002806/*
2807 * Set default or forced 'fileformat' and 'binary'.
2808 */
2809 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002810set_file_options(int set_options, exarg_T *eap)
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002811{
2812 /* set default 'fileformat' */
2813 if (set_options)
2814 {
2815 if (eap != NULL && eap->force_ff != 0)
2816 set_fileformat(get_fileformat_force(curbuf, eap), OPT_LOCAL);
2817 else if (*p_ffs != NUL)
2818 set_fileformat(default_fileformat(), OPT_LOCAL);
2819 }
2820
2821 /* set or reset 'binary' */
2822 if (eap != NULL && eap->force_bin != 0)
2823 {
2824 int oldval = curbuf->b_p_bin;
2825
2826 curbuf->b_p_bin = (eap->force_bin == FORCE_BIN);
2827 set_options_bin(oldval, curbuf->b_p_bin, OPT_LOCAL);
2828 }
2829}
2830
2831#if defined(FEAT_MBYTE) || defined(PROTO)
2832/*
2833 * Set forced 'fileencoding'.
2834 */
2835 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002836set_forced_fenc(exarg_T *eap)
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002837{
2838 if (eap->force_enc != 0)
2839 {
2840 char_u *fenc = enc_canonize(eap->cmd + eap->force_enc);
2841
2842 if (fenc != NULL)
2843 set_string_option_direct((char_u *)"fenc", -1,
2844 fenc, OPT_FREE|OPT_LOCAL, 0);
2845 vim_free(fenc);
2846 }
2847}
2848
Bram Moolenaar071d4272004-06-13 20:20:40 +00002849/*
2850 * Find next fileencoding to use from 'fileencodings'.
2851 * "pp" points to fenc_next. It's advanced to the next item.
2852 * When there are no more items, an empty string is returned and *pp is set to
2853 * NULL.
2854 * When *pp is not set to NULL, the result is in allocated memory.
2855 */
2856 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002857next_fenc(char_u **pp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002858{
2859 char_u *p;
2860 char_u *r;
2861
2862 if (**pp == NUL)
2863 {
2864 *pp = NULL;
2865 return (char_u *)"";
2866 }
2867 p = vim_strchr(*pp, ',');
2868 if (p == NULL)
2869 {
2870 r = enc_canonize(*pp);
2871 *pp += STRLEN(*pp);
2872 }
2873 else
2874 {
2875 r = vim_strnsave(*pp, (int)(p - *pp));
2876 *pp = p + 1;
2877 if (r != NULL)
2878 {
2879 p = enc_canonize(r);
2880 vim_free(r);
2881 r = p;
2882 }
2883 }
2884 if (r == NULL) /* out of memory */
2885 {
2886 r = (char_u *)"";
2887 *pp = NULL;
2888 }
2889 return r;
2890}
2891
2892# ifdef FEAT_EVAL
2893/*
2894 * Convert a file with the 'charconvert' expression.
2895 * This closes the file which is to be read, converts it and opens the
2896 * resulting file for reading.
2897 * Returns name of the resulting converted file (the caller should delete it
2898 * after reading it).
2899 * Returns NULL if the conversion failed ("*fdp" is not set) .
2900 */
2901 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002902readfile_charconvert(
2903 char_u *fname, /* name of input file */
2904 char_u *fenc, /* converted from */
2905 int *fdp) /* in/out: file descriptor of file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002906{
2907 char_u *tmpname;
2908 char_u *errmsg = NULL;
2909
Bram Moolenaare5c421c2015-03-31 13:33:08 +02002910 tmpname = vim_tempname('r', FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002911 if (tmpname == NULL)
2912 errmsg = (char_u *)_("Can't find temp file for conversion");
2913 else
2914 {
2915 close(*fdp); /* close the input file, ignore errors */
2916 *fdp = -1;
2917 if (eval_charconvert(fenc, enc_utf8 ? (char_u *)"utf-8" : p_enc,
2918 fname, tmpname) == FAIL)
2919 errmsg = (char_u *)_("Conversion with 'charconvert' failed");
2920 if (errmsg == NULL && (*fdp = mch_open((char *)tmpname,
2921 O_RDONLY | O_EXTRA, 0)) < 0)
2922 errmsg = (char_u *)_("can't read output of 'charconvert'");
2923 }
2924
2925 if (errmsg != NULL)
2926 {
2927 /* Don't use emsg(), it breaks mappings, the retry with
2928 * another type of conversion might still work. */
2929 MSG(errmsg);
2930 if (tmpname != NULL)
2931 {
2932 mch_remove(tmpname); /* delete converted file */
2933 vim_free(tmpname);
2934 tmpname = NULL;
2935 }
2936 }
2937
2938 /* If the input file is closed, open it (caller should check for error). */
2939 if (*fdp < 0)
2940 *fdp = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
2941
2942 return tmpname;
2943}
2944# endif
2945
2946#endif
2947
2948#ifdef FEAT_VIMINFO
2949/*
2950 * Read marks for the current buffer from the viminfo file, when we support
2951 * buffer marks and the buffer has a name.
2952 */
2953 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002954check_marks_read(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002955{
2956 if (!curbuf->b_marks_read && get_viminfo_parameter('\'') > 0
2957 && curbuf->b_ffname != NULL)
Bram Moolenaard812df62008-11-09 12:46:09 +00002958 read_viminfo(NULL, VIF_WANT_MARKS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002959
2960 /* Always set b_marks_read; needed when 'viminfo' is changed to include
2961 * the ' parameter after opening a buffer. */
2962 curbuf->b_marks_read = TRUE;
2963}
2964#endif
2965
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002966#if defined(FEAT_CRYPT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002967/*
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002968 * Check for magic number used for encryption. Applies to the current buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002969 * If found, the magic number is removed from ptr[*sizep] and *sizep and
2970 * *filesizep are updated.
2971 * Return the (new) encryption key, NULL for no encryption.
2972 */
2973 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002974check_for_cryptkey(
2975 char_u *cryptkey, /* previous encryption key or NULL */
2976 char_u *ptr, /* pointer to read bytes */
2977 long *sizep, /* length of read bytes */
Bram Moolenaar8767f522016-07-01 17:17:39 +02002978 off_T *filesizep, /* nr of bytes used from file */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002979 int newfile, /* editing a new buffer */
2980 char_u *fname, /* file name to display */
2981 int *did_ask) /* flag: whether already asked for key */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002982{
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002983 int method = crypt_method_nr_from_magic((char *)ptr, *sizep);
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02002984 int b_p_ro = curbuf->b_p_ro;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002985
2986 if (method >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002987 {
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02002988 /* Mark the buffer as read-only until the decryption has taken place.
2989 * Avoids accidentally overwriting the file with garbage. */
2990 curbuf->b_p_ro = TRUE;
2991
Bram Moolenaar2be79502014-08-13 21:58:28 +02002992 /* Set the cryptmethod local to the buffer. */
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002993 crypt_set_cm_option(curbuf, method);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002994 if (cryptkey == NULL && !*did_ask)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002995 {
2996 if (*curbuf->b_p_key)
2997 cryptkey = curbuf->b_p_key;
2998 else
2999 {
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003000 /* When newfile is TRUE, store the typed key in the 'key'
3001 * option and don't free it. bf needs hash of the key saved.
Bram Moolenaarf50a2532010-05-21 15:36:08 +02003002 * Don't ask for the key again when first time Enter was hit.
3003 * Happens when retrying to detect encoding. */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003004 smsg((char_u *)_(need_key_msg), fname);
3005 msg_scroll = TRUE;
Bram Moolenaar3a0c9082014-11-12 15:15:42 +01003006 crypt_check_method(method);
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003007 cryptkey = crypt_get_key(newfile, FALSE);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02003008 *did_ask = TRUE;
3009
Bram Moolenaar071d4272004-06-13 20:20:40 +00003010 /* check if empty key entered */
3011 if (cryptkey != NULL && *cryptkey == NUL)
3012 {
3013 if (cryptkey != curbuf->b_p_key)
3014 vim_free(cryptkey);
3015 cryptkey = NULL;
3016 }
3017 }
3018 }
3019
3020 if (cryptkey != NULL)
3021 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003022 int header_len;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003023
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003024 curbuf->b_cryptstate = crypt_create_from_header(
3025 method, cryptkey, ptr);
3026 crypt_set_cm_option(curbuf, method);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003027
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003028 /* Remove cryptmethod specific header from the text. */
3029 header_len = crypt_get_header_len(method);
Bram Moolenaar680e0152016-09-25 20:54:11 +02003030 if (*sizep <= header_len)
3031 /* invalid header, buffer can't be encrypted */
3032 return NULL;
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003033 *filesizep += header_len;
3034 *sizep -= header_len;
3035 mch_memmove(ptr, ptr + header_len, (size_t)*sizep);
3036
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02003037 /* Restore the read-only flag. */
3038 curbuf->b_p_ro = b_p_ro;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003039 }
3040 }
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003041 /* When starting to edit a new file which does not have encryption, clear
3042 * the 'key' option, except when starting up (called with -x argument) */
Bram Moolenaarfa0ff9a2010-07-25 16:05:19 +02003043 else if (newfile && *curbuf->b_p_key != NUL && !starting)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003044 set_option_value((char_u *)"key", 0L, (char_u *)"", OPT_LOCAL);
3045
3046 return cryptkey;
3047}
Bram Moolenaar80794b12010-06-13 05:20:42 +02003048#endif /* FEAT_CRYPT */
3049
Bram Moolenaar071d4272004-06-13 20:20:40 +00003050#ifdef UNIX
3051 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003052set_file_time(
3053 char_u *fname,
3054 time_t atime, /* access time */
3055 time_t mtime) /* modification time */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003056{
3057# if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
3058 struct utimbuf buf;
3059
3060 buf.actime = atime;
3061 buf.modtime = mtime;
3062 (void)utime((char *)fname, &buf);
3063# else
3064# if defined(HAVE_UTIMES)
3065 struct timeval tvp[2];
3066
3067 tvp[0].tv_sec = atime;
3068 tvp[0].tv_usec = 0;
3069 tvp[1].tv_sec = mtime;
3070 tvp[1].tv_usec = 0;
3071# ifdef NeXT
3072 (void)utimes((char *)fname, tvp);
3073# else
3074 (void)utimes((char *)fname, (const struct timeval *)&tvp);
3075# endif
3076# endif
3077# endif
3078}
3079#endif /* UNIX */
3080
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003081#if defined(VMS) && !defined(MIN)
3082/* Older DECC compiler for VAX doesn't define MIN() */
3083# define MIN(a, b) ((a) < (b) ? (a) : (b))
3084#endif
3085
Bram Moolenaar071d4272004-06-13 20:20:40 +00003086/*
Bram Moolenaar5386a122007-06-28 20:02:32 +00003087 * Return TRUE if a file appears to be read-only from the file permissions.
3088 */
3089 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003090check_file_readonly(
3091 char_u *fname, /* full path to file */
3092 int perm) /* known permissions on file */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003093{
3094#ifndef USE_MCH_ACCESS
3095 int fd = 0;
3096#endif
3097
3098 return (
3099#ifdef USE_MCH_ACCESS
3100# ifdef UNIX
3101 (perm & 0222) == 0 ||
3102# endif
3103 mch_access((char *)fname, W_OK)
3104#else
3105 (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0
3106 ? TRUE : (close(fd), FALSE)
3107#endif
3108 );
3109}
3110
3111
3112/*
Bram Moolenaar292ad192005-12-11 21:29:51 +00003113 * buf_write() - write to file "fname" lines "start" through "end"
Bram Moolenaar071d4272004-06-13 20:20:40 +00003114 *
3115 * We do our own buffering here because fwrite() is so slow.
3116 *
Bram Moolenaar292ad192005-12-11 21:29:51 +00003117 * If "forceit" is true, we don't care for errors when attempting backups.
3118 * In case of an error everything possible is done to restore the original
Bram Moolenaare37d50a2008-08-06 17:06:04 +00003119 * file. But when "forceit" is TRUE, we risk losing it.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003120 *
3121 * When "reset_changed" is TRUE and "append" == FALSE and "start" == 1 and
3122 * "end" == curbuf->b_ml.ml_line_count, reset curbuf->b_changed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003123 *
3124 * This function must NOT use NameBuff (because it's called by autowrite()).
3125 *
3126 * return FAIL for failure, OK otherwise
3127 */
3128 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003129buf_write(
3130 buf_T *buf,
3131 char_u *fname,
3132 char_u *sfname,
3133 linenr_T start,
3134 linenr_T end,
3135 exarg_T *eap, /* for forced 'ff' and 'fenc', can be
Bram Moolenaar071d4272004-06-13 20:20:40 +00003136 NULL! */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003137 int append, /* append to the file */
3138 int forceit,
3139 int reset_changed,
3140 int filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003141{
3142 int fd;
3143 char_u *backup = NULL;
3144 int backup_copy = FALSE; /* copy the original file? */
3145 int dobackup;
3146 char_u *ffname;
3147 char_u *wfname = NULL; /* name of file to write to */
3148 char_u *s;
3149 char_u *ptr;
3150 char_u c;
3151 int len;
3152 linenr_T lnum;
3153 long nchars;
3154 char_u *errmsg = NULL;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003155 int errmsg_allocated = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003156 char_u *errnum = NULL;
3157 char_u *buffer;
3158 char_u smallbuf[SMBUFSIZE];
3159 char_u *backup_ext;
3160 int bufsize;
3161 long perm; /* file permissions */
3162 int retval = OK;
3163 int newfile = FALSE; /* TRUE if file doesn't exist yet */
3164 int msg_save = msg_scroll;
3165 int overwriting; /* TRUE if writing over original */
3166 int no_eol = FALSE; /* no end-of-line written */
3167 int device = FALSE; /* writing to a device */
Bram Moolenaar8767f522016-07-01 17:17:39 +02003168 stat_T st_old;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003169 int prev_got_int = got_int;
Bram Moolenaare6bf6552017-06-27 22:11:51 +02003170 int checking_conversion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003171 int file_readonly = FALSE; /* overwritten file is read-only */
3172 static char *err_readonly = "is read-only (cannot override: \"W\" in 'cpoptions')";
Bram Moolenaara06ecab2016-07-16 14:47:36 +02003173#if defined(UNIX) /*XXX fix me sometime? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003174 int made_writable = FALSE; /* 'w' bit has been set */
3175#endif
3176 /* writing everything */
3177 int whole = (start == 1 && end == buf->b_ml.ml_line_count);
3178#ifdef FEAT_AUTOCMD
3179 linenr_T old_line_count = buf->b_ml.ml_line_count;
3180#endif
3181 int attr;
3182 int fileformat;
3183 int write_bin;
3184 struct bw_info write_info; /* info for buf_write_bytes() */
3185#ifdef FEAT_MBYTE
3186 int converted = FALSE;
3187 int notconverted = FALSE;
3188 char_u *fenc; /* effective 'fileencoding' */
3189 char_u *fenc_tofree = NULL; /* allocated "fenc" */
3190#endif
3191#ifdef HAS_BW_FLAGS
3192 int wb_flags = 0;
3193#endif
3194#ifdef HAVE_ACL
3195 vim_acl_T acl = NULL; /* ACL copied from original file to
3196 backup or new file */
3197#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003198#ifdef FEAT_PERSISTENT_UNDO
3199 int write_undo_file = FALSE;
3200 context_sha256_T sha_ctx;
3201#endif
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003202 unsigned int bkc = get_bkc_value(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003203
3204 if (fname == NULL || *fname == NUL) /* safety check */
3205 return FAIL;
Bram Moolenaar70d60e92009-12-31 13:53:33 +00003206 if (buf->b_ml.ml_mfp == NULL)
3207 {
3208 /* This can happen during startup when there is a stray "w" in the
3209 * vimrc file. */
3210 EMSG(_(e_emptybuf));
3211 return FAIL;
3212 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003213
3214 /*
3215 * Disallow writing from .exrc and .vimrc in current directory for
3216 * security reasons.
3217 */
3218 if (check_secure())
3219 return FAIL;
3220
3221 /* Avoid a crash for a long name. */
3222 if (STRLEN(fname) >= MAXPATHL)
3223 {
3224 EMSG(_(e_longname));
3225 return FAIL;
3226 }
3227
3228#ifdef FEAT_MBYTE
3229 /* must init bw_conv_buf and bw_iconv_fd before jumping to "fail" */
3230 write_info.bw_conv_buf = NULL;
3231 write_info.bw_conv_error = FALSE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003232 write_info.bw_conv_error_lnum = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003233 write_info.bw_restlen = 0;
3234# ifdef USE_ICONV
3235 write_info.bw_iconv_fd = (iconv_t)-1;
3236# endif
3237#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003238#ifdef FEAT_CRYPT
3239 write_info.bw_buffer = buf;
3240#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003241
Bram Moolenaardf177f62005-02-22 08:39:57 +00003242 /* After writing a file changedtick changes but we don't want to display
3243 * the line. */
3244 ex_no_reprint = TRUE;
3245
Bram Moolenaar071d4272004-06-13 20:20:40 +00003246 /*
3247 * If there is no file name yet, use the one for the written file.
3248 * BF_NOTEDITED is set to reflect this (in case the write fails).
3249 * Don't do this when the write is for a filter command.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003250 * Don't do this when appending.
3251 * Only do this when 'cpoptions' contains the 'F' flag.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003252 */
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003253 if (buf->b_ffname == NULL
3254 && reset_changed
Bram Moolenaar071d4272004-06-13 20:20:40 +00003255 && whole
3256 && buf == curbuf
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00003257#ifdef FEAT_QUICKFIX
3258 && !bt_nofile(buf)
3259#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003260 && !filtering
Bram Moolenaar292ad192005-12-11 21:29:51 +00003261 && (!append || vim_strchr(p_cpo, CPO_FNAMEAPP) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003262 && vim_strchr(p_cpo, CPO_FNAMEW) != NULL)
3263 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003264 if (set_rw_fname(fname, sfname) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003265 return FAIL;
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003266 buf = curbuf; /* just in case autocmds made "buf" invalid */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003267 }
3268
3269 if (sfname == NULL)
3270 sfname = fname;
3271 /*
3272 * For Unix: Use the short file name whenever possible.
3273 * Avoids problems with networks and when directory names are changed.
3274 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
3275 * another directory, which we don't detect
3276 */
3277 ffname = fname; /* remember full fname */
3278#ifdef UNIX
3279 fname = sfname;
3280#endif
3281
3282 if (buf->b_ffname != NULL && fnamecmp(ffname, buf->b_ffname) == 0)
3283 overwriting = TRUE;
3284 else
3285 overwriting = FALSE;
3286
3287 if (exiting)
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003288 settmode(TMODE_COOK); /* when exiting allow typeahead now */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003289
3290 ++no_wait_return; /* don't wait for return yet */
3291
3292 /*
3293 * Set '[ and '] marks to the lines to be written.
3294 */
3295 buf->b_op_start.lnum = start;
3296 buf->b_op_start.col = 0;
3297 buf->b_op_end.lnum = end;
3298 buf->b_op_end.col = 0;
3299
3300#ifdef FEAT_AUTOCMD
3301 {
3302 aco_save_T aco;
3303 int buf_ffname = FALSE;
3304 int buf_sfname = FALSE;
3305 int buf_fname_f = FALSE;
3306 int buf_fname_s = FALSE;
3307 int did_cmd = FALSE;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003308 int nofile_err = FALSE;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003309 int empty_memline = (buf->b_ml.ml_mfp == NULL);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003310 bufref_T bufref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003311
3312 /*
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003313 * Apply PRE autocommands.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003314 * Set curbuf to the buffer to be written.
3315 * Careful: The autocommands may call buf_write() recursively!
3316 */
3317 if (ffname == buf->b_ffname)
3318 buf_ffname = TRUE;
3319 if (sfname == buf->b_sfname)
3320 buf_sfname = TRUE;
3321 if (fname == buf->b_ffname)
3322 buf_fname_f = TRUE;
3323 if (fname == buf->b_sfname)
3324 buf_fname_s = TRUE;
3325
3326 /* set curwin/curbuf to buf and save a few things */
3327 aucmd_prepbuf(&aco, buf);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003328 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003329
3330 if (append)
3331 {
3332 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD,
3333 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003334 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003335#ifdef FEAT_QUICKFIX
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00003336 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003337 nofile_err = TRUE;
3338 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003339#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003340 apply_autocmds_exarg(EVENT_FILEAPPENDPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003341 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003342 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003343 }
3344 else if (filtering)
3345 {
3346 apply_autocmds_exarg(EVENT_FILTERWRITEPRE,
3347 NULL, sfname, FALSE, curbuf, eap);
3348 }
3349 else if (reset_changed && whole)
3350 {
Bram Moolenaar39fc42e2011-09-02 11:56:20 +02003351 int was_changed = curbufIsChanged();
3352
3353 did_cmd = apply_autocmds_exarg(EVENT_BUFWRITECMD,
3354 sfname, sfname, FALSE, curbuf, eap);
3355 if (did_cmd)
3356 {
3357 if (was_changed && !curbufIsChanged())
3358 {
3359 /* Written everything correctly and BufWriteCmd has reset
3360 * 'modified': Correct the undo information so that an
3361 * undo now sets 'modified'. */
3362 u_unchanged(curbuf);
3363 u_update_save_nr(curbuf);
3364 }
3365 }
3366 else
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003367 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003368#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003369 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003370 nofile_err = TRUE;
3371 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003372#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003373 apply_autocmds_exarg(EVENT_BUFWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003374 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003375 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003376 }
3377 else
3378 {
3379 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD,
3380 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003381 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003382#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003383 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003384 nofile_err = TRUE;
3385 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003386#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003387 apply_autocmds_exarg(EVENT_FILEWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003388 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003389 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003390 }
3391
3392 /* restore curwin/curbuf and a few other things */
3393 aucmd_restbuf(&aco);
3394
3395 /*
3396 * In three situations we return here and don't write the file:
3397 * 1. the autocommands deleted or unloaded the buffer.
3398 * 2. The autocommands abort script processing.
3399 * 3. If one of the "Cmd" autocommands was executed.
3400 */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003401 if (!bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003402 buf = NULL;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003403 if (buf == NULL || (buf->b_ml.ml_mfp == NULL && !empty_memline)
Bram Moolenaar1e015462005-09-25 22:16:38 +00003404 || did_cmd || nofile_err
3405#ifdef FEAT_EVAL
3406 || aborting()
3407#endif
3408 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003409 {
3410 --no_wait_return;
3411 msg_scroll = msg_save;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003412 if (nofile_err)
3413 EMSG(_("E676: No matching autocommands for acwrite buffer"));
3414
Bram Moolenaar1e015462005-09-25 22:16:38 +00003415 if (nofile_err
3416#ifdef FEAT_EVAL
3417 || aborting()
3418#endif
3419 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003420 /* An aborting error, interrupt or exception in the
3421 * autocommands. */
3422 return FAIL;
3423 if (did_cmd)
3424 {
3425 if (buf == NULL)
3426 /* The buffer was deleted. We assume it was written
3427 * (can't retry anyway). */
3428 return OK;
3429 if (overwriting)
3430 {
3431 /* Assume the buffer was written, update the timestamp. */
3432 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00003433 if (append)
3434 buf->b_flags &= ~BF_NEW;
3435 else
3436 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003437 }
Bram Moolenaar292ad192005-12-11 21:29:51 +00003438 if (reset_changed && buf->b_changed && !append
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003439 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003440 /* Buffer still changed, the autocommands didn't work
3441 * properly. */
3442 return FAIL;
3443 return OK;
3444 }
3445#ifdef FEAT_EVAL
3446 if (!aborting())
3447#endif
3448 EMSG(_("E203: Autocommands deleted or unloaded buffer to be written"));
3449 return FAIL;
3450 }
3451
3452 /*
3453 * The autocommands may have changed the number of lines in the file.
3454 * When writing the whole file, adjust the end.
3455 * When writing part of the file, assume that the autocommands only
3456 * changed the number of lines that are to be written (tricky!).
3457 */
3458 if (buf->b_ml.ml_line_count != old_line_count)
3459 {
3460 if (whole) /* write all */
3461 end = buf->b_ml.ml_line_count;
3462 else if (buf->b_ml.ml_line_count > old_line_count) /* more lines */
3463 end += buf->b_ml.ml_line_count - old_line_count;
3464 else /* less lines */
3465 {
3466 end -= old_line_count - buf->b_ml.ml_line_count;
3467 if (end < start)
3468 {
3469 --no_wait_return;
3470 msg_scroll = msg_save;
3471 EMSG(_("E204: Autocommand changed number of lines in unexpected way"));
3472 return FAIL;
3473 }
3474 }
3475 }
3476
3477 /*
3478 * The autocommands may have changed the name of the buffer, which may
3479 * be kept in fname, ffname and sfname.
3480 */
3481 if (buf_ffname)
3482 ffname = buf->b_ffname;
3483 if (buf_sfname)
3484 sfname = buf->b_sfname;
3485 if (buf_fname_f)
3486 fname = buf->b_ffname;
3487 if (buf_fname_s)
3488 fname = buf->b_sfname;
3489 }
3490#endif
3491
3492#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003493 if (netbeans_active() && isNetbeansBuffer(buf))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003494 {
3495 if (whole)
3496 {
3497 /*
3498 * b_changed can be 0 after an undo, but we still need to write
3499 * the buffer to NetBeans.
3500 */
3501 if (buf->b_changed || isNetbeansModified(buf))
3502 {
Bram Moolenaar009b2592004-10-24 19:18:58 +00003503 --no_wait_return; /* may wait for return now */
3504 msg_scroll = msg_save;
3505 netbeans_save_buffer(buf); /* no error checking... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003506 return retval;
3507 }
3508 else
3509 {
3510 errnum = (char_u *)"E656: ";
Bram Moolenaared0e7452008-06-27 19:17:34 +00003511 errmsg = (char_u *)_("NetBeans disallows writes of unmodified buffers");
Bram Moolenaar071d4272004-06-13 20:20:40 +00003512 buffer = NULL;
3513 goto fail;
3514 }
3515 }
3516 else
3517 {
3518 errnum = (char_u *)"E657: ";
3519 errmsg = (char_u *)_("Partial writes disallowed for NetBeans buffers");
3520 buffer = NULL;
3521 goto fail;
3522 }
3523 }
3524#endif
3525
3526 if (shortmess(SHM_OVER) && !exiting)
3527 msg_scroll = FALSE; /* overwrite previous file message */
3528 else
3529 msg_scroll = TRUE; /* don't overwrite previous file message */
3530 if (!filtering)
3531 filemess(buf,
3532#ifndef UNIX
3533 sfname,
3534#else
3535 fname,
3536#endif
3537 (char_u *)"", 0); /* show that we are busy */
3538 msg_scroll = FALSE; /* always overwrite the file message now */
3539
3540 buffer = alloc(BUFSIZE);
3541 if (buffer == NULL) /* can't allocate big buffer, use small
3542 * one (to be able to write when out of
3543 * memory) */
3544 {
3545 buffer = smallbuf;
3546 bufsize = SMBUFSIZE;
3547 }
3548 else
3549 bufsize = BUFSIZE;
3550
3551 /*
3552 * Get information about original file (if there is one).
3553 */
Bram Moolenaar53076832015-12-31 19:53:21 +01003554#if defined(UNIX)
Bram Moolenaar6f192452007-11-08 19:49:02 +00003555 st_old.st_dev = 0;
3556 st_old.st_ino = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003557 perm = -1;
3558 if (mch_stat((char *)fname, &st_old) < 0)
3559 newfile = TRUE;
3560 else
3561 {
3562 perm = st_old.st_mode;
3563 if (!S_ISREG(st_old.st_mode)) /* not a file */
3564 {
3565 if (S_ISDIR(st_old.st_mode))
3566 {
3567 errnum = (char_u *)"E502: ";
3568 errmsg = (char_u *)_("is a directory");
3569 goto fail;
3570 }
3571 if (mch_nodetype(fname) != NODE_WRITABLE)
3572 {
3573 errnum = (char_u *)"E503: ";
3574 errmsg = (char_u *)_("is not a file or writable device");
3575 goto fail;
3576 }
3577 /* It's a device of some kind (or a fifo) which we can write to
3578 * but for which we can't make a backup. */
3579 device = TRUE;
3580 newfile = TRUE;
3581 perm = -1;
3582 }
3583 }
3584#else /* !UNIX */
3585 /*
3586 * Check for a writable device name.
3587 */
3588 c = mch_nodetype(fname);
3589 if (c == NODE_OTHER)
3590 {
3591 errnum = (char_u *)"E503: ";
3592 errmsg = (char_u *)_("is not a file or writable device");
3593 goto fail;
3594 }
3595 if (c == NODE_WRITABLE)
3596 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003597# if defined(MSWIN)
Bram Moolenaar043545e2006-10-10 16:44:07 +00003598 /* MS-Windows allows opening a device, but we will probably get stuck
3599 * trying to write to it. */
3600 if (!p_odev)
3601 {
3602 errnum = (char_u *)"E796: ";
3603 errmsg = (char_u *)_("writing to device disabled with 'opendevice' option");
3604 goto fail;
3605 }
3606# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003607 device = TRUE;
3608 newfile = TRUE;
3609 perm = -1;
3610 }
3611 else
3612 {
3613 perm = mch_getperm(fname);
3614 if (perm < 0)
3615 newfile = TRUE;
3616 else if (mch_isdir(fname))
3617 {
3618 errnum = (char_u *)"E502: ";
3619 errmsg = (char_u *)_("is a directory");
3620 goto fail;
3621 }
3622 if (overwriting)
3623 (void)mch_stat((char *)fname, &st_old);
3624 }
3625#endif /* !UNIX */
3626
3627 if (!device && !newfile)
3628 {
3629 /*
3630 * Check if the file is really writable (when renaming the file to
3631 * make a backup we won't discover it later).
3632 */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003633 file_readonly = check_file_readonly(fname, (int)perm);
3634
Bram Moolenaar071d4272004-06-13 20:20:40 +00003635 if (!forceit && file_readonly)
3636 {
3637 if (vim_strchr(p_cpo, CPO_FWRITE) != NULL)
3638 {
3639 errnum = (char_u *)"E504: ";
3640 errmsg = (char_u *)_(err_readonly);
3641 }
3642 else
3643 {
3644 errnum = (char_u *)"E505: ";
3645 errmsg = (char_u *)_("is read-only (add ! to override)");
3646 }
3647 goto fail;
3648 }
3649
3650 /*
3651 * Check if the timestamp hasn't changed since reading the file.
3652 */
3653 if (overwriting)
3654 {
3655 retval = check_mtime(buf, &st_old);
3656 if (retval == FAIL)
3657 goto fail;
3658 }
3659 }
3660
3661#ifdef HAVE_ACL
3662 /*
3663 * For systems that support ACL: get the ACL from the original file.
3664 */
3665 if (!newfile)
3666 acl = mch_get_acl(fname);
3667#endif
3668
3669 /*
3670 * If 'backupskip' is not empty, don't make a backup for some files.
3671 */
3672 dobackup = (p_wb || p_bk || *p_pm != NUL);
3673#ifdef FEAT_WILDIGN
3674 if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname))
3675 dobackup = FALSE;
3676#endif
3677
3678 /*
3679 * Save the value of got_int and reset it. We don't want a previous
3680 * interruption cancel writing, only hitting CTRL-C while writing should
3681 * abort it.
3682 */
3683 prev_got_int = got_int;
3684 got_int = FALSE;
3685
3686 /* Mark the buffer as 'being saved' to prevent changed buffer warnings */
3687 buf->b_saving = TRUE;
3688
3689 /*
3690 * If we are not appending or filtering, the file exists, and the
3691 * 'writebackup', 'backup' or 'patchmode' option is set, need a backup.
3692 * When 'patchmode' is set also make a backup when appending.
3693 *
3694 * Do not make any backup, if 'writebackup' and 'backup' are both switched
3695 * off. This helps when editing large files on almost-full disks.
3696 */
3697 if (!(append && *p_pm == NUL) && !filtering && perm >= 0 && dobackup)
3698 {
3699#if defined(UNIX) || defined(WIN32)
Bram Moolenaar8767f522016-07-01 17:17:39 +02003700 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003701#endif
3702
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003703 if ((bkc & BKC_YES) || append) /* "yes" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003704 backup_copy = TRUE;
3705#if defined(UNIX) || defined(WIN32)
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003706 else if ((bkc & BKC_AUTO)) /* "auto" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003707 {
3708 int i;
3709
3710# ifdef UNIX
3711 /*
3712 * Don't rename the file when:
3713 * - it's a hard link
3714 * - it's a symbolic link
3715 * - we don't have write permission in the directory
3716 * - we can't set the owner/group of the new file
3717 */
3718 if (st_old.st_nlink > 1
3719 || mch_lstat((char *)fname, &st) < 0
3720 || st.st_dev != st_old.st_dev
Bram Moolenaara5792f52005-11-23 21:25:05 +00003721 || st.st_ino != st_old.st_ino
3722# ifndef HAVE_FCHOWN
3723 || st.st_uid != st_old.st_uid
3724 || st.st_gid != st_old.st_gid
3725# endif
3726 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003727 backup_copy = TRUE;
3728 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003729# else
3730# ifdef WIN32
3731 /* On NTFS file systems hard links are possible. */
3732 if (mch_is_linked(fname))
3733 backup_copy = TRUE;
3734 else
3735# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003736# endif
3737 {
3738 /*
3739 * Check if we can create a file and set the owner/group to
3740 * the ones from the original file.
3741 * First find a file name that doesn't exist yet (use some
3742 * arbitrary numbers).
3743 */
3744 STRCPY(IObuff, fname);
3745 for (i = 4913; ; i += 123)
3746 {
3747 sprintf((char *)gettail(IObuff), "%d", i);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003748 if (mch_lstat((char *)IObuff, &st) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003749 break;
3750 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00003751 fd = mch_open((char *)IObuff,
3752 O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003753 if (fd < 0) /* can't write in directory */
3754 backup_copy = TRUE;
3755 else
3756 {
3757# ifdef UNIX
Bram Moolenaara5792f52005-11-23 21:25:05 +00003758# ifdef HAVE_FCHOWN
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00003759 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003760# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003761 if (mch_stat((char *)IObuff, &st) < 0
3762 || st.st_uid != st_old.st_uid
3763 || st.st_gid != st_old.st_gid
Bram Moolenaar78a15312009-05-15 19:33:18 +00003764 || (long)st.st_mode != perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003765 backup_copy = TRUE;
3766# endif
Bram Moolenaar98358622005-11-28 22:58:23 +00003767 /* Close the file before removing it, on MS-Windows we
3768 * can't delete an open file. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003769 close(fd);
Bram Moolenaar98358622005-11-28 22:58:23 +00003770 mch_remove(IObuff);
Bram Moolenaar3479c5d2010-08-08 18:46:06 +02003771# ifdef MSWIN
3772 /* MS-Windows may trigger a virus scanner to open the
3773 * file, we can't delete it then. Keep trying for half a
3774 * second. */
3775 {
3776 int try;
3777
3778 for (try = 0; try < 10; ++try)
3779 {
3780 if (mch_lstat((char *)IObuff, &st) < 0)
3781 break;
3782 ui_delay(50L, TRUE); /* wait 50 msec */
3783 mch_remove(IObuff);
3784 }
3785 }
3786# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003787 }
3788 }
3789 }
3790
Bram Moolenaar071d4272004-06-13 20:20:40 +00003791 /*
3792 * Break symlinks and/or hardlinks if we've been asked to.
3793 */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003794 if ((bkc & BKC_BREAKSYMLINK) || (bkc & BKC_BREAKHARDLINK))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003795 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003796# ifdef UNIX
Bram Moolenaar071d4272004-06-13 20:20:40 +00003797 int lstat_res;
3798
3799 lstat_res = mch_lstat((char *)fname, &st);
3800
3801 /* Symlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003802 if ((bkc & BKC_BREAKSYMLINK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003803 && lstat_res == 0
3804 && st.st_ino != st_old.st_ino)
3805 backup_copy = FALSE;
3806
3807 /* Hardlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003808 if ((bkc & BKC_BREAKHARDLINK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003809 && st_old.st_nlink > 1
3810 && (lstat_res != 0 || st.st_ino == st_old.st_ino))
3811 backup_copy = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003812# else
3813# if defined(WIN32)
3814 /* Symlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003815 if ((bkc & BKC_BREAKSYMLINK) && mch_is_symbolic_link(fname))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003816 backup_copy = FALSE;
3817
3818 /* Hardlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003819 if ((bkc & BKC_BREAKHARDLINK) && mch_is_hard_link(fname))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003820 backup_copy = FALSE;
3821# endif
3822# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003823 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003824
3825#endif
3826
3827 /* make sure we have a valid backup extension to use */
3828 if (*p_bex == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003829 backup_ext = (char_u *)".bak";
Bram Moolenaar071d4272004-06-13 20:20:40 +00003830 else
3831 backup_ext = p_bex;
3832
3833 if (backup_copy
3834 && (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) >= 0)
3835 {
3836 int bfd;
3837 char_u *copybuf, *wp;
3838 int some_error = FALSE;
Bram Moolenaar8767f522016-07-01 17:17:39 +02003839 stat_T st_new;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003840 char_u *dirp;
3841 char_u *rootname;
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003842#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003843 int did_set_shortname;
3844#endif
3845
3846 copybuf = alloc(BUFSIZE + 1);
3847 if (copybuf == NULL)
3848 {
3849 some_error = TRUE; /* out of memory */
3850 goto nobackup;
3851 }
3852
3853 /*
3854 * Try to make the backup in each directory in the 'bdir' option.
3855 *
3856 * Unix semantics has it, that we may have a writable file,
3857 * that cannot be recreated with a simple open(..., O_CREAT, ) e.g:
3858 * - the directory is not writable,
3859 * - the file may be a symbolic link,
3860 * - the file may belong to another user/group, etc.
3861 *
3862 * For these reasons, the existing writable file must be truncated
3863 * and reused. Creation of a backup COPY will be attempted.
3864 */
3865 dirp = p_bdir;
3866 while (*dirp)
3867 {
3868#ifdef UNIX
3869 st_new.st_ino = 0;
3870 st_new.st_dev = 0;
3871 st_new.st_gid = 0;
3872#endif
3873
3874 /*
3875 * Isolate one directory name, using an entry in 'bdir'.
3876 */
3877 (void)copy_option_part(&dirp, copybuf, BUFSIZE, ",");
3878 rootname = get_file_in_dir(fname, copybuf);
3879 if (rootname == NULL)
3880 {
3881 some_error = TRUE; /* out of memory */
3882 goto nobackup;
3883 }
3884
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003885#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003886 did_set_shortname = FALSE;
3887#endif
3888
3889 /*
3890 * May try twice if 'shortname' not set.
3891 */
3892 for (;;)
3893 {
3894 /*
3895 * Make backup file name.
3896 */
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003897 backup = buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003898 rootname, backup_ext, FALSE);
3899 if (backup == NULL)
3900 {
3901 vim_free(rootname);
3902 some_error = TRUE; /* out of memory */
3903 goto nobackup;
3904 }
3905
3906 /*
3907 * Check if backup file already exists.
3908 */
3909 if (mch_stat((char *)backup, &st_new) >= 0)
3910 {
3911#ifdef UNIX
3912 /*
3913 * Check if backup file is same as original file.
3914 * May happen when modname() gave the same file back.
3915 * E.g. silly link, or file name-length reached.
3916 * If we don't check here, we either ruin the file
3917 * when copying or erase it after writing. jw.
3918 */
3919 if (st_new.st_dev == st_old.st_dev
3920 && st_new.st_ino == st_old.st_ino)
3921 {
3922 vim_free(backup);
3923 backup = NULL; /* no backup file to delete */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003924 /*
3925 * may try again with 'shortname' set
3926 */
3927 if (!(buf->b_shortname || buf->b_p_sn))
3928 {
3929 buf->b_shortname = TRUE;
3930 did_set_shortname = TRUE;
3931 continue;
3932 }
3933 /* setting shortname didn't help */
3934 if (did_set_shortname)
3935 buf->b_shortname = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003936 break;
3937 }
3938#endif
3939
3940 /*
3941 * If we are not going to keep the backup file, don't
3942 * delete an existing one, try to use another name.
3943 * Change one character, just before the extension.
3944 */
3945 if (!p_bk)
3946 {
3947 wp = backup + STRLEN(backup) - 1
3948 - STRLEN(backup_ext);
3949 if (wp < backup) /* empty file name ??? */
3950 wp = backup;
3951 *wp = 'z';
3952 while (*wp > 'a'
3953 && mch_stat((char *)backup, &st_new) >= 0)
3954 --*wp;
3955 /* They all exist??? Must be something wrong. */
3956 if (*wp == 'a')
3957 {
3958 vim_free(backup);
3959 backup = NULL;
3960 }
3961 }
3962 }
3963 break;
3964 }
3965 vim_free(rootname);
3966
3967 /*
3968 * Try to create the backup file
3969 */
3970 if (backup != NULL)
3971 {
3972 /* remove old backup, if present */
3973 mch_remove(backup);
3974 /* Open with O_EXCL to avoid the file being created while
3975 * we were sleeping (symlink hacker attack?) */
3976 bfd = mch_open((char *)backup,
Bram Moolenaara5792f52005-11-23 21:25:05 +00003977 O_WRONLY|O_CREAT|O_EXTRA|O_EXCL|O_NOFOLLOW,
3978 perm & 0777);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003979 if (bfd < 0)
3980 {
3981 vim_free(backup);
3982 backup = NULL;
3983 }
3984 else
3985 {
3986 /* set file protection same as original file, but
3987 * strip s-bit */
3988 (void)mch_setperm(backup, perm & 0777);
3989
3990#ifdef UNIX
3991 /*
3992 * Try to set the group of the backup same as the
3993 * original file. If this fails, set the protection
3994 * bits for the group same as the protection bits for
3995 * others.
3996 */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003997 if (st_new.st_gid != st_old.st_gid
Bram Moolenaar071d4272004-06-13 20:20:40 +00003998# ifdef HAVE_FCHOWN /* sequent-ptx lacks fchown() */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003999 && fchown(bfd, (uid_t)-1, st_old.st_gid) != 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00004000# endif
4001 )
4002 mch_setperm(backup,
4003 (perm & 0707) | ((perm & 07) << 3));
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004004# if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004005 mch_copy_sec(fname, backup);
4006# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004007#endif
4008
4009 /*
4010 * copy the file.
4011 */
4012 write_info.bw_fd = bfd;
4013 write_info.bw_buf = copybuf;
4014#ifdef HAS_BW_FLAGS
4015 write_info.bw_flags = FIO_NOCONVERT;
4016#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004017 while ((write_info.bw_len = read_eintr(fd, copybuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004018 BUFSIZE)) > 0)
4019 {
4020 if (buf_write_bytes(&write_info) == FAIL)
4021 {
4022 errmsg = (char_u *)_("E506: Can't write to backup file (add ! to override)");
4023 break;
4024 }
4025 ui_breakcheck();
4026 if (got_int)
4027 {
4028 errmsg = (char_u *)_(e_interr);
4029 break;
4030 }
4031 }
4032
4033 if (close(bfd) < 0 && errmsg == NULL)
4034 errmsg = (char_u *)_("E507: Close error for backup file (add ! to override)");
4035 if (write_info.bw_len < 0)
4036 errmsg = (char_u *)_("E508: Can't read file for backup (add ! to override)");
4037#ifdef UNIX
4038 set_file_time(backup, st_old.st_atime, st_old.st_mtime);
4039#endif
4040#ifdef HAVE_ACL
4041 mch_set_acl(backup, acl);
4042#endif
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004043#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004044 mch_copy_sec(fname, backup);
4045#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004046 break;
4047 }
4048 }
4049 }
4050 nobackup:
4051 close(fd); /* ignore errors for closing read file */
4052 vim_free(copybuf);
4053
4054 if (backup == NULL && errmsg == NULL)
4055 errmsg = (char_u *)_("E509: Cannot create backup file (add ! to override)");
4056 /* ignore errors when forceit is TRUE */
4057 if ((some_error || errmsg != NULL) && !forceit)
4058 {
4059 retval = FAIL;
4060 goto fail;
4061 }
4062 errmsg = NULL;
4063 }
4064 else
4065 {
4066 char_u *dirp;
4067 char_u *p;
4068 char_u *rootname;
4069
4070 /*
4071 * Make a backup by renaming the original file.
4072 */
4073 /*
4074 * If 'cpoptions' includes the "W" flag, we don't want to
4075 * overwrite a read-only file. But rename may be possible
4076 * anyway, thus we need an extra check here.
4077 */
4078 if (file_readonly && vim_strchr(p_cpo, CPO_FWRITE) != NULL)
4079 {
4080 errnum = (char_u *)"E504: ";
4081 errmsg = (char_u *)_(err_readonly);
4082 goto fail;
4083 }
4084
4085 /*
4086 *
4087 * Form the backup file name - change path/fo.o.h to
4088 * path/fo.o.h.bak Try all directories in 'backupdir', first one
4089 * that works is used.
4090 */
4091 dirp = p_bdir;
4092 while (*dirp)
4093 {
4094 /*
4095 * Isolate one directory name and make the backup file name.
4096 */
4097 (void)copy_option_part(&dirp, IObuff, IOSIZE, ",");
4098 rootname = get_file_in_dir(fname, IObuff);
4099 if (rootname == NULL)
4100 backup = NULL;
4101 else
4102 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01004103 backup = buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00004104 rootname, backup_ext, FALSE);
4105 vim_free(rootname);
4106 }
4107
4108 if (backup != NULL)
4109 {
4110 /*
4111 * If we are not going to keep the backup file, don't
4112 * delete an existing one, try to use another name.
4113 * Change one character, just before the extension.
4114 */
4115 if (!p_bk && mch_getperm(backup) >= 0)
4116 {
4117 p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext);
4118 if (p < backup) /* empty file name ??? */
4119 p = backup;
4120 *p = 'z';
4121 while (*p > 'a' && mch_getperm(backup) >= 0)
4122 --*p;
4123 /* They all exist??? Must be something wrong! */
4124 if (*p == 'a')
4125 {
4126 vim_free(backup);
4127 backup = NULL;
4128 }
4129 }
4130 }
4131 if (backup != NULL)
4132 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004133 /*
Bram Moolenaarbfd8fc02005-09-20 23:22:24 +00004134 * Delete any existing backup and move the current version
4135 * to the backup. For safety, we don't remove the backup
4136 * until the write has finished successfully. And if the
4137 * 'backup' option is set, leave it around.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004138 */
4139 /*
4140 * If the renaming of the original file to the backup file
4141 * works, quit here.
4142 */
4143 if (vim_rename(fname, backup) == 0)
4144 break;
4145
4146 vim_free(backup); /* don't do the rename below */
4147 backup = NULL;
4148 }
4149 }
4150 if (backup == NULL && !forceit)
4151 {
4152 errmsg = (char_u *)_("E510: Can't make backup file (add ! to override)");
4153 goto fail;
4154 }
4155 }
4156 }
4157
Bram Moolenaar53076832015-12-31 19:53:21 +01004158#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004159 /* When using ":w!" and the file was read-only: make it writable */
4160 if (forceit && perm >= 0 && !(perm & 0200) && st_old.st_uid == getuid()
4161 && vim_strchr(p_cpo, CPO_FWRITE) == NULL)
4162 {
4163 perm |= 0200;
4164 (void)mch_setperm(fname, perm);
4165 made_writable = TRUE;
4166 }
4167#endif
4168
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004169 /* When using ":w!" and writing to the current file, 'readonly' makes no
Bram Moolenaar4399ef42005-02-12 14:29:27 +00004170 * sense, reset it, unless 'Z' appears in 'cpoptions'. */
4171 if (forceit && overwriting && vim_strchr(p_cpo, CPO_KEEPRO) == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004172 {
4173 buf->b_p_ro = FALSE;
4174#ifdef FEAT_TITLE
4175 need_maketitle = TRUE; /* set window title later */
4176#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004177 status_redraw_all(); /* redraw status lines later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004178 }
4179
4180 if (end > buf->b_ml.ml_line_count)
4181 end = buf->b_ml.ml_line_count;
4182 if (buf->b_ml.ml_flags & ML_EMPTY)
4183 start = end + 1;
4184
4185 /*
4186 * If the original file is being overwritten, there is a small chance that
4187 * we crash in the middle of writing. Therefore the file is preserved now.
4188 * This makes all block numbers positive so that recovery does not need
4189 * the original file.
4190 * Don't do this if there is a backup file and we are exiting.
4191 */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004192 if (reset_changed && !newfile && overwriting
Bram Moolenaar071d4272004-06-13 20:20:40 +00004193 && !(exiting && backup != NULL))
4194 {
4195 ml_preserve(buf, FALSE);
4196 if (got_int)
4197 {
4198 errmsg = (char_u *)_(e_interr);
4199 goto restore_backup;
4200 }
4201 }
4202
4203#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
4204 /*
4205 * Before risking to lose the original file verify if there's
4206 * a resource fork to preserve, and if cannot be done warn
4207 * the users. This happens when overwriting without backups.
4208 */
4209 if (backup == NULL && overwriting && !append)
4210 if (mch_has_resource_fork(fname))
4211 {
4212 errmsg = (char_u *)_("E460: The resource fork would be lost (add ! to override)");
4213 goto restore_backup;
4214 }
4215#endif
4216
4217#ifdef VMS
4218 vms_remove_version(fname); /* remove version */
4219#endif
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00004220 /* Default: write the file directly. May write to a temp file for
Bram Moolenaar071d4272004-06-13 20:20:40 +00004221 * multi-byte conversion. */
4222 wfname = fname;
4223
4224#ifdef FEAT_MBYTE
4225 /* Check for forced 'fileencoding' from "++opt=val" argument. */
4226 if (eap != NULL && eap->force_enc != 0)
4227 {
4228 fenc = eap->cmd + eap->force_enc;
4229 fenc = enc_canonize(fenc);
4230 fenc_tofree = fenc;
4231 }
4232 else
4233 fenc = buf->b_p_fenc;
4234
4235 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004236 * Check if the file needs to be converted.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004237 */
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004238 converted = need_conversion(fenc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004239
4240 /*
4241 * Check if UTF-8 to UCS-2/4 or Latin1 conversion needs to be done. Or
4242 * Latin1 to Unicode conversion. This is handled in buf_write_bytes().
4243 * Prepare the flags for it and allocate bw_conv_buf when needed.
4244 */
4245 if (converted && (enc_utf8 || STRCMP(p_enc, "latin1") == 0))
4246 {
4247 wb_flags = get_fio_flags(fenc);
4248 if (wb_flags & (FIO_UCS2 | FIO_UCS4 | FIO_UTF16 | FIO_UTF8))
4249 {
4250 /* Need to allocate a buffer to translate into. */
4251 if (wb_flags & (FIO_UCS2 | FIO_UTF16 | FIO_UTF8))
4252 write_info.bw_conv_buflen = bufsize * 2;
4253 else /* FIO_UCS4 */
4254 write_info.bw_conv_buflen = bufsize * 4;
4255 write_info.bw_conv_buf
4256 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4257 if (write_info.bw_conv_buf == NULL)
4258 end = 0;
4259 }
4260 }
4261
4262# ifdef WIN3264
4263 if (converted && wb_flags == 0 && (wb_flags = get_win_fio_flags(fenc)) != 0)
4264 {
4265 /* Convert UTF-8 -> UCS-2 and UCS-2 -> DBCS. Worst-case * 4: */
4266 write_info.bw_conv_buflen = bufsize * 4;
4267 write_info.bw_conv_buf
4268 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4269 if (write_info.bw_conv_buf == NULL)
4270 end = 0;
4271 }
4272# endif
4273
4274# ifdef MACOS_X
4275 if (converted && wb_flags == 0 && (wb_flags = get_mac_fio_flags(fenc)) != 0)
4276 {
4277 write_info.bw_conv_buflen = bufsize * 3;
4278 write_info.bw_conv_buf
4279 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4280 if (write_info.bw_conv_buf == NULL)
4281 end = 0;
4282 }
4283# endif
4284
4285# if defined(FEAT_EVAL) || defined(USE_ICONV)
4286 if (converted && wb_flags == 0)
4287 {
4288# ifdef USE_ICONV
4289 /*
4290 * Use iconv() conversion when conversion is needed and it's not done
4291 * internally.
4292 */
4293 write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc,
4294 enc_utf8 ? (char_u *)"utf-8" : p_enc);
4295 if (write_info.bw_iconv_fd != (iconv_t)-1)
4296 {
4297 /* We're going to use iconv(), allocate a buffer to convert in. */
4298 write_info.bw_conv_buflen = bufsize * ICONV_MULT;
4299 write_info.bw_conv_buf
4300 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4301 if (write_info.bw_conv_buf == NULL)
4302 end = 0;
4303 write_info.bw_first = TRUE;
4304 }
4305# ifdef FEAT_EVAL
4306 else
4307# endif
4308# endif
4309
4310# ifdef FEAT_EVAL
4311 /*
4312 * When the file needs to be converted with 'charconvert' after
4313 * writing, write to a temp file instead and let the conversion
4314 * overwrite the original file.
4315 */
4316 if (*p_ccv != NUL)
4317 {
Bram Moolenaare5c421c2015-03-31 13:33:08 +02004318 wfname = vim_tempname('w', FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004319 if (wfname == NULL) /* Can't write without a tempfile! */
4320 {
4321 errmsg = (char_u *)_("E214: Can't find temp file for writing");
4322 goto restore_backup;
4323 }
4324 }
4325# endif
4326 }
4327# endif
4328 if (converted && wb_flags == 0
4329# ifdef USE_ICONV
4330 && write_info.bw_iconv_fd == (iconv_t)-1
4331# endif
4332# ifdef FEAT_EVAL
4333 && wfname == fname
4334# endif
4335 )
4336 {
4337 if (!forceit)
4338 {
4339 errmsg = (char_u *)_("E213: Cannot convert (add ! to write without conversion)");
4340 goto restore_backup;
4341 }
4342 notconverted = TRUE;
4343 }
4344#endif
4345
4346 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004347 * If conversion is taking place, we may first pretend to write and check
4348 * for conversion errors. Then loop again to write for real.
4349 * When not doing conversion this writes for real right away.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004350 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004351 for (checking_conversion = TRUE; ; checking_conversion = FALSE)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004352 {
4353 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004354 * There is no need to check conversion when:
4355 * - there is no conversion
4356 * - we make a backup file, that can be restored in case of conversion
4357 * failure.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004358 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004359#ifdef FEAT_MBYTE
4360 if (!converted || dobackup)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004361#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004362 checking_conversion = FALSE;
4363
4364 if (checking_conversion)
4365 {
4366 /* Make sure we don't write anything. */
4367 fd = -1;
4368 write_info.bw_fd = fd;
4369 }
4370 else
4371 {
4372 /*
4373 * Open the file "wfname" for writing.
4374 * We may try to open the file twice: If we can't write to the file
4375 * and forceit is TRUE we delete the existing file and try to
4376 * create a new one. If this still fails we may have lost the
4377 * original file! (this may happen when the user reached his
4378 * quotum for number of files).
4379 * Appending will fail if the file does not exist and forceit is
4380 * FALSE.
4381 */
4382 while ((fd = mch_open((char *)wfname, O_WRONLY | O_EXTRA | (append
4383 ? (forceit ? (O_APPEND | O_CREAT) : O_APPEND)
4384 : (O_CREAT | O_TRUNC))
4385 , perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004386 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004387 /*
4388 * A forced write will try to create a new file if the old one
4389 * is still readonly. This may also happen when the directory
4390 * is read-only. In that case the mch_remove() will fail.
4391 */
4392 if (errmsg == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004393 {
4394#ifdef UNIX
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004395 stat_T st;
4396
4397 /* Don't delete the file when it's a hard or symbolic link.
4398 */
4399 if ((!newfile && st_old.st_nlink > 1)
4400 || (mch_lstat((char *)fname, &st) == 0
4401 && (st.st_dev != st_old.st_dev
4402 || st.st_ino != st_old.st_ino)))
4403 errmsg = (char_u *)_("E166: Can't open linked file for writing");
4404 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004405#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004406 {
4407 errmsg = (char_u *)_("E212: Can't open file for writing");
4408 if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL
4409 && perm >= 0)
4410 {
4411#ifdef UNIX
4412 /* we write to the file, thus it should be marked
4413 writable after all */
4414 if (!(perm & 0200))
4415 made_writable = TRUE;
4416 perm |= 0200;
4417 if (st_old.st_uid != getuid()
4418 || st_old.st_gid != getgid())
4419 perm &= 0777;
4420#endif
4421 if (!append) /* don't remove when appending */
4422 mch_remove(wfname);
4423 continue;
4424 }
4425 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004426 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004427
4428restore_backup:
Bram Moolenaar071d4272004-06-13 20:20:40 +00004429 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004430 stat_T st;
4431
Bram Moolenaar071d4272004-06-13 20:20:40 +00004432 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004433 * If we failed to open the file, we don't need a backup.
4434 * Throw it away. If we moved or removed the original file
4435 * try to put the backup in its place.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004436 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004437 if (backup != NULL && wfname == fname)
4438 {
4439 if (backup_copy)
4440 {
4441 /*
4442 * There is a small chance that we removed the
4443 * original, try to move the copy in its place.
4444 * This may not work if the vim_rename() fails.
4445 * In that case we leave the copy around.
4446 */
4447 /* If file does not exist, put the copy in its
4448 * place */
4449 if (mch_stat((char *)fname, &st) < 0)
4450 vim_rename(backup, fname);
4451 /* if original file does exist throw away the copy
4452 */
4453 if (mch_stat((char *)fname, &st) >= 0)
4454 mch_remove(backup);
4455 }
4456 else
4457 {
4458 /* try to put the original file back */
4459 vim_rename(backup, fname);
4460 }
4461 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004462
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004463 /* if original file no longer exists give an extra warning
4464 */
4465 if (!newfile && mch_stat((char *)fname, &st) < 0)
4466 end = 0;
4467 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004468
4469#ifdef FEAT_MBYTE
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004470 if (wfname != fname)
4471 vim_free(wfname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004472#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004473 goto fail;
4474 }
4475 write_info.bw_fd = fd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004476
4477#if defined(MACOS_CLASSIC) || defined(WIN3264)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004478 /* TODO: Is it need for MACOS_X? (Dany) */
4479 /*
4480 * On macintosh copy the original files attributes (i.e. the backup)
4481 * This is done in order to preserve the resource fork and the
4482 * Finder attribute (label, comments, custom icons, file creator)
4483 */
4484 if (backup != NULL && overwriting && !append)
4485 {
4486 if (backup_copy)
4487 (void)mch_copy_file_attribute(wfname, backup);
4488 else
4489 (void)mch_copy_file_attribute(backup, wfname);
4490 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004491
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004492 if (!overwriting && !append)
4493 {
4494 if (buf->b_ffname != NULL)
4495 (void)mch_copy_file_attribute(buf->b_ffname, wfname);
4496 /* Should copy resource fork */
4497 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004498#endif
4499
Bram Moolenaar071d4272004-06-13 20:20:40 +00004500#ifdef FEAT_CRYPT
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004501 if (*buf->b_p_key != NUL && !filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004502 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004503 char_u *header;
4504 int header_len;
4505
4506 buf->b_cryptstate = crypt_create_for_writing(
4507 crypt_get_method_nr(buf),
4508 buf->b_p_key, &header, &header_len);
4509 if (buf->b_cryptstate == NULL || header == NULL)
4510 end = 0;
4511 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004512 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004513 /* Write magic number, so that Vim knows how this file is
4514 * encrypted when reading it back. */
4515 write_info.bw_buf = header;
4516 write_info.bw_len = header_len;
4517 write_info.bw_flags = FIO_NOCONVERT;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004518 if (buf_write_bytes(&write_info) == FAIL)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004519 end = 0;
4520 wb_flags |= FIO_ENCRYPTED;
4521 vim_free(header);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004522 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004523 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004524#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004525 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004526 errmsg = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004527
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004528 write_info.bw_buf = buffer;
4529 nchars = 0;
4530
4531 /* use "++bin", "++nobin" or 'binary' */
4532 if (eap != NULL && eap->force_bin != 0)
4533 write_bin = (eap->force_bin == FORCE_BIN);
4534 else
4535 write_bin = buf->b_p_bin;
4536
4537#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004538 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004539 * The BOM is written just after the encryption magic number.
4540 * Skip it when appending and the file already existed, the BOM only
4541 * makes sense at the start of the file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004542 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004543 if (buf->b_p_bomb && !write_bin && (!append || perm < 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004544 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004545 write_info.bw_len = make_bom(buffer, fenc);
4546 if (write_info.bw_len > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004547 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004548 /* don't convert, do encryption */
4549 write_info.bw_flags = FIO_NOCONVERT | wb_flags;
4550 if (buf_write_bytes(&write_info) == FAIL)
4551 end = 0;
4552 else
4553 nchars += write_info.bw_len;
4554 }
4555 }
4556 write_info.bw_start_lnum = start;
4557#endif
4558
4559#ifdef FEAT_PERSISTENT_UNDO
4560 write_undo_file = (buf->b_p_udf
4561 && overwriting
4562 && !append
4563 && !filtering
4564 && reset_changed
4565 && !checking_conversion);
4566 if (write_undo_file)
4567 /* Prepare for computing the hash value of the text. */
4568 sha256_start(&sha_ctx);
4569#endif
4570
4571 write_info.bw_len = bufsize;
4572#ifdef HAS_BW_FLAGS
4573 write_info.bw_flags = wb_flags;
4574#endif
4575 fileformat = get_fileformat_force(buf, eap);
4576 s = buffer;
4577 len = 0;
4578 for (lnum = start; lnum <= end; ++lnum)
4579 {
4580 /*
4581 * The next while loop is done once for each character written.
4582 * Keep it fast!
4583 */
4584 ptr = ml_get_buf(buf, lnum, FALSE) - 1;
4585#ifdef FEAT_PERSISTENT_UNDO
4586 if (write_undo_file)
4587 sha256_update(&sha_ctx, ptr + 1,
4588 (UINT32_T)(STRLEN(ptr + 1) + 1));
4589#endif
4590 while ((c = *++ptr) != NUL)
4591 {
4592 if (c == NL)
4593 *s = NUL; /* replace newlines with NULs */
4594 else if (c == CAR && fileformat == EOL_MAC)
4595 *s = NL; /* Mac: replace CRs with NLs */
4596 else
4597 *s = c;
4598 ++s;
4599 if (++len != bufsize)
4600 continue;
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004601 if (buf_write_bytes(&write_info) == FAIL)
4602 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004603 end = 0; /* write error: break loop */
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004604 break;
4605 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004606 nchars += bufsize;
4607 s = buffer;
4608 len = 0;
4609#ifdef FEAT_MBYTE
4610 write_info.bw_start_lnum = lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004611#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004612 }
4613 /* write failed or last line has no EOL: stop here */
4614 if (end == 0
4615 || (lnum == end
4616 && (write_bin || !buf->b_p_fixeol)
4617 && (lnum == buf->b_no_eol_lnum
4618 || (lnum == buf->b_ml.ml_line_count
4619 && !buf->b_p_eol))))
4620 {
4621 ++lnum; /* written the line, count it */
4622 no_eol = TRUE;
4623 break;
4624 }
4625 if (fileformat == EOL_UNIX)
4626 *s++ = NL;
4627 else
4628 {
4629 *s++ = CAR; /* EOL_MAC or EOL_DOS: write CR */
4630 if (fileformat == EOL_DOS) /* write CR-NL */
4631 {
4632 if (++len == bufsize)
4633 {
4634 if (buf_write_bytes(&write_info) == FAIL)
4635 {
4636 end = 0; /* write error: break loop */
4637 break;
4638 }
4639 nchars += bufsize;
4640 s = buffer;
4641 len = 0;
4642 }
4643 *s++ = NL;
4644 }
4645 }
4646 if (++len == bufsize && end)
4647 {
4648 if (buf_write_bytes(&write_info) == FAIL)
4649 {
4650 end = 0; /* write error: break loop */
4651 break;
4652 }
4653 nchars += bufsize;
4654 s = buffer;
4655 len = 0;
4656
4657 ui_breakcheck();
4658 if (got_int)
4659 {
4660 end = 0; /* Interrupted, break loop */
4661 break;
4662 }
4663 }
4664#ifdef VMS
4665 /*
4666 * On VMS there is a problem: newlines get added when writing
4667 * blocks at a time. Fix it by writing a line at a time.
4668 * This is much slower!
4669 * Explanation: VAX/DECC RTL insists that records in some RMS
4670 * structures end with a newline (carriage return) character, and
4671 * if they don't it adds one.
4672 * With other RMS structures it works perfect without this fix.
4673 */
4674 if (buf->b_fab_rfm == FAB$C_VFC
4675 || ((buf->b_fab_rat & (FAB$M_FTN | FAB$M_CR)) != 0))
4676 {
4677 int b2write;
4678
4679 buf->b_fab_mrs = (buf->b_fab_mrs == 0
4680 ? MIN(4096, bufsize)
4681 : MIN(buf->b_fab_mrs, bufsize));
4682
4683 b2write = len;
4684 while (b2write > 0)
4685 {
4686 write_info.bw_len = MIN(b2write, buf->b_fab_mrs);
4687 if (buf_write_bytes(&write_info) == FAIL)
4688 {
4689 end = 0;
4690 break;
4691 }
4692 b2write -= MIN(b2write, buf->b_fab_mrs);
4693 }
4694 write_info.bw_len = bufsize;
4695 nchars += len;
4696 s = buffer;
4697 len = 0;
4698 }
4699#endif
4700 }
4701 if (len > 0 && end > 0)
4702 {
4703 write_info.bw_len = len;
4704 if (buf_write_bytes(&write_info) == FAIL)
4705 end = 0; /* write error */
4706 nchars += len;
4707 }
4708
4709 /* Stop when writing done or an error was encountered. */
4710 if (!checking_conversion || end == 0)
4711 break;
4712
4713 /* If no error happened until now, writing should be ok, so loop to
4714 * really write the buffer. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004715 }
4716
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004717 /* If we started writing, finish writing. Also when an error was
4718 * encountered. */
4719 if (!checking_conversion)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004720 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004721#if defined(UNIX) && defined(HAVE_FSYNC)
4722 /*
4723 * On many journalling file systems there is a bug that causes both the
4724 * original and the backup file to be lost when halting the system
4725 * right after writing the file. That's because only the meta-data is
4726 * journalled. Syncing the file slows down the system, but assures it
4727 * has been written to disk and we don't lose it.
4728 * For a device do try the fsync() but don't complain if it does not
4729 * work (could be a pipe).
4730 * If the 'fsync' option is FALSE, don't fsync(). Useful for laptops.
4731 */
4732 if (p_fs && fsync(fd) != 0 && !device)
4733 {
4734 errmsg = (char_u *)_("E667: Fsync failed");
4735 end = 0;
4736 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004737#endif
4738
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004739#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004740 /* Probably need to set the security context. */
4741 if (!backup_copy)
4742 mch_copy_sec(backup, wfname);
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004743#endif
4744
Bram Moolenaara5792f52005-11-23 21:25:05 +00004745#ifdef UNIX
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004746 /* When creating a new file, set its owner/group to that of the
4747 * original file. Get the new device and inode number. */
4748 if (backup != NULL && !backup_copy)
Bram Moolenaara5792f52005-11-23 21:25:05 +00004749 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004750# ifdef HAVE_FCHOWN
4751 stat_T st;
4752
4753 /* don't change the owner when it's already OK, some systems remove
4754 * permission or ACL stuff */
4755 if (mch_stat((char *)wfname, &st) < 0
4756 || st.st_uid != st_old.st_uid
4757 || st.st_gid != st_old.st_gid)
4758 {
4759 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
4760 if (perm >= 0) /* set permission again, may have changed */
4761 (void)mch_setperm(wfname, perm);
4762 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00004763# endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004764 buf_setino(buf);
4765 }
4766 else if (!buf->b_dev_valid)
4767 /* Set the inode when creating a new file. */
4768 buf_setino(buf);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004769#endif
4770
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004771 if (close(fd) != 0)
4772 {
4773 errmsg = (char_u *)_("E512: Close failed");
4774 end = 0;
4775 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004776
4777#ifdef UNIX
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004778 if (made_writable)
4779 perm &= ~0200; /* reset 'w' bit for security reasons */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004780#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004781 if (perm >= 0) /* set perm. of new file same as old file */
4782 (void)mch_setperm(wfname, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004783#ifdef HAVE_ACL
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004784 /*
4785 * Probably need to set the ACL before changing the user (can't set the
4786 * ACL on a file the user doesn't own).
4787 * On Solaris, with ZFS and the aclmode property set to "discard" (the
4788 * default), chmod() discards all part of a file's ACL that don't
4789 * represent the mode of the file. It's non-trivial for us to discover
4790 * whether we're in that situation, so we simply always re-set the ACL.
4791 */
Bram Moolenaarda412772016-07-14 20:37:07 +02004792# ifndef HAVE_SOLARIS_ZFS_ACL
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004793 if (!backup_copy)
Bram Moolenaarda412772016-07-14 20:37:07 +02004794# endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004795 mch_set_acl(wfname, acl);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004796#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004797#ifdef FEAT_CRYPT
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004798 if (buf->b_cryptstate != NULL)
4799 {
4800 crypt_free_state(buf->b_cryptstate);
4801 buf->b_cryptstate = NULL;
4802 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004803#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004804
Bram Moolenaar071d4272004-06-13 20:20:40 +00004805#if defined(FEAT_MBYTE) && defined(FEAT_EVAL)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004806 if (wfname != fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004807 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004808 /*
4809 * The file was written to a temp file, now it needs to be
4810 * converted with 'charconvert' to (overwrite) the output file.
4811 */
4812 if (end != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004813 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004814 if (eval_charconvert(enc_utf8 ? (char_u *)"utf-8" : p_enc,
4815 fenc, wfname, fname) == FAIL)
4816 {
4817 write_info.bw_conv_error = TRUE;
4818 end = 0;
4819 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004820 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004821 mch_remove(wfname);
4822 vim_free(wfname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004823 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004824#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004825 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004826
4827 if (end == 0)
4828 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004829 /*
4830 * Error encountered.
4831 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004832 if (errmsg == NULL)
4833 {
4834#ifdef FEAT_MBYTE
4835 if (write_info.bw_conv_error)
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004836 {
4837 if (write_info.bw_conv_error_lnum == 0)
4838 errmsg = (char_u *)_("E513: write error, conversion failed (make 'fenc' empty to override)");
4839 else
4840 {
4841 errmsg_allocated = TRUE;
4842 errmsg = alloc(300);
4843 vim_snprintf((char *)errmsg, 300, _("E513: write error, conversion failed in line %ld (make 'fenc' empty to override)"),
4844 (long)write_info.bw_conv_error_lnum);
4845 }
4846 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004847 else
4848#endif
4849 if (got_int)
4850 errmsg = (char_u *)_(e_interr);
4851 else
4852 errmsg = (char_u *)_("E514: write error (file system full?)");
4853 }
4854
4855 /*
4856 * If we have a backup file, try to put it in place of the new file,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004857 * because the new file is probably corrupt. This avoids losing the
Bram Moolenaar071d4272004-06-13 20:20:40 +00004858 * original file when trying to make a backup when writing the file a
4859 * second time.
4860 * When "backup_copy" is set we need to copy the backup over the new
4861 * file. Otherwise rename the backup file.
4862 * If this is OK, don't give the extra warning message.
4863 */
4864 if (backup != NULL)
4865 {
4866 if (backup_copy)
4867 {
4868 /* This may take a while, if we were interrupted let the user
4869 * know we got the message. */
4870 if (got_int)
4871 {
4872 MSG(_(e_interr));
4873 out_flush();
4874 }
4875 if ((fd = mch_open((char *)backup, O_RDONLY | O_EXTRA, 0)) >= 0)
4876 {
4877 if ((write_info.bw_fd = mch_open((char *)fname,
Bram Moolenaar9be038d2005-03-08 22:34:32 +00004878 O_WRONLY | O_CREAT | O_TRUNC | O_EXTRA,
4879 perm & 0777)) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004880 {
4881 /* copy the file. */
4882 write_info.bw_buf = smallbuf;
4883#ifdef HAS_BW_FLAGS
4884 write_info.bw_flags = FIO_NOCONVERT;
4885#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004886 while ((write_info.bw_len = read_eintr(fd, smallbuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004887 SMBUFSIZE)) > 0)
4888 if (buf_write_bytes(&write_info) == FAIL)
4889 break;
4890
4891 if (close(write_info.bw_fd) >= 0
4892 && write_info.bw_len == 0)
4893 end = 1; /* success */
4894 }
4895 close(fd); /* ignore errors for closing read file */
4896 }
4897 }
4898 else
4899 {
4900 if (vim_rename(backup, fname) == 0)
4901 end = 1;
4902 }
4903 }
4904 goto fail;
4905 }
4906
4907 lnum -= start; /* compute number of written lines */
4908 --no_wait_return; /* may wait for return now */
4909
4910#if !(defined(UNIX) || defined(VMS))
4911 fname = sfname; /* use shortname now, for the messages */
4912#endif
4913 if (!filtering)
4914 {
4915 msg_add_fname(buf, fname); /* put fname in IObuff with quotes */
4916 c = FALSE;
4917#ifdef FEAT_MBYTE
4918 if (write_info.bw_conv_error)
4919 {
4920 STRCAT(IObuff, _(" CONVERSION ERROR"));
4921 c = TRUE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004922 if (write_info.bw_conv_error_lnum != 0)
Bram Moolenaara800b422010-06-27 01:15:55 +02004923 vim_snprintf_add((char *)IObuff, IOSIZE, _(" in line %ld;"),
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004924 (long)write_info.bw_conv_error_lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004925 }
4926 else if (notconverted)
4927 {
4928 STRCAT(IObuff, _("[NOT converted]"));
4929 c = TRUE;
4930 }
4931 else if (converted)
4932 {
4933 STRCAT(IObuff, _("[converted]"));
4934 c = TRUE;
4935 }
4936#endif
4937 if (device)
4938 {
4939 STRCAT(IObuff, _("[Device]"));
4940 c = TRUE;
4941 }
4942 else if (newfile)
4943 {
4944 STRCAT(IObuff, shortmess(SHM_NEW) ? _("[New]") : _("[New File]"));
4945 c = TRUE;
4946 }
4947 if (no_eol)
4948 {
4949 msg_add_eol();
4950 c = TRUE;
4951 }
4952 /* may add [unix/dos/mac] */
4953 if (msg_add_fileformat(fileformat))
4954 c = TRUE;
4955#ifdef FEAT_CRYPT
4956 if (wb_flags & FIO_ENCRYPTED)
4957 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004958 crypt_append_msg(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004959 c = TRUE;
4960 }
4961#endif
4962 msg_add_lines(c, (long)lnum, nchars); /* add line/char count */
4963 if (!shortmess(SHM_WRITE))
4964 {
4965 if (append)
4966 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended"));
4967 else
4968 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written"));
4969 }
4970
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00004971 set_keep_msg(msg_trunc_attr(IObuff, FALSE, 0), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004972 }
4973
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004974 /* When written everything correctly: reset 'modified'. Unless not
4975 * writing to the original file and '+' is not in 'cpoptions'. */
Bram Moolenaar292ad192005-12-11 21:29:51 +00004976 if (reset_changed && whole && !append
Bram Moolenaar071d4272004-06-13 20:20:40 +00004977#ifdef FEAT_MBYTE
4978 && !write_info.bw_conv_error
4979#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004980 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL)
4981 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004982 {
4983 unchanged(buf, TRUE);
Bram Moolenaar086329d2014-10-31 19:51:36 +01004984#ifdef FEAT_AUTOCMD
Bram Moolenaar95c526e2017-02-25 14:59:34 +01004985 /* b:changedtick is always incremented in unchanged() but that
Bram Moolenaar086329d2014-10-31 19:51:36 +01004986 * should not trigger a TextChanged event. */
Bram Moolenaar95c526e2017-02-25 14:59:34 +01004987 if (last_changedtick + 1 == CHANGEDTICK(buf)
Bram Moolenaar086329d2014-10-31 19:51:36 +01004988 && last_changedtick_buf == buf)
Bram Moolenaar95c526e2017-02-25 14:59:34 +01004989 last_changedtick = CHANGEDTICK(buf);
Bram Moolenaar086329d2014-10-31 19:51:36 +01004990#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004991 u_unchanged(buf);
Bram Moolenaar730cde92010-06-27 05:18:54 +02004992 u_update_save_nr(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004993 }
4994
4995 /*
4996 * If written to the current file, update the timestamp of the swap file
4997 * and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
4998 */
4999 if (overwriting)
5000 {
5001 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00005002 if (append)
5003 buf->b_flags &= ~BF_NEW;
5004 else
5005 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005006 }
5007
5008 /*
5009 * If we kept a backup until now, and we are in patch mode, then we make
5010 * the backup file our 'original' file.
5011 */
5012 if (*p_pm && dobackup)
5013 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01005014 char *org = (char *)buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005015 fname, p_pm, FALSE);
5016
5017 if (backup != NULL)
5018 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02005019 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005020
5021 /*
5022 * If the original file does not exist yet
5023 * the current backup file becomes the original file
5024 */
5025 if (org == NULL)
5026 EMSG(_("E205: Patchmode: can't save original file"));
5027 else if (mch_stat(org, &st) < 0)
5028 {
5029 vim_rename(backup, (char_u *)org);
5030 vim_free(backup); /* don't delete the file */
5031 backup = NULL;
5032#ifdef UNIX
5033 set_file_time((char_u *)org, st_old.st_atime, st_old.st_mtime);
5034#endif
5035 }
5036 }
5037 /*
5038 * If there is no backup file, remember that a (new) file was
5039 * created.
5040 */
5041 else
5042 {
5043 int empty_fd;
5044
5045 if (org == NULL
Bram Moolenaara5792f52005-11-23 21:25:05 +00005046 || (empty_fd = mch_open(org,
5047 O_CREAT | O_EXTRA | O_EXCL | O_NOFOLLOW,
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00005048 perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005049 EMSG(_("E206: patchmode: can't touch empty original file"));
5050 else
5051 close(empty_fd);
5052 }
5053 if (org != NULL)
5054 {
5055 mch_setperm((char_u *)org, mch_getperm(fname) & 0777);
5056 vim_free(org);
5057 }
5058 }
5059
5060 /*
5061 * Remove the backup unless 'backup' option is set
5062 */
5063 if (!p_bk && backup != NULL && mch_remove(backup) != 0)
5064 EMSG(_("E207: Can't delete backup file"));
5065
5066#ifdef FEAT_SUN_WORKSHOP
5067 if (usingSunWorkShop)
5068 workshop_file_saved((char *) ffname);
5069#endif
5070
5071 goto nofail;
5072
5073 /*
5074 * Finish up. We get here either after failure or success.
5075 */
5076fail:
5077 --no_wait_return; /* may wait for return now */
5078nofail:
5079
5080 /* Done saving, we accept changed buffer warnings again */
5081 buf->b_saving = FALSE;
5082
5083 vim_free(backup);
5084 if (buffer != smallbuf)
5085 vim_free(buffer);
5086#ifdef FEAT_MBYTE
5087 vim_free(fenc_tofree);
5088 vim_free(write_info.bw_conv_buf);
5089# ifdef USE_ICONV
5090 if (write_info.bw_iconv_fd != (iconv_t)-1)
5091 {
5092 iconv_close(write_info.bw_iconv_fd);
5093 write_info.bw_iconv_fd = (iconv_t)-1;
5094 }
5095# endif
5096#endif
5097#ifdef HAVE_ACL
5098 mch_free_acl(acl);
5099#endif
5100
5101 if (errmsg != NULL)
5102 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005103 int numlen = errnum != NULL ? (int)STRLEN(errnum) : 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005104
Bram Moolenaar8820b482017-03-16 17:23:31 +01005105 attr = HL_ATTR(HLF_E); /* set highlight for error messages */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005106 msg_add_fname(buf,
5107#ifndef UNIX
5108 sfname
5109#else
5110 fname
5111#endif
5112 ); /* put file name in IObuff with quotes */
5113 if (STRLEN(IObuff) + STRLEN(errmsg) + numlen >= IOSIZE)
5114 IObuff[IOSIZE - STRLEN(errmsg) - numlen - 1] = NUL;
5115 /* If the error message has the form "is ...", put the error number in
5116 * front of the file name. */
5117 if (errnum != NULL)
5118 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00005119 STRMOVE(IObuff + numlen, IObuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005120 mch_memmove(IObuff, errnum, (size_t)numlen);
5121 }
5122 STRCAT(IObuff, errmsg);
5123 emsg(IObuff);
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005124 if (errmsg_allocated)
5125 vim_free(errmsg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005126
5127 retval = FAIL;
5128 if (end == 0)
5129 {
5130 MSG_PUTS_ATTR(_("\nWARNING: Original file may be lost or damaged\n"),
5131 attr | MSG_HIST);
5132 MSG_PUTS_ATTR(_("don't quit the editor until the file is successfully written!"),
5133 attr | MSG_HIST);
5134
5135 /* Update the timestamp to avoid an "overwrite changed file"
5136 * prompt when writing again. */
5137 if (mch_stat((char *)fname, &st_old) >= 0)
5138 {
5139 buf_store_time(buf, &st_old, fname);
5140 buf->b_mtime_read = buf->b_mtime;
5141 }
5142 }
5143 }
5144 msg_scroll = msg_save;
5145
Bram Moolenaar55debbe2010-05-23 23:34:36 +02005146#ifdef FEAT_PERSISTENT_UNDO
5147 /*
5148 * When writing the whole file and 'undofile' is set, also write the undo
5149 * file.
5150 */
5151 if (retval == OK && write_undo_file)
5152 {
5153 char_u hash[UNDO_HASH_SIZE];
5154
5155 sha256_finish(&sha_ctx, hash);
5156 u_write_undo(NULL, FALSE, buf, hash);
5157 }
5158#endif
5159
Bram Moolenaar071d4272004-06-13 20:20:40 +00005160#ifdef FEAT_AUTOCMD
5161#ifdef FEAT_EVAL
5162 if (!should_abort(retval))
5163#else
5164 if (!got_int)
5165#endif
5166 {
5167 aco_save_T aco;
5168
Bram Moolenaar68a33fc2012-04-25 16:50:48 +02005169 curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */
5170
Bram Moolenaar071d4272004-06-13 20:20:40 +00005171 /*
5172 * Apply POST autocommands.
5173 * Careful: The autocommands may call buf_write() recursively!
5174 */
5175 aucmd_prepbuf(&aco, buf);
5176
5177 if (append)
5178 apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname,
5179 FALSE, curbuf, eap);
5180 else if (filtering)
5181 apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname,
5182 FALSE, curbuf, eap);
5183 else if (reset_changed && whole)
5184 apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname,
5185 FALSE, curbuf, eap);
5186 else
5187 apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname,
5188 FALSE, curbuf, eap);
5189
5190 /* restore curwin/curbuf and a few other things */
5191 aucmd_restbuf(&aco);
5192
5193#ifdef FEAT_EVAL
5194 if (aborting()) /* autocmds may abort script processing */
5195 retval = FALSE;
5196#endif
5197 }
5198#endif
5199
5200 got_int |= prev_got_int;
5201
5202#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
5203 /* Update machine specific information. */
5204 mch_post_buffer_write(buf);
5205#endif
5206 return retval;
5207}
5208
5209/*
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005210 * Set the name of the current buffer. Use when the buffer doesn't have a
5211 * name and a ":r" or ":w" command with a file name is used.
5212 */
5213 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005214set_rw_fname(char_u *fname, char_u *sfname)
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005215{
5216#ifdef FEAT_AUTOCMD
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005217 buf_T *buf = curbuf;
5218
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005219 /* It's like the unnamed buffer is deleted.... */
5220 if (curbuf->b_p_bl)
5221 apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
5222 apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf);
5223# ifdef FEAT_EVAL
5224 if (aborting()) /* autocmds may abort script processing */
5225 return FAIL;
5226# endif
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005227 if (curbuf != buf)
5228 {
5229 /* We are in another buffer now, don't do the renaming. */
5230 EMSG(_(e_auchangedbuf));
5231 return FAIL;
5232 }
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005233#endif
5234
5235 if (setfname(curbuf, fname, sfname, FALSE) == OK)
5236 curbuf->b_flags |= BF_NOTEDITED;
5237
5238#ifdef FEAT_AUTOCMD
5239 /* ....and a new named one is created */
5240 apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, curbuf);
5241 if (curbuf->b_p_bl)
5242 apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf);
5243# ifdef FEAT_EVAL
5244 if (aborting()) /* autocmds may abort script processing */
5245 return FAIL;
5246# endif
5247
5248 /* Do filetype detection now if 'filetype' is empty. */
5249 if (*curbuf->b_p_ft == NUL)
5250 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005251 if (au_has_group((char_u *)"filetypedetect"))
Bram Moolenaar1610d052016-06-09 22:53:01 +02005252 (void)do_doautocmd((char_u *)"filetypedetect BufRead", FALSE, NULL);
Bram Moolenaara3227e22006-03-08 21:32:40 +00005253 do_modelines(0);
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005254 }
5255#endif
5256
5257 return OK;
5258}
5259
5260/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00005261 * Put file name into IObuff with quotes.
5262 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005263 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005264msg_add_fname(buf_T *buf, char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005265{
5266 if (fname == NULL)
5267 fname = (char_u *)"-stdin-";
5268 home_replace(buf, fname, IObuff + 1, IOSIZE - 4, TRUE);
5269 IObuff[0] = '"';
5270 STRCAT(IObuff, "\" ");
5271}
5272
5273/*
5274 * Append message for text mode to IObuff.
5275 * Return TRUE if something appended.
5276 */
5277 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005278msg_add_fileformat(int eol_type)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005279{
5280#ifndef USE_CRNL
5281 if (eol_type == EOL_DOS)
5282 {
5283 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[dos]") : _("[dos format]"));
5284 return TRUE;
5285 }
5286#endif
5287#ifndef USE_CR
5288 if (eol_type == EOL_MAC)
5289 {
5290 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[mac]") : _("[mac format]"));
5291 return TRUE;
5292 }
5293#endif
5294#if defined(USE_CRNL) || defined(USE_CR)
5295 if (eol_type == EOL_UNIX)
5296 {
5297 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[unix]") : _("[unix format]"));
5298 return TRUE;
5299 }
5300#endif
5301 return FALSE;
5302}
5303
5304/*
5305 * Append line and character count to IObuff.
5306 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005307 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005308msg_add_lines(
5309 int insert_space,
5310 long lnum,
Bram Moolenaar8767f522016-07-01 17:17:39 +02005311 off_T nchars)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005312{
5313 char_u *p;
5314
5315 p = IObuff + STRLEN(IObuff);
5316
5317 if (insert_space)
5318 *p++ = ' ';
5319 if (shortmess(SHM_LINES))
Bram Moolenaarbde98102016-07-01 20:03:42 +02005320 vim_snprintf((char *)p, IOSIZE - (p - IObuff),
5321 "%ldL, %lldC", lnum, (varnumber_T)nchars);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005322 else
5323 {
5324 if (lnum == 1)
5325 STRCPY(p, _("1 line, "));
5326 else
5327 sprintf((char *)p, _("%ld lines, "), lnum);
5328 p += STRLEN(p);
5329 if (nchars == 1)
5330 STRCPY(p, _("1 character"));
5331 else
Bram Moolenaarbde98102016-07-01 20:03:42 +02005332 vim_snprintf((char *)p, IOSIZE - (p - IObuff),
5333 _("%lld characters"), (varnumber_T)nchars);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005334 }
5335}
5336
5337/*
5338 * Append message for missing line separator to IObuff.
5339 */
5340 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005341msg_add_eol(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005342{
5343 STRCAT(IObuff, shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]"));
5344}
5345
5346/*
5347 * Check modification time of file, before writing to it.
5348 * The size isn't checked, because using a tool like "gzip" takes care of
5349 * using the same timestamp but can't set the size.
5350 */
5351 static int
Bram Moolenaar8767f522016-07-01 17:17:39 +02005352check_mtime(buf_T *buf, stat_T *st)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005353{
5354 if (buf->b_mtime_read != 0
5355 && time_differs((long)st->st_mtime, buf->b_mtime_read))
5356 {
5357 msg_scroll = TRUE; /* don't overwrite messages here */
5358 msg_silent = 0; /* must give this prompt */
5359 /* don't use emsg() here, don't want to flush the buffers */
5360 MSG_ATTR(_("WARNING: The file has been changed since reading it!!!"),
Bram Moolenaar8820b482017-03-16 17:23:31 +01005361 HL_ATTR(HLF_E));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005362 if (ask_yesno((char_u *)_("Do you really want to write to it"),
5363 TRUE) == 'n')
5364 return FAIL;
5365 msg_scroll = FALSE; /* always overwrite the file message now */
5366 }
5367 return OK;
5368}
5369
5370 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005371time_differs(long t1, long t2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005372{
Bram Moolenaar48e330a2016-02-23 14:53:34 +01005373#if defined(__linux__) || defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005374 /* On a FAT filesystem, esp. under Linux, there are only 5 bits to store
5375 * the seconds. Since the roundoff is done when flushing the inode, the
5376 * time may change unexpectedly by one second!!! */
5377 return (t1 - t2 > 1 || t2 - t1 > 1);
5378#else
5379 return (t1 != t2);
5380#endif
5381}
5382
5383/*
5384 * Call write() to write a number of bytes to the file.
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005385 * Handles encryption and 'encoding' conversion.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005386 *
5387 * Return FAIL for failure, OK otherwise.
5388 */
5389 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005390buf_write_bytes(struct bw_info *ip)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005391{
5392 int wlen;
5393 char_u *buf = ip->bw_buf; /* data to write */
5394 int len = ip->bw_len; /* length of data */
5395#ifdef HAS_BW_FLAGS
5396 int flags = ip->bw_flags; /* extra flags */
5397#endif
5398
5399#ifdef FEAT_MBYTE
5400 /*
5401 * Skip conversion when writing the crypt magic number or the BOM.
5402 */
5403 if (!(flags & FIO_NOCONVERT))
5404 {
5405 char_u *p;
5406 unsigned c;
5407 int n;
5408
5409 if (flags & FIO_UTF8)
5410 {
5411 /*
5412 * Convert latin1 in the buffer to UTF-8 in the file.
5413 */
5414 p = ip->bw_conv_buf; /* translate to buffer */
5415 for (wlen = 0; wlen < len; ++wlen)
5416 p += utf_char2bytes(buf[wlen], p);
5417 buf = ip->bw_conv_buf;
5418 len = (int)(p - ip->bw_conv_buf);
5419 }
5420 else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1))
5421 {
5422 /*
5423 * Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
5424 * Latin1 chars in the file.
5425 */
5426 if (flags & FIO_LATIN1)
5427 p = buf; /* translate in-place (can only get shorter) */
5428 else
5429 p = ip->bw_conv_buf; /* translate to buffer */
5430 for (wlen = 0; wlen < len; wlen += n)
5431 {
5432 if (wlen == 0 && ip->bw_restlen != 0)
5433 {
5434 int l;
5435
5436 /* Use remainder of previous call. Append the start of
5437 * buf[] to get a full sequence. Might still be too
5438 * short! */
5439 l = CONV_RESTLEN - ip->bw_restlen;
5440 if (l > len)
5441 l = len;
5442 mch_memmove(ip->bw_rest + ip->bw_restlen, buf, (size_t)l);
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005443 n = utf_ptr2len_len(ip->bw_rest, ip->bw_restlen + l);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005444 if (n > ip->bw_restlen + len)
5445 {
5446 /* We have an incomplete byte sequence at the end to
5447 * be written. We can't convert it without the
5448 * remaining bytes. Keep them for the next call. */
5449 if (ip->bw_restlen + len > CONV_RESTLEN)
5450 return FAIL;
5451 ip->bw_restlen += len;
5452 break;
5453 }
5454 if (n > 1)
5455 c = utf_ptr2char(ip->bw_rest);
5456 else
5457 c = ip->bw_rest[0];
5458 if (n >= ip->bw_restlen)
5459 {
5460 n -= ip->bw_restlen;
5461 ip->bw_restlen = 0;
5462 }
5463 else
5464 {
5465 ip->bw_restlen -= n;
5466 mch_memmove(ip->bw_rest, ip->bw_rest + n,
5467 (size_t)ip->bw_restlen);
5468 n = 0;
5469 }
5470 }
5471 else
5472 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005473 n = utf_ptr2len_len(buf + wlen, len - wlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005474 if (n > len - wlen)
5475 {
5476 /* We have an incomplete byte sequence at the end to
5477 * be written. We can't convert it without the
5478 * remaining bytes. Keep them for the next call. */
5479 if (len - wlen > CONV_RESTLEN)
5480 return FAIL;
5481 ip->bw_restlen = len - wlen;
5482 mch_memmove(ip->bw_rest, buf + wlen,
5483 (size_t)ip->bw_restlen);
5484 break;
5485 }
5486 if (n > 1)
5487 c = utf_ptr2char(buf + wlen);
5488 else
5489 c = buf[wlen];
5490 }
5491
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005492 if (ucs2bytes(c, &p, flags) && !ip->bw_conv_error)
5493 {
5494 ip->bw_conv_error = TRUE;
5495 ip->bw_conv_error_lnum = ip->bw_start_lnum;
5496 }
5497 if (c == NL)
5498 ++ip->bw_start_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005499 }
5500 if (flags & FIO_LATIN1)
5501 len = (int)(p - buf);
5502 else
5503 {
5504 buf = ip->bw_conv_buf;
5505 len = (int)(p - ip->bw_conv_buf);
5506 }
5507 }
5508
5509# ifdef WIN3264
5510 else if (flags & FIO_CODEPAGE)
5511 {
5512 /*
5513 * Convert UTF-8 or codepage to UCS-2 and then to MS-Windows
5514 * codepage.
5515 */
5516 char_u *from;
5517 size_t fromlen;
5518 char_u *to;
5519 int u8c;
5520 BOOL bad = FALSE;
5521 int needed;
5522
5523 if (ip->bw_restlen > 0)
5524 {
5525 /* Need to concatenate the remainder of the previous call and
5526 * the bytes of the current call. Use the end of the
5527 * conversion buffer for this. */
5528 fromlen = len + ip->bw_restlen;
5529 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5530 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5531 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5532 }
5533 else
5534 {
5535 from = buf;
5536 fromlen = len;
5537 }
5538
5539 to = ip->bw_conv_buf;
5540 if (enc_utf8)
5541 {
5542 /* Convert from UTF-8 to UCS-2, to the start of the buffer.
5543 * The buffer has been allocated to be big enough. */
5544 while (fromlen > 0)
5545 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005546 n = (int)utf_ptr2len_len(from, (int)fromlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005547 if (n > (int)fromlen) /* incomplete byte sequence */
5548 break;
5549 u8c = utf_ptr2char(from);
5550 *to++ = (u8c & 0xff);
5551 *to++ = (u8c >> 8);
5552 fromlen -= n;
5553 from += n;
5554 }
5555
5556 /* Copy remainder to ip->bw_rest[] to be used for the next
5557 * call. */
5558 if (fromlen > CONV_RESTLEN)
5559 {
5560 /* weird overlong sequence */
5561 ip->bw_conv_error = TRUE;
5562 return FAIL;
5563 }
5564 mch_memmove(ip->bw_rest, from, fromlen);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005565 ip->bw_restlen = (int)fromlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005566 }
5567 else
5568 {
5569 /* Convert from enc_codepage to UCS-2, to the start of the
5570 * buffer. The buffer has been allocated to be big enough. */
5571 ip->bw_restlen = 0;
5572 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005573 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005574 NULL, 0);
5575 if (needed == 0)
5576 {
5577 /* When conversion fails there may be a trailing byte. */
5578 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005579 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen - 1,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005580 NULL, 0);
5581 if (needed == 0)
5582 {
5583 /* Conversion doesn't work. */
5584 ip->bw_conv_error = TRUE;
5585 return FAIL;
5586 }
5587 /* Save the trailing byte for the next call. */
5588 ip->bw_rest[0] = from[fromlen - 1];
5589 ip->bw_restlen = 1;
5590 }
5591 needed = MultiByteToWideChar(enc_codepage, MB_ERR_INVALID_CHARS,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005592 (LPCSTR)from, (int)(fromlen - ip->bw_restlen),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005593 (LPWSTR)to, needed);
5594 if (needed == 0)
5595 {
5596 /* Safety check: Conversion doesn't work. */
5597 ip->bw_conv_error = TRUE;
5598 return FAIL;
5599 }
5600 to += needed * 2;
5601 }
5602
5603 fromlen = to - ip->bw_conv_buf;
5604 buf = to;
5605# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5606 if (FIO_GET_CP(flags) == CP_UTF8)
5607 {
5608 /* Convert from UCS-2 to UTF-8, using the remainder of the
5609 * conversion buffer. Fails when out of space. */
5610 for (from = ip->bw_conv_buf; fromlen > 1; fromlen -= 2)
5611 {
5612 u8c = *from++;
5613 u8c += (*from++ << 8);
5614 to += utf_char2bytes(u8c, to);
5615 if (to + 6 >= ip->bw_conv_buf + ip->bw_conv_buflen)
5616 {
5617 ip->bw_conv_error = TRUE;
5618 return FAIL;
5619 }
5620 }
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005621 len = (int)(to - buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005622 }
5623 else
5624#endif
5625 {
5626 /* Convert from UCS-2 to the codepage, using the remainder of
5627 * the conversion buffer. If the conversion uses the default
5628 * character "0", the data doesn't fit in this encoding, so
5629 * fail. */
5630 len = WideCharToMultiByte(FIO_GET_CP(flags), 0,
5631 (LPCWSTR)ip->bw_conv_buf, (int)fromlen / sizeof(WCHAR),
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005632 (LPSTR)to, (int)(ip->bw_conv_buflen - fromlen), 0,
5633 &bad);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005634 if (bad)
5635 {
5636 ip->bw_conv_error = TRUE;
5637 return FAIL;
5638 }
5639 }
5640 }
5641# endif
5642
Bram Moolenaar56718732006-03-15 22:53:57 +00005643# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00005644 else if (flags & FIO_MACROMAN)
5645 {
5646 /*
5647 * Convert UTF-8 or latin1 to Apple MacRoman.
5648 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005649 char_u *from;
5650 size_t fromlen;
5651
5652 if (ip->bw_restlen > 0)
5653 {
5654 /* Need to concatenate the remainder of the previous call and
5655 * the bytes of the current call. Use the end of the
5656 * conversion buffer for this. */
5657 fromlen = len + ip->bw_restlen;
5658 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5659 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5660 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5661 }
5662 else
5663 {
5664 from = buf;
5665 fromlen = len;
5666 }
5667
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00005668 if (enc2macroman(from, fromlen,
5669 ip->bw_conv_buf, &len, ip->bw_conv_buflen,
5670 ip->bw_rest, &ip->bw_restlen) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005671 {
5672 ip->bw_conv_error = TRUE;
5673 return FAIL;
5674 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005675 buf = ip->bw_conv_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005676 }
5677# endif
5678
5679# ifdef USE_ICONV
5680 if (ip->bw_iconv_fd != (iconv_t)-1)
5681 {
5682 const char *from;
5683 size_t fromlen;
5684 char *to;
5685 size_t tolen;
5686
5687 /* Convert with iconv(). */
5688 if (ip->bw_restlen > 0)
5689 {
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005690 char *fp;
5691
Bram Moolenaar071d4272004-06-13 20:20:40 +00005692 /* Need to concatenate the remainder of the previous call and
5693 * the bytes of the current call. Use the end of the
5694 * conversion buffer for this. */
5695 fromlen = len + ip->bw_restlen;
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005696 fp = (char *)ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5697 mch_memmove(fp, ip->bw_rest, (size_t)ip->bw_restlen);
5698 mch_memmove(fp + ip->bw_restlen, buf, (size_t)len);
5699 from = fp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005700 tolen = ip->bw_conv_buflen - fromlen;
5701 }
5702 else
5703 {
5704 from = (const char *)buf;
5705 fromlen = len;
5706 tolen = ip->bw_conv_buflen;
5707 }
5708 to = (char *)ip->bw_conv_buf;
5709
5710 if (ip->bw_first)
5711 {
5712 size_t save_len = tolen;
5713
5714 /* output the initial shift state sequence */
5715 (void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen);
5716
5717 /* There is a bug in iconv() on Linux (which appears to be
5718 * wide-spread) which sets "to" to NULL and messes up "tolen".
5719 */
5720 if (to == NULL)
5721 {
5722 to = (char *)ip->bw_conv_buf;
5723 tolen = save_len;
5724 }
5725 ip->bw_first = FALSE;
5726 }
5727
5728 /*
5729 * If iconv() has an error or there is not enough room, fail.
5730 */
5731 if ((iconv(ip->bw_iconv_fd, (void *)&from, &fromlen, &to, &tolen)
5732 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
5733 || fromlen > CONV_RESTLEN)
5734 {
5735 ip->bw_conv_error = TRUE;
5736 return FAIL;
5737 }
5738
5739 /* copy remainder to ip->bw_rest[] to be used for the next call. */
5740 if (fromlen > 0)
5741 mch_memmove(ip->bw_rest, (void *)from, fromlen);
5742 ip->bw_restlen = (int)fromlen;
5743
5744 buf = ip->bw_conv_buf;
5745 len = (int)((char_u *)to - ip->bw_conv_buf);
5746 }
5747# endif
5748 }
5749#endif /* FEAT_MBYTE */
5750
Bram Moolenaare6bf6552017-06-27 22:11:51 +02005751 if (ip->bw_fd < 0)
5752 /* Only checking conversion, which is OK if we get here. */
5753 return OK;
5754
Bram Moolenaar071d4272004-06-13 20:20:40 +00005755#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02005756 if (flags & FIO_ENCRYPTED)
5757 {
5758 /* Encrypt the data. Do it in-place if possible, otherwise use an
5759 * allocated buffer. */
5760 if (crypt_works_inplace(ip->bw_buffer->b_cryptstate))
5761 {
5762 crypt_encode_inplace(ip->bw_buffer->b_cryptstate, buf, len);
5763 }
5764 else
5765 {
5766 char_u *outbuf;
5767
5768 len = crypt_encode_alloc(curbuf->b_cryptstate, buf, len, &outbuf);
5769 if (len == 0)
5770 return OK; /* Crypt layer is buffering, will flush later. */
5771 wlen = write_eintr(ip->bw_fd, outbuf, len);
5772 vim_free(outbuf);
5773 return (wlen < len) ? FAIL : OK;
5774 }
5775 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005776#endif
5777
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005778 wlen = write_eintr(ip->bw_fd, buf, len);
5779 return (wlen < len) ? FAIL : OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005780}
5781
5782#ifdef FEAT_MBYTE
5783/*
5784 * Convert a Unicode character to bytes.
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005785 * Return TRUE for an error, FALSE when it's OK.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005786 */
5787 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005788ucs2bytes(
5789 unsigned c, /* in: character */
5790 char_u **pp, /* in/out: pointer to result */
5791 int flags) /* FIO_ flags */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005792{
5793 char_u *p = *pp;
5794 int error = FALSE;
5795 int cc;
5796
5797
5798 if (flags & FIO_UCS4)
5799 {
5800 if (flags & FIO_ENDIAN_L)
5801 {
5802 *p++ = c;
5803 *p++ = (c >> 8);
5804 *p++ = (c >> 16);
5805 *p++ = (c >> 24);
5806 }
5807 else
5808 {
5809 *p++ = (c >> 24);
5810 *p++ = (c >> 16);
5811 *p++ = (c >> 8);
5812 *p++ = c;
5813 }
5814 }
5815 else if (flags & (FIO_UCS2 | FIO_UTF16))
5816 {
5817 if (c >= 0x10000)
5818 {
5819 if (flags & FIO_UTF16)
5820 {
5821 /* Make two words, ten bits of the character in each. First
5822 * word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff */
5823 c -= 0x10000;
5824 if (c >= 0x100000)
5825 error = TRUE;
5826 cc = ((c >> 10) & 0x3ff) + 0xd800;
5827 if (flags & FIO_ENDIAN_L)
5828 {
5829 *p++ = cc;
5830 *p++ = ((unsigned)cc >> 8);
5831 }
5832 else
5833 {
5834 *p++ = ((unsigned)cc >> 8);
5835 *p++ = cc;
5836 }
5837 c = (c & 0x3ff) + 0xdc00;
5838 }
5839 else
5840 error = TRUE;
5841 }
5842 if (flags & FIO_ENDIAN_L)
5843 {
5844 *p++ = c;
5845 *p++ = (c >> 8);
5846 }
5847 else
5848 {
5849 *p++ = (c >> 8);
5850 *p++ = c;
5851 }
5852 }
5853 else /* Latin1 */
5854 {
5855 if (c >= 0x100)
5856 {
5857 error = TRUE;
5858 *p++ = 0xBF;
5859 }
5860 else
5861 *p++ = c;
5862 }
5863
5864 *pp = p;
5865 return error;
5866}
5867
5868/*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005869 * Return TRUE if file encoding "fenc" requires conversion from or to
5870 * 'encoding'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005871 */
5872 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005873need_conversion(char_u *fenc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005874{
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005875 int same_encoding;
5876 int enc_flags;
5877 int fenc_flags;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005878
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005879 if (*fenc == NUL || STRCMP(p_enc, fenc) == 0)
Bram Moolenaar442b4222010-05-24 21:34:22 +02005880 {
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005881 same_encoding = TRUE;
Bram Moolenaar442b4222010-05-24 21:34:22 +02005882 fenc_flags = 0;
5883 }
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005884 else
5885 {
5886 /* Ignore difference between "ansi" and "latin1", "ucs-4" and
5887 * "ucs-4be", etc. */
5888 enc_flags = get_fio_flags(p_enc);
5889 fenc_flags = get_fio_flags(fenc);
5890 same_encoding = (enc_flags != 0 && fenc_flags == enc_flags);
5891 }
5892 if (same_encoding)
5893 {
5894 /* Specified encoding matches with 'encoding'. This requires
5895 * conversion when 'encoding' is Unicode but not UTF-8. */
5896 return enc_unicode != 0;
5897 }
5898
5899 /* Encodings differ. However, conversion is not needed when 'enc' is any
5900 * Unicode encoding and the file is UTF-8. */
5901 return !(enc_utf8 && fenc_flags == FIO_UTF8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005902}
5903
5904/*
5905 * Check "ptr" for a unicode encoding and return the FIO_ flags needed for the
5906 * internal conversion.
5907 * if "ptr" is an empty string, use 'encoding'.
5908 */
5909 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005910get_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005911{
5912 int prop;
5913
5914 if (*ptr == NUL)
5915 ptr = p_enc;
5916
5917 prop = enc_canon_props(ptr);
5918 if (prop & ENC_UNICODE)
5919 {
5920 if (prop & ENC_2BYTE)
5921 {
5922 if (prop & ENC_ENDIAN_L)
5923 return FIO_UCS2 | FIO_ENDIAN_L;
5924 return FIO_UCS2;
5925 }
5926 if (prop & ENC_4BYTE)
5927 {
5928 if (prop & ENC_ENDIAN_L)
5929 return FIO_UCS4 | FIO_ENDIAN_L;
5930 return FIO_UCS4;
5931 }
5932 if (prop & ENC_2WORD)
5933 {
5934 if (prop & ENC_ENDIAN_L)
5935 return FIO_UTF16 | FIO_ENDIAN_L;
5936 return FIO_UTF16;
5937 }
5938 return FIO_UTF8;
5939 }
5940 if (prop & ENC_LATIN1)
5941 return FIO_LATIN1;
5942 /* must be ENC_DBCS, requires iconv() */
5943 return 0;
5944}
5945
5946#ifdef WIN3264
5947/*
5948 * Check "ptr" for a MS-Windows codepage name and return the FIO_ flags needed
5949 * for the conversion MS-Windows can do for us. Also accept "utf-8".
5950 * Used for conversion between 'encoding' and 'fileencoding'.
5951 */
5952 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005953get_win_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005954{
5955 int cp;
5956
5957 /* Cannot do this when 'encoding' is not utf-8 and not a codepage. */
5958 if (!enc_utf8 && enc_codepage <= 0)
5959 return 0;
5960
5961 cp = encname2codepage(ptr);
5962 if (cp == 0)
5963 {
5964# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5965 if (STRCMP(ptr, "utf-8") == 0)
5966 cp = CP_UTF8;
5967 else
5968# endif
5969 return 0;
5970 }
5971 return FIO_PUT_CP(cp) | FIO_CODEPAGE;
5972}
5973#endif
5974
5975#ifdef MACOS_X
5976/*
5977 * Check "ptr" for a Carbon supported encoding and return the FIO_ flags
5978 * needed for the internal conversion to/from utf-8 or latin1.
5979 */
5980 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005981get_mac_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005982{
5983 if ((enc_utf8 || STRCMP(p_enc, "latin1") == 0)
5984 && (enc_canon_props(ptr) & ENC_MACROMAN))
5985 return FIO_MACROMAN;
5986 return 0;
5987}
5988#endif
5989
5990/*
5991 * Check for a Unicode BOM (Byte Order Mark) at the start of p[size].
5992 * "size" must be at least 2.
5993 * Return the name of the encoding and set "*lenp" to the length.
5994 * Returns NULL when no BOM found.
5995 */
5996 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005997check_for_bom(
5998 char_u *p,
5999 long size,
6000 int *lenp,
6001 int flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006002{
6003 char *name = NULL;
6004 int len = 2;
6005
6006 if (p[0] == 0xef && p[1] == 0xbb && size >= 3 && p[2] == 0xbf
Bram Moolenaaree0f5a62008-07-24 20:09:16 +00006007 && (flags == FIO_ALL || flags == FIO_UTF8 || flags == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006008 {
6009 name = "utf-8"; /* EF BB BF */
6010 len = 3;
6011 }
6012 else if (p[0] == 0xff && p[1] == 0xfe)
6013 {
6014 if (size >= 4 && p[2] == 0 && p[3] == 0
6015 && (flags == FIO_ALL || flags == (FIO_UCS4 | FIO_ENDIAN_L)))
6016 {
6017 name = "ucs-4le"; /* FF FE 00 00 */
6018 len = 4;
6019 }
Bram Moolenaar223a1892008-11-11 20:57:11 +00006020 else if (flags == (FIO_UCS2 | FIO_ENDIAN_L))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006021 name = "ucs-2le"; /* FF FE */
Bram Moolenaar223a1892008-11-11 20:57:11 +00006022 else if (flags == FIO_ALL || flags == (FIO_UTF16 | FIO_ENDIAN_L))
6023 /* utf-16le is preferred, it also works for ucs-2le text */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006024 name = "utf-16le"; /* FF FE */
6025 }
6026 else if (p[0] == 0xfe && p[1] == 0xff
6027 && (flags == FIO_ALL || flags == FIO_UCS2 || flags == FIO_UTF16))
6028 {
Bram Moolenaarffd82c52008-02-20 17:15:26 +00006029 /* Default to utf-16, it works also for ucs-2 text. */
6030 if (flags == FIO_UCS2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006031 name = "ucs-2"; /* FE FF */
Bram Moolenaarffd82c52008-02-20 17:15:26 +00006032 else
6033 name = "utf-16"; /* FE FF */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006034 }
6035 else if (size >= 4 && p[0] == 0 && p[1] == 0 && p[2] == 0xfe
6036 && p[3] == 0xff && (flags == FIO_ALL || flags == FIO_UCS4))
6037 {
6038 name = "ucs-4"; /* 00 00 FE FF */
6039 len = 4;
6040 }
6041
6042 *lenp = len;
6043 return (char_u *)name;
6044}
6045
6046/*
6047 * Generate a BOM in "buf[4]" for encoding "name".
6048 * Return the length of the BOM (zero when no BOM).
6049 */
6050 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006051make_bom(char_u *buf, char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006052{
6053 int flags;
6054 char_u *p;
6055
6056 flags = get_fio_flags(name);
6057
6058 /* Can't put a BOM in a non-Unicode file. */
6059 if (flags == FIO_LATIN1 || flags == 0)
6060 return 0;
6061
6062 if (flags == FIO_UTF8) /* UTF-8 */
6063 {
6064 buf[0] = 0xef;
6065 buf[1] = 0xbb;
6066 buf[2] = 0xbf;
6067 return 3;
6068 }
6069 p = buf;
6070 (void)ucs2bytes(0xfeff, &p, flags);
6071 return (int)(p - buf);
6072}
6073#endif
6074
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00006075#if defined(FEAT_VIMINFO) || defined(FEAT_BROWSE) || \
Bram Moolenaara0174af2008-01-02 20:08:25 +00006076 defined(FEAT_QUICKFIX) || defined(FEAT_AUTOCMD) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006077/*
6078 * Try to find a shortname by comparing the fullname with the current
6079 * directory.
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006080 * Returns "full_path" or pointer into "full_path" if shortened.
6081 */
6082 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006083shorten_fname1(char_u *full_path)
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006084{
Bram Moolenaard9462e32011-04-11 21:35:11 +02006085 char_u *dirname;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006086 char_u *p = full_path;
6087
Bram Moolenaard9462e32011-04-11 21:35:11 +02006088 dirname = alloc(MAXPATHL);
6089 if (dirname == NULL)
6090 return full_path;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006091 if (mch_dirname(dirname, MAXPATHL) == OK)
6092 {
6093 p = shorten_fname(full_path, dirname);
6094 if (p == NULL || *p == NUL)
6095 p = full_path;
6096 }
Bram Moolenaard9462e32011-04-11 21:35:11 +02006097 vim_free(dirname);
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006098 return p;
6099}
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00006100#endif
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006101
6102/*
6103 * Try to find a shortname by comparing the fullname with the current
6104 * directory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006105 * Returns NULL if not shorter name possible, pointer into "full_path"
6106 * otherwise.
6107 */
6108 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006109shorten_fname(char_u *full_path, char_u *dir_name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006110{
6111 int len;
6112 char_u *p;
6113
6114 if (full_path == NULL)
6115 return NULL;
6116 len = (int)STRLEN(dir_name);
6117 if (fnamencmp(dir_name, full_path, len) == 0)
6118 {
6119 p = full_path + len;
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006120#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006121 /*
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006122 * MSWIN: when a file is in the root directory, dir_name will end in a
Bram Moolenaar071d4272004-06-13 20:20:40 +00006123 * slash, since C: by itself does not define a specific dir. In this
6124 * case p may already be correct. <negri>
6125 */
6126 if (!((len > 2) && (*(p - 2) == ':')))
6127#endif
6128 {
6129 if (vim_ispathsep(*p))
6130 ++p;
6131#ifndef VMS /* the path separator is always part of the path */
6132 else
6133 p = NULL;
6134#endif
6135 }
6136 }
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006137#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006138 /*
6139 * When using a file in the current drive, remove the drive name:
6140 * "A:\dir\file" -> "\dir\file". This helps when moving a session file on
6141 * a floppy from "A:\dir" to "B:\dir".
6142 */
6143 else if (len > 3
6144 && TOUPPER_LOC(full_path[0]) == TOUPPER_LOC(dir_name[0])
6145 && full_path[1] == ':'
6146 && vim_ispathsep(full_path[2]))
6147 p = full_path + 2;
6148#endif
6149 else
6150 p = NULL;
6151 return p;
6152}
6153
6154/*
6155 * Shorten filenames for all buffers.
6156 * When "force" is TRUE: Use full path from now on for files currently being
6157 * edited, both for file name and swap file name. Try to shorten the file
6158 * names a bit, if safe to do so.
6159 * When "force" is FALSE: Only try to shorten absolute file names.
6160 * For buffers that have buftype "nofile" or "scratch": never change the file
6161 * name.
6162 */
6163 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006164shorten_fnames(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006165{
6166 char_u dirname[MAXPATHL];
6167 buf_T *buf;
6168 char_u *p;
6169
6170 mch_dirname(dirname, MAXPATHL);
Bram Moolenaar29323592016-07-24 22:04:11 +02006171 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006172 {
6173 if (buf->b_fname != NULL
6174#ifdef FEAT_QUICKFIX
6175 && !bt_nofile(buf)
6176#endif
6177 && !path_with_url(buf->b_fname)
6178 && (force
6179 || buf->b_sfname == NULL
6180 || mch_isFullName(buf->b_sfname)))
6181 {
6182 vim_free(buf->b_sfname);
6183 buf->b_sfname = NULL;
6184 p = shorten_fname(buf->b_ffname, dirname);
6185 if (p != NULL)
6186 {
6187 buf->b_sfname = vim_strsave(p);
6188 buf->b_fname = buf->b_sfname;
6189 }
6190 if (p == NULL || buf->b_fname == NULL)
6191 buf->b_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006192 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00006193
6194 /* Always make the swap file name a full path, a "nofile" buffer may
6195 * also have a swap file. */
6196 mf_fullname(buf->b_ml.ml_mfp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006197 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006198 status_redraw_all();
Bram Moolenaar49d7bf12006-02-17 21:45:41 +00006199 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006200}
6201
6202#if (defined(FEAT_DND) && defined(FEAT_GUI_GTK)) \
6203 || defined(FEAT_GUI_MSWIN) \
6204 || defined(FEAT_GUI_MAC) \
6205 || defined(PROTO)
6206/*
6207 * Shorten all filenames in "fnames[count]" by current directory.
6208 */
6209 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006210shorten_filenames(char_u **fnames, int count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006211{
6212 int i;
6213 char_u dirname[MAXPATHL];
6214 char_u *p;
6215
6216 if (fnames == NULL || count < 1)
6217 return;
6218 mch_dirname(dirname, sizeof(dirname));
6219 for (i = 0; i < count; ++i)
6220 {
6221 if ((p = shorten_fname(fnames[i], dirname)) != NULL)
6222 {
6223 /* shorten_fname() returns pointer in given "fnames[i]". If free
6224 * "fnames[i]" first, "p" becomes invalid. So we need to copy
6225 * "p" first then free fnames[i]. */
6226 p = vim_strsave(p);
6227 vim_free(fnames[i]);
6228 fnames[i] = p;
6229 }
6230 }
6231}
6232#endif
6233
6234/*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006235 * add extension to file name - change path/fo.o.h to path/fo.o.h.ext or
Bram Moolenaar071d4272004-06-13 20:20:40 +00006236 * fo_o_h.ext for MSDOS or when shortname option set.
6237 *
6238 * Assumed that fname is a valid name found in the filesystem we assure that
6239 * the return value is a different name and ends in 'ext'.
6240 * "ext" MUST be at most 4 characters long if it starts with a dot, 3
6241 * characters otherwise.
6242 * Space for the returned name is allocated, must be freed later.
6243 * Returns NULL when out of memory.
6244 */
6245 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006246modname(
6247 char_u *fname,
6248 char_u *ext,
6249 int prepend_dot) /* may prepend a '.' to file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006250{
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006251 return buf_modname((curbuf->b_p_sn || curbuf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00006252 fname, ext, prepend_dot);
6253}
6254
6255 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006256buf_modname(
6257 int shortname, /* use 8.3 file name */
6258 char_u *fname,
6259 char_u *ext,
6260 int prepend_dot) /* may prepend a '.' to file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006261{
6262 char_u *retval;
6263 char_u *s;
6264 char_u *e;
6265 char_u *ptr;
6266 int fnamelen, extlen;
6267
6268 extlen = (int)STRLEN(ext);
6269
6270 /*
6271 * If there is no file name we must get the name of the current directory
6272 * (we need the full path in case :cd is used).
6273 */
6274 if (fname == NULL || *fname == NUL)
6275 {
6276 retval = alloc((unsigned)(MAXPATHL + extlen + 3));
6277 if (retval == NULL)
6278 return NULL;
6279 if (mch_dirname(retval, MAXPATHL) == FAIL ||
6280 (fnamelen = (int)STRLEN(retval)) == 0)
6281 {
6282 vim_free(retval);
6283 return NULL;
6284 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006285 if (!after_pathsep(retval, retval + fnamelen))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006286 {
6287 retval[fnamelen++] = PATHSEP;
6288 retval[fnamelen] = NUL;
6289 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006290 prepend_dot = FALSE; /* nothing to prepend a dot to */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006291 }
6292 else
6293 {
6294 fnamelen = (int)STRLEN(fname);
6295 retval = alloc((unsigned)(fnamelen + extlen + 3));
6296 if (retval == NULL)
6297 return NULL;
6298 STRCPY(retval, fname);
6299#ifdef VMS
6300 vms_remove_version(retval); /* we do not need versions here */
6301#endif
6302 }
6303
6304 /*
6305 * search backwards until we hit a '/', '\' or ':' replacing all '.'
6306 * by '_' for MSDOS or when shortname option set and ext starts with a dot.
6307 * Then truncate what is after the '/', '\' or ':' to 8 characters for
6308 * MSDOS and 26 characters for AMIGA, a lot more for UNIX.
6309 */
Bram Moolenaar91acfff2017-03-12 19:22:36 +01006310 for (ptr = retval + fnamelen; ptr > retval; MB_PTR_BACK(retval, ptr))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006311 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006312 if (*ext == '.'
Bram Moolenaare60acc12011-05-10 16:41:25 +02006313#ifdef USE_LONG_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00006314 && (!USE_LONG_FNAME || shortname)
Bram Moolenaare60acc12011-05-10 16:41:25 +02006315#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006316 && shortname
Bram Moolenaare60acc12011-05-10 16:41:25 +02006317#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006318 )
6319 if (*ptr == '.') /* replace '.' by '_' */
6320 *ptr = '_';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006321 if (vim_ispathsep(*ptr))
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006322 {
6323 ++ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006324 break;
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006325 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006326 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006327
6328 /* the file name has at most BASENAMELEN characters. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006329 if (STRLEN(ptr) > (unsigned)BASENAMELEN)
6330 ptr[BASENAMELEN] = '\0';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006331
6332 s = ptr + STRLEN(ptr);
6333
6334 /*
6335 * For 8.3 file names we may have to reduce the length.
6336 */
6337#ifdef USE_LONG_FNAME
6338 if (!USE_LONG_FNAME || shortname)
6339#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006340 if (shortname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006341#endif
6342 {
6343 /*
6344 * If there is no file name, or the file name ends in '/', and the
6345 * extension starts with '.', put a '_' before the dot, because just
6346 * ".ext" is invalid.
6347 */
6348 if (fname == NULL || *fname == NUL
6349 || vim_ispathsep(fname[STRLEN(fname) - 1]))
6350 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006351 if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006352 *s++ = '_';
6353 }
6354 /*
6355 * If the extension starts with '.', truncate the base name at 8
6356 * characters
6357 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006358 else if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006359 {
Bram Moolenaar78a15312009-05-15 19:33:18 +00006360 if ((size_t)(s - ptr) > (size_t)8)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006361 {
6362 s = ptr + 8;
6363 *s = '\0';
6364 }
6365 }
6366 /*
6367 * If the extension doesn't start with '.', and the file name
6368 * doesn't have an extension yet, append a '.'
6369 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006370 else if ((e = vim_strchr(ptr, '.')) == NULL)
6371 *s++ = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006372 /*
6373 * If the extension doesn't start with '.', and there already is an
Bram Moolenaar7263a772007-05-10 17:35:54 +00006374 * extension, it may need to be truncated
Bram Moolenaar071d4272004-06-13 20:20:40 +00006375 */
6376 else if ((int)STRLEN(e) + extlen > 4)
6377 s = e + 4 - extlen;
6378 }
Bram Moolenaare7fedb62015-12-31 19:07:19 +01006379#if defined(USE_LONG_FNAME) || defined(WIN3264)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006380 /*
6381 * If there is no file name, and the extension starts with '.', put a
6382 * '_' before the dot, because just ".ext" may be invalid if it's on a
6383 * FAT partition, and on HPFS it doesn't matter.
6384 */
6385 else if ((fname == NULL || *fname == NUL) && *ext == '.')
6386 *s++ = '_';
6387#endif
6388
6389 /*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006390 * Append the extension.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006391 * ext can start with '.' and cannot exceed 3 more characters.
6392 */
6393 STRCPY(s, ext);
6394
Bram Moolenaar071d4272004-06-13 20:20:40 +00006395 /*
6396 * Prepend the dot.
6397 */
Bram Moolenaare60acc12011-05-10 16:41:25 +02006398 if (prepend_dot && !shortname && *(e = gettail(retval)) != '.'
Bram Moolenaar071d4272004-06-13 20:20:40 +00006399#ifdef USE_LONG_FNAME
6400 && USE_LONG_FNAME
6401#endif
6402 )
6403 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006404 STRMOVE(e + 1, e);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006405 *e = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006406 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006407
6408 /*
6409 * Check that, after appending the extension, the file name is really
6410 * different.
6411 */
6412 if (fname != NULL && STRCMP(fname, retval) == 0)
6413 {
6414 /* we search for a character that can be replaced by '_' */
6415 while (--s >= ptr)
6416 {
6417 if (*s != '_')
6418 {
6419 *s = '_';
6420 break;
6421 }
6422 }
6423 if (s < ptr) /* fname was "________.<ext>", how tricky! */
6424 *ptr = 'v';
6425 }
6426 return retval;
6427}
6428
6429/*
6430 * Like fgets(), but if the file line is too long, it is truncated and the
6431 * rest of the line is thrown away. Returns TRUE for end-of-file.
6432 */
6433 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006434vim_fgets(char_u *buf, int size, FILE *fp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006435{
6436 char *eof;
6437#define FGETS_SIZE 200
6438 char tbuf[FGETS_SIZE];
6439
6440 buf[size - 2] = NUL;
6441#ifdef USE_CR
6442 eof = fgets_cr((char *)buf, size, fp);
6443#else
6444 eof = fgets((char *)buf, size, fp);
6445#endif
6446 if (buf[size - 2] != NUL && buf[size - 2] != '\n')
6447 {
6448 buf[size - 1] = NUL; /* Truncate the line */
6449
6450 /* Now throw away the rest of the line: */
6451 do
6452 {
6453 tbuf[FGETS_SIZE - 2] = NUL;
6454#ifdef USE_CR
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006455 ignoredp = fgets_cr((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006456#else
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006457 ignoredp = fgets((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006458#endif
6459 } while (tbuf[FGETS_SIZE - 2] != NUL && tbuf[FGETS_SIZE - 2] != '\n');
6460 }
6461 return (eof == NULL);
6462}
6463
6464#if defined(USE_CR) || defined(PROTO)
6465/*
6466 * Like vim_fgets(), but accept any line terminator: CR, CR-LF or LF.
6467 * Returns TRUE for end-of-file.
6468 * Only used for the Mac, because it's much slower than vim_fgets().
6469 */
6470 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006471tag_fgets(char_u *buf, int size, FILE *fp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006472{
6473 int i = 0;
6474 int c;
6475 int eof = FALSE;
6476
6477 for (;;)
6478 {
6479 c = fgetc(fp);
6480 if (c == EOF)
6481 {
6482 eof = TRUE;
6483 break;
6484 }
6485 if (c == '\r')
6486 {
6487 /* Always store a NL for end-of-line. */
6488 if (i < size - 1)
6489 buf[i++] = '\n';
6490 c = fgetc(fp);
6491 if (c != '\n') /* Macintosh format: single CR. */
6492 ungetc(c, fp);
6493 break;
6494 }
6495 if (i < size - 1)
6496 buf[i++] = c;
6497 if (c == '\n')
6498 break;
6499 }
6500 buf[i] = NUL;
6501 return eof;
6502}
6503#endif
6504
6505/*
6506 * rename() only works if both files are on the same file system, this
6507 * function will (attempts to?) copy the file across if rename fails -- webb
6508 * Return -1 for failure, 0 for success.
6509 */
6510 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006511vim_rename(char_u *from, char_u *to)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006512{
6513 int fd_in;
6514 int fd_out;
6515 int n;
6516 char *errmsg = NULL;
6517 char *buffer;
6518#ifdef AMIGA
6519 BPTR flock;
6520#endif
Bram Moolenaar8767f522016-07-01 17:17:39 +02006521 stat_T st;
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006522 long perm;
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006523#ifdef HAVE_ACL
6524 vim_acl_T acl; /* ACL from original file */
6525#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006526 int use_tmp_file = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006527
6528 /*
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006529 * When the names are identical, there is nothing to do. When they refer
6530 * to the same file (ignoring case and slash/backslash differences) but
6531 * the file name differs we need to go through a temp file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006532 */
6533 if (fnamecmp(from, to) == 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006534 {
Bram Moolenaar71afbfe2013-03-19 16:49:16 +01006535 if (p_fic && STRCMP(gettail(from), gettail(to)) != 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006536 use_tmp_file = TRUE;
6537 else
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006538 return 0;
6539 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006540
6541 /*
6542 * Fail if the "from" file doesn't exist. Avoids that "to" is deleted.
6543 */
6544 if (mch_stat((char *)from, &st) < 0)
6545 return -1;
6546
Bram Moolenaar3576da72008-12-30 15:15:57 +00006547#ifdef UNIX
6548 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02006549 stat_T st_to;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006550
6551 /* It's possible for the source and destination to be the same file.
6552 * This happens when "from" and "to" differ in case and are on a FAT32
6553 * filesystem. In that case go through a temp file name. */
6554 if (mch_stat((char *)to, &st_to) >= 0
6555 && st.st_dev == st_to.st_dev
6556 && st.st_ino == st_to.st_ino)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006557 use_tmp_file = TRUE;
6558 }
6559#endif
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02006560#ifdef WIN3264
6561 {
6562 BY_HANDLE_FILE_INFORMATION info1, info2;
6563
6564 /* It's possible for the source and destination to be the same file.
6565 * In that case go through a temp file name. This makes rename("foo",
6566 * "./foo") a no-op (in a complicated way). */
6567 if (win32_fileinfo(from, &info1) == FILEINFO_OK
6568 && win32_fileinfo(to, &info2) == FILEINFO_OK
6569 && info1.dwVolumeSerialNumber == info2.dwVolumeSerialNumber
6570 && info1.nFileIndexHigh == info2.nFileIndexHigh
6571 && info1.nFileIndexLow == info2.nFileIndexLow)
6572 use_tmp_file = TRUE;
6573 }
6574#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006575
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006576 if (use_tmp_file)
6577 {
6578 char tempname[MAXPATHL + 1];
6579
6580 /*
6581 * Find a name that doesn't exist and is in the same directory.
6582 * Rename "from" to "tempname" and then rename "tempname" to "to".
6583 */
6584 if (STRLEN(from) >= MAXPATHL - 5)
6585 return -1;
6586 STRCPY(tempname, from);
6587 for (n = 123; n < 99999; ++n)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006588 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006589 sprintf((char *)gettail((char_u *)tempname), "%d", n);
6590 if (mch_stat(tempname, &st) < 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006591 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006592 if (mch_rename((char *)from, tempname) == 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006593 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006594 if (mch_rename(tempname, (char *)to) == 0)
6595 return 0;
6596 /* Strange, the second step failed. Try moving the
6597 * file back and return failure. */
6598 mch_rename(tempname, (char *)from);
Bram Moolenaar3576da72008-12-30 15:15:57 +00006599 return -1;
6600 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006601 /* If it fails for one temp name it will most likely fail
6602 * for any temp name, give up. */
6603 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006604 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006605 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006606 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006607 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006608
Bram Moolenaar071d4272004-06-13 20:20:40 +00006609 /*
6610 * Delete the "to" file, this is required on some systems to make the
6611 * mch_rename() work, on other systems it makes sure that we don't have
6612 * two files when the mch_rename() fails.
6613 */
6614
6615#ifdef AMIGA
6616 /*
6617 * With MSDOS-compatible filesystems (crossdos, messydos) it is possible
6618 * that the name of the "to" file is the same as the "from" file, even
Bram Moolenaar7263a772007-05-10 17:35:54 +00006619 * though the names are different. To avoid the chance of accidentally
Bram Moolenaar071d4272004-06-13 20:20:40 +00006620 * deleting the "from" file (horror!) we lock it during the remove.
6621 *
6622 * When used for making a backup before writing the file: This should not
6623 * happen with ":w", because startscript() should detect this problem and
6624 * set buf->b_shortname, causing modname() to return a correct ".bak" file
6625 * name. This problem does exist with ":w filename", but then the
6626 * original file will be somewhere else so the backup isn't really
6627 * important. If autoscripting is off the rename may fail.
6628 */
6629 flock = Lock((UBYTE *)from, (long)ACCESS_READ);
6630#endif
6631 mch_remove(to);
6632#ifdef AMIGA
6633 if (flock)
6634 UnLock(flock);
6635#endif
6636
6637 /*
6638 * First try a normal rename, return if it works.
6639 */
6640 if (mch_rename((char *)from, (char *)to) == 0)
6641 return 0;
6642
6643 /*
6644 * Rename() failed, try copying the file.
6645 */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006646 perm = mch_getperm(from);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006647#ifdef HAVE_ACL
6648 /* For systems that support ACL: get the ACL from the original file. */
6649 acl = mch_get_acl(from);
6650#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006651 fd_in = mch_open((char *)from, O_RDONLY|O_EXTRA, 0);
6652 if (fd_in == -1)
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006653 {
6654#ifdef HAVE_ACL
6655 mch_free_acl(acl);
6656#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006657 return -1;
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006658 }
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006659
6660 /* Create the new file with same permissions as the original. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00006661 fd_out = mch_open((char *)to,
6662 O_CREAT|O_EXCL|O_WRONLY|O_EXTRA|O_NOFOLLOW, (int)perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006663 if (fd_out == -1)
6664 {
6665 close(fd_in);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006666#ifdef HAVE_ACL
6667 mch_free_acl(acl);
6668#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006669 return -1;
6670 }
6671
6672 buffer = (char *)alloc(BUFSIZE);
6673 if (buffer == NULL)
6674 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006675 close(fd_out);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006676 close(fd_in);
6677#ifdef HAVE_ACL
6678 mch_free_acl(acl);
6679#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006680 return -1;
6681 }
6682
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01006683 while ((n = read_eintr(fd_in, buffer, BUFSIZE)) > 0)
6684 if (write_eintr(fd_out, buffer, n) != n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006685 {
6686 errmsg = _("E208: Error writing to \"%s\"");
6687 break;
6688 }
6689
6690 vim_free(buffer);
6691 close(fd_in);
6692 if (close(fd_out) < 0)
6693 errmsg = _("E209: Error closing \"%s\"");
6694 if (n < 0)
6695 {
6696 errmsg = _("E210: Error reading \"%s\"");
6697 to = from;
6698 }
Bram Moolenaar7263a772007-05-10 17:35:54 +00006699#ifndef UNIX /* for Unix mch_open() already set the permission */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006700 mch_setperm(to, perm);
Bram Moolenaarc6039d82005-12-02 00:44:04 +00006701#endif
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006702#ifdef HAVE_ACL
6703 mch_set_acl(to, acl);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006704 mch_free_acl(acl);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006705#endif
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02006706#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaare8747442013-11-12 18:09:29 +01006707 mch_copy_sec(from, to);
Bram Moolenaar0671de32013-11-12 05:12:03 +01006708#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006709 if (errmsg != NULL)
6710 {
6711 EMSG2(errmsg, to);
6712 return -1;
6713 }
6714 mch_remove(from);
6715 return 0;
6716}
6717
6718static int already_warned = FALSE;
6719
6720/*
6721 * Check if any not hidden buffer has been changed.
6722 * Postpone the check if there are characters in the stuff buffer, a global
6723 * command is being executed, a mapping is being executed or an autocommand is
6724 * busy.
6725 * Returns TRUE if some message was written (screen should be redrawn and
6726 * cursor positioned).
6727 */
6728 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006729check_timestamps(
6730 int focus) /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006731{
6732 buf_T *buf;
6733 int didit = 0;
6734 int n;
6735
6736 /* Don't check timestamps while system() or another low-level function may
6737 * cause us to lose and gain focus. */
6738 if (no_check_timestamps > 0)
6739 return FALSE;
6740
6741 /* Avoid doing a check twice. The OK/Reload dialog can cause a focus
6742 * event and we would keep on checking if the file is steadily growing.
6743 * Do check again after typing something. */
6744 if (focus && did_check_timestamps)
6745 {
6746 need_check_timestamps = TRUE;
6747 return FALSE;
6748 }
6749
6750 if (!stuff_empty() || global_busy || !typebuf_typed()
6751#ifdef FEAT_AUTOCMD
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006752 || autocmd_busy || curbuf_lock > 0 || allbuf_lock > 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00006753#endif
6754 )
6755 need_check_timestamps = TRUE; /* check later */
6756 else
6757 {
6758 ++no_wait_return;
6759 did_check_timestamps = TRUE;
6760 already_warned = FALSE;
Bram Moolenaar29323592016-07-24 22:04:11 +02006761 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006762 {
6763 /* Only check buffers in a window. */
6764 if (buf->b_nwindows > 0)
6765 {
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006766 bufref_T bufref;
6767
6768 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006769 n = buf_check_timestamp(buf, focus);
6770 if (didit < n)
6771 didit = n;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006772 if (n > 0 && !bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006773 {
6774 /* Autocommands have removed the buffer, start at the
6775 * first one again. */
6776 buf = firstbuf;
6777 continue;
6778 }
6779 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006780 }
6781 --no_wait_return;
6782 need_check_timestamps = FALSE;
6783 if (need_wait_return && didit == 2)
6784 {
6785 /* make sure msg isn't overwritten */
6786 msg_puts((char_u *)"\n");
6787 out_flush();
6788 }
6789 }
6790 return didit;
6791}
6792
6793/*
6794 * Move all the lines from buffer "frombuf" to buffer "tobuf".
6795 * Return OK or FAIL. When FAIL "tobuf" is incomplete and/or "frombuf" is not
6796 * empty.
6797 */
6798 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006799move_lines(buf_T *frombuf, buf_T *tobuf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006800{
6801 buf_T *tbuf = curbuf;
6802 int retval = OK;
6803 linenr_T lnum;
6804 char_u *p;
6805
6806 /* Copy the lines in "frombuf" to "tobuf". */
6807 curbuf = tobuf;
6808 for (lnum = 1; lnum <= frombuf->b_ml.ml_line_count; ++lnum)
6809 {
6810 p = vim_strsave(ml_get_buf(frombuf, lnum, FALSE));
6811 if (p == NULL || ml_append(lnum - 1, p, 0, FALSE) == FAIL)
6812 {
6813 vim_free(p);
6814 retval = FAIL;
6815 break;
6816 }
6817 vim_free(p);
6818 }
6819
6820 /* Delete all the lines in "frombuf". */
6821 if (retval != FAIL)
6822 {
6823 curbuf = frombuf;
Bram Moolenaar9460b9d2007-01-09 14:37:01 +00006824 for (lnum = curbuf->b_ml.ml_line_count; lnum > 0; --lnum)
6825 if (ml_delete(lnum, FALSE) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006826 {
6827 /* Oops! We could try putting back the saved lines, but that
6828 * might fail again... */
6829 retval = FAIL;
6830 break;
6831 }
6832 }
6833
6834 curbuf = tbuf;
6835 return retval;
6836}
6837
6838/*
6839 * Check if buffer "buf" has been changed.
6840 * Also check if the file for a new buffer unexpectedly appeared.
6841 * return 1 if a changed buffer was found.
6842 * return 2 if a message has been displayed.
6843 * return 0 otherwise.
6844 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006845 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006846buf_check_timestamp(
6847 buf_T *buf,
6848 int focus UNUSED) /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006849{
Bram Moolenaar8767f522016-07-01 17:17:39 +02006850 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006851 int stat_res;
6852 int retval = 0;
6853 char_u *path;
6854 char_u *tbuf;
6855 char *mesg = NULL;
Bram Moolenaar44ecf652005-03-07 23:09:59 +00006856 char *mesg2 = "";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006857 int helpmesg = FALSE;
6858 int reload = FALSE;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006859 char *reason;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006860#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6861 int can_reload = FALSE;
6862#endif
Bram Moolenaar8767f522016-07-01 17:17:39 +02006863 off_T orig_size = buf->b_orig_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006864 int orig_mode = buf->b_orig_mode;
6865#ifdef FEAT_GUI
6866 int save_mouse_correct = need_mouse_correct;
6867#endif
6868#ifdef FEAT_AUTOCMD
6869 static int busy = FALSE;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006870 int n;
6871 char_u *s;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006872 bufref_T bufref;
6873
6874 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006875#endif
6876
6877 /* If there is no file name, the buffer is not loaded, 'buftype' is
6878 * set, we are in the middle of a save or being called recursively: ignore
6879 * this buffer. */
6880 if (buf->b_ffname == NULL
6881 || buf->b_ml.ml_mfp == NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00006882 || *buf->b_p_bt != NUL
Bram Moolenaar071d4272004-06-13 20:20:40 +00006883 || buf->b_saving
6884#ifdef FEAT_AUTOCMD
6885 || busy
6886#endif
Bram Moolenaar009b2592004-10-24 19:18:58 +00006887#ifdef FEAT_NETBEANS_INTG
6888 || isNetbeansBuffer(buf)
6889#endif
Bram Moolenaar8cad9302017-08-12 14:32:32 +02006890#ifdef FEAT_TERMINAL
6891 || buf->b_term != NULL
6892#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006893 )
6894 return 0;
6895
6896 if ( !(buf->b_flags & BF_NOTEDITED)
6897 && buf->b_mtime != 0
6898 && ((stat_res = mch_stat((char *)buf->b_ffname, &st)) < 0
6899 || time_differs((long)st.st_mtime, buf->b_mtime)
Bram Moolenaara7611f62014-05-02 15:46:14 +02006900 || st.st_size != buf->b_orig_size
Bram Moolenaar071d4272004-06-13 20:20:40 +00006901#ifdef HAVE_ST_MODE
6902 || (int)st.st_mode != buf->b_orig_mode
6903#else
6904 || mch_getperm(buf->b_ffname) != buf->b_orig_mode
6905#endif
6906 ))
6907 {
6908 retval = 1;
6909
Bram Moolenaar316059c2006-01-14 21:18:42 +00006910 /* set b_mtime to stop further warnings (e.g., when executing
6911 * FileChangedShell autocmd) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006912 if (stat_res < 0)
6913 {
6914 buf->b_mtime = 0;
6915 buf->b_orig_size = 0;
6916 buf->b_orig_mode = 0;
6917 }
6918 else
6919 buf_store_time(buf, &st, buf->b_ffname);
6920
6921 /* Don't do anything for a directory. Might contain the file
6922 * explorer. */
6923 if (mch_isdir(buf->b_fname))
6924 ;
6925
6926 /*
6927 * If 'autoread' is set, the buffer has no changes and the file still
6928 * exists, reload the buffer. Use the buffer-local option value if it
6929 * was set, the global option value otherwise.
6930 */
6931 else if ((buf->b_p_ar >= 0 ? buf->b_p_ar : p_ar)
6932 && !bufIsChanged(buf) && stat_res >= 0)
6933 reload = TRUE;
6934 else
6935 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006936 if (stat_res < 0)
6937 reason = "deleted";
6938 else if (bufIsChanged(buf))
6939 reason = "conflict";
6940 else if (orig_size != buf->b_orig_size || buf_contents_changed(buf))
6941 reason = "changed";
6942 else if (orig_mode != buf->b_orig_mode)
6943 reason = "mode";
6944 else
6945 reason = "time";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006946
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006947#ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006948 /*
6949 * Only give the warning if there are no FileChangedShell
6950 * autocommands.
6951 * Avoid being called recursively by setting "busy".
6952 */
6953 busy = TRUE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00006954# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006955 set_vim_var_string(VV_FCS_REASON, (char_u *)reason, -1);
6956 set_vim_var_string(VV_FCS_CHOICE, (char_u *)"", -1);
Bram Moolenaar1e015462005-09-25 22:16:38 +00006957# endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006958 ++allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006959 n = apply_autocmds(EVENT_FILECHANGEDSHELL,
6960 buf->b_fname, buf->b_fname, FALSE, buf);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006961 --allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006962 busy = FALSE;
6963 if (n)
6964 {
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006965 if (!bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006966 EMSG(_("E246: FileChangedShell autocommand deleted buffer"));
Bram Moolenaar1e015462005-09-25 22:16:38 +00006967# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006968 s = get_vim_var_str(VV_FCS_CHOICE);
6969 if (STRCMP(s, "reload") == 0 && *reason != 'd')
6970 reload = TRUE;
6971 else if (STRCMP(s, "ask") == 0)
6972 n = FALSE;
6973 else
Bram Moolenaar1e015462005-09-25 22:16:38 +00006974# endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006975 return 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006976 }
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006977 if (!n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006978#endif
6979 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006980 if (*reason == 'd')
6981 mesg = _("E211: File \"%s\" no longer available");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006982 else
6983 {
6984 helpmesg = TRUE;
6985#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6986 can_reload = TRUE;
6987#endif
6988 /*
6989 * Check if the file contents really changed to avoid
6990 * giving a warning when only the timestamp was set (e.g.,
6991 * checked out of CVS). Always warn when the buffer was
6992 * changed.
6993 */
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006994 if (reason[2] == 'n')
6995 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006996 mesg = _("W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006997 mesg2 = _("See \":help W12\" for more info.");
6998 }
6999 else if (reason[1] == 'h')
7000 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007001 mesg = _("W11: Warning: File \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007002 mesg2 = _("See \":help W11\" for more info.");
7003 }
7004 else if (*reason == 'm')
7005 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007006 mesg = _("W16: Warning: Mode of file \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007007 mesg2 = _("See \":help W16\" for more info.");
7008 }
Bram Moolenaar85388b52009-06-24 09:58:32 +00007009 else
7010 /* Only timestamp changed, store it to avoid a warning
7011 * in check_mtime() later. */
7012 buf->b_mtime_read = buf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007013 }
7014 }
7015 }
7016
7017 }
7018 else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W)
7019 && vim_fexists(buf->b_ffname))
7020 {
7021 retval = 1;
7022 mesg = _("W13: Warning: File \"%s\" has been created after editing started");
7023 buf->b_flags |= BF_NEW_W;
7024#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
7025 can_reload = TRUE;
7026#endif
7027 }
7028
7029 if (mesg != NULL)
7030 {
7031 path = home_replace_save(buf, buf->b_fname);
7032 if (path != NULL)
7033 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007034 if (!helpmesg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007035 mesg2 = "";
7036 tbuf = alloc((unsigned)(STRLEN(path) + STRLEN(mesg)
7037 + STRLEN(mesg2) + 2));
7038 sprintf((char *)tbuf, mesg, path);
Bram Moolenaar496c5262009-03-18 14:42:00 +00007039#ifdef FEAT_EVAL
7040 /* Set warningmsg here, before the unimportant and output-specific
7041 * mesg2 has been appended. */
7042 set_vim_var_string(VV_WARNINGMSG, tbuf, -1);
7043#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007044#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
7045 if (can_reload)
7046 {
7047 if (*mesg2 != NUL)
7048 {
7049 STRCAT(tbuf, "\n");
7050 STRCAT(tbuf, mesg2);
7051 }
7052 if (do_dialog(VIM_WARNING, (char_u *)_("Warning"), tbuf,
Bram Moolenaard2c340a2011-01-17 20:08:11 +01007053 (char_u *)_("&OK\n&Load File"), 1, NULL, TRUE) == 2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007054 reload = TRUE;
7055 }
7056 else
7057#endif
7058 if (State > NORMAL_BUSY || (State & CMDLINE) || already_warned)
7059 {
7060 if (*mesg2 != NUL)
7061 {
7062 STRCAT(tbuf, "; ");
7063 STRCAT(tbuf, mesg2);
7064 }
7065 EMSG(tbuf);
7066 retval = 2;
7067 }
7068 else
7069 {
Bram Moolenaared203462004-06-16 11:19:22 +00007070# ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00007071 if (!autocmd_busy)
Bram Moolenaared203462004-06-16 11:19:22 +00007072# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007073 {
7074 msg_start();
Bram Moolenaar8820b482017-03-16 17:23:31 +01007075 msg_puts_attr(tbuf, HL_ATTR(HLF_E) + MSG_HIST);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007076 if (*mesg2 != NUL)
7077 msg_puts_attr((char_u *)mesg2,
Bram Moolenaar8820b482017-03-16 17:23:31 +01007078 HL_ATTR(HLF_W) + MSG_HIST);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007079 msg_clr_eos();
7080 (void)msg_end();
7081 if (emsg_silent == 0)
7082 {
7083 out_flush();
Bram Moolenaared203462004-06-16 11:19:22 +00007084# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00007085 if (!focus)
Bram Moolenaared203462004-06-16 11:19:22 +00007086# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007087 /* give the user some time to think about it */
7088 ui_delay(1000L, TRUE);
7089
7090 /* don't redraw and erase the message */
7091 redraw_cmdline = FALSE;
7092 }
7093 }
7094 already_warned = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007095 }
7096
7097 vim_free(path);
7098 vim_free(tbuf);
7099 }
7100 }
7101
7102 if (reload)
Bram Moolenaar465748e2012-08-29 18:50:54 +02007103 {
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007104 /* Reload the buffer. */
Bram Moolenaar316059c2006-01-14 21:18:42 +00007105 buf_reload(buf, orig_mode);
Bram Moolenaar465748e2012-08-29 18:50:54 +02007106#ifdef FEAT_PERSISTENT_UNDO
7107 if (buf->b_p_udf && buf->b_ffname != NULL)
7108 {
7109 char_u hash[UNDO_HASH_SIZE];
7110 buf_T *save_curbuf = curbuf;
7111
7112 /* Any existing undo file is unusable, write it now. */
7113 curbuf = buf;
7114 u_compute_hash(hash);
7115 u_write_undo(NULL, FALSE, buf, hash);
7116 curbuf = save_curbuf;
7117 }
7118#endif
7119 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007120
Bram Moolenaar56718732006-03-15 22:53:57 +00007121#ifdef FEAT_AUTOCMD
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00007122 /* Trigger FileChangedShell when the file was changed in any way. */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007123 if (bufref_valid(&bufref) && retval != 0)
Bram Moolenaar56718732006-03-15 22:53:57 +00007124 (void)apply_autocmds(EVENT_FILECHANGEDSHELLPOST,
7125 buf->b_fname, buf->b_fname, FALSE, buf);
7126#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007127#ifdef FEAT_GUI
7128 /* restore this in case an autocommand has set it; it would break
7129 * 'mousefocus' */
7130 need_mouse_correct = save_mouse_correct;
7131#endif
7132
7133 return retval;
7134}
7135
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007136/*
7137 * Reload a buffer that is already loaded.
7138 * Used when the file was changed outside of Vim.
Bram Moolenaar316059c2006-01-14 21:18:42 +00007139 * "orig_mode" is buf->b_orig_mode before the need for reloading was detected.
7140 * buf->b_orig_mode may have been reset already.
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007141 */
7142 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007143buf_reload(buf_T *buf, int orig_mode)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007144{
7145 exarg_T ea;
7146 pos_T old_cursor;
7147 linenr_T old_topline;
7148 int old_ro = buf->b_p_ro;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007149 buf_T *savebuf;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007150 bufref_T bufref;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007151 int saved = OK;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007152 aco_save_T aco;
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007153 int flags = READ_NEW;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007154
7155 /* set curwin/curbuf for "buf" and save some things */
7156 aucmd_prepbuf(&aco, buf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007157
7158 /* We only want to read the text from the file, not reset the syntax
7159 * highlighting, clear marks, diff status, etc. Force the fileformat
7160 * and encoding to be the same. */
7161 if (prep_exarg(&ea, buf) == OK)
7162 {
7163 old_cursor = curwin->w_cursor;
7164 old_topline = curwin->w_topline;
7165
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007166 if (p_ur < 0 || curbuf->b_ml.ml_line_count <= p_ur)
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007167 {
7168 /* Save all the text, so that the reload can be undone.
7169 * Sync first so that this is a separate undo-able action. */
7170 u_sync(FALSE);
7171 saved = u_savecommon(0, curbuf->b_ml.ml_line_count + 1, 0, TRUE);
7172 flags |= READ_KEEP_UNDO;
7173 }
7174
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007175 /*
7176 * To behave like when a new file is edited (matters for
7177 * BufReadPost autocommands) we first need to delete the current
7178 * buffer contents. But if reading the file fails we should keep
7179 * the old contents. Can't use memory only, the file might be
7180 * too big. Use a hidden buffer to move the buffer contents to.
7181 */
Bram Moolenaarb5aedf32017-03-12 18:23:53 +01007182 if (BUFEMPTY() || saved == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007183 savebuf = NULL;
7184 else
7185 {
7186 /* Allocate a buffer without putting it in the buffer list. */
7187 savebuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007188 set_bufref(&bufref, savebuf);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007189 if (savebuf != NULL && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007190 {
7191 /* Open the memline. */
7192 curbuf = savebuf;
7193 curwin->w_buffer = savebuf;
Bram Moolenaar4770d092006-01-12 23:22:24 +00007194 saved = ml_open(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007195 curbuf = buf;
7196 curwin->w_buffer = buf;
7197 }
Bram Moolenaar8424a622006-04-19 21:23:36 +00007198 if (savebuf == NULL || saved == FAIL || buf != curbuf
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007199 || move_lines(buf, savebuf) == FAIL)
7200 {
7201 EMSG2(_("E462: Could not prepare for reloading \"%s\""),
7202 buf->b_fname);
7203 saved = FAIL;
7204 }
7205 }
7206
7207 if (saved == OK)
7208 {
7209 curbuf->b_flags |= BF_CHECK_RO; /* check for RO again */
7210#ifdef FEAT_AUTOCMD
7211 keep_filetype = TRUE; /* don't detect 'filetype' */
7212#endif
7213 if (readfile(buf->b_ffname, buf->b_fname, (linenr_T)0,
7214 (linenr_T)0,
Bram Moolenaare13b9af2017-01-13 22:01:02 +01007215 (linenr_T)MAXLNUM, &ea, flags) != OK)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007216 {
7217#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
7218 if (!aborting())
7219#endif
7220 EMSG2(_("E321: Could not reload \"%s\""), buf->b_fname);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007221 if (savebuf != NULL && bufref_valid(&bufref) && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007222 {
7223 /* Put the text back from the save buffer. First
7224 * delete any lines that readfile() added. */
Bram Moolenaarb5aedf32017-03-12 18:23:53 +01007225 while (!BUFEMPTY())
Bram Moolenaar8424a622006-04-19 21:23:36 +00007226 if (ml_delete(buf->b_ml.ml_line_count, FALSE) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007227 break;
7228 (void)move_lines(savebuf, buf);
7229 }
7230 }
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007231 else if (buf == curbuf) /* "buf" still valid */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007232 {
7233 /* Mark the buffer as unmodified and free undo info. */
7234 unchanged(buf, TRUE);
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007235 if ((flags & READ_KEEP_UNDO) == 0)
7236 {
7237 u_blockfree(buf);
7238 u_clearall(buf);
7239 }
7240 else
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007241 {
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007242 /* Mark all undo states as changed. */
7243 u_unchanged(curbuf);
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007244 }
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007245 }
7246 }
7247 vim_free(ea.cmd);
7248
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007249 if (savebuf != NULL && bufref_valid(&bufref))
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007250 wipe_buffer(savebuf, FALSE);
7251
7252#ifdef FEAT_DIFF
7253 /* Invalidate diff info if necessary. */
Bram Moolenaar8424a622006-04-19 21:23:36 +00007254 diff_invalidate(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007255#endif
7256
7257 /* Restore the topline and cursor position and check it (lines may
7258 * have been removed). */
7259 if (old_topline > curbuf->b_ml.ml_line_count)
7260 curwin->w_topline = curbuf->b_ml.ml_line_count;
7261 else
7262 curwin->w_topline = old_topline;
7263 curwin->w_cursor = old_cursor;
7264 check_cursor();
7265 update_topline();
7266#ifdef FEAT_AUTOCMD
7267 keep_filetype = FALSE;
7268#endif
7269#ifdef FEAT_FOLDING
7270 {
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007271 win_T *wp;
7272 tabpage_T *tp;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007273
7274 /* Update folds unless they are defined manually. */
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007275 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007276 if (wp->w_buffer == curwin->w_buffer
7277 && !foldmethodIsManual(wp))
7278 foldUpdateAll(wp);
7279 }
7280#endif
7281 /* If the mode didn't change and 'readonly' was set, keep the old
7282 * value; the user probably used the ":view" command. But don't
7283 * reset it, might have had a read error. */
7284 if (orig_mode == curbuf->b_orig_mode)
7285 curbuf->b_p_ro |= old_ro;
Bram Moolenaar52f85b72013-01-30 14:13:56 +01007286
7287 /* Modelines must override settings done by autocommands. */
7288 do_modelines(0);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007289 }
7290
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007291 /* restore curwin/curbuf and a few other things */
7292 aucmd_restbuf(&aco);
7293 /* Careful: autocommands may have made "buf" invalid! */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007294}
7295
Bram Moolenaar071d4272004-06-13 20:20:40 +00007296 void
Bram Moolenaar8767f522016-07-01 17:17:39 +02007297buf_store_time(buf_T *buf, stat_T *st, char_u *fname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007298{
7299 buf->b_mtime = (long)st->st_mtime;
Bram Moolenaar914703b2010-05-31 21:59:46 +02007300 buf->b_orig_size = st->st_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007301#ifdef HAVE_ST_MODE
7302 buf->b_orig_mode = (int)st->st_mode;
7303#else
7304 buf->b_orig_mode = mch_getperm(fname);
7305#endif
7306}
7307
7308/*
7309 * Adjust the line with missing eol, used for the next write.
7310 * Used for do_filter(), when the input lines for the filter are deleted.
7311 */
7312 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007313write_lnum_adjust(linenr_T offset)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007314{
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01007315 if (curbuf->b_no_eol_lnum != 0) /* only if there is a missing eol */
7316 curbuf->b_no_eol_lnum += offset;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007317}
7318
Bram Moolenaarda440d22016-01-16 21:27:23 +01007319#if defined(TEMPDIRNAMES) || defined(FEAT_EVAL) || defined(PROTO)
7320/*
7321 * Delete "name" and everything in it, recursively.
7322 * return 0 for succes, -1 if some file was not deleted.
7323 */
7324 int
7325delete_recursive(char_u *name)
7326{
7327 int result = 0;
7328 char_u **files;
7329 int file_count;
7330 int i;
7331 char_u *exp;
7332
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007333 /* A symbolic link to a directory itself is deleted, not the directory it
7334 * points to. */
7335 if (
Bram Moolenaar203258c2016-01-17 22:15:16 +01007336# if defined(UNIX) || defined(WIN32)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007337 mch_isrealdir(name)
Bram Moolenaar203258c2016-01-17 22:15:16 +01007338# else
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007339 mch_isdir(name)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007340# endif
7341 )
Bram Moolenaarda440d22016-01-16 21:27:23 +01007342 {
7343 vim_snprintf((char *)NameBuff, MAXPATHL, "%s/*", name);
7344 exp = vim_strsave(NameBuff);
7345 if (exp == NULL)
7346 return -1;
7347 if (gen_expand_wildcards(1, &exp, &file_count, &files,
Bram Moolenaar336bd622016-01-17 18:23:58 +01007348 EW_DIR|EW_FILE|EW_SILENT|EW_ALLLINKS|EW_DODOT|EW_EMPTYOK) == OK)
Bram Moolenaarda440d22016-01-16 21:27:23 +01007349 {
7350 for (i = 0; i < file_count; ++i)
7351 if (delete_recursive(files[i]) != 0)
7352 result = -1;
7353 FreeWild(file_count, files);
7354 }
7355 else
7356 result = -1;
7357 vim_free(exp);
7358 (void)mch_rmdir(name);
7359 }
7360 else
7361 result = mch_remove(name) == 0 ? 0 : -1;
7362
7363 return result;
7364}
7365#endif
7366
Bram Moolenaar071d4272004-06-13 20:20:40 +00007367#if defined(TEMPDIRNAMES) || defined(PROTO)
7368static long temp_count = 0; /* Temp filename counter. */
7369
7370/*
7371 * Delete the temp directory and all files it contains.
7372 */
7373 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007374vim_deltempdir(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007375{
Bram Moolenaar071d4272004-06-13 20:20:40 +00007376 if (vim_tempdir != NULL)
7377 {
Bram Moolenaarda440d22016-01-16 21:27:23 +01007378 /* remove the trailing path separator */
7379 gettail(vim_tempdir)[-1] = NUL;
7380 delete_recursive(vim_tempdir);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007381 vim_free(vim_tempdir);
7382 vim_tempdir = NULL;
7383 }
7384}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007385
7386/*
Bram Moolenaareaf03392009-11-17 11:08:52 +00007387 * Directory "tempdir" was created. Expand this name to a full path and put
7388 * it in "vim_tempdir". This avoids that using ":cd" would confuse us.
7389 * "tempdir" must be no longer than MAXPATHL.
7390 */
7391 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007392vim_settempdir(char_u *tempdir)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007393{
7394 char_u *buf;
7395
7396 buf = alloc((unsigned)MAXPATHL + 2);
7397 if (buf != NULL)
7398 {
7399 if (vim_FullName(tempdir, buf, MAXPATHL, FALSE) == FAIL)
7400 STRCPY(buf, tempdir);
Bram Moolenaara06ecab2016-07-16 14:47:36 +02007401 add_pathsep(buf);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007402 vim_tempdir = vim_strsave(buf);
7403 vim_free(buf);
7404 }
7405}
Bram Moolenaar4592dee2009-11-18 19:11:58 +00007406#endif
Bram Moolenaareaf03392009-11-17 11:08:52 +00007407
7408/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007409 * vim_tempname(): Return a unique name that can be used for a temp file.
7410 *
Bram Moolenaar76ae22f2016-06-13 20:00:29 +02007411 * The temp file is NOT guaranteed to be created. If "keep" is FALSE it is
7412 * guaranteed to NOT be created.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007413 *
7414 * The returned pointer is to allocated memory.
7415 * The returned pointer is NULL if no valid name was found.
7416 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007417 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007418vim_tempname(
7419 int extra_char UNUSED, /* char to use in the name instead of '?' */
7420 int keep UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007421{
7422#ifdef USE_TMPNAM
7423 char_u itmp[L_tmpnam]; /* use tmpnam() */
7424#else
7425 char_u itmp[TEMPNAMELEN];
7426#endif
7427
7428#ifdef TEMPDIRNAMES
7429 static char *(tempdirs[]) = {TEMPDIRNAMES};
7430 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007431# ifndef EEXIST
Bram Moolenaar8767f522016-07-01 17:17:39 +02007432 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007433# endif
7434
7435 /*
7436 * This will create a directory for private use by this instance of Vim.
7437 * This is done once, and the same directory is used for all temp files.
7438 * This method avoids security problems because of symlink attacks et al.
7439 * It's also a bit faster, because we only need to check for an existing
7440 * file when creating the directory and not for each temp file.
7441 */
7442 if (vim_tempdir == NULL)
7443 {
7444 /*
7445 * Try the entries in TEMPDIRNAMES to create the temp directory.
7446 */
Bram Moolenaar78a15312009-05-15 19:33:18 +00007447 for (i = 0; i < (int)(sizeof(tempdirs) / sizeof(char *)); ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007448 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007449# ifndef HAVE_MKDTEMP
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007450 size_t itmplen;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007451 long nr;
7452 long off;
7453# endif
7454
Bram Moolenaare1a61992015-12-03 21:02:27 +01007455 /* Expand $TMP, leave room for "/v1100000/999999999".
7456 * Skip the directory check if the expansion fails. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007457 expand_env((char_u *)tempdirs[i], itmp, TEMPNAMELEN - 20);
Bram Moolenaare1a61992015-12-03 21:02:27 +01007458 if (itmp[0] != '$' && mch_isdir(itmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007459 {
Bram Moolenaare1a61992015-12-03 21:02:27 +01007460 /* directory exists */
Bram Moolenaara06ecab2016-07-16 14:47:36 +02007461 add_pathsep(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007462
Bram Moolenaareaf03392009-11-17 11:08:52 +00007463# ifdef HAVE_MKDTEMP
Bram Moolenaar35d88f42016-06-04 14:52:00 +02007464 {
7465# if defined(UNIX) || defined(VMS)
7466 /* Make sure the umask doesn't remove the executable bit.
7467 * "repl" has been reported to use "177". */
7468 mode_t umask_save = umask(077);
7469# endif
7470 /* Leave room for filename */
7471 STRCAT(itmp, "vXXXXXX");
7472 if (mkdtemp((char *)itmp) != NULL)
7473 vim_settempdir(itmp);
7474# if defined(UNIX) || defined(VMS)
7475 (void)umask(umask_save);
7476# endif
7477 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007478# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007479 /* Get an arbitrary number of up to 6 digits. When it's
7480 * unlikely that it already exists it will be faster,
7481 * otherwise it doesn't matter. The use of mkdir() avoids any
7482 * security problems because of the predictable number. */
7483 nr = (mch_get_pid() + (long)time(NULL)) % 1000000L;
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007484 itmplen = STRLEN(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007485
7486 /* Try up to 10000 different values until we find a name that
7487 * doesn't exist. */
7488 for (off = 0; off < 10000L; ++off)
7489 {
7490 int r;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007491# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007492 mode_t umask_save;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007493# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007494
Bram Moolenaareaf03392009-11-17 11:08:52 +00007495 sprintf((char *)itmp + itmplen, "v%ld", nr + off);
7496# ifndef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007497 /* If mkdir() does not set errno to EEXIST, check for
7498 * existing file here. There is a race condition then,
7499 * although it's fail-safe. */
7500 if (mch_stat((char *)itmp, &st) >= 0)
7501 continue;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007502# endif
7503# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007504 /* Make sure the umask doesn't remove the executable bit.
7505 * "repl" has been reported to use "177". */
7506 umask_save = umask(077);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007507# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007508 r = vim_mkdir(itmp, 0700);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007509# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007510 (void)umask(umask_save);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007511# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007512 if (r == 0)
7513 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007514 vim_settempdir(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007515 break;
7516 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007517# ifdef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007518 /* If the mkdir() didn't fail because the file/dir exists,
7519 * we probably can't create any dir here, try another
7520 * place. */
7521 if (errno != EEXIST)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007522# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007523 break;
7524 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007525# endif /* HAVE_MKDTEMP */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007526 if (vim_tempdir != NULL)
7527 break;
7528 }
7529 }
7530 }
7531
7532 if (vim_tempdir != NULL)
7533 {
7534 /* There is no need to check if the file exists, because we own the
7535 * directory and nobody else creates a file in it. */
7536 sprintf((char *)itmp, "%s%ld", vim_tempdir, temp_count++);
7537 return vim_strsave(itmp);
7538 }
7539
7540 return NULL;
7541
7542#else /* TEMPDIRNAMES */
7543
7544# ifdef WIN3264
7545 char szTempFile[_MAX_PATH + 1];
7546 char buf4[4];
7547 char_u *retval;
7548 char_u *p;
7549
7550 STRCPY(itmp, "");
7551 if (GetTempPath(_MAX_PATH, szTempFile) == 0)
Bram Moolenaarb1891912011-02-09 14:47:03 +01007552 {
7553 szTempFile[0] = '.'; /* GetTempPath() failed, use current dir */
7554 szTempFile[1] = NUL;
7555 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007556 strcpy(buf4, "VIM");
7557 buf4[2] = extra_char; /* make it "VIa", "VIb", etc. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007558 if (GetTempFileName(szTempFile, buf4, 0, (LPSTR)itmp) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007559 return NULL;
Bram Moolenaare5c421c2015-03-31 13:33:08 +02007560 if (!keep)
7561 /* GetTempFileName() will create the file, we don't want that */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007562 (void)DeleteFile((LPSTR)itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007563
7564 /* Backslashes in a temp file name cause problems when filtering with
7565 * "sh". NOTE: This also checks 'shellcmdflag' to help those people who
7566 * didn't set 'shellslash'. */
7567 retval = vim_strsave(itmp);
7568 if (*p_shcf == '-' || p_ssl)
7569 for (p = retval; *p; ++p)
7570 if (*p == '\\')
7571 *p = '/';
7572 return retval;
7573
7574# else /* WIN3264 */
7575
7576# ifdef USE_TMPNAM
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007577 char_u *p;
7578
Bram Moolenaar071d4272004-06-13 20:20:40 +00007579 /* tmpnam() will make its own name */
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007580 p = tmpnam((char *)itmp);
7581 if (p == NULL || *p == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007582 return NULL;
7583# else
7584 char_u *p;
7585
7586# ifdef VMS_TEMPNAM
7587 /* mktemp() is not working on VMS. It seems to be
7588 * a do-nothing function. Therefore we use tempnam().
7589 */
7590 sprintf((char *)itmp, "VIM%c", extra_char);
7591 p = (char_u *)tempnam("tmp:", (char *)itmp);
7592 if (p != NULL)
7593 {
Bram Moolenaar206f0112014-03-12 16:51:55 +01007594 /* VMS will use '.LIS' if we don't explicitly specify an extension,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007595 * and VIM will then be unable to find the file later */
7596 STRCPY(itmp, p);
7597 STRCAT(itmp, ".txt");
7598 free(p);
7599 }
7600 else
7601 return NULL;
7602# else
7603 STRCPY(itmp, TEMPNAME);
7604 if ((p = vim_strchr(itmp, '?')) != NULL)
7605 *p = extra_char;
7606 if (mktemp((char *)itmp) == NULL)
7607 return NULL;
7608# endif
7609# endif
7610
7611 return vim_strsave(itmp);
7612# endif /* WIN3264 */
7613#endif /* TEMPDIRNAMES */
7614}
7615
7616#if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
7617/*
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02007618 * Convert all backslashes in fname to forward slashes in-place, unless when
7619 * it looks like a URL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007620 */
7621 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007622forward_slash(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007623{
7624 char_u *p;
7625
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02007626 if (path_with_url(fname))
7627 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007628 for (p = fname; *p != NUL; ++p)
7629# ifdef FEAT_MBYTE
7630 /* The Big5 encoding can have '\' in the trail byte. */
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00007631 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007632 ++p;
7633 else
7634# endif
7635 if (*p == '\\')
7636 *p = '/';
7637}
7638#endif
7639
7640
7641/*
7642 * Code for automatic commands.
7643 *
7644 * Only included when "FEAT_AUTOCMD" has been defined.
7645 */
7646
7647#if defined(FEAT_AUTOCMD) || defined(PROTO)
7648
7649/*
7650 * The autocommands are stored in a list for each event.
7651 * Autocommands for the same pattern, that are consecutive, are joined
7652 * together, to avoid having to match the pattern too often.
7653 * The result is an array of Autopat lists, which point to AutoCmd lists:
7654 *
7655 * first_autopat[0] --> Autopat.next --> Autopat.next --> NULL
7656 * Autopat.cmds Autopat.cmds
7657 * | |
7658 * V V
7659 * AutoCmd.next AutoCmd.next
7660 * | |
7661 * V V
7662 * AutoCmd.next NULL
7663 * |
7664 * V
7665 * NULL
7666 *
7667 * first_autopat[1] --> Autopat.next --> NULL
7668 * Autopat.cmds
7669 * |
7670 * V
7671 * AutoCmd.next
7672 * |
7673 * V
7674 * NULL
7675 * etc.
7676 *
7677 * The order of AutoCmds is important, this is the order in which they were
7678 * defined and will have to be executed.
7679 */
7680typedef struct AutoCmd
7681{
7682 char_u *cmd; /* The command to be executed (NULL
7683 when command has been removed) */
7684 char nested; /* If autocommands nest here */
7685 char last; /* last command in list */
7686#ifdef FEAT_EVAL
7687 scid_T scriptID; /* script ID where defined */
7688#endif
7689 struct AutoCmd *next; /* Next AutoCmd in list */
7690} AutoCmd;
7691
7692typedef struct AutoPat
7693{
Bram Moolenaar071d4272004-06-13 20:20:40 +00007694 char_u *pat; /* pattern as typed (NULL when pattern
7695 has been removed) */
Bram Moolenaar748bf032005-02-02 23:04:36 +00007696 regprog_T *reg_prog; /* compiled regprog for pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007697 AutoCmd *cmds; /* list of commands to do */
7698 struct AutoPat *next; /* next AutoPat in AutoPat list */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007699 int group; /* group ID */
7700 int patlen; /* strlen() of pat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007701 int buflocal_nr; /* !=0 for buffer-local AutoPat */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007702 char allow_dirs; /* Pattern may match whole path */
7703 char last; /* last pattern for apply_autocmds() */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007704} AutoPat;
7705
7706static struct event_name
7707{
7708 char *name; /* event name */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007709 event_T event; /* event number */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007710} event_names[] =
7711{
7712 {"BufAdd", EVENT_BUFADD},
7713 {"BufCreate", EVENT_BUFADD},
7714 {"BufDelete", EVENT_BUFDELETE},
7715 {"BufEnter", EVENT_BUFENTER},
7716 {"BufFilePost", EVENT_BUFFILEPOST},
7717 {"BufFilePre", EVENT_BUFFILEPRE},
7718 {"BufHidden", EVENT_BUFHIDDEN},
7719 {"BufLeave", EVENT_BUFLEAVE},
7720 {"BufNew", EVENT_BUFNEW},
7721 {"BufNewFile", EVENT_BUFNEWFILE},
7722 {"BufRead", EVENT_BUFREADPOST},
7723 {"BufReadCmd", EVENT_BUFREADCMD},
7724 {"BufReadPost", EVENT_BUFREADPOST},
7725 {"BufReadPre", EVENT_BUFREADPRE},
7726 {"BufUnload", EVENT_BUFUNLOAD},
7727 {"BufWinEnter", EVENT_BUFWINENTER},
7728 {"BufWinLeave", EVENT_BUFWINLEAVE},
7729 {"BufWipeout", EVENT_BUFWIPEOUT},
7730 {"BufWrite", EVENT_BUFWRITEPRE},
7731 {"BufWritePost", EVENT_BUFWRITEPOST},
7732 {"BufWritePre", EVENT_BUFWRITEPRE},
7733 {"BufWriteCmd", EVENT_BUFWRITECMD},
Bram Moolenaarfafcf0d2017-10-19 18:35:51 +02007734 {"CmdlineEnter", EVENT_CMDLINEENTER},
7735 {"CmdlineLeave", EVENT_CMDLINELEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007736 {"CmdwinEnter", EVENT_CMDWINENTER},
7737 {"CmdwinLeave", EVENT_CMDWINLEAVE},
Bram Moolenaard5005162014-08-22 23:05:54 +02007738 {"CmdUndefined", EVENT_CMDUNDEFINED},
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007739 {"ColorScheme", EVENT_COLORSCHEME},
Bram Moolenaarcfa3cae2012-07-10 17:14:56 +02007740 {"CompleteDone", EVENT_COMPLETEDONE},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007741 {"CursorHold", EVENT_CURSORHOLD},
7742 {"CursorHoldI", EVENT_CURSORHOLDI},
7743 {"CursorMoved", EVENT_CURSORMOVED},
7744 {"CursorMovedI", EVENT_CURSORMOVEDI},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007745 {"EncodingChanged", EVENT_ENCODINGCHANGED},
7746 {"FileEncoding", EVENT_ENCODINGCHANGED},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007747 {"FileAppendPost", EVENT_FILEAPPENDPOST},
7748 {"FileAppendPre", EVENT_FILEAPPENDPRE},
7749 {"FileAppendCmd", EVENT_FILEAPPENDCMD},
7750 {"FileChangedShell",EVENT_FILECHANGEDSHELL},
Bram Moolenaar56718732006-03-15 22:53:57 +00007751 {"FileChangedShellPost",EVENT_FILECHANGEDSHELLPOST},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007752 {"FileChangedRO", EVENT_FILECHANGEDRO},
7753 {"FileReadPost", EVENT_FILEREADPOST},
7754 {"FileReadPre", EVENT_FILEREADPRE},
7755 {"FileReadCmd", EVENT_FILEREADCMD},
7756 {"FileType", EVENT_FILETYPE},
7757 {"FileWritePost", EVENT_FILEWRITEPOST},
7758 {"FileWritePre", EVENT_FILEWRITEPRE},
7759 {"FileWriteCmd", EVENT_FILEWRITECMD},
7760 {"FilterReadPost", EVENT_FILTERREADPOST},
7761 {"FilterReadPre", EVENT_FILTERREADPRE},
7762 {"FilterWritePost", EVENT_FILTERWRITEPOST},
7763 {"FilterWritePre", EVENT_FILTERWRITEPRE},
7764 {"FocusGained", EVENT_FOCUSGAINED},
7765 {"FocusLost", EVENT_FOCUSLOST},
7766 {"FuncUndefined", EVENT_FUNCUNDEFINED},
7767 {"GUIEnter", EVENT_GUIENTER},
Bram Moolenaar265e5072006-08-29 16:13:22 +00007768 {"GUIFailed", EVENT_GUIFAILED},
Bram Moolenaar843ee412004-06-30 16:16:41 +00007769 {"InsertChange", EVENT_INSERTCHANGE},
7770 {"InsertEnter", EVENT_INSERTENTER},
7771 {"InsertLeave", EVENT_INSERTLEAVE},
Bram Moolenaare659c952011-05-19 17:25:41 +02007772 {"InsertCharPre", EVENT_INSERTCHARPRE},
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00007773 {"MenuPopup", EVENT_MENUPOPUP},
Bram Moolenaar53744302015-07-17 17:38:22 +02007774 {"OptionSet", EVENT_OPTIONSET},
Bram Moolenaar7c626922005-02-07 22:01:03 +00007775 {"QuickFixCmdPost", EVENT_QUICKFIXCMDPOST},
7776 {"QuickFixCmdPre", EVENT_QUICKFIXCMDPRE},
Bram Moolenaar3b53dfb2012-06-06 18:03:07 +02007777 {"QuitPre", EVENT_QUITPRE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007778 {"RemoteReply", EVENT_REMOTEREPLY},
Bram Moolenaar9372a112005-12-06 19:59:18 +00007779 {"SessionLoadPost", EVENT_SESSIONLOADPOST},
Bram Moolenaar5c4bab02006-03-10 21:37:46 +00007780 {"ShellCmdPost", EVENT_SHELLCMDPOST},
7781 {"ShellFilterPost", EVENT_SHELLFILTERPOST},
Bram Moolenaara2031822006-03-07 22:29:51 +00007782 {"SourcePre", EVENT_SOURCEPRE},
Bram Moolenaar8dd1aa52007-01-16 20:33:19 +00007783 {"SourceCmd", EVENT_SOURCECMD},
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00007784 {"SpellFileMissing",EVENT_SPELLFILEMISSING},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007785 {"StdinReadPost", EVENT_STDINREADPOST},
7786 {"StdinReadPre", EVENT_STDINREADPRE},
Bram Moolenaarb815dac2005-12-07 20:59:24 +00007787 {"SwapExists", EVENT_SWAPEXISTS},
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00007788 {"Syntax", EVENT_SYNTAX},
Bram Moolenaarc917da42016-07-19 22:31:36 +02007789 {"TabNew", EVENT_TABNEW},
Bram Moolenaar12c11d52016-07-19 23:13:03 +02007790 {"TabClosed", EVENT_TABCLOSED},
Bram Moolenaar70836c82006-02-20 21:28:49 +00007791 {"TabEnter", EVENT_TABENTER},
7792 {"TabLeave", EVENT_TABLEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007793 {"TermChanged", EVENT_TERMCHANGED},
7794 {"TermResponse", EVENT_TERMRESPONSE},
Bram Moolenaar186628f2013-03-19 13:33:23 +01007795 {"TextChanged", EVENT_TEXTCHANGED},
7796 {"TextChangedI", EVENT_TEXTCHANGEDI},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007797 {"User", EVENT_USER},
7798 {"VimEnter", EVENT_VIMENTER},
7799 {"VimLeave", EVENT_VIMLEAVE},
7800 {"VimLeavePre", EVENT_VIMLEAVEPRE},
Bram Moolenaarc917da42016-07-19 22:31:36 +02007801 {"WinNew", EVENT_WINNEW},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007802 {"WinEnter", EVENT_WINENTER},
7803 {"WinLeave", EVENT_WINLEAVE},
Bram Moolenaar56718732006-03-15 22:53:57 +00007804 {"VimResized", EVENT_VIMRESIZED},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007805 {NULL, (event_T)0}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007806};
7807
7808static AutoPat *first_autopat[NUM_EVENTS] =
7809{
7810 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7811 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7812 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7813 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00007814 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaar53744302015-07-17 17:38:22 +02007815 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007816};
7817
7818/*
7819 * struct used to keep status while executing autocommands for an event.
7820 */
7821typedef struct AutoPatCmd
7822{
7823 AutoPat *curpat; /* next AutoPat to examine */
7824 AutoCmd *nextcmd; /* next AutoCmd to execute */
7825 int group; /* group being used */
7826 char_u *fname; /* fname to match with */
7827 char_u *sfname; /* sfname to match with */
7828 char_u *tail; /* tail of fname */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007829 event_T event; /* current event */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007830 int arg_bufnr; /* initially equal to <abuf>, set to zero when
7831 buf is deleted */
7832 struct AutoPatCmd *next; /* chain of active apc-s for auto-invalidation*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00007833} AutoPatCmd;
7834
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007835static AutoPatCmd *active_apc_list = NULL; /* stack of active autocommands */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007836
Bram Moolenaar071d4272004-06-13 20:20:40 +00007837/*
7838 * augroups stores a list of autocmd group names.
7839 */
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007840static garray_T augroups = {0, 0, sizeof(char_u *), 10, NULL};
Bram Moolenaar071d4272004-06-13 20:20:40 +00007841#define AUGROUP_NAME(i) (((char_u **)augroups.ga_data)[i])
Bram Moolenaarb62cc362016-09-03 16:43:53 +02007842/* use get_deleted_augroup() to get this */
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02007843static char_u *deleted_augroup = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007844
7845/*
7846 * The ID of the current group. Group 0 is the default one.
7847 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007848static int current_augroup = AUGROUP_DEFAULT;
7849
7850static int au_need_clean = FALSE; /* need to delete marked patterns */
7851
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007852static void show_autocmd(AutoPat *ap, event_T event);
7853static void au_remove_pat(AutoPat *ap);
7854static void au_remove_cmds(AutoPat *ap);
7855static void au_cleanup(void);
7856static int au_new_group(char_u *name);
7857static void au_del_group(char_u *name);
7858static event_T event_name2nr(char_u *start, char_u **end);
7859static char_u *event_nr2name(event_T event);
7860static char_u *find_end_event(char_u *arg, int have_group);
7861static int event_ignored(event_T event);
7862static int au_get_grouparg(char_u **argp);
7863static int do_autocmd_event(event_T event, char_u *pat, int nested, char_u *cmd, int forceit, int group);
7864static int apply_autocmds_group(event_T event, char_u *fname, char_u *fname_io, int force, int group, buf_T *buf, exarg_T *eap);
7865static void auto_next_pat(AutoPatCmd *apc, int stop_at_last);
Bram Moolenaardffa5b82014-11-19 16:38:07 +01007866#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN)
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007867static 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 +01007868#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007869
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007870
Bram Moolenaar754b5602006-02-09 23:53:20 +00007871static event_T last_event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007872static int last_group;
Bram Moolenaar78ab3312007-09-29 12:16:41 +00007873static int autocmd_blocked = 0; /* block all autocmds */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007874
Bram Moolenaarb62cc362016-09-03 16:43:53 +02007875 static char_u *
7876get_deleted_augroup(void)
7877{
7878 if (deleted_augroup == NULL)
7879 deleted_augroup = (char_u *)_("--Deleted--");
7880 return deleted_augroup;
7881}
7882
Bram Moolenaar071d4272004-06-13 20:20:40 +00007883/*
7884 * Show the autocommands for one AutoPat.
7885 */
7886 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007887show_autocmd(AutoPat *ap, event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007888{
7889 AutoCmd *ac;
7890
7891 /* Check for "got_int" (here and at various places below), which is set
7892 * when "q" has been hit for the "--more--" prompt */
7893 if (got_int)
7894 return;
7895 if (ap->pat == NULL) /* pattern has been removed */
7896 return;
7897
7898 msg_putchar('\n');
7899 if (got_int)
7900 return;
7901 if (event != last_event || ap->group != last_group)
7902 {
7903 if (ap->group != AUGROUP_DEFAULT)
7904 {
7905 if (AUGROUP_NAME(ap->group) == NULL)
Bram Moolenaar8820b482017-03-16 17:23:31 +01007906 msg_puts_attr(get_deleted_augroup(), HL_ATTR(HLF_E));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007907 else
Bram Moolenaar8820b482017-03-16 17:23:31 +01007908 msg_puts_attr(AUGROUP_NAME(ap->group), HL_ATTR(HLF_T));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007909 msg_puts((char_u *)" ");
7910 }
Bram Moolenaar8820b482017-03-16 17:23:31 +01007911 msg_puts_attr(event_nr2name(event), HL_ATTR(HLF_T));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007912 last_event = event;
7913 last_group = ap->group;
7914 msg_putchar('\n');
7915 if (got_int)
7916 return;
7917 }
7918 msg_col = 4;
7919 msg_outtrans(ap->pat);
7920
7921 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7922 {
7923 if (ac->cmd != NULL) /* skip removed commands */
7924 {
7925 if (msg_col >= 14)
7926 msg_putchar('\n');
7927 msg_col = 14;
7928 if (got_int)
7929 return;
7930 msg_outtrans(ac->cmd);
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00007931#ifdef FEAT_EVAL
7932 if (p_verbose > 0)
7933 last_set_msg(ac->scriptID);
7934#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007935 if (got_int)
7936 return;
7937 if (ac->next != NULL)
7938 {
7939 msg_putchar('\n');
7940 if (got_int)
7941 return;
7942 }
7943 }
7944 }
7945}
7946
7947/*
7948 * Mark an autocommand pattern for deletion.
7949 */
7950 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007951au_remove_pat(AutoPat *ap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007952{
7953 vim_free(ap->pat);
7954 ap->pat = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007955 ap->buflocal_nr = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007956 au_need_clean = TRUE;
7957}
7958
7959/*
7960 * Mark all commands for a pattern for deletion.
7961 */
7962 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007963au_remove_cmds(AutoPat *ap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007964{
7965 AutoCmd *ac;
7966
7967 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7968 {
7969 vim_free(ac->cmd);
7970 ac->cmd = NULL;
7971 }
7972 au_need_clean = TRUE;
7973}
7974
7975/*
7976 * Cleanup autocommands and patterns that have been deleted.
7977 * This is only done when not executing autocommands.
7978 */
7979 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007980au_cleanup(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007981{
7982 AutoPat *ap, **prev_ap;
7983 AutoCmd *ac, **prev_ac;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007984 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007985
7986 if (autocmd_busy || !au_need_clean)
7987 return;
7988
7989 /* loop over all events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007990 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7991 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007992 {
7993 /* loop over all autocommand patterns */
7994 prev_ap = &(first_autopat[(int)event]);
7995 for (ap = *prev_ap; ap != NULL; ap = *prev_ap)
7996 {
7997 /* loop over all commands for this pattern */
7998 prev_ac = &(ap->cmds);
7999 for (ac = *prev_ac; ac != NULL; ac = *prev_ac)
8000 {
8001 /* remove the command if the pattern is to be deleted or when
8002 * the command has been marked for deletion */
8003 if (ap->pat == NULL || ac->cmd == NULL)
8004 {
8005 *prev_ac = ac->next;
8006 vim_free(ac->cmd);
8007 vim_free(ac);
8008 }
8009 else
8010 prev_ac = &(ac->next);
8011 }
8012
8013 /* remove the pattern if it has been marked for deletion */
8014 if (ap->pat == NULL)
8015 {
8016 *prev_ap = ap->next;
Bram Moolenaar473de612013-06-08 18:19:48 +02008017 vim_regfree(ap->reg_prog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008018 vim_free(ap);
8019 }
8020 else
8021 prev_ap = &(ap->next);
8022 }
8023 }
8024
8025 au_need_clean = FALSE;
8026}
8027
8028/*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008029 * Called when buffer is freed, to remove/invalidate related buffer-local
8030 * autocmds.
8031 */
8032 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008033aubuflocal_remove(buf_T *buf)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008034{
8035 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008036 event_T event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008037 AutoPatCmd *apc;
8038
8039 /* invalidate currently executing autocommands */
8040 for (apc = active_apc_list; apc; apc = apc->next)
8041 if (buf->b_fnum == apc->arg_bufnr)
8042 apc->arg_bufnr = 0;
8043
8044 /* invalidate buflocals looping through events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008045 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8046 event = (event_T)((int)event + 1))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008047 /* loop over all autocommand patterns */
8048 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8049 if (ap->buflocal_nr == buf->b_fnum)
8050 {
8051 au_remove_pat(ap);
8052 if (p_verbose >= 6)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00008053 {
8054 verbose_enter();
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008055 smsg((char_u *)
8056 _("auto-removing autocommand: %s <buffer=%d>"),
8057 event_nr2name(event), buf->b_fnum);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00008058 verbose_leave();
8059 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008060 }
8061 au_cleanup();
8062}
8063
8064/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008065 * Add an autocmd group name.
8066 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
8067 */
8068 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008069au_new_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008070{
8071 int i;
8072
8073 i = au_find_group(name);
8074 if (i == AUGROUP_ERROR) /* the group doesn't exist yet, add it */
8075 {
8076 /* First try using a free entry. */
8077 for (i = 0; i < augroups.ga_len; ++i)
8078 if (AUGROUP_NAME(i) == NULL)
8079 break;
8080 if (i == augroups.ga_len && ga_grow(&augroups, 1) == FAIL)
8081 return AUGROUP_ERROR;
8082
8083 AUGROUP_NAME(i) = vim_strsave(name);
8084 if (AUGROUP_NAME(i) == NULL)
8085 return AUGROUP_ERROR;
8086 if (i == augroups.ga_len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008087 ++augroups.ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008088 }
8089
8090 return i;
8091}
8092
8093 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008094au_del_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008095{
8096 int i;
8097
8098 i = au_find_group(name);
8099 if (i == AUGROUP_ERROR) /* the group doesn't exist */
8100 EMSG2(_("E367: No such group: \"%s\""), name);
Bram Moolenaarde653f02016-09-03 16:59:06 +02008101 else if (i == current_augroup)
8102 EMSG(_("E936: Cannot delete the current group"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008103 else
8104 {
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008105 event_T event;
8106 AutoPat *ap;
8107 int in_use = FALSE;
8108
8109 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8110 event = (event_T)((int)event + 1))
8111 {
8112 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
Bram Moolenaar5c809082016-09-01 16:21:48 +02008113 if (ap->group == i && ap->pat != NULL)
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008114 {
8115 give_warning((char_u *)_("W19: Deleting augroup that is still in use"), TRUE);
8116 in_use = TRUE;
8117 event = NUM_EVENTS;
8118 break;
8119 }
8120 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008121 vim_free(AUGROUP_NAME(i));
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008122 if (in_use)
8123 {
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008124 AUGROUP_NAME(i) = get_deleted_augroup();
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008125 }
8126 else
8127 AUGROUP_NAME(i) = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008128 }
8129}
8130
8131/*
8132 * Find the ID of an autocmd group name.
8133 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
8134 */
8135 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008136au_find_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008137{
8138 int i;
8139
8140 for (i = 0; i < augroups.ga_len; ++i)
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008141 if (AUGROUP_NAME(i) != NULL && AUGROUP_NAME(i) != get_deleted_augroup()
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008142 && STRCMP(AUGROUP_NAME(i), name) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008143 return i;
8144 return AUGROUP_ERROR;
8145}
8146
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008147/*
8148 * Return TRUE if augroup "name" exists.
8149 */
8150 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008151au_has_group(char_u *name)
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008152{
8153 return au_find_group(name) != AUGROUP_ERROR;
8154}
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008155
Bram Moolenaar071d4272004-06-13 20:20:40 +00008156/*
8157 * ":augroup {name}".
8158 */
8159 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008160do_augroup(char_u *arg, int del_group)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008161{
8162 int i;
8163
8164 if (del_group)
8165 {
8166 if (*arg == NUL)
8167 EMSG(_(e_argreq));
8168 else
8169 au_del_group(arg);
8170 }
8171 else if (STRICMP(arg, "end") == 0) /* ":aug end": back to group 0 */
8172 current_augroup = AUGROUP_DEFAULT;
8173 else if (*arg) /* ":aug xxx": switch to group xxx */
8174 {
8175 i = au_new_group(arg);
8176 if (i != AUGROUP_ERROR)
8177 current_augroup = i;
8178 }
8179 else /* ":aug": list the group names */
8180 {
8181 msg_start();
8182 for (i = 0; i < augroups.ga_len; ++i)
8183 {
8184 if (AUGROUP_NAME(i) != NULL)
8185 {
8186 msg_puts(AUGROUP_NAME(i));
8187 msg_puts((char_u *)" ");
8188 }
8189 }
8190 msg_clr_eos();
8191 msg_end();
8192 }
8193}
8194
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008195#if defined(EXITFREE) || defined(PROTO)
8196 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008197free_all_autocmds(void)
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008198{
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008199 int i;
8200 char_u *s;
8201
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008202 for (current_augroup = -1; current_augroup < augroups.ga_len;
8203 ++current_augroup)
8204 do_autocmd((char_u *)"", TRUE);
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008205
8206 for (i = 0; i < augroups.ga_len; ++i)
8207 {
8208 s = ((char_u **)(augroups.ga_data))[i];
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008209 if (s != get_deleted_augroup())
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008210 vim_free(s);
8211 }
8212 ga_clear(&augroups);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008213}
8214#endif
8215
Bram Moolenaar071d4272004-06-13 20:20:40 +00008216/*
8217 * Return the event number for event name "start".
8218 * Return NUM_EVENTS if the event name was not found.
8219 * Return a pointer to the next event name in "end".
8220 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008221 static event_T
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008222event_name2nr(char_u *start, char_u **end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008223{
8224 char_u *p;
8225 int i;
8226 int len;
8227
Bram Moolenaare99e8442016-07-26 20:43:40 +02008228 /* the event name ends with end of line, '|', a blank or a comma */
Bram Moolenaar1c465442017-03-12 20:10:05 +01008229 for (p = start; *p && !VIM_ISWHITE(*p) && *p != ',' && *p != '|'; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008230 ;
8231 for (i = 0; event_names[i].name != NULL; ++i)
8232 {
8233 len = (int)STRLEN(event_names[i].name);
8234 if (len == p - start && STRNICMP(event_names[i].name, start, len) == 0)
8235 break;
8236 }
8237 if (*p == ',')
8238 ++p;
8239 *end = p;
8240 if (event_names[i].name == NULL)
8241 return NUM_EVENTS;
8242 return event_names[i].event;
8243}
8244
8245/*
8246 * Return the name for event "event".
8247 */
8248 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008249event_nr2name(event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008250{
8251 int i;
8252
8253 for (i = 0; event_names[i].name != NULL; ++i)
8254 if (event_names[i].event == event)
8255 return (char_u *)event_names[i].name;
8256 return (char_u *)"Unknown";
8257}
8258
8259/*
8260 * Scan over the events. "*" stands for all events.
8261 */
8262 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008263find_end_event(
8264 char_u *arg,
8265 int have_group) /* TRUE when group name was found */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008266{
8267 char_u *pat;
8268 char_u *p;
8269
8270 if (*arg == '*')
8271 {
Bram Moolenaar1c465442017-03-12 20:10:05 +01008272 if (arg[1] && !VIM_ISWHITE(arg[1]))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008273 {
8274 EMSG2(_("E215: Illegal character after *: %s"), arg);
8275 return NULL;
8276 }
8277 pat = arg + 1;
8278 }
8279 else
8280 {
Bram Moolenaar1c465442017-03-12 20:10:05 +01008281 for (pat = arg; *pat && *pat != '|' && !VIM_ISWHITE(*pat); pat = p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008282 {
8283 if ((int)event_name2nr(pat, &p) >= (int)NUM_EVENTS)
8284 {
8285 if (have_group)
8286 EMSG2(_("E216: No such event: %s"), pat);
8287 else
8288 EMSG2(_("E216: No such group or event: %s"), pat);
8289 return NULL;
8290 }
8291 }
8292 }
8293 return pat;
8294}
8295
8296/*
8297 * Return TRUE if "event" is included in 'eventignore'.
8298 */
8299 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008300event_ignored(event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008301{
8302 char_u *p = p_ei;
8303
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008304 while (*p != NUL)
8305 {
8306 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8307 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008308 if (event_name2nr(p, &p) == event)
8309 return TRUE;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008310 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008311
8312 return FALSE;
8313}
8314
8315/*
8316 * Return OK when the contents of p_ei is valid, FAIL otherwise.
8317 */
8318 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008319check_ei(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008320{
8321 char_u *p = p_ei;
8322
Bram Moolenaar071d4272004-06-13 20:20:40 +00008323 while (*p)
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008324 {
8325 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8326 {
8327 p += 3;
8328 if (*p == ',')
8329 ++p;
8330 }
8331 else if (event_name2nr(p, &p) == NUM_EVENTS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008332 return FAIL;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008333 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008334
8335 return OK;
8336}
8337
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008338# if defined(FEAT_SYN_HL) || defined(PROTO)
8339
8340/*
8341 * Add "what" to 'eventignore' to skip loading syntax highlighting for every
8342 * buffer loaded into the window. "what" must start with a comma.
8343 * Returns the old value of 'eventignore' in allocated memory.
8344 */
8345 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008346au_event_disable(char *what)
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008347{
8348 char_u *new_ei;
8349 char_u *save_ei;
8350
8351 save_ei = vim_strsave(p_ei);
8352 if (save_ei != NULL)
8353 {
Bram Moolenaara5792f52005-11-23 21:25:05 +00008354 new_ei = vim_strnsave(p_ei, (int)(STRLEN(p_ei) + STRLEN(what)));
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008355 if (new_ei != NULL)
8356 {
Bram Moolenaar8cac9fd2010-03-02 12:48:05 +01008357 if (*what == ',' && *p_ei == NUL)
8358 STRCPY(new_ei, what + 1);
8359 else
8360 STRCAT(new_ei, what);
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008361 set_string_option_direct((char_u *)"ei", -1, new_ei,
8362 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008363 vim_free(new_ei);
8364 }
8365 }
8366 return save_ei;
8367}
8368
8369 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008370au_event_restore(char_u *old_ei)
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008371{
8372 if (old_ei != NULL)
8373 {
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008374 set_string_option_direct((char_u *)"ei", -1, old_ei,
8375 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008376 vim_free(old_ei);
8377 }
8378}
8379# endif /* FEAT_SYN_HL */
8380
Bram Moolenaar071d4272004-06-13 20:20:40 +00008381/*
8382 * do_autocmd() -- implements the :autocmd command. Can be used in the
8383 * following ways:
8384 *
8385 * :autocmd <event> <pat> <cmd> Add <cmd> to the list of commands that
8386 * will be automatically executed for <event>
8387 * when editing a file matching <pat>, in
8388 * the current group.
8389 * :autocmd <event> <pat> Show the auto-commands associated with
8390 * <event> and <pat>.
8391 * :autocmd <event> Show the auto-commands associated with
8392 * <event>.
8393 * :autocmd Show all auto-commands.
8394 * :autocmd! <event> <pat> <cmd> Remove all auto-commands associated with
8395 * <event> and <pat>, and add the command
8396 * <cmd>, for the current group.
8397 * :autocmd! <event> <pat> Remove all auto-commands associated with
8398 * <event> and <pat> for the current group.
8399 * :autocmd! <event> Remove all auto-commands associated with
8400 * <event> for the current group.
8401 * :autocmd! Remove ALL auto-commands for the current
8402 * group.
8403 *
8404 * Multiple events and patterns may be given separated by commas. Here are
8405 * some examples:
8406 * :autocmd bufread,bufenter *.c,*.h set tw=0 smartindent noic
8407 * :autocmd bufleave * set tw=79 nosmartindent ic infercase
8408 *
8409 * :autocmd * *.c show all autocommands for *.c files.
Bram Moolenaard35f9712005-12-18 22:02:33 +00008410 *
8411 * Mostly a {group} argument can optionally appear before <event>.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008412 */
8413 void
Bram Moolenaare99e8442016-07-26 20:43:40 +02008414do_autocmd(char_u *arg_in, int forceit)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008415{
Bram Moolenaare99e8442016-07-26 20:43:40 +02008416 char_u *arg = arg_in;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008417 char_u *pat;
8418 char_u *envpat = NULL;
8419 char_u *cmd;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008420 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008421 int need_free = FALSE;
8422 int nested = FALSE;
8423 int group;
8424
Bram Moolenaare99e8442016-07-26 20:43:40 +02008425 if (*arg == '|')
8426 {
8427 arg = (char_u *)"";
8428 group = AUGROUP_ALL; /* no argument, use all groups */
8429 }
8430 else
8431 {
8432 /*
8433 * Check for a legal group name. If not, use AUGROUP_ALL.
8434 */
8435 group = au_get_grouparg(&arg);
8436 if (arg == NULL) /* out of memory */
8437 return;
8438 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008439
8440 /*
8441 * Scan over the events.
8442 * If we find an illegal name, return here, don't do anything.
8443 */
8444 pat = find_end_event(arg, group != AUGROUP_ALL);
8445 if (pat == NULL)
8446 return;
8447
Bram Moolenaar071d4272004-06-13 20:20:40 +00008448 pat = skipwhite(pat);
Bram Moolenaare99e8442016-07-26 20:43:40 +02008449 if (*pat == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008450 {
Bram Moolenaare99e8442016-07-26 20:43:40 +02008451 pat = (char_u *)"";
8452 cmd = (char_u *)"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00008453 }
Bram Moolenaare99e8442016-07-26 20:43:40 +02008454 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00008455 {
Bram Moolenaare99e8442016-07-26 20:43:40 +02008456 /*
8457 * Scan over the pattern. Put a NUL at the end.
8458 */
8459 cmd = pat;
Bram Moolenaar1c465442017-03-12 20:10:05 +01008460 while (*cmd && (!VIM_ISWHITE(*cmd) || cmd[-1] == '\\'))
Bram Moolenaare99e8442016-07-26 20:43:40 +02008461 cmd++;
8462 if (*cmd)
8463 *cmd++ = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008464
Bram Moolenaare99e8442016-07-26 20:43:40 +02008465 /* Expand environment variables in the pattern. Set 'shellslash', we want
8466 * forward slashes here. */
8467 if (vim_strchr(pat, '$') != NULL || vim_strchr(pat, '~') != NULL)
8468 {
8469#ifdef BACKSLASH_IN_FILENAME
8470 int p_ssl_save = p_ssl;
8471
8472 p_ssl = TRUE;
8473#endif
8474 envpat = expand_env_save(pat);
8475#ifdef BACKSLASH_IN_FILENAME
8476 p_ssl = p_ssl_save;
8477#endif
8478 if (envpat != NULL)
8479 pat = envpat;
8480 }
8481
8482 /*
8483 * Check for "nested" flag.
8484 */
8485 cmd = skipwhite(cmd);
Bram Moolenaar1c465442017-03-12 20:10:05 +01008486 if (*cmd != NUL && STRNCMP(cmd, "nested", 6) == 0 && VIM_ISWHITE(cmd[6]))
Bram Moolenaare99e8442016-07-26 20:43:40 +02008487 {
8488 nested = TRUE;
8489 cmd = skipwhite(cmd + 6);
8490 }
8491
8492 /*
8493 * Find the start of the commands.
8494 * Expand <sfile> in it.
8495 */
8496 if (*cmd != NUL)
8497 {
8498 cmd = expand_sfile(cmd);
8499 if (cmd == NULL) /* some error */
8500 return;
8501 need_free = TRUE;
8502 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008503 }
8504
8505 /*
8506 * Print header when showing autocommands.
8507 */
8508 if (!forceit && *cmd == NUL)
8509 {
8510 /* Highlight title */
8511 MSG_PUTS_TITLE(_("\n--- Auto-Commands ---"));
8512 }
8513
8514 /*
8515 * Loop over the events.
8516 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008517 last_event = (event_T)-1; /* for listing the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008518 last_group = AUGROUP_ERROR; /* for listing the group name */
Bram Moolenaare99e8442016-07-26 20:43:40 +02008519 if (*arg == '*' || *arg == NUL || *arg == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008520 {
Bram Moolenaar754b5602006-02-09 23:53:20 +00008521 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8522 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008523 if (do_autocmd_event(event, pat,
8524 nested, cmd, forceit, group) == FAIL)
8525 break;
8526 }
8527 else
8528 {
Bram Moolenaar1c465442017-03-12 20:10:05 +01008529 while (*arg && *arg != '|' && !VIM_ISWHITE(*arg))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008530 if (do_autocmd_event(event_name2nr(arg, &arg), pat,
8531 nested, cmd, forceit, group) == FAIL)
8532 break;
8533 }
8534
8535 if (need_free)
8536 vim_free(cmd);
8537 vim_free(envpat);
8538}
8539
8540/*
8541 * Find the group ID in a ":autocmd" or ":doautocmd" argument.
8542 * The "argp" argument is advanced to the following argument.
8543 *
8544 * Returns the group ID, AUGROUP_ERROR for error (out of memory).
8545 */
8546 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008547au_get_grouparg(char_u **argp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008548{
8549 char_u *group_name;
8550 char_u *p;
8551 char_u *arg = *argp;
8552 int group = AUGROUP_ALL;
8553
Bram Moolenaar1c465442017-03-12 20:10:05 +01008554 for (p = arg; *p && !VIM_ISWHITE(*p) && *p != '|'; ++p)
Bram Moolenaare99e8442016-07-26 20:43:40 +02008555 ;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008556 if (p > arg)
8557 {
8558 group_name = vim_strnsave(arg, (int)(p - arg));
8559 if (group_name == NULL) /* out of memory */
8560 return AUGROUP_ERROR;
8561 group = au_find_group(group_name);
8562 if (group == AUGROUP_ERROR)
8563 group = AUGROUP_ALL; /* no match, use all groups */
8564 else
8565 *argp = skipwhite(p); /* match, skip over group name */
8566 vim_free(group_name);
8567 }
8568 return group;
8569}
8570
8571/*
8572 * do_autocmd() for one event.
8573 * If *pat == NUL do for all patterns.
8574 * If *cmd == NUL show entries.
8575 * If forceit == TRUE delete entries.
8576 * If group is not AUGROUP_ALL, only use this group.
8577 */
8578 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008579do_autocmd_event(
8580 event_T event,
8581 char_u *pat,
8582 int nested,
8583 char_u *cmd,
8584 int forceit,
8585 int group)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008586{
8587 AutoPat *ap;
8588 AutoPat **prev_ap;
8589 AutoCmd *ac;
8590 AutoCmd **prev_ac;
8591 int brace_level;
8592 char_u *endpat;
8593 int findgroup;
8594 int allgroups;
8595 int patlen;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00008596 int is_buflocal;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008597 int buflocal_nr;
8598 char_u buflocal_pat[25]; /* for "<buffer=X>" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008599
8600 if (group == AUGROUP_ALL)
8601 findgroup = current_augroup;
8602 else
8603 findgroup = group;
8604 allgroups = (group == AUGROUP_ALL && !forceit && *cmd == NUL);
8605
8606 /*
8607 * Show or delete all patterns for an event.
8608 */
8609 if (*pat == NUL)
8610 {
8611 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8612 {
8613 if (forceit) /* delete the AutoPat, if it's in the current group */
8614 {
8615 if (ap->group == findgroup)
8616 au_remove_pat(ap);
8617 }
8618 else if (group == AUGROUP_ALL || ap->group == group)
8619 show_autocmd(ap, event);
8620 }
8621 }
8622
8623 /*
8624 * Loop through all the specified patterns.
8625 */
8626 for ( ; *pat; pat = (*endpat == ',' ? endpat + 1 : endpat))
8627 {
8628 /*
8629 * Find end of the pattern.
8630 * Watch out for a comma in braces, like "*.\{obj,o\}".
8631 */
8632 brace_level = 0;
8633 for (endpat = pat; *endpat && (*endpat != ',' || brace_level
Bram Moolenaar6b9be1b2015-07-28 13:33:45 +02008634 || (endpat > pat && endpat[-1] == '\\')); ++endpat)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008635 {
8636 if (*endpat == '{')
8637 brace_level++;
8638 else if (*endpat == '}')
8639 brace_level--;
8640 }
8641 if (pat == endpat) /* ignore single comma */
8642 continue;
8643 patlen = (int)(endpat - pat);
8644
8645 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008646 * detect special <buflocal[=X]> buffer-local patterns
8647 */
8648 is_buflocal = FALSE;
8649 buflocal_nr = 0;
8650
Bram Moolenaar1e997822015-02-17 16:04:57 +01008651 if (patlen >= 8 && STRNCMP(pat, "<buffer", 7) == 0
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008652 && pat[patlen - 1] == '>')
8653 {
Bram Moolenaar1e997822015-02-17 16:04:57 +01008654 /* "<buffer...>": Error will be printed only for addition.
8655 * printing and removing will proceed silently. */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008656 is_buflocal = TRUE;
8657 if (patlen == 8)
Bram Moolenaar1e997822015-02-17 16:04:57 +01008658 /* "<buffer>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008659 buflocal_nr = curbuf->b_fnum;
8660 else if (patlen > 9 && pat[7] == '=')
8661 {
Bram Moolenaar1e997822015-02-17 16:04:57 +01008662 if (patlen == 13 && STRNICMP(pat, "<buffer=abuf>", 13) == 0)
8663 /* "<buffer=abuf>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008664 buflocal_nr = autocmd_bufnr;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008665 else if (skipdigits(pat + 8) == pat + patlen - 1)
Bram Moolenaar1e997822015-02-17 16:04:57 +01008666 /* "<buffer=123>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008667 buflocal_nr = atoi((char *)pat + 8);
8668 }
8669 }
8670
8671 if (is_buflocal)
8672 {
8673 /* normalize pat into standard "<buffer>#N" form */
8674 sprintf((char *)buflocal_pat, "<buffer=%d>", buflocal_nr);
8675 pat = buflocal_pat; /* can modify pat and patlen */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008676 patlen = (int)STRLEN(buflocal_pat); /* but not endpat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008677 }
8678
8679 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008680 * Find AutoPat entries with this pattern.
8681 */
8682 prev_ap = &first_autopat[(int)event];
8683 while ((ap = *prev_ap) != NULL)
8684 {
8685 if (ap->pat != NULL)
8686 {
8687 /* Accept a pattern when:
8688 * - a group was specified and it's that group, or a group was
8689 * not specified and it's the current group, or a group was
8690 * not specified and we are listing
8691 * - the length of the pattern matches
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008692 * - the pattern matches.
8693 * For <buffer[=X]>, this condition works because we normalize
8694 * all buffer-local patterns.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008695 */
8696 if ((allgroups || ap->group == findgroup)
8697 && ap->patlen == patlen
8698 && STRNCMP(pat, ap->pat, patlen) == 0)
8699 {
8700 /*
8701 * Remove existing autocommands.
8702 * If adding any new autocmd's for this AutoPat, don't
8703 * delete the pattern from the autopat list, append to
8704 * this list.
8705 */
8706 if (forceit)
8707 {
8708 if (*cmd != NUL && ap->next == NULL)
8709 {
8710 au_remove_cmds(ap);
8711 break;
8712 }
8713 au_remove_pat(ap);
8714 }
8715
8716 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008717 * Show autocmd's for this autopat, or buflocals <buffer=X>
Bram Moolenaar071d4272004-06-13 20:20:40 +00008718 */
8719 else if (*cmd == NUL)
8720 show_autocmd(ap, event);
8721
8722 /*
8723 * Add autocmd to this autopat, if it's the last one.
8724 */
8725 else if (ap->next == NULL)
8726 break;
8727 }
8728 }
8729 prev_ap = &ap->next;
8730 }
8731
8732 /*
8733 * Add a new command.
8734 */
8735 if (*cmd != NUL)
8736 {
8737 /*
8738 * If the pattern we want to add a command to does appear at the
8739 * end of the list (or not is not in the list at all), add the
8740 * pattern at the end of the list.
8741 */
8742 if (ap == NULL)
8743 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008744 /* refuse to add buffer-local ap if buffer number is invalid */
8745 if (is_buflocal && (buflocal_nr == 0
8746 || buflist_findnr(buflocal_nr) == NULL))
8747 {
8748 EMSGN(_("E680: <buffer=%d>: invalid buffer number "),
8749 buflocal_nr);
8750 return FAIL;
8751 }
8752
Bram Moolenaar071d4272004-06-13 20:20:40 +00008753 ap = (AutoPat *)alloc((unsigned)sizeof(AutoPat));
8754 if (ap == NULL)
8755 return FAIL;
8756 ap->pat = vim_strnsave(pat, patlen);
8757 ap->patlen = patlen;
8758 if (ap->pat == NULL)
8759 {
8760 vim_free(ap);
8761 return FAIL;
8762 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008763
8764 if (is_buflocal)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008765 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008766 ap->buflocal_nr = buflocal_nr;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008767 ap->reg_prog = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008768 }
8769 else
8770 {
Bram Moolenaar748bf032005-02-02 23:04:36 +00008771 char_u *reg_pat;
8772
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008773 ap->buflocal_nr = 0;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008774 reg_pat = file_pat_to_reg_pat(pat, endpat,
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008775 &ap->allow_dirs, TRUE);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008776 if (reg_pat != NULL)
8777 ap->reg_prog = vim_regcomp(reg_pat, RE_MAGIC);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008778 vim_free(reg_pat);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008779 if (reg_pat == NULL || ap->reg_prog == NULL)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008780 {
8781 vim_free(ap->pat);
8782 vim_free(ap);
8783 return FAIL;
8784 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008785 }
8786 ap->cmds = NULL;
8787 *prev_ap = ap;
8788 ap->next = NULL;
8789 if (group == AUGROUP_ALL)
8790 ap->group = current_augroup;
8791 else
8792 ap->group = group;
8793 }
8794
8795 /*
8796 * Add the autocmd at the end of the AutoCmd list.
8797 */
8798 prev_ac = &(ap->cmds);
8799 while ((ac = *prev_ac) != NULL)
8800 prev_ac = &ac->next;
8801 ac = (AutoCmd *)alloc((unsigned)sizeof(AutoCmd));
8802 if (ac == NULL)
8803 return FAIL;
8804 ac->cmd = vim_strsave(cmd);
8805#ifdef FEAT_EVAL
8806 ac->scriptID = current_SID;
8807#endif
8808 if (ac->cmd == NULL)
8809 {
8810 vim_free(ac);
8811 return FAIL;
8812 }
8813 ac->next = NULL;
8814 *prev_ac = ac;
8815 ac->nested = nested;
8816 }
8817 }
8818
8819 au_cleanup(); /* may really delete removed patterns/commands now */
8820 return OK;
8821}
8822
8823/*
8824 * Implementation of ":doautocmd [group] event [fname]".
8825 * Return OK for success, FAIL for failure;
8826 */
8827 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008828do_doautocmd(
8829 char_u *arg,
Bram Moolenaar1610d052016-06-09 22:53:01 +02008830 int do_msg, /* give message for no matching autocmds? */
8831 int *did_something)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008832{
8833 char_u *fname;
8834 int nothing_done = TRUE;
8835 int group;
8836
Bram Moolenaar1610d052016-06-09 22:53:01 +02008837 if (did_something != NULL)
Bram Moolenaar76ae22f2016-06-13 20:00:29 +02008838 *did_something = FALSE;
Bram Moolenaar1610d052016-06-09 22:53:01 +02008839
Bram Moolenaar071d4272004-06-13 20:20:40 +00008840 /*
8841 * Check for a legal group name. If not, use AUGROUP_ALL.
8842 */
8843 group = au_get_grouparg(&arg);
8844 if (arg == NULL) /* out of memory */
8845 return FAIL;
8846
8847 if (*arg == '*')
8848 {
8849 EMSG(_("E217: Can't execute autocommands for ALL events"));
8850 return FAIL;
8851 }
8852
8853 /*
8854 * Scan over the events.
8855 * If we find an illegal name, return here, don't do anything.
8856 */
8857 fname = find_end_event(arg, group != AUGROUP_ALL);
8858 if (fname == NULL)
8859 return FAIL;
8860
8861 fname = skipwhite(fname);
8862
8863 /*
8864 * Loop over the events.
8865 */
Bram Moolenaarfaf29d72017-07-09 11:07:16 +02008866 while (*arg && !ends_excmd(*arg) && !VIM_ISWHITE(*arg))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008867 if (apply_autocmds_group(event_name2nr(arg, &arg),
8868 fname, NULL, TRUE, group, curbuf, NULL))
8869 nothing_done = FALSE;
8870
8871 if (nothing_done && do_msg)
8872 MSG(_("No matching autocommands"));
Bram Moolenaar1610d052016-06-09 22:53:01 +02008873 if (did_something != NULL)
8874 *did_something = !nothing_done;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008875
8876#ifdef FEAT_EVAL
8877 return aborting() ? FAIL : OK;
8878#else
8879 return OK;
8880#endif
8881}
8882
8883/*
8884 * ":doautoall": execute autocommands for each loaded buffer.
8885 */
8886 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008887ex_doautoall(exarg_T *eap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008888{
8889 int retval;
8890 aco_save_T aco;
8891 buf_T *buf;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008892 bufref_T bufref;
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008893 char_u *arg = eap->arg;
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008894 int call_do_modelines = check_nomodeline(&arg);
Bram Moolenaar1610d052016-06-09 22:53:01 +02008895 int did_aucmd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008896
8897 /*
8898 * This is a bit tricky: For some commands curwin->w_buffer needs to be
8899 * equal to curbuf, but for some buffers there may not be a window.
8900 * So we change the buffer for the current window for a moment. This
8901 * gives problems when the autocommands make changes to the list of
8902 * buffers or windows...
8903 */
Bram Moolenaar29323592016-07-24 22:04:11 +02008904 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008905 {
Bram Moolenaar3a847972008-07-08 09:36:58 +00008906 if (buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008907 {
8908 /* find a window for this buffer and save some values */
8909 aucmd_prepbuf(&aco, buf);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008910 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008911
8912 /* execute the autocommands for this buffer */
Bram Moolenaar1610d052016-06-09 22:53:01 +02008913 retval = do_doautocmd(arg, FALSE, &did_aucmd);
Bram Moolenaareeefcc72007-05-01 21:21:21 +00008914
Bram Moolenaar1610d052016-06-09 22:53:01 +02008915 if (call_do_modelines && did_aucmd)
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008916 {
8917 /* Execute the modeline settings, but don't set window-local
8918 * options if we are using the current window for another
8919 * buffer. */
8920 do_modelines(curwin == aucmd_win ? OPT_NOWIN : 0);
8921 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008922
8923 /* restore the current window */
8924 aucmd_restbuf(&aco);
8925
8926 /* stop if there is some error or buffer was deleted */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008927 if (retval == FAIL || !bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008928 break;
8929 }
8930 }
8931
8932 check_cursor(); /* just in case lines got deleted */
8933}
8934
8935/*
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008936 * Check *argp for <nomodeline>. When it is present return FALSE, otherwise
8937 * return TRUE and advance *argp to after it.
8938 * Thus return TRUE when do_modelines() should be called.
8939 */
8940 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008941check_nomodeline(char_u **argp)
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008942{
8943 if (STRNCMP(*argp, "<nomodeline>", 12) == 0)
8944 {
8945 *argp = skipwhite(*argp + 12);
8946 return FALSE;
8947 }
8948 return TRUE;
8949}
8950
8951/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008952 * Prepare for executing autocommands for (hidden) buffer "buf".
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008953 * Search for a visible window containing the current buffer. If there isn't
8954 * one then use "aucmd_win".
Bram Moolenaar071d4272004-06-13 20:20:40 +00008955 * Set "curbuf" and "curwin" to match "buf".
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00008956 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008957 */
8958 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008959aucmd_prepbuf(
8960 aco_save_T *aco, /* structure to save values in */
8961 buf_T *buf) /* new curbuf */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008962{
8963 win_T *win;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008964 int save_ea;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008965#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008966 int save_acd;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008967#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008968
8969 /* Find a window that is for the new buffer */
8970 if (buf == curbuf) /* be quick when buf is curbuf */
8971 win = curwin;
8972 else
Bram Moolenaar29323592016-07-24 22:04:11 +02008973 FOR_ALL_WINDOWS(win)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008974 if (win->w_buffer == buf)
8975 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008976
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008977 /* Allocate "aucmd_win" when needed. If this fails (out of memory) fall
8978 * back to using the current window. */
8979 if (win == NULL && aucmd_win == NULL)
8980 {
8981 win_alloc_aucmd_win();
8982 if (aucmd_win == NULL)
8983 win = curwin;
8984 }
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008985 if (win == NULL && aucmd_win_used)
8986 /* Strange recursive autocommand, fall back to using the current
8987 * window. Expect a few side effects... */
8988 win = curwin;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008989
8990 aco->save_curwin = curwin;
8991 aco->save_curbuf = curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008992 if (win != NULL)
8993 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008994 /* There is a window for "buf" in the current tab page, make it the
8995 * curwin. This is preferred, it has the least side effects (esp. if
8996 * "buf" is curbuf). */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008997 aco->use_aucmd_win = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008998 curwin = win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008999 }
9000 else
9001 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009002 /* There is no window for "buf", use "aucmd_win". To minimize the side
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02009003 * effects, insert it in the current tab page.
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009004 * Anything related to a window (e.g., setting folds) may have
9005 * unexpected results. */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009006 aco->use_aucmd_win = TRUE;
9007 aucmd_win_used = TRUE;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00009008 aucmd_win->w_buffer = buf;
Bram Moolenaarcdddaa42010-06-07 23:07:44 +02009009 aucmd_win->w_s = &buf->b_s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009010 ++buf->b_nwindows;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00009011 win_init_empty(aucmd_win); /* set cursor and topline to safe values */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009012
9013 /* Make sure w_localdir and globaldir are NULL to avoid a chdir() in
9014 * win_enter_ext(). */
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009015 vim_free(aucmd_win->w_localdir);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009016 aucmd_win->w_localdir = NULL;
9017 aco->globaldir = globaldir;
9018 globaldir = NULL;
9019
Bram Moolenaar071d4272004-06-13 20:20:40 +00009020
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00009021 /* Split the current window, put the aucmd_win in the upper half.
9022 * We don't want the BufEnter or WinEnter autocommands. */
9023 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009024 make_snapshot(SNAP_AUCMD_IDX);
9025 save_ea = p_ea;
9026 p_ea = FALSE;
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009027
Bram Moolenaar4033c552017-09-16 20:54:51 +02009028#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009029 /* Prevent chdir() call in win_enter_ext(), through do_autochdir(). */
9030 save_acd = p_acd;
9031 p_acd = FALSE;
Bram Moolenaar4033c552017-09-16 20:54:51 +02009032#endif
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009033
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009034 (void)win_split_ins(0, WSP_TOP, aucmd_win, 0);
9035 (void)win_comp_pos(); /* recompute window positions */
9036 p_ea = save_ea;
Bram Moolenaar4033c552017-09-16 20:54:51 +02009037#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009038 p_acd = save_acd;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009039#endif
Bram Moolenaar4033c552017-09-16 20:54:51 +02009040 unblock_autocmds();
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00009041 curwin = aucmd_win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009042 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009043 curbuf = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009044 aco->new_curwin = curwin;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009045 set_bufref(&aco->new_curbuf, curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009046}
9047
9048/*
9049 * Cleanup after executing autocommands for a (hidden) buffer.
9050 * Restore the window as it was (if possible).
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009051 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009052 */
9053 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009054aucmd_restbuf(
9055 aco_save_T *aco) /* structure holding saved values */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009056{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009057 int dummy;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009058
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009059 if (aco->use_aucmd_win)
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009060 {
9061 --curbuf->b_nwindows;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009062 /* Find "aucmd_win", it can't be closed, but it may be in another tab
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00009063 * page. Do not trigger autocommands here. */
9064 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009065 if (curwin != aucmd_win)
9066 {
9067 tabpage_T *tp;
9068 win_T *wp;
9069
9070 FOR_ALL_TAB_WINDOWS(tp, wp)
9071 {
9072 if (wp == aucmd_win)
9073 {
9074 if (tp != curtab)
Bram Moolenaar49e649f2013-05-06 04:50:35 +02009075 goto_tabpage_tp(tp, TRUE, TRUE);
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009076 win_goto(aucmd_win);
Bram Moolenaar28f29082012-02-11 23:45:37 +01009077 goto win_found;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009078 }
9079 }
9080 }
Bram Moolenaar28f29082012-02-11 23:45:37 +01009081win_found:
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009082
9083 /* Remove the window and frame from the tree of frames. */
9084 (void)winframe_remove(curwin, &dummy, NULL);
9085 win_remove(curwin, NULL);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009086 aucmd_win_used = FALSE;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009087 last_status(FALSE); /* may need to remove last status line */
Bram Moolenaar8c752bd2017-03-19 17:09:56 +01009088
9089 if (!valid_tabpage_win(curtab))
9090 /* no valid window in current tabpage */
9091 close_tabpage(curtab);
9092
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009093 restore_snapshot(SNAP_AUCMD_IDX, FALSE);
9094 (void)win_comp_pos(); /* recompute window positions */
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00009095 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009096
9097 if (win_valid(aco->save_curwin))
9098 curwin = aco->save_curwin;
9099 else
9100 /* Hmm, original window disappeared. Just use the first one. */
9101 curwin = firstwin;
Bram Moolenaar4033c552017-09-16 20:54:51 +02009102#ifdef FEAT_EVAL
Bram Moolenaar429fa852013-04-15 12:27:36 +02009103 vars_clear(&aucmd_win->w_vars->dv_hashtab); /* free all w: variables */
9104 hash_init(&aucmd_win->w_vars->dv_hashtab); /* re-use the hashtab */
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009105#endif
9106 curbuf = curwin->w_buffer;
9107
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009108 vim_free(globaldir);
9109 globaldir = aco->globaldir;
9110
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009111 /* the buffer contents may have changed */
9112 check_cursor();
9113 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
9114 {
9115 curwin->w_topline = curbuf->b_ml.ml_line_count;
9116#ifdef FEAT_DIFF
9117 curwin->w_topfill = 0;
9118#endif
9119 }
9120#if defined(FEAT_GUI)
9121 /* Hide the scrollbars from the aucmd_win and update. */
9122 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_LEFT], FALSE);
9123 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_RIGHT], FALSE);
9124 gui_may_update_scrollbars();
9125#endif
9126 }
9127 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00009128 {
9129 /* restore curwin */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009130 if (win_valid(aco->save_curwin))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009131 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009132 /* Restore the buffer which was previously edited by curwin, if
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009133 * it was changed, we are still the same window and the buffer is
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009134 * valid. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009135 if (curwin == aco->new_curwin
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009136 && curbuf != aco->new_curbuf.br_buf
9137 && bufref_valid(&aco->new_curbuf)
9138 && aco->new_curbuf.br_buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009139 {
Bram Moolenaar7da9c372012-04-30 17:04:52 +02009140# if defined(FEAT_SYN_HL) || defined(FEAT_SPELL)
9141 if (curwin->w_s == &curbuf->b_s)
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009142 curwin->w_s = &aco->new_curbuf.br_buf->b_s;
Bram Moolenaar7da9c372012-04-30 17:04:52 +02009143# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009144 --curbuf->b_nwindows;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009145 curbuf = aco->new_curbuf.br_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009146 curwin->w_buffer = curbuf;
9147 ++curbuf->b_nwindows;
9148 }
9149
9150 curwin = aco->save_curwin;
9151 curbuf = curwin->w_buffer;
Bram Moolenaar371932a2014-09-09 16:59:38 +02009152 /* In case the autocommand move the cursor to a position that that
9153 * not exist in curbuf. */
9154 check_cursor();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009155 }
9156 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009157}
9158
9159static int autocmd_nested = FALSE;
9160
9161/*
9162 * Execute autocommands for "event" and file name "fname".
9163 * Return TRUE if some commands were executed.
9164 */
9165 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009166apply_autocmds(
9167 event_T event,
9168 char_u *fname, /* NULL or empty means use actual file name */
9169 char_u *fname_io, /* fname to use for <afile> on cmdline */
9170 int force, /* when TRUE, ignore autocmd_busy */
9171 buf_T *buf) /* buffer for <abuf> */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009172{
9173 return apply_autocmds_group(event, fname, fname_io, force,
9174 AUGROUP_ALL, buf, NULL);
9175}
9176
9177/*
9178 * Like apply_autocmds(), but with extra "eap" argument. This takes care of
9179 * setting v:filearg.
9180 */
9181 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009182apply_autocmds_exarg(
9183 event_T event,
9184 char_u *fname,
9185 char_u *fname_io,
9186 int force,
9187 buf_T *buf,
9188 exarg_T *eap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009189{
9190 return apply_autocmds_group(event, fname, fname_io, force,
9191 AUGROUP_ALL, buf, eap);
9192}
9193
9194/*
9195 * Like apply_autocmds(), but handles the caller's retval. If the script
9196 * processing is being aborted or if retval is FAIL when inside a try
9197 * conditional, no autocommands are executed. If otherwise the autocommands
9198 * cause the script to be aborted, retval is set to FAIL.
9199 */
9200 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009201apply_autocmds_retval(
9202 event_T event,
9203 char_u *fname, /* NULL or empty means use actual file name */
9204 char_u *fname_io, /* fname to use for <afile> on cmdline */
9205 int force, /* when TRUE, ignore autocmd_busy */
9206 buf_T *buf, /* buffer for <abuf> */
9207 int *retval) /* pointer to caller's retval */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009208{
9209 int did_cmd;
9210
Bram Moolenaar1e015462005-09-25 22:16:38 +00009211#ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00009212 if (should_abort(*retval))
9213 return FALSE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00009214#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009215
9216 did_cmd = apply_autocmds_group(event, fname, fname_io, force,
9217 AUGROUP_ALL, buf, NULL);
Bram Moolenaar1e015462005-09-25 22:16:38 +00009218 if (did_cmd
9219#ifdef FEAT_EVAL
9220 && aborting()
9221#endif
9222 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00009223 *retval = FAIL;
9224 return did_cmd;
9225}
9226
Bram Moolenaard35f9712005-12-18 22:02:33 +00009227/*
9228 * Return TRUE when there is a CursorHold autocommand defined.
9229 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009230 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009231has_cursorhold(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009232{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009233 return (first_autopat[(int)(get_real_state() == NORMAL_BUSY
9234 ? EVENT_CURSORHOLD : EVENT_CURSORHOLDI)] != NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009235}
Bram Moolenaard35f9712005-12-18 22:02:33 +00009236
9237/*
9238 * Return TRUE if the CursorHold event can be triggered.
9239 */
9240 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009241trigger_cursorhold(void)
Bram Moolenaard35f9712005-12-18 22:02:33 +00009242{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009243 int state;
9244
Bram Moolenaar05334432011-07-20 18:29:39 +02009245 if (!did_cursorhold
9246 && has_cursorhold()
9247 && !Recording
9248 && typebuf.tb_len == 0
Bram Moolenaard29a9ee2006-09-14 09:07:34 +00009249#ifdef FEAT_INS_EXPAND
9250 && !ins_compl_active()
9251#endif
9252 )
Bram Moolenaar754b5602006-02-09 23:53:20 +00009253 {
9254 state = get_real_state();
9255 if (state == NORMAL_BUSY || (state & INSERT) != 0)
9256 return TRUE;
9257 }
9258 return FALSE;
Bram Moolenaard35f9712005-12-18 22:02:33 +00009259}
Bram Moolenaar754b5602006-02-09 23:53:20 +00009260
9261/*
9262 * Return TRUE when there is a CursorMoved autocommand defined.
9263 */
9264 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009265has_cursormoved(void)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009266{
9267 return (first_autopat[(int)EVENT_CURSORMOVED] != NULL);
9268}
9269
9270/*
9271 * Return TRUE when there is a CursorMovedI autocommand defined.
9272 */
9273 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009274has_cursormovedI(void)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009275{
9276 return (first_autopat[(int)EVENT_CURSORMOVEDI] != NULL);
9277}
Bram Moolenaar071d4272004-06-13 20:20:40 +00009278
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009279/*
Bram Moolenaar186628f2013-03-19 13:33:23 +01009280 * Return TRUE when there is a TextChanged autocommand defined.
9281 */
9282 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009283has_textchanged(void)
Bram Moolenaar186628f2013-03-19 13:33:23 +01009284{
9285 return (first_autopat[(int)EVENT_TEXTCHANGED] != NULL);
9286}
9287
9288/*
9289 * Return TRUE when there is a TextChangedI autocommand defined.
9290 */
9291 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009292has_textchangedI(void)
Bram Moolenaar186628f2013-03-19 13:33:23 +01009293{
9294 return (first_autopat[(int)EVENT_TEXTCHANGEDI] != NULL);
9295}
9296
9297/*
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009298 * Return TRUE when there is an InsertCharPre autocommand defined.
9299 */
9300 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009301has_insertcharpre(void)
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009302{
9303 return (first_autopat[(int)EVENT_INSERTCHARPRE] != NULL);
9304}
9305
Bram Moolenaard5005162014-08-22 23:05:54 +02009306/*
9307 * Return TRUE when there is an CmdUndefined autocommand defined.
9308 */
9309 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009310has_cmdundefined(void)
Bram Moolenaard5005162014-08-22 23:05:54 +02009311{
9312 return (first_autopat[(int)EVENT_CMDUNDEFINED] != NULL);
9313}
9314
9315/*
9316 * Return TRUE when there is an FuncUndefined autocommand defined.
9317 */
9318 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009319has_funcundefined(void)
Bram Moolenaard5005162014-08-22 23:05:54 +02009320{
9321 return (first_autopat[(int)EVENT_FUNCUNDEFINED] != NULL);
9322}
9323
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009324/*
9325 * Execute autocommands for "event" and file name "fname".
9326 * Return TRUE if some commands were executed.
9327 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009328 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009329apply_autocmds_group(
9330 event_T event,
9331 char_u *fname, /* NULL or empty means use actual file name */
9332 char_u *fname_io, /* fname to use for <afile> on cmdline, NULL means
Bram Moolenaar071d4272004-06-13 20:20:40 +00009333 use fname */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009334 int force, /* when TRUE, ignore autocmd_busy */
9335 int group, /* group ID, or AUGROUP_ALL */
9336 buf_T *buf, /* buffer for <abuf> */
9337 exarg_T *eap) /* command arguments */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009338{
9339 char_u *sfname = NULL; /* short file name */
9340 char_u *tail;
9341 int save_changed;
9342 buf_T *old_curbuf;
9343 int retval = FALSE;
9344 char_u *save_sourcing_name;
9345 linenr_T save_sourcing_lnum;
9346 char_u *save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009347 int save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009348 int save_autocmd_bufnr;
9349 char_u *save_autocmd_match;
9350 int save_autocmd_busy;
9351 int save_autocmd_nested;
9352 static int nesting = 0;
9353 AutoPatCmd patcmd;
9354 AutoPat *ap;
9355#ifdef FEAT_EVAL
9356 scid_T save_current_SID;
9357 void *save_funccalp;
9358 char_u *save_cmdarg;
9359 long save_cmdbang;
9360#endif
9361 static int filechangeshell_busy = FALSE;
Bram Moolenaar05159a02005-02-26 23:04:13 +00009362#ifdef FEAT_PROFILE
9363 proftime_T wait_time;
9364#endif
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009365 int did_save_redobuff = FALSE;
Bram Moolenaard4863aa2017-04-07 19:50:12 +02009366 save_redo_T save_redo;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009367
9368 /*
9369 * Quickly return if there are no autocommands for this event or
9370 * autocommands are blocked.
9371 */
Bram Moolenaarfaf29d72017-07-09 11:07:16 +02009372 if (event == NUM_EVENTS || first_autopat[(int)event] == NULL
9373 || autocmd_blocked > 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009374 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009375
9376 /*
9377 * When autocommands are busy, new autocommands are only executed when
9378 * explicitly enabled with the "nested" flag.
9379 */
9380 if (autocmd_busy && !(force || autocmd_nested))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009381 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009382
9383#ifdef FEAT_EVAL
9384 /*
Bram Moolenaar7263a772007-05-10 17:35:54 +00009385 * Quickly return when immediately aborting on error, or when an interrupt
Bram Moolenaar071d4272004-06-13 20:20:40 +00009386 * occurred or an exception was thrown but not caught.
9387 */
9388 if (aborting())
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009389 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009390#endif
9391
9392 /*
9393 * FileChangedShell never nests, because it can create an endless loop.
9394 */
Bram Moolenaar56718732006-03-15 22:53:57 +00009395 if (filechangeshell_busy && (event == EVENT_FILECHANGEDSHELL
9396 || event == EVENT_FILECHANGEDSHELLPOST))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009397 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009398
9399 /*
9400 * Ignore events in 'eventignore'.
9401 */
9402 if (event_ignored(event))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009403 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009404
9405 /*
9406 * Allow nesting of autocommands, but restrict the depth, because it's
9407 * possible to create an endless loop.
9408 */
9409 if (nesting == 10)
9410 {
9411 EMSG(_("E218: autocommand nesting too deep"));
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009412 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009413 }
9414
9415 /*
9416 * Check if these autocommands are disabled. Used when doing ":all" or
9417 * ":ball".
9418 */
9419 if ( (autocmd_no_enter
9420 && (event == EVENT_WINENTER || event == EVENT_BUFENTER))
9421 || (autocmd_no_leave
9422 && (event == EVENT_WINLEAVE || event == EVENT_BUFLEAVE)))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009423 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009424
9425 /*
9426 * Save the autocmd_* variables and info about the current buffer.
9427 */
9428 save_autocmd_fname = autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009429 save_autocmd_fname_full = autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009430 save_autocmd_bufnr = autocmd_bufnr;
9431 save_autocmd_match = autocmd_match;
9432 save_autocmd_busy = autocmd_busy;
9433 save_autocmd_nested = autocmd_nested;
9434 save_changed = curbuf->b_changed;
9435 old_curbuf = curbuf;
9436
9437 /*
9438 * Set the file name to be used for <afile>.
Bram Moolenaara0174af2008-01-02 20:08:25 +00009439 * Make a copy to avoid that changing a buffer name or directory makes it
9440 * invalid.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009441 */
9442 if (fname_io == NULL)
9443 {
Bram Moolenaar53744302015-07-17 17:38:22 +02009444 if (event == EVENT_COLORSCHEME || event == EVENT_OPTIONSET)
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009445 autocmd_fname = NULL;
Bram Moolenaarfaf29d72017-07-09 11:07:16 +02009446 else if (fname != NULL && !ends_excmd(*fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009447 autocmd_fname = fname;
9448 else if (buf != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009449 autocmd_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009450 else
9451 autocmd_fname = NULL;
9452 }
9453 else
9454 autocmd_fname = fname_io;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009455 if (autocmd_fname != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009456 autocmd_fname = vim_strsave(autocmd_fname);
9457 autocmd_fname_full = FALSE; /* call FullName_save() later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009458
9459 /*
9460 * Set the buffer number to be used for <abuf>.
9461 */
9462 if (buf == NULL)
9463 autocmd_bufnr = 0;
9464 else
9465 autocmd_bufnr = buf->b_fnum;
9466
9467 /*
9468 * When the file name is NULL or empty, use the file name of buffer "buf".
9469 * Always use the full path of the file name to match with, in case
9470 * "allow_dirs" is set.
9471 */
9472 if (fname == NULL || *fname == NUL)
9473 {
9474 if (buf == NULL)
9475 fname = NULL;
9476 else
9477 {
9478#ifdef FEAT_SYN_HL
9479 if (event == EVENT_SYNTAX)
9480 fname = buf->b_p_syn;
9481 else
9482#endif
9483 if (event == EVENT_FILETYPE)
9484 fname = buf->b_p_ft;
9485 else
9486 {
9487 if (buf->b_sfname != NULL)
9488 sfname = vim_strsave(buf->b_sfname);
9489 fname = buf->b_ffname;
9490 }
9491 }
9492 if (fname == NULL)
9493 fname = (char_u *)"";
9494 fname = vim_strsave(fname); /* make a copy, so we can change it */
9495 }
9496 else
9497 {
9498 sfname = vim_strsave(fname);
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009499 /* Don't try expanding FileType, Syntax, FuncUndefined, WindowID,
9500 * ColorScheme or QuickFixCmd* */
Bram Moolenaar7c626922005-02-07 22:01:03 +00009501 if (event == EVENT_FILETYPE
9502 || event == EVENT_SYNTAX
Bram Moolenaar5135d462009-04-29 16:03:38 +00009503 || event == EVENT_FUNCUNDEFINED
Bram Moolenaar7c626922005-02-07 22:01:03 +00009504 || event == EVENT_REMOTEREPLY
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00009505 || event == EVENT_SPELLFILEMISSING
Bram Moolenaar7c626922005-02-07 22:01:03 +00009506 || event == EVENT_QUICKFIXCMDPRE
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009507 || event == EVENT_COLORSCHEME
Bram Moolenaar53744302015-07-17 17:38:22 +02009508 || event == EVENT_OPTIONSET
Bram Moolenaar7c626922005-02-07 22:01:03 +00009509 || event == EVENT_QUICKFIXCMDPOST)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009510 fname = vim_strsave(fname);
9511 else
9512 fname = FullName_save(fname, FALSE);
9513 }
9514 if (fname == NULL) /* out of memory */
9515 {
9516 vim_free(sfname);
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009517 retval = FALSE;
9518 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009519 }
9520
9521#ifdef BACKSLASH_IN_FILENAME
9522 /*
9523 * Replace all backslashes with forward slashes. This makes the
9524 * autocommand patterns portable between Unix and MS-DOS.
9525 */
9526 if (sfname != NULL)
9527 forward_slash(sfname);
9528 forward_slash(fname);
9529#endif
9530
9531#ifdef VMS
9532 /* remove version for correct match */
9533 if (sfname != NULL)
9534 vms_remove_version(sfname);
9535 vms_remove_version(fname);
9536#endif
9537
9538 /*
9539 * Set the name to be used for <amatch>.
9540 */
9541 autocmd_match = fname;
9542
9543
9544 /* Don't redraw while doing auto commands. */
9545 ++RedrawingDisabled;
9546 save_sourcing_name = sourcing_name;
9547 sourcing_name = NULL; /* don't free this one */
9548 save_sourcing_lnum = sourcing_lnum;
9549 sourcing_lnum = 0; /* no line number here */
9550
9551#ifdef FEAT_EVAL
9552 save_current_SID = current_SID;
9553
Bram Moolenaar05159a02005-02-26 23:04:13 +00009554# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009555 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009556 prof_child_enter(&wait_time); /* doesn't count for the caller itself */
9557# endif
9558
Bram Moolenaar071d4272004-06-13 20:20:40 +00009559 /* Don't use local function variables, if called from a function */
9560 save_funccalp = save_funccal();
9561#endif
9562
9563 /*
9564 * When starting to execute autocommands, save the search patterns.
9565 */
9566 if (!autocmd_busy)
9567 {
9568 save_search_patterns();
Bram Moolenaar20ad69c2015-12-03 13:52:52 +01009569#ifdef FEAT_INS_EXPAND
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009570 if (!ins_compl_active())
Bram Moolenaar20ad69c2015-12-03 13:52:52 +01009571#endif
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009572 {
Bram Moolenaard4863aa2017-04-07 19:50:12 +02009573 saveRedobuff(&save_redo);
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009574 did_save_redobuff = TRUE;
9575 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009576 did_filetype = keep_filetype;
9577 }
9578
9579 /*
9580 * Note that we are applying autocmds. Some commands need to know.
9581 */
9582 autocmd_busy = TRUE;
9583 filechangeshell_busy = (event == EVENT_FILECHANGEDSHELL);
9584 ++nesting; /* see matching decrement below */
9585
9586 /* Remember that FileType was triggered. Used for did_filetype(). */
9587 if (event == EVENT_FILETYPE)
9588 did_filetype = TRUE;
9589
9590 tail = gettail(fname);
9591
9592 /* Find first autocommand that matches */
9593 patcmd.curpat = first_autopat[(int)event];
9594 patcmd.nextcmd = NULL;
9595 patcmd.group = group;
9596 patcmd.fname = fname;
9597 patcmd.sfname = sfname;
9598 patcmd.tail = tail;
9599 patcmd.event = event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009600 patcmd.arg_bufnr = autocmd_bufnr;
9601 patcmd.next = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009602 auto_next_pat(&patcmd, FALSE);
9603
9604 /* found one, start executing the autocommands */
9605 if (patcmd.curpat != NULL)
9606 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009607 /* add to active_apc_list */
9608 patcmd.next = active_apc_list;
9609 active_apc_list = &patcmd;
9610
Bram Moolenaar071d4272004-06-13 20:20:40 +00009611#ifdef FEAT_EVAL
9612 /* set v:cmdarg (only when there is a matching pattern) */
Bram Moolenaar22fcfad2016-07-01 18:17:26 +02009613 save_cmdbang = (long)get_vim_var_nr(VV_CMDBANG);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009614 if (eap != NULL)
9615 {
9616 save_cmdarg = set_cmdarg(eap, NULL);
9617 set_vim_var_nr(VV_CMDBANG, (long)eap->forceit);
9618 }
9619 else
9620 save_cmdarg = NULL; /* avoid gcc warning */
9621#endif
9622 retval = TRUE;
9623 /* mark the last pattern, to avoid an endless loop when more patterns
9624 * are added when executing autocommands */
9625 for (ap = patcmd.curpat; ap->next != NULL; ap = ap->next)
9626 ap->last = FALSE;
9627 ap->last = TRUE;
9628 check_lnums(TRUE); /* make sure cursor and topline are valid */
9629 do_cmdline(NULL, getnextac, (void *)&patcmd,
9630 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
9631#ifdef FEAT_EVAL
9632 if (eap != NULL)
9633 {
9634 (void)set_cmdarg(NULL, save_cmdarg);
9635 set_vim_var_nr(VV_CMDBANG, save_cmdbang);
9636 }
9637#endif
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009638 /* delete from active_apc_list */
9639 if (active_apc_list == &patcmd) /* just in case */
9640 active_apc_list = patcmd.next;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009641 }
9642
9643 --RedrawingDisabled;
9644 autocmd_busy = save_autocmd_busy;
9645 filechangeshell_busy = FALSE;
9646 autocmd_nested = save_autocmd_nested;
9647 vim_free(sourcing_name);
9648 sourcing_name = save_sourcing_name;
9649 sourcing_lnum = save_sourcing_lnum;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009650 vim_free(autocmd_fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009651 autocmd_fname = save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009652 autocmd_fname_full = save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009653 autocmd_bufnr = save_autocmd_bufnr;
9654 autocmd_match = save_autocmd_match;
9655#ifdef FEAT_EVAL
9656 current_SID = save_current_SID;
9657 restore_funccal(save_funccalp);
Bram Moolenaar05159a02005-02-26 23:04:13 +00009658# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009659 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009660 prof_child_exit(&wait_time);
9661# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009662#endif
9663 vim_free(fname);
9664 vim_free(sfname);
9665 --nesting; /* see matching increment above */
9666
9667 /*
9668 * When stopping to execute autocommands, restore the search patterns and
Bram Moolenaar3be85852014-06-12 14:01:31 +02009669 * the redo buffer. Free any buffers in the au_pending_free_buf list and
9670 * free any windows in the au_pending_free_win list.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009671 */
9672 if (!autocmd_busy)
9673 {
9674 restore_search_patterns();
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009675 if (did_save_redobuff)
Bram Moolenaard4863aa2017-04-07 19:50:12 +02009676 restoreRedobuff(&save_redo);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009677 did_filetype = FALSE;
Bram Moolenaar4c7ab1b2014-04-06 20:45:43 +02009678 while (au_pending_free_buf != NULL)
9679 {
9680 buf_T *b = au_pending_free_buf->b_next;
9681 vim_free(au_pending_free_buf);
9682 au_pending_free_buf = b;
9683 }
Bram Moolenaar3be85852014-06-12 14:01:31 +02009684 while (au_pending_free_win != NULL)
9685 {
9686 win_T *w = au_pending_free_win->w_next;
9687 vim_free(au_pending_free_win);
9688 au_pending_free_win = w;
9689 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009690 }
9691
9692 /*
9693 * Some events don't set or reset the Changed flag.
9694 * Check if still in the same buffer!
9695 */
9696 if (curbuf == old_curbuf
9697 && (event == EVENT_BUFREADPOST
9698 || event == EVENT_BUFWRITEPOST
9699 || event == EVENT_FILEAPPENDPOST
9700 || event == EVENT_VIMLEAVE
9701 || event == EVENT_VIMLEAVEPRE))
9702 {
9703#ifdef FEAT_TITLE
9704 if (curbuf->b_changed != save_changed)
9705 need_maketitle = TRUE;
9706#endif
9707 curbuf->b_changed = save_changed;
9708 }
9709
9710 au_cleanup(); /* may really delete removed patterns/commands now */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009711
9712BYPASS_AU:
9713 /* When wiping out a buffer make sure all its buffer-local autocommands
9714 * are deleted. */
9715 if (event == EVENT_BUFWIPEOUT && buf != NULL)
9716 aubuflocal_remove(buf);
9717
Bram Moolenaarc3691332016-04-20 12:49:49 +02009718 if (retval == OK && event == EVENT_FILETYPE)
9719 au_did_filetype = TRUE;
9720
Bram Moolenaar071d4272004-06-13 20:20:40 +00009721 return retval;
9722}
9723
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009724# ifdef FEAT_EVAL
9725static char_u *old_termresponse = NULL;
9726# endif
9727
9728/*
9729 * Block triggering autocommands until unblock_autocmd() is called.
9730 * Can be used recursively, so long as it's symmetric.
9731 */
9732 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009733block_autocmds(void)
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009734{
9735# ifdef FEAT_EVAL
9736 /* Remember the value of v:termresponse. */
9737 if (autocmd_blocked == 0)
9738 old_termresponse = get_vim_var_str(VV_TERMRESPONSE);
9739# endif
9740 ++autocmd_blocked;
9741}
9742
9743 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009744unblock_autocmds(void)
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009745{
9746 --autocmd_blocked;
9747
9748# ifdef FEAT_EVAL
9749 /* When v:termresponse was set while autocommands were blocked, trigger
9750 * the autocommands now. Esp. useful when executing a shell command
9751 * during startup (vimdiff). */
9752 if (autocmd_blocked == 0
9753 && get_vim_var_str(VV_TERMRESPONSE) != old_termresponse)
9754 apply_autocmds(EVENT_TERMRESPONSE, NULL, NULL, FALSE, curbuf);
9755# endif
9756}
9757
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009758 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009759is_autocmd_blocked(void)
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009760{
9761 return autocmd_blocked != 0;
9762}
9763
Bram Moolenaar071d4272004-06-13 20:20:40 +00009764/*
9765 * Find next autocommand pattern that matches.
9766 */
9767 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009768auto_next_pat(
9769 AutoPatCmd *apc,
9770 int stop_at_last) /* stop when 'last' flag is set */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009771{
9772 AutoPat *ap;
9773 AutoCmd *cp;
9774 char_u *name;
9775 char *s;
9776
9777 vim_free(sourcing_name);
9778 sourcing_name = NULL;
9779
9780 for (ap = apc->curpat; ap != NULL && !got_int; ap = ap->next)
9781 {
9782 apc->curpat = NULL;
9783
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009784 /* Only use a pattern when it has not been removed, has commands and
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009785 * the group matches. For buffer-local autocommands only check the
9786 * buffer number. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009787 if (ap->pat != NULL && ap->cmds != NULL
9788 && (apc->group == AUGROUP_ALL || apc->group == ap->group))
9789 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009790 /* execution-condition */
9791 if (ap->buflocal_nr == 0
Bram Moolenaardffa5b82014-11-19 16:38:07 +01009792 ? (match_file_pat(NULL, &ap->reg_prog, apc->fname,
Bram Moolenaar748bf032005-02-02 23:04:36 +00009793 apc->sfname, apc->tail, ap->allow_dirs))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009794 : ap->buflocal_nr == apc->arg_bufnr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009795 {
9796 name = event_nr2name(apc->event);
9797 s = _("%s Auto commands for \"%s\"");
9798 sourcing_name = alloc((unsigned)(STRLEN(s)
9799 + STRLEN(name) + ap->patlen + 1));
9800 if (sourcing_name != NULL)
9801 {
9802 sprintf((char *)sourcing_name, s,
9803 (char *)name, (char *)ap->pat);
9804 if (p_verbose >= 8)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009805 {
9806 verbose_enter();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009807 smsg((char_u *)_("Executing %s"), sourcing_name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009808 verbose_leave();
9809 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009810 }
9811
9812 apc->curpat = ap;
9813 apc->nextcmd = ap->cmds;
9814 /* mark last command */
9815 for (cp = ap->cmds; cp->next != NULL; cp = cp->next)
9816 cp->last = FALSE;
9817 cp->last = TRUE;
9818 }
9819 line_breakcheck();
9820 if (apc->curpat != NULL) /* found a match */
9821 break;
9822 }
9823 if (stop_at_last && ap->last)
9824 break;
9825 }
9826}
9827
9828/*
9829 * Get next autocommand command.
9830 * Called by do_cmdline() to get the next line for ":if".
9831 * Returns allocated string, or NULL for end of autocommands.
9832 */
Bram Moolenaar21691f82012-12-05 19:13:18 +01009833 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009834getnextac(int c UNUSED, void *cookie, int indent UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009835{
9836 AutoPatCmd *acp = (AutoPatCmd *)cookie;
9837 char_u *retval;
9838 AutoCmd *ac;
9839
9840 /* Can be called again after returning the last line. */
9841 if (acp->curpat == NULL)
9842 return NULL;
9843
9844 /* repeat until we find an autocommand to execute */
9845 for (;;)
9846 {
9847 /* skip removed commands */
9848 while (acp->nextcmd != NULL && acp->nextcmd->cmd == NULL)
9849 if (acp->nextcmd->last)
9850 acp->nextcmd = NULL;
9851 else
9852 acp->nextcmd = acp->nextcmd->next;
9853
9854 if (acp->nextcmd != NULL)
9855 break;
9856
9857 /* at end of commands, find next pattern that matches */
9858 if (acp->curpat->last)
9859 acp->curpat = NULL;
9860 else
9861 acp->curpat = acp->curpat->next;
9862 if (acp->curpat != NULL)
9863 auto_next_pat(acp, TRUE);
9864 if (acp->curpat == NULL)
9865 return NULL;
9866 }
9867
9868 ac = acp->nextcmd;
9869
9870 if (p_verbose >= 9)
9871 {
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009872 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009873 smsg((char_u *)_("autocommand %s"), ac->cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009874 msg_puts((char_u *)"\n"); /* don't overwrite this either */
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009875 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009876 }
9877 retval = vim_strsave(ac->cmd);
9878 autocmd_nested = ac->nested;
9879#ifdef FEAT_EVAL
9880 current_SID = ac->scriptID;
9881#endif
9882 if (ac->last)
9883 acp->nextcmd = NULL;
9884 else
9885 acp->nextcmd = ac->next;
9886 return retval;
9887}
9888
9889/*
9890 * Return TRUE if there is a matching autocommand for "fname".
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009891 * To account for buffer-local autocommands, function needs to know
9892 * in which buffer the file will be opened.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009893 */
9894 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009895has_autocmd(event_T event, char_u *sfname, buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009896{
9897 AutoPat *ap;
9898 char_u *fname;
9899 char_u *tail = gettail(sfname);
9900 int retval = FALSE;
9901
9902 fname = FullName_save(sfname, FALSE);
9903 if (fname == NULL)
9904 return FALSE;
9905
9906#ifdef BACKSLASH_IN_FILENAME
9907 /*
9908 * Replace all backslashes with forward slashes. This makes the
9909 * autocommand patterns portable between Unix and MS-DOS.
9910 */
9911 sfname = vim_strsave(sfname);
9912 if (sfname != NULL)
9913 forward_slash(sfname);
9914 forward_slash(fname);
9915#endif
9916
9917 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
9918 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009919 && (ap->buflocal_nr == 0
Bram Moolenaardffa5b82014-11-19 16:38:07 +01009920 ? match_file_pat(NULL, &ap->reg_prog,
Bram Moolenaar748bf032005-02-02 23:04:36 +00009921 fname, sfname, tail, ap->allow_dirs)
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009922 : buf != NULL && ap->buflocal_nr == buf->b_fnum
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009923 ))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009924 {
9925 retval = TRUE;
9926 break;
9927 }
9928
9929 vim_free(fname);
9930#ifdef BACKSLASH_IN_FILENAME
9931 vim_free(sfname);
9932#endif
9933
9934 return retval;
9935}
9936
9937#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
9938/*
9939 * Function given to ExpandGeneric() to obtain the list of autocommand group
9940 * names.
9941 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009942 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009943get_augroup_name(expand_T *xp UNUSED, int idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009944{
9945 if (idx == augroups.ga_len) /* add "END" add the end */
9946 return (char_u *)"END";
9947 if (idx >= augroups.ga_len) /* end of list */
9948 return NULL;
Bram Moolenaarb62cc362016-09-03 16:43:53 +02009949 if (AUGROUP_NAME(idx) == NULL || AUGROUP_NAME(idx) == get_deleted_augroup())
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02009950 /* skip deleted entries */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009951 return (char_u *)"";
9952 return AUGROUP_NAME(idx); /* return a name */
9953}
9954
9955static int include_groups = FALSE;
9956
9957 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009958set_context_in_autocmd(
9959 expand_T *xp,
9960 char_u *arg,
9961 int doautocmd) /* TRUE for :doauto*, FALSE for :autocmd */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009962{
9963 char_u *p;
9964 int group;
9965
9966 /* check for a group name, skip it if present */
9967 include_groups = FALSE;
9968 p = arg;
9969 group = au_get_grouparg(&arg);
9970 if (group == AUGROUP_ERROR)
9971 return NULL;
9972 /* If there only is a group name that's what we expand. */
Bram Moolenaar1c465442017-03-12 20:10:05 +01009973 if (*arg == NUL && group != AUGROUP_ALL && !VIM_ISWHITE(arg[-1]))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009974 {
9975 arg = p;
9976 group = AUGROUP_ALL;
9977 }
9978
9979 /* skip over event name */
Bram Moolenaar1c465442017-03-12 20:10:05 +01009980 for (p = arg; *p != NUL && !VIM_ISWHITE(*p); ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009981 if (*p == ',')
9982 arg = p + 1;
9983 if (*p == NUL)
9984 {
9985 if (group == AUGROUP_ALL)
9986 include_groups = TRUE;
9987 xp->xp_context = EXPAND_EVENTS; /* expand event name */
9988 xp->xp_pattern = arg;
9989 return NULL;
9990 }
9991
9992 /* skip over pattern */
9993 arg = skipwhite(p);
Bram Moolenaar1c465442017-03-12 20:10:05 +01009994 while (*arg && (!VIM_ISWHITE(*arg) || arg[-1] == '\\'))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009995 arg++;
9996 if (*arg)
9997 return arg; /* expand (next) command */
9998
9999 if (doautocmd)
10000 xp->xp_context = EXPAND_FILES; /* expand file names */
10001 else
10002 xp->xp_context = EXPAND_NOTHING; /* pattern is not expanded */
10003 return NULL;
10004}
10005
10006/*
10007 * Function given to ExpandGeneric() to obtain the list of event names.
10008 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010009 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010010get_event_name(expand_T *xp UNUSED, int idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010011{
10012 if (idx < augroups.ga_len) /* First list group names, if wanted */
10013 {
Bram Moolenaarf2c4c392016-07-29 20:50:24 +020010014 if (!include_groups || AUGROUP_NAME(idx) == NULL
Bram Moolenaarb62cc362016-09-03 16:43:53 +020010015 || AUGROUP_NAME(idx) == get_deleted_augroup())
Bram Moolenaar071d4272004-06-13 20:20:40 +000010016 return (char_u *)""; /* skip deleted entries */
10017 return AUGROUP_NAME(idx); /* return a name */
10018 }
10019 return (char_u *)event_names[idx - augroups.ga_len].name;
10020}
10021
10022#endif /* FEAT_CMDL_COMPL */
10023
10024/*
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010025 * Return TRUE if autocmd is supported.
10026 */
10027 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010028autocmd_supported(char_u *name)
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010029{
10030 char_u *p;
10031
10032 return (event_name2nr(name, &p) != NUM_EVENTS);
10033}
10034
10035/*
Bram Moolenaar195d6352005-12-19 22:08:24 +000010036 * Return TRUE if an autocommand is defined for a group, event and
10037 * pattern: The group can be omitted to accept any group. "event" and "pattern"
10038 * can be NULL to accept any event and pattern. "pattern" can be NULL to accept
10039 * any pattern. Buffer-local patterns <buffer> or <buffer=N> are accepted.
10040 * Used for:
10041 * exists("#Group") or
10042 * exists("#Group#Event") or
10043 * exists("#Group#Event#pat") or
10044 * exists("#Event") or
10045 * exists("#Event#pat")
Bram Moolenaar071d4272004-06-13 20:20:40 +000010046 */
10047 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010048au_exists(char_u *arg)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010049{
Bram Moolenaar195d6352005-12-19 22:08:24 +000010050 char_u *arg_save;
10051 char_u *pattern = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010052 char_u *event_name;
10053 char_u *p;
Bram Moolenaar754b5602006-02-09 23:53:20 +000010054 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010055 AutoPat *ap;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010056 buf_T *buflocal_buf = NULL;
Bram Moolenaar195d6352005-12-19 22:08:24 +000010057 int group;
10058 int retval = FALSE;
10059
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010060 /* Make a copy so that we can change the '#' chars to a NUL. */
Bram Moolenaar195d6352005-12-19 22:08:24 +000010061 arg_save = vim_strsave(arg);
10062 if (arg_save == NULL)
10063 return FALSE;
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010064 p = vim_strchr(arg_save, '#');
Bram Moolenaar195d6352005-12-19 22:08:24 +000010065 if (p != NULL)
10066 *p++ = NUL;
10067
10068 /* First, look for an autocmd group name */
10069 group = au_find_group(arg_save);
10070 if (group == AUGROUP_ERROR)
10071 {
10072 /* Didn't match a group name, assume the first argument is an event. */
10073 group = AUGROUP_ALL;
10074 event_name = arg_save;
10075 }
10076 else
10077 {
10078 if (p == NULL)
10079 {
10080 /* "Group": group name is present and it's recognized */
10081 retval = TRUE;
10082 goto theend;
10083 }
10084
10085 /* Must be "Group#Event" or "Group#Event#pat". */
10086 event_name = p;
10087 p = vim_strchr(event_name, '#');
10088 if (p != NULL)
10089 *p++ = NUL; /* "Group#Event#pat" */
10090 }
10091
10092 pattern = p; /* "pattern" is NULL when there is no pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010093
10094 /* find the index (enum) for the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010095 event = event_name2nr(event_name, &p);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010096
10097 /* return FALSE if the event name is not recognized */
Bram Moolenaar195d6352005-12-19 22:08:24 +000010098 if (event == NUM_EVENTS)
10099 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010100
10101 /* Find the first autocommand for this event.
10102 * If there isn't any, return FALSE;
10103 * If there is one and no pattern given, return TRUE; */
10104 ap = first_autopat[(int)event];
10105 if (ap == NULL)
Bram Moolenaar195d6352005-12-19 22:08:24 +000010106 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010107
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010108 /* if pattern is "<buffer>", special handling is needed which uses curbuf */
10109 /* for pattern "<buffer=N>, fnamecmp() will work fine */
Bram Moolenaar5b7880d2009-09-11 15:24:31 +000010110 if (pattern != NULL && STRICMP(pattern, "<buffer>") == 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010111 buflocal_buf = curbuf;
10112
Bram Moolenaar071d4272004-06-13 20:20:40 +000010113 /* Check if there is an autocommand with the given pattern. */
10114 for ( ; ap != NULL; ap = ap->next)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010115 /* only use a pattern when it has not been removed and has commands. */
10116 /* For buffer-local autocommands, fnamecmp() works fine. */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010117 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaar195d6352005-12-19 22:08:24 +000010118 && (group == AUGROUP_ALL || ap->group == group)
Bram Moolenaar5b7880d2009-09-11 15:24:31 +000010119 && (pattern == NULL
10120 || (buflocal_buf == NULL
10121 ? fnamecmp(ap->pat, pattern) == 0
10122 : ap->buflocal_nr == buflocal_buf->b_fnum)))
Bram Moolenaar195d6352005-12-19 22:08:24 +000010123 {
10124 retval = TRUE;
10125 break;
10126 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010127
Bram Moolenaar195d6352005-12-19 22:08:24 +000010128theend:
10129 vim_free(arg_save);
10130 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010131}
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010132
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010133#else /* FEAT_AUTOCMD */
10134
10135/*
10136 * Prepare for executing commands for (hidden) buffer "buf".
10137 * This is the non-autocommand version, it simply saves "curbuf" and sets
10138 * "curbuf" and "curwin" to match "buf".
10139 */
10140 void
Bram Moolenaard14e00e2016-01-31 17:30:51 +010010141aucmd_prepbuf(
10142 aco_save_T *aco, /* structure to save values in */
10143 buf_T *buf) /* new curbuf */
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010144{
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010145 aco->save_curbuf = curbuf;
10146 --curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010147 curbuf = buf;
10148 curwin->w_buffer = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010149 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010150}
10151
10152/*
10153 * Restore after executing commands for a (hidden) buffer.
10154 * This is the non-autocommand version.
10155 */
10156 void
Bram Moolenaard14e00e2016-01-31 17:30:51 +010010157aucmd_restbuf(
10158 aco_save_T *aco) /* structure holding saved values */
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010159{
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010160 --curbuf->b_nwindows;
10161 curbuf = aco->save_curbuf;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010162 curwin->w_buffer = curbuf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010163 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010164}
10165
Bram Moolenaar071d4272004-06-13 20:20:40 +000010166#endif /* FEAT_AUTOCMD */
10167
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010168
Bram Moolenaar071d4272004-06-13 20:20:40 +000010169#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN) || defined(PROTO)
10170/*
Bram Moolenaar748bf032005-02-02 23:04:36 +000010171 * Try matching a filename with a "pattern" ("prog" is NULL), or use the
10172 * precompiled regprog "prog" ("pattern" is NULL). That avoids calling
10173 * vim_regcomp() often.
Bram Moolenaar071d4272004-06-13 20:20:40 +000010174 * Used for autocommands and 'wildignore'.
10175 * Returns TRUE if there is a match, FALSE otherwise.
10176 */
Bram Moolenaardffa5b82014-11-19 16:38:07 +010010177 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010178match_file_pat(
10179 char_u *pattern, /* pattern to match with */
10180 regprog_T **prog, /* pre-compiled regprog or NULL */
10181 char_u *fname, /* full path of file name */
10182 char_u *sfname, /* short file name or NULL */
10183 char_u *tail, /* tail of path */
10184 int allow_dirs) /* allow matching with dir */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010185{
10186 regmatch_T regmatch;
10187 int result = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010188
Bram Moolenaar71afbfe2013-03-19 16:49:16 +010010189 regmatch.rm_ic = p_fic; /* ignore case if 'fileignorecase' is set */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010190 if (prog != NULL)
10191 regmatch.regprog = *prog;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010192 else
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010193 regmatch.regprog = vim_regcomp(pattern, RE_MAGIC);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010194
10195 /*
10196 * Try for a match with the pattern with:
10197 * 1. the full file name, when the pattern has a '/'.
10198 * 2. the short file name, when the pattern has a '/'.
10199 * 3. the tail of the file name, when the pattern has no '/'.
10200 */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010201 if (regmatch.regprog != NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +000010202 && ((allow_dirs
10203 && (vim_regexec(&regmatch, fname, (colnr_T)0)
10204 || (sfname != NULL
10205 && vim_regexec(&regmatch, sfname, (colnr_T)0))))
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010206 || (!allow_dirs && vim_regexec(&regmatch, tail, (colnr_T)0))))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010207 result = TRUE;
10208
Bram Moolenaardffa5b82014-11-19 16:38:07 +010010209 if (prog != NULL)
10210 *prog = regmatch.regprog;
10211 else
Bram Moolenaar473de612013-06-08 18:19:48 +020010212 vim_regfree(regmatch.regprog);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010213 return result;
10214}
10215#endif
10216
10217#if defined(FEAT_WILDIGN) || defined(PROTO)
10218/*
10219 * Return TRUE if a file matches with a pattern in "list".
10220 * "list" is a comma-separated list of patterns, like 'wildignore'.
10221 * "sfname" is the short file name or NULL, "ffname" the long file name.
10222 */
10223 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010224match_file_list(char_u *list, char_u *sfname, char_u *ffname)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010225{
10226 char_u buf[100];
10227 char_u *tail;
10228 char_u *regpat;
10229 char allow_dirs;
10230 int match;
10231 char_u *p;
10232
10233 tail = gettail(sfname);
10234
10235 /* try all patterns in 'wildignore' */
10236 p = list;
10237 while (*p)
10238 {
10239 copy_option_part(&p, buf, 100, ",");
10240 regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, FALSE);
10241 if (regpat == NULL)
10242 break;
Bram Moolenaar748bf032005-02-02 23:04:36 +000010243 match = match_file_pat(regpat, NULL, ffname, sfname,
10244 tail, (int)allow_dirs);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010245 vim_free(regpat);
10246 if (match)
10247 return TRUE;
10248 }
10249 return FALSE;
10250}
10251#endif
10252
10253/*
10254 * Convert the given pattern "pat" which has shell style wildcards in it, into
10255 * a regular expression, and return the result in allocated memory. If there
10256 * is a directory path separator to be matched, then TRUE is put in
10257 * allow_dirs, otherwise FALSE is put there -- webb.
10258 * Handle backslashes before special characters, like "\*" and "\ ".
10259 *
Bram Moolenaar071d4272004-06-13 20:20:40 +000010260 * Returns NULL when out of memory.
10261 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010262 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010263file_pat_to_reg_pat(
10264 char_u *pat,
10265 char_u *pat_end, /* first char after pattern or NULL */
10266 char *allow_dirs, /* Result passed back out in here */
10267 int no_bslash UNUSED) /* Don't use a backward slash as pathsep */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010268{
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010269 int size = 2; /* '^' at start, '$' at end */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010270 char_u *endp;
10271 char_u *reg_pat;
10272 char_u *p;
10273 int i;
10274 int nested = 0;
10275 int add_dollar = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010276
10277 if (allow_dirs != NULL)
10278 *allow_dirs = FALSE;
10279 if (pat_end == NULL)
10280 pat_end = pat + STRLEN(pat);
10281
Bram Moolenaar071d4272004-06-13 20:20:40 +000010282 for (p = pat; p < pat_end; p++)
10283 {
10284 switch (*p)
10285 {
10286 case '*':
10287 case '.':
10288 case ',':
10289 case '{':
10290 case '}':
10291 case '~':
10292 size += 2; /* extra backslash */
10293 break;
10294#ifdef BACKSLASH_IN_FILENAME
10295 case '\\':
10296 case '/':
10297 size += 4; /* could become "[\/]" */
10298 break;
10299#endif
10300 default:
10301 size++;
Bram Moolenaar2288afe2015-08-11 16:20:05 +020010302# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010303 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010304 {
10305 ++p;
10306 ++size;
10307 }
10308# endif
10309 break;
10310 }
10311 }
10312 reg_pat = alloc(size + 1);
10313 if (reg_pat == NULL)
10314 return NULL;
10315
Bram Moolenaar071d4272004-06-13 20:20:40 +000010316 i = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010317
10318 if (pat[0] == '*')
10319 while (pat[0] == '*' && pat < pat_end - 1)
10320 pat++;
10321 else
10322 reg_pat[i++] = '^';
10323 endp = pat_end - 1;
Bram Moolenaar8fee8782015-08-11 18:45:48 +020010324 if (endp >= pat && *endp == '*')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010325 {
10326 while (endp - pat > 0 && *endp == '*')
10327 endp--;
10328 add_dollar = FALSE;
10329 }
10330 for (p = pat; *p && nested >= 0 && p <= endp; p++)
10331 {
10332 switch (*p)
10333 {
10334 case '*':
10335 reg_pat[i++] = '.';
10336 reg_pat[i++] = '*';
Bram Moolenaar02743632005-07-25 20:42:36 +000010337 while (p[1] == '*') /* "**" matches like "*" */
10338 ++p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010339 break;
10340 case '.':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010341 case '~':
10342 reg_pat[i++] = '\\';
10343 reg_pat[i++] = *p;
10344 break;
10345 case '?':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010346 reg_pat[i++] = '.';
10347 break;
10348 case '\\':
10349 if (p[1] == NUL)
10350 break;
10351#ifdef BACKSLASH_IN_FILENAME
10352 if (!no_bslash)
10353 {
10354 /* translate:
10355 * "\x" to "\\x" e.g., "dir\file"
10356 * "\*" to "\\.*" e.g., "dir\*.c"
10357 * "\?" to "\\." e.g., "dir\??.c"
10358 * "\+" to "\+" e.g., "fileX\+.c"
10359 */
10360 if ((vim_isfilec(p[1]) || p[1] == '*' || p[1] == '?')
10361 && p[1] != '+')
10362 {
10363 reg_pat[i++] = '[';
10364 reg_pat[i++] = '\\';
10365 reg_pat[i++] = '/';
10366 reg_pat[i++] = ']';
10367 if (allow_dirs != NULL)
10368 *allow_dirs = TRUE;
10369 break;
10370 }
10371 }
10372#endif
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010373 /* Undo escaping from ExpandEscape():
10374 * foo\?bar -> foo?bar
10375 * foo\%bar -> foo%bar
10376 * foo\,bar -> foo,bar
10377 * foo\ bar -> foo bar
10378 * Don't unescape \, * and others that are also special in a
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010379 * regexp.
10380 * An escaped { must be unescaped since we use magic not
Bram Moolenaara946afe2013-08-02 15:22:39 +020010381 * verymagic. Use "\\\{n,m\}"" to get "\{n,m}".
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010382 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010383 if (*++p == '?'
10384#ifdef BACKSLASH_IN_FILENAME
10385 && no_bslash
10386#endif
10387 )
10388 reg_pat[i++] = '?';
10389 else
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010390 if (*p == ',' || *p == '%' || *p == '#'
Bram Moolenaar2288afe2015-08-11 16:20:05 +020010391 || vim_isspace(*p) || *p == '{' || *p == '}')
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010392 reg_pat[i++] = *p;
Bram Moolenaara946afe2013-08-02 15:22:39 +020010393 else if (*p == '\\' && p[1] == '\\' && p[2] == '{')
10394 {
10395 reg_pat[i++] = '\\';
10396 reg_pat[i++] = '{';
10397 p += 2;
10398 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010399 else
10400 {
10401 if (allow_dirs != NULL && vim_ispathsep(*p)
10402#ifdef BACKSLASH_IN_FILENAME
10403 && (!no_bslash || *p != '\\')
10404#endif
10405 )
10406 *allow_dirs = TRUE;
10407 reg_pat[i++] = '\\';
10408 reg_pat[i++] = *p;
10409 }
10410 break;
10411#ifdef BACKSLASH_IN_FILENAME
10412 case '/':
10413 reg_pat[i++] = '[';
10414 reg_pat[i++] = '\\';
10415 reg_pat[i++] = '/';
10416 reg_pat[i++] = ']';
10417 if (allow_dirs != NULL)
10418 *allow_dirs = TRUE;
10419 break;
10420#endif
10421 case '{':
10422 reg_pat[i++] = '\\';
10423 reg_pat[i++] = '(';
10424 nested++;
10425 break;
10426 case '}':
10427 reg_pat[i++] = '\\';
10428 reg_pat[i++] = ')';
10429 --nested;
10430 break;
10431 case ',':
10432 if (nested)
10433 {
10434 reg_pat[i++] = '\\';
10435 reg_pat[i++] = '|';
10436 }
10437 else
10438 reg_pat[i++] = ',';
10439 break;
10440 default:
10441# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010442 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010443 reg_pat[i++] = *p++;
10444 else
10445# endif
10446 if (allow_dirs != NULL && vim_ispathsep(*p))
10447 *allow_dirs = TRUE;
10448 reg_pat[i++] = *p;
10449 break;
10450 }
10451 }
10452 if (add_dollar)
10453 reg_pat[i++] = '$';
10454 reg_pat[i] = NUL;
10455 if (nested != 0)
10456 {
10457 if (nested < 0)
10458 EMSG(_("E219: Missing {."));
10459 else
10460 EMSG(_("E220: Missing }."));
10461 vim_free(reg_pat);
10462 reg_pat = NULL;
10463 }
10464 return reg_pat;
10465}
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010466
10467#if defined(EINTR) || defined(PROTO)
10468/*
10469 * Version of read() that retries when interrupted by EINTR (possibly
10470 * by a SIGWINCH).
10471 */
10472 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010473read_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010474{
10475 long ret;
10476
10477 for (;;)
10478 {
10479 ret = vim_read(fd, buf, bufsize);
10480 if (ret >= 0 || errno != EINTR)
10481 break;
10482 }
10483 return ret;
10484}
10485
10486/*
10487 * Version of write() that retries when interrupted by EINTR (possibly
10488 * by a SIGWINCH).
10489 */
10490 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010491write_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010492{
10493 long ret = 0;
10494 long wlen;
10495
10496 /* Repeat the write() so long it didn't fail, other than being interrupted
10497 * by a signal. */
10498 while (ret < (long)bufsize)
10499 {
Bram Moolenaar9c263032010-12-17 18:06:06 +010010500 wlen = vim_write(fd, (char *)buf + ret, bufsize - ret);
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010501 if (wlen < 0)
10502 {
10503 if (errno != EINTR)
10504 break;
10505 }
10506 else
10507 ret += wlen;
10508 }
10509 return ret;
10510}
10511#endif