blob: 87b85cf38652551a48a84dda7dabe024d1cd6524 [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
Bram Moolenaard0573012017-10-28 21:11:06 +020071# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +000072# 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
Bram Moolenaard0573012017-10-28 21:11:06 +0200130# ifdef MACOS_CONVERT
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
Bram Moolenaard0573012017-10-28 21:11:06 +02001091# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001092 /* 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
Bram Moolenaard0573012017-10-28 21:11:06 +02001277# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001278 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
Bram Moolenaar071d4272004-06-13 20:20:40 +00004203#ifdef VMS
4204 vms_remove_version(fname); /* remove version */
4205#endif
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00004206 /* Default: write the file directly. May write to a temp file for
Bram Moolenaar071d4272004-06-13 20:20:40 +00004207 * multi-byte conversion. */
4208 wfname = fname;
4209
4210#ifdef FEAT_MBYTE
4211 /* Check for forced 'fileencoding' from "++opt=val" argument. */
4212 if (eap != NULL && eap->force_enc != 0)
4213 {
4214 fenc = eap->cmd + eap->force_enc;
4215 fenc = enc_canonize(fenc);
4216 fenc_tofree = fenc;
4217 }
4218 else
4219 fenc = buf->b_p_fenc;
4220
4221 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004222 * Check if the file needs to be converted.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004223 */
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004224 converted = need_conversion(fenc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004225
4226 /*
4227 * Check if UTF-8 to UCS-2/4 or Latin1 conversion needs to be done. Or
4228 * Latin1 to Unicode conversion. This is handled in buf_write_bytes().
4229 * Prepare the flags for it and allocate bw_conv_buf when needed.
4230 */
4231 if (converted && (enc_utf8 || STRCMP(p_enc, "latin1") == 0))
4232 {
4233 wb_flags = get_fio_flags(fenc);
4234 if (wb_flags & (FIO_UCS2 | FIO_UCS4 | FIO_UTF16 | FIO_UTF8))
4235 {
4236 /* Need to allocate a buffer to translate into. */
4237 if (wb_flags & (FIO_UCS2 | FIO_UTF16 | FIO_UTF8))
4238 write_info.bw_conv_buflen = bufsize * 2;
4239 else /* FIO_UCS4 */
4240 write_info.bw_conv_buflen = bufsize * 4;
4241 write_info.bw_conv_buf
4242 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4243 if (write_info.bw_conv_buf == NULL)
4244 end = 0;
4245 }
4246 }
4247
4248# ifdef WIN3264
4249 if (converted && wb_flags == 0 && (wb_flags = get_win_fio_flags(fenc)) != 0)
4250 {
4251 /* Convert UTF-8 -> UCS-2 and UCS-2 -> DBCS. Worst-case * 4: */
4252 write_info.bw_conv_buflen = bufsize * 4;
4253 write_info.bw_conv_buf
4254 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4255 if (write_info.bw_conv_buf == NULL)
4256 end = 0;
4257 }
4258# endif
4259
Bram Moolenaard0573012017-10-28 21:11:06 +02004260# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00004261 if (converted && wb_flags == 0 && (wb_flags = get_mac_fio_flags(fenc)) != 0)
4262 {
4263 write_info.bw_conv_buflen = bufsize * 3;
4264 write_info.bw_conv_buf
4265 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4266 if (write_info.bw_conv_buf == NULL)
4267 end = 0;
4268 }
4269# endif
4270
4271# if defined(FEAT_EVAL) || defined(USE_ICONV)
4272 if (converted && wb_flags == 0)
4273 {
4274# ifdef USE_ICONV
4275 /*
4276 * Use iconv() conversion when conversion is needed and it's not done
4277 * internally.
4278 */
4279 write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc,
4280 enc_utf8 ? (char_u *)"utf-8" : p_enc);
4281 if (write_info.bw_iconv_fd != (iconv_t)-1)
4282 {
4283 /* We're going to use iconv(), allocate a buffer to convert in. */
4284 write_info.bw_conv_buflen = bufsize * ICONV_MULT;
4285 write_info.bw_conv_buf
4286 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4287 if (write_info.bw_conv_buf == NULL)
4288 end = 0;
4289 write_info.bw_first = TRUE;
4290 }
4291# ifdef FEAT_EVAL
4292 else
4293# endif
4294# endif
4295
4296# ifdef FEAT_EVAL
4297 /*
4298 * When the file needs to be converted with 'charconvert' after
4299 * writing, write to a temp file instead and let the conversion
4300 * overwrite the original file.
4301 */
4302 if (*p_ccv != NUL)
4303 {
Bram Moolenaare5c421c2015-03-31 13:33:08 +02004304 wfname = vim_tempname('w', FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004305 if (wfname == NULL) /* Can't write without a tempfile! */
4306 {
4307 errmsg = (char_u *)_("E214: Can't find temp file for writing");
4308 goto restore_backup;
4309 }
4310 }
4311# endif
4312 }
4313# endif
4314 if (converted && wb_flags == 0
4315# ifdef USE_ICONV
4316 && write_info.bw_iconv_fd == (iconv_t)-1
4317# endif
4318# ifdef FEAT_EVAL
4319 && wfname == fname
4320# endif
4321 )
4322 {
4323 if (!forceit)
4324 {
4325 errmsg = (char_u *)_("E213: Cannot convert (add ! to write without conversion)");
4326 goto restore_backup;
4327 }
4328 notconverted = TRUE;
4329 }
4330#endif
4331
4332 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004333 * If conversion is taking place, we may first pretend to write and check
4334 * for conversion errors. Then loop again to write for real.
4335 * When not doing conversion this writes for real right away.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004336 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004337 for (checking_conversion = TRUE; ; checking_conversion = FALSE)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004338 {
4339 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004340 * There is no need to check conversion when:
4341 * - there is no conversion
4342 * - we make a backup file, that can be restored in case of conversion
4343 * failure.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004344 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004345#ifdef FEAT_MBYTE
4346 if (!converted || dobackup)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004347#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004348 checking_conversion = FALSE;
4349
4350 if (checking_conversion)
4351 {
4352 /* Make sure we don't write anything. */
4353 fd = -1;
4354 write_info.bw_fd = fd;
4355 }
4356 else
4357 {
4358 /*
4359 * Open the file "wfname" for writing.
4360 * We may try to open the file twice: If we can't write to the file
4361 * and forceit is TRUE we delete the existing file and try to
4362 * create a new one. If this still fails we may have lost the
4363 * original file! (this may happen when the user reached his
4364 * quotum for number of files).
4365 * Appending will fail if the file does not exist and forceit is
4366 * FALSE.
4367 */
4368 while ((fd = mch_open((char *)wfname, O_WRONLY | O_EXTRA | (append
4369 ? (forceit ? (O_APPEND | O_CREAT) : O_APPEND)
4370 : (O_CREAT | O_TRUNC))
4371 , perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004372 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004373 /*
4374 * A forced write will try to create a new file if the old one
4375 * is still readonly. This may also happen when the directory
4376 * is read-only. In that case the mch_remove() will fail.
4377 */
4378 if (errmsg == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004379 {
4380#ifdef UNIX
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004381 stat_T st;
4382
4383 /* Don't delete the file when it's a hard or symbolic link.
4384 */
4385 if ((!newfile && st_old.st_nlink > 1)
4386 || (mch_lstat((char *)fname, &st) == 0
4387 && (st.st_dev != st_old.st_dev
4388 || st.st_ino != st_old.st_ino)))
4389 errmsg = (char_u *)_("E166: Can't open linked file for writing");
4390 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004391#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004392 {
4393 errmsg = (char_u *)_("E212: Can't open file for writing");
4394 if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL
4395 && perm >= 0)
4396 {
4397#ifdef UNIX
4398 /* we write to the file, thus it should be marked
4399 writable after all */
4400 if (!(perm & 0200))
4401 made_writable = TRUE;
4402 perm |= 0200;
4403 if (st_old.st_uid != getuid()
4404 || st_old.st_gid != getgid())
4405 perm &= 0777;
4406#endif
4407 if (!append) /* don't remove when appending */
4408 mch_remove(wfname);
4409 continue;
4410 }
4411 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004412 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004413
4414restore_backup:
Bram Moolenaar071d4272004-06-13 20:20:40 +00004415 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004416 stat_T st;
4417
Bram Moolenaar071d4272004-06-13 20:20:40 +00004418 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004419 * If we failed to open the file, we don't need a backup.
4420 * Throw it away. If we moved or removed the original file
4421 * try to put the backup in its place.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004422 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004423 if (backup != NULL && wfname == fname)
4424 {
4425 if (backup_copy)
4426 {
4427 /*
4428 * There is a small chance that we removed the
4429 * original, try to move the copy in its place.
4430 * This may not work if the vim_rename() fails.
4431 * In that case we leave the copy around.
4432 */
4433 /* If file does not exist, put the copy in its
4434 * place */
4435 if (mch_stat((char *)fname, &st) < 0)
4436 vim_rename(backup, fname);
4437 /* if original file does exist throw away the copy
4438 */
4439 if (mch_stat((char *)fname, &st) >= 0)
4440 mch_remove(backup);
4441 }
4442 else
4443 {
4444 /* try to put the original file back */
4445 vim_rename(backup, fname);
4446 }
4447 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004448
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004449 /* if original file no longer exists give an extra warning
4450 */
4451 if (!newfile && mch_stat((char *)fname, &st) < 0)
4452 end = 0;
4453 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004454
4455#ifdef FEAT_MBYTE
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004456 if (wfname != fname)
4457 vim_free(wfname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004458#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004459 goto fail;
4460 }
4461 write_info.bw_fd = fd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004462
Bram Moolenaard0573012017-10-28 21:11:06 +02004463#if defined(WIN3264)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004464 if (backup != NULL && overwriting && !append)
4465 {
4466 if (backup_copy)
4467 (void)mch_copy_file_attribute(wfname, backup);
4468 else
4469 (void)mch_copy_file_attribute(backup, wfname);
4470 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004471
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004472 if (!overwriting && !append)
4473 {
4474 if (buf->b_ffname != NULL)
4475 (void)mch_copy_file_attribute(buf->b_ffname, wfname);
4476 /* Should copy resource fork */
4477 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004478#endif
4479
Bram Moolenaar071d4272004-06-13 20:20:40 +00004480#ifdef FEAT_CRYPT
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004481 if (*buf->b_p_key != NUL && !filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004482 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004483 char_u *header;
4484 int header_len;
4485
4486 buf->b_cryptstate = crypt_create_for_writing(
4487 crypt_get_method_nr(buf),
4488 buf->b_p_key, &header, &header_len);
4489 if (buf->b_cryptstate == NULL || header == NULL)
4490 end = 0;
4491 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004492 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004493 /* Write magic number, so that Vim knows how this file is
4494 * encrypted when reading it back. */
4495 write_info.bw_buf = header;
4496 write_info.bw_len = header_len;
4497 write_info.bw_flags = FIO_NOCONVERT;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004498 if (buf_write_bytes(&write_info) == FAIL)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004499 end = 0;
4500 wb_flags |= FIO_ENCRYPTED;
4501 vim_free(header);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004502 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004503 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004504#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004505 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004506 errmsg = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004507
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004508 write_info.bw_buf = buffer;
4509 nchars = 0;
4510
4511 /* use "++bin", "++nobin" or 'binary' */
4512 if (eap != NULL && eap->force_bin != 0)
4513 write_bin = (eap->force_bin == FORCE_BIN);
4514 else
4515 write_bin = buf->b_p_bin;
4516
4517#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004518 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004519 * The BOM is written just after the encryption magic number.
4520 * Skip it when appending and the file already existed, the BOM only
4521 * makes sense at the start of the file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004522 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004523 if (buf->b_p_bomb && !write_bin && (!append || perm < 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004524 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004525 write_info.bw_len = make_bom(buffer, fenc);
4526 if (write_info.bw_len > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004527 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004528 /* don't convert, do encryption */
4529 write_info.bw_flags = FIO_NOCONVERT | wb_flags;
4530 if (buf_write_bytes(&write_info) == FAIL)
4531 end = 0;
4532 else
4533 nchars += write_info.bw_len;
4534 }
4535 }
4536 write_info.bw_start_lnum = start;
4537#endif
4538
4539#ifdef FEAT_PERSISTENT_UNDO
4540 write_undo_file = (buf->b_p_udf
4541 && overwriting
4542 && !append
4543 && !filtering
4544 && reset_changed
4545 && !checking_conversion);
4546 if (write_undo_file)
4547 /* Prepare for computing the hash value of the text. */
4548 sha256_start(&sha_ctx);
4549#endif
4550
4551 write_info.bw_len = bufsize;
4552#ifdef HAS_BW_FLAGS
4553 write_info.bw_flags = wb_flags;
4554#endif
4555 fileformat = get_fileformat_force(buf, eap);
4556 s = buffer;
4557 len = 0;
4558 for (lnum = start; lnum <= end; ++lnum)
4559 {
4560 /*
4561 * The next while loop is done once for each character written.
4562 * Keep it fast!
4563 */
4564 ptr = ml_get_buf(buf, lnum, FALSE) - 1;
4565#ifdef FEAT_PERSISTENT_UNDO
4566 if (write_undo_file)
4567 sha256_update(&sha_ctx, ptr + 1,
4568 (UINT32_T)(STRLEN(ptr + 1) + 1));
4569#endif
4570 while ((c = *++ptr) != NUL)
4571 {
4572 if (c == NL)
4573 *s = NUL; /* replace newlines with NULs */
4574 else if (c == CAR && fileformat == EOL_MAC)
4575 *s = NL; /* Mac: replace CRs with NLs */
4576 else
4577 *s = c;
4578 ++s;
4579 if (++len != bufsize)
4580 continue;
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004581 if (buf_write_bytes(&write_info) == FAIL)
4582 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004583 end = 0; /* write error: break loop */
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004584 break;
4585 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004586 nchars += bufsize;
4587 s = buffer;
4588 len = 0;
4589#ifdef FEAT_MBYTE
4590 write_info.bw_start_lnum = lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004591#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004592 }
4593 /* write failed or last line has no EOL: stop here */
4594 if (end == 0
4595 || (lnum == end
4596 && (write_bin || !buf->b_p_fixeol)
4597 && (lnum == buf->b_no_eol_lnum
4598 || (lnum == buf->b_ml.ml_line_count
4599 && !buf->b_p_eol))))
4600 {
4601 ++lnum; /* written the line, count it */
4602 no_eol = TRUE;
4603 break;
4604 }
4605 if (fileformat == EOL_UNIX)
4606 *s++ = NL;
4607 else
4608 {
4609 *s++ = CAR; /* EOL_MAC or EOL_DOS: write CR */
4610 if (fileformat == EOL_DOS) /* write CR-NL */
4611 {
4612 if (++len == bufsize)
4613 {
4614 if (buf_write_bytes(&write_info) == FAIL)
4615 {
4616 end = 0; /* write error: break loop */
4617 break;
4618 }
4619 nchars += bufsize;
4620 s = buffer;
4621 len = 0;
4622 }
4623 *s++ = NL;
4624 }
4625 }
4626 if (++len == bufsize && end)
4627 {
4628 if (buf_write_bytes(&write_info) == FAIL)
4629 {
4630 end = 0; /* write error: break loop */
4631 break;
4632 }
4633 nchars += bufsize;
4634 s = buffer;
4635 len = 0;
4636
4637 ui_breakcheck();
4638 if (got_int)
4639 {
4640 end = 0; /* Interrupted, break loop */
4641 break;
4642 }
4643 }
4644#ifdef VMS
4645 /*
4646 * On VMS there is a problem: newlines get added when writing
4647 * blocks at a time. Fix it by writing a line at a time.
4648 * This is much slower!
4649 * Explanation: VAX/DECC RTL insists that records in some RMS
4650 * structures end with a newline (carriage return) character, and
4651 * if they don't it adds one.
4652 * With other RMS structures it works perfect without this fix.
4653 */
4654 if (buf->b_fab_rfm == FAB$C_VFC
4655 || ((buf->b_fab_rat & (FAB$M_FTN | FAB$M_CR)) != 0))
4656 {
4657 int b2write;
4658
4659 buf->b_fab_mrs = (buf->b_fab_mrs == 0
4660 ? MIN(4096, bufsize)
4661 : MIN(buf->b_fab_mrs, bufsize));
4662
4663 b2write = len;
4664 while (b2write > 0)
4665 {
4666 write_info.bw_len = MIN(b2write, buf->b_fab_mrs);
4667 if (buf_write_bytes(&write_info) == FAIL)
4668 {
4669 end = 0;
4670 break;
4671 }
4672 b2write -= MIN(b2write, buf->b_fab_mrs);
4673 }
4674 write_info.bw_len = bufsize;
4675 nchars += len;
4676 s = buffer;
4677 len = 0;
4678 }
4679#endif
4680 }
4681 if (len > 0 && end > 0)
4682 {
4683 write_info.bw_len = len;
4684 if (buf_write_bytes(&write_info) == FAIL)
4685 end = 0; /* write error */
4686 nchars += len;
4687 }
4688
4689 /* Stop when writing done or an error was encountered. */
4690 if (!checking_conversion || end == 0)
4691 break;
4692
4693 /* If no error happened until now, writing should be ok, so loop to
4694 * really write the buffer. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004695 }
4696
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004697 /* If we started writing, finish writing. Also when an error was
4698 * encountered. */
4699 if (!checking_conversion)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004700 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004701#if defined(UNIX) && defined(HAVE_FSYNC)
4702 /*
4703 * On many journalling file systems there is a bug that causes both the
4704 * original and the backup file to be lost when halting the system
4705 * right after writing the file. That's because only the meta-data is
4706 * journalled. Syncing the file slows down the system, but assures it
4707 * has been written to disk and we don't lose it.
4708 * For a device do try the fsync() but don't complain if it does not
4709 * work (could be a pipe).
4710 * If the 'fsync' option is FALSE, don't fsync(). Useful for laptops.
4711 */
4712 if (p_fs && fsync(fd) != 0 && !device)
4713 {
4714 errmsg = (char_u *)_("E667: Fsync failed");
4715 end = 0;
4716 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004717#endif
4718
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004719#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004720 /* Probably need to set the security context. */
4721 if (!backup_copy)
4722 mch_copy_sec(backup, wfname);
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004723#endif
4724
Bram Moolenaara5792f52005-11-23 21:25:05 +00004725#ifdef UNIX
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004726 /* When creating a new file, set its owner/group to that of the
4727 * original file. Get the new device and inode number. */
4728 if (backup != NULL && !backup_copy)
Bram Moolenaara5792f52005-11-23 21:25:05 +00004729 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004730# ifdef HAVE_FCHOWN
4731 stat_T st;
4732
4733 /* don't change the owner when it's already OK, some systems remove
4734 * permission or ACL stuff */
4735 if (mch_stat((char *)wfname, &st) < 0
4736 || st.st_uid != st_old.st_uid
4737 || st.st_gid != st_old.st_gid)
4738 {
4739 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
4740 if (perm >= 0) /* set permission again, may have changed */
4741 (void)mch_setperm(wfname, perm);
4742 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00004743# endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004744 buf_setino(buf);
4745 }
4746 else if (!buf->b_dev_valid)
4747 /* Set the inode when creating a new file. */
4748 buf_setino(buf);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004749#endif
4750
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004751 if (close(fd) != 0)
4752 {
4753 errmsg = (char_u *)_("E512: Close failed");
4754 end = 0;
4755 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004756
4757#ifdef UNIX
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004758 if (made_writable)
4759 perm &= ~0200; /* reset 'w' bit for security reasons */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004760#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004761 if (perm >= 0) /* set perm. of new file same as old file */
4762 (void)mch_setperm(wfname, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004763#ifdef HAVE_ACL
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004764 /*
4765 * Probably need to set the ACL before changing the user (can't set the
4766 * ACL on a file the user doesn't own).
4767 * On Solaris, with ZFS and the aclmode property set to "discard" (the
4768 * default), chmod() discards all part of a file's ACL that don't
4769 * represent the mode of the file. It's non-trivial for us to discover
4770 * whether we're in that situation, so we simply always re-set the ACL.
4771 */
Bram Moolenaarda412772016-07-14 20:37:07 +02004772# ifndef HAVE_SOLARIS_ZFS_ACL
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004773 if (!backup_copy)
Bram Moolenaarda412772016-07-14 20:37:07 +02004774# endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004775 mch_set_acl(wfname, acl);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004776#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004777#ifdef FEAT_CRYPT
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004778 if (buf->b_cryptstate != NULL)
4779 {
4780 crypt_free_state(buf->b_cryptstate);
4781 buf->b_cryptstate = NULL;
4782 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004783#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004784
Bram Moolenaar071d4272004-06-13 20:20:40 +00004785#if defined(FEAT_MBYTE) && defined(FEAT_EVAL)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004786 if (wfname != fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004787 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004788 /*
4789 * The file was written to a temp file, now it needs to be
4790 * converted with 'charconvert' to (overwrite) the output file.
4791 */
4792 if (end != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004793 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004794 if (eval_charconvert(enc_utf8 ? (char_u *)"utf-8" : p_enc,
4795 fenc, wfname, fname) == FAIL)
4796 {
4797 write_info.bw_conv_error = TRUE;
4798 end = 0;
4799 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004800 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004801 mch_remove(wfname);
4802 vim_free(wfname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004803 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004804#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004805 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004806
4807 if (end == 0)
4808 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004809 /*
4810 * Error encountered.
4811 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004812 if (errmsg == NULL)
4813 {
4814#ifdef FEAT_MBYTE
4815 if (write_info.bw_conv_error)
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004816 {
4817 if (write_info.bw_conv_error_lnum == 0)
4818 errmsg = (char_u *)_("E513: write error, conversion failed (make 'fenc' empty to override)");
4819 else
4820 {
4821 errmsg_allocated = TRUE;
4822 errmsg = alloc(300);
4823 vim_snprintf((char *)errmsg, 300, _("E513: write error, conversion failed in line %ld (make 'fenc' empty to override)"),
4824 (long)write_info.bw_conv_error_lnum);
4825 }
4826 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004827 else
4828#endif
4829 if (got_int)
4830 errmsg = (char_u *)_(e_interr);
4831 else
4832 errmsg = (char_u *)_("E514: write error (file system full?)");
4833 }
4834
4835 /*
4836 * If we have a backup file, try to put it in place of the new file,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004837 * because the new file is probably corrupt. This avoids losing the
Bram Moolenaar071d4272004-06-13 20:20:40 +00004838 * original file when trying to make a backup when writing the file a
4839 * second time.
4840 * When "backup_copy" is set we need to copy the backup over the new
4841 * file. Otherwise rename the backup file.
4842 * If this is OK, don't give the extra warning message.
4843 */
4844 if (backup != NULL)
4845 {
4846 if (backup_copy)
4847 {
4848 /* This may take a while, if we were interrupted let the user
4849 * know we got the message. */
4850 if (got_int)
4851 {
4852 MSG(_(e_interr));
4853 out_flush();
4854 }
4855 if ((fd = mch_open((char *)backup, O_RDONLY | O_EXTRA, 0)) >= 0)
4856 {
4857 if ((write_info.bw_fd = mch_open((char *)fname,
Bram Moolenaar9be038d2005-03-08 22:34:32 +00004858 O_WRONLY | O_CREAT | O_TRUNC | O_EXTRA,
4859 perm & 0777)) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004860 {
4861 /* copy the file. */
4862 write_info.bw_buf = smallbuf;
4863#ifdef HAS_BW_FLAGS
4864 write_info.bw_flags = FIO_NOCONVERT;
4865#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004866 while ((write_info.bw_len = read_eintr(fd, smallbuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004867 SMBUFSIZE)) > 0)
4868 if (buf_write_bytes(&write_info) == FAIL)
4869 break;
4870
4871 if (close(write_info.bw_fd) >= 0
4872 && write_info.bw_len == 0)
4873 end = 1; /* success */
4874 }
4875 close(fd); /* ignore errors for closing read file */
4876 }
4877 }
4878 else
4879 {
4880 if (vim_rename(backup, fname) == 0)
4881 end = 1;
4882 }
4883 }
4884 goto fail;
4885 }
4886
4887 lnum -= start; /* compute number of written lines */
4888 --no_wait_return; /* may wait for return now */
4889
4890#if !(defined(UNIX) || defined(VMS))
4891 fname = sfname; /* use shortname now, for the messages */
4892#endif
4893 if (!filtering)
4894 {
4895 msg_add_fname(buf, fname); /* put fname in IObuff with quotes */
4896 c = FALSE;
4897#ifdef FEAT_MBYTE
4898 if (write_info.bw_conv_error)
4899 {
4900 STRCAT(IObuff, _(" CONVERSION ERROR"));
4901 c = TRUE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004902 if (write_info.bw_conv_error_lnum != 0)
Bram Moolenaara800b422010-06-27 01:15:55 +02004903 vim_snprintf_add((char *)IObuff, IOSIZE, _(" in line %ld;"),
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004904 (long)write_info.bw_conv_error_lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004905 }
4906 else if (notconverted)
4907 {
4908 STRCAT(IObuff, _("[NOT converted]"));
4909 c = TRUE;
4910 }
4911 else if (converted)
4912 {
4913 STRCAT(IObuff, _("[converted]"));
4914 c = TRUE;
4915 }
4916#endif
4917 if (device)
4918 {
4919 STRCAT(IObuff, _("[Device]"));
4920 c = TRUE;
4921 }
4922 else if (newfile)
4923 {
4924 STRCAT(IObuff, shortmess(SHM_NEW) ? _("[New]") : _("[New File]"));
4925 c = TRUE;
4926 }
4927 if (no_eol)
4928 {
4929 msg_add_eol();
4930 c = TRUE;
4931 }
4932 /* may add [unix/dos/mac] */
4933 if (msg_add_fileformat(fileformat))
4934 c = TRUE;
4935#ifdef FEAT_CRYPT
4936 if (wb_flags & FIO_ENCRYPTED)
4937 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004938 crypt_append_msg(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004939 c = TRUE;
4940 }
4941#endif
4942 msg_add_lines(c, (long)lnum, nchars); /* add line/char count */
4943 if (!shortmess(SHM_WRITE))
4944 {
4945 if (append)
4946 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended"));
4947 else
4948 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written"));
4949 }
4950
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00004951 set_keep_msg(msg_trunc_attr(IObuff, FALSE, 0), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004952 }
4953
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004954 /* When written everything correctly: reset 'modified'. Unless not
4955 * writing to the original file and '+' is not in 'cpoptions'. */
Bram Moolenaar292ad192005-12-11 21:29:51 +00004956 if (reset_changed && whole && !append
Bram Moolenaar071d4272004-06-13 20:20:40 +00004957#ifdef FEAT_MBYTE
4958 && !write_info.bw_conv_error
4959#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004960 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL)
4961 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004962 {
4963 unchanged(buf, TRUE);
Bram Moolenaar086329d2014-10-31 19:51:36 +01004964#ifdef FEAT_AUTOCMD
Bram Moolenaar95c526e2017-02-25 14:59:34 +01004965 /* b:changedtick is always incremented in unchanged() but that
Bram Moolenaar086329d2014-10-31 19:51:36 +01004966 * should not trigger a TextChanged event. */
Bram Moolenaar95c526e2017-02-25 14:59:34 +01004967 if (last_changedtick + 1 == CHANGEDTICK(buf)
Bram Moolenaar086329d2014-10-31 19:51:36 +01004968 && last_changedtick_buf == buf)
Bram Moolenaar95c526e2017-02-25 14:59:34 +01004969 last_changedtick = CHANGEDTICK(buf);
Bram Moolenaar086329d2014-10-31 19:51:36 +01004970#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004971 u_unchanged(buf);
Bram Moolenaar730cde92010-06-27 05:18:54 +02004972 u_update_save_nr(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004973 }
4974
4975 /*
4976 * If written to the current file, update the timestamp of the swap file
4977 * and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
4978 */
4979 if (overwriting)
4980 {
4981 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00004982 if (append)
4983 buf->b_flags &= ~BF_NEW;
4984 else
4985 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004986 }
4987
4988 /*
4989 * If we kept a backup until now, and we are in patch mode, then we make
4990 * the backup file our 'original' file.
4991 */
4992 if (*p_pm && dobackup)
4993 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01004994 char *org = (char *)buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00004995 fname, p_pm, FALSE);
4996
4997 if (backup != NULL)
4998 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02004999 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005000
5001 /*
5002 * If the original file does not exist yet
5003 * the current backup file becomes the original file
5004 */
5005 if (org == NULL)
5006 EMSG(_("E205: Patchmode: can't save original file"));
5007 else if (mch_stat(org, &st) < 0)
5008 {
5009 vim_rename(backup, (char_u *)org);
5010 vim_free(backup); /* don't delete the file */
5011 backup = NULL;
5012#ifdef UNIX
5013 set_file_time((char_u *)org, st_old.st_atime, st_old.st_mtime);
5014#endif
5015 }
5016 }
5017 /*
5018 * If there is no backup file, remember that a (new) file was
5019 * created.
5020 */
5021 else
5022 {
5023 int empty_fd;
5024
5025 if (org == NULL
Bram Moolenaara5792f52005-11-23 21:25:05 +00005026 || (empty_fd = mch_open(org,
5027 O_CREAT | O_EXTRA | O_EXCL | O_NOFOLLOW,
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00005028 perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005029 EMSG(_("E206: patchmode: can't touch empty original file"));
5030 else
5031 close(empty_fd);
5032 }
5033 if (org != NULL)
5034 {
5035 mch_setperm((char_u *)org, mch_getperm(fname) & 0777);
5036 vim_free(org);
5037 }
5038 }
5039
5040 /*
5041 * Remove the backup unless 'backup' option is set
5042 */
5043 if (!p_bk && backup != NULL && mch_remove(backup) != 0)
5044 EMSG(_("E207: Can't delete backup file"));
5045
5046#ifdef FEAT_SUN_WORKSHOP
5047 if (usingSunWorkShop)
5048 workshop_file_saved((char *) ffname);
5049#endif
5050
5051 goto nofail;
5052
5053 /*
5054 * Finish up. We get here either after failure or success.
5055 */
5056fail:
5057 --no_wait_return; /* may wait for return now */
5058nofail:
5059
5060 /* Done saving, we accept changed buffer warnings again */
5061 buf->b_saving = FALSE;
5062
5063 vim_free(backup);
5064 if (buffer != smallbuf)
5065 vim_free(buffer);
5066#ifdef FEAT_MBYTE
5067 vim_free(fenc_tofree);
5068 vim_free(write_info.bw_conv_buf);
5069# ifdef USE_ICONV
5070 if (write_info.bw_iconv_fd != (iconv_t)-1)
5071 {
5072 iconv_close(write_info.bw_iconv_fd);
5073 write_info.bw_iconv_fd = (iconv_t)-1;
5074 }
5075# endif
5076#endif
5077#ifdef HAVE_ACL
5078 mch_free_acl(acl);
5079#endif
5080
5081 if (errmsg != NULL)
5082 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005083 int numlen = errnum != NULL ? (int)STRLEN(errnum) : 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005084
Bram Moolenaar8820b482017-03-16 17:23:31 +01005085 attr = HL_ATTR(HLF_E); /* set highlight for error messages */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005086 msg_add_fname(buf,
5087#ifndef UNIX
5088 sfname
5089#else
5090 fname
5091#endif
5092 ); /* put file name in IObuff with quotes */
5093 if (STRLEN(IObuff) + STRLEN(errmsg) + numlen >= IOSIZE)
5094 IObuff[IOSIZE - STRLEN(errmsg) - numlen - 1] = NUL;
5095 /* If the error message has the form "is ...", put the error number in
5096 * front of the file name. */
5097 if (errnum != NULL)
5098 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00005099 STRMOVE(IObuff + numlen, IObuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005100 mch_memmove(IObuff, errnum, (size_t)numlen);
5101 }
5102 STRCAT(IObuff, errmsg);
5103 emsg(IObuff);
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005104 if (errmsg_allocated)
5105 vim_free(errmsg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005106
5107 retval = FAIL;
5108 if (end == 0)
5109 {
5110 MSG_PUTS_ATTR(_("\nWARNING: Original file may be lost or damaged\n"),
5111 attr | MSG_HIST);
5112 MSG_PUTS_ATTR(_("don't quit the editor until the file is successfully written!"),
5113 attr | MSG_HIST);
5114
5115 /* Update the timestamp to avoid an "overwrite changed file"
5116 * prompt when writing again. */
5117 if (mch_stat((char *)fname, &st_old) >= 0)
5118 {
5119 buf_store_time(buf, &st_old, fname);
5120 buf->b_mtime_read = buf->b_mtime;
5121 }
5122 }
5123 }
5124 msg_scroll = msg_save;
5125
Bram Moolenaar55debbe2010-05-23 23:34:36 +02005126#ifdef FEAT_PERSISTENT_UNDO
5127 /*
5128 * When writing the whole file and 'undofile' is set, also write the undo
5129 * file.
5130 */
5131 if (retval == OK && write_undo_file)
5132 {
5133 char_u hash[UNDO_HASH_SIZE];
5134
5135 sha256_finish(&sha_ctx, hash);
5136 u_write_undo(NULL, FALSE, buf, hash);
5137 }
5138#endif
5139
Bram Moolenaar071d4272004-06-13 20:20:40 +00005140#ifdef FEAT_AUTOCMD
5141#ifdef FEAT_EVAL
5142 if (!should_abort(retval))
5143#else
5144 if (!got_int)
5145#endif
5146 {
5147 aco_save_T aco;
5148
Bram Moolenaar68a33fc2012-04-25 16:50:48 +02005149 curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */
5150
Bram Moolenaar071d4272004-06-13 20:20:40 +00005151 /*
5152 * Apply POST autocommands.
5153 * Careful: The autocommands may call buf_write() recursively!
5154 */
5155 aucmd_prepbuf(&aco, buf);
5156
5157 if (append)
5158 apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname,
5159 FALSE, curbuf, eap);
5160 else if (filtering)
5161 apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname,
5162 FALSE, curbuf, eap);
5163 else if (reset_changed && whole)
5164 apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname,
5165 FALSE, curbuf, eap);
5166 else
5167 apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname,
5168 FALSE, curbuf, eap);
5169
5170 /* restore curwin/curbuf and a few other things */
5171 aucmd_restbuf(&aco);
5172
5173#ifdef FEAT_EVAL
5174 if (aborting()) /* autocmds may abort script processing */
5175 retval = FALSE;
5176#endif
5177 }
5178#endif
5179
5180 got_int |= prev_got_int;
5181
Bram Moolenaar071d4272004-06-13 20:20:40 +00005182 return retval;
5183}
5184
5185/*
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005186 * Set the name of the current buffer. Use when the buffer doesn't have a
5187 * name and a ":r" or ":w" command with a file name is used.
5188 */
5189 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005190set_rw_fname(char_u *fname, char_u *sfname)
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005191{
5192#ifdef FEAT_AUTOCMD
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005193 buf_T *buf = curbuf;
5194
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005195 /* It's like the unnamed buffer is deleted.... */
5196 if (curbuf->b_p_bl)
5197 apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
5198 apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf);
5199# ifdef FEAT_EVAL
5200 if (aborting()) /* autocmds may abort script processing */
5201 return FAIL;
5202# endif
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005203 if (curbuf != buf)
5204 {
5205 /* We are in another buffer now, don't do the renaming. */
5206 EMSG(_(e_auchangedbuf));
5207 return FAIL;
5208 }
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005209#endif
5210
5211 if (setfname(curbuf, fname, sfname, FALSE) == OK)
5212 curbuf->b_flags |= BF_NOTEDITED;
5213
5214#ifdef FEAT_AUTOCMD
5215 /* ....and a new named one is created */
5216 apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, curbuf);
5217 if (curbuf->b_p_bl)
5218 apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf);
5219# ifdef FEAT_EVAL
5220 if (aborting()) /* autocmds may abort script processing */
5221 return FAIL;
5222# endif
5223
5224 /* Do filetype detection now if 'filetype' is empty. */
5225 if (*curbuf->b_p_ft == NUL)
5226 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005227 if (au_has_group((char_u *)"filetypedetect"))
Bram Moolenaar1610d052016-06-09 22:53:01 +02005228 (void)do_doautocmd((char_u *)"filetypedetect BufRead", FALSE, NULL);
Bram Moolenaara3227e22006-03-08 21:32:40 +00005229 do_modelines(0);
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005230 }
5231#endif
5232
5233 return OK;
5234}
5235
5236/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00005237 * Put file name into IObuff with quotes.
5238 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005239 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005240msg_add_fname(buf_T *buf, char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005241{
5242 if (fname == NULL)
5243 fname = (char_u *)"-stdin-";
5244 home_replace(buf, fname, IObuff + 1, IOSIZE - 4, TRUE);
5245 IObuff[0] = '"';
5246 STRCAT(IObuff, "\" ");
5247}
5248
5249/*
5250 * Append message for text mode to IObuff.
5251 * Return TRUE if something appended.
5252 */
5253 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005254msg_add_fileformat(int eol_type)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005255{
5256#ifndef USE_CRNL
5257 if (eol_type == EOL_DOS)
5258 {
5259 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[dos]") : _("[dos format]"));
5260 return TRUE;
5261 }
5262#endif
5263#ifndef USE_CR
5264 if (eol_type == EOL_MAC)
5265 {
5266 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[mac]") : _("[mac format]"));
5267 return TRUE;
5268 }
5269#endif
5270#if defined(USE_CRNL) || defined(USE_CR)
5271 if (eol_type == EOL_UNIX)
5272 {
5273 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[unix]") : _("[unix format]"));
5274 return TRUE;
5275 }
5276#endif
5277 return FALSE;
5278}
5279
5280/*
5281 * Append line and character count to IObuff.
5282 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005283 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005284msg_add_lines(
5285 int insert_space,
5286 long lnum,
Bram Moolenaar8767f522016-07-01 17:17:39 +02005287 off_T nchars)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005288{
5289 char_u *p;
5290
5291 p = IObuff + STRLEN(IObuff);
5292
5293 if (insert_space)
5294 *p++ = ' ';
5295 if (shortmess(SHM_LINES))
Bram Moolenaarbde98102016-07-01 20:03:42 +02005296 vim_snprintf((char *)p, IOSIZE - (p - IObuff),
5297 "%ldL, %lldC", lnum, (varnumber_T)nchars);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005298 else
5299 {
5300 if (lnum == 1)
5301 STRCPY(p, _("1 line, "));
5302 else
5303 sprintf((char *)p, _("%ld lines, "), lnum);
5304 p += STRLEN(p);
5305 if (nchars == 1)
5306 STRCPY(p, _("1 character"));
5307 else
Bram Moolenaarbde98102016-07-01 20:03:42 +02005308 vim_snprintf((char *)p, IOSIZE - (p - IObuff),
5309 _("%lld characters"), (varnumber_T)nchars);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005310 }
5311}
5312
5313/*
5314 * Append message for missing line separator to IObuff.
5315 */
5316 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005317msg_add_eol(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005318{
5319 STRCAT(IObuff, shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]"));
5320}
5321
5322/*
5323 * Check modification time of file, before writing to it.
5324 * The size isn't checked, because using a tool like "gzip" takes care of
5325 * using the same timestamp but can't set the size.
5326 */
5327 static int
Bram Moolenaar8767f522016-07-01 17:17:39 +02005328check_mtime(buf_T *buf, stat_T *st)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005329{
5330 if (buf->b_mtime_read != 0
5331 && time_differs((long)st->st_mtime, buf->b_mtime_read))
5332 {
5333 msg_scroll = TRUE; /* don't overwrite messages here */
5334 msg_silent = 0; /* must give this prompt */
5335 /* don't use emsg() here, don't want to flush the buffers */
5336 MSG_ATTR(_("WARNING: The file has been changed since reading it!!!"),
Bram Moolenaar8820b482017-03-16 17:23:31 +01005337 HL_ATTR(HLF_E));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005338 if (ask_yesno((char_u *)_("Do you really want to write to it"),
5339 TRUE) == 'n')
5340 return FAIL;
5341 msg_scroll = FALSE; /* always overwrite the file message now */
5342 }
5343 return OK;
5344}
5345
5346 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005347time_differs(long t1, long t2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005348{
Bram Moolenaar48e330a2016-02-23 14:53:34 +01005349#if defined(__linux__) || defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005350 /* On a FAT filesystem, esp. under Linux, there are only 5 bits to store
5351 * the seconds. Since the roundoff is done when flushing the inode, the
5352 * time may change unexpectedly by one second!!! */
5353 return (t1 - t2 > 1 || t2 - t1 > 1);
5354#else
5355 return (t1 != t2);
5356#endif
5357}
5358
5359/*
5360 * Call write() to write a number of bytes to the file.
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005361 * Handles encryption and 'encoding' conversion.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005362 *
5363 * Return FAIL for failure, OK otherwise.
5364 */
5365 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005366buf_write_bytes(struct bw_info *ip)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005367{
5368 int wlen;
5369 char_u *buf = ip->bw_buf; /* data to write */
5370 int len = ip->bw_len; /* length of data */
5371#ifdef HAS_BW_FLAGS
5372 int flags = ip->bw_flags; /* extra flags */
5373#endif
5374
5375#ifdef FEAT_MBYTE
5376 /*
5377 * Skip conversion when writing the crypt magic number or the BOM.
5378 */
5379 if (!(flags & FIO_NOCONVERT))
5380 {
5381 char_u *p;
5382 unsigned c;
5383 int n;
5384
5385 if (flags & FIO_UTF8)
5386 {
5387 /*
5388 * Convert latin1 in the buffer to UTF-8 in the file.
5389 */
5390 p = ip->bw_conv_buf; /* translate to buffer */
5391 for (wlen = 0; wlen < len; ++wlen)
5392 p += utf_char2bytes(buf[wlen], p);
5393 buf = ip->bw_conv_buf;
5394 len = (int)(p - ip->bw_conv_buf);
5395 }
5396 else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1))
5397 {
5398 /*
5399 * Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
5400 * Latin1 chars in the file.
5401 */
5402 if (flags & FIO_LATIN1)
5403 p = buf; /* translate in-place (can only get shorter) */
5404 else
5405 p = ip->bw_conv_buf; /* translate to buffer */
5406 for (wlen = 0; wlen < len; wlen += n)
5407 {
5408 if (wlen == 0 && ip->bw_restlen != 0)
5409 {
5410 int l;
5411
5412 /* Use remainder of previous call. Append the start of
5413 * buf[] to get a full sequence. Might still be too
5414 * short! */
5415 l = CONV_RESTLEN - ip->bw_restlen;
5416 if (l > len)
5417 l = len;
5418 mch_memmove(ip->bw_rest + ip->bw_restlen, buf, (size_t)l);
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005419 n = utf_ptr2len_len(ip->bw_rest, ip->bw_restlen + l);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005420 if (n > ip->bw_restlen + len)
5421 {
5422 /* We have an incomplete byte sequence at the end to
5423 * be written. We can't convert it without the
5424 * remaining bytes. Keep them for the next call. */
5425 if (ip->bw_restlen + len > CONV_RESTLEN)
5426 return FAIL;
5427 ip->bw_restlen += len;
5428 break;
5429 }
5430 if (n > 1)
5431 c = utf_ptr2char(ip->bw_rest);
5432 else
5433 c = ip->bw_rest[0];
5434 if (n >= ip->bw_restlen)
5435 {
5436 n -= ip->bw_restlen;
5437 ip->bw_restlen = 0;
5438 }
5439 else
5440 {
5441 ip->bw_restlen -= n;
5442 mch_memmove(ip->bw_rest, ip->bw_rest + n,
5443 (size_t)ip->bw_restlen);
5444 n = 0;
5445 }
5446 }
5447 else
5448 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005449 n = utf_ptr2len_len(buf + wlen, len - wlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005450 if (n > len - wlen)
5451 {
5452 /* We have an incomplete byte sequence at the end to
5453 * be written. We can't convert it without the
5454 * remaining bytes. Keep them for the next call. */
5455 if (len - wlen > CONV_RESTLEN)
5456 return FAIL;
5457 ip->bw_restlen = len - wlen;
5458 mch_memmove(ip->bw_rest, buf + wlen,
5459 (size_t)ip->bw_restlen);
5460 break;
5461 }
5462 if (n > 1)
5463 c = utf_ptr2char(buf + wlen);
5464 else
5465 c = buf[wlen];
5466 }
5467
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005468 if (ucs2bytes(c, &p, flags) && !ip->bw_conv_error)
5469 {
5470 ip->bw_conv_error = TRUE;
5471 ip->bw_conv_error_lnum = ip->bw_start_lnum;
5472 }
5473 if (c == NL)
5474 ++ip->bw_start_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005475 }
5476 if (flags & FIO_LATIN1)
5477 len = (int)(p - buf);
5478 else
5479 {
5480 buf = ip->bw_conv_buf;
5481 len = (int)(p - ip->bw_conv_buf);
5482 }
5483 }
5484
5485# ifdef WIN3264
5486 else if (flags & FIO_CODEPAGE)
5487 {
5488 /*
5489 * Convert UTF-8 or codepage to UCS-2 and then to MS-Windows
5490 * codepage.
5491 */
5492 char_u *from;
5493 size_t fromlen;
5494 char_u *to;
5495 int u8c;
5496 BOOL bad = FALSE;
5497 int needed;
5498
5499 if (ip->bw_restlen > 0)
5500 {
5501 /* Need to concatenate the remainder of the previous call and
5502 * the bytes of the current call. Use the end of the
5503 * conversion buffer for this. */
5504 fromlen = len + ip->bw_restlen;
5505 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5506 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5507 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5508 }
5509 else
5510 {
5511 from = buf;
5512 fromlen = len;
5513 }
5514
5515 to = ip->bw_conv_buf;
5516 if (enc_utf8)
5517 {
5518 /* Convert from UTF-8 to UCS-2, to the start of the buffer.
5519 * The buffer has been allocated to be big enough. */
5520 while (fromlen > 0)
5521 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005522 n = (int)utf_ptr2len_len(from, (int)fromlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005523 if (n > (int)fromlen) /* incomplete byte sequence */
5524 break;
5525 u8c = utf_ptr2char(from);
5526 *to++ = (u8c & 0xff);
5527 *to++ = (u8c >> 8);
5528 fromlen -= n;
5529 from += n;
5530 }
5531
5532 /* Copy remainder to ip->bw_rest[] to be used for the next
5533 * call. */
5534 if (fromlen > CONV_RESTLEN)
5535 {
5536 /* weird overlong sequence */
5537 ip->bw_conv_error = TRUE;
5538 return FAIL;
5539 }
5540 mch_memmove(ip->bw_rest, from, fromlen);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005541 ip->bw_restlen = (int)fromlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005542 }
5543 else
5544 {
5545 /* Convert from enc_codepage to UCS-2, to the start of the
5546 * buffer. The buffer has been allocated to be big enough. */
5547 ip->bw_restlen = 0;
5548 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005549 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005550 NULL, 0);
5551 if (needed == 0)
5552 {
5553 /* When conversion fails there may be a trailing byte. */
5554 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005555 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen - 1,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005556 NULL, 0);
5557 if (needed == 0)
5558 {
5559 /* Conversion doesn't work. */
5560 ip->bw_conv_error = TRUE;
5561 return FAIL;
5562 }
5563 /* Save the trailing byte for the next call. */
5564 ip->bw_rest[0] = from[fromlen - 1];
5565 ip->bw_restlen = 1;
5566 }
5567 needed = MultiByteToWideChar(enc_codepage, MB_ERR_INVALID_CHARS,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005568 (LPCSTR)from, (int)(fromlen - ip->bw_restlen),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005569 (LPWSTR)to, needed);
5570 if (needed == 0)
5571 {
5572 /* Safety check: Conversion doesn't work. */
5573 ip->bw_conv_error = TRUE;
5574 return FAIL;
5575 }
5576 to += needed * 2;
5577 }
5578
5579 fromlen = to - ip->bw_conv_buf;
5580 buf = to;
5581# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5582 if (FIO_GET_CP(flags) == CP_UTF8)
5583 {
5584 /* Convert from UCS-2 to UTF-8, using the remainder of the
5585 * conversion buffer. Fails when out of space. */
5586 for (from = ip->bw_conv_buf; fromlen > 1; fromlen -= 2)
5587 {
5588 u8c = *from++;
5589 u8c += (*from++ << 8);
5590 to += utf_char2bytes(u8c, to);
5591 if (to + 6 >= ip->bw_conv_buf + ip->bw_conv_buflen)
5592 {
5593 ip->bw_conv_error = TRUE;
5594 return FAIL;
5595 }
5596 }
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005597 len = (int)(to - buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005598 }
5599 else
5600#endif
5601 {
5602 /* Convert from UCS-2 to the codepage, using the remainder of
5603 * the conversion buffer. If the conversion uses the default
5604 * character "0", the data doesn't fit in this encoding, so
5605 * fail. */
5606 len = WideCharToMultiByte(FIO_GET_CP(flags), 0,
5607 (LPCWSTR)ip->bw_conv_buf, (int)fromlen / sizeof(WCHAR),
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005608 (LPSTR)to, (int)(ip->bw_conv_buflen - fromlen), 0,
5609 &bad);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005610 if (bad)
5611 {
5612 ip->bw_conv_error = TRUE;
5613 return FAIL;
5614 }
5615 }
5616 }
5617# endif
5618
Bram Moolenaar56718732006-03-15 22:53:57 +00005619# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00005620 else if (flags & FIO_MACROMAN)
5621 {
5622 /*
5623 * Convert UTF-8 or latin1 to Apple MacRoman.
5624 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005625 char_u *from;
5626 size_t fromlen;
5627
5628 if (ip->bw_restlen > 0)
5629 {
5630 /* Need to concatenate the remainder of the previous call and
5631 * the bytes of the current call. Use the end of the
5632 * conversion buffer for this. */
5633 fromlen = len + ip->bw_restlen;
5634 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5635 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5636 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5637 }
5638 else
5639 {
5640 from = buf;
5641 fromlen = len;
5642 }
5643
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00005644 if (enc2macroman(from, fromlen,
5645 ip->bw_conv_buf, &len, ip->bw_conv_buflen,
5646 ip->bw_rest, &ip->bw_restlen) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005647 {
5648 ip->bw_conv_error = TRUE;
5649 return FAIL;
5650 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005651 buf = ip->bw_conv_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005652 }
5653# endif
5654
5655# ifdef USE_ICONV
5656 if (ip->bw_iconv_fd != (iconv_t)-1)
5657 {
5658 const char *from;
5659 size_t fromlen;
5660 char *to;
5661 size_t tolen;
5662
5663 /* Convert with iconv(). */
5664 if (ip->bw_restlen > 0)
5665 {
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005666 char *fp;
5667
Bram Moolenaar071d4272004-06-13 20:20:40 +00005668 /* Need to concatenate the remainder of the previous call and
5669 * the bytes of the current call. Use the end of the
5670 * conversion buffer for this. */
5671 fromlen = len + ip->bw_restlen;
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005672 fp = (char *)ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5673 mch_memmove(fp, ip->bw_rest, (size_t)ip->bw_restlen);
5674 mch_memmove(fp + ip->bw_restlen, buf, (size_t)len);
5675 from = fp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005676 tolen = ip->bw_conv_buflen - fromlen;
5677 }
5678 else
5679 {
5680 from = (const char *)buf;
5681 fromlen = len;
5682 tolen = ip->bw_conv_buflen;
5683 }
5684 to = (char *)ip->bw_conv_buf;
5685
5686 if (ip->bw_first)
5687 {
5688 size_t save_len = tolen;
5689
5690 /* output the initial shift state sequence */
5691 (void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen);
5692
5693 /* There is a bug in iconv() on Linux (which appears to be
5694 * wide-spread) which sets "to" to NULL and messes up "tolen".
5695 */
5696 if (to == NULL)
5697 {
5698 to = (char *)ip->bw_conv_buf;
5699 tolen = save_len;
5700 }
5701 ip->bw_first = FALSE;
5702 }
5703
5704 /*
5705 * If iconv() has an error or there is not enough room, fail.
5706 */
5707 if ((iconv(ip->bw_iconv_fd, (void *)&from, &fromlen, &to, &tolen)
5708 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
5709 || fromlen > CONV_RESTLEN)
5710 {
5711 ip->bw_conv_error = TRUE;
5712 return FAIL;
5713 }
5714
5715 /* copy remainder to ip->bw_rest[] to be used for the next call. */
5716 if (fromlen > 0)
5717 mch_memmove(ip->bw_rest, (void *)from, fromlen);
5718 ip->bw_restlen = (int)fromlen;
5719
5720 buf = ip->bw_conv_buf;
5721 len = (int)((char_u *)to - ip->bw_conv_buf);
5722 }
5723# endif
5724 }
5725#endif /* FEAT_MBYTE */
5726
Bram Moolenaare6bf6552017-06-27 22:11:51 +02005727 if (ip->bw_fd < 0)
5728 /* Only checking conversion, which is OK if we get here. */
5729 return OK;
5730
Bram Moolenaar071d4272004-06-13 20:20:40 +00005731#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02005732 if (flags & FIO_ENCRYPTED)
5733 {
5734 /* Encrypt the data. Do it in-place if possible, otherwise use an
5735 * allocated buffer. */
5736 if (crypt_works_inplace(ip->bw_buffer->b_cryptstate))
5737 {
5738 crypt_encode_inplace(ip->bw_buffer->b_cryptstate, buf, len);
5739 }
5740 else
5741 {
5742 char_u *outbuf;
5743
5744 len = crypt_encode_alloc(curbuf->b_cryptstate, buf, len, &outbuf);
5745 if (len == 0)
5746 return OK; /* Crypt layer is buffering, will flush later. */
5747 wlen = write_eintr(ip->bw_fd, outbuf, len);
5748 vim_free(outbuf);
5749 return (wlen < len) ? FAIL : OK;
5750 }
5751 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005752#endif
5753
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005754 wlen = write_eintr(ip->bw_fd, buf, len);
5755 return (wlen < len) ? FAIL : OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005756}
5757
5758#ifdef FEAT_MBYTE
5759/*
5760 * Convert a Unicode character to bytes.
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005761 * Return TRUE for an error, FALSE when it's OK.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005762 */
5763 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005764ucs2bytes(
5765 unsigned c, /* in: character */
5766 char_u **pp, /* in/out: pointer to result */
5767 int flags) /* FIO_ flags */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005768{
5769 char_u *p = *pp;
5770 int error = FALSE;
5771 int cc;
5772
5773
5774 if (flags & FIO_UCS4)
5775 {
5776 if (flags & FIO_ENDIAN_L)
5777 {
5778 *p++ = c;
5779 *p++ = (c >> 8);
5780 *p++ = (c >> 16);
5781 *p++ = (c >> 24);
5782 }
5783 else
5784 {
5785 *p++ = (c >> 24);
5786 *p++ = (c >> 16);
5787 *p++ = (c >> 8);
5788 *p++ = c;
5789 }
5790 }
5791 else if (flags & (FIO_UCS2 | FIO_UTF16))
5792 {
5793 if (c >= 0x10000)
5794 {
5795 if (flags & FIO_UTF16)
5796 {
5797 /* Make two words, ten bits of the character in each. First
5798 * word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff */
5799 c -= 0x10000;
5800 if (c >= 0x100000)
5801 error = TRUE;
5802 cc = ((c >> 10) & 0x3ff) + 0xd800;
5803 if (flags & FIO_ENDIAN_L)
5804 {
5805 *p++ = cc;
5806 *p++ = ((unsigned)cc >> 8);
5807 }
5808 else
5809 {
5810 *p++ = ((unsigned)cc >> 8);
5811 *p++ = cc;
5812 }
5813 c = (c & 0x3ff) + 0xdc00;
5814 }
5815 else
5816 error = TRUE;
5817 }
5818 if (flags & FIO_ENDIAN_L)
5819 {
5820 *p++ = c;
5821 *p++ = (c >> 8);
5822 }
5823 else
5824 {
5825 *p++ = (c >> 8);
5826 *p++ = c;
5827 }
5828 }
5829 else /* Latin1 */
5830 {
5831 if (c >= 0x100)
5832 {
5833 error = TRUE;
5834 *p++ = 0xBF;
5835 }
5836 else
5837 *p++ = c;
5838 }
5839
5840 *pp = p;
5841 return error;
5842}
5843
5844/*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005845 * Return TRUE if file encoding "fenc" requires conversion from or to
5846 * 'encoding'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005847 */
5848 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005849need_conversion(char_u *fenc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005850{
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005851 int same_encoding;
5852 int enc_flags;
5853 int fenc_flags;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005854
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005855 if (*fenc == NUL || STRCMP(p_enc, fenc) == 0)
Bram Moolenaar442b4222010-05-24 21:34:22 +02005856 {
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005857 same_encoding = TRUE;
Bram Moolenaar442b4222010-05-24 21:34:22 +02005858 fenc_flags = 0;
5859 }
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005860 else
5861 {
5862 /* Ignore difference between "ansi" and "latin1", "ucs-4" and
5863 * "ucs-4be", etc. */
5864 enc_flags = get_fio_flags(p_enc);
5865 fenc_flags = get_fio_flags(fenc);
5866 same_encoding = (enc_flags != 0 && fenc_flags == enc_flags);
5867 }
5868 if (same_encoding)
5869 {
5870 /* Specified encoding matches with 'encoding'. This requires
5871 * conversion when 'encoding' is Unicode but not UTF-8. */
5872 return enc_unicode != 0;
5873 }
5874
5875 /* Encodings differ. However, conversion is not needed when 'enc' is any
5876 * Unicode encoding and the file is UTF-8. */
5877 return !(enc_utf8 && fenc_flags == FIO_UTF8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005878}
5879
5880/*
5881 * Check "ptr" for a unicode encoding and return the FIO_ flags needed for the
5882 * internal conversion.
5883 * if "ptr" is an empty string, use 'encoding'.
5884 */
5885 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005886get_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005887{
5888 int prop;
5889
5890 if (*ptr == NUL)
5891 ptr = p_enc;
5892
5893 prop = enc_canon_props(ptr);
5894 if (prop & ENC_UNICODE)
5895 {
5896 if (prop & ENC_2BYTE)
5897 {
5898 if (prop & ENC_ENDIAN_L)
5899 return FIO_UCS2 | FIO_ENDIAN_L;
5900 return FIO_UCS2;
5901 }
5902 if (prop & ENC_4BYTE)
5903 {
5904 if (prop & ENC_ENDIAN_L)
5905 return FIO_UCS4 | FIO_ENDIAN_L;
5906 return FIO_UCS4;
5907 }
5908 if (prop & ENC_2WORD)
5909 {
5910 if (prop & ENC_ENDIAN_L)
5911 return FIO_UTF16 | FIO_ENDIAN_L;
5912 return FIO_UTF16;
5913 }
5914 return FIO_UTF8;
5915 }
5916 if (prop & ENC_LATIN1)
5917 return FIO_LATIN1;
5918 /* must be ENC_DBCS, requires iconv() */
5919 return 0;
5920}
5921
5922#ifdef WIN3264
5923/*
5924 * Check "ptr" for a MS-Windows codepage name and return the FIO_ flags needed
5925 * for the conversion MS-Windows can do for us. Also accept "utf-8".
5926 * Used for conversion between 'encoding' and 'fileencoding'.
5927 */
5928 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005929get_win_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005930{
5931 int cp;
5932
5933 /* Cannot do this when 'encoding' is not utf-8 and not a codepage. */
5934 if (!enc_utf8 && enc_codepage <= 0)
5935 return 0;
5936
5937 cp = encname2codepage(ptr);
5938 if (cp == 0)
5939 {
5940# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5941 if (STRCMP(ptr, "utf-8") == 0)
5942 cp = CP_UTF8;
5943 else
5944# endif
5945 return 0;
5946 }
5947 return FIO_PUT_CP(cp) | FIO_CODEPAGE;
5948}
5949#endif
5950
Bram Moolenaard0573012017-10-28 21:11:06 +02005951#ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00005952/*
5953 * Check "ptr" for a Carbon supported encoding and return the FIO_ flags
5954 * needed for the internal conversion to/from utf-8 or latin1.
5955 */
5956 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005957get_mac_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005958{
5959 if ((enc_utf8 || STRCMP(p_enc, "latin1") == 0)
5960 && (enc_canon_props(ptr) & ENC_MACROMAN))
5961 return FIO_MACROMAN;
5962 return 0;
5963}
5964#endif
5965
5966/*
5967 * Check for a Unicode BOM (Byte Order Mark) at the start of p[size].
5968 * "size" must be at least 2.
5969 * Return the name of the encoding and set "*lenp" to the length.
5970 * Returns NULL when no BOM found.
5971 */
5972 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005973check_for_bom(
5974 char_u *p,
5975 long size,
5976 int *lenp,
5977 int flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005978{
5979 char *name = NULL;
5980 int len = 2;
5981
5982 if (p[0] == 0xef && p[1] == 0xbb && size >= 3 && p[2] == 0xbf
Bram Moolenaaree0f5a62008-07-24 20:09:16 +00005983 && (flags == FIO_ALL || flags == FIO_UTF8 || flags == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005984 {
5985 name = "utf-8"; /* EF BB BF */
5986 len = 3;
5987 }
5988 else if (p[0] == 0xff && p[1] == 0xfe)
5989 {
5990 if (size >= 4 && p[2] == 0 && p[3] == 0
5991 && (flags == FIO_ALL || flags == (FIO_UCS4 | FIO_ENDIAN_L)))
5992 {
5993 name = "ucs-4le"; /* FF FE 00 00 */
5994 len = 4;
5995 }
Bram Moolenaar223a1892008-11-11 20:57:11 +00005996 else if (flags == (FIO_UCS2 | FIO_ENDIAN_L))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005997 name = "ucs-2le"; /* FF FE */
Bram Moolenaar223a1892008-11-11 20:57:11 +00005998 else if (flags == FIO_ALL || flags == (FIO_UTF16 | FIO_ENDIAN_L))
5999 /* utf-16le is preferred, it also works for ucs-2le text */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006000 name = "utf-16le"; /* FF FE */
6001 }
6002 else if (p[0] == 0xfe && p[1] == 0xff
6003 && (flags == FIO_ALL || flags == FIO_UCS2 || flags == FIO_UTF16))
6004 {
Bram Moolenaarffd82c52008-02-20 17:15:26 +00006005 /* Default to utf-16, it works also for ucs-2 text. */
6006 if (flags == FIO_UCS2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006007 name = "ucs-2"; /* FE FF */
Bram Moolenaarffd82c52008-02-20 17:15:26 +00006008 else
6009 name = "utf-16"; /* FE FF */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006010 }
6011 else if (size >= 4 && p[0] == 0 && p[1] == 0 && p[2] == 0xfe
6012 && p[3] == 0xff && (flags == FIO_ALL || flags == FIO_UCS4))
6013 {
6014 name = "ucs-4"; /* 00 00 FE FF */
6015 len = 4;
6016 }
6017
6018 *lenp = len;
6019 return (char_u *)name;
6020}
6021
6022/*
6023 * Generate a BOM in "buf[4]" for encoding "name".
6024 * Return the length of the BOM (zero when no BOM).
6025 */
6026 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006027make_bom(char_u *buf, char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006028{
6029 int flags;
6030 char_u *p;
6031
6032 flags = get_fio_flags(name);
6033
6034 /* Can't put a BOM in a non-Unicode file. */
6035 if (flags == FIO_LATIN1 || flags == 0)
6036 return 0;
6037
6038 if (flags == FIO_UTF8) /* UTF-8 */
6039 {
6040 buf[0] = 0xef;
6041 buf[1] = 0xbb;
6042 buf[2] = 0xbf;
6043 return 3;
6044 }
6045 p = buf;
6046 (void)ucs2bytes(0xfeff, &p, flags);
6047 return (int)(p - buf);
6048}
6049#endif
6050
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00006051#if defined(FEAT_VIMINFO) || defined(FEAT_BROWSE) || \
Bram Moolenaara0174af2008-01-02 20:08:25 +00006052 defined(FEAT_QUICKFIX) || defined(FEAT_AUTOCMD) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006053/*
6054 * Try to find a shortname by comparing the fullname with the current
6055 * directory.
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006056 * Returns "full_path" or pointer into "full_path" if shortened.
6057 */
6058 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006059shorten_fname1(char_u *full_path)
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006060{
Bram Moolenaard9462e32011-04-11 21:35:11 +02006061 char_u *dirname;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006062 char_u *p = full_path;
6063
Bram Moolenaard9462e32011-04-11 21:35:11 +02006064 dirname = alloc(MAXPATHL);
6065 if (dirname == NULL)
6066 return full_path;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006067 if (mch_dirname(dirname, MAXPATHL) == OK)
6068 {
6069 p = shorten_fname(full_path, dirname);
6070 if (p == NULL || *p == NUL)
6071 p = full_path;
6072 }
Bram Moolenaard9462e32011-04-11 21:35:11 +02006073 vim_free(dirname);
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006074 return p;
6075}
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00006076#endif
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006077
6078/*
6079 * Try to find a shortname by comparing the fullname with the current
6080 * directory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006081 * Returns NULL if not shorter name possible, pointer into "full_path"
6082 * otherwise.
6083 */
6084 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006085shorten_fname(char_u *full_path, char_u *dir_name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006086{
6087 int len;
6088 char_u *p;
6089
6090 if (full_path == NULL)
6091 return NULL;
6092 len = (int)STRLEN(dir_name);
6093 if (fnamencmp(dir_name, full_path, len) == 0)
6094 {
6095 p = full_path + len;
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006096#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006097 /*
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006098 * MSWIN: when a file is in the root directory, dir_name will end in a
Bram Moolenaar071d4272004-06-13 20:20:40 +00006099 * slash, since C: by itself does not define a specific dir. In this
6100 * case p may already be correct. <negri>
6101 */
6102 if (!((len > 2) && (*(p - 2) == ':')))
6103#endif
6104 {
6105 if (vim_ispathsep(*p))
6106 ++p;
6107#ifndef VMS /* the path separator is always part of the path */
6108 else
6109 p = NULL;
6110#endif
6111 }
6112 }
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006113#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006114 /*
6115 * When using a file in the current drive, remove the drive name:
6116 * "A:\dir\file" -> "\dir\file". This helps when moving a session file on
6117 * a floppy from "A:\dir" to "B:\dir".
6118 */
6119 else if (len > 3
6120 && TOUPPER_LOC(full_path[0]) == TOUPPER_LOC(dir_name[0])
6121 && full_path[1] == ':'
6122 && vim_ispathsep(full_path[2]))
6123 p = full_path + 2;
6124#endif
6125 else
6126 p = NULL;
6127 return p;
6128}
6129
6130/*
6131 * Shorten filenames for all buffers.
6132 * When "force" is TRUE: Use full path from now on for files currently being
6133 * edited, both for file name and swap file name. Try to shorten the file
6134 * names a bit, if safe to do so.
6135 * When "force" is FALSE: Only try to shorten absolute file names.
6136 * For buffers that have buftype "nofile" or "scratch": never change the file
6137 * name.
6138 */
6139 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006140shorten_fnames(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006141{
6142 char_u dirname[MAXPATHL];
6143 buf_T *buf;
6144 char_u *p;
6145
6146 mch_dirname(dirname, MAXPATHL);
Bram Moolenaar29323592016-07-24 22:04:11 +02006147 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006148 {
6149 if (buf->b_fname != NULL
6150#ifdef FEAT_QUICKFIX
6151 && !bt_nofile(buf)
6152#endif
6153 && !path_with_url(buf->b_fname)
6154 && (force
6155 || buf->b_sfname == NULL
6156 || mch_isFullName(buf->b_sfname)))
6157 {
6158 vim_free(buf->b_sfname);
6159 buf->b_sfname = NULL;
6160 p = shorten_fname(buf->b_ffname, dirname);
6161 if (p != NULL)
6162 {
6163 buf->b_sfname = vim_strsave(p);
6164 buf->b_fname = buf->b_sfname;
6165 }
6166 if (p == NULL || buf->b_fname == NULL)
6167 buf->b_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006168 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00006169
6170 /* Always make the swap file name a full path, a "nofile" buffer may
6171 * also have a swap file. */
6172 mf_fullname(buf->b_ml.ml_mfp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006173 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006174 status_redraw_all();
Bram Moolenaar49d7bf12006-02-17 21:45:41 +00006175 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006176}
6177
6178#if (defined(FEAT_DND) && defined(FEAT_GUI_GTK)) \
6179 || defined(FEAT_GUI_MSWIN) \
6180 || defined(FEAT_GUI_MAC) \
6181 || defined(PROTO)
6182/*
6183 * Shorten all filenames in "fnames[count]" by current directory.
6184 */
6185 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006186shorten_filenames(char_u **fnames, int count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006187{
6188 int i;
6189 char_u dirname[MAXPATHL];
6190 char_u *p;
6191
6192 if (fnames == NULL || count < 1)
6193 return;
6194 mch_dirname(dirname, sizeof(dirname));
6195 for (i = 0; i < count; ++i)
6196 {
6197 if ((p = shorten_fname(fnames[i], dirname)) != NULL)
6198 {
6199 /* shorten_fname() returns pointer in given "fnames[i]". If free
6200 * "fnames[i]" first, "p" becomes invalid. So we need to copy
6201 * "p" first then free fnames[i]. */
6202 p = vim_strsave(p);
6203 vim_free(fnames[i]);
6204 fnames[i] = p;
6205 }
6206 }
6207}
6208#endif
6209
6210/*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006211 * add extension to file name - change path/fo.o.h to path/fo.o.h.ext or
Bram Moolenaar071d4272004-06-13 20:20:40 +00006212 * fo_o_h.ext for MSDOS or when shortname option set.
6213 *
6214 * Assumed that fname is a valid name found in the filesystem we assure that
6215 * the return value is a different name and ends in 'ext'.
6216 * "ext" MUST be at most 4 characters long if it starts with a dot, 3
6217 * characters otherwise.
6218 * Space for the returned name is allocated, must be freed later.
6219 * Returns NULL when out of memory.
6220 */
6221 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006222modname(
6223 char_u *fname,
6224 char_u *ext,
6225 int prepend_dot) /* may prepend a '.' to file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006226{
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006227 return buf_modname((curbuf->b_p_sn || curbuf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00006228 fname, ext, prepend_dot);
6229}
6230
6231 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006232buf_modname(
6233 int shortname, /* use 8.3 file name */
6234 char_u *fname,
6235 char_u *ext,
6236 int prepend_dot) /* may prepend a '.' to file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006237{
6238 char_u *retval;
6239 char_u *s;
6240 char_u *e;
6241 char_u *ptr;
6242 int fnamelen, extlen;
6243
6244 extlen = (int)STRLEN(ext);
6245
6246 /*
6247 * If there is no file name we must get the name of the current directory
6248 * (we need the full path in case :cd is used).
6249 */
6250 if (fname == NULL || *fname == NUL)
6251 {
6252 retval = alloc((unsigned)(MAXPATHL + extlen + 3));
6253 if (retval == NULL)
6254 return NULL;
6255 if (mch_dirname(retval, MAXPATHL) == FAIL ||
6256 (fnamelen = (int)STRLEN(retval)) == 0)
6257 {
6258 vim_free(retval);
6259 return NULL;
6260 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006261 if (!after_pathsep(retval, retval + fnamelen))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006262 {
6263 retval[fnamelen++] = PATHSEP;
6264 retval[fnamelen] = NUL;
6265 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006266 prepend_dot = FALSE; /* nothing to prepend a dot to */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006267 }
6268 else
6269 {
6270 fnamelen = (int)STRLEN(fname);
6271 retval = alloc((unsigned)(fnamelen + extlen + 3));
6272 if (retval == NULL)
6273 return NULL;
6274 STRCPY(retval, fname);
6275#ifdef VMS
6276 vms_remove_version(retval); /* we do not need versions here */
6277#endif
6278 }
6279
6280 /*
6281 * search backwards until we hit a '/', '\' or ':' replacing all '.'
6282 * by '_' for MSDOS or when shortname option set and ext starts with a dot.
6283 * Then truncate what is after the '/', '\' or ':' to 8 characters for
6284 * MSDOS and 26 characters for AMIGA, a lot more for UNIX.
6285 */
Bram Moolenaar91acfff2017-03-12 19:22:36 +01006286 for (ptr = retval + fnamelen; ptr > retval; MB_PTR_BACK(retval, ptr))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006287 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006288 if (*ext == '.'
Bram Moolenaare60acc12011-05-10 16:41:25 +02006289#ifdef USE_LONG_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00006290 && (!USE_LONG_FNAME || shortname)
Bram Moolenaare60acc12011-05-10 16:41:25 +02006291#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006292 && shortname
Bram Moolenaare60acc12011-05-10 16:41:25 +02006293#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006294 )
6295 if (*ptr == '.') /* replace '.' by '_' */
6296 *ptr = '_';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006297 if (vim_ispathsep(*ptr))
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006298 {
6299 ++ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006300 break;
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006301 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006302 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006303
6304 /* the file name has at most BASENAMELEN characters. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006305 if (STRLEN(ptr) > (unsigned)BASENAMELEN)
6306 ptr[BASENAMELEN] = '\0';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006307
6308 s = ptr + STRLEN(ptr);
6309
6310 /*
6311 * For 8.3 file names we may have to reduce the length.
6312 */
6313#ifdef USE_LONG_FNAME
6314 if (!USE_LONG_FNAME || shortname)
6315#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006316 if (shortname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006317#endif
6318 {
6319 /*
6320 * If there is no file name, or the file name ends in '/', and the
6321 * extension starts with '.', put a '_' before the dot, because just
6322 * ".ext" is invalid.
6323 */
6324 if (fname == NULL || *fname == NUL
6325 || vim_ispathsep(fname[STRLEN(fname) - 1]))
6326 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006327 if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006328 *s++ = '_';
6329 }
6330 /*
6331 * If the extension starts with '.', truncate the base name at 8
6332 * characters
6333 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006334 else if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006335 {
Bram Moolenaar78a15312009-05-15 19:33:18 +00006336 if ((size_t)(s - ptr) > (size_t)8)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006337 {
6338 s = ptr + 8;
6339 *s = '\0';
6340 }
6341 }
6342 /*
6343 * If the extension doesn't start with '.', and the file name
6344 * doesn't have an extension yet, append a '.'
6345 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006346 else if ((e = vim_strchr(ptr, '.')) == NULL)
6347 *s++ = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006348 /*
6349 * If the extension doesn't start with '.', and there already is an
Bram Moolenaar7263a772007-05-10 17:35:54 +00006350 * extension, it may need to be truncated
Bram Moolenaar071d4272004-06-13 20:20:40 +00006351 */
6352 else if ((int)STRLEN(e) + extlen > 4)
6353 s = e + 4 - extlen;
6354 }
Bram Moolenaare7fedb62015-12-31 19:07:19 +01006355#if defined(USE_LONG_FNAME) || defined(WIN3264)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006356 /*
6357 * If there is no file name, and the extension starts with '.', put a
6358 * '_' before the dot, because just ".ext" may be invalid if it's on a
6359 * FAT partition, and on HPFS it doesn't matter.
6360 */
6361 else if ((fname == NULL || *fname == NUL) && *ext == '.')
6362 *s++ = '_';
6363#endif
6364
6365 /*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006366 * Append the extension.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006367 * ext can start with '.' and cannot exceed 3 more characters.
6368 */
6369 STRCPY(s, ext);
6370
Bram Moolenaar071d4272004-06-13 20:20:40 +00006371 /*
6372 * Prepend the dot.
6373 */
Bram Moolenaare60acc12011-05-10 16:41:25 +02006374 if (prepend_dot && !shortname && *(e = gettail(retval)) != '.'
Bram Moolenaar071d4272004-06-13 20:20:40 +00006375#ifdef USE_LONG_FNAME
6376 && USE_LONG_FNAME
6377#endif
6378 )
6379 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006380 STRMOVE(e + 1, e);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006381 *e = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006382 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006383
6384 /*
6385 * Check that, after appending the extension, the file name is really
6386 * different.
6387 */
6388 if (fname != NULL && STRCMP(fname, retval) == 0)
6389 {
6390 /* we search for a character that can be replaced by '_' */
6391 while (--s >= ptr)
6392 {
6393 if (*s != '_')
6394 {
6395 *s = '_';
6396 break;
6397 }
6398 }
6399 if (s < ptr) /* fname was "________.<ext>", how tricky! */
6400 *ptr = 'v';
6401 }
6402 return retval;
6403}
6404
6405/*
6406 * Like fgets(), but if the file line is too long, it is truncated and the
6407 * rest of the line is thrown away. Returns TRUE for end-of-file.
6408 */
6409 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006410vim_fgets(char_u *buf, int size, FILE *fp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006411{
6412 char *eof;
6413#define FGETS_SIZE 200
6414 char tbuf[FGETS_SIZE];
6415
6416 buf[size - 2] = NUL;
6417#ifdef USE_CR
6418 eof = fgets_cr((char *)buf, size, fp);
6419#else
6420 eof = fgets((char *)buf, size, fp);
6421#endif
6422 if (buf[size - 2] != NUL && buf[size - 2] != '\n')
6423 {
6424 buf[size - 1] = NUL; /* Truncate the line */
6425
6426 /* Now throw away the rest of the line: */
6427 do
6428 {
6429 tbuf[FGETS_SIZE - 2] = NUL;
6430#ifdef USE_CR
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006431 ignoredp = fgets_cr((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006432#else
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006433 ignoredp = fgets((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006434#endif
6435 } while (tbuf[FGETS_SIZE - 2] != NUL && tbuf[FGETS_SIZE - 2] != '\n');
6436 }
6437 return (eof == NULL);
6438}
6439
6440#if defined(USE_CR) || defined(PROTO)
6441/*
6442 * Like vim_fgets(), but accept any line terminator: CR, CR-LF or LF.
6443 * Returns TRUE for end-of-file.
6444 * Only used for the Mac, because it's much slower than vim_fgets().
6445 */
6446 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006447tag_fgets(char_u *buf, int size, FILE *fp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006448{
6449 int i = 0;
6450 int c;
6451 int eof = FALSE;
6452
6453 for (;;)
6454 {
6455 c = fgetc(fp);
6456 if (c == EOF)
6457 {
6458 eof = TRUE;
6459 break;
6460 }
6461 if (c == '\r')
6462 {
6463 /* Always store a NL for end-of-line. */
6464 if (i < size - 1)
6465 buf[i++] = '\n';
6466 c = fgetc(fp);
6467 if (c != '\n') /* Macintosh format: single CR. */
6468 ungetc(c, fp);
6469 break;
6470 }
6471 if (i < size - 1)
6472 buf[i++] = c;
6473 if (c == '\n')
6474 break;
6475 }
6476 buf[i] = NUL;
6477 return eof;
6478}
6479#endif
6480
6481/*
6482 * rename() only works if both files are on the same file system, this
6483 * function will (attempts to?) copy the file across if rename fails -- webb
6484 * Return -1 for failure, 0 for success.
6485 */
6486 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006487vim_rename(char_u *from, char_u *to)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006488{
6489 int fd_in;
6490 int fd_out;
6491 int n;
6492 char *errmsg = NULL;
6493 char *buffer;
6494#ifdef AMIGA
6495 BPTR flock;
6496#endif
Bram Moolenaar8767f522016-07-01 17:17:39 +02006497 stat_T st;
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006498 long perm;
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006499#ifdef HAVE_ACL
6500 vim_acl_T acl; /* ACL from original file */
6501#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006502 int use_tmp_file = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006503
6504 /*
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006505 * When the names are identical, there is nothing to do. When they refer
6506 * to the same file (ignoring case and slash/backslash differences) but
6507 * the file name differs we need to go through a temp file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006508 */
6509 if (fnamecmp(from, to) == 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006510 {
Bram Moolenaar71afbfe2013-03-19 16:49:16 +01006511 if (p_fic && STRCMP(gettail(from), gettail(to)) != 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006512 use_tmp_file = TRUE;
6513 else
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006514 return 0;
6515 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006516
6517 /*
6518 * Fail if the "from" file doesn't exist. Avoids that "to" is deleted.
6519 */
6520 if (mch_stat((char *)from, &st) < 0)
6521 return -1;
6522
Bram Moolenaar3576da72008-12-30 15:15:57 +00006523#ifdef UNIX
6524 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02006525 stat_T st_to;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006526
6527 /* It's possible for the source and destination to be the same file.
6528 * This happens when "from" and "to" differ in case and are on a FAT32
6529 * filesystem. In that case go through a temp file name. */
6530 if (mch_stat((char *)to, &st_to) >= 0
6531 && st.st_dev == st_to.st_dev
6532 && st.st_ino == st_to.st_ino)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006533 use_tmp_file = TRUE;
6534 }
6535#endif
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02006536#ifdef WIN3264
6537 {
6538 BY_HANDLE_FILE_INFORMATION info1, info2;
6539
6540 /* It's possible for the source and destination to be the same file.
6541 * In that case go through a temp file name. This makes rename("foo",
6542 * "./foo") a no-op (in a complicated way). */
6543 if (win32_fileinfo(from, &info1) == FILEINFO_OK
6544 && win32_fileinfo(to, &info2) == FILEINFO_OK
6545 && info1.dwVolumeSerialNumber == info2.dwVolumeSerialNumber
6546 && info1.nFileIndexHigh == info2.nFileIndexHigh
6547 && info1.nFileIndexLow == info2.nFileIndexLow)
6548 use_tmp_file = TRUE;
6549 }
6550#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006551
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006552 if (use_tmp_file)
6553 {
6554 char tempname[MAXPATHL + 1];
6555
6556 /*
6557 * Find a name that doesn't exist and is in the same directory.
6558 * Rename "from" to "tempname" and then rename "tempname" to "to".
6559 */
6560 if (STRLEN(from) >= MAXPATHL - 5)
6561 return -1;
6562 STRCPY(tempname, from);
6563 for (n = 123; n < 99999; ++n)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006564 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006565 sprintf((char *)gettail((char_u *)tempname), "%d", n);
6566 if (mch_stat(tempname, &st) < 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006567 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006568 if (mch_rename((char *)from, tempname) == 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006569 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006570 if (mch_rename(tempname, (char *)to) == 0)
6571 return 0;
6572 /* Strange, the second step failed. Try moving the
6573 * file back and return failure. */
6574 mch_rename(tempname, (char *)from);
Bram Moolenaar3576da72008-12-30 15:15:57 +00006575 return -1;
6576 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006577 /* If it fails for one temp name it will most likely fail
6578 * for any temp name, give up. */
6579 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006580 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006581 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006582 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006583 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006584
Bram Moolenaar071d4272004-06-13 20:20:40 +00006585 /*
6586 * Delete the "to" file, this is required on some systems to make the
6587 * mch_rename() work, on other systems it makes sure that we don't have
6588 * two files when the mch_rename() fails.
6589 */
6590
6591#ifdef AMIGA
6592 /*
6593 * With MSDOS-compatible filesystems (crossdos, messydos) it is possible
6594 * that the name of the "to" file is the same as the "from" file, even
Bram Moolenaar7263a772007-05-10 17:35:54 +00006595 * though the names are different. To avoid the chance of accidentally
Bram Moolenaar071d4272004-06-13 20:20:40 +00006596 * deleting the "from" file (horror!) we lock it during the remove.
6597 *
6598 * When used for making a backup before writing the file: This should not
6599 * happen with ":w", because startscript() should detect this problem and
6600 * set buf->b_shortname, causing modname() to return a correct ".bak" file
6601 * name. This problem does exist with ":w filename", but then the
6602 * original file will be somewhere else so the backup isn't really
6603 * important. If autoscripting is off the rename may fail.
6604 */
6605 flock = Lock((UBYTE *)from, (long)ACCESS_READ);
6606#endif
6607 mch_remove(to);
6608#ifdef AMIGA
6609 if (flock)
6610 UnLock(flock);
6611#endif
6612
6613 /*
6614 * First try a normal rename, return if it works.
6615 */
6616 if (mch_rename((char *)from, (char *)to) == 0)
6617 return 0;
6618
6619 /*
6620 * Rename() failed, try copying the file.
6621 */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006622 perm = mch_getperm(from);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006623#ifdef HAVE_ACL
6624 /* For systems that support ACL: get the ACL from the original file. */
6625 acl = mch_get_acl(from);
6626#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006627 fd_in = mch_open((char *)from, O_RDONLY|O_EXTRA, 0);
6628 if (fd_in == -1)
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006629 {
6630#ifdef HAVE_ACL
6631 mch_free_acl(acl);
6632#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006633 return -1;
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006634 }
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006635
6636 /* Create the new file with same permissions as the original. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00006637 fd_out = mch_open((char *)to,
6638 O_CREAT|O_EXCL|O_WRONLY|O_EXTRA|O_NOFOLLOW, (int)perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006639 if (fd_out == -1)
6640 {
6641 close(fd_in);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006642#ifdef HAVE_ACL
6643 mch_free_acl(acl);
6644#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006645 return -1;
6646 }
6647
6648 buffer = (char *)alloc(BUFSIZE);
6649 if (buffer == NULL)
6650 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006651 close(fd_out);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006652 close(fd_in);
6653#ifdef HAVE_ACL
6654 mch_free_acl(acl);
6655#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006656 return -1;
6657 }
6658
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01006659 while ((n = read_eintr(fd_in, buffer, BUFSIZE)) > 0)
6660 if (write_eintr(fd_out, buffer, n) != n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006661 {
6662 errmsg = _("E208: Error writing to \"%s\"");
6663 break;
6664 }
6665
6666 vim_free(buffer);
6667 close(fd_in);
6668 if (close(fd_out) < 0)
6669 errmsg = _("E209: Error closing \"%s\"");
6670 if (n < 0)
6671 {
6672 errmsg = _("E210: Error reading \"%s\"");
6673 to = from;
6674 }
Bram Moolenaar7263a772007-05-10 17:35:54 +00006675#ifndef UNIX /* for Unix mch_open() already set the permission */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006676 mch_setperm(to, perm);
Bram Moolenaarc6039d82005-12-02 00:44:04 +00006677#endif
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006678#ifdef HAVE_ACL
6679 mch_set_acl(to, acl);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006680 mch_free_acl(acl);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006681#endif
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02006682#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaare8747442013-11-12 18:09:29 +01006683 mch_copy_sec(from, to);
Bram Moolenaar0671de32013-11-12 05:12:03 +01006684#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006685 if (errmsg != NULL)
6686 {
6687 EMSG2(errmsg, to);
6688 return -1;
6689 }
6690 mch_remove(from);
6691 return 0;
6692}
6693
6694static int already_warned = FALSE;
6695
6696/*
6697 * Check if any not hidden buffer has been changed.
6698 * Postpone the check if there are characters in the stuff buffer, a global
6699 * command is being executed, a mapping is being executed or an autocommand is
6700 * busy.
6701 * Returns TRUE if some message was written (screen should be redrawn and
6702 * cursor positioned).
6703 */
6704 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006705check_timestamps(
6706 int focus) /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006707{
6708 buf_T *buf;
6709 int didit = 0;
6710 int n;
6711
6712 /* Don't check timestamps while system() or another low-level function may
6713 * cause us to lose and gain focus. */
6714 if (no_check_timestamps > 0)
6715 return FALSE;
6716
6717 /* Avoid doing a check twice. The OK/Reload dialog can cause a focus
6718 * event and we would keep on checking if the file is steadily growing.
6719 * Do check again after typing something. */
6720 if (focus && did_check_timestamps)
6721 {
6722 need_check_timestamps = TRUE;
6723 return FALSE;
6724 }
6725
6726 if (!stuff_empty() || global_busy || !typebuf_typed()
6727#ifdef FEAT_AUTOCMD
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006728 || autocmd_busy || curbuf_lock > 0 || allbuf_lock > 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00006729#endif
6730 )
6731 need_check_timestamps = TRUE; /* check later */
6732 else
6733 {
6734 ++no_wait_return;
6735 did_check_timestamps = TRUE;
6736 already_warned = FALSE;
Bram Moolenaar29323592016-07-24 22:04:11 +02006737 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006738 {
6739 /* Only check buffers in a window. */
6740 if (buf->b_nwindows > 0)
6741 {
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006742 bufref_T bufref;
6743
6744 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006745 n = buf_check_timestamp(buf, focus);
6746 if (didit < n)
6747 didit = n;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006748 if (n > 0 && !bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006749 {
6750 /* Autocommands have removed the buffer, start at the
6751 * first one again. */
6752 buf = firstbuf;
6753 continue;
6754 }
6755 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006756 }
6757 --no_wait_return;
6758 need_check_timestamps = FALSE;
6759 if (need_wait_return && didit == 2)
6760 {
6761 /* make sure msg isn't overwritten */
6762 msg_puts((char_u *)"\n");
6763 out_flush();
6764 }
6765 }
6766 return didit;
6767}
6768
6769/*
6770 * Move all the lines from buffer "frombuf" to buffer "tobuf".
6771 * Return OK or FAIL. When FAIL "tobuf" is incomplete and/or "frombuf" is not
6772 * empty.
6773 */
6774 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006775move_lines(buf_T *frombuf, buf_T *tobuf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006776{
6777 buf_T *tbuf = curbuf;
6778 int retval = OK;
6779 linenr_T lnum;
6780 char_u *p;
6781
6782 /* Copy the lines in "frombuf" to "tobuf". */
6783 curbuf = tobuf;
6784 for (lnum = 1; lnum <= frombuf->b_ml.ml_line_count; ++lnum)
6785 {
6786 p = vim_strsave(ml_get_buf(frombuf, lnum, FALSE));
6787 if (p == NULL || ml_append(lnum - 1, p, 0, FALSE) == FAIL)
6788 {
6789 vim_free(p);
6790 retval = FAIL;
6791 break;
6792 }
6793 vim_free(p);
6794 }
6795
6796 /* Delete all the lines in "frombuf". */
6797 if (retval != FAIL)
6798 {
6799 curbuf = frombuf;
Bram Moolenaar9460b9d2007-01-09 14:37:01 +00006800 for (lnum = curbuf->b_ml.ml_line_count; lnum > 0; --lnum)
6801 if (ml_delete(lnum, FALSE) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006802 {
6803 /* Oops! We could try putting back the saved lines, but that
6804 * might fail again... */
6805 retval = FAIL;
6806 break;
6807 }
6808 }
6809
6810 curbuf = tbuf;
6811 return retval;
6812}
6813
6814/*
6815 * Check if buffer "buf" has been changed.
6816 * Also check if the file for a new buffer unexpectedly appeared.
6817 * return 1 if a changed buffer was found.
6818 * return 2 if a message has been displayed.
6819 * return 0 otherwise.
6820 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006821 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006822buf_check_timestamp(
6823 buf_T *buf,
6824 int focus UNUSED) /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006825{
Bram Moolenaar8767f522016-07-01 17:17:39 +02006826 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006827 int stat_res;
6828 int retval = 0;
6829 char_u *path;
6830 char_u *tbuf;
6831 char *mesg = NULL;
Bram Moolenaar44ecf652005-03-07 23:09:59 +00006832 char *mesg2 = "";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006833 int helpmesg = FALSE;
6834 int reload = FALSE;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006835 char *reason;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006836#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6837 int can_reload = FALSE;
6838#endif
Bram Moolenaar8767f522016-07-01 17:17:39 +02006839 off_T orig_size = buf->b_orig_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006840 int orig_mode = buf->b_orig_mode;
6841#ifdef FEAT_GUI
6842 int save_mouse_correct = need_mouse_correct;
6843#endif
6844#ifdef FEAT_AUTOCMD
6845 static int busy = FALSE;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006846 int n;
6847 char_u *s;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006848 bufref_T bufref;
6849
6850 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006851#endif
6852
6853 /* If there is no file name, the buffer is not loaded, 'buftype' is
6854 * set, we are in the middle of a save or being called recursively: ignore
6855 * this buffer. */
6856 if (buf->b_ffname == NULL
6857 || buf->b_ml.ml_mfp == NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00006858 || *buf->b_p_bt != NUL
Bram Moolenaar071d4272004-06-13 20:20:40 +00006859 || buf->b_saving
6860#ifdef FEAT_AUTOCMD
6861 || busy
6862#endif
Bram Moolenaar009b2592004-10-24 19:18:58 +00006863#ifdef FEAT_NETBEANS_INTG
6864 || isNetbeansBuffer(buf)
6865#endif
Bram Moolenaar8cad9302017-08-12 14:32:32 +02006866#ifdef FEAT_TERMINAL
6867 || buf->b_term != NULL
6868#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006869 )
6870 return 0;
6871
6872 if ( !(buf->b_flags & BF_NOTEDITED)
6873 && buf->b_mtime != 0
6874 && ((stat_res = mch_stat((char *)buf->b_ffname, &st)) < 0
6875 || time_differs((long)st.st_mtime, buf->b_mtime)
Bram Moolenaara7611f62014-05-02 15:46:14 +02006876 || st.st_size != buf->b_orig_size
Bram Moolenaar071d4272004-06-13 20:20:40 +00006877#ifdef HAVE_ST_MODE
6878 || (int)st.st_mode != buf->b_orig_mode
6879#else
6880 || mch_getperm(buf->b_ffname) != buf->b_orig_mode
6881#endif
6882 ))
6883 {
6884 retval = 1;
6885
Bram Moolenaar316059c2006-01-14 21:18:42 +00006886 /* set b_mtime to stop further warnings (e.g., when executing
6887 * FileChangedShell autocmd) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006888 if (stat_res < 0)
6889 {
6890 buf->b_mtime = 0;
6891 buf->b_orig_size = 0;
6892 buf->b_orig_mode = 0;
6893 }
6894 else
6895 buf_store_time(buf, &st, buf->b_ffname);
6896
6897 /* Don't do anything for a directory. Might contain the file
6898 * explorer. */
6899 if (mch_isdir(buf->b_fname))
6900 ;
6901
6902 /*
6903 * If 'autoread' is set, the buffer has no changes and the file still
6904 * exists, reload the buffer. Use the buffer-local option value if it
6905 * was set, the global option value otherwise.
6906 */
6907 else if ((buf->b_p_ar >= 0 ? buf->b_p_ar : p_ar)
6908 && !bufIsChanged(buf) && stat_res >= 0)
6909 reload = TRUE;
6910 else
6911 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006912 if (stat_res < 0)
6913 reason = "deleted";
6914 else if (bufIsChanged(buf))
6915 reason = "conflict";
6916 else if (orig_size != buf->b_orig_size || buf_contents_changed(buf))
6917 reason = "changed";
6918 else if (orig_mode != buf->b_orig_mode)
6919 reason = "mode";
6920 else
6921 reason = "time";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006922
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006923#ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006924 /*
6925 * Only give the warning if there are no FileChangedShell
6926 * autocommands.
6927 * Avoid being called recursively by setting "busy".
6928 */
6929 busy = TRUE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00006930# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006931 set_vim_var_string(VV_FCS_REASON, (char_u *)reason, -1);
6932 set_vim_var_string(VV_FCS_CHOICE, (char_u *)"", -1);
Bram Moolenaar1e015462005-09-25 22:16:38 +00006933# endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006934 ++allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006935 n = apply_autocmds(EVENT_FILECHANGEDSHELL,
6936 buf->b_fname, buf->b_fname, FALSE, buf);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006937 --allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006938 busy = FALSE;
6939 if (n)
6940 {
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006941 if (!bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006942 EMSG(_("E246: FileChangedShell autocommand deleted buffer"));
Bram Moolenaar1e015462005-09-25 22:16:38 +00006943# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006944 s = get_vim_var_str(VV_FCS_CHOICE);
6945 if (STRCMP(s, "reload") == 0 && *reason != 'd')
6946 reload = TRUE;
6947 else if (STRCMP(s, "ask") == 0)
6948 n = FALSE;
6949 else
Bram Moolenaar1e015462005-09-25 22:16:38 +00006950# endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006951 return 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006952 }
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006953 if (!n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006954#endif
6955 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006956 if (*reason == 'd')
6957 mesg = _("E211: File \"%s\" no longer available");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006958 else
6959 {
6960 helpmesg = TRUE;
6961#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6962 can_reload = TRUE;
6963#endif
6964 /*
6965 * Check if the file contents really changed to avoid
6966 * giving a warning when only the timestamp was set (e.g.,
6967 * checked out of CVS). Always warn when the buffer was
6968 * changed.
6969 */
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006970 if (reason[2] == 'n')
6971 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006972 mesg = _("W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006973 mesg2 = _("See \":help W12\" for more info.");
6974 }
6975 else if (reason[1] == 'h')
6976 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006977 mesg = _("W11: Warning: File \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006978 mesg2 = _("See \":help W11\" for more info.");
6979 }
6980 else if (*reason == 'm')
6981 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006982 mesg = _("W16: Warning: Mode of file \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006983 mesg2 = _("See \":help W16\" for more info.");
6984 }
Bram Moolenaar85388b52009-06-24 09:58:32 +00006985 else
6986 /* Only timestamp changed, store it to avoid a warning
6987 * in check_mtime() later. */
6988 buf->b_mtime_read = buf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006989 }
6990 }
6991 }
6992
6993 }
6994 else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W)
6995 && vim_fexists(buf->b_ffname))
6996 {
6997 retval = 1;
6998 mesg = _("W13: Warning: File \"%s\" has been created after editing started");
6999 buf->b_flags |= BF_NEW_W;
7000#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
7001 can_reload = TRUE;
7002#endif
7003 }
7004
7005 if (mesg != NULL)
7006 {
7007 path = home_replace_save(buf, buf->b_fname);
7008 if (path != NULL)
7009 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007010 if (!helpmesg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007011 mesg2 = "";
7012 tbuf = alloc((unsigned)(STRLEN(path) + STRLEN(mesg)
7013 + STRLEN(mesg2) + 2));
7014 sprintf((char *)tbuf, mesg, path);
Bram Moolenaar496c5262009-03-18 14:42:00 +00007015#ifdef FEAT_EVAL
7016 /* Set warningmsg here, before the unimportant and output-specific
7017 * mesg2 has been appended. */
7018 set_vim_var_string(VV_WARNINGMSG, tbuf, -1);
7019#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007020#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
7021 if (can_reload)
7022 {
7023 if (*mesg2 != NUL)
7024 {
7025 STRCAT(tbuf, "\n");
7026 STRCAT(tbuf, mesg2);
7027 }
7028 if (do_dialog(VIM_WARNING, (char_u *)_("Warning"), tbuf,
Bram Moolenaard2c340a2011-01-17 20:08:11 +01007029 (char_u *)_("&OK\n&Load File"), 1, NULL, TRUE) == 2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007030 reload = TRUE;
7031 }
7032 else
7033#endif
7034 if (State > NORMAL_BUSY || (State & CMDLINE) || already_warned)
7035 {
7036 if (*mesg2 != NUL)
7037 {
7038 STRCAT(tbuf, "; ");
7039 STRCAT(tbuf, mesg2);
7040 }
7041 EMSG(tbuf);
7042 retval = 2;
7043 }
7044 else
7045 {
Bram Moolenaared203462004-06-16 11:19:22 +00007046# ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00007047 if (!autocmd_busy)
Bram Moolenaared203462004-06-16 11:19:22 +00007048# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007049 {
7050 msg_start();
Bram Moolenaar8820b482017-03-16 17:23:31 +01007051 msg_puts_attr(tbuf, HL_ATTR(HLF_E) + MSG_HIST);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007052 if (*mesg2 != NUL)
7053 msg_puts_attr((char_u *)mesg2,
Bram Moolenaar8820b482017-03-16 17:23:31 +01007054 HL_ATTR(HLF_W) + MSG_HIST);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007055 msg_clr_eos();
7056 (void)msg_end();
7057 if (emsg_silent == 0)
7058 {
7059 out_flush();
Bram Moolenaared203462004-06-16 11:19:22 +00007060# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00007061 if (!focus)
Bram Moolenaared203462004-06-16 11:19:22 +00007062# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007063 /* give the user some time to think about it */
7064 ui_delay(1000L, TRUE);
7065
7066 /* don't redraw and erase the message */
7067 redraw_cmdline = FALSE;
7068 }
7069 }
7070 already_warned = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007071 }
7072
7073 vim_free(path);
7074 vim_free(tbuf);
7075 }
7076 }
7077
7078 if (reload)
Bram Moolenaar465748e2012-08-29 18:50:54 +02007079 {
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007080 /* Reload the buffer. */
Bram Moolenaar316059c2006-01-14 21:18:42 +00007081 buf_reload(buf, orig_mode);
Bram Moolenaar465748e2012-08-29 18:50:54 +02007082#ifdef FEAT_PERSISTENT_UNDO
7083 if (buf->b_p_udf && buf->b_ffname != NULL)
7084 {
7085 char_u hash[UNDO_HASH_SIZE];
7086 buf_T *save_curbuf = curbuf;
7087
7088 /* Any existing undo file is unusable, write it now. */
7089 curbuf = buf;
7090 u_compute_hash(hash);
7091 u_write_undo(NULL, FALSE, buf, hash);
7092 curbuf = save_curbuf;
7093 }
7094#endif
7095 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007096
Bram Moolenaar56718732006-03-15 22:53:57 +00007097#ifdef FEAT_AUTOCMD
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00007098 /* Trigger FileChangedShell when the file was changed in any way. */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007099 if (bufref_valid(&bufref) && retval != 0)
Bram Moolenaar56718732006-03-15 22:53:57 +00007100 (void)apply_autocmds(EVENT_FILECHANGEDSHELLPOST,
7101 buf->b_fname, buf->b_fname, FALSE, buf);
7102#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007103#ifdef FEAT_GUI
7104 /* restore this in case an autocommand has set it; it would break
7105 * 'mousefocus' */
7106 need_mouse_correct = save_mouse_correct;
7107#endif
7108
7109 return retval;
7110}
7111
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007112/*
7113 * Reload a buffer that is already loaded.
7114 * Used when the file was changed outside of Vim.
Bram Moolenaar316059c2006-01-14 21:18:42 +00007115 * "orig_mode" is buf->b_orig_mode before the need for reloading was detected.
7116 * buf->b_orig_mode may have been reset already.
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007117 */
7118 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007119buf_reload(buf_T *buf, int orig_mode)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007120{
7121 exarg_T ea;
7122 pos_T old_cursor;
7123 linenr_T old_topline;
7124 int old_ro = buf->b_p_ro;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007125 buf_T *savebuf;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007126 bufref_T bufref;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007127 int saved = OK;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007128 aco_save_T aco;
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007129 int flags = READ_NEW;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007130
7131 /* set curwin/curbuf for "buf" and save some things */
7132 aucmd_prepbuf(&aco, buf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007133
7134 /* We only want to read the text from the file, not reset the syntax
7135 * highlighting, clear marks, diff status, etc. Force the fileformat
7136 * and encoding to be the same. */
7137 if (prep_exarg(&ea, buf) == OK)
7138 {
7139 old_cursor = curwin->w_cursor;
7140 old_topline = curwin->w_topline;
7141
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007142 if (p_ur < 0 || curbuf->b_ml.ml_line_count <= p_ur)
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007143 {
7144 /* Save all the text, so that the reload can be undone.
7145 * Sync first so that this is a separate undo-able action. */
7146 u_sync(FALSE);
7147 saved = u_savecommon(0, curbuf->b_ml.ml_line_count + 1, 0, TRUE);
7148 flags |= READ_KEEP_UNDO;
7149 }
7150
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007151 /*
7152 * To behave like when a new file is edited (matters for
7153 * BufReadPost autocommands) we first need to delete the current
7154 * buffer contents. But if reading the file fails we should keep
7155 * the old contents. Can't use memory only, the file might be
7156 * too big. Use a hidden buffer to move the buffer contents to.
7157 */
Bram Moolenaarb5aedf32017-03-12 18:23:53 +01007158 if (BUFEMPTY() || saved == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007159 savebuf = NULL;
7160 else
7161 {
7162 /* Allocate a buffer without putting it in the buffer list. */
7163 savebuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007164 set_bufref(&bufref, savebuf);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007165 if (savebuf != NULL && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007166 {
7167 /* Open the memline. */
7168 curbuf = savebuf;
7169 curwin->w_buffer = savebuf;
Bram Moolenaar4770d092006-01-12 23:22:24 +00007170 saved = ml_open(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007171 curbuf = buf;
7172 curwin->w_buffer = buf;
7173 }
Bram Moolenaar8424a622006-04-19 21:23:36 +00007174 if (savebuf == NULL || saved == FAIL || buf != curbuf
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007175 || move_lines(buf, savebuf) == FAIL)
7176 {
7177 EMSG2(_("E462: Could not prepare for reloading \"%s\""),
7178 buf->b_fname);
7179 saved = FAIL;
7180 }
7181 }
7182
7183 if (saved == OK)
7184 {
7185 curbuf->b_flags |= BF_CHECK_RO; /* check for RO again */
7186#ifdef FEAT_AUTOCMD
7187 keep_filetype = TRUE; /* don't detect 'filetype' */
7188#endif
7189 if (readfile(buf->b_ffname, buf->b_fname, (linenr_T)0,
7190 (linenr_T)0,
Bram Moolenaare13b9af2017-01-13 22:01:02 +01007191 (linenr_T)MAXLNUM, &ea, flags) != OK)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007192 {
7193#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
7194 if (!aborting())
7195#endif
7196 EMSG2(_("E321: Could not reload \"%s\""), buf->b_fname);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007197 if (savebuf != NULL && bufref_valid(&bufref) && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007198 {
7199 /* Put the text back from the save buffer. First
7200 * delete any lines that readfile() added. */
Bram Moolenaarb5aedf32017-03-12 18:23:53 +01007201 while (!BUFEMPTY())
Bram Moolenaar8424a622006-04-19 21:23:36 +00007202 if (ml_delete(buf->b_ml.ml_line_count, FALSE) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007203 break;
7204 (void)move_lines(savebuf, buf);
7205 }
7206 }
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007207 else if (buf == curbuf) /* "buf" still valid */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007208 {
7209 /* Mark the buffer as unmodified and free undo info. */
7210 unchanged(buf, TRUE);
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007211 if ((flags & READ_KEEP_UNDO) == 0)
7212 {
7213 u_blockfree(buf);
7214 u_clearall(buf);
7215 }
7216 else
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007217 {
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007218 /* Mark all undo states as changed. */
7219 u_unchanged(curbuf);
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007220 }
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007221 }
7222 }
7223 vim_free(ea.cmd);
7224
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007225 if (savebuf != NULL && bufref_valid(&bufref))
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007226 wipe_buffer(savebuf, FALSE);
7227
7228#ifdef FEAT_DIFF
7229 /* Invalidate diff info if necessary. */
Bram Moolenaar8424a622006-04-19 21:23:36 +00007230 diff_invalidate(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007231#endif
7232
7233 /* Restore the topline and cursor position and check it (lines may
7234 * have been removed). */
7235 if (old_topline > curbuf->b_ml.ml_line_count)
7236 curwin->w_topline = curbuf->b_ml.ml_line_count;
7237 else
7238 curwin->w_topline = old_topline;
7239 curwin->w_cursor = old_cursor;
7240 check_cursor();
7241 update_topline();
7242#ifdef FEAT_AUTOCMD
7243 keep_filetype = FALSE;
7244#endif
7245#ifdef FEAT_FOLDING
7246 {
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007247 win_T *wp;
7248 tabpage_T *tp;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007249
7250 /* Update folds unless they are defined manually. */
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007251 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007252 if (wp->w_buffer == curwin->w_buffer
7253 && !foldmethodIsManual(wp))
7254 foldUpdateAll(wp);
7255 }
7256#endif
7257 /* If the mode didn't change and 'readonly' was set, keep the old
7258 * value; the user probably used the ":view" command. But don't
7259 * reset it, might have had a read error. */
7260 if (orig_mode == curbuf->b_orig_mode)
7261 curbuf->b_p_ro |= old_ro;
Bram Moolenaar52f85b72013-01-30 14:13:56 +01007262
7263 /* Modelines must override settings done by autocommands. */
7264 do_modelines(0);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007265 }
7266
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007267 /* restore curwin/curbuf and a few other things */
7268 aucmd_restbuf(&aco);
7269 /* Careful: autocommands may have made "buf" invalid! */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007270}
7271
Bram Moolenaar071d4272004-06-13 20:20:40 +00007272 void
Bram Moolenaar8767f522016-07-01 17:17:39 +02007273buf_store_time(buf_T *buf, stat_T *st, char_u *fname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007274{
7275 buf->b_mtime = (long)st->st_mtime;
Bram Moolenaar914703b2010-05-31 21:59:46 +02007276 buf->b_orig_size = st->st_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007277#ifdef HAVE_ST_MODE
7278 buf->b_orig_mode = (int)st->st_mode;
7279#else
7280 buf->b_orig_mode = mch_getperm(fname);
7281#endif
7282}
7283
7284/*
7285 * Adjust the line with missing eol, used for the next write.
7286 * Used for do_filter(), when the input lines for the filter are deleted.
7287 */
7288 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007289write_lnum_adjust(linenr_T offset)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007290{
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01007291 if (curbuf->b_no_eol_lnum != 0) /* only if there is a missing eol */
7292 curbuf->b_no_eol_lnum += offset;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007293}
7294
Bram Moolenaarda440d22016-01-16 21:27:23 +01007295#if defined(TEMPDIRNAMES) || defined(FEAT_EVAL) || defined(PROTO)
7296/*
7297 * Delete "name" and everything in it, recursively.
7298 * return 0 for succes, -1 if some file was not deleted.
7299 */
7300 int
7301delete_recursive(char_u *name)
7302{
7303 int result = 0;
7304 char_u **files;
7305 int file_count;
7306 int i;
7307 char_u *exp;
7308
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007309 /* A symbolic link to a directory itself is deleted, not the directory it
7310 * points to. */
7311 if (
Bram Moolenaar203258c2016-01-17 22:15:16 +01007312# if defined(UNIX) || defined(WIN32)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007313 mch_isrealdir(name)
Bram Moolenaar203258c2016-01-17 22:15:16 +01007314# else
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007315 mch_isdir(name)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007316# endif
7317 )
Bram Moolenaarda440d22016-01-16 21:27:23 +01007318 {
7319 vim_snprintf((char *)NameBuff, MAXPATHL, "%s/*", name);
7320 exp = vim_strsave(NameBuff);
7321 if (exp == NULL)
7322 return -1;
7323 if (gen_expand_wildcards(1, &exp, &file_count, &files,
Bram Moolenaar336bd622016-01-17 18:23:58 +01007324 EW_DIR|EW_FILE|EW_SILENT|EW_ALLLINKS|EW_DODOT|EW_EMPTYOK) == OK)
Bram Moolenaarda440d22016-01-16 21:27:23 +01007325 {
7326 for (i = 0; i < file_count; ++i)
7327 if (delete_recursive(files[i]) != 0)
7328 result = -1;
7329 FreeWild(file_count, files);
7330 }
7331 else
7332 result = -1;
7333 vim_free(exp);
7334 (void)mch_rmdir(name);
7335 }
7336 else
7337 result = mch_remove(name) == 0 ? 0 : -1;
7338
7339 return result;
7340}
7341#endif
7342
Bram Moolenaar071d4272004-06-13 20:20:40 +00007343#if defined(TEMPDIRNAMES) || defined(PROTO)
7344static long temp_count = 0; /* Temp filename counter. */
7345
7346/*
7347 * Delete the temp directory and all files it contains.
7348 */
7349 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007350vim_deltempdir(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007351{
Bram Moolenaar071d4272004-06-13 20:20:40 +00007352 if (vim_tempdir != NULL)
7353 {
Bram Moolenaarda440d22016-01-16 21:27:23 +01007354 /* remove the trailing path separator */
7355 gettail(vim_tempdir)[-1] = NUL;
7356 delete_recursive(vim_tempdir);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007357 vim_free(vim_tempdir);
7358 vim_tempdir = NULL;
7359 }
7360}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007361
7362/*
Bram Moolenaareaf03392009-11-17 11:08:52 +00007363 * Directory "tempdir" was created. Expand this name to a full path and put
7364 * it in "vim_tempdir". This avoids that using ":cd" would confuse us.
7365 * "tempdir" must be no longer than MAXPATHL.
7366 */
7367 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007368vim_settempdir(char_u *tempdir)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007369{
7370 char_u *buf;
7371
7372 buf = alloc((unsigned)MAXPATHL + 2);
7373 if (buf != NULL)
7374 {
7375 if (vim_FullName(tempdir, buf, MAXPATHL, FALSE) == FAIL)
7376 STRCPY(buf, tempdir);
Bram Moolenaara06ecab2016-07-16 14:47:36 +02007377 add_pathsep(buf);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007378 vim_tempdir = vim_strsave(buf);
7379 vim_free(buf);
7380 }
7381}
Bram Moolenaar4592dee2009-11-18 19:11:58 +00007382#endif
Bram Moolenaareaf03392009-11-17 11:08:52 +00007383
7384/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007385 * vim_tempname(): Return a unique name that can be used for a temp file.
7386 *
Bram Moolenaar76ae22f2016-06-13 20:00:29 +02007387 * The temp file is NOT guaranteed to be created. If "keep" is FALSE it is
7388 * guaranteed to NOT be created.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007389 *
7390 * The returned pointer is to allocated memory.
7391 * The returned pointer is NULL if no valid name was found.
7392 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007393 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007394vim_tempname(
7395 int extra_char UNUSED, /* char to use in the name instead of '?' */
7396 int keep UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007397{
7398#ifdef USE_TMPNAM
7399 char_u itmp[L_tmpnam]; /* use tmpnam() */
7400#else
7401 char_u itmp[TEMPNAMELEN];
7402#endif
7403
7404#ifdef TEMPDIRNAMES
7405 static char *(tempdirs[]) = {TEMPDIRNAMES};
7406 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007407# ifndef EEXIST
Bram Moolenaar8767f522016-07-01 17:17:39 +02007408 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007409# endif
7410
7411 /*
7412 * This will create a directory for private use by this instance of Vim.
7413 * This is done once, and the same directory is used for all temp files.
7414 * This method avoids security problems because of symlink attacks et al.
7415 * It's also a bit faster, because we only need to check for an existing
7416 * file when creating the directory and not for each temp file.
7417 */
7418 if (vim_tempdir == NULL)
7419 {
7420 /*
7421 * Try the entries in TEMPDIRNAMES to create the temp directory.
7422 */
Bram Moolenaar78a15312009-05-15 19:33:18 +00007423 for (i = 0; i < (int)(sizeof(tempdirs) / sizeof(char *)); ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007424 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007425# ifndef HAVE_MKDTEMP
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007426 size_t itmplen;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007427 long nr;
7428 long off;
7429# endif
7430
Bram Moolenaare1a61992015-12-03 21:02:27 +01007431 /* Expand $TMP, leave room for "/v1100000/999999999".
7432 * Skip the directory check if the expansion fails. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007433 expand_env((char_u *)tempdirs[i], itmp, TEMPNAMELEN - 20);
Bram Moolenaare1a61992015-12-03 21:02:27 +01007434 if (itmp[0] != '$' && mch_isdir(itmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007435 {
Bram Moolenaare1a61992015-12-03 21:02:27 +01007436 /* directory exists */
Bram Moolenaara06ecab2016-07-16 14:47:36 +02007437 add_pathsep(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007438
Bram Moolenaareaf03392009-11-17 11:08:52 +00007439# ifdef HAVE_MKDTEMP
Bram Moolenaar35d88f42016-06-04 14:52:00 +02007440 {
7441# if defined(UNIX) || defined(VMS)
7442 /* Make sure the umask doesn't remove the executable bit.
7443 * "repl" has been reported to use "177". */
7444 mode_t umask_save = umask(077);
7445# endif
7446 /* Leave room for filename */
7447 STRCAT(itmp, "vXXXXXX");
7448 if (mkdtemp((char *)itmp) != NULL)
7449 vim_settempdir(itmp);
7450# if defined(UNIX) || defined(VMS)
7451 (void)umask(umask_save);
7452# endif
7453 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007454# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007455 /* Get an arbitrary number of up to 6 digits. When it's
7456 * unlikely that it already exists it will be faster,
7457 * otherwise it doesn't matter. The use of mkdir() avoids any
7458 * security problems because of the predictable number. */
7459 nr = (mch_get_pid() + (long)time(NULL)) % 1000000L;
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007460 itmplen = STRLEN(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007461
7462 /* Try up to 10000 different values until we find a name that
7463 * doesn't exist. */
7464 for (off = 0; off < 10000L; ++off)
7465 {
7466 int r;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007467# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007468 mode_t umask_save;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007469# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007470
Bram Moolenaareaf03392009-11-17 11:08:52 +00007471 sprintf((char *)itmp + itmplen, "v%ld", nr + off);
7472# ifndef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007473 /* If mkdir() does not set errno to EEXIST, check for
7474 * existing file here. There is a race condition then,
7475 * although it's fail-safe. */
7476 if (mch_stat((char *)itmp, &st) >= 0)
7477 continue;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007478# endif
7479# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007480 /* Make sure the umask doesn't remove the executable bit.
7481 * "repl" has been reported to use "177". */
7482 umask_save = umask(077);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007483# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007484 r = vim_mkdir(itmp, 0700);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007485# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007486 (void)umask(umask_save);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007487# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007488 if (r == 0)
7489 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007490 vim_settempdir(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007491 break;
7492 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007493# ifdef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007494 /* If the mkdir() didn't fail because the file/dir exists,
7495 * we probably can't create any dir here, try another
7496 * place. */
7497 if (errno != EEXIST)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007498# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007499 break;
7500 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007501# endif /* HAVE_MKDTEMP */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007502 if (vim_tempdir != NULL)
7503 break;
7504 }
7505 }
7506 }
7507
7508 if (vim_tempdir != NULL)
7509 {
7510 /* There is no need to check if the file exists, because we own the
7511 * directory and nobody else creates a file in it. */
7512 sprintf((char *)itmp, "%s%ld", vim_tempdir, temp_count++);
7513 return vim_strsave(itmp);
7514 }
7515
7516 return NULL;
7517
7518#else /* TEMPDIRNAMES */
7519
7520# ifdef WIN3264
7521 char szTempFile[_MAX_PATH + 1];
7522 char buf4[4];
7523 char_u *retval;
7524 char_u *p;
7525
7526 STRCPY(itmp, "");
7527 if (GetTempPath(_MAX_PATH, szTempFile) == 0)
Bram Moolenaarb1891912011-02-09 14:47:03 +01007528 {
7529 szTempFile[0] = '.'; /* GetTempPath() failed, use current dir */
7530 szTempFile[1] = NUL;
7531 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007532 strcpy(buf4, "VIM");
7533 buf4[2] = extra_char; /* make it "VIa", "VIb", etc. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007534 if (GetTempFileName(szTempFile, buf4, 0, (LPSTR)itmp) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007535 return NULL;
Bram Moolenaare5c421c2015-03-31 13:33:08 +02007536 if (!keep)
7537 /* GetTempFileName() will create the file, we don't want that */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007538 (void)DeleteFile((LPSTR)itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007539
7540 /* Backslashes in a temp file name cause problems when filtering with
7541 * "sh". NOTE: This also checks 'shellcmdflag' to help those people who
7542 * didn't set 'shellslash'. */
7543 retval = vim_strsave(itmp);
7544 if (*p_shcf == '-' || p_ssl)
7545 for (p = retval; *p; ++p)
7546 if (*p == '\\')
7547 *p = '/';
7548 return retval;
7549
7550# else /* WIN3264 */
7551
7552# ifdef USE_TMPNAM
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007553 char_u *p;
7554
Bram Moolenaar071d4272004-06-13 20:20:40 +00007555 /* tmpnam() will make its own name */
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007556 p = tmpnam((char *)itmp);
7557 if (p == NULL || *p == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007558 return NULL;
7559# else
7560 char_u *p;
7561
7562# ifdef VMS_TEMPNAM
7563 /* mktemp() is not working on VMS. It seems to be
7564 * a do-nothing function. Therefore we use tempnam().
7565 */
7566 sprintf((char *)itmp, "VIM%c", extra_char);
7567 p = (char_u *)tempnam("tmp:", (char *)itmp);
7568 if (p != NULL)
7569 {
Bram Moolenaar206f0112014-03-12 16:51:55 +01007570 /* VMS will use '.LIS' if we don't explicitly specify an extension,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007571 * and VIM will then be unable to find the file later */
7572 STRCPY(itmp, p);
7573 STRCAT(itmp, ".txt");
7574 free(p);
7575 }
7576 else
7577 return NULL;
7578# else
7579 STRCPY(itmp, TEMPNAME);
7580 if ((p = vim_strchr(itmp, '?')) != NULL)
7581 *p = extra_char;
7582 if (mktemp((char *)itmp) == NULL)
7583 return NULL;
7584# endif
7585# endif
7586
7587 return vim_strsave(itmp);
7588# endif /* WIN3264 */
7589#endif /* TEMPDIRNAMES */
7590}
7591
7592#if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
7593/*
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02007594 * Convert all backslashes in fname to forward slashes in-place, unless when
7595 * it looks like a URL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007596 */
7597 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007598forward_slash(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007599{
7600 char_u *p;
7601
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02007602 if (path_with_url(fname))
7603 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007604 for (p = fname; *p != NUL; ++p)
7605# ifdef FEAT_MBYTE
7606 /* The Big5 encoding can have '\' in the trail byte. */
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00007607 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007608 ++p;
7609 else
7610# endif
7611 if (*p == '\\')
7612 *p = '/';
7613}
7614#endif
7615
7616
7617/*
7618 * Code for automatic commands.
7619 *
7620 * Only included when "FEAT_AUTOCMD" has been defined.
7621 */
7622
7623#if defined(FEAT_AUTOCMD) || defined(PROTO)
7624
7625/*
7626 * The autocommands are stored in a list for each event.
7627 * Autocommands for the same pattern, that are consecutive, are joined
7628 * together, to avoid having to match the pattern too often.
7629 * The result is an array of Autopat lists, which point to AutoCmd lists:
7630 *
7631 * first_autopat[0] --> Autopat.next --> Autopat.next --> NULL
7632 * Autopat.cmds Autopat.cmds
7633 * | |
7634 * V V
7635 * AutoCmd.next AutoCmd.next
7636 * | |
7637 * V V
7638 * AutoCmd.next NULL
7639 * |
7640 * V
7641 * NULL
7642 *
7643 * first_autopat[1] --> Autopat.next --> NULL
7644 * Autopat.cmds
7645 * |
7646 * V
7647 * AutoCmd.next
7648 * |
7649 * V
7650 * NULL
7651 * etc.
7652 *
7653 * The order of AutoCmds is important, this is the order in which they were
7654 * defined and will have to be executed.
7655 */
7656typedef struct AutoCmd
7657{
7658 char_u *cmd; /* The command to be executed (NULL
7659 when command has been removed) */
7660 char nested; /* If autocommands nest here */
7661 char last; /* last command in list */
7662#ifdef FEAT_EVAL
7663 scid_T scriptID; /* script ID where defined */
7664#endif
7665 struct AutoCmd *next; /* Next AutoCmd in list */
7666} AutoCmd;
7667
7668typedef struct AutoPat
7669{
Bram Moolenaar071d4272004-06-13 20:20:40 +00007670 char_u *pat; /* pattern as typed (NULL when pattern
7671 has been removed) */
Bram Moolenaar748bf032005-02-02 23:04:36 +00007672 regprog_T *reg_prog; /* compiled regprog for pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007673 AutoCmd *cmds; /* list of commands to do */
7674 struct AutoPat *next; /* next AutoPat in AutoPat list */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007675 int group; /* group ID */
7676 int patlen; /* strlen() of pat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007677 int buflocal_nr; /* !=0 for buffer-local AutoPat */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007678 char allow_dirs; /* Pattern may match whole path */
7679 char last; /* last pattern for apply_autocmds() */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007680} AutoPat;
7681
7682static struct event_name
7683{
7684 char *name; /* event name */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007685 event_T event; /* event number */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007686} event_names[] =
7687{
7688 {"BufAdd", EVENT_BUFADD},
7689 {"BufCreate", EVENT_BUFADD},
7690 {"BufDelete", EVENT_BUFDELETE},
7691 {"BufEnter", EVENT_BUFENTER},
7692 {"BufFilePost", EVENT_BUFFILEPOST},
7693 {"BufFilePre", EVENT_BUFFILEPRE},
7694 {"BufHidden", EVENT_BUFHIDDEN},
7695 {"BufLeave", EVENT_BUFLEAVE},
7696 {"BufNew", EVENT_BUFNEW},
7697 {"BufNewFile", EVENT_BUFNEWFILE},
7698 {"BufRead", EVENT_BUFREADPOST},
7699 {"BufReadCmd", EVENT_BUFREADCMD},
7700 {"BufReadPost", EVENT_BUFREADPOST},
7701 {"BufReadPre", EVENT_BUFREADPRE},
7702 {"BufUnload", EVENT_BUFUNLOAD},
7703 {"BufWinEnter", EVENT_BUFWINENTER},
7704 {"BufWinLeave", EVENT_BUFWINLEAVE},
7705 {"BufWipeout", EVENT_BUFWIPEOUT},
7706 {"BufWrite", EVENT_BUFWRITEPRE},
7707 {"BufWritePost", EVENT_BUFWRITEPOST},
7708 {"BufWritePre", EVENT_BUFWRITEPRE},
7709 {"BufWriteCmd", EVENT_BUFWRITECMD},
Bram Moolenaarfafcf0d2017-10-19 18:35:51 +02007710 {"CmdlineEnter", EVENT_CMDLINEENTER},
7711 {"CmdlineLeave", EVENT_CMDLINELEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007712 {"CmdwinEnter", EVENT_CMDWINENTER},
7713 {"CmdwinLeave", EVENT_CMDWINLEAVE},
Bram Moolenaard5005162014-08-22 23:05:54 +02007714 {"CmdUndefined", EVENT_CMDUNDEFINED},
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007715 {"ColorScheme", EVENT_COLORSCHEME},
Bram Moolenaarcfa3cae2012-07-10 17:14:56 +02007716 {"CompleteDone", EVENT_COMPLETEDONE},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007717 {"CursorHold", EVENT_CURSORHOLD},
7718 {"CursorHoldI", EVENT_CURSORHOLDI},
7719 {"CursorMoved", EVENT_CURSORMOVED},
7720 {"CursorMovedI", EVENT_CURSORMOVEDI},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007721 {"EncodingChanged", EVENT_ENCODINGCHANGED},
7722 {"FileEncoding", EVENT_ENCODINGCHANGED},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007723 {"FileAppendPost", EVENT_FILEAPPENDPOST},
7724 {"FileAppendPre", EVENT_FILEAPPENDPRE},
7725 {"FileAppendCmd", EVENT_FILEAPPENDCMD},
7726 {"FileChangedShell",EVENT_FILECHANGEDSHELL},
Bram Moolenaar56718732006-03-15 22:53:57 +00007727 {"FileChangedShellPost",EVENT_FILECHANGEDSHELLPOST},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007728 {"FileChangedRO", EVENT_FILECHANGEDRO},
7729 {"FileReadPost", EVENT_FILEREADPOST},
7730 {"FileReadPre", EVENT_FILEREADPRE},
7731 {"FileReadCmd", EVENT_FILEREADCMD},
7732 {"FileType", EVENT_FILETYPE},
7733 {"FileWritePost", EVENT_FILEWRITEPOST},
7734 {"FileWritePre", EVENT_FILEWRITEPRE},
7735 {"FileWriteCmd", EVENT_FILEWRITECMD},
7736 {"FilterReadPost", EVENT_FILTERREADPOST},
7737 {"FilterReadPre", EVENT_FILTERREADPRE},
7738 {"FilterWritePost", EVENT_FILTERWRITEPOST},
7739 {"FilterWritePre", EVENT_FILTERWRITEPRE},
7740 {"FocusGained", EVENT_FOCUSGAINED},
7741 {"FocusLost", EVENT_FOCUSLOST},
7742 {"FuncUndefined", EVENT_FUNCUNDEFINED},
7743 {"GUIEnter", EVENT_GUIENTER},
Bram Moolenaar265e5072006-08-29 16:13:22 +00007744 {"GUIFailed", EVENT_GUIFAILED},
Bram Moolenaar843ee412004-06-30 16:16:41 +00007745 {"InsertChange", EVENT_INSERTCHANGE},
7746 {"InsertEnter", EVENT_INSERTENTER},
7747 {"InsertLeave", EVENT_INSERTLEAVE},
Bram Moolenaare659c952011-05-19 17:25:41 +02007748 {"InsertCharPre", EVENT_INSERTCHARPRE},
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00007749 {"MenuPopup", EVENT_MENUPOPUP},
Bram Moolenaar53744302015-07-17 17:38:22 +02007750 {"OptionSet", EVENT_OPTIONSET},
Bram Moolenaar7c626922005-02-07 22:01:03 +00007751 {"QuickFixCmdPost", EVENT_QUICKFIXCMDPOST},
7752 {"QuickFixCmdPre", EVENT_QUICKFIXCMDPRE},
Bram Moolenaar3b53dfb2012-06-06 18:03:07 +02007753 {"QuitPre", EVENT_QUITPRE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007754 {"RemoteReply", EVENT_REMOTEREPLY},
Bram Moolenaar9372a112005-12-06 19:59:18 +00007755 {"SessionLoadPost", EVENT_SESSIONLOADPOST},
Bram Moolenaar5c4bab02006-03-10 21:37:46 +00007756 {"ShellCmdPost", EVENT_SHELLCMDPOST},
7757 {"ShellFilterPost", EVENT_SHELLFILTERPOST},
Bram Moolenaara2031822006-03-07 22:29:51 +00007758 {"SourcePre", EVENT_SOURCEPRE},
Bram Moolenaar8dd1aa52007-01-16 20:33:19 +00007759 {"SourceCmd", EVENT_SOURCECMD},
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00007760 {"SpellFileMissing",EVENT_SPELLFILEMISSING},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007761 {"StdinReadPost", EVENT_STDINREADPOST},
7762 {"StdinReadPre", EVENT_STDINREADPRE},
Bram Moolenaarb815dac2005-12-07 20:59:24 +00007763 {"SwapExists", EVENT_SWAPEXISTS},
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00007764 {"Syntax", EVENT_SYNTAX},
Bram Moolenaarc917da42016-07-19 22:31:36 +02007765 {"TabNew", EVENT_TABNEW},
Bram Moolenaar12c11d52016-07-19 23:13:03 +02007766 {"TabClosed", EVENT_TABCLOSED},
Bram Moolenaar70836c82006-02-20 21:28:49 +00007767 {"TabEnter", EVENT_TABENTER},
7768 {"TabLeave", EVENT_TABLEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007769 {"TermChanged", EVENT_TERMCHANGED},
7770 {"TermResponse", EVENT_TERMRESPONSE},
Bram Moolenaar186628f2013-03-19 13:33:23 +01007771 {"TextChanged", EVENT_TEXTCHANGED},
7772 {"TextChangedI", EVENT_TEXTCHANGEDI},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007773 {"User", EVENT_USER},
7774 {"VimEnter", EVENT_VIMENTER},
7775 {"VimLeave", EVENT_VIMLEAVE},
7776 {"VimLeavePre", EVENT_VIMLEAVEPRE},
Bram Moolenaarc917da42016-07-19 22:31:36 +02007777 {"WinNew", EVENT_WINNEW},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007778 {"WinEnter", EVENT_WINENTER},
7779 {"WinLeave", EVENT_WINLEAVE},
Bram Moolenaar56718732006-03-15 22:53:57 +00007780 {"VimResized", EVENT_VIMRESIZED},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007781 {NULL, (event_T)0}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007782};
7783
7784static AutoPat *first_autopat[NUM_EVENTS] =
7785{
7786 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7787 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7788 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7789 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00007790 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaar53744302015-07-17 17:38:22 +02007791 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007792};
7793
7794/*
7795 * struct used to keep status while executing autocommands for an event.
7796 */
7797typedef struct AutoPatCmd
7798{
7799 AutoPat *curpat; /* next AutoPat to examine */
7800 AutoCmd *nextcmd; /* next AutoCmd to execute */
7801 int group; /* group being used */
7802 char_u *fname; /* fname to match with */
7803 char_u *sfname; /* sfname to match with */
7804 char_u *tail; /* tail of fname */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007805 event_T event; /* current event */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007806 int arg_bufnr; /* initially equal to <abuf>, set to zero when
7807 buf is deleted */
7808 struct AutoPatCmd *next; /* chain of active apc-s for auto-invalidation*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00007809} AutoPatCmd;
7810
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007811static AutoPatCmd *active_apc_list = NULL; /* stack of active autocommands */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007812
Bram Moolenaar071d4272004-06-13 20:20:40 +00007813/*
7814 * augroups stores a list of autocmd group names.
7815 */
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007816static garray_T augroups = {0, 0, sizeof(char_u *), 10, NULL};
Bram Moolenaar071d4272004-06-13 20:20:40 +00007817#define AUGROUP_NAME(i) (((char_u **)augroups.ga_data)[i])
Bram Moolenaarb62cc362016-09-03 16:43:53 +02007818/* use get_deleted_augroup() to get this */
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02007819static char_u *deleted_augroup = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007820
7821/*
7822 * The ID of the current group. Group 0 is the default one.
7823 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007824static int current_augroup = AUGROUP_DEFAULT;
7825
7826static int au_need_clean = FALSE; /* need to delete marked patterns */
7827
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007828static void show_autocmd(AutoPat *ap, event_T event);
7829static void au_remove_pat(AutoPat *ap);
7830static void au_remove_cmds(AutoPat *ap);
7831static void au_cleanup(void);
7832static int au_new_group(char_u *name);
7833static void au_del_group(char_u *name);
7834static event_T event_name2nr(char_u *start, char_u **end);
7835static char_u *event_nr2name(event_T event);
7836static char_u *find_end_event(char_u *arg, int have_group);
7837static int event_ignored(event_T event);
7838static int au_get_grouparg(char_u **argp);
7839static int do_autocmd_event(event_T event, char_u *pat, int nested, char_u *cmd, int forceit, int group);
7840static int apply_autocmds_group(event_T event, char_u *fname, char_u *fname_io, int force, int group, buf_T *buf, exarg_T *eap);
7841static void auto_next_pat(AutoPatCmd *apc, int stop_at_last);
Bram Moolenaardffa5b82014-11-19 16:38:07 +01007842#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN)
Bram Moolenaard25c16e2016-01-29 22:13:30 +01007843static 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 +01007844#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007845
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007846
Bram Moolenaar754b5602006-02-09 23:53:20 +00007847static event_T last_event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007848static int last_group;
Bram Moolenaar78ab3312007-09-29 12:16:41 +00007849static int autocmd_blocked = 0; /* block all autocmds */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007850
Bram Moolenaarb62cc362016-09-03 16:43:53 +02007851 static char_u *
7852get_deleted_augroup(void)
7853{
7854 if (deleted_augroup == NULL)
7855 deleted_augroup = (char_u *)_("--Deleted--");
7856 return deleted_augroup;
7857}
7858
Bram Moolenaar071d4272004-06-13 20:20:40 +00007859/*
7860 * Show the autocommands for one AutoPat.
7861 */
7862 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007863show_autocmd(AutoPat *ap, event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007864{
7865 AutoCmd *ac;
7866
7867 /* Check for "got_int" (here and at various places below), which is set
7868 * when "q" has been hit for the "--more--" prompt */
7869 if (got_int)
7870 return;
7871 if (ap->pat == NULL) /* pattern has been removed */
7872 return;
7873
7874 msg_putchar('\n');
7875 if (got_int)
7876 return;
7877 if (event != last_event || ap->group != last_group)
7878 {
7879 if (ap->group != AUGROUP_DEFAULT)
7880 {
7881 if (AUGROUP_NAME(ap->group) == NULL)
Bram Moolenaar8820b482017-03-16 17:23:31 +01007882 msg_puts_attr(get_deleted_augroup(), HL_ATTR(HLF_E));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007883 else
Bram Moolenaar8820b482017-03-16 17:23:31 +01007884 msg_puts_attr(AUGROUP_NAME(ap->group), HL_ATTR(HLF_T));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007885 msg_puts((char_u *)" ");
7886 }
Bram Moolenaar8820b482017-03-16 17:23:31 +01007887 msg_puts_attr(event_nr2name(event), HL_ATTR(HLF_T));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007888 last_event = event;
7889 last_group = ap->group;
7890 msg_putchar('\n');
7891 if (got_int)
7892 return;
7893 }
7894 msg_col = 4;
7895 msg_outtrans(ap->pat);
7896
7897 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7898 {
7899 if (ac->cmd != NULL) /* skip removed commands */
7900 {
7901 if (msg_col >= 14)
7902 msg_putchar('\n');
7903 msg_col = 14;
7904 if (got_int)
7905 return;
7906 msg_outtrans(ac->cmd);
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00007907#ifdef FEAT_EVAL
7908 if (p_verbose > 0)
7909 last_set_msg(ac->scriptID);
7910#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007911 if (got_int)
7912 return;
7913 if (ac->next != NULL)
7914 {
7915 msg_putchar('\n');
7916 if (got_int)
7917 return;
7918 }
7919 }
7920 }
7921}
7922
7923/*
7924 * Mark an autocommand pattern for deletion.
7925 */
7926 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007927au_remove_pat(AutoPat *ap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007928{
7929 vim_free(ap->pat);
7930 ap->pat = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007931 ap->buflocal_nr = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007932 au_need_clean = TRUE;
7933}
7934
7935/*
7936 * Mark all commands for a pattern for deletion.
7937 */
7938 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007939au_remove_cmds(AutoPat *ap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007940{
7941 AutoCmd *ac;
7942
7943 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7944 {
7945 vim_free(ac->cmd);
7946 ac->cmd = NULL;
7947 }
7948 au_need_clean = TRUE;
7949}
7950
7951/*
7952 * Cleanup autocommands and patterns that have been deleted.
7953 * This is only done when not executing autocommands.
7954 */
7955 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007956au_cleanup(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007957{
7958 AutoPat *ap, **prev_ap;
7959 AutoCmd *ac, **prev_ac;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007960 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007961
7962 if (autocmd_busy || !au_need_clean)
7963 return;
7964
7965 /* loop over all events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007966 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7967 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007968 {
7969 /* loop over all autocommand patterns */
7970 prev_ap = &(first_autopat[(int)event]);
7971 for (ap = *prev_ap; ap != NULL; ap = *prev_ap)
7972 {
7973 /* loop over all commands for this pattern */
7974 prev_ac = &(ap->cmds);
7975 for (ac = *prev_ac; ac != NULL; ac = *prev_ac)
7976 {
7977 /* remove the command if the pattern is to be deleted or when
7978 * the command has been marked for deletion */
7979 if (ap->pat == NULL || ac->cmd == NULL)
7980 {
7981 *prev_ac = ac->next;
7982 vim_free(ac->cmd);
7983 vim_free(ac);
7984 }
7985 else
7986 prev_ac = &(ac->next);
7987 }
7988
7989 /* remove the pattern if it has been marked for deletion */
7990 if (ap->pat == NULL)
7991 {
7992 *prev_ap = ap->next;
Bram Moolenaar473de612013-06-08 18:19:48 +02007993 vim_regfree(ap->reg_prog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007994 vim_free(ap);
7995 }
7996 else
7997 prev_ap = &(ap->next);
7998 }
7999 }
8000
8001 au_need_clean = FALSE;
8002}
8003
8004/*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008005 * Called when buffer is freed, to remove/invalidate related buffer-local
8006 * autocmds.
8007 */
8008 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008009aubuflocal_remove(buf_T *buf)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008010{
8011 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008012 event_T event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008013 AutoPatCmd *apc;
8014
8015 /* invalidate currently executing autocommands */
8016 for (apc = active_apc_list; apc; apc = apc->next)
8017 if (buf->b_fnum == apc->arg_bufnr)
8018 apc->arg_bufnr = 0;
8019
8020 /* invalidate buflocals looping through events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008021 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8022 event = (event_T)((int)event + 1))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008023 /* loop over all autocommand patterns */
8024 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8025 if (ap->buflocal_nr == buf->b_fnum)
8026 {
8027 au_remove_pat(ap);
8028 if (p_verbose >= 6)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00008029 {
8030 verbose_enter();
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008031 smsg((char_u *)
8032 _("auto-removing autocommand: %s <buffer=%d>"),
8033 event_nr2name(event), buf->b_fnum);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00008034 verbose_leave();
8035 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008036 }
8037 au_cleanup();
8038}
8039
8040/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008041 * Add an autocmd group name.
8042 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
8043 */
8044 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008045au_new_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008046{
8047 int i;
8048
8049 i = au_find_group(name);
8050 if (i == AUGROUP_ERROR) /* the group doesn't exist yet, add it */
8051 {
8052 /* First try using a free entry. */
8053 for (i = 0; i < augroups.ga_len; ++i)
8054 if (AUGROUP_NAME(i) == NULL)
8055 break;
8056 if (i == augroups.ga_len && ga_grow(&augroups, 1) == FAIL)
8057 return AUGROUP_ERROR;
8058
8059 AUGROUP_NAME(i) = vim_strsave(name);
8060 if (AUGROUP_NAME(i) == NULL)
8061 return AUGROUP_ERROR;
8062 if (i == augroups.ga_len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008063 ++augroups.ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008064 }
8065
8066 return i;
8067}
8068
8069 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008070au_del_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008071{
8072 int i;
8073
8074 i = au_find_group(name);
8075 if (i == AUGROUP_ERROR) /* the group doesn't exist */
8076 EMSG2(_("E367: No such group: \"%s\""), name);
Bram Moolenaarde653f02016-09-03 16:59:06 +02008077 else if (i == current_augroup)
8078 EMSG(_("E936: Cannot delete the current group"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008079 else
8080 {
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008081 event_T event;
8082 AutoPat *ap;
8083 int in_use = FALSE;
8084
8085 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8086 event = (event_T)((int)event + 1))
8087 {
8088 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
Bram Moolenaar5c809082016-09-01 16:21:48 +02008089 if (ap->group == i && ap->pat != NULL)
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008090 {
8091 give_warning((char_u *)_("W19: Deleting augroup that is still in use"), TRUE);
8092 in_use = TRUE;
8093 event = NUM_EVENTS;
8094 break;
8095 }
8096 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008097 vim_free(AUGROUP_NAME(i));
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008098 if (in_use)
8099 {
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008100 AUGROUP_NAME(i) = get_deleted_augroup();
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008101 }
8102 else
8103 AUGROUP_NAME(i) = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008104 }
8105}
8106
8107/*
8108 * Find the ID of an autocmd group name.
8109 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
8110 */
8111 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008112au_find_group(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008113{
8114 int i;
8115
8116 for (i = 0; i < augroups.ga_len; ++i)
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008117 if (AUGROUP_NAME(i) != NULL && AUGROUP_NAME(i) != get_deleted_augroup()
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008118 && STRCMP(AUGROUP_NAME(i), name) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008119 return i;
8120 return AUGROUP_ERROR;
8121}
8122
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008123/*
8124 * Return TRUE if augroup "name" exists.
8125 */
8126 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008127au_has_group(char_u *name)
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008128{
8129 return au_find_group(name) != AUGROUP_ERROR;
8130}
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008131
Bram Moolenaar071d4272004-06-13 20:20:40 +00008132/*
8133 * ":augroup {name}".
8134 */
8135 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008136do_augroup(char_u *arg, int del_group)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008137{
8138 int i;
8139
8140 if (del_group)
8141 {
8142 if (*arg == NUL)
8143 EMSG(_(e_argreq));
8144 else
8145 au_del_group(arg);
8146 }
8147 else if (STRICMP(arg, "end") == 0) /* ":aug end": back to group 0 */
8148 current_augroup = AUGROUP_DEFAULT;
8149 else if (*arg) /* ":aug xxx": switch to group xxx */
8150 {
8151 i = au_new_group(arg);
8152 if (i != AUGROUP_ERROR)
8153 current_augroup = i;
8154 }
8155 else /* ":aug": list the group names */
8156 {
8157 msg_start();
8158 for (i = 0; i < augroups.ga_len; ++i)
8159 {
8160 if (AUGROUP_NAME(i) != NULL)
8161 {
8162 msg_puts(AUGROUP_NAME(i));
8163 msg_puts((char_u *)" ");
8164 }
8165 }
8166 msg_clr_eos();
8167 msg_end();
8168 }
8169}
8170
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008171#if defined(EXITFREE) || defined(PROTO)
8172 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008173free_all_autocmds(void)
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008174{
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008175 int i;
8176 char_u *s;
8177
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008178 for (current_augroup = -1; current_augroup < augroups.ga_len;
8179 ++current_augroup)
8180 do_autocmd((char_u *)"", TRUE);
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008181
8182 for (i = 0; i < augroups.ga_len; ++i)
8183 {
8184 s = ((char_u **)(augroups.ga_data))[i];
Bram Moolenaarb62cc362016-09-03 16:43:53 +02008185 if (s != get_deleted_augroup())
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02008186 vim_free(s);
8187 }
8188 ga_clear(&augroups);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008189}
8190#endif
8191
Bram Moolenaar071d4272004-06-13 20:20:40 +00008192/*
8193 * Return the event number for event name "start".
8194 * Return NUM_EVENTS if the event name was not found.
8195 * Return a pointer to the next event name in "end".
8196 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008197 static event_T
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008198event_name2nr(char_u *start, char_u **end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008199{
8200 char_u *p;
8201 int i;
8202 int len;
8203
Bram Moolenaare99e8442016-07-26 20:43:40 +02008204 /* the event name ends with end of line, '|', a blank or a comma */
Bram Moolenaar1c465442017-03-12 20:10:05 +01008205 for (p = start; *p && !VIM_ISWHITE(*p) && *p != ',' && *p != '|'; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008206 ;
8207 for (i = 0; event_names[i].name != NULL; ++i)
8208 {
8209 len = (int)STRLEN(event_names[i].name);
8210 if (len == p - start && STRNICMP(event_names[i].name, start, len) == 0)
8211 break;
8212 }
8213 if (*p == ',')
8214 ++p;
8215 *end = p;
8216 if (event_names[i].name == NULL)
8217 return NUM_EVENTS;
8218 return event_names[i].event;
8219}
8220
8221/*
8222 * Return the name for event "event".
8223 */
8224 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008225event_nr2name(event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008226{
8227 int i;
8228
8229 for (i = 0; event_names[i].name != NULL; ++i)
8230 if (event_names[i].event == event)
8231 return (char_u *)event_names[i].name;
8232 return (char_u *)"Unknown";
8233}
8234
8235/*
8236 * Scan over the events. "*" stands for all events.
8237 */
8238 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008239find_end_event(
8240 char_u *arg,
8241 int have_group) /* TRUE when group name was found */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008242{
8243 char_u *pat;
8244 char_u *p;
8245
8246 if (*arg == '*')
8247 {
Bram Moolenaar1c465442017-03-12 20:10:05 +01008248 if (arg[1] && !VIM_ISWHITE(arg[1]))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008249 {
8250 EMSG2(_("E215: Illegal character after *: %s"), arg);
8251 return NULL;
8252 }
8253 pat = arg + 1;
8254 }
8255 else
8256 {
Bram Moolenaar1c465442017-03-12 20:10:05 +01008257 for (pat = arg; *pat && *pat != '|' && !VIM_ISWHITE(*pat); pat = p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008258 {
8259 if ((int)event_name2nr(pat, &p) >= (int)NUM_EVENTS)
8260 {
8261 if (have_group)
8262 EMSG2(_("E216: No such event: %s"), pat);
8263 else
8264 EMSG2(_("E216: No such group or event: %s"), pat);
8265 return NULL;
8266 }
8267 }
8268 }
8269 return pat;
8270}
8271
8272/*
8273 * Return TRUE if "event" is included in 'eventignore'.
8274 */
8275 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008276event_ignored(event_T event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008277{
8278 char_u *p = p_ei;
8279
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008280 while (*p != NUL)
8281 {
8282 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8283 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008284 if (event_name2nr(p, &p) == event)
8285 return TRUE;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008286 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008287
8288 return FALSE;
8289}
8290
8291/*
8292 * Return OK when the contents of p_ei is valid, FAIL otherwise.
8293 */
8294 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008295check_ei(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008296{
8297 char_u *p = p_ei;
8298
Bram Moolenaar071d4272004-06-13 20:20:40 +00008299 while (*p)
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008300 {
8301 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8302 {
8303 p += 3;
8304 if (*p == ',')
8305 ++p;
8306 }
8307 else if (event_name2nr(p, &p) == NUM_EVENTS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008308 return FAIL;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008309 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008310
8311 return OK;
8312}
8313
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008314# if defined(FEAT_SYN_HL) || defined(PROTO)
8315
8316/*
8317 * Add "what" to 'eventignore' to skip loading syntax highlighting for every
8318 * buffer loaded into the window. "what" must start with a comma.
8319 * Returns the old value of 'eventignore' in allocated memory.
8320 */
8321 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008322au_event_disable(char *what)
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008323{
8324 char_u *new_ei;
8325 char_u *save_ei;
8326
8327 save_ei = vim_strsave(p_ei);
8328 if (save_ei != NULL)
8329 {
Bram Moolenaara5792f52005-11-23 21:25:05 +00008330 new_ei = vim_strnsave(p_ei, (int)(STRLEN(p_ei) + STRLEN(what)));
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008331 if (new_ei != NULL)
8332 {
Bram Moolenaar8cac9fd2010-03-02 12:48:05 +01008333 if (*what == ',' && *p_ei == NUL)
8334 STRCPY(new_ei, what + 1);
8335 else
8336 STRCAT(new_ei, what);
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008337 set_string_option_direct((char_u *)"ei", -1, new_ei,
8338 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008339 vim_free(new_ei);
8340 }
8341 }
8342 return save_ei;
8343}
8344
8345 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008346au_event_restore(char_u *old_ei)
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008347{
8348 if (old_ei != NULL)
8349 {
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008350 set_string_option_direct((char_u *)"ei", -1, old_ei,
8351 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008352 vim_free(old_ei);
8353 }
8354}
8355# endif /* FEAT_SYN_HL */
8356
Bram Moolenaar071d4272004-06-13 20:20:40 +00008357/*
8358 * do_autocmd() -- implements the :autocmd command. Can be used in the
8359 * following ways:
8360 *
8361 * :autocmd <event> <pat> <cmd> Add <cmd> to the list of commands that
8362 * will be automatically executed for <event>
8363 * when editing a file matching <pat>, in
8364 * the current group.
8365 * :autocmd <event> <pat> Show the auto-commands associated with
8366 * <event> and <pat>.
8367 * :autocmd <event> Show the auto-commands associated with
8368 * <event>.
8369 * :autocmd Show all auto-commands.
8370 * :autocmd! <event> <pat> <cmd> Remove all auto-commands associated with
8371 * <event> and <pat>, and add the command
8372 * <cmd>, for the current group.
8373 * :autocmd! <event> <pat> Remove all auto-commands associated with
8374 * <event> and <pat> for the current group.
8375 * :autocmd! <event> Remove all auto-commands associated with
8376 * <event> for the current group.
8377 * :autocmd! Remove ALL auto-commands for the current
8378 * group.
8379 *
8380 * Multiple events and patterns may be given separated by commas. Here are
8381 * some examples:
8382 * :autocmd bufread,bufenter *.c,*.h set tw=0 smartindent noic
8383 * :autocmd bufleave * set tw=79 nosmartindent ic infercase
8384 *
8385 * :autocmd * *.c show all autocommands for *.c files.
Bram Moolenaard35f9712005-12-18 22:02:33 +00008386 *
8387 * Mostly a {group} argument can optionally appear before <event>.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008388 */
8389 void
Bram Moolenaare99e8442016-07-26 20:43:40 +02008390do_autocmd(char_u *arg_in, int forceit)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008391{
Bram Moolenaare99e8442016-07-26 20:43:40 +02008392 char_u *arg = arg_in;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008393 char_u *pat;
8394 char_u *envpat = NULL;
8395 char_u *cmd;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008396 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008397 int need_free = FALSE;
8398 int nested = FALSE;
8399 int group;
8400
Bram Moolenaare99e8442016-07-26 20:43:40 +02008401 if (*arg == '|')
8402 {
8403 arg = (char_u *)"";
8404 group = AUGROUP_ALL; /* no argument, use all groups */
8405 }
8406 else
8407 {
8408 /*
8409 * Check for a legal group name. If not, use AUGROUP_ALL.
8410 */
8411 group = au_get_grouparg(&arg);
8412 if (arg == NULL) /* out of memory */
8413 return;
8414 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008415
8416 /*
8417 * Scan over the events.
8418 * If we find an illegal name, return here, don't do anything.
8419 */
8420 pat = find_end_event(arg, group != AUGROUP_ALL);
8421 if (pat == NULL)
8422 return;
8423
Bram Moolenaar071d4272004-06-13 20:20:40 +00008424 pat = skipwhite(pat);
Bram Moolenaare99e8442016-07-26 20:43:40 +02008425 if (*pat == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008426 {
Bram Moolenaare99e8442016-07-26 20:43:40 +02008427 pat = (char_u *)"";
8428 cmd = (char_u *)"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00008429 }
Bram Moolenaare99e8442016-07-26 20:43:40 +02008430 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00008431 {
Bram Moolenaare99e8442016-07-26 20:43:40 +02008432 /*
8433 * Scan over the pattern. Put a NUL at the end.
8434 */
8435 cmd = pat;
Bram Moolenaar1c465442017-03-12 20:10:05 +01008436 while (*cmd && (!VIM_ISWHITE(*cmd) || cmd[-1] == '\\'))
Bram Moolenaare99e8442016-07-26 20:43:40 +02008437 cmd++;
8438 if (*cmd)
8439 *cmd++ = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008440
Bram Moolenaare99e8442016-07-26 20:43:40 +02008441 /* Expand environment variables in the pattern. Set 'shellslash', we want
8442 * forward slashes here. */
8443 if (vim_strchr(pat, '$') != NULL || vim_strchr(pat, '~') != NULL)
8444 {
8445#ifdef BACKSLASH_IN_FILENAME
8446 int p_ssl_save = p_ssl;
8447
8448 p_ssl = TRUE;
8449#endif
8450 envpat = expand_env_save(pat);
8451#ifdef BACKSLASH_IN_FILENAME
8452 p_ssl = p_ssl_save;
8453#endif
8454 if (envpat != NULL)
8455 pat = envpat;
8456 }
8457
8458 /*
8459 * Check for "nested" flag.
8460 */
8461 cmd = skipwhite(cmd);
Bram Moolenaar1c465442017-03-12 20:10:05 +01008462 if (*cmd != NUL && STRNCMP(cmd, "nested", 6) == 0 && VIM_ISWHITE(cmd[6]))
Bram Moolenaare99e8442016-07-26 20:43:40 +02008463 {
8464 nested = TRUE;
8465 cmd = skipwhite(cmd + 6);
8466 }
8467
8468 /*
8469 * Find the start of the commands.
8470 * Expand <sfile> in it.
8471 */
8472 if (*cmd != NUL)
8473 {
8474 cmd = expand_sfile(cmd);
8475 if (cmd == NULL) /* some error */
8476 return;
8477 need_free = TRUE;
8478 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008479 }
8480
8481 /*
8482 * Print header when showing autocommands.
8483 */
8484 if (!forceit && *cmd == NUL)
8485 {
8486 /* Highlight title */
8487 MSG_PUTS_TITLE(_("\n--- Auto-Commands ---"));
8488 }
8489
8490 /*
8491 * Loop over the events.
8492 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008493 last_event = (event_T)-1; /* for listing the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008494 last_group = AUGROUP_ERROR; /* for listing the group name */
Bram Moolenaare99e8442016-07-26 20:43:40 +02008495 if (*arg == '*' || *arg == NUL || *arg == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008496 {
Bram Moolenaar754b5602006-02-09 23:53:20 +00008497 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8498 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008499 if (do_autocmd_event(event, pat,
8500 nested, cmd, forceit, group) == FAIL)
8501 break;
8502 }
8503 else
8504 {
Bram Moolenaar1c465442017-03-12 20:10:05 +01008505 while (*arg && *arg != '|' && !VIM_ISWHITE(*arg))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008506 if (do_autocmd_event(event_name2nr(arg, &arg), pat,
8507 nested, cmd, forceit, group) == FAIL)
8508 break;
8509 }
8510
8511 if (need_free)
8512 vim_free(cmd);
8513 vim_free(envpat);
8514}
8515
8516/*
8517 * Find the group ID in a ":autocmd" or ":doautocmd" argument.
8518 * The "argp" argument is advanced to the following argument.
8519 *
8520 * Returns the group ID, AUGROUP_ERROR for error (out of memory).
8521 */
8522 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008523au_get_grouparg(char_u **argp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008524{
8525 char_u *group_name;
8526 char_u *p;
8527 char_u *arg = *argp;
8528 int group = AUGROUP_ALL;
8529
Bram Moolenaar1c465442017-03-12 20:10:05 +01008530 for (p = arg; *p && !VIM_ISWHITE(*p) && *p != '|'; ++p)
Bram Moolenaare99e8442016-07-26 20:43:40 +02008531 ;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008532 if (p > arg)
8533 {
8534 group_name = vim_strnsave(arg, (int)(p - arg));
8535 if (group_name == NULL) /* out of memory */
8536 return AUGROUP_ERROR;
8537 group = au_find_group(group_name);
8538 if (group == AUGROUP_ERROR)
8539 group = AUGROUP_ALL; /* no match, use all groups */
8540 else
8541 *argp = skipwhite(p); /* match, skip over group name */
8542 vim_free(group_name);
8543 }
8544 return group;
8545}
8546
8547/*
8548 * do_autocmd() for one event.
8549 * If *pat == NUL do for all patterns.
8550 * If *cmd == NUL show entries.
8551 * If forceit == TRUE delete entries.
8552 * If group is not AUGROUP_ALL, only use this group.
8553 */
8554 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008555do_autocmd_event(
8556 event_T event,
8557 char_u *pat,
8558 int nested,
8559 char_u *cmd,
8560 int forceit,
8561 int group)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008562{
8563 AutoPat *ap;
8564 AutoPat **prev_ap;
8565 AutoCmd *ac;
8566 AutoCmd **prev_ac;
8567 int brace_level;
8568 char_u *endpat;
8569 int findgroup;
8570 int allgroups;
8571 int patlen;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00008572 int is_buflocal;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008573 int buflocal_nr;
8574 char_u buflocal_pat[25]; /* for "<buffer=X>" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008575
8576 if (group == AUGROUP_ALL)
8577 findgroup = current_augroup;
8578 else
8579 findgroup = group;
8580 allgroups = (group == AUGROUP_ALL && !forceit && *cmd == NUL);
8581
8582 /*
8583 * Show or delete all patterns for an event.
8584 */
8585 if (*pat == NUL)
8586 {
8587 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8588 {
8589 if (forceit) /* delete the AutoPat, if it's in the current group */
8590 {
8591 if (ap->group == findgroup)
8592 au_remove_pat(ap);
8593 }
8594 else if (group == AUGROUP_ALL || ap->group == group)
8595 show_autocmd(ap, event);
8596 }
8597 }
8598
8599 /*
8600 * Loop through all the specified patterns.
8601 */
8602 for ( ; *pat; pat = (*endpat == ',' ? endpat + 1 : endpat))
8603 {
8604 /*
8605 * Find end of the pattern.
8606 * Watch out for a comma in braces, like "*.\{obj,o\}".
8607 */
8608 brace_level = 0;
8609 for (endpat = pat; *endpat && (*endpat != ',' || brace_level
Bram Moolenaar6b9be1b2015-07-28 13:33:45 +02008610 || (endpat > pat && endpat[-1] == '\\')); ++endpat)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008611 {
8612 if (*endpat == '{')
8613 brace_level++;
8614 else if (*endpat == '}')
8615 brace_level--;
8616 }
8617 if (pat == endpat) /* ignore single comma */
8618 continue;
8619 patlen = (int)(endpat - pat);
8620
8621 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008622 * detect special <buflocal[=X]> buffer-local patterns
8623 */
8624 is_buflocal = FALSE;
8625 buflocal_nr = 0;
8626
Bram Moolenaar1e997822015-02-17 16:04:57 +01008627 if (patlen >= 8 && STRNCMP(pat, "<buffer", 7) == 0
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008628 && pat[patlen - 1] == '>')
8629 {
Bram Moolenaar1e997822015-02-17 16:04:57 +01008630 /* "<buffer...>": Error will be printed only for addition.
8631 * printing and removing will proceed silently. */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008632 is_buflocal = TRUE;
8633 if (patlen == 8)
Bram Moolenaar1e997822015-02-17 16:04:57 +01008634 /* "<buffer>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008635 buflocal_nr = curbuf->b_fnum;
8636 else if (patlen > 9 && pat[7] == '=')
8637 {
Bram Moolenaar1e997822015-02-17 16:04:57 +01008638 if (patlen == 13 && STRNICMP(pat, "<buffer=abuf>", 13) == 0)
8639 /* "<buffer=abuf>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008640 buflocal_nr = autocmd_bufnr;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008641 else if (skipdigits(pat + 8) == pat + patlen - 1)
Bram Moolenaar1e997822015-02-17 16:04:57 +01008642 /* "<buffer=123>" */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008643 buflocal_nr = atoi((char *)pat + 8);
8644 }
8645 }
8646
8647 if (is_buflocal)
8648 {
8649 /* normalize pat into standard "<buffer>#N" form */
8650 sprintf((char *)buflocal_pat, "<buffer=%d>", buflocal_nr);
8651 pat = buflocal_pat; /* can modify pat and patlen */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008652 patlen = (int)STRLEN(buflocal_pat); /* but not endpat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008653 }
8654
8655 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008656 * Find AutoPat entries with this pattern.
8657 */
8658 prev_ap = &first_autopat[(int)event];
8659 while ((ap = *prev_ap) != NULL)
8660 {
8661 if (ap->pat != NULL)
8662 {
8663 /* Accept a pattern when:
8664 * - a group was specified and it's that group, or a group was
8665 * not specified and it's the current group, or a group was
8666 * not specified and we are listing
8667 * - the length of the pattern matches
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008668 * - the pattern matches.
8669 * For <buffer[=X]>, this condition works because we normalize
8670 * all buffer-local patterns.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008671 */
8672 if ((allgroups || ap->group == findgroup)
8673 && ap->patlen == patlen
8674 && STRNCMP(pat, ap->pat, patlen) == 0)
8675 {
8676 /*
8677 * Remove existing autocommands.
8678 * If adding any new autocmd's for this AutoPat, don't
8679 * delete the pattern from the autopat list, append to
8680 * this list.
8681 */
8682 if (forceit)
8683 {
8684 if (*cmd != NUL && ap->next == NULL)
8685 {
8686 au_remove_cmds(ap);
8687 break;
8688 }
8689 au_remove_pat(ap);
8690 }
8691
8692 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008693 * Show autocmd's for this autopat, or buflocals <buffer=X>
Bram Moolenaar071d4272004-06-13 20:20:40 +00008694 */
8695 else if (*cmd == NUL)
8696 show_autocmd(ap, event);
8697
8698 /*
8699 * Add autocmd to this autopat, if it's the last one.
8700 */
8701 else if (ap->next == NULL)
8702 break;
8703 }
8704 }
8705 prev_ap = &ap->next;
8706 }
8707
8708 /*
8709 * Add a new command.
8710 */
8711 if (*cmd != NUL)
8712 {
8713 /*
8714 * If the pattern we want to add a command to does appear at the
8715 * end of the list (or not is not in the list at all), add the
8716 * pattern at the end of the list.
8717 */
8718 if (ap == NULL)
8719 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008720 /* refuse to add buffer-local ap if buffer number is invalid */
8721 if (is_buflocal && (buflocal_nr == 0
8722 || buflist_findnr(buflocal_nr) == NULL))
8723 {
8724 EMSGN(_("E680: <buffer=%d>: invalid buffer number "),
8725 buflocal_nr);
8726 return FAIL;
8727 }
8728
Bram Moolenaar071d4272004-06-13 20:20:40 +00008729 ap = (AutoPat *)alloc((unsigned)sizeof(AutoPat));
8730 if (ap == NULL)
8731 return FAIL;
8732 ap->pat = vim_strnsave(pat, patlen);
8733 ap->patlen = patlen;
8734 if (ap->pat == NULL)
8735 {
8736 vim_free(ap);
8737 return FAIL;
8738 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008739
8740 if (is_buflocal)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008741 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008742 ap->buflocal_nr = buflocal_nr;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008743 ap->reg_prog = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008744 }
8745 else
8746 {
Bram Moolenaar748bf032005-02-02 23:04:36 +00008747 char_u *reg_pat;
8748
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008749 ap->buflocal_nr = 0;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008750 reg_pat = file_pat_to_reg_pat(pat, endpat,
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008751 &ap->allow_dirs, TRUE);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008752 if (reg_pat != NULL)
8753 ap->reg_prog = vim_regcomp(reg_pat, RE_MAGIC);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008754 vim_free(reg_pat);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008755 if (reg_pat == NULL || ap->reg_prog == NULL)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008756 {
8757 vim_free(ap->pat);
8758 vim_free(ap);
8759 return FAIL;
8760 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008761 }
8762 ap->cmds = NULL;
8763 *prev_ap = ap;
8764 ap->next = NULL;
8765 if (group == AUGROUP_ALL)
8766 ap->group = current_augroup;
8767 else
8768 ap->group = group;
8769 }
8770
8771 /*
8772 * Add the autocmd at the end of the AutoCmd list.
8773 */
8774 prev_ac = &(ap->cmds);
8775 while ((ac = *prev_ac) != NULL)
8776 prev_ac = &ac->next;
8777 ac = (AutoCmd *)alloc((unsigned)sizeof(AutoCmd));
8778 if (ac == NULL)
8779 return FAIL;
8780 ac->cmd = vim_strsave(cmd);
8781#ifdef FEAT_EVAL
8782 ac->scriptID = current_SID;
8783#endif
8784 if (ac->cmd == NULL)
8785 {
8786 vim_free(ac);
8787 return FAIL;
8788 }
8789 ac->next = NULL;
8790 *prev_ac = ac;
8791 ac->nested = nested;
8792 }
8793 }
8794
8795 au_cleanup(); /* may really delete removed patterns/commands now */
8796 return OK;
8797}
8798
8799/*
8800 * Implementation of ":doautocmd [group] event [fname]".
8801 * Return OK for success, FAIL for failure;
8802 */
8803 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008804do_doautocmd(
8805 char_u *arg,
Bram Moolenaar1610d052016-06-09 22:53:01 +02008806 int do_msg, /* give message for no matching autocmds? */
8807 int *did_something)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008808{
8809 char_u *fname;
8810 int nothing_done = TRUE;
8811 int group;
8812
Bram Moolenaar1610d052016-06-09 22:53:01 +02008813 if (did_something != NULL)
Bram Moolenaar76ae22f2016-06-13 20:00:29 +02008814 *did_something = FALSE;
Bram Moolenaar1610d052016-06-09 22:53:01 +02008815
Bram Moolenaar071d4272004-06-13 20:20:40 +00008816 /*
8817 * Check for a legal group name. If not, use AUGROUP_ALL.
8818 */
8819 group = au_get_grouparg(&arg);
8820 if (arg == NULL) /* out of memory */
8821 return FAIL;
8822
8823 if (*arg == '*')
8824 {
8825 EMSG(_("E217: Can't execute autocommands for ALL events"));
8826 return FAIL;
8827 }
8828
8829 /*
8830 * Scan over the events.
8831 * If we find an illegal name, return here, don't do anything.
8832 */
8833 fname = find_end_event(arg, group != AUGROUP_ALL);
8834 if (fname == NULL)
8835 return FAIL;
8836
8837 fname = skipwhite(fname);
8838
8839 /*
8840 * Loop over the events.
8841 */
Bram Moolenaarfaf29d72017-07-09 11:07:16 +02008842 while (*arg && !ends_excmd(*arg) && !VIM_ISWHITE(*arg))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008843 if (apply_autocmds_group(event_name2nr(arg, &arg),
8844 fname, NULL, TRUE, group, curbuf, NULL))
8845 nothing_done = FALSE;
8846
8847 if (nothing_done && do_msg)
8848 MSG(_("No matching autocommands"));
Bram Moolenaar1610d052016-06-09 22:53:01 +02008849 if (did_something != NULL)
8850 *did_something = !nothing_done;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008851
8852#ifdef FEAT_EVAL
8853 return aborting() ? FAIL : OK;
8854#else
8855 return OK;
8856#endif
8857}
8858
8859/*
8860 * ":doautoall": execute autocommands for each loaded buffer.
8861 */
8862 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008863ex_doautoall(exarg_T *eap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008864{
8865 int retval;
8866 aco_save_T aco;
8867 buf_T *buf;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008868 bufref_T bufref;
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008869 char_u *arg = eap->arg;
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008870 int call_do_modelines = check_nomodeline(&arg);
Bram Moolenaar1610d052016-06-09 22:53:01 +02008871 int did_aucmd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008872
8873 /*
8874 * This is a bit tricky: For some commands curwin->w_buffer needs to be
8875 * equal to curbuf, but for some buffers there may not be a window.
8876 * So we change the buffer for the current window for a moment. This
8877 * gives problems when the autocommands make changes to the list of
8878 * buffers or windows...
8879 */
Bram Moolenaar29323592016-07-24 22:04:11 +02008880 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008881 {
Bram Moolenaar3a847972008-07-08 09:36:58 +00008882 if (buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008883 {
8884 /* find a window for this buffer and save some values */
8885 aucmd_prepbuf(&aco, buf);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008886 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008887
8888 /* execute the autocommands for this buffer */
Bram Moolenaar1610d052016-06-09 22:53:01 +02008889 retval = do_doautocmd(arg, FALSE, &did_aucmd);
Bram Moolenaareeefcc72007-05-01 21:21:21 +00008890
Bram Moolenaar1610d052016-06-09 22:53:01 +02008891 if (call_do_modelines && did_aucmd)
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008892 {
8893 /* Execute the modeline settings, but don't set window-local
8894 * options if we are using the current window for another
8895 * buffer. */
8896 do_modelines(curwin == aucmd_win ? OPT_NOWIN : 0);
8897 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008898
8899 /* restore the current window */
8900 aucmd_restbuf(&aco);
8901
8902 /* stop if there is some error or buffer was deleted */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02008903 if (retval == FAIL || !bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008904 break;
8905 }
8906 }
8907
8908 check_cursor(); /* just in case lines got deleted */
8909}
8910
8911/*
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008912 * Check *argp for <nomodeline>. When it is present return FALSE, otherwise
8913 * return TRUE and advance *argp to after it.
8914 * Thus return TRUE when do_modelines() should be called.
8915 */
8916 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008917check_nomodeline(char_u **argp)
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008918{
8919 if (STRNCMP(*argp, "<nomodeline>", 12) == 0)
8920 {
8921 *argp = skipwhite(*argp + 12);
8922 return FALSE;
8923 }
8924 return TRUE;
8925}
8926
8927/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008928 * Prepare for executing autocommands for (hidden) buffer "buf".
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008929 * Search for a visible window containing the current buffer. If there isn't
8930 * one then use "aucmd_win".
Bram Moolenaar071d4272004-06-13 20:20:40 +00008931 * Set "curbuf" and "curwin" to match "buf".
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00008932 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008933 */
8934 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01008935aucmd_prepbuf(
8936 aco_save_T *aco, /* structure to save values in */
8937 buf_T *buf) /* new curbuf */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008938{
8939 win_T *win;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008940 int save_ea;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008941#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008942 int save_acd;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008943#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008944
8945 /* Find a window that is for the new buffer */
8946 if (buf == curbuf) /* be quick when buf is curbuf */
8947 win = curwin;
8948 else
Bram Moolenaar29323592016-07-24 22:04:11 +02008949 FOR_ALL_WINDOWS(win)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008950 if (win->w_buffer == buf)
8951 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008952
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008953 /* Allocate "aucmd_win" when needed. If this fails (out of memory) fall
8954 * back to using the current window. */
8955 if (win == NULL && aucmd_win == NULL)
8956 {
8957 win_alloc_aucmd_win();
8958 if (aucmd_win == NULL)
8959 win = curwin;
8960 }
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008961 if (win == NULL && aucmd_win_used)
8962 /* Strange recursive autocommand, fall back to using the current
8963 * window. Expect a few side effects... */
8964 win = curwin;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008965
8966 aco->save_curwin = curwin;
8967 aco->save_curbuf = curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008968 if (win != NULL)
8969 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008970 /* There is a window for "buf" in the current tab page, make it the
8971 * curwin. This is preferred, it has the least side effects (esp. if
8972 * "buf" is curbuf). */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008973 aco->use_aucmd_win = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008974 curwin = win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008975 }
8976 else
8977 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008978 /* There is no window for "buf", use "aucmd_win". To minimize the side
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02008979 * effects, insert it in the current tab page.
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008980 * Anything related to a window (e.g., setting folds) may have
8981 * unexpected results. */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008982 aco->use_aucmd_win = TRUE;
8983 aucmd_win_used = TRUE;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008984 aucmd_win->w_buffer = buf;
Bram Moolenaarcdddaa42010-06-07 23:07:44 +02008985 aucmd_win->w_s = &buf->b_s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008986 ++buf->b_nwindows;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008987 win_init_empty(aucmd_win); /* set cursor and topline to safe values */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008988
8989 /* Make sure w_localdir and globaldir are NULL to avoid a chdir() in
8990 * win_enter_ext(). */
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008991 vim_free(aucmd_win->w_localdir);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008992 aucmd_win->w_localdir = NULL;
8993 aco->globaldir = globaldir;
8994 globaldir = NULL;
8995
Bram Moolenaar071d4272004-06-13 20:20:40 +00008996
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008997 /* Split the current window, put the aucmd_win in the upper half.
8998 * We don't want the BufEnter or WinEnter autocommands. */
8999 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009000 make_snapshot(SNAP_AUCMD_IDX);
9001 save_ea = p_ea;
9002 p_ea = FALSE;
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009003
Bram Moolenaar4033c552017-09-16 20:54:51 +02009004#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009005 /* Prevent chdir() call in win_enter_ext(), through do_autochdir(). */
9006 save_acd = p_acd;
9007 p_acd = FALSE;
Bram Moolenaar4033c552017-09-16 20:54:51 +02009008#endif
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009009
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009010 (void)win_split_ins(0, WSP_TOP, aucmd_win, 0);
9011 (void)win_comp_pos(); /* recompute window positions */
9012 p_ea = save_ea;
Bram Moolenaar4033c552017-09-16 20:54:51 +02009013#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02009014 p_acd = save_acd;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009015#endif
Bram Moolenaar4033c552017-09-16 20:54:51 +02009016 unblock_autocmds();
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00009017 curwin = aucmd_win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009018 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009019 curbuf = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009020 aco->new_curwin = curwin;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009021 set_bufref(&aco->new_curbuf, curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009022}
9023
9024/*
9025 * Cleanup after executing autocommands for a (hidden) buffer.
9026 * Restore the window as it was (if possible).
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009027 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009028 */
9029 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009030aucmd_restbuf(
9031 aco_save_T *aco) /* structure holding saved values */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009032{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009033 int dummy;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009034
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009035 if (aco->use_aucmd_win)
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009036 {
9037 --curbuf->b_nwindows;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009038 /* Find "aucmd_win", it can't be closed, but it may be in another tab
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00009039 * page. Do not trigger autocommands here. */
9040 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009041 if (curwin != aucmd_win)
9042 {
9043 tabpage_T *tp;
9044 win_T *wp;
9045
9046 FOR_ALL_TAB_WINDOWS(tp, wp)
9047 {
9048 if (wp == aucmd_win)
9049 {
9050 if (tp != curtab)
Bram Moolenaar49e649f2013-05-06 04:50:35 +02009051 goto_tabpage_tp(tp, TRUE, TRUE);
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009052 win_goto(aucmd_win);
Bram Moolenaar28f29082012-02-11 23:45:37 +01009053 goto win_found;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009054 }
9055 }
9056 }
Bram Moolenaar28f29082012-02-11 23:45:37 +01009057win_found:
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009058
9059 /* Remove the window and frame from the tree of frames. */
9060 (void)winframe_remove(curwin, &dummy, NULL);
9061 win_remove(curwin, NULL);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009062 aucmd_win_used = FALSE;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009063 last_status(FALSE); /* may need to remove last status line */
Bram Moolenaar8c752bd2017-03-19 17:09:56 +01009064
9065 if (!valid_tabpage_win(curtab))
9066 /* no valid window in current tabpage */
9067 close_tabpage(curtab);
9068
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009069 restore_snapshot(SNAP_AUCMD_IDX, FALSE);
9070 (void)win_comp_pos(); /* recompute window positions */
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00009071 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009072
9073 if (win_valid(aco->save_curwin))
9074 curwin = aco->save_curwin;
9075 else
9076 /* Hmm, original window disappeared. Just use the first one. */
9077 curwin = firstwin;
Bram Moolenaar4033c552017-09-16 20:54:51 +02009078#ifdef FEAT_EVAL
Bram Moolenaar429fa852013-04-15 12:27:36 +02009079 vars_clear(&aucmd_win->w_vars->dv_hashtab); /* free all w: variables */
9080 hash_init(&aucmd_win->w_vars->dv_hashtab); /* re-use the hashtab */
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009081#endif
9082 curbuf = curwin->w_buffer;
9083
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009084 vim_free(globaldir);
9085 globaldir = aco->globaldir;
9086
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009087 /* the buffer contents may have changed */
9088 check_cursor();
9089 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
9090 {
9091 curwin->w_topline = curbuf->b_ml.ml_line_count;
9092#ifdef FEAT_DIFF
9093 curwin->w_topfill = 0;
9094#endif
9095 }
9096#if defined(FEAT_GUI)
9097 /* Hide the scrollbars from the aucmd_win and update. */
9098 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_LEFT], FALSE);
9099 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_RIGHT], FALSE);
9100 gui_may_update_scrollbars();
9101#endif
9102 }
9103 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00009104 {
9105 /* restore curwin */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009106 if (win_valid(aco->save_curwin))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009107 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009108 /* Restore the buffer which was previously edited by curwin, if
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009109 * it was changed, we are still the same window and the buffer is
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009110 * valid. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009111 if (curwin == aco->new_curwin
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009112 && curbuf != aco->new_curbuf.br_buf
9113 && bufref_valid(&aco->new_curbuf)
9114 && aco->new_curbuf.br_buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009115 {
Bram Moolenaar7da9c372012-04-30 17:04:52 +02009116# if defined(FEAT_SYN_HL) || defined(FEAT_SPELL)
9117 if (curwin->w_s == &curbuf->b_s)
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009118 curwin->w_s = &aco->new_curbuf.br_buf->b_s;
Bram Moolenaar7da9c372012-04-30 17:04:52 +02009119# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009120 --curbuf->b_nwindows;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009121 curbuf = aco->new_curbuf.br_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009122 curwin->w_buffer = curbuf;
9123 ++curbuf->b_nwindows;
9124 }
9125
9126 curwin = aco->save_curwin;
9127 curbuf = curwin->w_buffer;
Bram Moolenaar371932a2014-09-09 16:59:38 +02009128 /* In case the autocommand move the cursor to a position that that
9129 * not exist in curbuf. */
9130 check_cursor();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009131 }
9132 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009133}
9134
9135static int autocmd_nested = FALSE;
9136
9137/*
9138 * Execute autocommands for "event" and file name "fname".
9139 * Return TRUE if some commands were executed.
9140 */
9141 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009142apply_autocmds(
9143 event_T event,
9144 char_u *fname, /* NULL or empty means use actual file name */
9145 char_u *fname_io, /* fname to use for <afile> on cmdline */
9146 int force, /* when TRUE, ignore autocmd_busy */
9147 buf_T *buf) /* buffer for <abuf> */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009148{
9149 return apply_autocmds_group(event, fname, fname_io, force,
9150 AUGROUP_ALL, buf, NULL);
9151}
9152
9153/*
9154 * Like apply_autocmds(), but with extra "eap" argument. This takes care of
9155 * setting v:filearg.
9156 */
9157 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009158apply_autocmds_exarg(
9159 event_T event,
9160 char_u *fname,
9161 char_u *fname_io,
9162 int force,
9163 buf_T *buf,
9164 exarg_T *eap)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009165{
9166 return apply_autocmds_group(event, fname, fname_io, force,
9167 AUGROUP_ALL, buf, eap);
9168}
9169
9170/*
9171 * Like apply_autocmds(), but handles the caller's retval. If the script
9172 * processing is being aborted or if retval is FAIL when inside a try
9173 * conditional, no autocommands are executed. If otherwise the autocommands
9174 * cause the script to be aborted, retval is set to FAIL.
9175 */
9176 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009177apply_autocmds_retval(
9178 event_T event,
9179 char_u *fname, /* NULL or empty means use actual file name */
9180 char_u *fname_io, /* fname to use for <afile> on cmdline */
9181 int force, /* when TRUE, ignore autocmd_busy */
9182 buf_T *buf, /* buffer for <abuf> */
9183 int *retval) /* pointer to caller's retval */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009184{
9185 int did_cmd;
9186
Bram Moolenaar1e015462005-09-25 22:16:38 +00009187#ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00009188 if (should_abort(*retval))
9189 return FALSE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00009190#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009191
9192 did_cmd = apply_autocmds_group(event, fname, fname_io, force,
9193 AUGROUP_ALL, buf, NULL);
Bram Moolenaar1e015462005-09-25 22:16:38 +00009194 if (did_cmd
9195#ifdef FEAT_EVAL
9196 && aborting()
9197#endif
9198 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00009199 *retval = FAIL;
9200 return did_cmd;
9201}
9202
Bram Moolenaard35f9712005-12-18 22:02:33 +00009203/*
9204 * Return TRUE when there is a CursorHold autocommand defined.
9205 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009206 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009207has_cursorhold(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009208{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009209 return (first_autopat[(int)(get_real_state() == NORMAL_BUSY
9210 ? EVENT_CURSORHOLD : EVENT_CURSORHOLDI)] != NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009211}
Bram Moolenaard35f9712005-12-18 22:02:33 +00009212
9213/*
9214 * Return TRUE if the CursorHold event can be triggered.
9215 */
9216 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009217trigger_cursorhold(void)
Bram Moolenaard35f9712005-12-18 22:02:33 +00009218{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009219 int state;
9220
Bram Moolenaar05334432011-07-20 18:29:39 +02009221 if (!did_cursorhold
9222 && has_cursorhold()
9223 && !Recording
9224 && typebuf.tb_len == 0
Bram Moolenaard29a9ee2006-09-14 09:07:34 +00009225#ifdef FEAT_INS_EXPAND
9226 && !ins_compl_active()
9227#endif
9228 )
Bram Moolenaar754b5602006-02-09 23:53:20 +00009229 {
9230 state = get_real_state();
9231 if (state == NORMAL_BUSY || (state & INSERT) != 0)
9232 return TRUE;
9233 }
9234 return FALSE;
Bram Moolenaard35f9712005-12-18 22:02:33 +00009235}
Bram Moolenaar754b5602006-02-09 23:53:20 +00009236
9237/*
9238 * Return TRUE when there is a CursorMoved autocommand defined.
9239 */
9240 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009241has_cursormoved(void)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009242{
9243 return (first_autopat[(int)EVENT_CURSORMOVED] != NULL);
9244}
9245
9246/*
9247 * Return TRUE when there is a CursorMovedI autocommand defined.
9248 */
9249 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009250has_cursormovedI(void)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009251{
9252 return (first_autopat[(int)EVENT_CURSORMOVEDI] != NULL);
9253}
Bram Moolenaar071d4272004-06-13 20:20:40 +00009254
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009255/*
Bram Moolenaar186628f2013-03-19 13:33:23 +01009256 * Return TRUE when there is a TextChanged autocommand defined.
9257 */
9258 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009259has_textchanged(void)
Bram Moolenaar186628f2013-03-19 13:33:23 +01009260{
9261 return (first_autopat[(int)EVENT_TEXTCHANGED] != NULL);
9262}
9263
9264/*
9265 * Return TRUE when there is a TextChangedI autocommand defined.
9266 */
9267 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009268has_textchangedI(void)
Bram Moolenaar186628f2013-03-19 13:33:23 +01009269{
9270 return (first_autopat[(int)EVENT_TEXTCHANGEDI] != NULL);
9271}
9272
9273/*
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009274 * Return TRUE when there is an InsertCharPre autocommand defined.
9275 */
9276 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009277has_insertcharpre(void)
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009278{
9279 return (first_autopat[(int)EVENT_INSERTCHARPRE] != NULL);
9280}
9281
Bram Moolenaard5005162014-08-22 23:05:54 +02009282/*
9283 * Return TRUE when there is an CmdUndefined autocommand defined.
9284 */
9285 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009286has_cmdundefined(void)
Bram Moolenaard5005162014-08-22 23:05:54 +02009287{
9288 return (first_autopat[(int)EVENT_CMDUNDEFINED] != NULL);
9289}
9290
9291/*
9292 * Return TRUE when there is an FuncUndefined autocommand defined.
9293 */
9294 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009295has_funcundefined(void)
Bram Moolenaard5005162014-08-22 23:05:54 +02009296{
9297 return (first_autopat[(int)EVENT_FUNCUNDEFINED] != NULL);
9298}
9299
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02009300/*
9301 * Execute autocommands for "event" and file name "fname".
9302 * Return TRUE if some commands were executed.
9303 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009304 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009305apply_autocmds_group(
9306 event_T event,
9307 char_u *fname, /* NULL or empty means use actual file name */
9308 char_u *fname_io, /* fname to use for <afile> on cmdline, NULL means
Bram Moolenaar071d4272004-06-13 20:20:40 +00009309 use fname */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009310 int force, /* when TRUE, ignore autocmd_busy */
9311 int group, /* group ID, or AUGROUP_ALL */
9312 buf_T *buf, /* buffer for <abuf> */
9313 exarg_T *eap) /* command arguments */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009314{
9315 char_u *sfname = NULL; /* short file name */
9316 char_u *tail;
9317 int save_changed;
9318 buf_T *old_curbuf;
9319 int retval = FALSE;
9320 char_u *save_sourcing_name;
9321 linenr_T save_sourcing_lnum;
9322 char_u *save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009323 int save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009324 int save_autocmd_bufnr;
9325 char_u *save_autocmd_match;
9326 int save_autocmd_busy;
9327 int save_autocmd_nested;
9328 static int nesting = 0;
9329 AutoPatCmd patcmd;
9330 AutoPat *ap;
9331#ifdef FEAT_EVAL
9332 scid_T save_current_SID;
9333 void *save_funccalp;
9334 char_u *save_cmdarg;
9335 long save_cmdbang;
9336#endif
9337 static int filechangeshell_busy = FALSE;
Bram Moolenaar05159a02005-02-26 23:04:13 +00009338#ifdef FEAT_PROFILE
9339 proftime_T wait_time;
9340#endif
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009341 int did_save_redobuff = FALSE;
Bram Moolenaard4863aa2017-04-07 19:50:12 +02009342 save_redo_T save_redo;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009343
9344 /*
9345 * Quickly return if there are no autocommands for this event or
9346 * autocommands are blocked.
9347 */
Bram Moolenaarfaf29d72017-07-09 11:07:16 +02009348 if (event == NUM_EVENTS || first_autopat[(int)event] == NULL
9349 || autocmd_blocked > 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009350 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009351
9352 /*
9353 * When autocommands are busy, new autocommands are only executed when
9354 * explicitly enabled with the "nested" flag.
9355 */
9356 if (autocmd_busy && !(force || autocmd_nested))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009357 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009358
9359#ifdef FEAT_EVAL
9360 /*
Bram Moolenaar7263a772007-05-10 17:35:54 +00009361 * Quickly return when immediately aborting on error, or when an interrupt
Bram Moolenaar071d4272004-06-13 20:20:40 +00009362 * occurred or an exception was thrown but not caught.
9363 */
9364 if (aborting())
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009365 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009366#endif
9367
9368 /*
9369 * FileChangedShell never nests, because it can create an endless loop.
9370 */
Bram Moolenaar56718732006-03-15 22:53:57 +00009371 if (filechangeshell_busy && (event == EVENT_FILECHANGEDSHELL
9372 || event == EVENT_FILECHANGEDSHELLPOST))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009373 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009374
9375 /*
9376 * Ignore events in 'eventignore'.
9377 */
9378 if (event_ignored(event))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009379 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009380
9381 /*
9382 * Allow nesting of autocommands, but restrict the depth, because it's
9383 * possible to create an endless loop.
9384 */
9385 if (nesting == 10)
9386 {
9387 EMSG(_("E218: autocommand nesting too deep"));
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009388 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009389 }
9390
9391 /*
9392 * Check if these autocommands are disabled. Used when doing ":all" or
9393 * ":ball".
9394 */
9395 if ( (autocmd_no_enter
9396 && (event == EVENT_WINENTER || event == EVENT_BUFENTER))
9397 || (autocmd_no_leave
9398 && (event == EVENT_WINLEAVE || event == EVENT_BUFLEAVE)))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009399 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009400
9401 /*
9402 * Save the autocmd_* variables and info about the current buffer.
9403 */
9404 save_autocmd_fname = autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009405 save_autocmd_fname_full = autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009406 save_autocmd_bufnr = autocmd_bufnr;
9407 save_autocmd_match = autocmd_match;
9408 save_autocmd_busy = autocmd_busy;
9409 save_autocmd_nested = autocmd_nested;
9410 save_changed = curbuf->b_changed;
9411 old_curbuf = curbuf;
9412
9413 /*
9414 * Set the file name to be used for <afile>.
Bram Moolenaara0174af2008-01-02 20:08:25 +00009415 * Make a copy to avoid that changing a buffer name or directory makes it
9416 * invalid.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009417 */
9418 if (fname_io == NULL)
9419 {
Bram Moolenaar53744302015-07-17 17:38:22 +02009420 if (event == EVENT_COLORSCHEME || event == EVENT_OPTIONSET)
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009421 autocmd_fname = NULL;
Bram Moolenaarfaf29d72017-07-09 11:07:16 +02009422 else if (fname != NULL && !ends_excmd(*fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009423 autocmd_fname = fname;
9424 else if (buf != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009425 autocmd_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009426 else
9427 autocmd_fname = NULL;
9428 }
9429 else
9430 autocmd_fname = fname_io;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009431 if (autocmd_fname != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009432 autocmd_fname = vim_strsave(autocmd_fname);
9433 autocmd_fname_full = FALSE; /* call FullName_save() later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009434
9435 /*
9436 * Set the buffer number to be used for <abuf>.
9437 */
9438 if (buf == NULL)
9439 autocmd_bufnr = 0;
9440 else
9441 autocmd_bufnr = buf->b_fnum;
9442
9443 /*
9444 * When the file name is NULL or empty, use the file name of buffer "buf".
9445 * Always use the full path of the file name to match with, in case
9446 * "allow_dirs" is set.
9447 */
9448 if (fname == NULL || *fname == NUL)
9449 {
9450 if (buf == NULL)
9451 fname = NULL;
9452 else
9453 {
9454#ifdef FEAT_SYN_HL
9455 if (event == EVENT_SYNTAX)
9456 fname = buf->b_p_syn;
9457 else
9458#endif
9459 if (event == EVENT_FILETYPE)
9460 fname = buf->b_p_ft;
9461 else
9462 {
9463 if (buf->b_sfname != NULL)
9464 sfname = vim_strsave(buf->b_sfname);
9465 fname = buf->b_ffname;
9466 }
9467 }
9468 if (fname == NULL)
9469 fname = (char_u *)"";
9470 fname = vim_strsave(fname); /* make a copy, so we can change it */
9471 }
9472 else
9473 {
9474 sfname = vim_strsave(fname);
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009475 /* Don't try expanding FileType, Syntax, FuncUndefined, WindowID,
9476 * ColorScheme or QuickFixCmd* */
Bram Moolenaar7c626922005-02-07 22:01:03 +00009477 if (event == EVENT_FILETYPE
9478 || event == EVENT_SYNTAX
Bram Moolenaar5135d462009-04-29 16:03:38 +00009479 || event == EVENT_FUNCUNDEFINED
Bram Moolenaar7c626922005-02-07 22:01:03 +00009480 || event == EVENT_REMOTEREPLY
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00009481 || event == EVENT_SPELLFILEMISSING
Bram Moolenaar7c626922005-02-07 22:01:03 +00009482 || event == EVENT_QUICKFIXCMDPRE
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009483 || event == EVENT_COLORSCHEME
Bram Moolenaar53744302015-07-17 17:38:22 +02009484 || event == EVENT_OPTIONSET
Bram Moolenaar7c626922005-02-07 22:01:03 +00009485 || event == EVENT_QUICKFIXCMDPOST)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009486 fname = vim_strsave(fname);
9487 else
9488 fname = FullName_save(fname, FALSE);
9489 }
9490 if (fname == NULL) /* out of memory */
9491 {
9492 vim_free(sfname);
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009493 retval = FALSE;
9494 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009495 }
9496
9497#ifdef BACKSLASH_IN_FILENAME
9498 /*
9499 * Replace all backslashes with forward slashes. This makes the
9500 * autocommand patterns portable between Unix and MS-DOS.
9501 */
9502 if (sfname != NULL)
9503 forward_slash(sfname);
9504 forward_slash(fname);
9505#endif
9506
9507#ifdef VMS
9508 /* remove version for correct match */
9509 if (sfname != NULL)
9510 vms_remove_version(sfname);
9511 vms_remove_version(fname);
9512#endif
9513
9514 /*
9515 * Set the name to be used for <amatch>.
9516 */
9517 autocmd_match = fname;
9518
9519
9520 /* Don't redraw while doing auto commands. */
9521 ++RedrawingDisabled;
9522 save_sourcing_name = sourcing_name;
9523 sourcing_name = NULL; /* don't free this one */
9524 save_sourcing_lnum = sourcing_lnum;
9525 sourcing_lnum = 0; /* no line number here */
9526
9527#ifdef FEAT_EVAL
9528 save_current_SID = current_SID;
9529
Bram Moolenaar05159a02005-02-26 23:04:13 +00009530# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009531 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009532 prof_child_enter(&wait_time); /* doesn't count for the caller itself */
9533# endif
9534
Bram Moolenaar071d4272004-06-13 20:20:40 +00009535 /* Don't use local function variables, if called from a function */
9536 save_funccalp = save_funccal();
9537#endif
9538
9539 /*
9540 * When starting to execute autocommands, save the search patterns.
9541 */
9542 if (!autocmd_busy)
9543 {
9544 save_search_patterns();
Bram Moolenaar20ad69c2015-12-03 13:52:52 +01009545#ifdef FEAT_INS_EXPAND
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009546 if (!ins_compl_active())
Bram Moolenaar20ad69c2015-12-03 13:52:52 +01009547#endif
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009548 {
Bram Moolenaard4863aa2017-04-07 19:50:12 +02009549 saveRedobuff(&save_redo);
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009550 did_save_redobuff = TRUE;
9551 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009552 did_filetype = keep_filetype;
9553 }
9554
9555 /*
9556 * Note that we are applying autocmds. Some commands need to know.
9557 */
9558 autocmd_busy = TRUE;
9559 filechangeshell_busy = (event == EVENT_FILECHANGEDSHELL);
9560 ++nesting; /* see matching decrement below */
9561
9562 /* Remember that FileType was triggered. Used for did_filetype(). */
9563 if (event == EVENT_FILETYPE)
9564 did_filetype = TRUE;
9565
9566 tail = gettail(fname);
9567
9568 /* Find first autocommand that matches */
9569 patcmd.curpat = first_autopat[(int)event];
9570 patcmd.nextcmd = NULL;
9571 patcmd.group = group;
9572 patcmd.fname = fname;
9573 patcmd.sfname = sfname;
9574 patcmd.tail = tail;
9575 patcmd.event = event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009576 patcmd.arg_bufnr = autocmd_bufnr;
9577 patcmd.next = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009578 auto_next_pat(&patcmd, FALSE);
9579
9580 /* found one, start executing the autocommands */
9581 if (patcmd.curpat != NULL)
9582 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009583 /* add to active_apc_list */
9584 patcmd.next = active_apc_list;
9585 active_apc_list = &patcmd;
9586
Bram Moolenaar071d4272004-06-13 20:20:40 +00009587#ifdef FEAT_EVAL
9588 /* set v:cmdarg (only when there is a matching pattern) */
Bram Moolenaar22fcfad2016-07-01 18:17:26 +02009589 save_cmdbang = (long)get_vim_var_nr(VV_CMDBANG);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009590 if (eap != NULL)
9591 {
9592 save_cmdarg = set_cmdarg(eap, NULL);
9593 set_vim_var_nr(VV_CMDBANG, (long)eap->forceit);
9594 }
9595 else
9596 save_cmdarg = NULL; /* avoid gcc warning */
9597#endif
9598 retval = TRUE;
9599 /* mark the last pattern, to avoid an endless loop when more patterns
9600 * are added when executing autocommands */
9601 for (ap = patcmd.curpat; ap->next != NULL; ap = ap->next)
9602 ap->last = FALSE;
9603 ap->last = TRUE;
9604 check_lnums(TRUE); /* make sure cursor and topline are valid */
9605 do_cmdline(NULL, getnextac, (void *)&patcmd,
9606 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
9607#ifdef FEAT_EVAL
9608 if (eap != NULL)
9609 {
9610 (void)set_cmdarg(NULL, save_cmdarg);
9611 set_vim_var_nr(VV_CMDBANG, save_cmdbang);
9612 }
9613#endif
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009614 /* delete from active_apc_list */
9615 if (active_apc_list == &patcmd) /* just in case */
9616 active_apc_list = patcmd.next;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009617 }
9618
9619 --RedrawingDisabled;
9620 autocmd_busy = save_autocmd_busy;
9621 filechangeshell_busy = FALSE;
9622 autocmd_nested = save_autocmd_nested;
9623 vim_free(sourcing_name);
9624 sourcing_name = save_sourcing_name;
9625 sourcing_lnum = save_sourcing_lnum;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009626 vim_free(autocmd_fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009627 autocmd_fname = save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009628 autocmd_fname_full = save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009629 autocmd_bufnr = save_autocmd_bufnr;
9630 autocmd_match = save_autocmd_match;
9631#ifdef FEAT_EVAL
9632 current_SID = save_current_SID;
9633 restore_funccal(save_funccalp);
Bram Moolenaar05159a02005-02-26 23:04:13 +00009634# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009635 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009636 prof_child_exit(&wait_time);
9637# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009638#endif
9639 vim_free(fname);
9640 vim_free(sfname);
9641 --nesting; /* see matching increment above */
9642
9643 /*
9644 * When stopping to execute autocommands, restore the search patterns and
Bram Moolenaar3be85852014-06-12 14:01:31 +02009645 * the redo buffer. Free any buffers in the au_pending_free_buf list and
9646 * free any windows in the au_pending_free_win list.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009647 */
9648 if (!autocmd_busy)
9649 {
9650 restore_search_patterns();
Bram Moolenaarc51b02d2015-02-17 10:58:25 +01009651 if (did_save_redobuff)
Bram Moolenaard4863aa2017-04-07 19:50:12 +02009652 restoreRedobuff(&save_redo);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009653 did_filetype = FALSE;
Bram Moolenaar4c7ab1b2014-04-06 20:45:43 +02009654 while (au_pending_free_buf != NULL)
9655 {
9656 buf_T *b = au_pending_free_buf->b_next;
9657 vim_free(au_pending_free_buf);
9658 au_pending_free_buf = b;
9659 }
Bram Moolenaar3be85852014-06-12 14:01:31 +02009660 while (au_pending_free_win != NULL)
9661 {
9662 win_T *w = au_pending_free_win->w_next;
9663 vim_free(au_pending_free_win);
9664 au_pending_free_win = w;
9665 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009666 }
9667
9668 /*
9669 * Some events don't set or reset the Changed flag.
9670 * Check if still in the same buffer!
9671 */
9672 if (curbuf == old_curbuf
9673 && (event == EVENT_BUFREADPOST
9674 || event == EVENT_BUFWRITEPOST
9675 || event == EVENT_FILEAPPENDPOST
9676 || event == EVENT_VIMLEAVE
9677 || event == EVENT_VIMLEAVEPRE))
9678 {
9679#ifdef FEAT_TITLE
9680 if (curbuf->b_changed != save_changed)
9681 need_maketitle = TRUE;
9682#endif
9683 curbuf->b_changed = save_changed;
9684 }
9685
9686 au_cleanup(); /* may really delete removed patterns/commands now */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009687
9688BYPASS_AU:
9689 /* When wiping out a buffer make sure all its buffer-local autocommands
9690 * are deleted. */
9691 if (event == EVENT_BUFWIPEOUT && buf != NULL)
9692 aubuflocal_remove(buf);
9693
Bram Moolenaarc3691332016-04-20 12:49:49 +02009694 if (retval == OK && event == EVENT_FILETYPE)
9695 au_did_filetype = TRUE;
9696
Bram Moolenaar071d4272004-06-13 20:20:40 +00009697 return retval;
9698}
9699
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009700# ifdef FEAT_EVAL
9701static char_u *old_termresponse = NULL;
9702# endif
9703
9704/*
9705 * Block triggering autocommands until unblock_autocmd() is called.
9706 * Can be used recursively, so long as it's symmetric.
9707 */
9708 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009709block_autocmds(void)
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009710{
9711# ifdef FEAT_EVAL
9712 /* Remember the value of v:termresponse. */
9713 if (autocmd_blocked == 0)
9714 old_termresponse = get_vim_var_str(VV_TERMRESPONSE);
9715# endif
9716 ++autocmd_blocked;
9717}
9718
9719 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009720unblock_autocmds(void)
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009721{
9722 --autocmd_blocked;
9723
9724# ifdef FEAT_EVAL
9725 /* When v:termresponse was set while autocommands were blocked, trigger
9726 * the autocommands now. Esp. useful when executing a shell command
9727 * during startup (vimdiff). */
9728 if (autocmd_blocked == 0
9729 && get_vim_var_str(VV_TERMRESPONSE) != old_termresponse)
9730 apply_autocmds(EVENT_TERMRESPONSE, NULL, NULL, FALSE, curbuf);
9731# endif
9732}
9733
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009734 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009735is_autocmd_blocked(void)
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009736{
9737 return autocmd_blocked != 0;
9738}
9739
Bram Moolenaar071d4272004-06-13 20:20:40 +00009740/*
9741 * Find next autocommand pattern that matches.
9742 */
9743 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009744auto_next_pat(
9745 AutoPatCmd *apc,
9746 int stop_at_last) /* stop when 'last' flag is set */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009747{
9748 AutoPat *ap;
9749 AutoCmd *cp;
9750 char_u *name;
9751 char *s;
9752
9753 vim_free(sourcing_name);
9754 sourcing_name = NULL;
9755
9756 for (ap = apc->curpat; ap != NULL && !got_int; ap = ap->next)
9757 {
9758 apc->curpat = NULL;
9759
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009760 /* Only use a pattern when it has not been removed, has commands and
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009761 * the group matches. For buffer-local autocommands only check the
9762 * buffer number. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009763 if (ap->pat != NULL && ap->cmds != NULL
9764 && (apc->group == AUGROUP_ALL || apc->group == ap->group))
9765 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009766 /* execution-condition */
9767 if (ap->buflocal_nr == 0
Bram Moolenaardffa5b82014-11-19 16:38:07 +01009768 ? (match_file_pat(NULL, &ap->reg_prog, apc->fname,
Bram Moolenaar748bf032005-02-02 23:04:36 +00009769 apc->sfname, apc->tail, ap->allow_dirs))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009770 : ap->buflocal_nr == apc->arg_bufnr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009771 {
9772 name = event_nr2name(apc->event);
9773 s = _("%s Auto commands for \"%s\"");
9774 sourcing_name = alloc((unsigned)(STRLEN(s)
9775 + STRLEN(name) + ap->patlen + 1));
9776 if (sourcing_name != NULL)
9777 {
9778 sprintf((char *)sourcing_name, s,
9779 (char *)name, (char *)ap->pat);
9780 if (p_verbose >= 8)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009781 {
9782 verbose_enter();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009783 smsg((char_u *)_("Executing %s"), sourcing_name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009784 verbose_leave();
9785 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009786 }
9787
9788 apc->curpat = ap;
9789 apc->nextcmd = ap->cmds;
9790 /* mark last command */
9791 for (cp = ap->cmds; cp->next != NULL; cp = cp->next)
9792 cp->last = FALSE;
9793 cp->last = TRUE;
9794 }
9795 line_breakcheck();
9796 if (apc->curpat != NULL) /* found a match */
9797 break;
9798 }
9799 if (stop_at_last && ap->last)
9800 break;
9801 }
9802}
9803
9804/*
9805 * Get next autocommand command.
9806 * Called by do_cmdline() to get the next line for ":if".
9807 * Returns allocated string, or NULL for end of autocommands.
9808 */
Bram Moolenaar21691f82012-12-05 19:13:18 +01009809 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009810getnextac(int c UNUSED, void *cookie, int indent UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009811{
9812 AutoPatCmd *acp = (AutoPatCmd *)cookie;
9813 char_u *retval;
9814 AutoCmd *ac;
9815
9816 /* Can be called again after returning the last line. */
9817 if (acp->curpat == NULL)
9818 return NULL;
9819
9820 /* repeat until we find an autocommand to execute */
9821 for (;;)
9822 {
9823 /* skip removed commands */
9824 while (acp->nextcmd != NULL && acp->nextcmd->cmd == NULL)
9825 if (acp->nextcmd->last)
9826 acp->nextcmd = NULL;
9827 else
9828 acp->nextcmd = acp->nextcmd->next;
9829
9830 if (acp->nextcmd != NULL)
9831 break;
9832
9833 /* at end of commands, find next pattern that matches */
9834 if (acp->curpat->last)
9835 acp->curpat = NULL;
9836 else
9837 acp->curpat = acp->curpat->next;
9838 if (acp->curpat != NULL)
9839 auto_next_pat(acp, TRUE);
9840 if (acp->curpat == NULL)
9841 return NULL;
9842 }
9843
9844 ac = acp->nextcmd;
9845
9846 if (p_verbose >= 9)
9847 {
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009848 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009849 smsg((char_u *)_("autocommand %s"), ac->cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009850 msg_puts((char_u *)"\n"); /* don't overwrite this either */
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009851 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009852 }
9853 retval = vim_strsave(ac->cmd);
9854 autocmd_nested = ac->nested;
9855#ifdef FEAT_EVAL
9856 current_SID = ac->scriptID;
9857#endif
9858 if (ac->last)
9859 acp->nextcmd = NULL;
9860 else
9861 acp->nextcmd = ac->next;
9862 return retval;
9863}
9864
9865/*
9866 * Return TRUE if there is a matching autocommand for "fname".
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009867 * To account for buffer-local autocommands, function needs to know
9868 * in which buffer the file will be opened.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009869 */
9870 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009871has_autocmd(event_T event, char_u *sfname, buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009872{
9873 AutoPat *ap;
9874 char_u *fname;
9875 char_u *tail = gettail(sfname);
9876 int retval = FALSE;
9877
9878 fname = FullName_save(sfname, FALSE);
9879 if (fname == NULL)
9880 return FALSE;
9881
9882#ifdef BACKSLASH_IN_FILENAME
9883 /*
9884 * Replace all backslashes with forward slashes. This makes the
9885 * autocommand patterns portable between Unix and MS-DOS.
9886 */
9887 sfname = vim_strsave(sfname);
9888 if (sfname != NULL)
9889 forward_slash(sfname);
9890 forward_slash(fname);
9891#endif
9892
9893 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
9894 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009895 && (ap->buflocal_nr == 0
Bram Moolenaardffa5b82014-11-19 16:38:07 +01009896 ? match_file_pat(NULL, &ap->reg_prog,
Bram Moolenaar748bf032005-02-02 23:04:36 +00009897 fname, sfname, tail, ap->allow_dirs)
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009898 : buf != NULL && ap->buflocal_nr == buf->b_fnum
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009899 ))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009900 {
9901 retval = TRUE;
9902 break;
9903 }
9904
9905 vim_free(fname);
9906#ifdef BACKSLASH_IN_FILENAME
9907 vim_free(sfname);
9908#endif
9909
9910 return retval;
9911}
9912
9913#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
9914/*
9915 * Function given to ExpandGeneric() to obtain the list of autocommand group
9916 * names.
9917 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009918 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009919get_augroup_name(expand_T *xp UNUSED, int idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009920{
9921 if (idx == augroups.ga_len) /* add "END" add the end */
9922 return (char_u *)"END";
9923 if (idx >= augroups.ga_len) /* end of list */
9924 return NULL;
Bram Moolenaarb62cc362016-09-03 16:43:53 +02009925 if (AUGROUP_NAME(idx) == NULL || AUGROUP_NAME(idx) == get_deleted_augroup())
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02009926 /* skip deleted entries */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009927 return (char_u *)"";
9928 return AUGROUP_NAME(idx); /* return a name */
9929}
9930
9931static int include_groups = FALSE;
9932
9933 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009934set_context_in_autocmd(
9935 expand_T *xp,
9936 char_u *arg,
9937 int doautocmd) /* TRUE for :doauto*, FALSE for :autocmd */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009938{
9939 char_u *p;
9940 int group;
9941
9942 /* check for a group name, skip it if present */
9943 include_groups = FALSE;
9944 p = arg;
9945 group = au_get_grouparg(&arg);
9946 if (group == AUGROUP_ERROR)
9947 return NULL;
9948 /* If there only is a group name that's what we expand. */
Bram Moolenaar1c465442017-03-12 20:10:05 +01009949 if (*arg == NUL && group != AUGROUP_ALL && !VIM_ISWHITE(arg[-1]))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009950 {
9951 arg = p;
9952 group = AUGROUP_ALL;
9953 }
9954
9955 /* skip over event name */
Bram Moolenaar1c465442017-03-12 20:10:05 +01009956 for (p = arg; *p != NUL && !VIM_ISWHITE(*p); ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009957 if (*p == ',')
9958 arg = p + 1;
9959 if (*p == NUL)
9960 {
9961 if (group == AUGROUP_ALL)
9962 include_groups = TRUE;
9963 xp->xp_context = EXPAND_EVENTS; /* expand event name */
9964 xp->xp_pattern = arg;
9965 return NULL;
9966 }
9967
9968 /* skip over pattern */
9969 arg = skipwhite(p);
Bram Moolenaar1c465442017-03-12 20:10:05 +01009970 while (*arg && (!VIM_ISWHITE(*arg) || arg[-1] == '\\'))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009971 arg++;
9972 if (*arg)
9973 return arg; /* expand (next) command */
9974
9975 if (doautocmd)
9976 xp->xp_context = EXPAND_FILES; /* expand file names */
9977 else
9978 xp->xp_context = EXPAND_NOTHING; /* pattern is not expanded */
9979 return NULL;
9980}
9981
9982/*
9983 * Function given to ExpandGeneric() to obtain the list of event names.
9984 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009985 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01009986get_event_name(expand_T *xp UNUSED, int idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009987{
9988 if (idx < augroups.ga_len) /* First list group names, if wanted */
9989 {
Bram Moolenaarf2c4c392016-07-29 20:50:24 +02009990 if (!include_groups || AUGROUP_NAME(idx) == NULL
Bram Moolenaarb62cc362016-09-03 16:43:53 +02009991 || AUGROUP_NAME(idx) == get_deleted_augroup())
Bram Moolenaar071d4272004-06-13 20:20:40 +00009992 return (char_u *)""; /* skip deleted entries */
9993 return AUGROUP_NAME(idx); /* return a name */
9994 }
9995 return (char_u *)event_names[idx - augroups.ga_len].name;
9996}
9997
9998#endif /* FEAT_CMDL_COMPL */
9999
10000/*
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010001 * Return TRUE if autocmd is supported.
10002 */
10003 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010004autocmd_supported(char_u *name)
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010005{
10006 char_u *p;
10007
10008 return (event_name2nr(name, &p) != NUM_EVENTS);
10009}
10010
10011/*
Bram Moolenaar195d6352005-12-19 22:08:24 +000010012 * Return TRUE if an autocommand is defined for a group, event and
10013 * pattern: The group can be omitted to accept any group. "event" and "pattern"
10014 * can be NULL to accept any event and pattern. "pattern" can be NULL to accept
10015 * any pattern. Buffer-local patterns <buffer> or <buffer=N> are accepted.
10016 * Used for:
10017 * exists("#Group") or
10018 * exists("#Group#Event") or
10019 * exists("#Group#Event#pat") or
10020 * exists("#Event") or
10021 * exists("#Event#pat")
Bram Moolenaar071d4272004-06-13 20:20:40 +000010022 */
10023 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010024au_exists(char_u *arg)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010025{
Bram Moolenaar195d6352005-12-19 22:08:24 +000010026 char_u *arg_save;
10027 char_u *pattern = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010028 char_u *event_name;
10029 char_u *p;
Bram Moolenaar754b5602006-02-09 23:53:20 +000010030 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010031 AutoPat *ap;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010032 buf_T *buflocal_buf = NULL;
Bram Moolenaar195d6352005-12-19 22:08:24 +000010033 int group;
10034 int retval = FALSE;
10035
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010036 /* Make a copy so that we can change the '#' chars to a NUL. */
Bram Moolenaar195d6352005-12-19 22:08:24 +000010037 arg_save = vim_strsave(arg);
10038 if (arg_save == NULL)
10039 return FALSE;
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +000010040 p = vim_strchr(arg_save, '#');
Bram Moolenaar195d6352005-12-19 22:08:24 +000010041 if (p != NULL)
10042 *p++ = NUL;
10043
10044 /* First, look for an autocmd group name */
10045 group = au_find_group(arg_save);
10046 if (group == AUGROUP_ERROR)
10047 {
10048 /* Didn't match a group name, assume the first argument is an event. */
10049 group = AUGROUP_ALL;
10050 event_name = arg_save;
10051 }
10052 else
10053 {
10054 if (p == NULL)
10055 {
10056 /* "Group": group name is present and it's recognized */
10057 retval = TRUE;
10058 goto theend;
10059 }
10060
10061 /* Must be "Group#Event" or "Group#Event#pat". */
10062 event_name = p;
10063 p = vim_strchr(event_name, '#');
10064 if (p != NULL)
10065 *p++ = NUL; /* "Group#Event#pat" */
10066 }
10067
10068 pattern = p; /* "pattern" is NULL when there is no pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010069
10070 /* find the index (enum) for the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010071 event = event_name2nr(event_name, &p);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010072
10073 /* return FALSE if the event name is not recognized */
Bram Moolenaar195d6352005-12-19 22:08:24 +000010074 if (event == NUM_EVENTS)
10075 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010076
10077 /* Find the first autocommand for this event.
10078 * If there isn't any, return FALSE;
10079 * If there is one and no pattern given, return TRUE; */
10080 ap = first_autopat[(int)event];
10081 if (ap == NULL)
Bram Moolenaar195d6352005-12-19 22:08:24 +000010082 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010083
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010084 /* if pattern is "<buffer>", special handling is needed which uses curbuf */
10085 /* for pattern "<buffer=N>, fnamecmp() will work fine */
Bram Moolenaar5b7880d2009-09-11 15:24:31 +000010086 if (pattern != NULL && STRICMP(pattern, "<buffer>") == 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010087 buflocal_buf = curbuf;
10088
Bram Moolenaar071d4272004-06-13 20:20:40 +000010089 /* Check if there is an autocommand with the given pattern. */
10090 for ( ; ap != NULL; ap = ap->next)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010091 /* only use a pattern when it has not been removed and has commands. */
10092 /* For buffer-local autocommands, fnamecmp() works fine. */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010093 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaar195d6352005-12-19 22:08:24 +000010094 && (group == AUGROUP_ALL || ap->group == group)
Bram Moolenaar5b7880d2009-09-11 15:24:31 +000010095 && (pattern == NULL
10096 || (buflocal_buf == NULL
10097 ? fnamecmp(ap->pat, pattern) == 0
10098 : ap->buflocal_nr == buflocal_buf->b_fnum)))
Bram Moolenaar195d6352005-12-19 22:08:24 +000010099 {
10100 retval = TRUE;
10101 break;
10102 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010103
Bram Moolenaar195d6352005-12-19 22:08:24 +000010104theend:
10105 vim_free(arg_save);
10106 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010107}
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +000010108
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010109#else /* FEAT_AUTOCMD */
10110
10111/*
10112 * Prepare for executing commands for (hidden) buffer "buf".
10113 * This is the non-autocommand version, it simply saves "curbuf" and sets
10114 * "curbuf" and "curwin" to match "buf".
10115 */
10116 void
Bram Moolenaard14e00e2016-01-31 17:30:51 +010010117aucmd_prepbuf(
10118 aco_save_T *aco, /* structure to save values in */
10119 buf_T *buf) /* new curbuf */
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010120{
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010121 aco->save_curbuf = curbuf;
10122 --curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010123 curbuf = buf;
10124 curwin->w_buffer = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010125 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010126}
10127
10128/*
10129 * Restore after executing commands for a (hidden) buffer.
10130 * This is the non-autocommand version.
10131 */
10132 void
Bram Moolenaard14e00e2016-01-31 17:30:51 +010010133aucmd_restbuf(
10134 aco_save_T *aco) /* structure holding saved values */
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010135{
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010136 --curbuf->b_nwindows;
10137 curbuf = aco->save_curbuf;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010138 curwin->w_buffer = curbuf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010139 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010140}
10141
Bram Moolenaar071d4272004-06-13 20:20:40 +000010142#endif /* FEAT_AUTOCMD */
10143
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010144
Bram Moolenaar071d4272004-06-13 20:20:40 +000010145#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN) || defined(PROTO)
10146/*
Bram Moolenaar748bf032005-02-02 23:04:36 +000010147 * Try matching a filename with a "pattern" ("prog" is NULL), or use the
10148 * precompiled regprog "prog" ("pattern" is NULL). That avoids calling
10149 * vim_regcomp() often.
Bram Moolenaar071d4272004-06-13 20:20:40 +000010150 * Used for autocommands and 'wildignore'.
10151 * Returns TRUE if there is a match, FALSE otherwise.
10152 */
Bram Moolenaardffa5b82014-11-19 16:38:07 +010010153 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010154match_file_pat(
10155 char_u *pattern, /* pattern to match with */
10156 regprog_T **prog, /* pre-compiled regprog or NULL */
10157 char_u *fname, /* full path of file name */
10158 char_u *sfname, /* short file name or NULL */
10159 char_u *tail, /* tail of path */
10160 int allow_dirs) /* allow matching with dir */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010161{
10162 regmatch_T regmatch;
10163 int result = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010164
Bram Moolenaar71afbfe2013-03-19 16:49:16 +010010165 regmatch.rm_ic = p_fic; /* ignore case if 'fileignorecase' is set */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010166 if (prog != NULL)
10167 regmatch.regprog = *prog;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010168 else
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010169 regmatch.regprog = vim_regcomp(pattern, RE_MAGIC);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010170
10171 /*
10172 * Try for a match with the pattern with:
10173 * 1. the full file name, when the pattern has a '/'.
10174 * 2. the short file name, when the pattern has a '/'.
10175 * 3. the tail of the file name, when the pattern has no '/'.
10176 */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010177 if (regmatch.regprog != NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +000010178 && ((allow_dirs
10179 && (vim_regexec(&regmatch, fname, (colnr_T)0)
10180 || (sfname != NULL
10181 && vim_regexec(&regmatch, sfname, (colnr_T)0))))
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010182 || (!allow_dirs && vim_regexec(&regmatch, tail, (colnr_T)0))))
Bram Moolenaar071d4272004-06-13 20:20:40 +000010183 result = TRUE;
10184
Bram Moolenaardffa5b82014-11-19 16:38:07 +010010185 if (prog != NULL)
10186 *prog = regmatch.regprog;
10187 else
Bram Moolenaar473de612013-06-08 18:19:48 +020010188 vim_regfree(regmatch.regprog);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010189 return result;
10190}
10191#endif
10192
10193#if defined(FEAT_WILDIGN) || defined(PROTO)
10194/*
10195 * Return TRUE if a file matches with a pattern in "list".
10196 * "list" is a comma-separated list of patterns, like 'wildignore'.
10197 * "sfname" is the short file name or NULL, "ffname" the long file name.
10198 */
10199 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010200match_file_list(char_u *list, char_u *sfname, char_u *ffname)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010201{
10202 char_u buf[100];
10203 char_u *tail;
10204 char_u *regpat;
10205 char allow_dirs;
10206 int match;
10207 char_u *p;
10208
10209 tail = gettail(sfname);
10210
10211 /* try all patterns in 'wildignore' */
10212 p = list;
10213 while (*p)
10214 {
10215 copy_option_part(&p, buf, 100, ",");
10216 regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, FALSE);
10217 if (regpat == NULL)
10218 break;
Bram Moolenaar748bf032005-02-02 23:04:36 +000010219 match = match_file_pat(regpat, NULL, ffname, sfname,
10220 tail, (int)allow_dirs);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010221 vim_free(regpat);
10222 if (match)
10223 return TRUE;
10224 }
10225 return FALSE;
10226}
10227#endif
10228
10229/*
10230 * Convert the given pattern "pat" which has shell style wildcards in it, into
10231 * a regular expression, and return the result in allocated memory. If there
10232 * is a directory path separator to be matched, then TRUE is put in
10233 * allow_dirs, otherwise FALSE is put there -- webb.
10234 * Handle backslashes before special characters, like "\*" and "\ ".
10235 *
Bram Moolenaar071d4272004-06-13 20:20:40 +000010236 * Returns NULL when out of memory.
10237 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010238 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010239file_pat_to_reg_pat(
10240 char_u *pat,
10241 char_u *pat_end, /* first char after pattern or NULL */
10242 char *allow_dirs, /* Result passed back out in here */
10243 int no_bslash UNUSED) /* Don't use a backward slash as pathsep */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010244{
Bram Moolenaar49a6ed82015-01-07 14:43:39 +010010245 int size = 2; /* '^' at start, '$' at end */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010246 char_u *endp;
10247 char_u *reg_pat;
10248 char_u *p;
10249 int i;
10250 int nested = 0;
10251 int add_dollar = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010252
10253 if (allow_dirs != NULL)
10254 *allow_dirs = FALSE;
10255 if (pat_end == NULL)
10256 pat_end = pat + STRLEN(pat);
10257
Bram Moolenaar071d4272004-06-13 20:20:40 +000010258 for (p = pat; p < pat_end; p++)
10259 {
10260 switch (*p)
10261 {
10262 case '*':
10263 case '.':
10264 case ',':
10265 case '{':
10266 case '}':
10267 case '~':
10268 size += 2; /* extra backslash */
10269 break;
10270#ifdef BACKSLASH_IN_FILENAME
10271 case '\\':
10272 case '/':
10273 size += 4; /* could become "[\/]" */
10274 break;
10275#endif
10276 default:
10277 size++;
Bram Moolenaar2288afe2015-08-11 16:20:05 +020010278# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010279 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010280 {
10281 ++p;
10282 ++size;
10283 }
10284# endif
10285 break;
10286 }
10287 }
10288 reg_pat = alloc(size + 1);
10289 if (reg_pat == NULL)
10290 return NULL;
10291
Bram Moolenaar071d4272004-06-13 20:20:40 +000010292 i = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010293
10294 if (pat[0] == '*')
10295 while (pat[0] == '*' && pat < pat_end - 1)
10296 pat++;
10297 else
10298 reg_pat[i++] = '^';
10299 endp = pat_end - 1;
Bram Moolenaar8fee8782015-08-11 18:45:48 +020010300 if (endp >= pat && *endp == '*')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010301 {
10302 while (endp - pat > 0 && *endp == '*')
10303 endp--;
10304 add_dollar = FALSE;
10305 }
10306 for (p = pat; *p && nested >= 0 && p <= endp; p++)
10307 {
10308 switch (*p)
10309 {
10310 case '*':
10311 reg_pat[i++] = '.';
10312 reg_pat[i++] = '*';
Bram Moolenaar02743632005-07-25 20:42:36 +000010313 while (p[1] == '*') /* "**" matches like "*" */
10314 ++p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010315 break;
10316 case '.':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010317 case '~':
10318 reg_pat[i++] = '\\';
10319 reg_pat[i++] = *p;
10320 break;
10321 case '?':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010322 reg_pat[i++] = '.';
10323 break;
10324 case '\\':
10325 if (p[1] == NUL)
10326 break;
10327#ifdef BACKSLASH_IN_FILENAME
10328 if (!no_bslash)
10329 {
10330 /* translate:
10331 * "\x" to "\\x" e.g., "dir\file"
10332 * "\*" to "\\.*" e.g., "dir\*.c"
10333 * "\?" to "\\." e.g., "dir\??.c"
10334 * "\+" to "\+" e.g., "fileX\+.c"
10335 */
10336 if ((vim_isfilec(p[1]) || p[1] == '*' || p[1] == '?')
10337 && p[1] != '+')
10338 {
10339 reg_pat[i++] = '[';
10340 reg_pat[i++] = '\\';
10341 reg_pat[i++] = '/';
10342 reg_pat[i++] = ']';
10343 if (allow_dirs != NULL)
10344 *allow_dirs = TRUE;
10345 break;
10346 }
10347 }
10348#endif
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010349 /* Undo escaping from ExpandEscape():
10350 * foo\?bar -> foo?bar
10351 * foo\%bar -> foo%bar
10352 * foo\,bar -> foo,bar
10353 * foo\ bar -> foo bar
10354 * Don't unescape \, * and others that are also special in a
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010355 * regexp.
10356 * An escaped { must be unescaped since we use magic not
Bram Moolenaara946afe2013-08-02 15:22:39 +020010357 * verymagic. Use "\\\{n,m\}"" to get "\{n,m}".
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010358 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010359 if (*++p == '?'
10360#ifdef BACKSLASH_IN_FILENAME
10361 && no_bslash
10362#endif
10363 )
10364 reg_pat[i++] = '?';
10365 else
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010366 if (*p == ',' || *p == '%' || *p == '#'
Bram Moolenaar2288afe2015-08-11 16:20:05 +020010367 || vim_isspace(*p) || *p == '{' || *p == '}')
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010368 reg_pat[i++] = *p;
Bram Moolenaara946afe2013-08-02 15:22:39 +020010369 else if (*p == '\\' && p[1] == '\\' && p[2] == '{')
10370 {
10371 reg_pat[i++] = '\\';
10372 reg_pat[i++] = '{';
10373 p += 2;
10374 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010375 else
10376 {
10377 if (allow_dirs != NULL && vim_ispathsep(*p)
10378#ifdef BACKSLASH_IN_FILENAME
10379 && (!no_bslash || *p != '\\')
10380#endif
10381 )
10382 *allow_dirs = TRUE;
10383 reg_pat[i++] = '\\';
10384 reg_pat[i++] = *p;
10385 }
10386 break;
10387#ifdef BACKSLASH_IN_FILENAME
10388 case '/':
10389 reg_pat[i++] = '[';
10390 reg_pat[i++] = '\\';
10391 reg_pat[i++] = '/';
10392 reg_pat[i++] = ']';
10393 if (allow_dirs != NULL)
10394 *allow_dirs = TRUE;
10395 break;
10396#endif
10397 case '{':
10398 reg_pat[i++] = '\\';
10399 reg_pat[i++] = '(';
10400 nested++;
10401 break;
10402 case '}':
10403 reg_pat[i++] = '\\';
10404 reg_pat[i++] = ')';
10405 --nested;
10406 break;
10407 case ',':
10408 if (nested)
10409 {
10410 reg_pat[i++] = '\\';
10411 reg_pat[i++] = '|';
10412 }
10413 else
10414 reg_pat[i++] = ',';
10415 break;
10416 default:
10417# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010418 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010419 reg_pat[i++] = *p++;
10420 else
10421# endif
10422 if (allow_dirs != NULL && vim_ispathsep(*p))
10423 *allow_dirs = TRUE;
10424 reg_pat[i++] = *p;
10425 break;
10426 }
10427 }
10428 if (add_dollar)
10429 reg_pat[i++] = '$';
10430 reg_pat[i] = NUL;
10431 if (nested != 0)
10432 {
10433 if (nested < 0)
10434 EMSG(_("E219: Missing {."));
10435 else
10436 EMSG(_("E220: Missing }."));
10437 vim_free(reg_pat);
10438 reg_pat = NULL;
10439 }
10440 return reg_pat;
10441}
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010442
10443#if defined(EINTR) || defined(PROTO)
10444/*
10445 * Version of read() that retries when interrupted by EINTR (possibly
10446 * by a SIGWINCH).
10447 */
10448 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010449read_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010450{
10451 long ret;
10452
10453 for (;;)
10454 {
10455 ret = vim_read(fd, buf, bufsize);
10456 if (ret >= 0 || errno != EINTR)
10457 break;
10458 }
10459 return ret;
10460}
10461
10462/*
10463 * Version of write() that retries when interrupted by EINTR (possibly
10464 * by a SIGWINCH).
10465 */
10466 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010010467write_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010468{
10469 long ret = 0;
10470 long wlen;
10471
10472 /* Repeat the write() so long it didn't fail, other than being interrupted
10473 * by a signal. */
10474 while (ret < (long)bufsize)
10475 {
Bram Moolenaar9c263032010-12-17 18:06:06 +010010476 wlen = vim_write(fd, (char *)buf + ret, bufsize - ret);
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010477 if (wlen < 0)
10478 {
10479 if (errno != EINTR)
10480 break;
10481 }
10482 else
10483 ret += wlen;
10484 }
10485 return ret;
10486}
10487#endif