blob: 71ecf42aead5148acfe3333720302f0c44dce677 [file] [log] [blame]
Bram Moolenaar071d4272004-06-13 20:20:40 +00001/* vi:set ts=8 sts=4 sw=4:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
11 * fileio.c: read from and write to a file
12 */
13
Bram Moolenaar071d4272004-06-13 20:20:40 +000014#include "vim.h"
15
Bram Moolenaarf4888d02009-12-02 12:31:27 +000016#if defined(__TANDEM) || defined(__MINT__)
Bram Moolenaar071d4272004-06-13 20:20:40 +000017# include <limits.h> /* for SSIZE_MAX */
18#endif
19
20#if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
21# include <utime.h> /* for struct utimbuf */
22#endif
23
24#define BUFSIZE 8192 /* size of normal write buffer */
25#define SMBUFSIZE 256 /* size of emergency write buffer */
26
27#ifdef FEAT_CRYPT
Bram Moolenaar40e6a712010-05-16 22:32:54 +020028/* crypt_magic[0] is pkzip crypt, crypt_magic[1] is sha2+blowfish */
Bram Moolenaarf50a2532010-05-21 15:36:08 +020029static char *crypt_magic[] = {"VimCrypt~01!", "VimCrypt~02!"};
30static char crypt_magic_head[] = "VimCrypt~";
31# define CRYPT_MAGIC_LEN 12 /* must be multiple of 4! */
Bram Moolenaar80794b12010-06-13 05:20:42 +020032
33/* For blowfish, after the magic header, we store 8 bytes of salt and then 8
34 * bytes of seed (initialisation vector). */
35static int crypt_salt_len[] = {0, 8};
Bram Moolenaarf50a2532010-05-21 15:36:08 +020036static int crypt_seed_len[] = {0, 8};
Bram Moolenaar80794b12010-06-13 05:20:42 +020037#define CRYPT_SALT_LEN_MAX 8
Bram Moolenaar40e6a712010-05-16 22:32:54 +020038#define CRYPT_SEED_LEN_MAX 8
Bram Moolenaar071d4272004-06-13 20:20:40 +000039#endif
40
41/* Is there any system that doesn't have access()? */
Bram Moolenaar9372a112005-12-06 19:59:18 +000042#define USE_MCH_ACCESS
Bram Moolenaar071d4272004-06-13 20:20:40 +000043
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +000044#if defined(sun) && defined(S_ISCHR)
45# define OPEN_CHR_FILES
46static int is_dev_fd_file(char_u *fname);
47#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000048#ifdef FEAT_MBYTE
49static char_u *next_fenc __ARGS((char_u **pp));
50# ifdef FEAT_EVAL
51static char_u *readfile_charconvert __ARGS((char_u *fname, char_u *fenc, int *fdp));
52# endif
53#endif
54#ifdef FEAT_VIMINFO
55static void check_marks_read __ARGS((void));
56#endif
57#ifdef FEAT_CRYPT
Bram Moolenaar49771f42010-07-20 17:32:38 +020058static int crypt_method_from_magic __ARGS((char *ptr, int len));
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +020059static char_u *check_for_cryptkey __ARGS((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 +000060#endif
61#ifdef UNIX
62static void set_file_time __ARGS((char_u *fname, time_t atime, time_t mtime));
63#endif
Bram Moolenaar2d3f4892006-01-20 23:02:51 +000064static int set_rw_fname __ARGS((char_u *fname, char_u *sfname));
Bram Moolenaar071d4272004-06-13 20:20:40 +000065static int msg_add_fileformat __ARGS((int eol_type));
Bram Moolenaar071d4272004-06-13 20:20:40 +000066static void msg_add_eol __ARGS((void));
67static int check_mtime __ARGS((buf_T *buf, struct stat *s));
68static int time_differs __ARGS((long t1, long t2));
69#ifdef FEAT_AUTOCMD
Bram Moolenaar754b5602006-02-09 23:53:20 +000070static int apply_autocmds_exarg __ARGS((event_T event, char_u *fname, char_u *fname_io, int force, buf_T *buf, exarg_T *eap));
Bram Moolenaar70836c82006-02-20 21:28:49 +000071static int au_find_group __ARGS((char_u *name));
72
73# define AUGROUP_DEFAULT -1 /* default autocmd group */
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +000074# define AUGROUP_ERROR -2 /* erroneous autocmd group */
Bram Moolenaar70836c82006-02-20 21:28:49 +000075# define AUGROUP_ALL -3 /* all autocmd groups */
Bram Moolenaar071d4272004-06-13 20:20:40 +000076#endif
77
78#if defined(FEAT_CRYPT) || defined(FEAT_MBYTE)
79# define HAS_BW_FLAGS
80# define FIO_LATIN1 0x01 /* convert Latin1 */
81# define FIO_UTF8 0x02 /* convert UTF-8 */
82# define FIO_UCS2 0x04 /* convert UCS-2 */
83# define FIO_UCS4 0x08 /* convert UCS-4 */
84# define FIO_UTF16 0x10 /* convert UTF-16 */
85# ifdef WIN3264
86# define FIO_CODEPAGE 0x20 /* convert MS-Windows codepage */
87# define FIO_PUT_CP(x) (((x) & 0xffff) << 16) /* put codepage in top word */
88# define FIO_GET_CP(x) (((x)>>16) & 0xffff) /* get codepage from top word */
89# endif
90# ifdef MACOS_X
91# define FIO_MACROMAN 0x20 /* convert MacRoman */
92# endif
93# define FIO_ENDIAN_L 0x80 /* little endian */
94# define FIO_ENCRYPTED 0x1000 /* encrypt written bytes */
95# define FIO_NOCONVERT 0x2000 /* skip encoding conversion */
96# define FIO_UCSBOM 0x4000 /* check for BOM at start of file */
97# define FIO_ALL -1 /* allow all formats */
98#endif
99
100/* When converting, a read() or write() may leave some bytes to be converted
101 * for the next call. The value is guessed... */
102#define CONV_RESTLEN 30
103
104/* We have to guess how much a sequence of bytes may expand when converting
105 * with iconv() to be able to allocate a buffer. */
106#define ICONV_MULT 8
107
108/*
109 * Structure to pass arguments from buf_write() to buf_write_bytes().
110 */
111struct bw_info
112{
113 int bw_fd; /* file descriptor */
114 char_u *bw_buf; /* buffer with data to be written */
Bram Moolenaard089d9b2007-09-30 12:02:55 +0000115 int bw_len; /* length of data */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000116#ifdef HAS_BW_FLAGS
117 int bw_flags; /* FIO_ flags */
118#endif
119#ifdef FEAT_MBYTE
120 char_u bw_rest[CONV_RESTLEN]; /* not converted bytes */
121 int bw_restlen; /* nr of bytes in bw_rest[] */
122 int bw_first; /* first write call */
123 char_u *bw_conv_buf; /* buffer for writing converted chars */
124 int bw_conv_buflen; /* size of bw_conv_buf */
125 int bw_conv_error; /* set for conversion error */
Bram Moolenaar32b485f2009-07-29 16:06:27 +0000126 linenr_T bw_conv_error_lnum; /* first line with error or zero */
127 linenr_T bw_start_lnum; /* line number at start of buffer */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000128# ifdef USE_ICONV
129 iconv_t bw_iconv_fd; /* descriptor for iconv() or -1 */
130# endif
131#endif
132};
133
134static int buf_write_bytes __ARGS((struct bw_info *ip));
135
136#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000137static linenr_T readfile_linenr __ARGS((linenr_T linecnt, char_u *p, char_u *endp));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000138static int ucs2bytes __ARGS((unsigned c, char_u **pp, int flags));
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +0000139static int need_conversion __ARGS((char_u *fenc));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000140static int get_fio_flags __ARGS((char_u *ptr));
141static char_u *check_for_bom __ARGS((char_u *p, long size, int *lenp, int flags));
142static int make_bom __ARGS((char_u *buf, char_u *name));
143# ifdef WIN3264
144static int get_win_fio_flags __ARGS((char_u *ptr));
145# endif
146# ifdef MACOS_X
147static int get_mac_fio_flags __ARGS((char_u *ptr));
148# endif
149#endif
150static int move_lines __ARGS((buf_T *frombuf, buf_T *tobuf));
Bram Moolenaar4592dee2009-11-18 19:11:58 +0000151#ifdef TEMPDIRNAMES
Bram Moolenaareaf03392009-11-17 11:08:52 +0000152static void vim_settempdir __ARGS((char_u *tempdir));
Bram Moolenaar4592dee2009-11-18 19:11:58 +0000153#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000154#ifdef FEAT_AUTOCMD
155static char *e_auchangedbuf = N_("E812: Autocommands changed buffer or buffer name");
156#endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000157
Bram Moolenaar071d4272004-06-13 20:20:40 +0000158 void
159filemess(buf, name, s, attr)
160 buf_T *buf;
161 char_u *name;
162 char_u *s;
163 int attr;
164{
165 int msg_scroll_save;
166
167 if (msg_silent != 0)
168 return;
169 msg_add_fname(buf, name); /* put file name in IObuff with quotes */
170 /* If it's extremely long, truncate it. */
171 if (STRLEN(IObuff) > IOSIZE - 80)
172 IObuff[IOSIZE - 80] = NUL;
173 STRCAT(IObuff, s);
174 /*
175 * For the first message may have to start a new line.
176 * For further ones overwrite the previous one, reset msg_scroll before
177 * calling filemess().
178 */
179 msg_scroll_save = msg_scroll;
180 if (shortmess(SHM_OVERALL) && !exiting && p_verbose == 0)
181 msg_scroll = FALSE;
182 if (!msg_scroll) /* wait a bit when overwriting an error msg */
183 check_for_delay(FALSE);
184 msg_start();
185 msg_scroll = msg_scroll_save;
186 msg_scrolled_ign = TRUE;
187 /* may truncate the message to avoid a hit-return prompt */
188 msg_outtrans_attr(msg_may_trunc(FALSE, IObuff), attr);
189 msg_clr_eos();
190 out_flush();
191 msg_scrolled_ign = FALSE;
192}
193
194/*
195 * Read lines from file "fname" into the buffer after line "from".
196 *
197 * 1. We allocate blocks with lalloc, as big as possible.
198 * 2. Each block is filled with characters from the file with a single read().
199 * 3. The lines are inserted in the buffer with ml_append().
200 *
201 * (caller must check that fname != NULL, unless READ_STDIN is used)
202 *
203 * "lines_to_skip" is the number of lines that must be skipped
204 * "lines_to_read" is the number of lines that are appended
205 * When not recovering lines_to_skip is 0 and lines_to_read MAXLNUM.
206 *
207 * flags:
208 * READ_NEW starting to edit a new buffer
209 * READ_FILTER reading filter output
210 * READ_STDIN read from stdin instead of a file
211 * READ_BUFFER read from curbuf instead of a file (converting after reading
212 * stdin)
213 * READ_DUMMY read into a dummy buffer (to check if file contents changed)
Bram Moolenaar59f931e2010-07-24 20:27:03 +0200214 * READ_KEEP_UNDO don't clear undo info or read it from a file
Bram Moolenaar071d4272004-06-13 20:20:40 +0000215 *
216 * return FAIL for failure, OK otherwise
217 */
218 int
219readfile(fname, sfname, from, lines_to_skip, lines_to_read, eap, flags)
220 char_u *fname;
221 char_u *sfname;
222 linenr_T from;
223 linenr_T lines_to_skip;
224 linenr_T lines_to_read;
225 exarg_T *eap; /* can be NULL! */
226 int flags;
227{
228 int fd = 0;
229 int newfile = (flags & READ_NEW);
230 int check_readonly;
231 int filtering = (flags & READ_FILTER);
232 int read_stdin = (flags & READ_STDIN);
233 int read_buffer = (flags & READ_BUFFER);
Bram Moolenaar690ffc02008-01-04 15:31:21 +0000234 int set_options = newfile || read_buffer
235 || (eap != NULL && eap->read_edit);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000236 linenr_T read_buf_lnum = 1; /* next line to read from curbuf */
237 colnr_T read_buf_col = 0; /* next char to read from this line */
238 char_u c;
239 linenr_T lnum = from;
240 char_u *ptr = NULL; /* pointer into read buffer */
241 char_u *buffer = NULL; /* read buffer */
242 char_u *new_buffer = NULL; /* init to shut up gcc */
243 char_u *line_start = NULL; /* init to shut up gcc */
244 int wasempty; /* buffer was empty before reading */
245 colnr_T len;
246 long size = 0;
247 char_u *p;
Bram Moolenaar914703b2010-05-31 21:59:46 +0200248 off_t filesize = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000249 int skip_read = FALSE;
250#ifdef FEAT_CRYPT
251 char_u *cryptkey = NULL;
Bram Moolenaarf50a2532010-05-21 15:36:08 +0200252 int did_ask_for_key = FALSE;
Bram Moolenaar4cf35c22011-02-25 16:52:17 +0100253 int crypt_method_used;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000254#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +0200255#ifdef FEAT_PERSISTENT_UNDO
256 context_sha256_T sha_ctx;
257 int read_undo_file = FALSE;
258#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000259 int split = 0; /* number of split lines */
260#define UNKNOWN 0x0fffffff /* file size is unknown */
261 linenr_T linecnt;
262 int error = FALSE; /* errors encountered */
263 int ff_error = EOL_UNKNOWN; /* file format with errors */
264 long linerest = 0; /* remaining chars in line */
265#ifdef UNIX
266 int perm = 0;
267 int swap_mode = -1; /* protection bits for swap file */
268#else
269 int perm;
270#endif
271 int fileformat = 0; /* end-of-line format */
272 int keep_fileformat = FALSE;
273 struct stat st;
274 int file_readonly;
275 linenr_T skip_count = 0;
276 linenr_T read_count = 0;
277 int msg_save = msg_scroll;
278 linenr_T read_no_eol_lnum = 0; /* non-zero lnum when last line of
279 * last read was missing the eol */
280 int try_mac = (vim_strchr(p_ffs, 'm') != NULL);
281 int try_dos = (vim_strchr(p_ffs, 'd') != NULL);
282 int try_unix = (vim_strchr(p_ffs, 'x') != NULL);
283 int file_rewind = FALSE;
284#ifdef FEAT_MBYTE
285 int can_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000286 linenr_T conv_error = 0; /* line nr with conversion error */
287 linenr_T illegal_byte = 0; /* line nr with illegal byte */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000288 int keep_dest_enc = FALSE; /* don't retry when char doesn't fit
289 in destination encoding */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000290 int bad_char_behavior = BAD_REPLACE;
291 /* BAD_KEEP, BAD_DROP or character to
292 * replace with */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000293 char_u *tmpname = NULL; /* name of 'charconvert' output file */
294 int fio_flags = 0;
295 char_u *fenc; /* fileencoding to use */
296 int fenc_alloced; /* fenc_next is in allocated memory */
297 char_u *fenc_next = NULL; /* next item in 'fencs' or NULL */
298 int advance_fenc = FALSE;
299 long real_size = 0;
300# ifdef USE_ICONV
301 iconv_t iconv_fd = (iconv_t)-1; /* descriptor for iconv() or -1 */
302# ifdef FEAT_EVAL
303 int did_iconv = FALSE; /* TRUE when iconv() failed and trying
304 'charconvert' next */
305# endif
306# endif
307 int converted = FALSE; /* TRUE if conversion done */
308 int notconverted = FALSE; /* TRUE if conversion wanted but it
309 wasn't possible */
310 char_u conv_rest[CONV_RESTLEN];
311 int conv_restlen = 0; /* nr of bytes in conv_rest[] */
312#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000313#ifdef FEAT_AUTOCMD
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200314 buf_T *old_curbuf;
315 char_u *old_b_ffname;
316 char_u *old_b_fname;
317 int using_b_ffname;
318 int using_b_fname;
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000319#endif
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200320
Bram Moolenaarcab35ad2011-02-15 17:39:22 +0100321 curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000322
323 /*
324 * If there is no file name yet, use the one for the read file.
325 * BF_NOTEDITED is set to reflect this.
326 * Don't do this for a read from a filter.
327 * Only do this when 'cpoptions' contains the 'f' flag.
328 */
329 if (curbuf->b_ffname == NULL
330 && !filtering
331 && fname != NULL
332 && vim_strchr(p_cpo, CPO_FNAMER) != NULL
333 && !(flags & READ_DUMMY))
334 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000335 if (set_rw_fname(fname, sfname) == FAIL)
336 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000337 }
338
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200339#ifdef FEAT_AUTOCMD
340 /* Remember the initial values of curbuf, curbuf->b_ffname and
341 * curbuf->b_fname to detect whether they are altered as a result of
342 * executing nasty autocommands. Also check if "fname" and "sfname"
343 * point to one of these values. */
344 old_curbuf = curbuf;
345 old_b_ffname = curbuf->b_ffname;
346 old_b_fname = curbuf->b_fname;
347 using_b_ffname = (fname == curbuf->b_ffname)
348 || (sfname == curbuf->b_ffname);
349 using_b_fname = (fname == curbuf->b_fname) || (sfname == curbuf->b_fname);
350#endif
351
Bram Moolenaardf177f62005-02-22 08:39:57 +0000352 /* After reading a file the cursor line changes but we don't want to
353 * display the line. */
354 ex_no_reprint = TRUE;
355
Bram Moolenaar55b7cf82006-09-09 12:52:42 +0000356 /* don't display the file info for another buffer now */
357 need_fileinfo = FALSE;
358
Bram Moolenaar071d4272004-06-13 20:20:40 +0000359 /*
360 * For Unix: Use the short file name whenever possible.
361 * Avoids problems with networks and when directory names are changed.
362 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
363 * another directory, which we don't detect.
364 */
365 if (sfname == NULL)
366 sfname = fname;
367#if defined(UNIX) || defined(__EMX__)
368 fname = sfname;
369#endif
370
371#ifdef FEAT_AUTOCMD
372 /*
373 * The BufReadCmd and FileReadCmd events intercept the reading process by
374 * executing the associated commands instead.
375 */
376 if (!filtering && !read_stdin && !read_buffer)
377 {
378 pos_T pos;
379
380 pos = curbuf->b_op_start;
381
382 /* Set '[ mark to the line above where the lines go (line 1 if zero). */
383 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
384 curbuf->b_op_start.col = 0;
385
386 if (newfile)
387 {
388 if (apply_autocmds_exarg(EVENT_BUFREADCMD, NULL, sfname,
389 FALSE, curbuf, eap))
390#ifdef FEAT_EVAL
391 return aborting() ? FAIL : OK;
392#else
393 return OK;
394#endif
395 }
396 else if (apply_autocmds_exarg(EVENT_FILEREADCMD, sfname, sfname,
397 FALSE, NULL, eap))
398#ifdef FEAT_EVAL
399 return aborting() ? FAIL : OK;
400#else
401 return OK;
402#endif
403
404 curbuf->b_op_start = pos;
405 }
406#endif
407
408 if ((shortmess(SHM_OVER) || curbuf->b_help) && p_verbose == 0)
409 msg_scroll = FALSE; /* overwrite previous file message */
410 else
411 msg_scroll = TRUE; /* don't overwrite previous file message */
412
413 /*
414 * If the name ends in a path separator, we can't open it. Check here,
415 * because reading the file may actually work, but then creating the swap
416 * file may destroy it! Reported on MS-DOS and Win 95.
417 * If the name is too long we might crash further on, quit here.
418 */
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000419 if (fname != NULL && *fname != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000420 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000421 p = fname + STRLEN(fname);
422 if (after_pathsep(fname, p) || STRLEN(fname) >= MAXPATHL)
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000423 {
424 filemess(curbuf, fname, (char_u *)_("Illegal file name"), 0);
425 msg_end();
426 msg_scroll = msg_save;
427 return FAIL;
428 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000429 }
430
431#ifdef UNIX
432 /*
433 * On Unix it is possible to read a directory, so we have to
434 * check for it before the mch_open().
435 */
436 if (!read_stdin && !read_buffer)
437 {
438 perm = mch_getperm(fname);
439 if (perm >= 0 && !S_ISREG(perm) /* not a regular file ... */
440# ifdef S_ISFIFO
441 && !S_ISFIFO(perm) /* ... or fifo */
442# endif
443# ifdef S_ISSOCK
444 && !S_ISSOCK(perm) /* ... or socket */
445# endif
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +0000446# ifdef OPEN_CHR_FILES
447 && !(S_ISCHR(perm) && is_dev_fd_file(fname))
448 /* ... or a character special file named /dev/fd/<n> */
449# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000450 )
451 {
452 if (S_ISDIR(perm))
453 filemess(curbuf, fname, (char_u *)_("is a directory"), 0);
454 else
455 filemess(curbuf, fname, (char_u *)_("is not a file"), 0);
456 msg_end();
457 msg_scroll = msg_save;
458 return FAIL;
459 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000460
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000461# if defined(MSDOS) || defined(MSWIN) || defined(OS2)
462 /*
463 * MS-Windows allows opening a device, but we will probably get stuck
464 * trying to read it.
465 */
466 if (!p_odev && mch_nodetype(fname) == NODE_WRITABLE)
467 {
Bram Moolenaar5386a122007-06-28 20:02:32 +0000468 filemess(curbuf, fname, (char_u *)_("is a device (disabled with 'opendevice' option)"), 0);
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000469 msg_end();
470 msg_scroll = msg_save;
471 return FAIL;
472 }
473# endif
Bram Moolenaar043545e2006-10-10 16:44:07 +0000474 }
475#endif
476
Bram Moolenaar071d4272004-06-13 20:20:40 +0000477 /* set default 'fileformat' */
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000478 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000479 {
480 if (eap != NULL && eap->force_ff != 0)
481 set_fileformat(get_fileformat_force(curbuf, eap), OPT_LOCAL);
482 else if (*p_ffs != NUL)
483 set_fileformat(default_fileformat(), OPT_LOCAL);
484 }
485
486 /* set or reset 'binary' */
487 if (eap != NULL && eap->force_bin != 0)
488 {
489 int oldval = curbuf->b_p_bin;
490
491 curbuf->b_p_bin = (eap->force_bin == FORCE_BIN);
492 set_options_bin(oldval, curbuf->b_p_bin, OPT_LOCAL);
493 }
494
495 /*
496 * When opening a new file we take the readonly flag from the file.
497 * Default is r/w, can be set to r/o below.
498 * Don't reset it when in readonly mode
499 * Only set/reset b_p_ro when BF_CHECK_RO is set.
500 */
501 check_readonly = (newfile && (curbuf->b_flags & BF_CHECK_RO));
Bram Moolenaar4399ef42005-02-12 14:29:27 +0000502 if (check_readonly && !readonlymode)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000503 curbuf->b_p_ro = FALSE;
504
505 if (newfile && !read_stdin && !read_buffer)
506 {
Bram Moolenaare60acc12011-05-10 16:41:25 +0200507 /* Remember time of file. */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000508 if (mch_stat((char *)fname, &st) >= 0)
509 {
510 buf_store_time(curbuf, &st, fname);
511 curbuf->b_mtime_read = curbuf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000512#ifdef UNIX
513 /*
514 * Use the protection bits of the original file for the swap file.
515 * This makes it possible for others to read the name of the
516 * edited file from the swapfile, but only if they can read the
517 * edited file.
518 * Remove the "write" and "execute" bits for group and others
519 * (they must not write the swapfile).
520 * Add the "read" and "write" bits for the user, otherwise we may
521 * not be able to write to the file ourselves.
522 * Setting the bits is done below, after creating the swap file.
523 */
524 swap_mode = (st.st_mode & 0644) | 0600;
525#endif
526#ifdef FEAT_CW_EDITOR
527 /* Get the FSSpec on MacOS
528 * TODO: Update it properly when the buffer name changes
529 */
530 (void)GetFSSpecFromPath(curbuf->b_ffname, &curbuf->b_FSSpec);
531#endif
532#ifdef VMS
533 curbuf->b_fab_rfm = st.st_fab_rfm;
Bram Moolenaard4755bb2004-09-02 19:12:26 +0000534 curbuf->b_fab_rat = st.st_fab_rat;
535 curbuf->b_fab_mrs = st.st_fab_mrs;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000536#endif
537 }
538 else
539 {
540 curbuf->b_mtime = 0;
541 curbuf->b_mtime_read = 0;
542 curbuf->b_orig_size = 0;
543 curbuf->b_orig_mode = 0;
544 }
545
546 /* Reset the "new file" flag. It will be set again below when the
547 * file doesn't exist. */
548 curbuf->b_flags &= ~(BF_NEW | BF_NEW_W);
549 }
550
551/*
552 * for UNIX: check readonly with perm and mch_access()
Bram Moolenaar071d4272004-06-13 20:20:40 +0000553 * for MSDOS and Amiga: check readonly by trying to open the file for writing
554 */
555 file_readonly = FALSE;
556 if (read_stdin)
557 {
558#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
559 /* Force binary I/O on stdin to avoid CR-LF -> LF conversion. */
560 setmode(0, O_BINARY);
561#endif
562 }
563 else if (!read_buffer)
564 {
565#ifdef USE_MCH_ACCESS
566 if (
567# ifdef UNIX
568 !(perm & 0222) ||
569# endif
570 mch_access((char *)fname, W_OK))
571 file_readonly = TRUE;
572 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
573#else
574 if (!newfile
575 || readonlymode
576 || (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0)
577 {
578 file_readonly = TRUE;
579 /* try to open ro */
580 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
581 }
582#endif
583 }
584
585 if (fd < 0) /* cannot open at all */
586 {
587#ifndef UNIX
588 int isdir_f;
589#endif
590 msg_scroll = msg_save;
591#ifndef UNIX
592 /*
593 * On MSDOS and Amiga we can't open a directory, check here.
594 */
595 isdir_f = (mch_isdir(fname));
596 perm = mch_getperm(fname); /* check if the file exists */
597 if (isdir_f)
598 {
599 filemess(curbuf, sfname, (char_u *)_("is a directory"), 0);
600 curbuf->b_p_ro = TRUE; /* must use "w!" now */
601 }
602 else
603#endif
604 if (newfile)
605 {
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200606 if (perm < 0
607#ifdef ENOENT
608 && errno == ENOENT
609#endif
610 )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000611 {
612 /*
613 * Set the 'new-file' flag, so that when the file has
614 * been created by someone else, a ":w" will complain.
615 */
616 curbuf->b_flags |= BF_NEW;
617
618 /* Create a swap file now, so that other Vims are warned
619 * that we are editing this file. Don't do this for a
620 * "nofile" or "nowrite" buffer type. */
621#ifdef FEAT_QUICKFIX
622 if (!bt_dontwrite(curbuf))
623#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000624 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000625 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000626#ifdef FEAT_AUTOCMD
627 /* SwapExists autocommand may mess things up */
628 if (curbuf != old_curbuf
629 || (using_b_ffname
630 && (old_b_ffname != curbuf->b_ffname))
631 || (using_b_fname
632 && (old_b_fname != curbuf->b_fname)))
633 {
634 EMSG(_(e_auchangedbuf));
635 return FAIL;
636 }
637#endif
638 }
Bram Moolenaar5b962cf2005-12-12 21:58:40 +0000639 if (dir_of_file_exists(fname))
640 filemess(curbuf, sfname, (char_u *)_("[New File]"), 0);
641 else
642 filemess(curbuf, sfname,
643 (char_u *)_("[New DIRECTORY]"), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000644#ifdef FEAT_VIMINFO
645 /* Even though this is a new file, it might have been
646 * edited before and deleted. Get the old marks. */
647 check_marks_read();
648#endif
649#ifdef FEAT_MBYTE
650 if (eap != NULL && eap->force_enc != 0)
651 {
652 /* set forced 'fileencoding' */
653 fenc = enc_canonize(eap->cmd + eap->force_enc);
654 if (fenc != NULL)
655 set_string_option_direct((char_u *)"fenc", -1,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +0000656 fenc, OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000657 vim_free(fenc);
658 }
659#endif
660#ifdef FEAT_AUTOCMD
661 apply_autocmds_exarg(EVENT_BUFNEWFILE, sfname, sfname,
662 FALSE, curbuf, eap);
663#endif
664 /* remember the current fileformat */
665 save_file_ff(curbuf);
666
667#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
668 if (aborting()) /* autocmds may abort script processing */
669 return FAIL;
670#endif
671 return OK; /* a new file is not an error */
672 }
673 else
674 {
Bram Moolenaar202795b2005-10-11 20:29:39 +0000675 filemess(curbuf, sfname, (char_u *)(
676# ifdef EFBIG
677 (errno == EFBIG) ? _("[File too big]") :
678# endif
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200679# ifdef EOVERFLOW
680 (errno == EOVERFLOW) ? _("[File too big]") :
681# endif
Bram Moolenaar202795b2005-10-11 20:29:39 +0000682 _("[Permission Denied]")), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000683 curbuf->b_p_ro = TRUE; /* must use "w!" now */
684 }
685 }
686
687 return FAIL;
688 }
689
690 /*
691 * Only set the 'ro' flag for readonly files the first time they are
692 * loaded. Help files always get readonly mode
693 */
694 if ((check_readonly && file_readonly) || curbuf->b_help)
695 curbuf->b_p_ro = TRUE;
696
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000697 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000698 {
Bram Moolenaar690ffc02008-01-04 15:31:21 +0000699 /* Don't change 'eol' if reading from buffer as it will already be
700 * correctly set when reading stdin. */
701 if (!read_buffer)
702 {
703 curbuf->b_p_eol = TRUE;
704 curbuf->b_start_eol = TRUE;
705 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000706#ifdef FEAT_MBYTE
707 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000708 curbuf->b_start_bomb = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000709#endif
710 }
711
712 /* Create a swap file now, so that other Vims are warned that we are
713 * editing this file.
714 * Don't do this for a "nofile" or "nowrite" buffer type. */
715#ifdef FEAT_QUICKFIX
716 if (!bt_dontwrite(curbuf))
717#endif
718 {
719 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000720#ifdef FEAT_AUTOCMD
721 if (!read_stdin && (curbuf != old_curbuf
722 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
723 || (using_b_fname && (old_b_fname != curbuf->b_fname))))
724 {
725 EMSG(_(e_auchangedbuf));
726 if (!read_buffer)
727 close(fd);
728 return FAIL;
729 }
730#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000731#ifdef UNIX
732 /* Set swap file protection bits after creating it. */
Bram Moolenaarf061e0b2009-06-24 15:32:01 +0000733 if (swap_mode > 0 && curbuf->b_ml.ml_mfp != NULL
734 && curbuf->b_ml.ml_mfp->mf_fname != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000735 (void)mch_setperm(curbuf->b_ml.ml_mfp->mf_fname, (long)swap_mode);
736#endif
737 }
738
Bram Moolenaarb815dac2005-12-07 20:59:24 +0000739#if defined(HAS_SWAP_EXISTS_ACTION)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000740 /* If "Quit" selected at ATTENTION dialog, don't load the file */
741 if (swap_exists_action == SEA_QUIT)
742 {
743 if (!read_buffer && !read_stdin)
744 close(fd);
745 return FAIL;
746 }
747#endif
748
749 ++no_wait_return; /* don't wait for return yet */
750
751 /*
752 * Set '[ mark to the line above where the lines go (line 1 if zero).
753 */
754 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
755 curbuf->b_op_start.col = 0;
756
757#ifdef FEAT_AUTOCMD
758 if (!read_buffer)
759 {
760 int m = msg_scroll;
761 int n = msg_scrolled;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000762
763 /*
764 * The file must be closed again, the autocommands may want to change
765 * the file before reading it.
766 */
767 if (!read_stdin)
768 close(fd); /* ignore errors */
769
770 /*
771 * The output from the autocommands should not overwrite anything and
772 * should not be overwritten: Set msg_scroll, restore its value if no
773 * output was done.
774 */
775 msg_scroll = TRUE;
776 if (filtering)
777 apply_autocmds_exarg(EVENT_FILTERREADPRE, NULL, sfname,
778 FALSE, curbuf, eap);
779 else if (read_stdin)
780 apply_autocmds_exarg(EVENT_STDINREADPRE, NULL, sfname,
781 FALSE, curbuf, eap);
782 else if (newfile)
783 apply_autocmds_exarg(EVENT_BUFREADPRE, NULL, sfname,
784 FALSE, curbuf, eap);
785 else
786 apply_autocmds_exarg(EVENT_FILEREADPRE, sfname, sfname,
787 FALSE, NULL, eap);
788 if (msg_scrolled == n)
789 msg_scroll = m;
790
791#ifdef FEAT_EVAL
792 if (aborting()) /* autocmds may abort script processing */
793 {
794 --no_wait_return;
795 msg_scroll = msg_save;
796 curbuf->b_p_ro = TRUE; /* must use "w!" now */
797 return FAIL;
798 }
799#endif
800 /*
801 * Don't allow the autocommands to change the current buffer.
802 * Try to re-open the file.
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000803 *
804 * Don't allow the autocommands to change the buffer name either
805 * (cd for example) if it invalidates fname or sfname.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000806 */
807 if (!read_stdin && (curbuf != old_curbuf
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000808 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
809 || (using_b_fname && (old_b_fname != curbuf->b_fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000810 || (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) < 0))
811 {
812 --no_wait_return;
813 msg_scroll = msg_save;
814 if (fd < 0)
815 EMSG(_("E200: *ReadPre autocommands made the file unreadable"));
816 else
817 EMSG(_("E201: *ReadPre autocommands must not change current buffer"));
818 curbuf->b_p_ro = TRUE; /* must use "w!" now */
819 return FAIL;
820 }
821 }
822#endif /* FEAT_AUTOCMD */
823
824 /* Autocommands may add lines to the file, need to check if it is empty */
825 wasempty = (curbuf->b_ml.ml_flags & ML_EMPTY);
826
827 if (!recoverymode && !filtering && !(flags & READ_DUMMY))
828 {
829 /*
830 * Show the user that we are busy reading the input. Sometimes this
831 * may take a while. When reading from stdin another program may
832 * still be running, don't move the cursor to the last line, unless
833 * always using the GUI.
834 */
835 if (read_stdin)
836 {
837#ifndef ALWAYS_USE_GUI
838 mch_msg(_("Vim: Reading from stdin...\n"));
839#endif
840#ifdef FEAT_GUI
841 /* Also write a message in the GUI window, if there is one. */
842 if (gui.in_use && !gui.dying && !gui.starting)
843 {
844 p = (char_u *)_("Reading from stdin...");
845 gui_write(p, (int)STRLEN(p));
846 }
847#endif
848 }
849 else if (!read_buffer)
850 filemess(curbuf, sfname, (char_u *)"", 0);
851 }
852
853 msg_scroll = FALSE; /* overwrite the file message */
854
855 /*
856 * Set linecnt now, before the "retry" caused by a wrong guess for
857 * fileformat, and after the autocommands, which may change them.
858 */
859 linecnt = curbuf->b_ml.ml_line_count;
860
861#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000862 /* "++bad=" argument. */
863 if (eap != NULL && eap->bad_char != 0)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000864 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000865 bad_char_behavior = eap->bad_char;
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000866 if (set_options)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000867 curbuf->b_bad_char = eap->bad_char;
868 }
869 else
870 curbuf->b_bad_char = 0;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000871
Bram Moolenaar071d4272004-06-13 20:20:40 +0000872 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000873 * Decide which 'encoding' to use or use first.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000874 */
875 if (eap != NULL && eap->force_enc != 0)
876 {
877 fenc = enc_canonize(eap->cmd + eap->force_enc);
878 fenc_alloced = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000879 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000880 }
881 else if (curbuf->b_p_bin)
882 {
883 fenc = (char_u *)""; /* binary: don't convert */
884 fenc_alloced = FALSE;
885 }
886 else if (curbuf->b_help)
887 {
888 char_u firstline[80];
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000889 int fc;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000890
891 /* Help files are either utf-8 or latin1. Try utf-8 first, if this
892 * fails it must be latin1.
893 * Always do this when 'encoding' is "utf-8". Otherwise only do
894 * this when needed to avoid [converted] remarks all the time.
895 * It is needed when the first line contains non-ASCII characters.
896 * That is only in *.??x files. */
897 fenc = (char_u *)"latin1";
898 c = enc_utf8;
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000899 if (!c && !read_stdin)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000900 {
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000901 fc = fname[STRLEN(fname) - 1];
902 if (TOLOWER_ASC(fc) == 'x')
903 {
904 /* Read the first line (and a bit more). Immediately rewind to
905 * the start of the file. If the read() fails "len" is -1. */
Bram Moolenaar540fc6f2010-12-17 16:27:16 +0100906 len = read_eintr(fd, firstline, 80);
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000907 lseek(fd, (off_t)0L, SEEK_SET);
908 for (p = firstline; p < firstline + len; ++p)
909 if (*p >= 0x80)
910 {
911 c = TRUE;
912 break;
913 }
914 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000915 }
916
917 if (c)
918 {
919 fenc_next = fenc;
920 fenc = (char_u *)"utf-8";
921
922 /* When the file is utf-8 but a character doesn't fit in
923 * 'encoding' don't retry. In help text editing utf-8 bytes
924 * doesn't make sense. */
Bram Moolenaarf193fff2006-04-27 00:02:13 +0000925 if (!enc_utf8)
926 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000927 }
928 fenc_alloced = FALSE;
929 }
930 else if (*p_fencs == NUL)
931 {
932 fenc = curbuf->b_p_fenc; /* use format from buffer */
933 fenc_alloced = FALSE;
934 }
935 else
936 {
937 fenc_next = p_fencs; /* try items in 'fileencodings' */
938 fenc = next_fenc(&fenc_next);
939 fenc_alloced = TRUE;
940 }
941#endif
942
943 /*
944 * Jump back here to retry reading the file in different ways.
945 * Reasons to retry:
946 * - encoding conversion failed: try another one from "fenc_next"
947 * - BOM detected and fenc was set, need to setup conversion
948 * - "fileformat" check failed: try another
949 *
950 * Variables set for special retry actions:
951 * "file_rewind" Rewind the file to start reading it again.
952 * "advance_fenc" Advance "fenc" using "fenc_next".
953 * "skip_read" Re-use already read bytes (BOM detected).
954 * "did_iconv" iconv() conversion failed, try 'charconvert'.
955 * "keep_fileformat" Don't reset "fileformat".
956 *
957 * Other status indicators:
958 * "tmpname" When != NULL did conversion with 'charconvert'.
959 * Output file has to be deleted afterwards.
960 * "iconv_fd" When != -1 did conversion with iconv().
961 */
962retry:
963
964 if (file_rewind)
965 {
966 if (read_buffer)
967 {
968 read_buf_lnum = 1;
969 read_buf_col = 0;
970 }
971 else if (read_stdin || lseek(fd, (off_t)0L, SEEK_SET) != 0)
972 {
973 /* Can't rewind the file, give up. */
974 error = TRUE;
975 goto failed;
976 }
977 /* Delete the previously read lines. */
978 while (lnum > from)
979 ml_delete(lnum--, FALSE);
980 file_rewind = FALSE;
981#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000982 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000983 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000984 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000985 curbuf->b_start_bomb = FALSE;
986 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000987 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000988#endif
989 }
990
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200991#ifdef FEAT_CRYPT
992 if (cryptkey != NULL)
993 /* Need to reset the state, but keep the key, don't want to ask for it
994 * again. */
995 crypt_pop_state();
996#endif
997
Bram Moolenaar071d4272004-06-13 20:20:40 +0000998 /*
999 * When retrying with another "fenc" and the first time "fileformat"
1000 * will be reset.
1001 */
1002 if (keep_fileformat)
1003 keep_fileformat = FALSE;
1004 else
1005 {
1006 if (eap != NULL && eap->force_ff != 0)
Bram Moolenaar1c860362008-11-12 15:05:21 +00001007 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001008 fileformat = get_fileformat_force(curbuf, eap);
Bram Moolenaar1c860362008-11-12 15:05:21 +00001009 try_unix = try_dos = try_mac = FALSE;
1010 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001011 else if (curbuf->b_p_bin)
1012 fileformat = EOL_UNIX; /* binary: use Unix format */
1013 else if (*p_ffs == NUL)
1014 fileformat = get_fileformat(curbuf);/* use format from buffer */
1015 else
1016 fileformat = EOL_UNKNOWN; /* detect from file */
1017 }
1018
1019#ifdef FEAT_MBYTE
1020# ifdef USE_ICONV
1021 if (iconv_fd != (iconv_t)-1)
1022 {
1023 /* aborted conversion with iconv(), close the descriptor */
1024 iconv_close(iconv_fd);
1025 iconv_fd = (iconv_t)-1;
1026 }
1027# endif
1028
1029 if (advance_fenc)
1030 {
1031 /*
1032 * Try the next entry in 'fileencodings'.
1033 */
1034 advance_fenc = FALSE;
1035
1036 if (eap != NULL && eap->force_enc != 0)
1037 {
1038 /* Conversion given with "++cc=" wasn't possible, read
1039 * without conversion. */
1040 notconverted = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001041 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001042 if (fenc_alloced)
1043 vim_free(fenc);
1044 fenc = (char_u *)"";
1045 fenc_alloced = FALSE;
1046 }
1047 else
1048 {
1049 if (fenc_alloced)
1050 vim_free(fenc);
1051 if (fenc_next != NULL)
1052 {
1053 fenc = next_fenc(&fenc_next);
1054 fenc_alloced = (fenc_next != NULL);
1055 }
1056 else
1057 {
1058 fenc = (char_u *)"";
1059 fenc_alloced = FALSE;
1060 }
1061 }
1062 if (tmpname != NULL)
1063 {
1064 mch_remove(tmpname); /* delete converted file */
1065 vim_free(tmpname);
1066 tmpname = NULL;
1067 }
1068 }
1069
1070 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001071 * Conversion may be required when the encoding of the file is different
1072 * from 'encoding' or 'encoding' is UTF-16, UCS-2 or UCS-4.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001073 */
1074 fio_flags = 0;
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001075 converted = need_conversion(fenc);
1076 if (converted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001077 {
1078
1079 /* "ucs-bom" means we need to check the first bytes of the file
1080 * for a BOM. */
1081 if (STRCMP(fenc, ENC_UCSBOM) == 0)
1082 fio_flags = FIO_UCSBOM;
1083
1084 /*
1085 * Check if UCS-2/4 or Latin1 to UTF-8 conversion needs to be
1086 * done. This is handled below after read(). Prepare the
1087 * fio_flags to avoid having to parse the string each time.
1088 * Also check for Unicode to Latin1 conversion, because iconv()
1089 * appears not to handle this correctly. This works just like
1090 * conversion to UTF-8 except how the resulting character is put in
1091 * the buffer.
1092 */
1093 else if (enc_utf8 || STRCMP(p_enc, "latin1") == 0)
1094 fio_flags = get_fio_flags(fenc);
1095
1096# ifdef WIN3264
1097 /*
1098 * Conversion from an MS-Windows codepage to UTF-8 or another codepage
1099 * is handled with MultiByteToWideChar().
1100 */
1101 if (fio_flags == 0)
1102 fio_flags = get_win_fio_flags(fenc);
1103# endif
1104
1105# ifdef MACOS_X
1106 /* Conversion from Apple MacRoman to latin1 or UTF-8 */
1107 if (fio_flags == 0)
1108 fio_flags = get_mac_fio_flags(fenc);
1109# endif
1110
1111# ifdef USE_ICONV
1112 /*
1113 * Try using iconv() if we can't convert internally.
1114 */
1115 if (fio_flags == 0
1116# ifdef FEAT_EVAL
1117 && !did_iconv
1118# endif
1119 )
1120 iconv_fd = (iconv_t)my_iconv_open(
1121 enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc);
1122# endif
1123
1124# ifdef FEAT_EVAL
1125 /*
1126 * Use the 'charconvert' expression when conversion is required
1127 * and we can't do it internally or with iconv().
1128 */
1129 if (fio_flags == 0 && !read_stdin && !read_buffer && *p_ccv != NUL
1130# ifdef USE_ICONV
1131 && iconv_fd == (iconv_t)-1
1132# endif
1133 )
1134 {
1135# ifdef USE_ICONV
1136 did_iconv = FALSE;
1137# endif
1138 /* Skip conversion when it's already done (retry for wrong
1139 * "fileformat"). */
1140 if (tmpname == NULL)
1141 {
1142 tmpname = readfile_charconvert(fname, fenc, &fd);
1143 if (tmpname == NULL)
1144 {
1145 /* Conversion failed. Try another one. */
1146 advance_fenc = TRUE;
1147 if (fd < 0)
1148 {
1149 /* Re-opening the original file failed! */
1150 EMSG(_("E202: Conversion made file unreadable!"));
1151 error = TRUE;
1152 goto failed;
1153 }
1154 goto retry;
1155 }
1156 }
1157 }
1158 else
1159# endif
1160 {
1161 if (fio_flags == 0
1162# ifdef USE_ICONV
1163 && iconv_fd == (iconv_t)-1
1164# endif
1165 )
1166 {
1167 /* Conversion wanted but we can't.
1168 * Try the next conversion in 'fileencodings' */
1169 advance_fenc = TRUE;
1170 goto retry;
1171 }
1172 }
1173 }
1174
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001175 /* Set "can_retry" when it's possible to rewind the file and try with
Bram Moolenaar071d4272004-06-13 20:20:40 +00001176 * another "fenc" value. It's FALSE when no other "fenc" to try, reading
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001177 * stdin or fixed at a specific encoding. */
1178 can_retry = (*fenc != NUL && !read_stdin && !keep_dest_enc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001179#endif
1180
1181 if (!skip_read)
1182 {
1183 linerest = 0;
1184 filesize = 0;
1185 skip_count = lines_to_skip;
1186 read_count = lines_to_read;
1187#ifdef FEAT_MBYTE
1188 conv_restlen = 0;
1189#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001190#ifdef FEAT_PERSISTENT_UNDO
Bram Moolenaar59f931e2010-07-24 20:27:03 +02001191 read_undo_file = (newfile && (flags & READ_KEEP_UNDO) == 0
1192 && curbuf->b_ffname != NULL
1193 && curbuf->b_p_udf
1194 && !filtering
1195 && !read_stdin
1196 && !read_buffer);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001197 if (read_undo_file)
1198 sha256_start(&sha_ctx);
1199#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001200 }
1201
1202 while (!error && !got_int)
1203 {
1204 /*
1205 * We allocate as much space for the file as we can get, plus
1206 * space for the old line plus room for one terminating NUL.
1207 * The amount is limited by the fact that read() only can read
1208 * upto max_unsigned characters (and other things).
1209 */
1210#if SIZEOF_INT <= 2
1211 if (linerest >= 0x7ff0)
1212 {
1213 ++split;
1214 *ptr = NL; /* split line by inserting a NL */
1215 size = 1;
1216 }
1217 else
1218#endif
1219 {
1220 if (!skip_read)
1221 {
1222#if SIZEOF_INT > 2
Bram Moolenaar311d9822007-02-27 15:48:28 +00001223# if defined(SSIZE_MAX) && (SSIZE_MAX < 0x10000L)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001224 size = SSIZE_MAX; /* use max I/O size, 52K */
1225# else
1226 size = 0x10000L; /* use buffer >= 64K */
1227# endif
1228#else
1229 size = 0x7ff0L - linerest; /* limit buffer to 32K */
1230#endif
1231
Bram Moolenaarc1e37902006-04-18 21:55:01 +00001232 for ( ; size >= 10; size = (long)((long_u)size >> 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001233 {
1234 if ((new_buffer = lalloc((long_u)(size + linerest + 1),
1235 FALSE)) != NULL)
1236 break;
1237 }
1238 if (new_buffer == NULL)
1239 {
1240 do_outofmem_msg((long_u)(size * 2 + linerest + 1));
1241 error = TRUE;
1242 break;
1243 }
1244 if (linerest) /* copy characters from the previous buffer */
1245 mch_memmove(new_buffer, ptr - linerest, (size_t)linerest);
1246 vim_free(buffer);
1247 buffer = new_buffer;
1248 ptr = buffer + linerest;
1249 line_start = buffer;
1250
1251#ifdef FEAT_MBYTE
1252 /* May need room to translate into.
1253 * For iconv() we don't really know the required space, use a
1254 * factor ICONV_MULT.
1255 * latin1 to utf-8: 1 byte becomes up to 2 bytes
1256 * utf-16 to utf-8: 2 bytes become up to 3 bytes, 4 bytes
1257 * become up to 4 bytes, size must be multiple of 2
1258 * ucs-2 to utf-8: 2 bytes become up to 3 bytes, size must be
1259 * multiple of 2
1260 * ucs-4 to utf-8: 4 bytes become up to 6 bytes, size must be
1261 * multiple of 4 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001262 real_size = (int)size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001263# ifdef USE_ICONV
1264 if (iconv_fd != (iconv_t)-1)
1265 size = size / ICONV_MULT;
1266 else
1267# endif
1268 if (fio_flags & FIO_LATIN1)
1269 size = size / 2;
1270 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1271 size = (size * 2 / 3) & ~1;
1272 else if (fio_flags & FIO_UCS4)
1273 size = (size * 2 / 3) & ~3;
1274 else if (fio_flags == FIO_UCSBOM)
1275 size = size / ICONV_MULT; /* worst case */
1276# ifdef WIN3264
1277 else if (fio_flags & FIO_CODEPAGE)
1278 size = size / ICONV_MULT; /* also worst case */
1279# endif
1280# ifdef MACOS_X
1281 else if (fio_flags & FIO_MACROMAN)
1282 size = size / ICONV_MULT; /* also worst case */
1283# endif
1284#endif
1285
1286#ifdef FEAT_MBYTE
1287 if (conv_restlen > 0)
1288 {
1289 /* Insert unconverted bytes from previous line. */
1290 mch_memmove(ptr, conv_rest, conv_restlen);
1291 ptr += conv_restlen;
1292 size -= conv_restlen;
1293 }
1294#endif
1295
1296 if (read_buffer)
1297 {
1298 /*
1299 * Read bytes from curbuf. Used for converting text read
1300 * from stdin.
1301 */
1302 if (read_buf_lnum > from)
1303 size = 0;
1304 else
1305 {
1306 int n, ni;
1307 long tlen;
1308
1309 tlen = 0;
1310 for (;;)
1311 {
1312 p = ml_get(read_buf_lnum) + read_buf_col;
1313 n = (int)STRLEN(p);
1314 if ((int)tlen + n + 1 > size)
1315 {
1316 /* Filled up to "size", append partial line.
1317 * Change NL to NUL to reverse the effect done
1318 * below. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001319 n = (int)(size - tlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001320 for (ni = 0; ni < n; ++ni)
1321 {
1322 if (p[ni] == NL)
1323 ptr[tlen++] = NUL;
1324 else
1325 ptr[tlen++] = p[ni];
1326 }
1327 read_buf_col += n;
1328 break;
1329 }
1330 else
1331 {
1332 /* Append whole line and new-line. Change NL
1333 * to NUL to reverse the effect done below. */
1334 for (ni = 0; ni < n; ++ni)
1335 {
1336 if (p[ni] == NL)
1337 ptr[tlen++] = NUL;
1338 else
1339 ptr[tlen++] = p[ni];
1340 }
1341 ptr[tlen++] = NL;
1342 read_buf_col = 0;
1343 if (++read_buf_lnum > from)
1344 {
1345 /* When the last line didn't have an
1346 * end-of-line don't add it now either. */
1347 if (!curbuf->b_p_eol)
1348 --tlen;
1349 size = tlen;
1350 break;
1351 }
1352 }
1353 }
1354 }
1355 }
1356 else
1357 {
1358 /*
1359 * Read bytes from the file.
1360 */
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01001361 size = read_eintr(fd, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001362 }
1363
1364 if (size <= 0)
1365 {
1366 if (size < 0) /* read error */
1367 error = TRUE;
1368#ifdef FEAT_MBYTE
1369 else if (conv_restlen > 0)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001370 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001371 /*
1372 * Reached end-of-file but some trailing bytes could
1373 * not be converted. Truncated file?
1374 */
1375
1376 /* When we did a conversion report an error. */
1377 if (fio_flags != 0
1378# ifdef USE_ICONV
1379 || iconv_fd != (iconv_t)-1
1380# endif
1381 )
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001382 {
Bram Moolenaare8d95302013-04-24 16:34:02 +02001383 if (can_retry)
1384 goto rewind_retry;
Bram Moolenaarf453d352008-06-04 17:37:34 +00001385 if (conv_error == 0)
1386 conv_error = curbuf->b_ml.ml_line_count
1387 - linecnt + 1;
1388 }
1389 /* Remember the first linenr with an illegal byte */
1390 else if (illegal_byte == 0)
1391 illegal_byte = curbuf->b_ml.ml_line_count
1392 - linecnt + 1;
1393 if (bad_char_behavior == BAD_DROP)
1394 {
1395 *(ptr - conv_restlen) = NUL;
1396 conv_restlen = 0;
1397 }
1398 else
1399 {
1400 /* Replace the trailing bytes with the replacement
1401 * character if we were converting; if we weren't,
1402 * leave the UTF8 checking code to do it, as it
1403 * works slightly differently. */
1404 if (bad_char_behavior != BAD_KEEP && (fio_flags != 0
1405# ifdef USE_ICONV
1406 || iconv_fd != (iconv_t)-1
1407# endif
1408 ))
1409 {
1410 while (conv_restlen > 0)
1411 {
1412 *(--ptr) = bad_char_behavior;
1413 --conv_restlen;
1414 }
1415 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001416 fio_flags = 0; /* don't convert this */
Bram Moolenaarb21e5842006-04-16 18:30:08 +00001417# ifdef USE_ICONV
1418 if (iconv_fd != (iconv_t)-1)
1419 {
1420 iconv_close(iconv_fd);
1421 iconv_fd = (iconv_t)-1;
1422 }
1423# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001424 }
1425 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001426#endif
1427 }
1428
1429#ifdef FEAT_CRYPT
1430 /*
1431 * At start of file: Check for magic number of encryption.
1432 */
1433 if (filesize == 0)
1434 cryptkey = check_for_cryptkey(cryptkey, ptr, &size,
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001435 &filesize, newfile, sfname,
1436 &did_ask_for_key);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001437 /*
1438 * Decrypt the read bytes.
1439 */
1440 if (cryptkey != NULL && size > 0)
Bram Moolenaar04c9baf2010-06-01 23:37:39 +02001441 crypt_decode(ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001442#endif
1443 }
1444 skip_read = FALSE;
1445
1446#ifdef FEAT_MBYTE
1447 /*
1448 * At start of file (or after crypt magic number): Check for BOM.
1449 * Also check for a BOM for other Unicode encodings, but not after
1450 * converting with 'charconvert' or when a BOM has already been
1451 * found.
1452 */
1453 if ((filesize == 0
1454# ifdef FEAT_CRYPT
Bram Moolenaar40e6a712010-05-16 22:32:54 +02001455 || (filesize == (CRYPT_MAGIC_LEN
Bram Moolenaar80794b12010-06-13 05:20:42 +02001456 + crypt_salt_len[use_crypt_method]
Bram Moolenaar40e6a712010-05-16 22:32:54 +02001457 + crypt_seed_len[use_crypt_method])
1458 && cryptkey != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001459# endif
1460 )
1461 && (fio_flags == FIO_UCSBOM
1462 || (!curbuf->b_p_bomb
1463 && tmpname == NULL
1464 && (*fenc == 'u' || (*fenc == NUL && enc_utf8)))))
1465 {
1466 char_u *ccname;
1467 int blen;
1468
1469 /* no BOM detection in a short file or in binary mode */
1470 if (size < 2 || curbuf->b_p_bin)
1471 ccname = NULL;
1472 else
1473 ccname = check_for_bom(ptr, size, &blen,
1474 fio_flags == FIO_UCSBOM ? FIO_ALL : get_fio_flags(fenc));
1475 if (ccname != NULL)
1476 {
1477 /* Remove BOM from the text */
1478 filesize += blen;
1479 size -= blen;
1480 mch_memmove(ptr, ptr + blen, (size_t)size);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00001481 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001482 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001483 curbuf->b_p_bomb = TRUE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001484 curbuf->b_start_bomb = TRUE;
1485 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001486 }
1487
1488 if (fio_flags == FIO_UCSBOM)
1489 {
1490 if (ccname == NULL)
1491 {
1492 /* No BOM detected: retry with next encoding. */
1493 advance_fenc = TRUE;
1494 }
1495 else
1496 {
1497 /* BOM detected: set "fenc" and jump back */
1498 if (fenc_alloced)
1499 vim_free(fenc);
1500 fenc = ccname;
1501 fenc_alloced = FALSE;
1502 }
1503 /* retry reading without getting new bytes or rewinding */
1504 skip_read = TRUE;
1505 goto retry;
1506 }
1507 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001508
1509 /* Include not converted bytes. */
1510 ptr -= conv_restlen;
1511 size += conv_restlen;
1512 conv_restlen = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001513#endif
1514 /*
1515 * Break here for a read error or end-of-file.
1516 */
1517 if (size <= 0)
1518 break;
1519
1520#ifdef FEAT_MBYTE
1521
Bram Moolenaar071d4272004-06-13 20:20:40 +00001522# ifdef USE_ICONV
1523 if (iconv_fd != (iconv_t)-1)
1524 {
1525 /*
1526 * Attempt conversion of the read bytes to 'encoding' using
1527 * iconv().
1528 */
1529 const char *fromp;
1530 char *top;
1531 size_t from_size;
1532 size_t to_size;
1533
1534 fromp = (char *)ptr;
1535 from_size = size;
1536 ptr += size;
1537 top = (char *)ptr;
1538 to_size = real_size - size;
1539
1540 /*
1541 * If there is conversion error or not enough room try using
Bram Moolenaar19a09a12005-03-04 23:39:37 +00001542 * another conversion. Except for when there is no
1543 * alternative (help files).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001544 */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001545 while ((iconv(iconv_fd, (void *)&fromp, &from_size,
1546 &top, &to_size)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001547 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
1548 || from_size > CONV_RESTLEN)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001549 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001550 if (can_retry)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001551 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001552 if (conv_error == 0)
1553 conv_error = readfile_linenr(linecnt,
1554 ptr, (char_u *)top);
Bram Moolenaar42eeac32005-06-29 22:40:58 +00001555
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001556 /* Deal with a bad byte and continue with the next. */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001557 ++fromp;
1558 --from_size;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001559 if (bad_char_behavior == BAD_KEEP)
1560 {
1561 *top++ = *(fromp - 1);
1562 --to_size;
1563 }
1564 else if (bad_char_behavior != BAD_DROP)
1565 {
1566 *top++ = bad_char_behavior;
1567 --to_size;
1568 }
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001569 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001570
1571 if (from_size > 0)
1572 {
1573 /* Some remaining characters, keep them for the next
1574 * round. */
1575 mch_memmove(conv_rest, (char_u *)fromp, from_size);
1576 conv_restlen = (int)from_size;
1577 }
1578
1579 /* move the linerest to before the converted characters */
1580 line_start = ptr - linerest;
1581 mch_memmove(line_start, buffer, (size_t)linerest);
1582 size = (long)((char_u *)top - ptr);
1583 }
1584# endif
1585
1586# ifdef WIN3264
1587 if (fio_flags & FIO_CODEPAGE)
1588 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001589 char_u *src, *dst;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001590 WCHAR ucs2buf[3];
1591 int ucs2len;
1592 int codepage = FIO_GET_CP(fio_flags);
1593 int bytelen;
1594 int found_bad;
1595 char replstr[2];
1596
Bram Moolenaar071d4272004-06-13 20:20:40 +00001597 /*
1598 * Conversion from an MS-Windows codepage or UTF-8 to UTF-8 or
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001599 * a codepage, using standard MS-Windows functions. This
1600 * requires two steps:
1601 * 1. convert from 'fileencoding' to ucs-2
1602 * 2. convert from ucs-2 to 'encoding'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001603 *
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001604 * Because there may be illegal bytes AND an incomplete byte
1605 * sequence at the end, we may have to do the conversion one
1606 * character at a time to get it right.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001607 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001608
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001609 /* Replacement string for WideCharToMultiByte(). */
1610 if (bad_char_behavior > 0)
1611 replstr[0] = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001612 else
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001613 replstr[0] = '?';
1614 replstr[1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001615
1616 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001617 * Move the bytes to the end of the buffer, so that we have
1618 * room to put the result at the start.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001619 */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001620 src = ptr + real_size - size;
1621 mch_memmove(src, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001622
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001623 /*
1624 * Do the conversion.
1625 */
1626 dst = ptr;
1627 size = size;
1628 while (size > 0)
1629 {
1630 found_bad = FALSE;
1631
1632# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
1633 if (codepage == CP_UTF8)
1634 {
1635 /* Handle CP_UTF8 input ourselves to be able to handle
1636 * trailing bytes properly.
1637 * Get one UTF-8 character from src. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001638 bytelen = (int)utf_ptr2len_len(src, size);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001639 if (bytelen > size)
1640 {
1641 /* Only got some bytes of a character. Normally
1642 * it's put in "conv_rest", but if it's too long
1643 * deal with it as if they were illegal bytes. */
1644 if (bytelen <= CONV_RESTLEN)
1645 break;
1646
1647 /* weird overlong byte sequence */
1648 bytelen = size;
1649 found_bad = TRUE;
1650 }
1651 else
1652 {
Bram Moolenaarc01140a2006-03-24 22:21:52 +00001653 int u8c = utf_ptr2char(src);
1654
Bram Moolenaar86e01082005-12-29 22:45:34 +00001655 if (u8c > 0xffff || (*src >= 0x80 && bytelen == 1))
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001656 found_bad = TRUE;
1657 ucs2buf[0] = u8c;
1658 ucs2len = 1;
1659 }
1660 }
1661 else
1662# endif
1663 {
1664 /* We don't know how long the byte sequence is, try
1665 * from one to three bytes. */
1666 for (bytelen = 1; bytelen <= size && bytelen <= 3;
1667 ++bytelen)
1668 {
1669 ucs2len = MultiByteToWideChar(codepage,
1670 MB_ERR_INVALID_CHARS,
1671 (LPCSTR)src, bytelen,
1672 ucs2buf, 3);
1673 if (ucs2len > 0)
1674 break;
1675 }
1676 if (ucs2len == 0)
1677 {
1678 /* If we have only one byte then it's probably an
1679 * incomplete byte sequence. Otherwise discard
1680 * one byte as a bad character. */
1681 if (size == 1)
1682 break;
1683 found_bad = TRUE;
1684 bytelen = 1;
1685 }
1686 }
1687
1688 if (!found_bad)
1689 {
1690 int i;
1691
1692 /* Convert "ucs2buf[ucs2len]" to 'enc' in "dst". */
1693 if (enc_utf8)
1694 {
1695 /* From UCS-2 to UTF-8. Cannot fail. */
1696 for (i = 0; i < ucs2len; ++i)
1697 dst += utf_char2bytes(ucs2buf[i], dst);
1698 }
1699 else
1700 {
1701 BOOL bad = FALSE;
1702 int dstlen;
1703
1704 /* From UCS-2 to "enc_codepage". If the
1705 * conversion uses the default character "?",
1706 * the data doesn't fit in this encoding. */
1707 dstlen = WideCharToMultiByte(enc_codepage, 0,
1708 (LPCWSTR)ucs2buf, ucs2len,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001709 (LPSTR)dst, (int)(src - dst),
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001710 replstr, &bad);
1711 if (bad)
1712 found_bad = TRUE;
1713 else
1714 dst += dstlen;
1715 }
1716 }
1717
1718 if (found_bad)
1719 {
1720 /* Deal with bytes we can't convert. */
1721 if (can_retry)
1722 goto rewind_retry;
1723 if (conv_error == 0)
1724 conv_error = readfile_linenr(linecnt, ptr, dst);
1725 if (bad_char_behavior != BAD_DROP)
1726 {
1727 if (bad_char_behavior == BAD_KEEP)
1728 {
1729 mch_memmove(dst, src, bytelen);
1730 dst += bytelen;
1731 }
1732 else
1733 *dst++ = bad_char_behavior;
1734 }
1735 }
1736
1737 src += bytelen;
1738 size -= bytelen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001739 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001740
1741 if (size > 0)
1742 {
1743 /* An incomplete byte sequence remaining. */
1744 mch_memmove(conv_rest, src, size);
1745 conv_restlen = size;
1746 }
1747
1748 /* The new size is equal to how much "dst" was advanced. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001749 size = (long)(dst - ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001750 }
1751 else
1752# endif
Bram Moolenaar56718732006-03-15 22:53:57 +00001753# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001754 if (fio_flags & FIO_MACROMAN)
1755 {
1756 /*
1757 * Conversion from Apple MacRoman char encoding to UTF-8 or
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001758 * latin1. This is in os_mac_conv.c.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001759 */
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001760 if (macroman2enc(ptr, &size, real_size) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001761 goto rewind_retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001762 }
1763 else
1764# endif
1765 if (fio_flags != 0)
1766 {
1767 int u8c;
1768 char_u *dest;
1769 char_u *tail = NULL;
1770
1771 /*
1772 * "enc_utf8" set: Convert Unicode or Latin1 to UTF-8.
1773 * "enc_utf8" not set: Convert Unicode to Latin1.
1774 * Go from end to start through the buffer, because the number
1775 * of bytes may increase.
1776 * "dest" points to after where the UTF-8 bytes go, "p" points
1777 * to after the next character to convert.
1778 */
1779 dest = ptr + real_size;
1780 if (fio_flags == FIO_LATIN1 || fio_flags == FIO_UTF8)
1781 {
1782 p = ptr + size;
1783 if (fio_flags == FIO_UTF8)
1784 {
1785 /* Check for a trailing incomplete UTF-8 sequence */
1786 tail = ptr + size - 1;
1787 while (tail > ptr && (*tail & 0xc0) == 0x80)
1788 --tail;
1789 if (tail + utf_byte2len(*tail) <= ptr + size)
1790 tail = NULL;
1791 else
1792 p = tail;
1793 }
1794 }
1795 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1796 {
1797 /* Check for a trailing byte */
1798 p = ptr + (size & ~1);
1799 if (size & 1)
1800 tail = p;
1801 if ((fio_flags & FIO_UTF16) && p > ptr)
1802 {
1803 /* Check for a trailing leading word */
1804 if (fio_flags & FIO_ENDIAN_L)
1805 {
1806 u8c = (*--p << 8);
1807 u8c += *--p;
1808 }
1809 else
1810 {
1811 u8c = *--p;
1812 u8c += (*--p << 8);
1813 }
1814 if (u8c >= 0xd800 && u8c <= 0xdbff)
1815 tail = p;
1816 else
1817 p += 2;
1818 }
1819 }
1820 else /* FIO_UCS4 */
1821 {
1822 /* Check for trailing 1, 2 or 3 bytes */
1823 p = ptr + (size & ~3);
1824 if (size & 3)
1825 tail = p;
1826 }
1827
1828 /* If there is a trailing incomplete sequence move it to
1829 * conv_rest[]. */
1830 if (tail != NULL)
1831 {
1832 conv_restlen = (int)((ptr + size) - tail);
1833 mch_memmove(conv_rest, (char_u *)tail, conv_restlen);
1834 size -= conv_restlen;
1835 }
1836
1837
1838 while (p > ptr)
1839 {
1840 if (fio_flags & FIO_LATIN1)
1841 u8c = *--p;
1842 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1843 {
1844 if (fio_flags & FIO_ENDIAN_L)
1845 {
1846 u8c = (*--p << 8);
1847 u8c += *--p;
1848 }
1849 else
1850 {
1851 u8c = *--p;
1852 u8c += (*--p << 8);
1853 }
1854 if ((fio_flags & FIO_UTF16)
1855 && u8c >= 0xdc00 && u8c <= 0xdfff)
1856 {
1857 int u16c;
1858
1859 if (p == ptr)
1860 {
1861 /* Missing leading word. */
1862 if (can_retry)
1863 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001864 if (conv_error == 0)
1865 conv_error = readfile_linenr(linecnt,
1866 ptr, p);
1867 if (bad_char_behavior == BAD_DROP)
1868 continue;
1869 if (bad_char_behavior != BAD_KEEP)
1870 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001871 }
1872
1873 /* found second word of double-word, get the first
1874 * word and compute the resulting character */
1875 if (fio_flags & FIO_ENDIAN_L)
1876 {
1877 u16c = (*--p << 8);
1878 u16c += *--p;
1879 }
1880 else
1881 {
1882 u16c = *--p;
1883 u16c += (*--p << 8);
1884 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001885 u8c = 0x10000 + ((u16c & 0x3ff) << 10)
1886 + (u8c & 0x3ff);
1887
Bram Moolenaar071d4272004-06-13 20:20:40 +00001888 /* Check if the word is indeed a leading word. */
1889 if (u16c < 0xd800 || u16c > 0xdbff)
1890 {
1891 if (can_retry)
1892 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001893 if (conv_error == 0)
1894 conv_error = readfile_linenr(linecnt,
1895 ptr, p);
1896 if (bad_char_behavior == BAD_DROP)
1897 continue;
1898 if (bad_char_behavior != BAD_KEEP)
1899 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001900 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001901 }
1902 }
1903 else if (fio_flags & FIO_UCS4)
1904 {
1905 if (fio_flags & FIO_ENDIAN_L)
1906 {
1907 u8c = (*--p << 24);
1908 u8c += (*--p << 16);
1909 u8c += (*--p << 8);
1910 u8c += *--p;
1911 }
1912 else /* big endian */
1913 {
1914 u8c = *--p;
1915 u8c += (*--p << 8);
1916 u8c += (*--p << 16);
1917 u8c += (*--p << 24);
1918 }
1919 }
1920 else /* UTF-8 */
1921 {
1922 if (*--p < 0x80)
1923 u8c = *p;
1924 else
1925 {
1926 len = utf_head_off(ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001927 p -= len;
1928 u8c = utf_ptr2char(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001929 if (len == 0)
1930 {
1931 /* Not a valid UTF-8 character, retry with
1932 * another fenc when possible, otherwise just
1933 * report the error. */
1934 if (can_retry)
1935 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001936 if (conv_error == 0)
1937 conv_error = readfile_linenr(linecnt,
1938 ptr, p);
1939 if (bad_char_behavior == BAD_DROP)
1940 continue;
1941 if (bad_char_behavior != BAD_KEEP)
1942 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001943 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001944 }
1945 }
1946 if (enc_utf8) /* produce UTF-8 */
1947 {
1948 dest -= utf_char2len(u8c);
1949 (void)utf_char2bytes(u8c, dest);
1950 }
1951 else /* produce Latin1 */
1952 {
1953 --dest;
1954 if (u8c >= 0x100)
1955 {
1956 /* character doesn't fit in latin1, retry with
1957 * another fenc when possible, otherwise just
1958 * report the error. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001959 if (can_retry)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001960 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001961 if (conv_error == 0)
1962 conv_error = readfile_linenr(linecnt, ptr, p);
1963 if (bad_char_behavior == BAD_DROP)
1964 ++dest;
1965 else if (bad_char_behavior == BAD_KEEP)
1966 *dest = u8c;
1967 else if (eap != NULL && eap->bad_char != 0)
1968 *dest = bad_char_behavior;
1969 else
1970 *dest = 0xBF;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001971 }
1972 else
1973 *dest = u8c;
1974 }
1975 }
1976
1977 /* move the linerest to before the converted characters */
1978 line_start = dest - linerest;
1979 mch_memmove(line_start, buffer, (size_t)linerest);
1980 size = (long)((ptr + real_size) - dest);
1981 ptr = dest;
1982 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001983 else if (enc_utf8 && !curbuf->b_p_bin)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001984 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001985 int incomplete_tail = FALSE;
1986
1987 /* Reading UTF-8: Check if the bytes are valid UTF-8. */
1988 for (p = ptr; ; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001989 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001990 int todo = (int)((ptr + size) - p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001991 int l;
1992
1993 if (todo <= 0)
1994 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001995 if (*p >= 0x80)
1996 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001997 /* A length of 1 means it's an illegal byte. Accept
1998 * an incomplete character at the end though, the next
1999 * read() will get the next bytes, we'll check it
2000 * then. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002001 l = utf_ptr2len_len(p, todo);
Bram Moolenaarf453d352008-06-04 17:37:34 +00002002 if (l > todo && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002003 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002004 /* Avoid retrying with a different encoding when
2005 * a truncated file is more likely, or attempting
2006 * to read the rest of an incomplete sequence when
2007 * we have already done so. */
2008 if (p > ptr || filesize > 0)
2009 incomplete_tail = TRUE;
2010 /* Incomplete byte sequence, move it to conv_rest[]
2011 * and try to read the rest of it, unless we've
2012 * already done so. */
2013 if (p > ptr)
2014 {
2015 conv_restlen = todo;
2016 mch_memmove(conv_rest, p, conv_restlen);
2017 size -= conv_restlen;
2018 break;
2019 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002020 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002021 if (l == 1 || l > todo)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002022 {
2023 /* Illegal byte. If we can try another encoding
Bram Moolenaarf453d352008-06-04 17:37:34 +00002024 * do that, unless at EOF where a truncated
2025 * file is more likely than a conversion error. */
2026 if (can_retry && !incomplete_tail)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002027 break;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002028# ifdef USE_ICONV
2029 /* When we did a conversion report an error. */
2030 if (iconv_fd != (iconv_t)-1 && conv_error == 0)
2031 conv_error = readfile_linenr(linecnt, ptr, p);
2032# endif
Bram Moolenaarf453d352008-06-04 17:37:34 +00002033 /* Remember the first linenr with an illegal byte */
2034 if (conv_error == 0 && illegal_byte == 0)
2035 illegal_byte = readfile_linenr(linecnt, ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002036
2037 /* Drop, keep or replace the bad byte. */
2038 if (bad_char_behavior == BAD_DROP)
2039 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002040 mch_memmove(p, p + 1, todo - 1);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002041 --p;
2042 --size;
2043 }
2044 else if (bad_char_behavior != BAD_KEEP)
2045 *p = bad_char_behavior;
2046 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002047 else
2048 p += l - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002049 }
2050 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002051 if (p < ptr + size && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002052 {
2053 /* Detected a UTF-8 error. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002054rewind_retry:
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002055 /* Retry reading with another conversion. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002056# if defined(FEAT_EVAL) && defined(USE_ICONV)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002057 if (*p_ccv != NUL && iconv_fd != (iconv_t)-1)
2058 /* iconv() failed, try 'charconvert' */
2059 did_iconv = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002060 else
2061# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002062 /* use next item from 'fileencodings' */
2063 advance_fenc = TRUE;
2064 file_rewind = TRUE;
2065 goto retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002066 }
2067 }
2068#endif
2069
2070 /* count the number of characters (after conversion!) */
2071 filesize += size;
2072
2073 /*
2074 * when reading the first part of a file: guess EOL type
2075 */
2076 if (fileformat == EOL_UNKNOWN)
2077 {
2078 /* First try finding a NL, for Dos and Unix */
2079 if (try_dos || try_unix)
2080 {
2081 for (p = ptr; p < ptr + size; ++p)
2082 {
2083 if (*p == NL)
2084 {
2085 if (!try_unix
2086 || (try_dos && p > ptr && p[-1] == CAR))
2087 fileformat = EOL_DOS;
2088 else
2089 fileformat = EOL_UNIX;
2090 break;
2091 }
2092 }
2093
2094 /* Don't give in to EOL_UNIX if EOL_MAC is more likely */
2095 if (fileformat == EOL_UNIX && try_mac)
2096 {
2097 /* Need to reset the counters when retrying fenc. */
2098 try_mac = 1;
2099 try_unix = 1;
2100 for (; p >= ptr && *p != CAR; p--)
2101 ;
2102 if (p >= ptr)
2103 {
2104 for (p = ptr; p < ptr + size; ++p)
2105 {
2106 if (*p == NL)
2107 try_unix++;
2108 else if (*p == CAR)
2109 try_mac++;
2110 }
2111 if (try_mac > try_unix)
2112 fileformat = EOL_MAC;
2113 }
2114 }
2115 }
2116
2117 /* No NL found: may use Mac format */
2118 if (fileformat == EOL_UNKNOWN && try_mac)
2119 fileformat = EOL_MAC;
2120
2121 /* Still nothing found? Use first format in 'ffs' */
2122 if (fileformat == EOL_UNKNOWN)
2123 fileformat = default_fileformat();
2124
2125 /* if editing a new file: may set p_tx and p_ff */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002126 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002127 set_fileformat(fileformat, OPT_LOCAL);
2128 }
2129 }
2130
2131 /*
2132 * This loop is executed once for every character read.
2133 * Keep it fast!
2134 */
2135 if (fileformat == EOL_MAC)
2136 {
2137 --ptr;
2138 while (++ptr, --size >= 0)
2139 {
2140 /* catch most common case first */
2141 if ((c = *ptr) != NUL && c != CAR && c != NL)
2142 continue;
2143 if (c == NUL)
2144 *ptr = NL; /* NULs are replaced by newlines! */
2145 else if (c == NL)
2146 *ptr = CAR; /* NLs are replaced by CRs! */
2147 else
2148 {
2149 if (skip_count == 0)
2150 {
2151 *ptr = NUL; /* end of line */
2152 len = (colnr_T) (ptr - line_start + 1);
2153 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2154 {
2155 error = TRUE;
2156 break;
2157 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002158#ifdef FEAT_PERSISTENT_UNDO
2159 if (read_undo_file)
2160 sha256_update(&sha_ctx, line_start, len);
2161#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002162 ++lnum;
2163 if (--read_count == 0)
2164 {
2165 error = TRUE; /* break loop */
2166 line_start = ptr; /* nothing left to write */
2167 break;
2168 }
2169 }
2170 else
2171 --skip_count;
2172 line_start = ptr + 1;
2173 }
2174 }
2175 }
2176 else
2177 {
2178 --ptr;
2179 while (++ptr, --size >= 0)
2180 {
2181 if ((c = *ptr) != NUL && c != NL) /* catch most common case */
2182 continue;
2183 if (c == NUL)
2184 *ptr = NL; /* NULs are replaced by newlines! */
2185 else
2186 {
2187 if (skip_count == 0)
2188 {
2189 *ptr = NUL; /* end of line */
2190 len = (colnr_T)(ptr - line_start + 1);
2191 if (fileformat == EOL_DOS)
2192 {
2193 if (ptr[-1] == CAR) /* remove CR */
2194 {
2195 ptr[-1] = NUL;
2196 --len;
2197 }
2198 /*
2199 * Reading in Dos format, but no CR-LF found!
2200 * When 'fileformats' includes "unix", delete all
2201 * the lines read so far and start all over again.
2202 * Otherwise give an error message later.
2203 */
2204 else if (ff_error != EOL_DOS)
2205 {
2206 if ( try_unix
2207 && !read_stdin
2208 && (read_buffer
2209 || lseek(fd, (off_t)0L, SEEK_SET) == 0))
2210 {
2211 fileformat = EOL_UNIX;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002212 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002213 set_fileformat(EOL_UNIX, OPT_LOCAL);
2214 file_rewind = TRUE;
2215 keep_fileformat = TRUE;
2216 goto retry;
2217 }
2218 ff_error = EOL_DOS;
2219 }
2220 }
2221 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2222 {
2223 error = TRUE;
2224 break;
2225 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002226#ifdef FEAT_PERSISTENT_UNDO
2227 if (read_undo_file)
2228 sha256_update(&sha_ctx, line_start, len);
2229#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002230 ++lnum;
2231 if (--read_count == 0)
2232 {
2233 error = TRUE; /* break loop */
2234 line_start = ptr; /* nothing left to write */
2235 break;
2236 }
2237 }
2238 else
2239 --skip_count;
2240 line_start = ptr + 1;
2241 }
2242 }
2243 }
2244 linerest = (long)(ptr - line_start);
2245 ui_breakcheck();
2246 }
2247
2248failed:
2249 /* not an error, max. number of lines reached */
2250 if (error && read_count == 0)
2251 error = FALSE;
2252
2253 /*
2254 * If we get EOF in the middle of a line, note the fact and
2255 * complete the line ourselves.
2256 * In Dos format ignore a trailing CTRL-Z, unless 'binary' set.
2257 */
2258 if (!error
2259 && !got_int
2260 && linerest != 0
2261 && !(!curbuf->b_p_bin
2262 && fileformat == EOL_DOS
2263 && *line_start == Ctrl_Z
2264 && ptr == line_start + 1))
2265 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002266 /* remember for when writing */
2267 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002268 curbuf->b_p_eol = FALSE;
2269 *ptr = NUL;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002270 len = (colnr_T)(ptr - line_start + 1);
2271 if (ml_append(lnum, line_start, len, newfile) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002272 error = TRUE;
2273 else
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002274 {
2275#ifdef FEAT_PERSISTENT_UNDO
2276 if (read_undo_file)
2277 sha256_update(&sha_ctx, line_start, len);
2278#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002279 read_no_eol_lnum = ++lnum;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002280 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002281 }
2282
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002283 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002284 save_file_ff(curbuf); /* remember the current file format */
2285
2286#ifdef FEAT_CRYPT
Bram Moolenaar4cf35c22011-02-25 16:52:17 +01002287 crypt_method_used = use_crypt_method;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002288 if (cryptkey != NULL)
2289 {
2290 crypt_pop_state();
2291 if (cryptkey != curbuf->b_p_key)
2292 free_crypt_key(cryptkey);
2293 /* don't set cryptkey to NULL, it's used below as a flag that
2294 * encryption was used */
2295 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002296#endif
2297
2298#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002299 /* If editing a new file: set 'fenc' for the current buffer.
2300 * Also for ":read ++edit file". */
2301 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002302 set_string_option_direct((char_u *)"fenc", -1, fenc,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00002303 OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002304 if (fenc_alloced)
2305 vim_free(fenc);
2306# ifdef USE_ICONV
2307 if (iconv_fd != (iconv_t)-1)
2308 {
2309 iconv_close(iconv_fd);
2310 iconv_fd = (iconv_t)-1;
2311 }
2312# endif
2313#endif
2314
2315 if (!read_buffer && !read_stdin)
2316 close(fd); /* errors are ignored */
Bram Moolenaarf05da212009-11-17 16:13:15 +00002317#ifdef HAVE_FD_CLOEXEC
2318 else
2319 {
2320 int fdflags = fcntl(fd, F_GETFD);
2321 if (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0)
2322 fcntl(fd, F_SETFD, fdflags | FD_CLOEXEC);
2323 }
2324#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002325 vim_free(buffer);
2326
2327#ifdef HAVE_DUP
2328 if (read_stdin)
2329 {
2330 /* Use stderr for stdin, makes shell commands work. */
2331 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00002332 ignored = dup(2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002333 }
2334#endif
2335
2336#ifdef FEAT_MBYTE
2337 if (tmpname != NULL)
2338 {
2339 mch_remove(tmpname); /* delete converted file */
2340 vim_free(tmpname);
2341 }
2342#endif
2343 --no_wait_return; /* may wait for return now */
2344
2345 /*
2346 * In recovery mode everything but autocommands is skipped.
2347 */
2348 if (!recoverymode)
2349 {
2350 /* need to delete the last line, which comes from the empty buffer */
2351 if (newfile && wasempty && !(curbuf->b_ml.ml_flags & ML_EMPTY))
2352 {
2353#ifdef FEAT_NETBEANS_INTG
2354 netbeansFireChanges = 0;
2355#endif
2356 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
2357#ifdef FEAT_NETBEANS_INTG
2358 netbeansFireChanges = 1;
2359#endif
2360 --linecnt;
2361 }
2362 linecnt = curbuf->b_ml.ml_line_count - linecnt;
2363 if (filesize == 0)
2364 linecnt = 0;
2365 if (newfile || read_buffer)
Bram Moolenaar7263a772007-05-10 17:35:54 +00002366 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002367 redraw_curbuf_later(NOT_VALID);
Bram Moolenaar7263a772007-05-10 17:35:54 +00002368#ifdef FEAT_DIFF
2369 /* After reading the text into the buffer the diff info needs to
2370 * be updated. */
2371 diff_invalidate(curbuf);
2372#endif
2373#ifdef FEAT_FOLDING
2374 /* All folds in the window are invalid now. Mark them for update
2375 * before triggering autocommands. */
2376 foldUpdateAll(curwin);
2377#endif
2378 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002379 else if (linecnt) /* appended at least one line */
2380 appended_lines_mark(from, linecnt);
2381
Bram Moolenaar071d4272004-06-13 20:20:40 +00002382#ifndef ALWAYS_USE_GUI
2383 /*
2384 * If we were reading from the same terminal as where messages go,
2385 * the screen will have been messed up.
2386 * Switch on raw mode now and clear the screen.
2387 */
2388 if (read_stdin)
2389 {
2390 settmode(TMODE_RAW); /* set to raw mode */
2391 starttermcap();
2392 screenclear();
2393 }
2394#endif
2395
2396 if (got_int)
2397 {
2398 if (!(flags & READ_DUMMY))
2399 {
2400 filemess(curbuf, sfname, (char_u *)_(e_interr), 0);
2401 if (newfile)
2402 curbuf->b_p_ro = TRUE; /* must use "w!" now */
2403 }
2404 msg_scroll = msg_save;
2405#ifdef FEAT_VIMINFO
2406 check_marks_read();
2407#endif
2408 return OK; /* an interrupt isn't really an error */
2409 }
2410
2411 if (!filtering && !(flags & READ_DUMMY))
2412 {
2413 msg_add_fname(curbuf, sfname); /* fname in IObuff with quotes */
2414 c = FALSE;
2415
2416#ifdef UNIX
2417# ifdef S_ISFIFO
2418 if (S_ISFIFO(perm)) /* fifo or socket */
2419 {
2420 STRCAT(IObuff, _("[fifo/socket]"));
2421 c = TRUE;
2422 }
2423# else
2424# ifdef S_IFIFO
2425 if ((perm & S_IFMT) == S_IFIFO) /* fifo */
2426 {
2427 STRCAT(IObuff, _("[fifo]"));
2428 c = TRUE;
2429 }
2430# endif
2431# ifdef S_IFSOCK
2432 if ((perm & S_IFMT) == S_IFSOCK) /* or socket */
2433 {
2434 STRCAT(IObuff, _("[socket]"));
2435 c = TRUE;
2436 }
2437# endif
2438# endif
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002439# ifdef OPEN_CHR_FILES
2440 if (S_ISCHR(perm)) /* or character special */
2441 {
2442 STRCAT(IObuff, _("[character special]"));
2443 c = TRUE;
2444 }
2445# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002446#endif
2447 if (curbuf->b_p_ro)
2448 {
2449 STRCAT(IObuff, shortmess(SHM_RO) ? _("[RO]") : _("[readonly]"));
2450 c = TRUE;
2451 }
2452 if (read_no_eol_lnum)
2453 {
2454 msg_add_eol();
2455 c = TRUE;
2456 }
2457 if (ff_error == EOL_DOS)
2458 {
2459 STRCAT(IObuff, _("[CR missing]"));
2460 c = TRUE;
2461 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002462 if (split)
2463 {
2464 STRCAT(IObuff, _("[long lines split]"));
2465 c = TRUE;
2466 }
2467#ifdef FEAT_MBYTE
2468 if (notconverted)
2469 {
2470 STRCAT(IObuff, _("[NOT converted]"));
2471 c = TRUE;
2472 }
2473 else if (converted)
2474 {
2475 STRCAT(IObuff, _("[converted]"));
2476 c = TRUE;
2477 }
2478#endif
2479#ifdef FEAT_CRYPT
2480 if (cryptkey != NULL)
2481 {
Bram Moolenaar4cf35c22011-02-25 16:52:17 +01002482 if (crypt_method_used == 1)
2483 STRCAT(IObuff, _("[blowfish]"));
2484 else
2485 STRCAT(IObuff, _("[crypted]"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002486 c = TRUE;
2487 }
2488#endif
2489#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002490 if (conv_error != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002491 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002492 sprintf((char *)IObuff + STRLEN(IObuff),
2493 _("[CONVERSION ERROR in line %ld]"), (long)conv_error);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002494 c = TRUE;
2495 }
2496 else if (illegal_byte > 0)
2497 {
2498 sprintf((char *)IObuff + STRLEN(IObuff),
2499 _("[ILLEGAL BYTE in line %ld]"), (long)illegal_byte);
2500 c = TRUE;
2501 }
2502 else
2503#endif
2504 if (error)
2505 {
2506 STRCAT(IObuff, _("[READ ERRORS]"));
2507 c = TRUE;
2508 }
2509 if (msg_add_fileformat(fileformat))
2510 c = TRUE;
2511#ifdef FEAT_CRYPT
2512 if (cryptkey != NULL)
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002513 msg_add_lines(c, (long)linecnt, filesize
Bram Moolenaar80794b12010-06-13 05:20:42 +02002514 - CRYPT_MAGIC_LEN
2515 - crypt_salt_len[use_crypt_method]
2516 - crypt_seed_len[use_crypt_method]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002517 else
2518#endif
2519 msg_add_lines(c, (long)linecnt, filesize);
2520
2521 vim_free(keep_msg);
2522 keep_msg = NULL;
2523 msg_scrolled_ign = TRUE;
2524#ifdef ALWAYS_USE_GUI
2525 /* Don't show the message when reading stdin, it would end up in a
2526 * message box (which might be shown when exiting!) */
2527 if (read_stdin || read_buffer)
2528 p = msg_may_trunc(FALSE, IObuff);
2529 else
2530#endif
2531 p = msg_trunc_attr(IObuff, FALSE, 0);
2532 if (read_stdin || read_buffer || restart_edit != 0
Bram Moolenaar1c7715d2005-10-03 22:02:18 +00002533 || (msg_scrolled != 0 && !need_wait_return))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002534 /* Need to repeat the message after redrawing when:
2535 * - When reading from stdin (the screen will be cleared next).
2536 * - When restart_edit is set (otherwise there will be a delay
2537 * before redrawing).
2538 * - When the screen was scrolled but there is no wait-return
2539 * prompt. */
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002540 set_keep_msg(p, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002541 msg_scrolled_ign = FALSE;
2542 }
2543
2544 /* with errors writing the file requires ":w!" */
2545 if (newfile && (error
2546#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002547 || conv_error != 0
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002548 || (illegal_byte > 0 && bad_char_behavior != BAD_KEEP)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002549#endif
2550 ))
2551 curbuf->b_p_ro = TRUE;
2552
2553 u_clearline(); /* cannot use "U" command after adding lines */
2554
2555 /*
2556 * In Ex mode: cursor at last new line.
2557 * Otherwise: cursor at first new line.
2558 */
2559 if (exmode_active)
2560 curwin->w_cursor.lnum = from + linecnt;
2561 else
2562 curwin->w_cursor.lnum = from + 1;
2563 check_cursor_lnum();
2564 beginline(BL_WHITE | BL_FIX); /* on first non-blank */
2565
2566 /*
2567 * Set '[ and '] marks to the newly read lines.
2568 */
2569 curbuf->b_op_start.lnum = from + 1;
2570 curbuf->b_op_start.col = 0;
2571 curbuf->b_op_end.lnum = from + linecnt;
2572 curbuf->b_op_end.col = 0;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002573
2574#ifdef WIN32
2575 /*
2576 * Work around a weird problem: When a file has two links (only
2577 * possible on NTFS) and we write through one link, then stat() it
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00002578 * through the other link, the timestamp information may be wrong.
Bram Moolenaar03f48552006-02-28 23:52:23 +00002579 * It's correct again after reading the file, thus reset the timestamp
2580 * here.
2581 */
2582 if (newfile && !read_stdin && !read_buffer
2583 && mch_stat((char *)fname, &st) >= 0)
2584 {
2585 buf_store_time(curbuf, &st, fname);
2586 curbuf->b_mtime_read = curbuf->b_mtime;
2587 }
2588#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002589 }
2590 msg_scroll = msg_save;
2591
2592#ifdef FEAT_VIMINFO
2593 /*
2594 * Get the marks before executing autocommands, so they can be used there.
2595 */
2596 check_marks_read();
2597#endif
2598
Bram Moolenaar071d4272004-06-13 20:20:40 +00002599 /*
2600 * Trick: We remember if the last line of the read didn't have
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002601 * an eol even when 'binary' is off, for when writing it again with
2602 * 'binary' on. This is required for
Bram Moolenaar071d4272004-06-13 20:20:40 +00002603 * ":autocmd FileReadPost *.gz set bin|'[,']!gunzip" to work.
2604 */
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002605 curbuf->b_no_eol_lnum = read_no_eol_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002606
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02002607 /* When reloading a buffer put the cursor at the first line that is
2608 * different. */
2609 if (flags & READ_KEEP_UNDO)
2610 u_find_first_changed();
2611
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002612#ifdef FEAT_PERSISTENT_UNDO
2613 /*
2614 * When opening a new file locate undo info and read it.
2615 */
2616 if (read_undo_file)
2617 {
2618 char_u hash[UNDO_HASH_SIZE];
2619
2620 sha256_finish(&sha_ctx, hash);
Bram Moolenaar6ed8ed82010-05-30 20:40:11 +02002621 u_read_undo(NULL, hash, fname);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002622 }
2623#endif
2624
Bram Moolenaardf177f62005-02-22 08:39:57 +00002625#ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00002626 if (!read_stdin && !read_buffer)
2627 {
2628 int m = msg_scroll;
2629 int n = msg_scrolled;
2630
2631 /* Save the fileformat now, otherwise the buffer will be considered
2632 * modified if the format/encoding was automatically detected. */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002633 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002634 save_file_ff(curbuf);
2635
2636 /*
2637 * The output from the autocommands should not overwrite anything and
2638 * should not be overwritten: Set msg_scroll, restore its value if no
2639 * output was done.
2640 */
2641 msg_scroll = TRUE;
2642 if (filtering)
2643 apply_autocmds_exarg(EVENT_FILTERREADPOST, NULL, sfname,
2644 FALSE, curbuf, eap);
2645 else if (newfile)
2646 apply_autocmds_exarg(EVENT_BUFREADPOST, NULL, sfname,
2647 FALSE, curbuf, eap);
2648 else
2649 apply_autocmds_exarg(EVENT_FILEREADPOST, sfname, sfname,
2650 FALSE, NULL, eap);
2651 if (msg_scrolled == n)
2652 msg_scroll = m;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002653# ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002654 if (aborting()) /* autocmds may abort script processing */
2655 return FAIL;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002656# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002657 }
2658#endif
2659
2660 if (recoverymode && error)
2661 return FAIL;
2662 return OK;
2663}
2664
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002665#ifdef OPEN_CHR_FILES
2666/*
2667 * Returns TRUE if the file name argument is of the form "/dev/fd/\d\+",
2668 * which is the name of files used for process substitution output by
2669 * some shells on some operating systems, e.g., bash on SunOS.
2670 * Do not accept "/dev/fd/[012]", opening these may hang Vim.
2671 */
2672 static int
2673is_dev_fd_file(fname)
2674 char_u *fname;
2675{
2676 return (STRNCMP(fname, "/dev/fd/", 8) == 0
2677 && VIM_ISDIGIT(fname[8])
2678 && *skipdigits(fname + 9) == NUL
2679 && (fname[9] != NUL
2680 || (fname[8] != '0' && fname[8] != '1' && fname[8] != '2')));
2681}
2682#endif
2683
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002684#ifdef FEAT_MBYTE
2685
2686/*
2687 * From the current line count and characters read after that, estimate the
2688 * line number where we are now.
2689 * Used for error messages that include a line number.
2690 */
2691 static linenr_T
2692readfile_linenr(linecnt, p, endp)
2693 linenr_T linecnt; /* line count before reading more bytes */
2694 char_u *p; /* start of more bytes read */
2695 char_u *endp; /* end of more bytes read */
2696{
2697 char_u *s;
2698 linenr_T lnum;
2699
2700 lnum = curbuf->b_ml.ml_line_count - linecnt + 1;
2701 for (s = p; s < endp; ++s)
2702 if (*s == '\n')
2703 ++lnum;
2704 return lnum;
2705}
2706#endif
2707
Bram Moolenaar071d4272004-06-13 20:20:40 +00002708/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00002709 * Fill "*eap" to force the 'fileencoding', 'fileformat' and 'binary to be
2710 * equal to the buffer "buf". Used for calling readfile().
Bram Moolenaar071d4272004-06-13 20:20:40 +00002711 * Returns OK or FAIL.
2712 */
2713 int
2714prep_exarg(eap, buf)
2715 exarg_T *eap;
2716 buf_T *buf;
2717{
2718 eap->cmd = alloc((unsigned)(STRLEN(buf->b_p_ff)
2719#ifdef FEAT_MBYTE
2720 + STRLEN(buf->b_p_fenc)
2721#endif
2722 + 15));
2723 if (eap->cmd == NULL)
2724 return FAIL;
2725
2726#ifdef FEAT_MBYTE
2727 sprintf((char *)eap->cmd, "e ++ff=%s ++enc=%s", buf->b_p_ff, buf->b_p_fenc);
2728 eap->force_enc = 14 + (int)STRLEN(buf->b_p_ff);
Bram Moolenaar195d6352005-12-19 22:08:24 +00002729 eap->bad_char = buf->b_bad_char;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002730#else
2731 sprintf((char *)eap->cmd, "e ++ff=%s", buf->b_p_ff);
2732#endif
2733 eap->force_ff = 7;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002734
2735 eap->force_bin = buf->b_p_bin ? FORCE_BIN : FORCE_NOBIN;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002736 eap->read_edit = FALSE;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002737 eap->forceit = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002738 return OK;
2739}
2740
2741#ifdef FEAT_MBYTE
2742/*
2743 * Find next fileencoding to use from 'fileencodings'.
2744 * "pp" points to fenc_next. It's advanced to the next item.
2745 * When there are no more items, an empty string is returned and *pp is set to
2746 * NULL.
2747 * When *pp is not set to NULL, the result is in allocated memory.
2748 */
2749 static char_u *
2750next_fenc(pp)
2751 char_u **pp;
2752{
2753 char_u *p;
2754 char_u *r;
2755
2756 if (**pp == NUL)
2757 {
2758 *pp = NULL;
2759 return (char_u *)"";
2760 }
2761 p = vim_strchr(*pp, ',');
2762 if (p == NULL)
2763 {
2764 r = enc_canonize(*pp);
2765 *pp += STRLEN(*pp);
2766 }
2767 else
2768 {
2769 r = vim_strnsave(*pp, (int)(p - *pp));
2770 *pp = p + 1;
2771 if (r != NULL)
2772 {
2773 p = enc_canonize(r);
2774 vim_free(r);
2775 r = p;
2776 }
2777 }
2778 if (r == NULL) /* out of memory */
2779 {
2780 r = (char_u *)"";
2781 *pp = NULL;
2782 }
2783 return r;
2784}
2785
2786# ifdef FEAT_EVAL
2787/*
2788 * Convert a file with the 'charconvert' expression.
2789 * This closes the file which is to be read, converts it and opens the
2790 * resulting file for reading.
2791 * Returns name of the resulting converted file (the caller should delete it
2792 * after reading it).
2793 * Returns NULL if the conversion failed ("*fdp" is not set) .
2794 */
2795 static char_u *
2796readfile_charconvert(fname, fenc, fdp)
2797 char_u *fname; /* name of input file */
2798 char_u *fenc; /* converted from */
2799 int *fdp; /* in/out: file descriptor of file */
2800{
2801 char_u *tmpname;
2802 char_u *errmsg = NULL;
2803
2804 tmpname = vim_tempname('r');
2805 if (tmpname == NULL)
2806 errmsg = (char_u *)_("Can't find temp file for conversion");
2807 else
2808 {
2809 close(*fdp); /* close the input file, ignore errors */
2810 *fdp = -1;
2811 if (eval_charconvert(fenc, enc_utf8 ? (char_u *)"utf-8" : p_enc,
2812 fname, tmpname) == FAIL)
2813 errmsg = (char_u *)_("Conversion with 'charconvert' failed");
2814 if (errmsg == NULL && (*fdp = mch_open((char *)tmpname,
2815 O_RDONLY | O_EXTRA, 0)) < 0)
2816 errmsg = (char_u *)_("can't read output of 'charconvert'");
2817 }
2818
2819 if (errmsg != NULL)
2820 {
2821 /* Don't use emsg(), it breaks mappings, the retry with
2822 * another type of conversion might still work. */
2823 MSG(errmsg);
2824 if (tmpname != NULL)
2825 {
2826 mch_remove(tmpname); /* delete converted file */
2827 vim_free(tmpname);
2828 tmpname = NULL;
2829 }
2830 }
2831
2832 /* If the input file is closed, open it (caller should check for error). */
2833 if (*fdp < 0)
2834 *fdp = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
2835
2836 return tmpname;
2837}
2838# endif
2839
2840#endif
2841
2842#ifdef FEAT_VIMINFO
2843/*
2844 * Read marks for the current buffer from the viminfo file, when we support
2845 * buffer marks and the buffer has a name.
2846 */
2847 static void
2848check_marks_read()
2849{
2850 if (!curbuf->b_marks_read && get_viminfo_parameter('\'') > 0
2851 && curbuf->b_ffname != NULL)
Bram Moolenaard812df62008-11-09 12:46:09 +00002852 read_viminfo(NULL, VIF_WANT_MARKS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002853
2854 /* Always set b_marks_read; needed when 'viminfo' is changed to include
2855 * the ' parameter after opening a buffer. */
2856 curbuf->b_marks_read = TRUE;
2857}
2858#endif
2859
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002860#if defined(FEAT_CRYPT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002861/*
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002862 * Get the crypt method used for a file from "ptr[len]", the magic text at the
2863 * start of the file.
2864 * Returns -1 when no encryption used.
2865 */
2866 static int
Bram Moolenaar49771f42010-07-20 17:32:38 +02002867crypt_method_from_magic(ptr, len)
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002868 char *ptr;
2869 int len;
2870{
2871 int i;
2872
2873 for (i = 0; i < (int)(sizeof(crypt_magic) / sizeof(crypt_magic[0])); i++)
2874 {
Bram Moolenaar80794b12010-06-13 05:20:42 +02002875 if (len < (CRYPT_MAGIC_LEN + crypt_salt_len[i] + crypt_seed_len[i]))
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002876 continue;
2877 if (memcmp(ptr, crypt_magic[i], CRYPT_MAGIC_LEN) == 0)
2878 return i;
2879 }
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002880
Bram Moolenaar442b4222010-05-24 21:34:22 +02002881 i = (int)STRLEN(crypt_magic_head);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002882 if (len >= i && memcmp(ptr, crypt_magic_head, i) == 0)
2883 EMSG(_("E821: File is encrypted with unknown method"));
2884
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002885 return -1;
2886}
2887
2888/*
2889 * Check for magic number used for encryption. Applies to the current buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002890 * If found, the magic number is removed from ptr[*sizep] and *sizep and
2891 * *filesizep are updated.
2892 * Return the (new) encryption key, NULL for no encryption.
2893 */
2894 static char_u *
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002895check_for_cryptkey(cryptkey, ptr, sizep, filesizep, newfile, fname, did_ask)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002896 char_u *cryptkey; /* previous encryption key or NULL */
2897 char_u *ptr; /* pointer to read bytes */
2898 long *sizep; /* length of read bytes */
Bram Moolenaar914703b2010-05-31 21:59:46 +02002899 off_t *filesizep; /* nr of bytes used from file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002900 int newfile; /* editing a new buffer */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002901 char_u *fname; /* file name to display */
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002902 int *did_ask; /* flag: whether already asked for key */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002903{
Bram Moolenaar49771f42010-07-20 17:32:38 +02002904 int method = crypt_method_from_magic((char *)ptr, *sizep);
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002905
2906 if (method >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002907 {
Bram Moolenaar49771f42010-07-20 17:32:38 +02002908 set_crypt_method(curbuf, method);
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002909 if (method > 0)
2910 (void)blowfish_self_test();
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002911 if (cryptkey == NULL && !*did_ask)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002912 {
2913 if (*curbuf->b_p_key)
2914 cryptkey = curbuf->b_p_key;
2915 else
2916 {
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002917 /* When newfile is TRUE, store the typed key in the 'key'
2918 * option and don't free it. bf needs hash of the key saved.
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002919 * Don't ask for the key again when first time Enter was hit.
2920 * Happens when retrying to detect encoding. */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002921 smsg((char_u *)_(need_key_msg), fname);
2922 msg_scroll = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002923 cryptkey = get_crypt_key(newfile, FALSE);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002924 *did_ask = TRUE;
2925
Bram Moolenaar071d4272004-06-13 20:20:40 +00002926 /* check if empty key entered */
2927 if (cryptkey != NULL && *cryptkey == NUL)
2928 {
2929 if (cryptkey != curbuf->b_p_key)
2930 vim_free(cryptkey);
2931 cryptkey = NULL;
2932 }
2933 }
2934 }
2935
2936 if (cryptkey != NULL)
2937 {
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002938 int seed_len = crypt_seed_len[method];
Bram Moolenaar80794b12010-06-13 05:20:42 +02002939 int salt_len = crypt_salt_len[method];
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002940
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002941 crypt_push_state();
2942 use_crypt_method = method;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002943 if (method == 0)
2944 crypt_init_keys(cryptkey);
2945 else
2946 {
Bram Moolenaar80794b12010-06-13 05:20:42 +02002947 bf_key_init(cryptkey, ptr + CRYPT_MAGIC_LEN, salt_len);
2948 bf_ofb_init(ptr + CRYPT_MAGIC_LEN + salt_len, seed_len);
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002949 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002950
2951 /* Remove magic number from the text */
Bram Moolenaar80794b12010-06-13 05:20:42 +02002952 *filesizep += CRYPT_MAGIC_LEN + salt_len + seed_len;
2953 *sizep -= CRYPT_MAGIC_LEN + salt_len + seed_len;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002954 mch_memmove(ptr, ptr + CRYPT_MAGIC_LEN + salt_len + seed_len,
2955 (size_t)*sizep);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002956 }
2957 }
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002958 /* When starting to edit a new file which does not have encryption, clear
2959 * the 'key' option, except when starting up (called with -x argument) */
Bram Moolenaarfa0ff9a2010-07-25 16:05:19 +02002960 else if (newfile && *curbuf->b_p_key != NUL && !starting)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002961 set_option_value((char_u *)"key", 0L, (char_u *)"", OPT_LOCAL);
2962
2963 return cryptkey;
2964}
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002965
2966/*
2967 * Check for magic number used for encryption. Applies to the current buffer.
2968 * If found and decryption is possible returns OK;
2969 */
2970 int
2971prepare_crypt_read(fp)
2972 FILE *fp;
2973{
2974 int method;
Bram Moolenaar80794b12010-06-13 05:20:42 +02002975 char_u buffer[CRYPT_MAGIC_LEN + CRYPT_SALT_LEN_MAX
2976 + CRYPT_SEED_LEN_MAX + 2];
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002977
2978 if (fread(buffer, CRYPT_MAGIC_LEN, 1, fp) != 1)
2979 return FAIL;
Bram Moolenaar49771f42010-07-20 17:32:38 +02002980 method = crypt_method_from_magic((char *)buffer,
Bram Moolenaar80794b12010-06-13 05:20:42 +02002981 CRYPT_MAGIC_LEN +
Bram Moolenaarcc448b32010-07-14 16:52:17 +02002982 CRYPT_SEED_LEN_MAX +
2983 CRYPT_SALT_LEN_MAX);
Bram Moolenaar49771f42010-07-20 17:32:38 +02002984 if (method < 0 || method != get_crypt_method(curbuf))
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002985 return FAIL;
2986
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002987 crypt_push_state();
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002988 if (method == 0)
2989 crypt_init_keys(curbuf->b_p_key);
2990 else
2991 {
Bram Moolenaar80794b12010-06-13 05:20:42 +02002992 int salt_len = crypt_salt_len[method];
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002993 int seed_len = crypt_seed_len[method];
2994
Bram Moolenaar80794b12010-06-13 05:20:42 +02002995 if (fread(buffer, salt_len + seed_len, 1, fp) != 1)
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002996 return FAIL;
Bram Moolenaar80794b12010-06-13 05:20:42 +02002997 bf_key_init(curbuf->b_p_key, buffer, salt_len);
2998 bf_ofb_init(buffer + salt_len, seed_len);
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002999 }
3000 return OK;
3001}
3002
3003/*
3004 * Prepare for writing encrypted bytes for buffer "buf".
3005 * Returns a pointer to an allocated header of length "*lenp".
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003006 * When out of memory returns NULL.
3007 * Otherwise calls crypt_push_state(), call crypt_pop_state() later.
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003008 */
3009 char_u *
3010prepare_crypt_write(buf, lenp)
3011 buf_T *buf;
3012 int *lenp;
3013{
3014 char_u *header;
Bram Moolenaar49771f42010-07-20 17:32:38 +02003015 int seed_len = crypt_seed_len[get_crypt_method(buf)];
3016 int salt_len = crypt_salt_len[get_crypt_method(buf)];
Bram Moolenaar80794b12010-06-13 05:20:42 +02003017 char_u *salt;
3018 char_u *seed;
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003019
Bram Moolenaar80794b12010-06-13 05:20:42 +02003020 header = alloc_clear(CRYPT_MAGIC_LEN + CRYPT_SALT_LEN_MAX
3021 + CRYPT_SEED_LEN_MAX + 2);
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003022 if (header != NULL)
3023 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003024 crypt_push_state();
Bram Moolenaar49771f42010-07-20 17:32:38 +02003025 use_crypt_method = get_crypt_method(buf); /* select zip or blowfish */
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003026 vim_strncpy(header, (char_u *)crypt_magic[use_crypt_method],
3027 CRYPT_MAGIC_LEN);
Bram Moolenaar49771f42010-07-20 17:32:38 +02003028 if (use_crypt_method == 0)
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003029 crypt_init_keys(buf->b_p_key);
3030 else
3031 {
Bram Moolenaar80794b12010-06-13 05:20:42 +02003032 /* Using blowfish, add salt and seed. */
3033 salt = header + CRYPT_MAGIC_LEN;
3034 seed = salt + salt_len;
3035 sha2_seed(salt, salt_len, seed, seed_len);
3036 bf_key_init(buf->b_p_key, salt, salt_len);
3037 bf_ofb_init(seed, seed_len);
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003038 }
3039 }
Bram Moolenaar80794b12010-06-13 05:20:42 +02003040 *lenp = CRYPT_MAGIC_LEN + salt_len + seed_len;
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003041 return header;
3042}
3043
Bram Moolenaar80794b12010-06-13 05:20:42 +02003044#endif /* FEAT_CRYPT */
3045
Bram Moolenaar071d4272004-06-13 20:20:40 +00003046#ifdef UNIX
3047 static void
3048set_file_time(fname, atime, mtime)
3049 char_u *fname;
3050 time_t atime; /* access time */
3051 time_t mtime; /* modification time */
3052{
3053# if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
3054 struct utimbuf buf;
3055
3056 buf.actime = atime;
3057 buf.modtime = mtime;
3058 (void)utime((char *)fname, &buf);
3059# else
3060# if defined(HAVE_UTIMES)
3061 struct timeval tvp[2];
3062
3063 tvp[0].tv_sec = atime;
3064 tvp[0].tv_usec = 0;
3065 tvp[1].tv_sec = mtime;
3066 tvp[1].tv_usec = 0;
3067# ifdef NeXT
3068 (void)utimes((char *)fname, tvp);
3069# else
3070 (void)utimes((char *)fname, (const struct timeval *)&tvp);
3071# endif
3072# endif
3073# endif
3074}
3075#endif /* UNIX */
3076
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003077#if defined(VMS) && !defined(MIN)
3078/* Older DECC compiler for VAX doesn't define MIN() */
3079# define MIN(a, b) ((a) < (b) ? (a) : (b))
3080#endif
3081
Bram Moolenaar071d4272004-06-13 20:20:40 +00003082/*
Bram Moolenaar5386a122007-06-28 20:02:32 +00003083 * Return TRUE if a file appears to be read-only from the file permissions.
3084 */
3085 int
3086check_file_readonly(fname, perm)
3087 char_u *fname; /* full path to file */
3088 int perm; /* known permissions on file */
3089{
3090#ifndef USE_MCH_ACCESS
3091 int fd = 0;
3092#endif
3093
3094 return (
3095#ifdef USE_MCH_ACCESS
3096# ifdef UNIX
3097 (perm & 0222) == 0 ||
3098# endif
3099 mch_access((char *)fname, W_OK)
3100#else
3101 (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0
3102 ? TRUE : (close(fd), FALSE)
3103#endif
3104 );
3105}
3106
3107
3108/*
Bram Moolenaar292ad192005-12-11 21:29:51 +00003109 * buf_write() - write to file "fname" lines "start" through "end"
Bram Moolenaar071d4272004-06-13 20:20:40 +00003110 *
3111 * We do our own buffering here because fwrite() is so slow.
3112 *
Bram Moolenaar292ad192005-12-11 21:29:51 +00003113 * If "forceit" is true, we don't care for errors when attempting backups.
3114 * In case of an error everything possible is done to restore the original
Bram Moolenaare37d50a2008-08-06 17:06:04 +00003115 * file. But when "forceit" is TRUE, we risk losing it.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003116 *
3117 * When "reset_changed" is TRUE and "append" == FALSE and "start" == 1 and
3118 * "end" == curbuf->b_ml.ml_line_count, reset curbuf->b_changed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003119 *
3120 * This function must NOT use NameBuff (because it's called by autowrite()).
3121 *
3122 * return FAIL for failure, OK otherwise
3123 */
3124 int
3125buf_write(buf, fname, sfname, start, end, eap, append, forceit,
3126 reset_changed, filtering)
3127 buf_T *buf;
3128 char_u *fname;
3129 char_u *sfname;
3130 linenr_T start, end;
3131 exarg_T *eap; /* for forced 'ff' and 'fenc', can be
3132 NULL! */
Bram Moolenaar292ad192005-12-11 21:29:51 +00003133 int append; /* append to the file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003134 int forceit;
3135 int reset_changed;
3136 int filtering;
3137{
3138 int fd;
3139 char_u *backup = NULL;
3140 int backup_copy = FALSE; /* copy the original file? */
3141 int dobackup;
3142 char_u *ffname;
3143 char_u *wfname = NULL; /* name of file to write to */
3144 char_u *s;
3145 char_u *ptr;
3146 char_u c;
3147 int len;
3148 linenr_T lnum;
3149 long nchars;
3150 char_u *errmsg = NULL;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003151 int errmsg_allocated = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003152 char_u *errnum = NULL;
3153 char_u *buffer;
3154 char_u smallbuf[SMBUFSIZE];
3155 char_u *backup_ext;
3156 int bufsize;
3157 long perm; /* file permissions */
3158 int retval = OK;
3159 int newfile = FALSE; /* TRUE if file doesn't exist yet */
3160 int msg_save = msg_scroll;
3161 int overwriting; /* TRUE if writing over original */
3162 int no_eol = FALSE; /* no end-of-line written */
3163 int device = FALSE; /* writing to a device */
3164 struct stat st_old;
3165 int prev_got_int = got_int;
3166 int file_readonly = FALSE; /* overwritten file is read-only */
3167 static char *err_readonly = "is read-only (cannot override: \"W\" in 'cpoptions')";
3168#if defined(UNIX) || defined(__EMX__XX) /*XXX fix me sometime? */
3169 int made_writable = FALSE; /* 'w' bit has been set */
3170#endif
3171 /* writing everything */
3172 int whole = (start == 1 && end == buf->b_ml.ml_line_count);
3173#ifdef FEAT_AUTOCMD
3174 linenr_T old_line_count = buf->b_ml.ml_line_count;
3175#endif
3176 int attr;
3177 int fileformat;
3178 int write_bin;
3179 struct bw_info write_info; /* info for buf_write_bytes() */
3180#ifdef FEAT_MBYTE
3181 int converted = FALSE;
3182 int notconverted = FALSE;
3183 char_u *fenc; /* effective 'fileencoding' */
3184 char_u *fenc_tofree = NULL; /* allocated "fenc" */
3185#endif
3186#ifdef HAS_BW_FLAGS
3187 int wb_flags = 0;
3188#endif
3189#ifdef HAVE_ACL
3190 vim_acl_T acl = NULL; /* ACL copied from original file to
3191 backup or new file */
3192#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003193#ifdef FEAT_PERSISTENT_UNDO
3194 int write_undo_file = FALSE;
3195 context_sha256_T sha_ctx;
3196#endif
Bram Moolenaar4cf35c22011-02-25 16:52:17 +01003197#ifdef FEAT_CRYPT
3198 int crypt_method_used;
3199#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003200
3201 if (fname == NULL || *fname == NUL) /* safety check */
3202 return FAIL;
Bram Moolenaar70d60e92009-12-31 13:53:33 +00003203 if (buf->b_ml.ml_mfp == NULL)
3204 {
3205 /* This can happen during startup when there is a stray "w" in the
3206 * vimrc file. */
3207 EMSG(_(e_emptybuf));
3208 return FAIL;
3209 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003210
3211 /*
3212 * Disallow writing from .exrc and .vimrc in current directory for
3213 * security reasons.
3214 */
3215 if (check_secure())
3216 return FAIL;
3217
3218 /* Avoid a crash for a long name. */
3219 if (STRLEN(fname) >= MAXPATHL)
3220 {
3221 EMSG(_(e_longname));
3222 return FAIL;
3223 }
3224
3225#ifdef FEAT_MBYTE
3226 /* must init bw_conv_buf and bw_iconv_fd before jumping to "fail" */
3227 write_info.bw_conv_buf = NULL;
3228 write_info.bw_conv_error = FALSE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003229 write_info.bw_conv_error_lnum = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003230 write_info.bw_restlen = 0;
3231# ifdef USE_ICONV
3232 write_info.bw_iconv_fd = (iconv_t)-1;
3233# endif
3234#endif
3235
Bram Moolenaardf177f62005-02-22 08:39:57 +00003236 /* After writing a file changedtick changes but we don't want to display
3237 * the line. */
3238 ex_no_reprint = TRUE;
3239
Bram Moolenaar071d4272004-06-13 20:20:40 +00003240 /*
3241 * If there is no file name yet, use the one for the written file.
3242 * BF_NOTEDITED is set to reflect this (in case the write fails).
3243 * Don't do this when the write is for a filter command.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003244 * Don't do this when appending.
3245 * Only do this when 'cpoptions' contains the 'F' flag.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003246 */
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003247 if (buf->b_ffname == NULL
3248 && reset_changed
Bram Moolenaar071d4272004-06-13 20:20:40 +00003249 && whole
3250 && buf == curbuf
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00003251#ifdef FEAT_QUICKFIX
3252 && !bt_nofile(buf)
3253#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003254 && !filtering
Bram Moolenaar292ad192005-12-11 21:29:51 +00003255 && (!append || vim_strchr(p_cpo, CPO_FNAMEAPP) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003256 && vim_strchr(p_cpo, CPO_FNAMEW) != NULL)
3257 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003258 if (set_rw_fname(fname, sfname) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003259 return FAIL;
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003260 buf = curbuf; /* just in case autocmds made "buf" invalid */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003261 }
3262
3263 if (sfname == NULL)
3264 sfname = fname;
3265 /*
3266 * For Unix: Use the short file name whenever possible.
3267 * Avoids problems with networks and when directory names are changed.
3268 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
3269 * another directory, which we don't detect
3270 */
3271 ffname = fname; /* remember full fname */
3272#ifdef UNIX
3273 fname = sfname;
3274#endif
3275
3276 if (buf->b_ffname != NULL && fnamecmp(ffname, buf->b_ffname) == 0)
3277 overwriting = TRUE;
3278 else
3279 overwriting = FALSE;
3280
3281 if (exiting)
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003282 settmode(TMODE_COOK); /* when exiting allow typeahead now */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003283
3284 ++no_wait_return; /* don't wait for return yet */
3285
3286 /*
3287 * Set '[ and '] marks to the lines to be written.
3288 */
3289 buf->b_op_start.lnum = start;
3290 buf->b_op_start.col = 0;
3291 buf->b_op_end.lnum = end;
3292 buf->b_op_end.col = 0;
3293
3294#ifdef FEAT_AUTOCMD
3295 {
3296 aco_save_T aco;
3297 int buf_ffname = FALSE;
3298 int buf_sfname = FALSE;
3299 int buf_fname_f = FALSE;
3300 int buf_fname_s = FALSE;
3301 int did_cmd = FALSE;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003302 int nofile_err = FALSE;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003303 int empty_memline = (buf->b_ml.ml_mfp == NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003304
3305 /*
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003306 * Apply PRE autocommands.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003307 * Set curbuf to the buffer to be written.
3308 * Careful: The autocommands may call buf_write() recursively!
3309 */
3310 if (ffname == buf->b_ffname)
3311 buf_ffname = TRUE;
3312 if (sfname == buf->b_sfname)
3313 buf_sfname = TRUE;
3314 if (fname == buf->b_ffname)
3315 buf_fname_f = TRUE;
3316 if (fname == buf->b_sfname)
3317 buf_fname_s = TRUE;
3318
3319 /* set curwin/curbuf to buf and save a few things */
3320 aucmd_prepbuf(&aco, buf);
3321
3322 if (append)
3323 {
3324 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD,
3325 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003326 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003327#ifdef FEAT_QUICKFIX
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00003328 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003329 nofile_err = TRUE;
3330 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003331#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003332 apply_autocmds_exarg(EVENT_FILEAPPENDPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003333 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003334 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003335 }
3336 else if (filtering)
3337 {
3338 apply_autocmds_exarg(EVENT_FILTERWRITEPRE,
3339 NULL, sfname, FALSE, curbuf, eap);
3340 }
3341 else if (reset_changed && whole)
3342 {
Bram Moolenaar39fc42e2011-09-02 11:56:20 +02003343 int was_changed = curbufIsChanged();
3344
3345 did_cmd = apply_autocmds_exarg(EVENT_BUFWRITECMD,
3346 sfname, sfname, FALSE, curbuf, eap);
3347 if (did_cmd)
3348 {
3349 if (was_changed && !curbufIsChanged())
3350 {
3351 /* Written everything correctly and BufWriteCmd has reset
3352 * 'modified': Correct the undo information so that an
3353 * undo now sets 'modified'. */
3354 u_unchanged(curbuf);
3355 u_update_save_nr(curbuf);
3356 }
3357 }
3358 else
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003359 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003360#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003361 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003362 nofile_err = TRUE;
3363 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003364#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003365 apply_autocmds_exarg(EVENT_BUFWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003366 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003367 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003368 }
3369 else
3370 {
3371 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD,
3372 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003373 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003374#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003375 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003376 nofile_err = TRUE;
3377 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003378#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003379 apply_autocmds_exarg(EVENT_FILEWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003380 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003381 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003382 }
3383
3384 /* restore curwin/curbuf and a few other things */
3385 aucmd_restbuf(&aco);
3386
3387 /*
3388 * In three situations we return here and don't write the file:
3389 * 1. the autocommands deleted or unloaded the buffer.
3390 * 2. The autocommands abort script processing.
3391 * 3. If one of the "Cmd" autocommands was executed.
3392 */
3393 if (!buf_valid(buf))
3394 buf = NULL;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003395 if (buf == NULL || (buf->b_ml.ml_mfp == NULL && !empty_memline)
Bram Moolenaar1e015462005-09-25 22:16:38 +00003396 || did_cmd || nofile_err
3397#ifdef FEAT_EVAL
3398 || aborting()
3399#endif
3400 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003401 {
3402 --no_wait_return;
3403 msg_scroll = msg_save;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003404 if (nofile_err)
3405 EMSG(_("E676: No matching autocommands for acwrite buffer"));
3406
Bram Moolenaar1e015462005-09-25 22:16:38 +00003407 if (nofile_err
3408#ifdef FEAT_EVAL
3409 || aborting()
3410#endif
3411 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003412 /* An aborting error, interrupt or exception in the
3413 * autocommands. */
3414 return FAIL;
3415 if (did_cmd)
3416 {
3417 if (buf == NULL)
3418 /* The buffer was deleted. We assume it was written
3419 * (can't retry anyway). */
3420 return OK;
3421 if (overwriting)
3422 {
3423 /* Assume the buffer was written, update the timestamp. */
3424 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00003425 if (append)
3426 buf->b_flags &= ~BF_NEW;
3427 else
3428 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003429 }
Bram Moolenaar292ad192005-12-11 21:29:51 +00003430 if (reset_changed && buf->b_changed && !append
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003431 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003432 /* Buffer still changed, the autocommands didn't work
3433 * properly. */
3434 return FAIL;
3435 return OK;
3436 }
3437#ifdef FEAT_EVAL
3438 if (!aborting())
3439#endif
3440 EMSG(_("E203: Autocommands deleted or unloaded buffer to be written"));
3441 return FAIL;
3442 }
3443
3444 /*
3445 * The autocommands may have changed the number of lines in the file.
3446 * When writing the whole file, adjust the end.
3447 * When writing part of the file, assume that the autocommands only
3448 * changed the number of lines that are to be written (tricky!).
3449 */
3450 if (buf->b_ml.ml_line_count != old_line_count)
3451 {
3452 if (whole) /* write all */
3453 end = buf->b_ml.ml_line_count;
3454 else if (buf->b_ml.ml_line_count > old_line_count) /* more lines */
3455 end += buf->b_ml.ml_line_count - old_line_count;
3456 else /* less lines */
3457 {
3458 end -= old_line_count - buf->b_ml.ml_line_count;
3459 if (end < start)
3460 {
3461 --no_wait_return;
3462 msg_scroll = msg_save;
3463 EMSG(_("E204: Autocommand changed number of lines in unexpected way"));
3464 return FAIL;
3465 }
3466 }
3467 }
3468
3469 /*
3470 * The autocommands may have changed the name of the buffer, which may
3471 * be kept in fname, ffname and sfname.
3472 */
3473 if (buf_ffname)
3474 ffname = buf->b_ffname;
3475 if (buf_sfname)
3476 sfname = buf->b_sfname;
3477 if (buf_fname_f)
3478 fname = buf->b_ffname;
3479 if (buf_fname_s)
3480 fname = buf->b_sfname;
3481 }
3482#endif
3483
3484#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003485 if (netbeans_active() && isNetbeansBuffer(buf))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003486 {
3487 if (whole)
3488 {
3489 /*
3490 * b_changed can be 0 after an undo, but we still need to write
3491 * the buffer to NetBeans.
3492 */
3493 if (buf->b_changed || isNetbeansModified(buf))
3494 {
Bram Moolenaar009b2592004-10-24 19:18:58 +00003495 --no_wait_return; /* may wait for return now */
3496 msg_scroll = msg_save;
3497 netbeans_save_buffer(buf); /* no error checking... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003498 return retval;
3499 }
3500 else
3501 {
3502 errnum = (char_u *)"E656: ";
Bram Moolenaared0e7452008-06-27 19:17:34 +00003503 errmsg = (char_u *)_("NetBeans disallows writes of unmodified buffers");
Bram Moolenaar071d4272004-06-13 20:20:40 +00003504 buffer = NULL;
3505 goto fail;
3506 }
3507 }
3508 else
3509 {
3510 errnum = (char_u *)"E657: ";
3511 errmsg = (char_u *)_("Partial writes disallowed for NetBeans buffers");
3512 buffer = NULL;
3513 goto fail;
3514 }
3515 }
3516#endif
3517
3518 if (shortmess(SHM_OVER) && !exiting)
3519 msg_scroll = FALSE; /* overwrite previous file message */
3520 else
3521 msg_scroll = TRUE; /* don't overwrite previous file message */
3522 if (!filtering)
3523 filemess(buf,
3524#ifndef UNIX
3525 sfname,
3526#else
3527 fname,
3528#endif
3529 (char_u *)"", 0); /* show that we are busy */
3530 msg_scroll = FALSE; /* always overwrite the file message now */
3531
3532 buffer = alloc(BUFSIZE);
3533 if (buffer == NULL) /* can't allocate big buffer, use small
3534 * one (to be able to write when out of
3535 * memory) */
3536 {
3537 buffer = smallbuf;
3538 bufsize = SMBUFSIZE;
3539 }
3540 else
3541 bufsize = BUFSIZE;
3542
3543 /*
3544 * Get information about original file (if there is one).
3545 */
3546#if defined(UNIX) && !defined(ARCHIE)
Bram Moolenaar6f192452007-11-08 19:49:02 +00003547 st_old.st_dev = 0;
3548 st_old.st_ino = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003549 perm = -1;
3550 if (mch_stat((char *)fname, &st_old) < 0)
3551 newfile = TRUE;
3552 else
3553 {
3554 perm = st_old.st_mode;
3555 if (!S_ISREG(st_old.st_mode)) /* not a file */
3556 {
3557 if (S_ISDIR(st_old.st_mode))
3558 {
3559 errnum = (char_u *)"E502: ";
3560 errmsg = (char_u *)_("is a directory");
3561 goto fail;
3562 }
3563 if (mch_nodetype(fname) != NODE_WRITABLE)
3564 {
3565 errnum = (char_u *)"E503: ";
3566 errmsg = (char_u *)_("is not a file or writable device");
3567 goto fail;
3568 }
3569 /* It's a device of some kind (or a fifo) which we can write to
3570 * but for which we can't make a backup. */
3571 device = TRUE;
3572 newfile = TRUE;
3573 perm = -1;
3574 }
3575 }
3576#else /* !UNIX */
3577 /*
3578 * Check for a writable device name.
3579 */
3580 c = mch_nodetype(fname);
3581 if (c == NODE_OTHER)
3582 {
3583 errnum = (char_u *)"E503: ";
3584 errmsg = (char_u *)_("is not a file or writable device");
3585 goto fail;
3586 }
3587 if (c == NODE_WRITABLE)
3588 {
Bram Moolenaar043545e2006-10-10 16:44:07 +00003589# if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3590 /* MS-Windows allows opening a device, but we will probably get stuck
3591 * trying to write to it. */
3592 if (!p_odev)
3593 {
3594 errnum = (char_u *)"E796: ";
3595 errmsg = (char_u *)_("writing to device disabled with 'opendevice' option");
3596 goto fail;
3597 }
3598# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003599 device = TRUE;
3600 newfile = TRUE;
3601 perm = -1;
3602 }
3603 else
3604 {
3605 perm = mch_getperm(fname);
3606 if (perm < 0)
3607 newfile = TRUE;
3608 else if (mch_isdir(fname))
3609 {
3610 errnum = (char_u *)"E502: ";
3611 errmsg = (char_u *)_("is a directory");
3612 goto fail;
3613 }
3614 if (overwriting)
3615 (void)mch_stat((char *)fname, &st_old);
3616 }
3617#endif /* !UNIX */
3618
3619 if (!device && !newfile)
3620 {
3621 /*
3622 * Check if the file is really writable (when renaming the file to
3623 * make a backup we won't discover it later).
3624 */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003625 file_readonly = check_file_readonly(fname, (int)perm);
3626
Bram Moolenaar071d4272004-06-13 20:20:40 +00003627 if (!forceit && file_readonly)
3628 {
3629 if (vim_strchr(p_cpo, CPO_FWRITE) != NULL)
3630 {
3631 errnum = (char_u *)"E504: ";
3632 errmsg = (char_u *)_(err_readonly);
3633 }
3634 else
3635 {
3636 errnum = (char_u *)"E505: ";
3637 errmsg = (char_u *)_("is read-only (add ! to override)");
3638 }
3639 goto fail;
3640 }
3641
3642 /*
3643 * Check if the timestamp hasn't changed since reading the file.
3644 */
3645 if (overwriting)
3646 {
3647 retval = check_mtime(buf, &st_old);
3648 if (retval == FAIL)
3649 goto fail;
3650 }
3651 }
3652
3653#ifdef HAVE_ACL
3654 /*
3655 * For systems that support ACL: get the ACL from the original file.
3656 */
3657 if (!newfile)
3658 acl = mch_get_acl(fname);
3659#endif
3660
3661 /*
3662 * If 'backupskip' is not empty, don't make a backup for some files.
3663 */
3664 dobackup = (p_wb || p_bk || *p_pm != NUL);
3665#ifdef FEAT_WILDIGN
3666 if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname))
3667 dobackup = FALSE;
3668#endif
3669
3670 /*
3671 * Save the value of got_int and reset it. We don't want a previous
3672 * interruption cancel writing, only hitting CTRL-C while writing should
3673 * abort it.
3674 */
3675 prev_got_int = got_int;
3676 got_int = FALSE;
3677
3678 /* Mark the buffer as 'being saved' to prevent changed buffer warnings */
3679 buf->b_saving = TRUE;
3680
3681 /*
3682 * If we are not appending or filtering, the file exists, and the
3683 * 'writebackup', 'backup' or 'patchmode' option is set, need a backup.
3684 * When 'patchmode' is set also make a backup when appending.
3685 *
3686 * Do not make any backup, if 'writebackup' and 'backup' are both switched
3687 * off. This helps when editing large files on almost-full disks.
3688 */
3689 if (!(append && *p_pm == NUL) && !filtering && perm >= 0 && dobackup)
3690 {
3691#if defined(UNIX) || defined(WIN32)
3692 struct stat st;
3693#endif
3694
3695 if ((bkc_flags & BKC_YES) || append) /* "yes" */
3696 backup_copy = TRUE;
3697#if defined(UNIX) || defined(WIN32)
3698 else if ((bkc_flags & BKC_AUTO)) /* "auto" */
3699 {
3700 int i;
3701
3702# ifdef UNIX
3703 /*
3704 * Don't rename the file when:
3705 * - it's a hard link
3706 * - it's a symbolic link
3707 * - we don't have write permission in the directory
3708 * - we can't set the owner/group of the new file
3709 */
3710 if (st_old.st_nlink > 1
3711 || mch_lstat((char *)fname, &st) < 0
3712 || st.st_dev != st_old.st_dev
Bram Moolenaara5792f52005-11-23 21:25:05 +00003713 || st.st_ino != st_old.st_ino
3714# ifndef HAVE_FCHOWN
3715 || st.st_uid != st_old.st_uid
3716 || st.st_gid != st_old.st_gid
3717# endif
3718 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003719 backup_copy = TRUE;
3720 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003721# else
3722# ifdef WIN32
3723 /* On NTFS file systems hard links are possible. */
3724 if (mch_is_linked(fname))
3725 backup_copy = TRUE;
3726 else
3727# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003728# endif
3729 {
3730 /*
3731 * Check if we can create a file and set the owner/group to
3732 * the ones from the original file.
3733 * First find a file name that doesn't exist yet (use some
3734 * arbitrary numbers).
3735 */
3736 STRCPY(IObuff, fname);
3737 for (i = 4913; ; i += 123)
3738 {
3739 sprintf((char *)gettail(IObuff), "%d", i);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003740 if (mch_lstat((char *)IObuff, &st) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003741 break;
3742 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00003743 fd = mch_open((char *)IObuff,
3744 O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003745 if (fd < 0) /* can't write in directory */
3746 backup_copy = TRUE;
3747 else
3748 {
3749# ifdef UNIX
Bram Moolenaara5792f52005-11-23 21:25:05 +00003750# ifdef HAVE_FCHOWN
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00003751 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003752# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003753 if (mch_stat((char *)IObuff, &st) < 0
3754 || st.st_uid != st_old.st_uid
3755 || st.st_gid != st_old.st_gid
Bram Moolenaar78a15312009-05-15 19:33:18 +00003756 || (long)st.st_mode != perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003757 backup_copy = TRUE;
3758# endif
Bram Moolenaar98358622005-11-28 22:58:23 +00003759 /* Close the file before removing it, on MS-Windows we
3760 * can't delete an open file. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003761 close(fd);
Bram Moolenaar98358622005-11-28 22:58:23 +00003762 mch_remove(IObuff);
Bram Moolenaar3479c5d2010-08-08 18:46:06 +02003763# ifdef MSWIN
3764 /* MS-Windows may trigger a virus scanner to open the
3765 * file, we can't delete it then. Keep trying for half a
3766 * second. */
3767 {
3768 int try;
3769
3770 for (try = 0; try < 10; ++try)
3771 {
3772 if (mch_lstat((char *)IObuff, &st) < 0)
3773 break;
3774 ui_delay(50L, TRUE); /* wait 50 msec */
3775 mch_remove(IObuff);
3776 }
3777 }
3778# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003779 }
3780 }
3781 }
3782
Bram Moolenaar071d4272004-06-13 20:20:40 +00003783 /*
3784 * Break symlinks and/or hardlinks if we've been asked to.
3785 */
3786 if ((bkc_flags & BKC_BREAKSYMLINK) || (bkc_flags & BKC_BREAKHARDLINK))
3787 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003788# ifdef UNIX
Bram Moolenaar071d4272004-06-13 20:20:40 +00003789 int lstat_res;
3790
3791 lstat_res = mch_lstat((char *)fname, &st);
3792
3793 /* Symlinks. */
3794 if ((bkc_flags & BKC_BREAKSYMLINK)
3795 && lstat_res == 0
3796 && st.st_ino != st_old.st_ino)
3797 backup_copy = FALSE;
3798
3799 /* Hardlinks. */
3800 if ((bkc_flags & BKC_BREAKHARDLINK)
3801 && st_old.st_nlink > 1
3802 && (lstat_res != 0 || st.st_ino == st_old.st_ino))
3803 backup_copy = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003804# else
3805# if defined(WIN32)
3806 /* Symlinks. */
3807 if ((bkc_flags & BKC_BREAKSYMLINK) && mch_is_symbolic_link(fname))
3808 backup_copy = FALSE;
3809
3810 /* Hardlinks. */
3811 if ((bkc_flags & BKC_BREAKHARDLINK) && mch_is_hard_link(fname))
3812 backup_copy = FALSE;
3813# endif
3814# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003815 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003816
3817#endif
3818
3819 /* make sure we have a valid backup extension to use */
3820 if (*p_bex == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003821 backup_ext = (char_u *)".bak";
Bram Moolenaar071d4272004-06-13 20:20:40 +00003822 else
3823 backup_ext = p_bex;
3824
3825 if (backup_copy
3826 && (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) >= 0)
3827 {
3828 int bfd;
3829 char_u *copybuf, *wp;
3830 int some_error = FALSE;
3831 struct stat st_new;
3832 char_u *dirp;
3833 char_u *rootname;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003834#if defined(UNIX) && !defined(SHORT_FNAME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003835 int did_set_shortname;
3836#endif
3837
3838 copybuf = alloc(BUFSIZE + 1);
3839 if (copybuf == NULL)
3840 {
3841 some_error = TRUE; /* out of memory */
3842 goto nobackup;
3843 }
3844
3845 /*
3846 * Try to make the backup in each directory in the 'bdir' option.
3847 *
3848 * Unix semantics has it, that we may have a writable file,
3849 * that cannot be recreated with a simple open(..., O_CREAT, ) e.g:
3850 * - the directory is not writable,
3851 * - the file may be a symbolic link,
3852 * - the file may belong to another user/group, etc.
3853 *
3854 * For these reasons, the existing writable file must be truncated
3855 * and reused. Creation of a backup COPY will be attempted.
3856 */
3857 dirp = p_bdir;
3858 while (*dirp)
3859 {
3860#ifdef UNIX
3861 st_new.st_ino = 0;
3862 st_new.st_dev = 0;
3863 st_new.st_gid = 0;
3864#endif
3865
3866 /*
3867 * Isolate one directory name, using an entry in 'bdir'.
3868 */
3869 (void)copy_option_part(&dirp, copybuf, BUFSIZE, ",");
3870 rootname = get_file_in_dir(fname, copybuf);
3871 if (rootname == NULL)
3872 {
3873 some_error = TRUE; /* out of memory */
3874 goto nobackup;
3875 }
3876
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003877#if defined(UNIX) && !defined(SHORT_FNAME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003878 did_set_shortname = FALSE;
3879#endif
3880
3881 /*
3882 * May try twice if 'shortname' not set.
3883 */
3884 for (;;)
3885 {
3886 /*
3887 * Make backup file name.
3888 */
3889 backup = buf_modname(
3890#ifdef SHORT_FNAME
3891 TRUE,
3892#else
3893 (buf->b_p_sn || buf->b_shortname),
3894#endif
3895 rootname, backup_ext, FALSE);
3896 if (backup == NULL)
3897 {
3898 vim_free(rootname);
3899 some_error = TRUE; /* out of memory */
3900 goto nobackup;
3901 }
3902
3903 /*
3904 * Check if backup file already exists.
3905 */
3906 if (mch_stat((char *)backup, &st_new) >= 0)
3907 {
3908#ifdef UNIX
3909 /*
3910 * Check if backup file is same as original file.
3911 * May happen when modname() gave the same file back.
3912 * E.g. silly link, or file name-length reached.
3913 * If we don't check here, we either ruin the file
3914 * when copying or erase it after writing. jw.
3915 */
3916 if (st_new.st_dev == st_old.st_dev
3917 && st_new.st_ino == st_old.st_ino)
3918 {
3919 vim_free(backup);
3920 backup = NULL; /* no backup file to delete */
3921# ifndef SHORT_FNAME
3922 /*
3923 * may try again with 'shortname' set
3924 */
3925 if (!(buf->b_shortname || buf->b_p_sn))
3926 {
3927 buf->b_shortname = TRUE;
3928 did_set_shortname = TRUE;
3929 continue;
3930 }
3931 /* setting shortname didn't help */
3932 if (did_set_shortname)
3933 buf->b_shortname = FALSE;
3934# endif
3935 break;
3936 }
3937#endif
3938
3939 /*
3940 * If we are not going to keep the backup file, don't
3941 * delete an existing one, try to use another name.
3942 * Change one character, just before the extension.
3943 */
3944 if (!p_bk)
3945 {
3946 wp = backup + STRLEN(backup) - 1
3947 - STRLEN(backup_ext);
3948 if (wp < backup) /* empty file name ??? */
3949 wp = backup;
3950 *wp = 'z';
3951 while (*wp > 'a'
3952 && mch_stat((char *)backup, &st_new) >= 0)
3953 --*wp;
3954 /* They all exist??? Must be something wrong. */
3955 if (*wp == 'a')
3956 {
3957 vim_free(backup);
3958 backup = NULL;
3959 }
3960 }
3961 }
3962 break;
3963 }
3964 vim_free(rootname);
3965
3966 /*
3967 * Try to create the backup file
3968 */
3969 if (backup != NULL)
3970 {
3971 /* remove old backup, if present */
3972 mch_remove(backup);
3973 /* Open with O_EXCL to avoid the file being created while
3974 * we were sleeping (symlink hacker attack?) */
3975 bfd = mch_open((char *)backup,
Bram Moolenaara5792f52005-11-23 21:25:05 +00003976 O_WRONLY|O_CREAT|O_EXTRA|O_EXCL|O_NOFOLLOW,
3977 perm & 0777);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003978 if (bfd < 0)
3979 {
3980 vim_free(backup);
3981 backup = NULL;
3982 }
3983 else
3984 {
3985 /* set file protection same as original file, but
3986 * strip s-bit */
3987 (void)mch_setperm(backup, perm & 0777);
3988
3989#ifdef UNIX
3990 /*
3991 * Try to set the group of the backup same as the
3992 * original file. If this fails, set the protection
3993 * bits for the group same as the protection bits for
3994 * others.
3995 */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003996 if (st_new.st_gid != st_old.st_gid
Bram Moolenaar071d4272004-06-13 20:20:40 +00003997# ifdef HAVE_FCHOWN /* sequent-ptx lacks fchown() */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003998 && fchown(bfd, (uid_t)-1, st_old.st_gid) != 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00003999# endif
4000 )
4001 mch_setperm(backup,
4002 (perm & 0707) | ((perm & 07) << 3));
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004003# ifdef HAVE_SELINUX
4004 mch_copy_sec(fname, backup);
4005# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004006#endif
4007
4008 /*
4009 * copy the file.
4010 */
4011 write_info.bw_fd = bfd;
4012 write_info.bw_buf = copybuf;
4013#ifdef HAS_BW_FLAGS
4014 write_info.bw_flags = FIO_NOCONVERT;
4015#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004016 while ((write_info.bw_len = read_eintr(fd, copybuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004017 BUFSIZE)) > 0)
4018 {
4019 if (buf_write_bytes(&write_info) == FAIL)
4020 {
4021 errmsg = (char_u *)_("E506: Can't write to backup file (add ! to override)");
4022 break;
4023 }
4024 ui_breakcheck();
4025 if (got_int)
4026 {
4027 errmsg = (char_u *)_(e_interr);
4028 break;
4029 }
4030 }
4031
4032 if (close(bfd) < 0 && errmsg == NULL)
4033 errmsg = (char_u *)_("E507: Close error for backup file (add ! to override)");
4034 if (write_info.bw_len < 0)
4035 errmsg = (char_u *)_("E508: Can't read file for backup (add ! to override)");
4036#ifdef UNIX
4037 set_file_time(backup, st_old.st_atime, st_old.st_mtime);
4038#endif
4039#ifdef HAVE_ACL
4040 mch_set_acl(backup, acl);
4041#endif
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004042#ifdef HAVE_SELINUX
4043 mch_copy_sec(fname, backup);
4044#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004045 break;
4046 }
4047 }
4048 }
4049 nobackup:
4050 close(fd); /* ignore errors for closing read file */
4051 vim_free(copybuf);
4052
4053 if (backup == NULL && errmsg == NULL)
4054 errmsg = (char_u *)_("E509: Cannot create backup file (add ! to override)");
4055 /* ignore errors when forceit is TRUE */
4056 if ((some_error || errmsg != NULL) && !forceit)
4057 {
4058 retval = FAIL;
4059 goto fail;
4060 }
4061 errmsg = NULL;
4062 }
4063 else
4064 {
4065 char_u *dirp;
4066 char_u *p;
4067 char_u *rootname;
4068
4069 /*
4070 * Make a backup by renaming the original file.
4071 */
4072 /*
4073 * If 'cpoptions' includes the "W" flag, we don't want to
4074 * overwrite a read-only file. But rename may be possible
4075 * anyway, thus we need an extra check here.
4076 */
4077 if (file_readonly && vim_strchr(p_cpo, CPO_FWRITE) != NULL)
4078 {
4079 errnum = (char_u *)"E504: ";
4080 errmsg = (char_u *)_(err_readonly);
4081 goto fail;
4082 }
4083
4084 /*
4085 *
4086 * Form the backup file name - change path/fo.o.h to
4087 * path/fo.o.h.bak Try all directories in 'backupdir', first one
4088 * that works is used.
4089 */
4090 dirp = p_bdir;
4091 while (*dirp)
4092 {
4093 /*
4094 * Isolate one directory name and make the backup file name.
4095 */
4096 (void)copy_option_part(&dirp, IObuff, IOSIZE, ",");
4097 rootname = get_file_in_dir(fname, IObuff);
4098 if (rootname == NULL)
4099 backup = NULL;
4100 else
4101 {
4102 backup = buf_modname(
4103#ifdef SHORT_FNAME
4104 TRUE,
4105#else
4106 (buf->b_p_sn || buf->b_shortname),
4107#endif
4108 rootname, backup_ext, FALSE);
4109 vim_free(rootname);
4110 }
4111
4112 if (backup != NULL)
4113 {
4114 /*
4115 * If we are not going to keep the backup file, don't
4116 * delete an existing one, try to use another name.
4117 * Change one character, just before the extension.
4118 */
4119 if (!p_bk && mch_getperm(backup) >= 0)
4120 {
4121 p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext);
4122 if (p < backup) /* empty file name ??? */
4123 p = backup;
4124 *p = 'z';
4125 while (*p > 'a' && mch_getperm(backup) >= 0)
4126 --*p;
4127 /* They all exist??? Must be something wrong! */
4128 if (*p == 'a')
4129 {
4130 vim_free(backup);
4131 backup = NULL;
4132 }
4133 }
4134 }
4135 if (backup != NULL)
4136 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004137 /*
Bram Moolenaarbfd8fc02005-09-20 23:22:24 +00004138 * Delete any existing backup and move the current version
4139 * to the backup. For safety, we don't remove the backup
4140 * until the write has finished successfully. And if the
4141 * 'backup' option is set, leave it around.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004142 */
4143 /*
4144 * If the renaming of the original file to the backup file
4145 * works, quit here.
4146 */
4147 if (vim_rename(fname, backup) == 0)
4148 break;
4149
4150 vim_free(backup); /* don't do the rename below */
4151 backup = NULL;
4152 }
4153 }
4154 if (backup == NULL && !forceit)
4155 {
4156 errmsg = (char_u *)_("E510: Can't make backup file (add ! to override)");
4157 goto fail;
4158 }
4159 }
4160 }
4161
4162#if defined(UNIX) && !defined(ARCHIE)
4163 /* When using ":w!" and the file was read-only: make it writable */
4164 if (forceit && perm >= 0 && !(perm & 0200) && st_old.st_uid == getuid()
4165 && vim_strchr(p_cpo, CPO_FWRITE) == NULL)
4166 {
4167 perm |= 0200;
4168 (void)mch_setperm(fname, perm);
4169 made_writable = TRUE;
4170 }
4171#endif
4172
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004173 /* When using ":w!" and writing to the current file, 'readonly' makes no
Bram Moolenaar4399ef42005-02-12 14:29:27 +00004174 * sense, reset it, unless 'Z' appears in 'cpoptions'. */
4175 if (forceit && overwriting && vim_strchr(p_cpo, CPO_KEEPRO) == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004176 {
4177 buf->b_p_ro = FALSE;
4178#ifdef FEAT_TITLE
4179 need_maketitle = TRUE; /* set window title later */
4180#endif
4181#ifdef FEAT_WINDOWS
4182 status_redraw_all(); /* redraw status lines later */
4183#endif
4184 }
4185
4186 if (end > buf->b_ml.ml_line_count)
4187 end = buf->b_ml.ml_line_count;
4188 if (buf->b_ml.ml_flags & ML_EMPTY)
4189 start = end + 1;
4190
4191 /*
4192 * If the original file is being overwritten, there is a small chance that
4193 * we crash in the middle of writing. Therefore the file is preserved now.
4194 * This makes all block numbers positive so that recovery does not need
4195 * the original file.
4196 * Don't do this if there is a backup file and we are exiting.
4197 */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004198 if (reset_changed && !newfile && overwriting
Bram Moolenaar071d4272004-06-13 20:20:40 +00004199 && !(exiting && backup != NULL))
4200 {
4201 ml_preserve(buf, FALSE);
4202 if (got_int)
4203 {
4204 errmsg = (char_u *)_(e_interr);
4205 goto restore_backup;
4206 }
4207 }
4208
4209#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
4210 /*
4211 * Before risking to lose the original file verify if there's
4212 * a resource fork to preserve, and if cannot be done warn
4213 * the users. This happens when overwriting without backups.
4214 */
4215 if (backup == NULL && overwriting && !append)
4216 if (mch_has_resource_fork(fname))
4217 {
4218 errmsg = (char_u *)_("E460: The resource fork would be lost (add ! to override)");
4219 goto restore_backup;
4220 }
4221#endif
4222
4223#ifdef VMS
4224 vms_remove_version(fname); /* remove version */
4225#endif
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00004226 /* Default: write the file directly. May write to a temp file for
Bram Moolenaar071d4272004-06-13 20:20:40 +00004227 * multi-byte conversion. */
4228 wfname = fname;
4229
4230#ifdef FEAT_MBYTE
4231 /* Check for forced 'fileencoding' from "++opt=val" argument. */
4232 if (eap != NULL && eap->force_enc != 0)
4233 {
4234 fenc = eap->cmd + eap->force_enc;
4235 fenc = enc_canonize(fenc);
4236 fenc_tofree = fenc;
4237 }
4238 else
4239 fenc = buf->b_p_fenc;
4240
4241 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004242 * Check if the file needs to be converted.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004243 */
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004244 converted = need_conversion(fenc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004245
4246 /*
4247 * Check if UTF-8 to UCS-2/4 or Latin1 conversion needs to be done. Or
4248 * Latin1 to Unicode conversion. This is handled in buf_write_bytes().
4249 * Prepare the flags for it and allocate bw_conv_buf when needed.
4250 */
4251 if (converted && (enc_utf8 || STRCMP(p_enc, "latin1") == 0))
4252 {
4253 wb_flags = get_fio_flags(fenc);
4254 if (wb_flags & (FIO_UCS2 | FIO_UCS4 | FIO_UTF16 | FIO_UTF8))
4255 {
4256 /* Need to allocate a buffer to translate into. */
4257 if (wb_flags & (FIO_UCS2 | FIO_UTF16 | FIO_UTF8))
4258 write_info.bw_conv_buflen = bufsize * 2;
4259 else /* FIO_UCS4 */
4260 write_info.bw_conv_buflen = bufsize * 4;
4261 write_info.bw_conv_buf
4262 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4263 if (write_info.bw_conv_buf == NULL)
4264 end = 0;
4265 }
4266 }
4267
4268# ifdef WIN3264
4269 if (converted && wb_flags == 0 && (wb_flags = get_win_fio_flags(fenc)) != 0)
4270 {
4271 /* Convert UTF-8 -> UCS-2 and UCS-2 -> DBCS. Worst-case * 4: */
4272 write_info.bw_conv_buflen = bufsize * 4;
4273 write_info.bw_conv_buf
4274 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4275 if (write_info.bw_conv_buf == NULL)
4276 end = 0;
4277 }
4278# endif
4279
4280# ifdef MACOS_X
4281 if (converted && wb_flags == 0 && (wb_flags = get_mac_fio_flags(fenc)) != 0)
4282 {
4283 write_info.bw_conv_buflen = bufsize * 3;
4284 write_info.bw_conv_buf
4285 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4286 if (write_info.bw_conv_buf == NULL)
4287 end = 0;
4288 }
4289# endif
4290
4291# if defined(FEAT_EVAL) || defined(USE_ICONV)
4292 if (converted && wb_flags == 0)
4293 {
4294# ifdef USE_ICONV
4295 /*
4296 * Use iconv() conversion when conversion is needed and it's not done
4297 * internally.
4298 */
4299 write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc,
4300 enc_utf8 ? (char_u *)"utf-8" : p_enc);
4301 if (write_info.bw_iconv_fd != (iconv_t)-1)
4302 {
4303 /* We're going to use iconv(), allocate a buffer to convert in. */
4304 write_info.bw_conv_buflen = bufsize * ICONV_MULT;
4305 write_info.bw_conv_buf
4306 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4307 if (write_info.bw_conv_buf == NULL)
4308 end = 0;
4309 write_info.bw_first = TRUE;
4310 }
4311# ifdef FEAT_EVAL
4312 else
4313# endif
4314# endif
4315
4316# ifdef FEAT_EVAL
4317 /*
4318 * When the file needs to be converted with 'charconvert' after
4319 * writing, write to a temp file instead and let the conversion
4320 * overwrite the original file.
4321 */
4322 if (*p_ccv != NUL)
4323 {
4324 wfname = vim_tempname('w');
4325 if (wfname == NULL) /* Can't write without a tempfile! */
4326 {
4327 errmsg = (char_u *)_("E214: Can't find temp file for writing");
4328 goto restore_backup;
4329 }
4330 }
4331# endif
4332 }
4333# endif
4334 if (converted && wb_flags == 0
4335# ifdef USE_ICONV
4336 && write_info.bw_iconv_fd == (iconv_t)-1
4337# endif
4338# ifdef FEAT_EVAL
4339 && wfname == fname
4340# endif
4341 )
4342 {
4343 if (!forceit)
4344 {
4345 errmsg = (char_u *)_("E213: Cannot convert (add ! to write without conversion)");
4346 goto restore_backup;
4347 }
4348 notconverted = TRUE;
4349 }
4350#endif
4351
4352 /*
4353 * Open the file "wfname" for writing.
4354 * We may try to open the file twice: If we can't write to the
4355 * file and forceit is TRUE we delete the existing file and try to create
4356 * a new one. If this still fails we may have lost the original file!
4357 * (this may happen when the user reached his quotum for number of files).
4358 * Appending will fail if the file does not exist and forceit is FALSE.
4359 */
4360 while ((fd = mch_open((char *)wfname, O_WRONLY | O_EXTRA | (append
4361 ? (forceit ? (O_APPEND | O_CREAT) : O_APPEND)
4362 : (O_CREAT | O_TRUNC))
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00004363 , perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004364 {
4365 /*
4366 * A forced write will try to create a new file if the old one is
4367 * still readonly. This may also happen when the directory is
4368 * read-only. In that case the mch_remove() will fail.
4369 */
4370 if (errmsg == NULL)
4371 {
4372#ifdef UNIX
4373 struct stat st;
4374
4375 /* Don't delete the file when it's a hard or symbolic link. */
4376 if ((!newfile && st_old.st_nlink > 1)
4377 || (mch_lstat((char *)fname, &st) == 0
4378 && (st.st_dev != st_old.st_dev
4379 || st.st_ino != st_old.st_ino)))
4380 errmsg = (char_u *)_("E166: Can't open linked file for writing");
4381 else
4382#endif
4383 {
4384 errmsg = (char_u *)_("E212: Can't open file for writing");
4385 if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL
4386 && perm >= 0)
4387 {
4388#ifdef UNIX
4389 /* we write to the file, thus it should be marked
4390 writable after all */
4391 if (!(perm & 0200))
4392 made_writable = TRUE;
4393 perm |= 0200;
4394 if (st_old.st_uid != getuid() || st_old.st_gid != getgid())
4395 perm &= 0777;
4396#endif
4397 if (!append) /* don't remove when appending */
4398 mch_remove(wfname);
4399 continue;
4400 }
4401 }
4402 }
4403
4404restore_backup:
4405 {
4406 struct stat st;
4407
4408 /*
4409 * If we failed to open the file, we don't need a backup. Throw it
4410 * away. If we moved or removed the original file try to put the
4411 * backup in its place.
4412 */
4413 if (backup != NULL && wfname == fname)
4414 {
4415 if (backup_copy)
4416 {
4417 /*
4418 * There is a small chance that we removed the original,
4419 * try to move the copy in its place.
4420 * This may not work if the vim_rename() fails.
4421 * In that case we leave the copy around.
4422 */
4423 /* If file does not exist, put the copy in its place */
4424 if (mch_stat((char *)fname, &st) < 0)
4425 vim_rename(backup, fname);
4426 /* if original file does exist throw away the copy */
4427 if (mch_stat((char *)fname, &st) >= 0)
4428 mch_remove(backup);
4429 }
4430 else
4431 {
4432 /* try to put the original file back */
4433 vim_rename(backup, fname);
4434 }
4435 }
4436
4437 /* if original file no longer exists give an extra warning */
4438 if (!newfile && mch_stat((char *)fname, &st) < 0)
4439 end = 0;
4440 }
4441
4442#ifdef FEAT_MBYTE
4443 if (wfname != fname)
4444 vim_free(wfname);
4445#endif
4446 goto fail;
4447 }
4448 errmsg = NULL;
4449
4450#if defined(MACOS_CLASSIC) || defined(WIN3264)
4451 /* TODO: Is it need for MACOS_X? (Dany) */
4452 /*
4453 * On macintosh copy the original files attributes (i.e. the backup)
Bram Moolenaar7263a772007-05-10 17:35:54 +00004454 * This is done in order to preserve the resource fork and the
4455 * Finder attribute (label, comments, custom icons, file creator)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004456 */
4457 if (backup != NULL && overwriting && !append)
4458 {
4459 if (backup_copy)
4460 (void)mch_copy_file_attribute(wfname, backup);
4461 else
4462 (void)mch_copy_file_attribute(backup, wfname);
4463 }
4464
4465 if (!overwriting && !append)
4466 {
4467 if (buf->b_ffname != NULL)
4468 (void)mch_copy_file_attribute(buf->b_ffname, wfname);
Bram Moolenaar7263a772007-05-10 17:35:54 +00004469 /* Should copy resource fork */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004470 }
4471#endif
4472
4473 write_info.bw_fd = fd;
4474
4475#ifdef FEAT_CRYPT
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004476 if (*buf->b_p_key != NUL && !filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004477 {
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02004478 char_u *header;
4479 int header_len;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004480
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02004481 header = prepare_crypt_write(buf, &header_len);
4482 if (header == NULL)
4483 end = 0;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004484 else
4485 {
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02004486 /* Write magic number, so that Vim knows that this file is
4487 * encrypted when reading it again. This also undergoes utf-8 to
4488 * ucs-2/4 conversion when needed. */
4489 write_info.bw_buf = header;
4490 write_info.bw_len = header_len;
4491 write_info.bw_flags = FIO_NOCONVERT;
4492 if (buf_write_bytes(&write_info) == FAIL)
4493 end = 0;
4494 wb_flags |= FIO_ENCRYPTED;
4495 vim_free(header);
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004496 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004497 }
4498#endif
4499
4500 write_info.bw_buf = buffer;
4501 nchars = 0;
4502
4503 /* use "++bin", "++nobin" or 'binary' */
4504 if (eap != NULL && eap->force_bin != 0)
4505 write_bin = (eap->force_bin == FORCE_BIN);
4506 else
4507 write_bin = buf->b_p_bin;
4508
4509#ifdef FEAT_MBYTE
4510 /*
4511 * The BOM is written just after the encryption magic number.
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004512 * Skip it when appending and the file already existed, the BOM only makes
4513 * sense at the start of the file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004514 */
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004515 if (buf->b_p_bomb && !write_bin && (!append || perm < 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004516 {
4517 write_info.bw_len = make_bom(buffer, fenc);
4518 if (write_info.bw_len > 0)
4519 {
4520 /* don't convert, do encryption */
4521 write_info.bw_flags = FIO_NOCONVERT | wb_flags;
4522 if (buf_write_bytes(&write_info) == FAIL)
4523 end = 0;
4524 else
4525 nchars += write_info.bw_len;
4526 }
4527 }
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004528 write_info.bw_start_lnum = start;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004529#endif
4530
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004531#ifdef FEAT_PERSISTENT_UNDO
4532 write_undo_file = (buf->b_p_udf && overwriting && !append
4533 && !filtering && reset_changed);
4534 if (write_undo_file)
4535 /* Prepare for computing the hash value of the text. */
4536 sha256_start(&sha_ctx);
4537#endif
4538
Bram Moolenaar071d4272004-06-13 20:20:40 +00004539 write_info.bw_len = bufsize;
4540#ifdef HAS_BW_FLAGS
4541 write_info.bw_flags = wb_flags;
4542#endif
4543 fileformat = get_fileformat_force(buf, eap);
4544 s = buffer;
4545 len = 0;
4546 for (lnum = start; lnum <= end; ++lnum)
4547 {
4548 /*
4549 * The next while loop is done once for each character written.
4550 * Keep it fast!
4551 */
4552 ptr = ml_get_buf(buf, lnum, FALSE) - 1;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004553#ifdef FEAT_PERSISTENT_UNDO
4554 if (write_undo_file)
Bram Moolenaar442b4222010-05-24 21:34:22 +02004555 sha256_update(&sha_ctx, ptr + 1, (UINT32_T)(STRLEN(ptr + 1) + 1));
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004556#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004557 while ((c = *++ptr) != NUL)
4558 {
4559 if (c == NL)
4560 *s = NUL; /* replace newlines with NULs */
4561 else if (c == CAR && fileformat == EOL_MAC)
4562 *s = NL; /* Mac: replace CRs with NLs */
4563 else
4564 *s = c;
4565 ++s;
4566 if (++len != bufsize)
4567 continue;
4568 if (buf_write_bytes(&write_info) == FAIL)
4569 {
4570 end = 0; /* write error: break loop */
4571 break;
4572 }
4573 nchars += bufsize;
4574 s = buffer;
4575 len = 0;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004576#ifdef FEAT_MBYTE
4577 write_info.bw_start_lnum = lnum;
4578#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004579 }
4580 /* write failed or last line has no EOL: stop here */
4581 if (end == 0
4582 || (lnum == end
4583 && write_bin
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004584 && (lnum == buf->b_no_eol_lnum
Bram Moolenaar071d4272004-06-13 20:20:40 +00004585 || (lnum == buf->b_ml.ml_line_count && !buf->b_p_eol))))
4586 {
4587 ++lnum; /* written the line, count it */
4588 no_eol = TRUE;
4589 break;
4590 }
4591 if (fileformat == EOL_UNIX)
4592 *s++ = NL;
4593 else
4594 {
4595 *s++ = CAR; /* EOL_MAC or EOL_DOS: write CR */
4596 if (fileformat == EOL_DOS) /* write CR-NL */
4597 {
4598 if (++len == bufsize)
4599 {
4600 if (buf_write_bytes(&write_info) == FAIL)
4601 {
4602 end = 0; /* write error: break loop */
4603 break;
4604 }
4605 nchars += bufsize;
4606 s = buffer;
4607 len = 0;
4608 }
4609 *s++ = NL;
4610 }
4611 }
4612 if (++len == bufsize && end)
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 ui_breakcheck();
4624 if (got_int)
4625 {
4626 end = 0; /* Interrupted, break loop */
4627 break;
4628 }
4629 }
4630#ifdef VMS
4631 /*
4632 * On VMS there is a problem: newlines get added when writing blocks
4633 * at a time. Fix it by writing a line at a time.
4634 * This is much slower!
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004635 * Explanation: VAX/DECC RTL insists that records in some RMS
4636 * structures end with a newline (carriage return) character, and if
4637 * they don't it adds one.
4638 * With other RMS structures it works perfect without this fix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004639 */
Bram Moolenaarb52e2602007-10-29 21:38:54 +00004640 if (buf->b_fab_rfm == FAB$C_VFC
4641 || ((buf->b_fab_rat & (FAB$M_FTN | FAB$M_CR)) != 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004642 {
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004643 int b2write;
4644
4645 buf->b_fab_mrs = (buf->b_fab_mrs == 0
4646 ? MIN(4096, bufsize)
4647 : MIN(buf->b_fab_mrs, bufsize));
4648
4649 b2write = len;
4650 while (b2write > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004651 {
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004652 write_info.bw_len = MIN(b2write, buf->b_fab_mrs);
4653 if (buf_write_bytes(&write_info) == FAIL)
4654 {
4655 end = 0;
4656 break;
4657 }
4658 b2write -= MIN(b2write, buf->b_fab_mrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004659 }
4660 write_info.bw_len = bufsize;
4661 nchars += len;
4662 s = buffer;
4663 len = 0;
4664 }
4665#endif
4666 }
4667 if (len > 0 && end > 0)
4668 {
4669 write_info.bw_len = len;
4670 if (buf_write_bytes(&write_info) == FAIL)
4671 end = 0; /* write error */
4672 nchars += len;
4673 }
4674
4675#if defined(UNIX) && defined(HAVE_FSYNC)
4676 /* On many journalling file systems there is a bug that causes both the
4677 * original and the backup file to be lost when halting the system right
4678 * after writing the file. That's because only the meta-data is
4679 * journalled. Syncing the file slows down the system, but assures it has
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004680 * been written to disk and we don't lose it.
4681 * For a device do try the fsync() but don't complain if it does not work
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00004682 * (could be a pipe).
4683 * If the 'fsync' option is FALSE, don't fsync(). Useful for laptops. */
4684 if (p_fs && fsync(fd) != 0 && !device)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004685 {
4686 errmsg = (char_u *)_("E667: Fsync failed");
4687 end = 0;
4688 }
4689#endif
4690
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004691#ifdef HAVE_SELINUX
4692 /* Probably need to set the security context. */
4693 if (!backup_copy)
4694 mch_copy_sec(backup, wfname);
4695#endif
4696
Bram Moolenaara5792f52005-11-23 21:25:05 +00004697#ifdef UNIX
4698 /* When creating a new file, set its owner/group to that of the original
4699 * file. Get the new device and inode number. */
4700 if (backup != NULL && !backup_copy)
4701 {
4702# ifdef HAVE_FCHOWN
4703 struct stat st;
4704
4705 /* don't change the owner when it's already OK, some systems remove
4706 * permission or ACL stuff */
4707 if (mch_stat((char *)wfname, &st) < 0
4708 || st.st_uid != st_old.st_uid
4709 || st.st_gid != st_old.st_gid)
4710 {
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004711 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004712 if (perm >= 0) /* set permission again, may have changed */
4713 (void)mch_setperm(wfname, perm);
4714 }
4715# endif
4716 buf_setino(buf);
4717 }
Bram Moolenaarf1726cc2009-05-13 18:48:16 +00004718 else if (!buf->b_dev_valid)
Bram Moolenaar8fa04452005-12-23 22:13:51 +00004719 /* Set the inode when creating a new file. */
4720 buf_setino(buf);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004721#endif
4722
Bram Moolenaar071d4272004-06-13 20:20:40 +00004723 if (close(fd) != 0)
4724 {
4725 errmsg = (char_u *)_("E512: Close failed");
4726 end = 0;
4727 }
4728
4729#ifdef UNIX
4730 if (made_writable)
4731 perm &= ~0200; /* reset 'w' bit for security reasons */
4732#endif
4733 if (perm >= 0) /* set perm. of new file same as old file */
4734 (void)mch_setperm(wfname, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004735#ifdef HAVE_ACL
4736 /* Probably need to set the ACL before changing the user (can't set the
4737 * ACL on a file the user doesn't own). */
4738 if (!backup_copy)
4739 mch_set_acl(wfname, acl);
4740#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004741#ifdef FEAT_CRYPT
Bram Moolenaar4cf35c22011-02-25 16:52:17 +01004742 crypt_method_used = use_crypt_method;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004743 if (wb_flags & FIO_ENCRYPTED)
4744 crypt_pop_state();
4745#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004746
Bram Moolenaar071d4272004-06-13 20:20:40 +00004747
4748#if defined(FEAT_MBYTE) && defined(FEAT_EVAL)
4749 if (wfname != fname)
4750 {
4751 /*
4752 * The file was written to a temp file, now it needs to be converted
4753 * with 'charconvert' to (overwrite) the output file.
4754 */
4755 if (end != 0)
4756 {
4757 if (eval_charconvert(enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc,
4758 wfname, fname) == FAIL)
4759 {
4760 write_info.bw_conv_error = TRUE;
4761 end = 0;
4762 }
4763 }
4764 mch_remove(wfname);
4765 vim_free(wfname);
4766 }
4767#endif
4768
4769 if (end == 0)
4770 {
4771 if (errmsg == NULL)
4772 {
4773#ifdef FEAT_MBYTE
4774 if (write_info.bw_conv_error)
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004775 {
4776 if (write_info.bw_conv_error_lnum == 0)
4777 errmsg = (char_u *)_("E513: write error, conversion failed (make 'fenc' empty to override)");
4778 else
4779 {
4780 errmsg_allocated = TRUE;
4781 errmsg = alloc(300);
4782 vim_snprintf((char *)errmsg, 300, _("E513: write error, conversion failed in line %ld (make 'fenc' empty to override)"),
4783 (long)write_info.bw_conv_error_lnum);
4784 }
4785 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004786 else
4787#endif
4788 if (got_int)
4789 errmsg = (char_u *)_(e_interr);
4790 else
4791 errmsg = (char_u *)_("E514: write error (file system full?)");
4792 }
4793
4794 /*
4795 * If we have a backup file, try to put it in place of the new file,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004796 * because the new file is probably corrupt. This avoids losing the
Bram Moolenaar071d4272004-06-13 20:20:40 +00004797 * original file when trying to make a backup when writing the file a
4798 * second time.
4799 * When "backup_copy" is set we need to copy the backup over the new
4800 * file. Otherwise rename the backup file.
4801 * If this is OK, don't give the extra warning message.
4802 */
4803 if (backup != NULL)
4804 {
4805 if (backup_copy)
4806 {
4807 /* This may take a while, if we were interrupted let the user
4808 * know we got the message. */
4809 if (got_int)
4810 {
4811 MSG(_(e_interr));
4812 out_flush();
4813 }
4814 if ((fd = mch_open((char *)backup, O_RDONLY | O_EXTRA, 0)) >= 0)
4815 {
4816 if ((write_info.bw_fd = mch_open((char *)fname,
Bram Moolenaar9be038d2005-03-08 22:34:32 +00004817 O_WRONLY | O_CREAT | O_TRUNC | O_EXTRA,
4818 perm & 0777)) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004819 {
4820 /* copy the file. */
4821 write_info.bw_buf = smallbuf;
4822#ifdef HAS_BW_FLAGS
4823 write_info.bw_flags = FIO_NOCONVERT;
4824#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004825 while ((write_info.bw_len = read_eintr(fd, smallbuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004826 SMBUFSIZE)) > 0)
4827 if (buf_write_bytes(&write_info) == FAIL)
4828 break;
4829
4830 if (close(write_info.bw_fd) >= 0
4831 && write_info.bw_len == 0)
4832 end = 1; /* success */
4833 }
4834 close(fd); /* ignore errors for closing read file */
4835 }
4836 }
4837 else
4838 {
4839 if (vim_rename(backup, fname) == 0)
4840 end = 1;
4841 }
4842 }
4843 goto fail;
4844 }
4845
4846 lnum -= start; /* compute number of written lines */
4847 --no_wait_return; /* may wait for return now */
4848
4849#if !(defined(UNIX) || defined(VMS))
4850 fname = sfname; /* use shortname now, for the messages */
4851#endif
4852 if (!filtering)
4853 {
4854 msg_add_fname(buf, fname); /* put fname in IObuff with quotes */
4855 c = FALSE;
4856#ifdef FEAT_MBYTE
4857 if (write_info.bw_conv_error)
4858 {
4859 STRCAT(IObuff, _(" CONVERSION ERROR"));
4860 c = TRUE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004861 if (write_info.bw_conv_error_lnum != 0)
Bram Moolenaara800b422010-06-27 01:15:55 +02004862 vim_snprintf_add((char *)IObuff, IOSIZE, _(" in line %ld;"),
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004863 (long)write_info.bw_conv_error_lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004864 }
4865 else if (notconverted)
4866 {
4867 STRCAT(IObuff, _("[NOT converted]"));
4868 c = TRUE;
4869 }
4870 else if (converted)
4871 {
4872 STRCAT(IObuff, _("[converted]"));
4873 c = TRUE;
4874 }
4875#endif
4876 if (device)
4877 {
4878 STRCAT(IObuff, _("[Device]"));
4879 c = TRUE;
4880 }
4881 else if (newfile)
4882 {
4883 STRCAT(IObuff, shortmess(SHM_NEW) ? _("[New]") : _("[New File]"));
4884 c = TRUE;
4885 }
4886 if (no_eol)
4887 {
4888 msg_add_eol();
4889 c = TRUE;
4890 }
4891 /* may add [unix/dos/mac] */
4892 if (msg_add_fileformat(fileformat))
4893 c = TRUE;
4894#ifdef FEAT_CRYPT
4895 if (wb_flags & FIO_ENCRYPTED)
4896 {
Bram Moolenaar4cf35c22011-02-25 16:52:17 +01004897 if (crypt_method_used == 1)
4898 STRCAT(IObuff, _("[blowfish]"));
4899 else
4900 STRCAT(IObuff, _("[crypted]"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004901 c = TRUE;
4902 }
4903#endif
4904 msg_add_lines(c, (long)lnum, nchars); /* add line/char count */
4905 if (!shortmess(SHM_WRITE))
4906 {
4907 if (append)
4908 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended"));
4909 else
4910 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written"));
4911 }
4912
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00004913 set_keep_msg(msg_trunc_attr(IObuff, FALSE, 0), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004914 }
4915
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004916 /* When written everything correctly: reset 'modified'. Unless not
4917 * writing to the original file and '+' is not in 'cpoptions'. */
Bram Moolenaar292ad192005-12-11 21:29:51 +00004918 if (reset_changed && whole && !append
Bram Moolenaar071d4272004-06-13 20:20:40 +00004919#ifdef FEAT_MBYTE
4920 && !write_info.bw_conv_error
4921#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004922 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL)
4923 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004924 {
4925 unchanged(buf, TRUE);
4926 u_unchanged(buf);
Bram Moolenaar730cde92010-06-27 05:18:54 +02004927 u_update_save_nr(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004928 }
4929
4930 /*
4931 * If written to the current file, update the timestamp of the swap file
4932 * and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
4933 */
4934 if (overwriting)
4935 {
4936 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00004937 if (append)
4938 buf->b_flags &= ~BF_NEW;
4939 else
4940 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004941 }
4942
4943 /*
4944 * If we kept a backup until now, and we are in patch mode, then we make
4945 * the backup file our 'original' file.
4946 */
4947 if (*p_pm && dobackup)
4948 {
4949 char *org = (char *)buf_modname(
4950#ifdef SHORT_FNAME
4951 TRUE,
4952#else
4953 (buf->b_p_sn || buf->b_shortname),
4954#endif
4955 fname, p_pm, FALSE);
4956
4957 if (backup != NULL)
4958 {
4959 struct stat st;
4960
4961 /*
4962 * If the original file does not exist yet
4963 * the current backup file becomes the original file
4964 */
4965 if (org == NULL)
4966 EMSG(_("E205: Patchmode: can't save original file"));
4967 else if (mch_stat(org, &st) < 0)
4968 {
4969 vim_rename(backup, (char_u *)org);
4970 vim_free(backup); /* don't delete the file */
4971 backup = NULL;
4972#ifdef UNIX
4973 set_file_time((char_u *)org, st_old.st_atime, st_old.st_mtime);
4974#endif
4975 }
4976 }
4977 /*
4978 * If there is no backup file, remember that a (new) file was
4979 * created.
4980 */
4981 else
4982 {
4983 int empty_fd;
4984
4985 if (org == NULL
Bram Moolenaara5792f52005-11-23 21:25:05 +00004986 || (empty_fd = mch_open(org,
4987 O_CREAT | O_EXTRA | O_EXCL | O_NOFOLLOW,
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00004988 perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004989 EMSG(_("E206: patchmode: can't touch empty original file"));
4990 else
4991 close(empty_fd);
4992 }
4993 if (org != NULL)
4994 {
4995 mch_setperm((char_u *)org, mch_getperm(fname) & 0777);
4996 vim_free(org);
4997 }
4998 }
4999
5000 /*
5001 * Remove the backup unless 'backup' option is set
5002 */
5003 if (!p_bk && backup != NULL && mch_remove(backup) != 0)
5004 EMSG(_("E207: Can't delete backup file"));
5005
5006#ifdef FEAT_SUN_WORKSHOP
5007 if (usingSunWorkShop)
5008 workshop_file_saved((char *) ffname);
5009#endif
5010
5011 goto nofail;
5012
5013 /*
5014 * Finish up. We get here either after failure or success.
5015 */
5016fail:
5017 --no_wait_return; /* may wait for return now */
5018nofail:
5019
5020 /* Done saving, we accept changed buffer warnings again */
5021 buf->b_saving = FALSE;
5022
5023 vim_free(backup);
5024 if (buffer != smallbuf)
5025 vim_free(buffer);
5026#ifdef FEAT_MBYTE
5027 vim_free(fenc_tofree);
5028 vim_free(write_info.bw_conv_buf);
5029# ifdef USE_ICONV
5030 if (write_info.bw_iconv_fd != (iconv_t)-1)
5031 {
5032 iconv_close(write_info.bw_iconv_fd);
5033 write_info.bw_iconv_fd = (iconv_t)-1;
5034 }
5035# endif
5036#endif
5037#ifdef HAVE_ACL
5038 mch_free_acl(acl);
5039#endif
5040
5041 if (errmsg != NULL)
5042 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005043 int numlen = errnum != NULL ? (int)STRLEN(errnum) : 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005044
5045 attr = hl_attr(HLF_E); /* set highlight for error messages */
5046 msg_add_fname(buf,
5047#ifndef UNIX
5048 sfname
5049#else
5050 fname
5051#endif
5052 ); /* put file name in IObuff with quotes */
5053 if (STRLEN(IObuff) + STRLEN(errmsg) + numlen >= IOSIZE)
5054 IObuff[IOSIZE - STRLEN(errmsg) - numlen - 1] = NUL;
5055 /* If the error message has the form "is ...", put the error number in
5056 * front of the file name. */
5057 if (errnum != NULL)
5058 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00005059 STRMOVE(IObuff + numlen, IObuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005060 mch_memmove(IObuff, errnum, (size_t)numlen);
5061 }
5062 STRCAT(IObuff, errmsg);
5063 emsg(IObuff);
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005064 if (errmsg_allocated)
5065 vim_free(errmsg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005066
5067 retval = FAIL;
5068 if (end == 0)
5069 {
5070 MSG_PUTS_ATTR(_("\nWARNING: Original file may be lost or damaged\n"),
5071 attr | MSG_HIST);
5072 MSG_PUTS_ATTR(_("don't quit the editor until the file is successfully written!"),
5073 attr | MSG_HIST);
5074
5075 /* Update the timestamp to avoid an "overwrite changed file"
5076 * prompt when writing again. */
5077 if (mch_stat((char *)fname, &st_old) >= 0)
5078 {
5079 buf_store_time(buf, &st_old, fname);
5080 buf->b_mtime_read = buf->b_mtime;
5081 }
5082 }
5083 }
5084 msg_scroll = msg_save;
5085
Bram Moolenaar55debbe2010-05-23 23:34:36 +02005086#ifdef FEAT_PERSISTENT_UNDO
5087 /*
5088 * When writing the whole file and 'undofile' is set, also write the undo
5089 * file.
5090 */
5091 if (retval == OK && write_undo_file)
5092 {
5093 char_u hash[UNDO_HASH_SIZE];
5094
5095 sha256_finish(&sha_ctx, hash);
5096 u_write_undo(NULL, FALSE, buf, hash);
5097 }
5098#endif
5099
Bram Moolenaar071d4272004-06-13 20:20:40 +00005100#ifdef FEAT_AUTOCMD
5101#ifdef FEAT_EVAL
5102 if (!should_abort(retval))
5103#else
5104 if (!got_int)
5105#endif
5106 {
5107 aco_save_T aco;
5108
Bram Moolenaar68a33fc2012-04-25 16:50:48 +02005109 curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */
5110
Bram Moolenaar071d4272004-06-13 20:20:40 +00005111 /*
5112 * Apply POST autocommands.
5113 * Careful: The autocommands may call buf_write() recursively!
5114 */
5115 aucmd_prepbuf(&aco, buf);
5116
5117 if (append)
5118 apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname,
5119 FALSE, curbuf, eap);
5120 else if (filtering)
5121 apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname,
5122 FALSE, curbuf, eap);
5123 else if (reset_changed && whole)
5124 apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname,
5125 FALSE, curbuf, eap);
5126 else
5127 apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname,
5128 FALSE, curbuf, eap);
5129
5130 /* restore curwin/curbuf and a few other things */
5131 aucmd_restbuf(&aco);
5132
5133#ifdef FEAT_EVAL
5134 if (aborting()) /* autocmds may abort script processing */
5135 retval = FALSE;
5136#endif
5137 }
5138#endif
5139
5140 got_int |= prev_got_int;
5141
5142#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
5143 /* Update machine specific information. */
5144 mch_post_buffer_write(buf);
5145#endif
5146 return retval;
5147}
5148
5149/*
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005150 * Set the name of the current buffer. Use when the buffer doesn't have a
5151 * name and a ":r" or ":w" command with a file name is used.
5152 */
5153 static int
5154set_rw_fname(fname, sfname)
5155 char_u *fname;
5156 char_u *sfname;
5157{
5158#ifdef FEAT_AUTOCMD
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005159 buf_T *buf = curbuf;
5160
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005161 /* It's like the unnamed buffer is deleted.... */
5162 if (curbuf->b_p_bl)
5163 apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
5164 apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf);
5165# ifdef FEAT_EVAL
5166 if (aborting()) /* autocmds may abort script processing */
5167 return FAIL;
5168# endif
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005169 if (curbuf != buf)
5170 {
5171 /* We are in another buffer now, don't do the renaming. */
5172 EMSG(_(e_auchangedbuf));
5173 return FAIL;
5174 }
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005175#endif
5176
5177 if (setfname(curbuf, fname, sfname, FALSE) == OK)
5178 curbuf->b_flags |= BF_NOTEDITED;
5179
5180#ifdef FEAT_AUTOCMD
5181 /* ....and a new named one is created */
5182 apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, curbuf);
5183 if (curbuf->b_p_bl)
5184 apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf);
5185# ifdef FEAT_EVAL
5186 if (aborting()) /* autocmds may abort script processing */
5187 return FAIL;
5188# endif
5189
5190 /* Do filetype detection now if 'filetype' is empty. */
5191 if (*curbuf->b_p_ft == NUL)
5192 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005193 if (au_has_group((char_u *)"filetypedetect"))
Bram Moolenaar70836c82006-02-20 21:28:49 +00005194 (void)do_doautocmd((char_u *)"filetypedetect BufRead", FALSE);
Bram Moolenaara3227e22006-03-08 21:32:40 +00005195 do_modelines(0);
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005196 }
5197#endif
5198
5199 return OK;
5200}
5201
5202/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00005203 * Put file name into IObuff with quotes.
5204 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005205 void
Bram Moolenaar071d4272004-06-13 20:20:40 +00005206msg_add_fname(buf, fname)
5207 buf_T *buf;
5208 char_u *fname;
5209{
5210 if (fname == NULL)
5211 fname = (char_u *)"-stdin-";
5212 home_replace(buf, fname, IObuff + 1, IOSIZE - 4, TRUE);
5213 IObuff[0] = '"';
5214 STRCAT(IObuff, "\" ");
5215}
5216
5217/*
5218 * Append message for text mode to IObuff.
5219 * Return TRUE if something appended.
5220 */
5221 static int
5222msg_add_fileformat(eol_type)
5223 int eol_type;
5224{
5225#ifndef USE_CRNL
5226 if (eol_type == EOL_DOS)
5227 {
5228 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[dos]") : _("[dos format]"));
5229 return TRUE;
5230 }
5231#endif
5232#ifndef USE_CR
5233 if (eol_type == EOL_MAC)
5234 {
5235 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[mac]") : _("[mac format]"));
5236 return TRUE;
5237 }
5238#endif
5239#if defined(USE_CRNL) || defined(USE_CR)
5240 if (eol_type == EOL_UNIX)
5241 {
5242 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[unix]") : _("[unix format]"));
5243 return TRUE;
5244 }
5245#endif
5246 return FALSE;
5247}
5248
5249/*
5250 * Append line and character count to IObuff.
5251 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005252 void
Bram Moolenaar071d4272004-06-13 20:20:40 +00005253msg_add_lines(insert_space, lnum, nchars)
5254 int insert_space;
5255 long lnum;
Bram Moolenaar914703b2010-05-31 21:59:46 +02005256 off_t nchars;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005257{
5258 char_u *p;
5259
5260 p = IObuff + STRLEN(IObuff);
5261
5262 if (insert_space)
5263 *p++ = ' ';
5264 if (shortmess(SHM_LINES))
Bram Moolenaar914703b2010-05-31 21:59:46 +02005265 sprintf((char *)p,
5266#ifdef LONG_LONG_OFF_T
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005267 "%ldL, %lldC", lnum, nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005268#else
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005269 /* Explicit typecast avoids warning on Mac OS X 10.6 */
5270 "%ldL, %ldC", lnum, (long)nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005271#endif
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005272 );
Bram Moolenaar071d4272004-06-13 20:20:40 +00005273 else
5274 {
5275 if (lnum == 1)
5276 STRCPY(p, _("1 line, "));
5277 else
5278 sprintf((char *)p, _("%ld lines, "), lnum);
5279 p += STRLEN(p);
5280 if (nchars == 1)
5281 STRCPY(p, _("1 character"));
5282 else
Bram Moolenaar914703b2010-05-31 21:59:46 +02005283 sprintf((char *)p,
5284#ifdef LONG_LONG_OFF_T
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005285 _("%lld characters"), nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005286#else
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005287 /* Explicit typecast avoids warning on Mac OS X 10.6 */
5288 _("%ld characters"), (long)nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005289#endif
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005290 );
Bram Moolenaar071d4272004-06-13 20:20:40 +00005291 }
5292}
5293
5294/*
5295 * Append message for missing line separator to IObuff.
5296 */
5297 static void
5298msg_add_eol()
5299{
5300 STRCAT(IObuff, shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]"));
5301}
5302
5303/*
5304 * Check modification time of file, before writing to it.
5305 * The size isn't checked, because using a tool like "gzip" takes care of
5306 * using the same timestamp but can't set the size.
5307 */
5308 static int
5309check_mtime(buf, st)
5310 buf_T *buf;
5311 struct stat *st;
5312{
5313 if (buf->b_mtime_read != 0
5314 && time_differs((long)st->st_mtime, buf->b_mtime_read))
5315 {
5316 msg_scroll = TRUE; /* don't overwrite messages here */
5317 msg_silent = 0; /* must give this prompt */
5318 /* don't use emsg() here, don't want to flush the buffers */
5319 MSG_ATTR(_("WARNING: The file has been changed since reading it!!!"),
5320 hl_attr(HLF_E));
5321 if (ask_yesno((char_u *)_("Do you really want to write to it"),
5322 TRUE) == 'n')
5323 return FAIL;
5324 msg_scroll = FALSE; /* always overwrite the file message now */
5325 }
5326 return OK;
5327}
5328
5329 static int
5330time_differs(t1, t2)
5331 long t1, t2;
5332{
5333#if defined(__linux__) || defined(MSDOS) || defined(MSWIN)
5334 /* On a FAT filesystem, esp. under Linux, there are only 5 bits to store
5335 * the seconds. Since the roundoff is done when flushing the inode, the
5336 * time may change unexpectedly by one second!!! */
5337 return (t1 - t2 > 1 || t2 - t1 > 1);
5338#else
5339 return (t1 != t2);
5340#endif
5341}
5342
5343/*
5344 * Call write() to write a number of bytes to the file.
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005345 * Handles encryption and 'encoding' conversion.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005346 *
5347 * Return FAIL for failure, OK otherwise.
5348 */
5349 static int
5350buf_write_bytes(ip)
5351 struct bw_info *ip;
5352{
5353 int wlen;
5354 char_u *buf = ip->bw_buf; /* data to write */
5355 int len = ip->bw_len; /* length of data */
5356#ifdef HAS_BW_FLAGS
5357 int flags = ip->bw_flags; /* extra flags */
5358#endif
5359
5360#ifdef FEAT_MBYTE
5361 /*
5362 * Skip conversion when writing the crypt magic number or the BOM.
5363 */
5364 if (!(flags & FIO_NOCONVERT))
5365 {
5366 char_u *p;
5367 unsigned c;
5368 int n;
5369
5370 if (flags & FIO_UTF8)
5371 {
5372 /*
5373 * Convert latin1 in the buffer to UTF-8 in the file.
5374 */
5375 p = ip->bw_conv_buf; /* translate to buffer */
5376 for (wlen = 0; wlen < len; ++wlen)
5377 p += utf_char2bytes(buf[wlen], p);
5378 buf = ip->bw_conv_buf;
5379 len = (int)(p - ip->bw_conv_buf);
5380 }
5381 else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1))
5382 {
5383 /*
5384 * Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
5385 * Latin1 chars in the file.
5386 */
5387 if (flags & FIO_LATIN1)
5388 p = buf; /* translate in-place (can only get shorter) */
5389 else
5390 p = ip->bw_conv_buf; /* translate to buffer */
5391 for (wlen = 0; wlen < len; wlen += n)
5392 {
5393 if (wlen == 0 && ip->bw_restlen != 0)
5394 {
5395 int l;
5396
5397 /* Use remainder of previous call. Append the start of
5398 * buf[] to get a full sequence. Might still be too
5399 * short! */
5400 l = CONV_RESTLEN - ip->bw_restlen;
5401 if (l > len)
5402 l = len;
5403 mch_memmove(ip->bw_rest + ip->bw_restlen, buf, (size_t)l);
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005404 n = utf_ptr2len_len(ip->bw_rest, ip->bw_restlen + l);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005405 if (n > ip->bw_restlen + len)
5406 {
5407 /* We have an incomplete byte sequence at the end to
5408 * be written. We can't convert it without the
5409 * remaining bytes. Keep them for the next call. */
5410 if (ip->bw_restlen + len > CONV_RESTLEN)
5411 return FAIL;
5412 ip->bw_restlen += len;
5413 break;
5414 }
5415 if (n > 1)
5416 c = utf_ptr2char(ip->bw_rest);
5417 else
5418 c = ip->bw_rest[0];
5419 if (n >= ip->bw_restlen)
5420 {
5421 n -= ip->bw_restlen;
5422 ip->bw_restlen = 0;
5423 }
5424 else
5425 {
5426 ip->bw_restlen -= n;
5427 mch_memmove(ip->bw_rest, ip->bw_rest + n,
5428 (size_t)ip->bw_restlen);
5429 n = 0;
5430 }
5431 }
5432 else
5433 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005434 n = utf_ptr2len_len(buf + wlen, len - wlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005435 if (n > len - wlen)
5436 {
5437 /* We have an incomplete byte sequence at the end to
5438 * be written. We can't convert it without the
5439 * remaining bytes. Keep them for the next call. */
5440 if (len - wlen > CONV_RESTLEN)
5441 return FAIL;
5442 ip->bw_restlen = len - wlen;
5443 mch_memmove(ip->bw_rest, buf + wlen,
5444 (size_t)ip->bw_restlen);
5445 break;
5446 }
5447 if (n > 1)
5448 c = utf_ptr2char(buf + wlen);
5449 else
5450 c = buf[wlen];
5451 }
5452
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005453 if (ucs2bytes(c, &p, flags) && !ip->bw_conv_error)
5454 {
5455 ip->bw_conv_error = TRUE;
5456 ip->bw_conv_error_lnum = ip->bw_start_lnum;
5457 }
5458 if (c == NL)
5459 ++ip->bw_start_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005460 }
5461 if (flags & FIO_LATIN1)
5462 len = (int)(p - buf);
5463 else
5464 {
5465 buf = ip->bw_conv_buf;
5466 len = (int)(p - ip->bw_conv_buf);
5467 }
5468 }
5469
5470# ifdef WIN3264
5471 else if (flags & FIO_CODEPAGE)
5472 {
5473 /*
5474 * Convert UTF-8 or codepage to UCS-2 and then to MS-Windows
5475 * codepage.
5476 */
5477 char_u *from;
5478 size_t fromlen;
5479 char_u *to;
5480 int u8c;
5481 BOOL bad = FALSE;
5482 int needed;
5483
5484 if (ip->bw_restlen > 0)
5485 {
5486 /* Need to concatenate the remainder of the previous call and
5487 * the bytes of the current call. Use the end of the
5488 * conversion buffer for this. */
5489 fromlen = len + ip->bw_restlen;
5490 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5491 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5492 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5493 }
5494 else
5495 {
5496 from = buf;
5497 fromlen = len;
5498 }
5499
5500 to = ip->bw_conv_buf;
5501 if (enc_utf8)
5502 {
5503 /* Convert from UTF-8 to UCS-2, to the start of the buffer.
5504 * The buffer has been allocated to be big enough. */
5505 while (fromlen > 0)
5506 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005507 n = (int)utf_ptr2len_len(from, (int)fromlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005508 if (n > (int)fromlen) /* incomplete byte sequence */
5509 break;
5510 u8c = utf_ptr2char(from);
5511 *to++ = (u8c & 0xff);
5512 *to++ = (u8c >> 8);
5513 fromlen -= n;
5514 from += n;
5515 }
5516
5517 /* Copy remainder to ip->bw_rest[] to be used for the next
5518 * call. */
5519 if (fromlen > CONV_RESTLEN)
5520 {
5521 /* weird overlong sequence */
5522 ip->bw_conv_error = TRUE;
5523 return FAIL;
5524 }
5525 mch_memmove(ip->bw_rest, from, fromlen);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005526 ip->bw_restlen = (int)fromlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005527 }
5528 else
5529 {
5530 /* Convert from enc_codepage to UCS-2, to the start of the
5531 * buffer. The buffer has been allocated to be big enough. */
5532 ip->bw_restlen = 0;
5533 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005534 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005535 NULL, 0);
5536 if (needed == 0)
5537 {
5538 /* When conversion fails there may be a trailing byte. */
5539 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005540 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen - 1,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005541 NULL, 0);
5542 if (needed == 0)
5543 {
5544 /* Conversion doesn't work. */
5545 ip->bw_conv_error = TRUE;
5546 return FAIL;
5547 }
5548 /* Save the trailing byte for the next call. */
5549 ip->bw_rest[0] = from[fromlen - 1];
5550 ip->bw_restlen = 1;
5551 }
5552 needed = MultiByteToWideChar(enc_codepage, MB_ERR_INVALID_CHARS,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005553 (LPCSTR)from, (int)(fromlen - ip->bw_restlen),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005554 (LPWSTR)to, needed);
5555 if (needed == 0)
5556 {
5557 /* Safety check: Conversion doesn't work. */
5558 ip->bw_conv_error = TRUE;
5559 return FAIL;
5560 }
5561 to += needed * 2;
5562 }
5563
5564 fromlen = to - ip->bw_conv_buf;
5565 buf = to;
5566# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5567 if (FIO_GET_CP(flags) == CP_UTF8)
5568 {
5569 /* Convert from UCS-2 to UTF-8, using the remainder of the
5570 * conversion buffer. Fails when out of space. */
5571 for (from = ip->bw_conv_buf; fromlen > 1; fromlen -= 2)
5572 {
5573 u8c = *from++;
5574 u8c += (*from++ << 8);
5575 to += utf_char2bytes(u8c, to);
5576 if (to + 6 >= ip->bw_conv_buf + ip->bw_conv_buflen)
5577 {
5578 ip->bw_conv_error = TRUE;
5579 return FAIL;
5580 }
5581 }
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005582 len = (int)(to - buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005583 }
5584 else
5585#endif
5586 {
5587 /* Convert from UCS-2 to the codepage, using the remainder of
5588 * the conversion buffer. If the conversion uses the default
5589 * character "0", the data doesn't fit in this encoding, so
5590 * fail. */
5591 len = WideCharToMultiByte(FIO_GET_CP(flags), 0,
5592 (LPCWSTR)ip->bw_conv_buf, (int)fromlen / sizeof(WCHAR),
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005593 (LPSTR)to, (int)(ip->bw_conv_buflen - fromlen), 0,
5594 &bad);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005595 if (bad)
5596 {
5597 ip->bw_conv_error = TRUE;
5598 return FAIL;
5599 }
5600 }
5601 }
5602# endif
5603
Bram Moolenaar56718732006-03-15 22:53:57 +00005604# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00005605 else if (flags & FIO_MACROMAN)
5606 {
5607 /*
5608 * Convert UTF-8 or latin1 to Apple MacRoman.
5609 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005610 char_u *from;
5611 size_t fromlen;
5612
5613 if (ip->bw_restlen > 0)
5614 {
5615 /* Need to concatenate the remainder of the previous call and
5616 * the bytes of the current call. Use the end of the
5617 * conversion buffer for this. */
5618 fromlen = len + ip->bw_restlen;
5619 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5620 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5621 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5622 }
5623 else
5624 {
5625 from = buf;
5626 fromlen = len;
5627 }
5628
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00005629 if (enc2macroman(from, fromlen,
5630 ip->bw_conv_buf, &len, ip->bw_conv_buflen,
5631 ip->bw_rest, &ip->bw_restlen) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005632 {
5633 ip->bw_conv_error = TRUE;
5634 return FAIL;
5635 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005636 buf = ip->bw_conv_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005637 }
5638# endif
5639
5640# ifdef USE_ICONV
5641 if (ip->bw_iconv_fd != (iconv_t)-1)
5642 {
5643 const char *from;
5644 size_t fromlen;
5645 char *to;
5646 size_t tolen;
5647
5648 /* Convert with iconv(). */
5649 if (ip->bw_restlen > 0)
5650 {
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005651 char *fp;
5652
Bram Moolenaar071d4272004-06-13 20:20:40 +00005653 /* Need to concatenate the remainder of the previous call and
5654 * the bytes of the current call. Use the end of the
5655 * conversion buffer for this. */
5656 fromlen = len + ip->bw_restlen;
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005657 fp = (char *)ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5658 mch_memmove(fp, ip->bw_rest, (size_t)ip->bw_restlen);
5659 mch_memmove(fp + ip->bw_restlen, buf, (size_t)len);
5660 from = fp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005661 tolen = ip->bw_conv_buflen - fromlen;
5662 }
5663 else
5664 {
5665 from = (const char *)buf;
5666 fromlen = len;
5667 tolen = ip->bw_conv_buflen;
5668 }
5669 to = (char *)ip->bw_conv_buf;
5670
5671 if (ip->bw_first)
5672 {
5673 size_t save_len = tolen;
5674
5675 /* output the initial shift state sequence */
5676 (void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen);
5677
5678 /* There is a bug in iconv() on Linux (which appears to be
5679 * wide-spread) which sets "to" to NULL and messes up "tolen".
5680 */
5681 if (to == NULL)
5682 {
5683 to = (char *)ip->bw_conv_buf;
5684 tolen = save_len;
5685 }
5686 ip->bw_first = FALSE;
5687 }
5688
5689 /*
5690 * If iconv() has an error or there is not enough room, fail.
5691 */
5692 if ((iconv(ip->bw_iconv_fd, (void *)&from, &fromlen, &to, &tolen)
5693 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
5694 || fromlen > CONV_RESTLEN)
5695 {
5696 ip->bw_conv_error = TRUE;
5697 return FAIL;
5698 }
5699
5700 /* copy remainder to ip->bw_rest[] to be used for the next call. */
5701 if (fromlen > 0)
5702 mch_memmove(ip->bw_rest, (void *)from, fromlen);
5703 ip->bw_restlen = (int)fromlen;
5704
5705 buf = ip->bw_conv_buf;
5706 len = (int)((char_u *)to - ip->bw_conv_buf);
5707 }
5708# endif
5709 }
5710#endif /* FEAT_MBYTE */
5711
5712#ifdef FEAT_CRYPT
5713 if (flags & FIO_ENCRYPTED) /* encrypt the data */
Bram Moolenaar04c9baf2010-06-01 23:37:39 +02005714 crypt_encode(buf, len, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005715#endif
5716
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005717 wlen = write_eintr(ip->bw_fd, buf, len);
5718 return (wlen < len) ? FAIL : OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005719}
5720
5721#ifdef FEAT_MBYTE
5722/*
5723 * Convert a Unicode character to bytes.
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005724 * Return TRUE for an error, FALSE when it's OK.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005725 */
5726 static int
5727ucs2bytes(c, pp, flags)
5728 unsigned c; /* in: character */
5729 char_u **pp; /* in/out: pointer to result */
5730 int flags; /* FIO_ flags */
5731{
5732 char_u *p = *pp;
5733 int error = FALSE;
5734 int cc;
5735
5736
5737 if (flags & FIO_UCS4)
5738 {
5739 if (flags & FIO_ENDIAN_L)
5740 {
5741 *p++ = c;
5742 *p++ = (c >> 8);
5743 *p++ = (c >> 16);
5744 *p++ = (c >> 24);
5745 }
5746 else
5747 {
5748 *p++ = (c >> 24);
5749 *p++ = (c >> 16);
5750 *p++ = (c >> 8);
5751 *p++ = c;
5752 }
5753 }
5754 else if (flags & (FIO_UCS2 | FIO_UTF16))
5755 {
5756 if (c >= 0x10000)
5757 {
5758 if (flags & FIO_UTF16)
5759 {
5760 /* Make two words, ten bits of the character in each. First
5761 * word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff */
5762 c -= 0x10000;
5763 if (c >= 0x100000)
5764 error = TRUE;
5765 cc = ((c >> 10) & 0x3ff) + 0xd800;
5766 if (flags & FIO_ENDIAN_L)
5767 {
5768 *p++ = cc;
5769 *p++ = ((unsigned)cc >> 8);
5770 }
5771 else
5772 {
5773 *p++ = ((unsigned)cc >> 8);
5774 *p++ = cc;
5775 }
5776 c = (c & 0x3ff) + 0xdc00;
5777 }
5778 else
5779 error = TRUE;
5780 }
5781 if (flags & FIO_ENDIAN_L)
5782 {
5783 *p++ = c;
5784 *p++ = (c >> 8);
5785 }
5786 else
5787 {
5788 *p++ = (c >> 8);
5789 *p++ = c;
5790 }
5791 }
5792 else /* Latin1 */
5793 {
5794 if (c >= 0x100)
5795 {
5796 error = TRUE;
5797 *p++ = 0xBF;
5798 }
5799 else
5800 *p++ = c;
5801 }
5802
5803 *pp = p;
5804 return error;
5805}
5806
5807/*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005808 * Return TRUE if file encoding "fenc" requires conversion from or to
5809 * 'encoding'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005810 */
5811 static int
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005812need_conversion(fenc)
5813 char_u *fenc;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005814{
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005815 int same_encoding;
5816 int enc_flags;
5817 int fenc_flags;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005818
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005819 if (*fenc == NUL || STRCMP(p_enc, fenc) == 0)
Bram Moolenaar442b4222010-05-24 21:34:22 +02005820 {
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005821 same_encoding = TRUE;
Bram Moolenaar442b4222010-05-24 21:34:22 +02005822 fenc_flags = 0;
5823 }
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005824 else
5825 {
5826 /* Ignore difference between "ansi" and "latin1", "ucs-4" and
5827 * "ucs-4be", etc. */
5828 enc_flags = get_fio_flags(p_enc);
5829 fenc_flags = get_fio_flags(fenc);
5830 same_encoding = (enc_flags != 0 && fenc_flags == enc_flags);
5831 }
5832 if (same_encoding)
5833 {
5834 /* Specified encoding matches with 'encoding'. This requires
5835 * conversion when 'encoding' is Unicode but not UTF-8. */
5836 return enc_unicode != 0;
5837 }
5838
5839 /* Encodings differ. However, conversion is not needed when 'enc' is any
5840 * Unicode encoding and the file is UTF-8. */
5841 return !(enc_utf8 && fenc_flags == FIO_UTF8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005842}
5843
5844/*
5845 * Check "ptr" for a unicode encoding and return the FIO_ flags needed for the
5846 * internal conversion.
5847 * if "ptr" is an empty string, use 'encoding'.
5848 */
5849 static int
5850get_fio_flags(ptr)
5851 char_u *ptr;
5852{
5853 int prop;
5854
5855 if (*ptr == NUL)
5856 ptr = p_enc;
5857
5858 prop = enc_canon_props(ptr);
5859 if (prop & ENC_UNICODE)
5860 {
5861 if (prop & ENC_2BYTE)
5862 {
5863 if (prop & ENC_ENDIAN_L)
5864 return FIO_UCS2 | FIO_ENDIAN_L;
5865 return FIO_UCS2;
5866 }
5867 if (prop & ENC_4BYTE)
5868 {
5869 if (prop & ENC_ENDIAN_L)
5870 return FIO_UCS4 | FIO_ENDIAN_L;
5871 return FIO_UCS4;
5872 }
5873 if (prop & ENC_2WORD)
5874 {
5875 if (prop & ENC_ENDIAN_L)
5876 return FIO_UTF16 | FIO_ENDIAN_L;
5877 return FIO_UTF16;
5878 }
5879 return FIO_UTF8;
5880 }
5881 if (prop & ENC_LATIN1)
5882 return FIO_LATIN1;
5883 /* must be ENC_DBCS, requires iconv() */
5884 return 0;
5885}
5886
5887#ifdef WIN3264
5888/*
5889 * Check "ptr" for a MS-Windows codepage name and return the FIO_ flags needed
5890 * for the conversion MS-Windows can do for us. Also accept "utf-8".
5891 * Used for conversion between 'encoding' and 'fileencoding'.
5892 */
5893 static int
5894get_win_fio_flags(ptr)
5895 char_u *ptr;
5896{
5897 int cp;
5898
5899 /* Cannot do this when 'encoding' is not utf-8 and not a codepage. */
5900 if (!enc_utf8 && enc_codepage <= 0)
5901 return 0;
5902
5903 cp = encname2codepage(ptr);
5904 if (cp == 0)
5905 {
5906# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5907 if (STRCMP(ptr, "utf-8") == 0)
5908 cp = CP_UTF8;
5909 else
5910# endif
5911 return 0;
5912 }
5913 return FIO_PUT_CP(cp) | FIO_CODEPAGE;
5914}
5915#endif
5916
5917#ifdef MACOS_X
5918/*
5919 * Check "ptr" for a Carbon supported encoding and return the FIO_ flags
5920 * needed for the internal conversion to/from utf-8 or latin1.
5921 */
5922 static int
5923get_mac_fio_flags(ptr)
5924 char_u *ptr;
5925{
5926 if ((enc_utf8 || STRCMP(p_enc, "latin1") == 0)
5927 && (enc_canon_props(ptr) & ENC_MACROMAN))
5928 return FIO_MACROMAN;
5929 return 0;
5930}
5931#endif
5932
5933/*
5934 * Check for a Unicode BOM (Byte Order Mark) at the start of p[size].
5935 * "size" must be at least 2.
5936 * Return the name of the encoding and set "*lenp" to the length.
5937 * Returns NULL when no BOM found.
5938 */
5939 static char_u *
5940check_for_bom(p, size, lenp, flags)
5941 char_u *p;
5942 long size;
5943 int *lenp;
5944 int flags;
5945{
5946 char *name = NULL;
5947 int len = 2;
5948
5949 if (p[0] == 0xef && p[1] == 0xbb && size >= 3 && p[2] == 0xbf
Bram Moolenaaree0f5a62008-07-24 20:09:16 +00005950 && (flags == FIO_ALL || flags == FIO_UTF8 || flags == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005951 {
5952 name = "utf-8"; /* EF BB BF */
5953 len = 3;
5954 }
5955 else if (p[0] == 0xff && p[1] == 0xfe)
5956 {
5957 if (size >= 4 && p[2] == 0 && p[3] == 0
5958 && (flags == FIO_ALL || flags == (FIO_UCS4 | FIO_ENDIAN_L)))
5959 {
5960 name = "ucs-4le"; /* FF FE 00 00 */
5961 len = 4;
5962 }
Bram Moolenaar223a1892008-11-11 20:57:11 +00005963 else if (flags == (FIO_UCS2 | FIO_ENDIAN_L))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005964 name = "ucs-2le"; /* FF FE */
Bram Moolenaar223a1892008-11-11 20:57:11 +00005965 else if (flags == FIO_ALL || flags == (FIO_UTF16 | FIO_ENDIAN_L))
5966 /* utf-16le is preferred, it also works for ucs-2le text */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005967 name = "utf-16le"; /* FF FE */
5968 }
5969 else if (p[0] == 0xfe && p[1] == 0xff
5970 && (flags == FIO_ALL || flags == FIO_UCS2 || flags == FIO_UTF16))
5971 {
Bram Moolenaarffd82c52008-02-20 17:15:26 +00005972 /* Default to utf-16, it works also for ucs-2 text. */
5973 if (flags == FIO_UCS2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005974 name = "ucs-2"; /* FE FF */
Bram Moolenaarffd82c52008-02-20 17:15:26 +00005975 else
5976 name = "utf-16"; /* FE FF */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005977 }
5978 else if (size >= 4 && p[0] == 0 && p[1] == 0 && p[2] == 0xfe
5979 && p[3] == 0xff && (flags == FIO_ALL || flags == FIO_UCS4))
5980 {
5981 name = "ucs-4"; /* 00 00 FE FF */
5982 len = 4;
5983 }
5984
5985 *lenp = len;
5986 return (char_u *)name;
5987}
5988
5989/*
5990 * Generate a BOM in "buf[4]" for encoding "name".
5991 * Return the length of the BOM (zero when no BOM).
5992 */
5993 static int
5994make_bom(buf, name)
5995 char_u *buf;
5996 char_u *name;
5997{
5998 int flags;
5999 char_u *p;
6000
6001 flags = get_fio_flags(name);
6002
6003 /* Can't put a BOM in a non-Unicode file. */
6004 if (flags == FIO_LATIN1 || flags == 0)
6005 return 0;
6006
6007 if (flags == FIO_UTF8) /* UTF-8 */
6008 {
6009 buf[0] = 0xef;
6010 buf[1] = 0xbb;
6011 buf[2] = 0xbf;
6012 return 3;
6013 }
6014 p = buf;
6015 (void)ucs2bytes(0xfeff, &p, flags);
6016 return (int)(p - buf);
6017}
6018#endif
6019
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00006020#if defined(FEAT_VIMINFO) || defined(FEAT_BROWSE) || \
Bram Moolenaara0174af2008-01-02 20:08:25 +00006021 defined(FEAT_QUICKFIX) || defined(FEAT_AUTOCMD) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006022/*
6023 * Try to find a shortname by comparing the fullname with the current
6024 * directory.
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006025 * Returns "full_path" or pointer into "full_path" if shortened.
6026 */
6027 char_u *
6028shorten_fname1(full_path)
6029 char_u *full_path;
6030{
Bram Moolenaard9462e32011-04-11 21:35:11 +02006031 char_u *dirname;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006032 char_u *p = full_path;
6033
Bram Moolenaard9462e32011-04-11 21:35:11 +02006034 dirname = alloc(MAXPATHL);
6035 if (dirname == NULL)
6036 return full_path;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006037 if (mch_dirname(dirname, MAXPATHL) == OK)
6038 {
6039 p = shorten_fname(full_path, dirname);
6040 if (p == NULL || *p == NUL)
6041 p = full_path;
6042 }
Bram Moolenaard9462e32011-04-11 21:35:11 +02006043 vim_free(dirname);
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006044 return p;
6045}
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00006046#endif
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006047
6048/*
6049 * Try to find a shortname by comparing the fullname with the current
6050 * directory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006051 * Returns NULL if not shorter name possible, pointer into "full_path"
6052 * otherwise.
6053 */
6054 char_u *
6055shorten_fname(full_path, dir_name)
6056 char_u *full_path;
6057 char_u *dir_name;
6058{
6059 int len;
6060 char_u *p;
6061
6062 if (full_path == NULL)
6063 return NULL;
6064 len = (int)STRLEN(dir_name);
6065 if (fnamencmp(dir_name, full_path, len) == 0)
6066 {
6067 p = full_path + len;
6068#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
6069 /*
6070 * MSDOS: when a file is in the root directory, dir_name will end in a
6071 * slash, since C: by itself does not define a specific dir. In this
6072 * case p may already be correct. <negri>
6073 */
6074 if (!((len > 2) && (*(p - 2) == ':')))
6075#endif
6076 {
6077 if (vim_ispathsep(*p))
6078 ++p;
6079#ifndef VMS /* the path separator is always part of the path */
6080 else
6081 p = NULL;
6082#endif
6083 }
6084 }
6085#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
6086 /*
6087 * When using a file in the current drive, remove the drive name:
6088 * "A:\dir\file" -> "\dir\file". This helps when moving a session file on
6089 * a floppy from "A:\dir" to "B:\dir".
6090 */
6091 else if (len > 3
6092 && TOUPPER_LOC(full_path[0]) == TOUPPER_LOC(dir_name[0])
6093 && full_path[1] == ':'
6094 && vim_ispathsep(full_path[2]))
6095 p = full_path + 2;
6096#endif
6097 else
6098 p = NULL;
6099 return p;
6100}
6101
6102/*
6103 * Shorten filenames for all buffers.
6104 * When "force" is TRUE: Use full path from now on for files currently being
6105 * edited, both for file name and swap file name. Try to shorten the file
6106 * names a bit, if safe to do so.
6107 * When "force" is FALSE: Only try to shorten absolute file names.
6108 * For buffers that have buftype "nofile" or "scratch": never change the file
6109 * name.
6110 */
6111 void
6112shorten_fnames(force)
6113 int force;
6114{
6115 char_u dirname[MAXPATHL];
6116 buf_T *buf;
6117 char_u *p;
6118
6119 mch_dirname(dirname, MAXPATHL);
6120 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
6121 {
6122 if (buf->b_fname != NULL
6123#ifdef FEAT_QUICKFIX
6124 && !bt_nofile(buf)
6125#endif
6126 && !path_with_url(buf->b_fname)
6127 && (force
6128 || buf->b_sfname == NULL
6129 || mch_isFullName(buf->b_sfname)))
6130 {
6131 vim_free(buf->b_sfname);
6132 buf->b_sfname = NULL;
6133 p = shorten_fname(buf->b_ffname, dirname);
6134 if (p != NULL)
6135 {
6136 buf->b_sfname = vim_strsave(p);
6137 buf->b_fname = buf->b_sfname;
6138 }
6139 if (p == NULL || buf->b_fname == NULL)
6140 buf->b_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006141 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00006142
6143 /* Always make the swap file name a full path, a "nofile" buffer may
6144 * also have a swap file. */
6145 mf_fullname(buf->b_ml.ml_mfp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006146 }
6147#ifdef FEAT_WINDOWS
6148 status_redraw_all();
Bram Moolenaar49d7bf12006-02-17 21:45:41 +00006149 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006150#endif
6151}
6152
6153#if (defined(FEAT_DND) && defined(FEAT_GUI_GTK)) \
6154 || defined(FEAT_GUI_MSWIN) \
6155 || defined(FEAT_GUI_MAC) \
6156 || defined(PROTO)
6157/*
6158 * Shorten all filenames in "fnames[count]" by current directory.
6159 */
6160 void
6161shorten_filenames(fnames, count)
6162 char_u **fnames;
6163 int count;
6164{
6165 int i;
6166 char_u dirname[MAXPATHL];
6167 char_u *p;
6168
6169 if (fnames == NULL || count < 1)
6170 return;
6171 mch_dirname(dirname, sizeof(dirname));
6172 for (i = 0; i < count; ++i)
6173 {
6174 if ((p = shorten_fname(fnames[i], dirname)) != NULL)
6175 {
6176 /* shorten_fname() returns pointer in given "fnames[i]". If free
6177 * "fnames[i]" first, "p" becomes invalid. So we need to copy
6178 * "p" first then free fnames[i]. */
6179 p = vim_strsave(p);
6180 vim_free(fnames[i]);
6181 fnames[i] = p;
6182 }
6183 }
6184}
6185#endif
6186
6187/*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006188 * add extension to file name - change path/fo.o.h to path/fo.o.h.ext or
Bram Moolenaar071d4272004-06-13 20:20:40 +00006189 * fo_o_h.ext for MSDOS or when shortname option set.
6190 *
6191 * Assumed that fname is a valid name found in the filesystem we assure that
6192 * the return value is a different name and ends in 'ext'.
6193 * "ext" MUST be at most 4 characters long if it starts with a dot, 3
6194 * characters otherwise.
6195 * Space for the returned name is allocated, must be freed later.
6196 * Returns NULL when out of memory.
6197 */
6198 char_u *
6199modname(fname, ext, prepend_dot)
6200 char_u *fname, *ext;
6201 int prepend_dot; /* may prepend a '.' to file name */
6202{
6203 return buf_modname(
6204#ifdef SHORT_FNAME
6205 TRUE,
6206#else
6207 (curbuf->b_p_sn || curbuf->b_shortname),
6208#endif
6209 fname, ext, prepend_dot);
6210}
6211
6212 char_u *
6213buf_modname(shortname, fname, ext, prepend_dot)
6214 int shortname; /* use 8.3 file name */
6215 char_u *fname, *ext;
6216 int prepend_dot; /* may prepend a '.' to file name */
6217{
6218 char_u *retval;
6219 char_u *s;
6220 char_u *e;
6221 char_u *ptr;
6222 int fnamelen, extlen;
6223
6224 extlen = (int)STRLEN(ext);
6225
6226 /*
6227 * If there is no file name we must get the name of the current directory
6228 * (we need the full path in case :cd is used).
6229 */
6230 if (fname == NULL || *fname == NUL)
6231 {
6232 retval = alloc((unsigned)(MAXPATHL + extlen + 3));
6233 if (retval == NULL)
6234 return NULL;
6235 if (mch_dirname(retval, MAXPATHL) == FAIL ||
6236 (fnamelen = (int)STRLEN(retval)) == 0)
6237 {
6238 vim_free(retval);
6239 return NULL;
6240 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006241 if (!after_pathsep(retval, retval + fnamelen))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006242 {
6243 retval[fnamelen++] = PATHSEP;
6244 retval[fnamelen] = NUL;
6245 }
6246#ifndef SHORT_FNAME
6247 prepend_dot = FALSE; /* nothing to prepend a dot to */
6248#endif
6249 }
6250 else
6251 {
6252 fnamelen = (int)STRLEN(fname);
6253 retval = alloc((unsigned)(fnamelen + extlen + 3));
6254 if (retval == NULL)
6255 return NULL;
6256 STRCPY(retval, fname);
6257#ifdef VMS
6258 vms_remove_version(retval); /* we do not need versions here */
6259#endif
6260 }
6261
6262 /*
6263 * search backwards until we hit a '/', '\' or ':' replacing all '.'
6264 * by '_' for MSDOS or when shortname option set and ext starts with a dot.
6265 * Then truncate what is after the '/', '\' or ':' to 8 characters for
6266 * MSDOS and 26 characters for AMIGA, a lot more for UNIX.
6267 */
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006268 for (ptr = retval + fnamelen; ptr > retval; mb_ptr_back(retval, ptr))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006269 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006270 if (*ext == '.'
Bram Moolenaare60acc12011-05-10 16:41:25 +02006271#ifdef USE_LONG_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00006272 && (!USE_LONG_FNAME || shortname)
Bram Moolenaare60acc12011-05-10 16:41:25 +02006273#else
6274# ifndef SHORT_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00006275 && shortname
6276# endif
Bram Moolenaare60acc12011-05-10 16:41:25 +02006277#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006278 )
6279 if (*ptr == '.') /* replace '.' by '_' */
6280 *ptr = '_';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006281 if (vim_ispathsep(*ptr))
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006282 {
6283 ++ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006284 break;
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006285 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006286 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006287
6288 /* the file name has at most BASENAMELEN characters. */
6289#ifndef SHORT_FNAME
6290 if (STRLEN(ptr) > (unsigned)BASENAMELEN)
6291 ptr[BASENAMELEN] = '\0';
6292#endif
6293
6294 s = ptr + STRLEN(ptr);
6295
6296 /*
6297 * For 8.3 file names we may have to reduce the length.
6298 */
6299#ifdef USE_LONG_FNAME
6300 if (!USE_LONG_FNAME || shortname)
6301#else
6302# ifndef SHORT_FNAME
6303 if (shortname)
6304# endif
6305#endif
6306 {
6307 /*
6308 * If there is no file name, or the file name ends in '/', and the
6309 * extension starts with '.', put a '_' before the dot, because just
6310 * ".ext" is invalid.
6311 */
6312 if (fname == NULL || *fname == NUL
6313 || vim_ispathsep(fname[STRLEN(fname) - 1]))
6314 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006315 if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006316 *s++ = '_';
6317 }
6318 /*
6319 * If the extension starts with '.', truncate the base name at 8
6320 * characters
6321 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006322 else if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006323 {
Bram Moolenaar78a15312009-05-15 19:33:18 +00006324 if ((size_t)(s - ptr) > (size_t)8)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006325 {
6326 s = ptr + 8;
6327 *s = '\0';
6328 }
6329 }
6330 /*
6331 * If the extension doesn't start with '.', and the file name
6332 * doesn't have an extension yet, append a '.'
6333 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006334 else if ((e = vim_strchr(ptr, '.')) == NULL)
6335 *s++ = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006336 /*
6337 * If the extension doesn't start with '.', and there already is an
Bram Moolenaar7263a772007-05-10 17:35:54 +00006338 * extension, it may need to be truncated
Bram Moolenaar071d4272004-06-13 20:20:40 +00006339 */
6340 else if ((int)STRLEN(e) + extlen > 4)
6341 s = e + 4 - extlen;
6342 }
6343#if defined(OS2) || defined(USE_LONG_FNAME) || defined(WIN3264)
6344 /*
6345 * If there is no file name, and the extension starts with '.', put a
6346 * '_' before the dot, because just ".ext" may be invalid if it's on a
6347 * FAT partition, and on HPFS it doesn't matter.
6348 */
6349 else if ((fname == NULL || *fname == NUL) && *ext == '.')
6350 *s++ = '_';
6351#endif
6352
6353 /*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006354 * Append the extension.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006355 * ext can start with '.' and cannot exceed 3 more characters.
6356 */
6357 STRCPY(s, ext);
6358
6359#ifndef SHORT_FNAME
6360 /*
6361 * Prepend the dot.
6362 */
Bram Moolenaare60acc12011-05-10 16:41:25 +02006363 if (prepend_dot && !shortname && *(e = gettail(retval)) != '.'
Bram Moolenaar071d4272004-06-13 20:20:40 +00006364#ifdef USE_LONG_FNAME
6365 && USE_LONG_FNAME
6366#endif
6367 )
6368 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006369 STRMOVE(e + 1, e);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006370 *e = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006371 }
6372#endif
6373
6374 /*
6375 * Check that, after appending the extension, the file name is really
6376 * different.
6377 */
6378 if (fname != NULL && STRCMP(fname, retval) == 0)
6379 {
6380 /* we search for a character that can be replaced by '_' */
6381 while (--s >= ptr)
6382 {
6383 if (*s != '_')
6384 {
6385 *s = '_';
6386 break;
6387 }
6388 }
6389 if (s < ptr) /* fname was "________.<ext>", how tricky! */
6390 *ptr = 'v';
6391 }
6392 return retval;
6393}
6394
6395/*
6396 * Like fgets(), but if the file line is too long, it is truncated and the
6397 * rest of the line is thrown away. Returns TRUE for end-of-file.
6398 */
6399 int
6400vim_fgets(buf, size, fp)
6401 char_u *buf;
6402 int size;
6403 FILE *fp;
6404{
6405 char *eof;
6406#define FGETS_SIZE 200
6407 char tbuf[FGETS_SIZE];
6408
6409 buf[size - 2] = NUL;
6410#ifdef USE_CR
6411 eof = fgets_cr((char *)buf, size, fp);
6412#else
6413 eof = fgets((char *)buf, size, fp);
6414#endif
6415 if (buf[size - 2] != NUL && buf[size - 2] != '\n')
6416 {
6417 buf[size - 1] = NUL; /* Truncate the line */
6418
6419 /* Now throw away the rest of the line: */
6420 do
6421 {
6422 tbuf[FGETS_SIZE - 2] = NUL;
6423#ifdef USE_CR
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006424 ignoredp = fgets_cr((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006425#else
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006426 ignoredp = fgets((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006427#endif
6428 } while (tbuf[FGETS_SIZE - 2] != NUL && tbuf[FGETS_SIZE - 2] != '\n');
6429 }
6430 return (eof == NULL);
6431}
6432
6433#if defined(USE_CR) || defined(PROTO)
6434/*
6435 * Like vim_fgets(), but accept any line terminator: CR, CR-LF or LF.
6436 * Returns TRUE for end-of-file.
6437 * Only used for the Mac, because it's much slower than vim_fgets().
6438 */
6439 int
6440tag_fgets(buf, size, fp)
6441 char_u *buf;
6442 int size;
6443 FILE *fp;
6444{
6445 int i = 0;
6446 int c;
6447 int eof = FALSE;
6448
6449 for (;;)
6450 {
6451 c = fgetc(fp);
6452 if (c == EOF)
6453 {
6454 eof = TRUE;
6455 break;
6456 }
6457 if (c == '\r')
6458 {
6459 /* Always store a NL for end-of-line. */
6460 if (i < size - 1)
6461 buf[i++] = '\n';
6462 c = fgetc(fp);
6463 if (c != '\n') /* Macintosh format: single CR. */
6464 ungetc(c, fp);
6465 break;
6466 }
6467 if (i < size - 1)
6468 buf[i++] = c;
6469 if (c == '\n')
6470 break;
6471 }
6472 buf[i] = NUL;
6473 return eof;
6474}
6475#endif
6476
6477/*
6478 * rename() only works if both files are on the same file system, this
6479 * function will (attempts to?) copy the file across if rename fails -- webb
6480 * Return -1 for failure, 0 for success.
6481 */
6482 int
6483vim_rename(from, to)
6484 char_u *from;
6485 char_u *to;
6486{
6487 int fd_in;
6488 int fd_out;
6489 int n;
6490 char *errmsg = NULL;
6491 char *buffer;
6492#ifdef AMIGA
6493 BPTR flock;
6494#endif
6495 struct stat st;
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006496 long perm;
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006497#ifdef HAVE_ACL
6498 vim_acl_T acl; /* ACL from original file */
6499#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006500 int use_tmp_file = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006501
6502 /*
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006503 * When the names are identical, there is nothing to do. When they refer
6504 * to the same file (ignoring case and slash/backslash differences) but
6505 * the file name differs we need to go through a temp file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006506 */
6507 if (fnamecmp(from, to) == 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006508 {
Bram Moolenaar71afbfe2013-03-19 16:49:16 +01006509 if (p_fic && STRCMP(gettail(from), gettail(to)) != 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006510 use_tmp_file = TRUE;
6511 else
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006512 return 0;
6513 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006514
6515 /*
6516 * Fail if the "from" file doesn't exist. Avoids that "to" is deleted.
6517 */
6518 if (mch_stat((char *)from, &st) < 0)
6519 return -1;
6520
Bram Moolenaar3576da72008-12-30 15:15:57 +00006521#ifdef UNIX
6522 {
6523 struct stat st_to;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006524
6525 /* It's possible for the source and destination to be the same file.
6526 * This happens when "from" and "to" differ in case and are on a FAT32
6527 * filesystem. In that case go through a temp file name. */
6528 if (mch_stat((char *)to, &st_to) >= 0
6529 && st.st_dev == st_to.st_dev
6530 && st.st_ino == st_to.st_ino)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006531 use_tmp_file = TRUE;
6532 }
6533#endif
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02006534#ifdef WIN3264
6535 {
6536 BY_HANDLE_FILE_INFORMATION info1, info2;
6537
6538 /* It's possible for the source and destination to be the same file.
6539 * In that case go through a temp file name. This makes rename("foo",
6540 * "./foo") a no-op (in a complicated way). */
6541 if (win32_fileinfo(from, &info1) == FILEINFO_OK
6542 && win32_fileinfo(to, &info2) == FILEINFO_OK
6543 && info1.dwVolumeSerialNumber == info2.dwVolumeSerialNumber
6544 && info1.nFileIndexHigh == info2.nFileIndexHigh
6545 && info1.nFileIndexLow == info2.nFileIndexLow)
6546 use_tmp_file = TRUE;
6547 }
6548#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006549
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006550 if (use_tmp_file)
6551 {
6552 char tempname[MAXPATHL + 1];
6553
6554 /*
6555 * Find a name that doesn't exist and is in the same directory.
6556 * Rename "from" to "tempname" and then rename "tempname" to "to".
6557 */
6558 if (STRLEN(from) >= MAXPATHL - 5)
6559 return -1;
6560 STRCPY(tempname, from);
6561 for (n = 123; n < 99999; ++n)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006562 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006563 sprintf((char *)gettail((char_u *)tempname), "%d", n);
6564 if (mch_stat(tempname, &st) < 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006565 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006566 if (mch_rename((char *)from, tempname) == 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006567 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006568 if (mch_rename(tempname, (char *)to) == 0)
6569 return 0;
6570 /* Strange, the second step failed. Try moving the
6571 * file back and return failure. */
6572 mch_rename(tempname, (char *)from);
Bram Moolenaar3576da72008-12-30 15:15:57 +00006573 return -1;
6574 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006575 /* If it fails for one temp name it will most likely fail
6576 * for any temp name, give up. */
6577 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006578 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006579 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006580 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006581 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006582
Bram Moolenaar071d4272004-06-13 20:20:40 +00006583 /*
6584 * Delete the "to" file, this is required on some systems to make the
6585 * mch_rename() work, on other systems it makes sure that we don't have
6586 * two files when the mch_rename() fails.
6587 */
6588
6589#ifdef AMIGA
6590 /*
6591 * With MSDOS-compatible filesystems (crossdos, messydos) it is possible
6592 * that the name of the "to" file is the same as the "from" file, even
Bram Moolenaar7263a772007-05-10 17:35:54 +00006593 * though the names are different. To avoid the chance of accidentally
Bram Moolenaar071d4272004-06-13 20:20:40 +00006594 * deleting the "from" file (horror!) we lock it during the remove.
6595 *
6596 * When used for making a backup before writing the file: This should not
6597 * happen with ":w", because startscript() should detect this problem and
6598 * set buf->b_shortname, causing modname() to return a correct ".bak" file
6599 * name. This problem does exist with ":w filename", but then the
6600 * original file will be somewhere else so the backup isn't really
6601 * important. If autoscripting is off the rename may fail.
6602 */
6603 flock = Lock((UBYTE *)from, (long)ACCESS_READ);
6604#endif
6605 mch_remove(to);
6606#ifdef AMIGA
6607 if (flock)
6608 UnLock(flock);
6609#endif
6610
6611 /*
6612 * First try a normal rename, return if it works.
6613 */
6614 if (mch_rename((char *)from, (char *)to) == 0)
6615 return 0;
6616
6617 /*
6618 * Rename() failed, try copying the file.
6619 */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006620 perm = mch_getperm(from);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006621#ifdef HAVE_ACL
6622 /* For systems that support ACL: get the ACL from the original file. */
6623 acl = mch_get_acl(from);
6624#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006625 fd_in = mch_open((char *)from, O_RDONLY|O_EXTRA, 0);
6626 if (fd_in == -1)
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006627 {
6628#ifdef HAVE_ACL
6629 mch_free_acl(acl);
6630#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006631 return -1;
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006632 }
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006633
6634 /* Create the new file with same permissions as the original. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00006635 fd_out = mch_open((char *)to,
6636 O_CREAT|O_EXCL|O_WRONLY|O_EXTRA|O_NOFOLLOW, (int)perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006637 if (fd_out == -1)
6638 {
6639 close(fd_in);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006640#ifdef HAVE_ACL
6641 mch_free_acl(acl);
6642#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006643 return -1;
6644 }
6645
6646 buffer = (char *)alloc(BUFSIZE);
6647 if (buffer == NULL)
6648 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006649 close(fd_out);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006650 close(fd_in);
6651#ifdef HAVE_ACL
6652 mch_free_acl(acl);
6653#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006654 return -1;
6655 }
6656
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01006657 while ((n = read_eintr(fd_in, buffer, BUFSIZE)) > 0)
6658 if (write_eintr(fd_out, buffer, n) != n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006659 {
6660 errmsg = _("E208: Error writing to \"%s\"");
6661 break;
6662 }
6663
6664 vim_free(buffer);
6665 close(fd_in);
6666 if (close(fd_out) < 0)
6667 errmsg = _("E209: Error closing \"%s\"");
6668 if (n < 0)
6669 {
6670 errmsg = _("E210: Error reading \"%s\"");
6671 to = from;
6672 }
Bram Moolenaar7263a772007-05-10 17:35:54 +00006673#ifndef UNIX /* for Unix mch_open() already set the permission */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006674 mch_setperm(to, perm);
Bram Moolenaarc6039d82005-12-02 00:44:04 +00006675#endif
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006676#ifdef HAVE_ACL
6677 mch_set_acl(to, acl);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006678 mch_free_acl(acl);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006679#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006680 if (errmsg != NULL)
6681 {
6682 EMSG2(errmsg, to);
6683 return -1;
6684 }
6685 mch_remove(from);
6686 return 0;
6687}
6688
6689static int already_warned = FALSE;
6690
6691/*
6692 * Check if any not hidden buffer has been changed.
6693 * Postpone the check if there are characters in the stuff buffer, a global
6694 * command is being executed, a mapping is being executed or an autocommand is
6695 * busy.
6696 * Returns TRUE if some message was written (screen should be redrawn and
6697 * cursor positioned).
6698 */
6699 int
6700check_timestamps(focus)
6701 int focus; /* called for GUI focus event */
6702{
6703 buf_T *buf;
6704 int didit = 0;
6705 int n;
6706
6707 /* Don't check timestamps while system() or another low-level function may
6708 * cause us to lose and gain focus. */
6709 if (no_check_timestamps > 0)
6710 return FALSE;
6711
6712 /* Avoid doing a check twice. The OK/Reload dialog can cause a focus
6713 * event and we would keep on checking if the file is steadily growing.
6714 * Do check again after typing something. */
6715 if (focus && did_check_timestamps)
6716 {
6717 need_check_timestamps = TRUE;
6718 return FALSE;
6719 }
6720
6721 if (!stuff_empty() || global_busy || !typebuf_typed()
6722#ifdef FEAT_AUTOCMD
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006723 || autocmd_busy || curbuf_lock > 0 || allbuf_lock > 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00006724#endif
6725 )
6726 need_check_timestamps = TRUE; /* check later */
6727 else
6728 {
6729 ++no_wait_return;
6730 did_check_timestamps = TRUE;
6731 already_warned = FALSE;
6732 for (buf = firstbuf; buf != NULL; )
6733 {
6734 /* Only check buffers in a window. */
6735 if (buf->b_nwindows > 0)
6736 {
6737 n = buf_check_timestamp(buf, focus);
6738 if (didit < n)
6739 didit = n;
6740 if (n > 0 && !buf_valid(buf))
6741 {
6742 /* Autocommands have removed the buffer, start at the
6743 * first one again. */
6744 buf = firstbuf;
6745 continue;
6746 }
6747 }
6748 buf = buf->b_next;
6749 }
6750 --no_wait_return;
6751 need_check_timestamps = FALSE;
6752 if (need_wait_return && didit == 2)
6753 {
6754 /* make sure msg isn't overwritten */
6755 msg_puts((char_u *)"\n");
6756 out_flush();
6757 }
6758 }
6759 return didit;
6760}
6761
6762/*
6763 * Move all the lines from buffer "frombuf" to buffer "tobuf".
6764 * Return OK or FAIL. When FAIL "tobuf" is incomplete and/or "frombuf" is not
6765 * empty.
6766 */
6767 static int
6768move_lines(frombuf, tobuf)
6769 buf_T *frombuf;
6770 buf_T *tobuf;
6771{
6772 buf_T *tbuf = curbuf;
6773 int retval = OK;
6774 linenr_T lnum;
6775 char_u *p;
6776
6777 /* Copy the lines in "frombuf" to "tobuf". */
6778 curbuf = tobuf;
6779 for (lnum = 1; lnum <= frombuf->b_ml.ml_line_count; ++lnum)
6780 {
6781 p = vim_strsave(ml_get_buf(frombuf, lnum, FALSE));
6782 if (p == NULL || ml_append(lnum - 1, p, 0, FALSE) == FAIL)
6783 {
6784 vim_free(p);
6785 retval = FAIL;
6786 break;
6787 }
6788 vim_free(p);
6789 }
6790
6791 /* Delete all the lines in "frombuf". */
6792 if (retval != FAIL)
6793 {
6794 curbuf = frombuf;
Bram Moolenaar9460b9d2007-01-09 14:37:01 +00006795 for (lnum = curbuf->b_ml.ml_line_count; lnum > 0; --lnum)
6796 if (ml_delete(lnum, FALSE) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006797 {
6798 /* Oops! We could try putting back the saved lines, but that
6799 * might fail again... */
6800 retval = FAIL;
6801 break;
6802 }
6803 }
6804
6805 curbuf = tbuf;
6806 return retval;
6807}
6808
6809/*
6810 * Check if buffer "buf" has been changed.
6811 * Also check if the file for a new buffer unexpectedly appeared.
6812 * return 1 if a changed buffer was found.
6813 * return 2 if a message has been displayed.
6814 * return 0 otherwise.
6815 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006816 int
6817buf_check_timestamp(buf, focus)
6818 buf_T *buf;
Bram Moolenaar78a15312009-05-15 19:33:18 +00006819 int focus UNUSED; /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006820{
6821 struct stat st;
6822 int stat_res;
6823 int retval = 0;
6824 char_u *path;
6825 char_u *tbuf;
6826 char *mesg = NULL;
Bram Moolenaar44ecf652005-03-07 23:09:59 +00006827 char *mesg2 = "";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006828 int helpmesg = FALSE;
6829 int reload = FALSE;
6830#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6831 int can_reload = FALSE;
6832#endif
Bram Moolenaar914703b2010-05-31 21:59:46 +02006833 off_t orig_size = buf->b_orig_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006834 int orig_mode = buf->b_orig_mode;
6835#ifdef FEAT_GUI
6836 int save_mouse_correct = need_mouse_correct;
6837#endif
6838#ifdef FEAT_AUTOCMD
6839 static int busy = FALSE;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006840 int n;
6841 char_u *s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006842#endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006843 char *reason;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006844
6845 /* If there is no file name, the buffer is not loaded, 'buftype' is
6846 * set, we are in the middle of a save or being called recursively: ignore
6847 * this buffer. */
6848 if (buf->b_ffname == NULL
6849 || buf->b_ml.ml_mfp == NULL
6850#if defined(FEAT_QUICKFIX)
6851 || *buf->b_p_bt != NUL
6852#endif
6853 || buf->b_saving
6854#ifdef FEAT_AUTOCMD
6855 || busy
6856#endif
Bram Moolenaar009b2592004-10-24 19:18:58 +00006857#ifdef FEAT_NETBEANS_INTG
6858 || isNetbeansBuffer(buf)
6859#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006860 )
6861 return 0;
6862
6863 if ( !(buf->b_flags & BF_NOTEDITED)
6864 && buf->b_mtime != 0
6865 && ((stat_res = mch_stat((char *)buf->b_ffname, &st)) < 0
6866 || time_differs((long)st.st_mtime, buf->b_mtime)
6867#ifdef HAVE_ST_MODE
6868 || (int)st.st_mode != buf->b_orig_mode
6869#else
6870 || mch_getperm(buf->b_ffname) != buf->b_orig_mode
6871#endif
6872 ))
6873 {
6874 retval = 1;
6875
Bram Moolenaar316059c2006-01-14 21:18:42 +00006876 /* set b_mtime to stop further warnings (e.g., when executing
6877 * FileChangedShell autocmd) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006878 if (stat_res < 0)
6879 {
6880 buf->b_mtime = 0;
6881 buf->b_orig_size = 0;
6882 buf->b_orig_mode = 0;
6883 }
6884 else
6885 buf_store_time(buf, &st, buf->b_ffname);
6886
6887 /* Don't do anything for a directory. Might contain the file
6888 * explorer. */
6889 if (mch_isdir(buf->b_fname))
6890 ;
6891
6892 /*
6893 * If 'autoread' is set, the buffer has no changes and the file still
6894 * exists, reload the buffer. Use the buffer-local option value if it
6895 * was set, the global option value otherwise.
6896 */
6897 else if ((buf->b_p_ar >= 0 ? buf->b_p_ar : p_ar)
6898 && !bufIsChanged(buf) && stat_res >= 0)
6899 reload = TRUE;
6900 else
6901 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006902 if (stat_res < 0)
6903 reason = "deleted";
6904 else if (bufIsChanged(buf))
6905 reason = "conflict";
6906 else if (orig_size != buf->b_orig_size || buf_contents_changed(buf))
6907 reason = "changed";
6908 else if (orig_mode != buf->b_orig_mode)
6909 reason = "mode";
6910 else
6911 reason = "time";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006912
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006913#ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006914 /*
6915 * Only give the warning if there are no FileChangedShell
6916 * autocommands.
6917 * Avoid being called recursively by setting "busy".
6918 */
6919 busy = TRUE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00006920# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006921 set_vim_var_string(VV_FCS_REASON, (char_u *)reason, -1);
6922 set_vim_var_string(VV_FCS_CHOICE, (char_u *)"", -1);
Bram Moolenaar1e015462005-09-25 22:16:38 +00006923# endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006924 ++allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006925 n = apply_autocmds(EVENT_FILECHANGEDSHELL,
6926 buf->b_fname, buf->b_fname, FALSE, buf);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006927 --allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006928 busy = FALSE;
6929 if (n)
6930 {
6931 if (!buf_valid(buf))
6932 EMSG(_("E246: FileChangedShell autocommand deleted buffer"));
Bram Moolenaar1e015462005-09-25 22:16:38 +00006933# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006934 s = get_vim_var_str(VV_FCS_CHOICE);
6935 if (STRCMP(s, "reload") == 0 && *reason != 'd')
6936 reload = TRUE;
6937 else if (STRCMP(s, "ask") == 0)
6938 n = FALSE;
6939 else
Bram Moolenaar1e015462005-09-25 22:16:38 +00006940# endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006941 return 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006942 }
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006943 if (!n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006944#endif
6945 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006946 if (*reason == 'd')
6947 mesg = _("E211: File \"%s\" no longer available");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006948 else
6949 {
6950 helpmesg = TRUE;
6951#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6952 can_reload = TRUE;
6953#endif
6954 /*
6955 * Check if the file contents really changed to avoid
6956 * giving a warning when only the timestamp was set (e.g.,
6957 * checked out of CVS). Always warn when the buffer was
6958 * changed.
6959 */
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006960 if (reason[2] == 'n')
6961 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006962 mesg = _("W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006963 mesg2 = _("See \":help W12\" for more info.");
6964 }
6965 else if (reason[1] == 'h')
6966 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006967 mesg = _("W11: Warning: File \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006968 mesg2 = _("See \":help W11\" for more info.");
6969 }
6970 else if (*reason == 'm')
6971 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006972 mesg = _("W16: Warning: Mode of file \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006973 mesg2 = _("See \":help W16\" for more info.");
6974 }
Bram Moolenaar85388b52009-06-24 09:58:32 +00006975 else
6976 /* Only timestamp changed, store it to avoid a warning
6977 * in check_mtime() later. */
6978 buf->b_mtime_read = buf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006979 }
6980 }
6981 }
6982
6983 }
6984 else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W)
6985 && vim_fexists(buf->b_ffname))
6986 {
6987 retval = 1;
6988 mesg = _("W13: Warning: File \"%s\" has been created after editing started");
6989 buf->b_flags |= BF_NEW_W;
6990#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6991 can_reload = TRUE;
6992#endif
6993 }
6994
6995 if (mesg != NULL)
6996 {
6997 path = home_replace_save(buf, buf->b_fname);
6998 if (path != NULL)
6999 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007000 if (!helpmesg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007001 mesg2 = "";
7002 tbuf = alloc((unsigned)(STRLEN(path) + STRLEN(mesg)
7003 + STRLEN(mesg2) + 2));
7004 sprintf((char *)tbuf, mesg, path);
Bram Moolenaar496c5262009-03-18 14:42:00 +00007005#ifdef FEAT_EVAL
7006 /* Set warningmsg here, before the unimportant and output-specific
7007 * mesg2 has been appended. */
7008 set_vim_var_string(VV_WARNINGMSG, tbuf, -1);
7009#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007010#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
7011 if (can_reload)
7012 {
7013 if (*mesg2 != NUL)
7014 {
7015 STRCAT(tbuf, "\n");
7016 STRCAT(tbuf, mesg2);
7017 }
7018 if (do_dialog(VIM_WARNING, (char_u *)_("Warning"), tbuf,
Bram Moolenaard2c340a2011-01-17 20:08:11 +01007019 (char_u *)_("&OK\n&Load File"), 1, NULL, TRUE) == 2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007020 reload = TRUE;
7021 }
7022 else
7023#endif
7024 if (State > NORMAL_BUSY || (State & CMDLINE) || already_warned)
7025 {
7026 if (*mesg2 != NUL)
7027 {
7028 STRCAT(tbuf, "; ");
7029 STRCAT(tbuf, mesg2);
7030 }
7031 EMSG(tbuf);
7032 retval = 2;
7033 }
7034 else
7035 {
Bram Moolenaared203462004-06-16 11:19:22 +00007036# ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00007037 if (!autocmd_busy)
Bram Moolenaared203462004-06-16 11:19:22 +00007038# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007039 {
7040 msg_start();
7041 msg_puts_attr(tbuf, hl_attr(HLF_E) + MSG_HIST);
7042 if (*mesg2 != NUL)
7043 msg_puts_attr((char_u *)mesg2,
7044 hl_attr(HLF_W) + MSG_HIST);
7045 msg_clr_eos();
7046 (void)msg_end();
7047 if (emsg_silent == 0)
7048 {
7049 out_flush();
Bram Moolenaared203462004-06-16 11:19:22 +00007050# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00007051 if (!focus)
Bram Moolenaared203462004-06-16 11:19:22 +00007052# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007053 /* give the user some time to think about it */
7054 ui_delay(1000L, TRUE);
7055
7056 /* don't redraw and erase the message */
7057 redraw_cmdline = FALSE;
7058 }
7059 }
7060 already_warned = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007061 }
7062
7063 vim_free(path);
7064 vim_free(tbuf);
7065 }
7066 }
7067
7068 if (reload)
Bram Moolenaar465748e2012-08-29 18:50:54 +02007069 {
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007070 /* Reload the buffer. */
Bram Moolenaar316059c2006-01-14 21:18:42 +00007071 buf_reload(buf, orig_mode);
Bram Moolenaar465748e2012-08-29 18:50:54 +02007072#ifdef FEAT_PERSISTENT_UNDO
7073 if (buf->b_p_udf && buf->b_ffname != NULL)
7074 {
7075 char_u hash[UNDO_HASH_SIZE];
7076 buf_T *save_curbuf = curbuf;
7077
7078 /* Any existing undo file is unusable, write it now. */
7079 curbuf = buf;
7080 u_compute_hash(hash);
7081 u_write_undo(NULL, FALSE, buf, hash);
7082 curbuf = save_curbuf;
7083 }
7084#endif
7085 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007086
Bram Moolenaar56718732006-03-15 22:53:57 +00007087#ifdef FEAT_AUTOCMD
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00007088 /* Trigger FileChangedShell when the file was changed in any way. */
7089 if (buf_valid(buf) && retval != 0)
Bram Moolenaar56718732006-03-15 22:53:57 +00007090 (void)apply_autocmds(EVENT_FILECHANGEDSHELLPOST,
7091 buf->b_fname, buf->b_fname, FALSE, buf);
7092#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007093#ifdef FEAT_GUI
7094 /* restore this in case an autocommand has set it; it would break
7095 * 'mousefocus' */
7096 need_mouse_correct = save_mouse_correct;
7097#endif
7098
7099 return retval;
7100}
7101
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007102/*
7103 * Reload a buffer that is already loaded.
7104 * Used when the file was changed outside of Vim.
Bram Moolenaar316059c2006-01-14 21:18:42 +00007105 * "orig_mode" is buf->b_orig_mode before the need for reloading was detected.
7106 * buf->b_orig_mode may have been reset already.
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007107 */
7108 void
Bram Moolenaar316059c2006-01-14 21:18:42 +00007109buf_reload(buf, orig_mode)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007110 buf_T *buf;
Bram Moolenaar316059c2006-01-14 21:18:42 +00007111 int orig_mode;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007112{
7113 exarg_T ea;
7114 pos_T old_cursor;
7115 linenr_T old_topline;
7116 int old_ro = buf->b_p_ro;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007117 buf_T *savebuf;
7118 int saved = OK;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007119 aco_save_T aco;
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007120 int flags = READ_NEW;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007121
7122 /* set curwin/curbuf for "buf" and save some things */
7123 aucmd_prepbuf(&aco, buf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007124
7125 /* We only want to read the text from the file, not reset the syntax
7126 * highlighting, clear marks, diff status, etc. Force the fileformat
7127 * and encoding to be the same. */
7128 if (prep_exarg(&ea, buf) == OK)
7129 {
7130 old_cursor = curwin->w_cursor;
7131 old_topline = curwin->w_topline;
7132
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007133 if (p_ur < 0 || curbuf->b_ml.ml_line_count <= p_ur)
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007134 {
7135 /* Save all the text, so that the reload can be undone.
7136 * Sync first so that this is a separate undo-able action. */
7137 u_sync(FALSE);
7138 saved = u_savecommon(0, curbuf->b_ml.ml_line_count + 1, 0, TRUE);
7139 flags |= READ_KEEP_UNDO;
7140 }
7141
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007142 /*
7143 * To behave like when a new file is edited (matters for
7144 * BufReadPost autocommands) we first need to delete the current
7145 * buffer contents. But if reading the file fails we should keep
7146 * the old contents. Can't use memory only, the file might be
7147 * too big. Use a hidden buffer to move the buffer contents to.
7148 */
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007149 if (bufempty() || saved == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007150 savebuf = NULL;
7151 else
7152 {
7153 /* Allocate a buffer without putting it in the buffer list. */
7154 savebuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007155 if (savebuf != NULL && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007156 {
7157 /* Open the memline. */
7158 curbuf = savebuf;
7159 curwin->w_buffer = savebuf;
Bram Moolenaar4770d092006-01-12 23:22:24 +00007160 saved = ml_open(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007161 curbuf = buf;
7162 curwin->w_buffer = buf;
7163 }
Bram Moolenaar8424a622006-04-19 21:23:36 +00007164 if (savebuf == NULL || saved == FAIL || buf != curbuf
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007165 || move_lines(buf, savebuf) == FAIL)
7166 {
7167 EMSG2(_("E462: Could not prepare for reloading \"%s\""),
7168 buf->b_fname);
7169 saved = FAIL;
7170 }
7171 }
7172
7173 if (saved == OK)
7174 {
7175 curbuf->b_flags |= BF_CHECK_RO; /* check for RO again */
7176#ifdef FEAT_AUTOCMD
7177 keep_filetype = TRUE; /* don't detect 'filetype' */
7178#endif
7179 if (readfile(buf->b_ffname, buf->b_fname, (linenr_T)0,
7180 (linenr_T)0,
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007181 (linenr_T)MAXLNUM, &ea, flags) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007182 {
7183#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
7184 if (!aborting())
7185#endif
7186 EMSG2(_("E321: Could not reload \"%s\""), buf->b_fname);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007187 if (savebuf != NULL && buf_valid(savebuf) && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007188 {
7189 /* Put the text back from the save buffer. First
7190 * delete any lines that readfile() added. */
7191 while (!bufempty())
Bram Moolenaar8424a622006-04-19 21:23:36 +00007192 if (ml_delete(buf->b_ml.ml_line_count, FALSE) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007193 break;
7194 (void)move_lines(savebuf, buf);
7195 }
7196 }
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007197 else if (buf == curbuf) /* "buf" still valid */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007198 {
7199 /* Mark the buffer as unmodified and free undo info. */
7200 unchanged(buf, TRUE);
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007201 if ((flags & READ_KEEP_UNDO) == 0)
7202 {
7203 u_blockfree(buf);
7204 u_clearall(buf);
7205 }
7206 else
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007207 {
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007208 /* Mark all undo states as changed. */
7209 u_unchanged(curbuf);
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007210 }
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007211 }
7212 }
7213 vim_free(ea.cmd);
7214
Bram Moolenaar8424a622006-04-19 21:23:36 +00007215 if (savebuf != NULL && buf_valid(savebuf))
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007216 wipe_buffer(savebuf, FALSE);
7217
7218#ifdef FEAT_DIFF
7219 /* Invalidate diff info if necessary. */
Bram Moolenaar8424a622006-04-19 21:23:36 +00007220 diff_invalidate(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007221#endif
7222
7223 /* Restore the topline and cursor position and check it (lines may
7224 * have been removed). */
7225 if (old_topline > curbuf->b_ml.ml_line_count)
7226 curwin->w_topline = curbuf->b_ml.ml_line_count;
7227 else
7228 curwin->w_topline = old_topline;
7229 curwin->w_cursor = old_cursor;
7230 check_cursor();
7231 update_topline();
7232#ifdef FEAT_AUTOCMD
7233 keep_filetype = FALSE;
7234#endif
7235#ifdef FEAT_FOLDING
7236 {
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007237 win_T *wp;
7238 tabpage_T *tp;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007239
7240 /* Update folds unless they are defined manually. */
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007241 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007242 if (wp->w_buffer == curwin->w_buffer
7243 && !foldmethodIsManual(wp))
7244 foldUpdateAll(wp);
7245 }
7246#endif
7247 /* If the mode didn't change and 'readonly' was set, keep the old
7248 * value; the user probably used the ":view" command. But don't
7249 * reset it, might have had a read error. */
7250 if (orig_mode == curbuf->b_orig_mode)
7251 curbuf->b_p_ro |= old_ro;
Bram Moolenaar52f85b72013-01-30 14:13:56 +01007252
7253 /* Modelines must override settings done by autocommands. */
7254 do_modelines(0);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007255 }
7256
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007257 /* restore curwin/curbuf and a few other things */
7258 aucmd_restbuf(&aco);
7259 /* Careful: autocommands may have made "buf" invalid! */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007260}
7261
Bram Moolenaar071d4272004-06-13 20:20:40 +00007262 void
7263buf_store_time(buf, st, fname)
7264 buf_T *buf;
7265 struct stat *st;
Bram Moolenaar78a15312009-05-15 19:33:18 +00007266 char_u *fname UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007267{
7268 buf->b_mtime = (long)st->st_mtime;
Bram Moolenaar914703b2010-05-31 21:59:46 +02007269 buf->b_orig_size = st->st_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007270#ifdef HAVE_ST_MODE
7271 buf->b_orig_mode = (int)st->st_mode;
7272#else
7273 buf->b_orig_mode = mch_getperm(fname);
7274#endif
7275}
7276
7277/*
7278 * Adjust the line with missing eol, used for the next write.
7279 * Used for do_filter(), when the input lines for the filter are deleted.
7280 */
7281 void
7282write_lnum_adjust(offset)
7283 linenr_T offset;
7284{
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01007285 if (curbuf->b_no_eol_lnum != 0) /* only if there is a missing eol */
7286 curbuf->b_no_eol_lnum += offset;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007287}
7288
7289#if defined(TEMPDIRNAMES) || defined(PROTO)
7290static long temp_count = 0; /* Temp filename counter. */
7291
7292/*
7293 * Delete the temp directory and all files it contains.
7294 */
7295 void
7296vim_deltempdir()
7297{
7298 char_u **files;
7299 int file_count;
7300 int i;
7301
7302 if (vim_tempdir != NULL)
7303 {
7304 sprintf((char *)NameBuff, "%s*", vim_tempdir);
7305 if (gen_expand_wildcards(1, &NameBuff, &file_count, &files,
7306 EW_DIR|EW_FILE|EW_SILENT) == OK)
7307 {
7308 for (i = 0; i < file_count; ++i)
7309 mch_remove(files[i]);
7310 FreeWild(file_count, files);
7311 }
7312 gettail(NameBuff)[-1] = NUL;
7313 (void)mch_rmdir(NameBuff);
7314
7315 vim_free(vim_tempdir);
7316 vim_tempdir = NULL;
7317 }
7318}
7319#endif
7320
Bram Moolenaar4592dee2009-11-18 19:11:58 +00007321#ifdef TEMPDIRNAMES
Bram Moolenaar071d4272004-06-13 20:20:40 +00007322/*
Bram Moolenaareaf03392009-11-17 11:08:52 +00007323 * Directory "tempdir" was created. Expand this name to a full path and put
7324 * it in "vim_tempdir". This avoids that using ":cd" would confuse us.
7325 * "tempdir" must be no longer than MAXPATHL.
7326 */
7327 static void
7328vim_settempdir(tempdir)
7329 char_u *tempdir;
7330{
7331 char_u *buf;
7332
7333 buf = alloc((unsigned)MAXPATHL + 2);
7334 if (buf != NULL)
7335 {
7336 if (vim_FullName(tempdir, buf, MAXPATHL, FALSE) == FAIL)
7337 STRCPY(buf, tempdir);
7338# ifdef __EMX__
7339 if (vim_strchr(buf, '/') != NULL)
7340 STRCAT(buf, "/");
7341 else
7342# endif
7343 add_pathsep(buf);
7344 vim_tempdir = vim_strsave(buf);
7345 vim_free(buf);
7346 }
7347}
Bram Moolenaar4592dee2009-11-18 19:11:58 +00007348#endif
Bram Moolenaareaf03392009-11-17 11:08:52 +00007349
7350/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007351 * vim_tempname(): Return a unique name that can be used for a temp file.
7352 *
7353 * The temp file is NOT created.
7354 *
7355 * The returned pointer is to allocated memory.
7356 * The returned pointer is NULL if no valid name was found.
7357 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007358 char_u *
7359vim_tempname(extra_char)
Bram Moolenaar78a15312009-05-15 19:33:18 +00007360 int extra_char UNUSED; /* char to use in the name instead of '?' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007361{
7362#ifdef USE_TMPNAM
7363 char_u itmp[L_tmpnam]; /* use tmpnam() */
7364#else
7365 char_u itmp[TEMPNAMELEN];
7366#endif
7367
7368#ifdef TEMPDIRNAMES
7369 static char *(tempdirs[]) = {TEMPDIRNAMES};
7370 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007371# ifndef EEXIST
7372 struct stat st;
7373# endif
7374
7375 /*
7376 * This will create a directory for private use by this instance of Vim.
7377 * This is done once, and the same directory is used for all temp files.
7378 * This method avoids security problems because of symlink attacks et al.
7379 * It's also a bit faster, because we only need to check for an existing
7380 * file when creating the directory and not for each temp file.
7381 */
7382 if (vim_tempdir == NULL)
7383 {
7384 /*
7385 * Try the entries in TEMPDIRNAMES to create the temp directory.
7386 */
Bram Moolenaar78a15312009-05-15 19:33:18 +00007387 for (i = 0; i < (int)(sizeof(tempdirs) / sizeof(char *)); ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007388 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007389# ifndef HAVE_MKDTEMP
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007390 size_t itmplen;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007391 long nr;
7392 long off;
7393# endif
7394
Bram Moolenaar071d4272004-06-13 20:20:40 +00007395 /* expand $TMP, leave room for "/v1100000/999999999" */
7396 expand_env((char_u *)tempdirs[i], itmp, TEMPNAMELEN - 20);
7397 if (mch_isdir(itmp)) /* directory exists */
7398 {
7399# ifdef __EMX__
7400 /* If $TMP contains a forward slash (perhaps using bash or
7401 * tcsh), don't add a backslash, use a forward slash!
7402 * Adding 2 backslashes didn't work. */
7403 if (vim_strchr(itmp, '/') != NULL)
7404 STRCAT(itmp, "/");
7405 else
7406# endif
7407 add_pathsep(itmp);
7408
Bram Moolenaareaf03392009-11-17 11:08:52 +00007409# ifdef HAVE_MKDTEMP
7410 /* Leave room for filename */
7411 STRCAT(itmp, "vXXXXXX");
7412 if (mkdtemp((char *)itmp) != NULL)
7413 vim_settempdir(itmp);
7414# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007415 /* Get an arbitrary number of up to 6 digits. When it's
7416 * unlikely that it already exists it will be faster,
7417 * otherwise it doesn't matter. The use of mkdir() avoids any
7418 * security problems because of the predictable number. */
7419 nr = (mch_get_pid() + (long)time(NULL)) % 1000000L;
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007420 itmplen = STRLEN(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007421
7422 /* Try up to 10000 different values until we find a name that
7423 * doesn't exist. */
7424 for (off = 0; off < 10000L; ++off)
7425 {
7426 int r;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007427# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007428 mode_t umask_save;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007429# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007430
Bram Moolenaareaf03392009-11-17 11:08:52 +00007431 sprintf((char *)itmp + itmplen, "v%ld", nr + off);
7432# ifndef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007433 /* If mkdir() does not set errno to EEXIST, check for
7434 * existing file here. There is a race condition then,
7435 * although it's fail-safe. */
7436 if (mch_stat((char *)itmp, &st) >= 0)
7437 continue;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007438# endif
7439# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007440 /* Make sure the umask doesn't remove the executable bit.
7441 * "repl" has been reported to use "177". */
7442 umask_save = umask(077);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007443# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007444 r = vim_mkdir(itmp, 0700);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007445# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007446 (void)umask(umask_save);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007447# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007448 if (r == 0)
7449 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007450 vim_settempdir(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007451 break;
7452 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007453# ifdef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007454 /* If the mkdir() didn't fail because the file/dir exists,
7455 * we probably can't create any dir here, try another
7456 * place. */
7457 if (errno != EEXIST)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007458# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007459 break;
7460 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007461# endif /* HAVE_MKDTEMP */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007462 if (vim_tempdir != NULL)
7463 break;
7464 }
7465 }
7466 }
7467
7468 if (vim_tempdir != NULL)
7469 {
7470 /* There is no need to check if the file exists, because we own the
7471 * directory and nobody else creates a file in it. */
7472 sprintf((char *)itmp, "%s%ld", vim_tempdir, temp_count++);
7473 return vim_strsave(itmp);
7474 }
7475
7476 return NULL;
7477
7478#else /* TEMPDIRNAMES */
7479
7480# ifdef WIN3264
7481 char szTempFile[_MAX_PATH + 1];
7482 char buf4[4];
7483 char_u *retval;
7484 char_u *p;
7485
7486 STRCPY(itmp, "");
7487 if (GetTempPath(_MAX_PATH, szTempFile) == 0)
Bram Moolenaarb1891912011-02-09 14:47:03 +01007488 {
7489 szTempFile[0] = '.'; /* GetTempPath() failed, use current dir */
7490 szTempFile[1] = NUL;
7491 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007492 strcpy(buf4, "VIM");
7493 buf4[2] = extra_char; /* make it "VIa", "VIb", etc. */
7494 if (GetTempFileName(szTempFile, buf4, 0, itmp) == 0)
7495 return NULL;
7496 /* GetTempFileName() will create the file, we don't want that */
7497 (void)DeleteFile(itmp);
7498
7499 /* Backslashes in a temp file name cause problems when filtering with
7500 * "sh". NOTE: This also checks 'shellcmdflag' to help those people who
7501 * didn't set 'shellslash'. */
7502 retval = vim_strsave(itmp);
7503 if (*p_shcf == '-' || p_ssl)
7504 for (p = retval; *p; ++p)
7505 if (*p == '\\')
7506 *p = '/';
7507 return retval;
7508
7509# else /* WIN3264 */
7510
7511# ifdef USE_TMPNAM
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007512 char_u *p;
7513
Bram Moolenaar071d4272004-06-13 20:20:40 +00007514 /* tmpnam() will make its own name */
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007515 p = tmpnam((char *)itmp);
7516 if (p == NULL || *p == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007517 return NULL;
7518# else
7519 char_u *p;
7520
7521# ifdef VMS_TEMPNAM
7522 /* mktemp() is not working on VMS. It seems to be
7523 * a do-nothing function. Therefore we use tempnam().
7524 */
7525 sprintf((char *)itmp, "VIM%c", extra_char);
7526 p = (char_u *)tempnam("tmp:", (char *)itmp);
7527 if (p != NULL)
7528 {
7529 /* VMS will use '.LOG' if we don't explicitly specify an extension,
7530 * and VIM will then be unable to find the file later */
7531 STRCPY(itmp, p);
7532 STRCAT(itmp, ".txt");
7533 free(p);
7534 }
7535 else
7536 return NULL;
7537# else
7538 STRCPY(itmp, TEMPNAME);
7539 if ((p = vim_strchr(itmp, '?')) != NULL)
7540 *p = extra_char;
7541 if (mktemp((char *)itmp) == NULL)
7542 return NULL;
7543# endif
7544# endif
7545
7546 return vim_strsave(itmp);
7547# endif /* WIN3264 */
7548#endif /* TEMPDIRNAMES */
7549}
7550
7551#if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
7552/*
7553 * Convert all backslashes in fname to forward slashes in-place.
7554 */
7555 void
7556forward_slash(fname)
7557 char_u *fname;
7558{
7559 char_u *p;
7560
7561 for (p = fname; *p != NUL; ++p)
7562# ifdef FEAT_MBYTE
7563 /* The Big5 encoding can have '\' in the trail byte. */
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00007564 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007565 ++p;
7566 else
7567# endif
7568 if (*p == '\\')
7569 *p = '/';
7570}
7571#endif
7572
7573
7574/*
7575 * Code for automatic commands.
7576 *
7577 * Only included when "FEAT_AUTOCMD" has been defined.
7578 */
7579
7580#if defined(FEAT_AUTOCMD) || defined(PROTO)
7581
7582/*
7583 * The autocommands are stored in a list for each event.
7584 * Autocommands for the same pattern, that are consecutive, are joined
7585 * together, to avoid having to match the pattern too often.
7586 * The result is an array of Autopat lists, which point to AutoCmd lists:
7587 *
7588 * first_autopat[0] --> Autopat.next --> Autopat.next --> NULL
7589 * Autopat.cmds Autopat.cmds
7590 * | |
7591 * V V
7592 * AutoCmd.next AutoCmd.next
7593 * | |
7594 * V V
7595 * AutoCmd.next NULL
7596 * |
7597 * V
7598 * NULL
7599 *
7600 * first_autopat[1] --> Autopat.next --> NULL
7601 * Autopat.cmds
7602 * |
7603 * V
7604 * AutoCmd.next
7605 * |
7606 * V
7607 * NULL
7608 * etc.
7609 *
7610 * The order of AutoCmds is important, this is the order in which they were
7611 * defined and will have to be executed.
7612 */
7613typedef struct AutoCmd
7614{
7615 char_u *cmd; /* The command to be executed (NULL
7616 when command has been removed) */
7617 char nested; /* If autocommands nest here */
7618 char last; /* last command in list */
7619#ifdef FEAT_EVAL
7620 scid_T scriptID; /* script ID where defined */
7621#endif
7622 struct AutoCmd *next; /* Next AutoCmd in list */
7623} AutoCmd;
7624
7625typedef struct AutoPat
7626{
Bram Moolenaar071d4272004-06-13 20:20:40 +00007627 char_u *pat; /* pattern as typed (NULL when pattern
7628 has been removed) */
Bram Moolenaar748bf032005-02-02 23:04:36 +00007629 regprog_T *reg_prog; /* compiled regprog for pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007630 AutoCmd *cmds; /* list of commands to do */
7631 struct AutoPat *next; /* next AutoPat in AutoPat list */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007632 int group; /* group ID */
7633 int patlen; /* strlen() of pat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007634 int buflocal_nr; /* !=0 for buffer-local AutoPat */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007635 char allow_dirs; /* Pattern may match whole path */
7636 char last; /* last pattern for apply_autocmds() */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007637} AutoPat;
7638
7639static struct event_name
7640{
7641 char *name; /* event name */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007642 event_T event; /* event number */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007643} event_names[] =
7644{
7645 {"BufAdd", EVENT_BUFADD},
7646 {"BufCreate", EVENT_BUFADD},
7647 {"BufDelete", EVENT_BUFDELETE},
7648 {"BufEnter", EVENT_BUFENTER},
7649 {"BufFilePost", EVENT_BUFFILEPOST},
7650 {"BufFilePre", EVENT_BUFFILEPRE},
7651 {"BufHidden", EVENT_BUFHIDDEN},
7652 {"BufLeave", EVENT_BUFLEAVE},
7653 {"BufNew", EVENT_BUFNEW},
7654 {"BufNewFile", EVENT_BUFNEWFILE},
7655 {"BufRead", EVENT_BUFREADPOST},
7656 {"BufReadCmd", EVENT_BUFREADCMD},
7657 {"BufReadPost", EVENT_BUFREADPOST},
7658 {"BufReadPre", EVENT_BUFREADPRE},
7659 {"BufUnload", EVENT_BUFUNLOAD},
7660 {"BufWinEnter", EVENT_BUFWINENTER},
7661 {"BufWinLeave", EVENT_BUFWINLEAVE},
7662 {"BufWipeout", EVENT_BUFWIPEOUT},
7663 {"BufWrite", EVENT_BUFWRITEPRE},
7664 {"BufWritePost", EVENT_BUFWRITEPOST},
7665 {"BufWritePre", EVENT_BUFWRITEPRE},
7666 {"BufWriteCmd", EVENT_BUFWRITECMD},
7667 {"CmdwinEnter", EVENT_CMDWINENTER},
7668 {"CmdwinLeave", EVENT_CMDWINLEAVE},
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007669 {"ColorScheme", EVENT_COLORSCHEME},
Bram Moolenaarcfa3cae2012-07-10 17:14:56 +02007670 {"CompleteDone", EVENT_COMPLETEDONE},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007671 {"CursorHold", EVENT_CURSORHOLD},
7672 {"CursorHoldI", EVENT_CURSORHOLDI},
7673 {"CursorMoved", EVENT_CURSORMOVED},
7674 {"CursorMovedI", EVENT_CURSORMOVEDI},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007675 {"EncodingChanged", EVENT_ENCODINGCHANGED},
7676 {"FileEncoding", EVENT_ENCODINGCHANGED},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007677 {"FileAppendPost", EVENT_FILEAPPENDPOST},
7678 {"FileAppendPre", EVENT_FILEAPPENDPRE},
7679 {"FileAppendCmd", EVENT_FILEAPPENDCMD},
7680 {"FileChangedShell",EVENT_FILECHANGEDSHELL},
Bram Moolenaar56718732006-03-15 22:53:57 +00007681 {"FileChangedShellPost",EVENT_FILECHANGEDSHELLPOST},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007682 {"FileChangedRO", EVENT_FILECHANGEDRO},
7683 {"FileReadPost", EVENT_FILEREADPOST},
7684 {"FileReadPre", EVENT_FILEREADPRE},
7685 {"FileReadCmd", EVENT_FILEREADCMD},
7686 {"FileType", EVENT_FILETYPE},
7687 {"FileWritePost", EVENT_FILEWRITEPOST},
7688 {"FileWritePre", EVENT_FILEWRITEPRE},
7689 {"FileWriteCmd", EVENT_FILEWRITECMD},
7690 {"FilterReadPost", EVENT_FILTERREADPOST},
7691 {"FilterReadPre", EVENT_FILTERREADPRE},
7692 {"FilterWritePost", EVENT_FILTERWRITEPOST},
7693 {"FilterWritePre", EVENT_FILTERWRITEPRE},
7694 {"FocusGained", EVENT_FOCUSGAINED},
7695 {"FocusLost", EVENT_FOCUSLOST},
7696 {"FuncUndefined", EVENT_FUNCUNDEFINED},
7697 {"GUIEnter", EVENT_GUIENTER},
Bram Moolenaar265e5072006-08-29 16:13:22 +00007698 {"GUIFailed", EVENT_GUIFAILED},
Bram Moolenaar843ee412004-06-30 16:16:41 +00007699 {"InsertChange", EVENT_INSERTCHANGE},
7700 {"InsertEnter", EVENT_INSERTENTER},
7701 {"InsertLeave", EVENT_INSERTLEAVE},
Bram Moolenaare659c952011-05-19 17:25:41 +02007702 {"InsertCharPre", EVENT_INSERTCHARPRE},
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00007703 {"MenuPopup", EVENT_MENUPOPUP},
Bram Moolenaar7c626922005-02-07 22:01:03 +00007704 {"QuickFixCmdPost", EVENT_QUICKFIXCMDPOST},
7705 {"QuickFixCmdPre", EVENT_QUICKFIXCMDPRE},
Bram Moolenaar3b53dfb2012-06-06 18:03:07 +02007706 {"QuitPre", EVENT_QUITPRE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007707 {"RemoteReply", EVENT_REMOTEREPLY},
Bram Moolenaar9372a112005-12-06 19:59:18 +00007708 {"SessionLoadPost", EVENT_SESSIONLOADPOST},
Bram Moolenaar5c4bab02006-03-10 21:37:46 +00007709 {"ShellCmdPost", EVENT_SHELLCMDPOST},
7710 {"ShellFilterPost", EVENT_SHELLFILTERPOST},
Bram Moolenaara2031822006-03-07 22:29:51 +00007711 {"SourcePre", EVENT_SOURCEPRE},
Bram Moolenaar8dd1aa52007-01-16 20:33:19 +00007712 {"SourceCmd", EVENT_SOURCECMD},
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00007713 {"SpellFileMissing",EVENT_SPELLFILEMISSING},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007714 {"StdinReadPost", EVENT_STDINREADPOST},
7715 {"StdinReadPre", EVENT_STDINREADPRE},
Bram Moolenaarb815dac2005-12-07 20:59:24 +00007716 {"SwapExists", EVENT_SWAPEXISTS},
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00007717 {"Syntax", EVENT_SYNTAX},
Bram Moolenaar70836c82006-02-20 21:28:49 +00007718 {"TabEnter", EVENT_TABENTER},
7719 {"TabLeave", EVENT_TABLEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007720 {"TermChanged", EVENT_TERMCHANGED},
7721 {"TermResponse", EVENT_TERMRESPONSE},
Bram Moolenaar186628f2013-03-19 13:33:23 +01007722 {"TextChanged", EVENT_TEXTCHANGED},
7723 {"TextChangedI", EVENT_TEXTCHANGEDI},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007724 {"User", EVENT_USER},
7725 {"VimEnter", EVENT_VIMENTER},
7726 {"VimLeave", EVENT_VIMLEAVE},
7727 {"VimLeavePre", EVENT_VIMLEAVEPRE},
7728 {"WinEnter", EVENT_WINENTER},
7729 {"WinLeave", EVENT_WINLEAVE},
Bram Moolenaar56718732006-03-15 22:53:57 +00007730 {"VimResized", EVENT_VIMRESIZED},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007731 {NULL, (event_T)0}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007732};
7733
7734static AutoPat *first_autopat[NUM_EVENTS] =
7735{
7736 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7737 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7738 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7739 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00007740 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7741 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007742};
7743
7744/*
7745 * struct used to keep status while executing autocommands for an event.
7746 */
7747typedef struct AutoPatCmd
7748{
7749 AutoPat *curpat; /* next AutoPat to examine */
7750 AutoCmd *nextcmd; /* next AutoCmd to execute */
7751 int group; /* group being used */
7752 char_u *fname; /* fname to match with */
7753 char_u *sfname; /* sfname to match with */
7754 char_u *tail; /* tail of fname */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007755 event_T event; /* current event */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007756 int arg_bufnr; /* initially equal to <abuf>, set to zero when
7757 buf is deleted */
7758 struct AutoPatCmd *next; /* chain of active apc-s for auto-invalidation*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00007759} AutoPatCmd;
7760
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007761static AutoPatCmd *active_apc_list = NULL; /* stack of active autocommands */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007762
Bram Moolenaar071d4272004-06-13 20:20:40 +00007763/*
7764 * augroups stores a list of autocmd group names.
7765 */
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007766static garray_T augroups = {0, 0, sizeof(char_u *), 10, NULL};
Bram Moolenaar071d4272004-06-13 20:20:40 +00007767#define AUGROUP_NAME(i) (((char_u **)augroups.ga_data)[i])
7768
7769/*
7770 * The ID of the current group. Group 0 is the default one.
7771 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007772static int current_augroup = AUGROUP_DEFAULT;
7773
7774static int au_need_clean = FALSE; /* need to delete marked patterns */
7775
Bram Moolenaar754b5602006-02-09 23:53:20 +00007776static void show_autocmd __ARGS((AutoPat *ap, event_T event));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007777static void au_remove_pat __ARGS((AutoPat *ap));
7778static void au_remove_cmds __ARGS((AutoPat *ap));
7779static void au_cleanup __ARGS((void));
7780static int au_new_group __ARGS((char_u *name));
7781static void au_del_group __ARGS((char_u *name));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007782static event_T event_name2nr __ARGS((char_u *start, char_u **end));
7783static char_u *event_nr2name __ARGS((event_T event));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007784static char_u *find_end_event __ARGS((char_u *arg, int have_group));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007785static int event_ignored __ARGS((event_T event));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007786static int au_get_grouparg __ARGS((char_u **argp));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007787static int do_autocmd_event __ARGS((event_T event, char_u *pat, int nested, char_u *cmd, int forceit, int group));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007788static int apply_autocmds_group __ARGS((event_T event, char_u *fname, char_u *fname_io, int force, int group, buf_T *buf, exarg_T *eap));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007789static void auto_next_pat __ARGS((AutoPatCmd *apc, int stop_at_last));
7790
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007791
Bram Moolenaar754b5602006-02-09 23:53:20 +00007792static event_T last_event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007793static int last_group;
Bram Moolenaar78ab3312007-09-29 12:16:41 +00007794static int autocmd_blocked = 0; /* block all autocmds */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007795
7796/*
7797 * Show the autocommands for one AutoPat.
7798 */
7799 static void
7800show_autocmd(ap, event)
7801 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007802 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007803{
7804 AutoCmd *ac;
7805
7806 /* Check for "got_int" (here and at various places below), which is set
7807 * when "q" has been hit for the "--more--" prompt */
7808 if (got_int)
7809 return;
7810 if (ap->pat == NULL) /* pattern has been removed */
7811 return;
7812
7813 msg_putchar('\n');
7814 if (got_int)
7815 return;
7816 if (event != last_event || ap->group != last_group)
7817 {
7818 if (ap->group != AUGROUP_DEFAULT)
7819 {
7820 if (AUGROUP_NAME(ap->group) == NULL)
7821 msg_puts_attr((char_u *)_("--Deleted--"), hl_attr(HLF_E));
7822 else
7823 msg_puts_attr(AUGROUP_NAME(ap->group), hl_attr(HLF_T));
7824 msg_puts((char_u *)" ");
7825 }
7826 msg_puts_attr(event_nr2name(event), hl_attr(HLF_T));
7827 last_event = event;
7828 last_group = ap->group;
7829 msg_putchar('\n');
7830 if (got_int)
7831 return;
7832 }
7833 msg_col = 4;
7834 msg_outtrans(ap->pat);
7835
7836 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7837 {
7838 if (ac->cmd != NULL) /* skip removed commands */
7839 {
7840 if (msg_col >= 14)
7841 msg_putchar('\n');
7842 msg_col = 14;
7843 if (got_int)
7844 return;
7845 msg_outtrans(ac->cmd);
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00007846#ifdef FEAT_EVAL
7847 if (p_verbose > 0)
7848 last_set_msg(ac->scriptID);
7849#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007850 if (got_int)
7851 return;
7852 if (ac->next != NULL)
7853 {
7854 msg_putchar('\n');
7855 if (got_int)
7856 return;
7857 }
7858 }
7859 }
7860}
7861
7862/*
7863 * Mark an autocommand pattern for deletion.
7864 */
7865 static void
7866au_remove_pat(ap)
7867 AutoPat *ap;
7868{
7869 vim_free(ap->pat);
7870 ap->pat = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007871 ap->buflocal_nr = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007872 au_need_clean = TRUE;
7873}
7874
7875/*
7876 * Mark all commands for a pattern for deletion.
7877 */
7878 static void
7879au_remove_cmds(ap)
7880 AutoPat *ap;
7881{
7882 AutoCmd *ac;
7883
7884 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7885 {
7886 vim_free(ac->cmd);
7887 ac->cmd = NULL;
7888 }
7889 au_need_clean = TRUE;
7890}
7891
7892/*
7893 * Cleanup autocommands and patterns that have been deleted.
7894 * This is only done when not executing autocommands.
7895 */
7896 static void
7897au_cleanup()
7898{
7899 AutoPat *ap, **prev_ap;
7900 AutoCmd *ac, **prev_ac;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007901 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007902
7903 if (autocmd_busy || !au_need_clean)
7904 return;
7905
7906 /* loop over all events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007907 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7908 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007909 {
7910 /* loop over all autocommand patterns */
7911 prev_ap = &(first_autopat[(int)event]);
7912 for (ap = *prev_ap; ap != NULL; ap = *prev_ap)
7913 {
7914 /* loop over all commands for this pattern */
7915 prev_ac = &(ap->cmds);
7916 for (ac = *prev_ac; ac != NULL; ac = *prev_ac)
7917 {
7918 /* remove the command if the pattern is to be deleted or when
7919 * the command has been marked for deletion */
7920 if (ap->pat == NULL || ac->cmd == NULL)
7921 {
7922 *prev_ac = ac->next;
7923 vim_free(ac->cmd);
7924 vim_free(ac);
7925 }
7926 else
7927 prev_ac = &(ac->next);
7928 }
7929
7930 /* remove the pattern if it has been marked for deletion */
7931 if (ap->pat == NULL)
7932 {
7933 *prev_ap = ap->next;
Bram Moolenaar473de612013-06-08 18:19:48 +02007934 vim_regfree(ap->reg_prog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007935 vim_free(ap);
7936 }
7937 else
7938 prev_ap = &(ap->next);
7939 }
7940 }
7941
7942 au_need_clean = FALSE;
7943}
7944
7945/*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007946 * Called when buffer is freed, to remove/invalidate related buffer-local
7947 * autocmds.
7948 */
7949 void
7950aubuflocal_remove(buf)
7951 buf_T *buf;
7952{
7953 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007954 event_T event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007955 AutoPatCmd *apc;
7956
7957 /* invalidate currently executing autocommands */
7958 for (apc = active_apc_list; apc; apc = apc->next)
7959 if (buf->b_fnum == apc->arg_bufnr)
7960 apc->arg_bufnr = 0;
7961
7962 /* invalidate buflocals looping through events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007963 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7964 event = (event_T)((int)event + 1))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007965 /* loop over all autocommand patterns */
7966 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
7967 if (ap->buflocal_nr == buf->b_fnum)
7968 {
7969 au_remove_pat(ap);
7970 if (p_verbose >= 6)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007971 {
7972 verbose_enter();
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007973 smsg((char_u *)
7974 _("auto-removing autocommand: %s <buffer=%d>"),
7975 event_nr2name(event), buf->b_fnum);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007976 verbose_leave();
7977 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007978 }
7979 au_cleanup();
7980}
7981
7982/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007983 * Add an autocmd group name.
7984 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
7985 */
7986 static int
7987au_new_group(name)
7988 char_u *name;
7989{
7990 int i;
7991
7992 i = au_find_group(name);
7993 if (i == AUGROUP_ERROR) /* the group doesn't exist yet, add it */
7994 {
7995 /* First try using a free entry. */
7996 for (i = 0; i < augroups.ga_len; ++i)
7997 if (AUGROUP_NAME(i) == NULL)
7998 break;
7999 if (i == augroups.ga_len && ga_grow(&augroups, 1) == FAIL)
8000 return AUGROUP_ERROR;
8001
8002 AUGROUP_NAME(i) = vim_strsave(name);
8003 if (AUGROUP_NAME(i) == NULL)
8004 return AUGROUP_ERROR;
8005 if (i == augroups.ga_len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008006 ++augroups.ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008007 }
8008
8009 return i;
8010}
8011
8012 static void
8013au_del_group(name)
8014 char_u *name;
8015{
8016 int i;
8017
8018 i = au_find_group(name);
8019 if (i == AUGROUP_ERROR) /* the group doesn't exist */
8020 EMSG2(_("E367: No such group: \"%s\""), name);
8021 else
8022 {
8023 vim_free(AUGROUP_NAME(i));
8024 AUGROUP_NAME(i) = NULL;
8025 }
8026}
8027
8028/*
8029 * Find the ID of an autocmd group name.
8030 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
8031 */
8032 static int
8033au_find_group(name)
8034 char_u *name;
8035{
8036 int i;
8037
8038 for (i = 0; i < augroups.ga_len; ++i)
8039 if (AUGROUP_NAME(i) != NULL && STRCMP(AUGROUP_NAME(i), name) == 0)
8040 return i;
8041 return AUGROUP_ERROR;
8042}
8043
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008044/*
8045 * Return TRUE if augroup "name" exists.
8046 */
8047 int
8048au_has_group(name)
8049 char_u *name;
8050{
8051 return au_find_group(name) != AUGROUP_ERROR;
8052}
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008053
Bram Moolenaar071d4272004-06-13 20:20:40 +00008054/*
8055 * ":augroup {name}".
8056 */
8057 void
8058do_augroup(arg, del_group)
8059 char_u *arg;
8060 int del_group;
8061{
8062 int i;
8063
8064 if (del_group)
8065 {
8066 if (*arg == NUL)
8067 EMSG(_(e_argreq));
8068 else
8069 au_del_group(arg);
8070 }
8071 else if (STRICMP(arg, "end") == 0) /* ":aug end": back to group 0 */
8072 current_augroup = AUGROUP_DEFAULT;
8073 else if (*arg) /* ":aug xxx": switch to group xxx */
8074 {
8075 i = au_new_group(arg);
8076 if (i != AUGROUP_ERROR)
8077 current_augroup = i;
8078 }
8079 else /* ":aug": list the group names */
8080 {
8081 msg_start();
8082 for (i = 0; i < augroups.ga_len; ++i)
8083 {
8084 if (AUGROUP_NAME(i) != NULL)
8085 {
8086 msg_puts(AUGROUP_NAME(i));
8087 msg_puts((char_u *)" ");
8088 }
8089 }
8090 msg_clr_eos();
8091 msg_end();
8092 }
8093}
8094
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008095#if defined(EXITFREE) || defined(PROTO)
8096 void
8097free_all_autocmds()
8098{
8099 for (current_augroup = -1; current_augroup < augroups.ga_len;
8100 ++current_augroup)
8101 do_autocmd((char_u *)"", TRUE);
8102 ga_clear_strings(&augroups);
8103}
8104#endif
8105
Bram Moolenaar071d4272004-06-13 20:20:40 +00008106/*
8107 * Return the event number for event name "start".
8108 * Return NUM_EVENTS if the event name was not found.
8109 * Return a pointer to the next event name in "end".
8110 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008111 static event_T
Bram Moolenaar071d4272004-06-13 20:20:40 +00008112event_name2nr(start, end)
8113 char_u *start;
8114 char_u **end;
8115{
8116 char_u *p;
8117 int i;
8118 int len;
8119
8120 /* the event name ends with end of line, a blank or a comma */
8121 for (p = start; *p && !vim_iswhite(*p) && *p != ','; ++p)
8122 ;
8123 for (i = 0; event_names[i].name != NULL; ++i)
8124 {
8125 len = (int)STRLEN(event_names[i].name);
8126 if (len == p - start && STRNICMP(event_names[i].name, start, len) == 0)
8127 break;
8128 }
8129 if (*p == ',')
8130 ++p;
8131 *end = p;
8132 if (event_names[i].name == NULL)
8133 return NUM_EVENTS;
8134 return event_names[i].event;
8135}
8136
8137/*
8138 * Return the name for event "event".
8139 */
8140 static char_u *
8141event_nr2name(event)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008142 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008143{
8144 int i;
8145
8146 for (i = 0; event_names[i].name != NULL; ++i)
8147 if (event_names[i].event == event)
8148 return (char_u *)event_names[i].name;
8149 return (char_u *)"Unknown";
8150}
8151
8152/*
8153 * Scan over the events. "*" stands for all events.
8154 */
8155 static char_u *
8156find_end_event(arg, have_group)
8157 char_u *arg;
8158 int have_group; /* TRUE when group name was found */
8159{
8160 char_u *pat;
8161 char_u *p;
8162
8163 if (*arg == '*')
8164 {
8165 if (arg[1] && !vim_iswhite(arg[1]))
8166 {
8167 EMSG2(_("E215: Illegal character after *: %s"), arg);
8168 return NULL;
8169 }
8170 pat = arg + 1;
8171 }
8172 else
8173 {
8174 for (pat = arg; *pat && !vim_iswhite(*pat); pat = p)
8175 {
8176 if ((int)event_name2nr(pat, &p) >= (int)NUM_EVENTS)
8177 {
8178 if (have_group)
8179 EMSG2(_("E216: No such event: %s"), pat);
8180 else
8181 EMSG2(_("E216: No such group or event: %s"), pat);
8182 return NULL;
8183 }
8184 }
8185 }
8186 return pat;
8187}
8188
8189/*
8190 * Return TRUE if "event" is included in 'eventignore'.
8191 */
8192 static int
8193event_ignored(event)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008194 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008195{
8196 char_u *p = p_ei;
8197
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008198 while (*p != NUL)
8199 {
8200 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8201 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008202 if (event_name2nr(p, &p) == event)
8203 return TRUE;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008204 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008205
8206 return FALSE;
8207}
8208
8209/*
8210 * Return OK when the contents of p_ei is valid, FAIL otherwise.
8211 */
8212 int
8213check_ei()
8214{
8215 char_u *p = p_ei;
8216
Bram Moolenaar071d4272004-06-13 20:20:40 +00008217 while (*p)
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008218 {
8219 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8220 {
8221 p += 3;
8222 if (*p == ',')
8223 ++p;
8224 }
8225 else if (event_name2nr(p, &p) == NUM_EVENTS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008226 return FAIL;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008227 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008228
8229 return OK;
8230}
8231
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008232# if defined(FEAT_SYN_HL) || defined(PROTO)
8233
8234/*
8235 * Add "what" to 'eventignore' to skip loading syntax highlighting for every
8236 * buffer loaded into the window. "what" must start with a comma.
8237 * Returns the old value of 'eventignore' in allocated memory.
8238 */
8239 char_u *
8240au_event_disable(what)
8241 char *what;
8242{
8243 char_u *new_ei;
8244 char_u *save_ei;
8245
8246 save_ei = vim_strsave(p_ei);
8247 if (save_ei != NULL)
8248 {
Bram Moolenaara5792f52005-11-23 21:25:05 +00008249 new_ei = vim_strnsave(p_ei, (int)(STRLEN(p_ei) + STRLEN(what)));
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008250 if (new_ei != NULL)
8251 {
Bram Moolenaar8cac9fd2010-03-02 12:48:05 +01008252 if (*what == ',' && *p_ei == NUL)
8253 STRCPY(new_ei, what + 1);
8254 else
8255 STRCAT(new_ei, what);
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008256 set_string_option_direct((char_u *)"ei", -1, new_ei,
8257 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008258 vim_free(new_ei);
8259 }
8260 }
8261 return save_ei;
8262}
8263
8264 void
8265au_event_restore(old_ei)
8266 char_u *old_ei;
8267{
8268 if (old_ei != NULL)
8269 {
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008270 set_string_option_direct((char_u *)"ei", -1, old_ei,
8271 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008272 vim_free(old_ei);
8273 }
8274}
8275# endif /* FEAT_SYN_HL */
8276
Bram Moolenaar071d4272004-06-13 20:20:40 +00008277/*
8278 * do_autocmd() -- implements the :autocmd command. Can be used in the
8279 * following ways:
8280 *
8281 * :autocmd <event> <pat> <cmd> Add <cmd> to the list of commands that
8282 * will be automatically executed for <event>
8283 * when editing a file matching <pat>, in
8284 * the current group.
8285 * :autocmd <event> <pat> Show the auto-commands associated with
8286 * <event> and <pat>.
8287 * :autocmd <event> Show the auto-commands associated with
8288 * <event>.
8289 * :autocmd Show all auto-commands.
8290 * :autocmd! <event> <pat> <cmd> Remove all auto-commands associated with
8291 * <event> and <pat>, and add the command
8292 * <cmd>, for the current group.
8293 * :autocmd! <event> <pat> Remove all auto-commands associated with
8294 * <event> and <pat> for the current group.
8295 * :autocmd! <event> Remove all auto-commands associated with
8296 * <event> for the current group.
8297 * :autocmd! Remove ALL auto-commands for the current
8298 * group.
8299 *
8300 * Multiple events and patterns may be given separated by commas. Here are
8301 * some examples:
8302 * :autocmd bufread,bufenter *.c,*.h set tw=0 smartindent noic
8303 * :autocmd bufleave * set tw=79 nosmartindent ic infercase
8304 *
8305 * :autocmd * *.c show all autocommands for *.c files.
Bram Moolenaard35f9712005-12-18 22:02:33 +00008306 *
8307 * Mostly a {group} argument can optionally appear before <event>.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008308 */
8309 void
8310do_autocmd(arg, forceit)
8311 char_u *arg;
8312 int forceit;
8313{
8314 char_u *pat;
8315 char_u *envpat = NULL;
8316 char_u *cmd;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008317 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008318 int need_free = FALSE;
8319 int nested = FALSE;
8320 int group;
8321
8322 /*
8323 * Check for a legal group name. If not, use AUGROUP_ALL.
8324 */
8325 group = au_get_grouparg(&arg);
8326 if (arg == NULL) /* out of memory */
8327 return;
8328
8329 /*
8330 * Scan over the events.
8331 * If we find an illegal name, return here, don't do anything.
8332 */
8333 pat = find_end_event(arg, group != AUGROUP_ALL);
8334 if (pat == NULL)
8335 return;
8336
8337 /*
8338 * Scan over the pattern. Put a NUL at the end.
8339 */
8340 pat = skipwhite(pat);
8341 cmd = pat;
8342 while (*cmd && (!vim_iswhite(*cmd) || cmd[-1] == '\\'))
8343 cmd++;
8344 if (*cmd)
8345 *cmd++ = NUL;
8346
8347 /* Expand environment variables in the pattern. Set 'shellslash', we want
8348 * forward slashes here. */
8349 if (vim_strchr(pat, '$') != NULL || vim_strchr(pat, '~') != NULL)
8350 {
8351#ifdef BACKSLASH_IN_FILENAME
8352 int p_ssl_save = p_ssl;
8353
8354 p_ssl = TRUE;
8355#endif
8356 envpat = expand_env_save(pat);
8357#ifdef BACKSLASH_IN_FILENAME
8358 p_ssl = p_ssl_save;
8359#endif
8360 if (envpat != NULL)
8361 pat = envpat;
8362 }
8363
8364 /*
8365 * Check for "nested" flag.
8366 */
8367 cmd = skipwhite(cmd);
8368 if (*cmd != NUL && STRNCMP(cmd, "nested", 6) == 0 && vim_iswhite(cmd[6]))
8369 {
8370 nested = TRUE;
8371 cmd = skipwhite(cmd + 6);
8372 }
8373
8374 /*
8375 * Find the start of the commands.
8376 * Expand <sfile> in it.
8377 */
8378 if (*cmd != NUL)
8379 {
8380 cmd = expand_sfile(cmd);
8381 if (cmd == NULL) /* some error */
8382 return;
8383 need_free = TRUE;
8384 }
8385
8386 /*
8387 * Print header when showing autocommands.
8388 */
8389 if (!forceit && *cmd == NUL)
8390 {
8391 /* Highlight title */
8392 MSG_PUTS_TITLE(_("\n--- Auto-Commands ---"));
8393 }
8394
8395 /*
8396 * Loop over the events.
8397 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008398 last_event = (event_T)-1; /* for listing the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008399 last_group = AUGROUP_ERROR; /* for listing the group name */
8400 if (*arg == '*' || *arg == NUL)
8401 {
Bram Moolenaar754b5602006-02-09 23:53:20 +00008402 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8403 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008404 if (do_autocmd_event(event, pat,
8405 nested, cmd, forceit, group) == FAIL)
8406 break;
8407 }
8408 else
8409 {
8410 while (*arg && !vim_iswhite(*arg))
8411 if (do_autocmd_event(event_name2nr(arg, &arg), pat,
8412 nested, cmd, forceit, group) == FAIL)
8413 break;
8414 }
8415
8416 if (need_free)
8417 vim_free(cmd);
8418 vim_free(envpat);
8419}
8420
8421/*
8422 * Find the group ID in a ":autocmd" or ":doautocmd" argument.
8423 * The "argp" argument is advanced to the following argument.
8424 *
8425 * Returns the group ID, AUGROUP_ERROR for error (out of memory).
8426 */
8427 static int
8428au_get_grouparg(argp)
8429 char_u **argp;
8430{
8431 char_u *group_name;
8432 char_u *p;
8433 char_u *arg = *argp;
8434 int group = AUGROUP_ALL;
8435
8436 p = skiptowhite(arg);
8437 if (p > arg)
8438 {
8439 group_name = vim_strnsave(arg, (int)(p - arg));
8440 if (group_name == NULL) /* out of memory */
8441 return AUGROUP_ERROR;
8442 group = au_find_group(group_name);
8443 if (group == AUGROUP_ERROR)
8444 group = AUGROUP_ALL; /* no match, use all groups */
8445 else
8446 *argp = skipwhite(p); /* match, skip over group name */
8447 vim_free(group_name);
8448 }
8449 return group;
8450}
8451
8452/*
8453 * do_autocmd() for one event.
8454 * If *pat == NUL do for all patterns.
8455 * If *cmd == NUL show entries.
8456 * If forceit == TRUE delete entries.
8457 * If group is not AUGROUP_ALL, only use this group.
8458 */
8459 static int
8460do_autocmd_event(event, pat, nested, cmd, forceit, group)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008461 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008462 char_u *pat;
8463 int nested;
8464 char_u *cmd;
8465 int forceit;
8466 int group;
8467{
8468 AutoPat *ap;
8469 AutoPat **prev_ap;
8470 AutoCmd *ac;
8471 AutoCmd **prev_ac;
8472 int brace_level;
8473 char_u *endpat;
8474 int findgroup;
8475 int allgroups;
8476 int patlen;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00008477 int is_buflocal;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008478 int buflocal_nr;
8479 char_u buflocal_pat[25]; /* for "<buffer=X>" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008480
8481 if (group == AUGROUP_ALL)
8482 findgroup = current_augroup;
8483 else
8484 findgroup = group;
8485 allgroups = (group == AUGROUP_ALL && !forceit && *cmd == NUL);
8486
8487 /*
8488 * Show or delete all patterns for an event.
8489 */
8490 if (*pat == NUL)
8491 {
8492 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8493 {
8494 if (forceit) /* delete the AutoPat, if it's in the current group */
8495 {
8496 if (ap->group == findgroup)
8497 au_remove_pat(ap);
8498 }
8499 else if (group == AUGROUP_ALL || ap->group == group)
8500 show_autocmd(ap, event);
8501 }
8502 }
8503
8504 /*
8505 * Loop through all the specified patterns.
8506 */
8507 for ( ; *pat; pat = (*endpat == ',' ? endpat + 1 : endpat))
8508 {
8509 /*
8510 * Find end of the pattern.
8511 * Watch out for a comma in braces, like "*.\{obj,o\}".
8512 */
8513 brace_level = 0;
8514 for (endpat = pat; *endpat && (*endpat != ',' || brace_level
8515 || endpat[-1] == '\\'); ++endpat)
8516 {
8517 if (*endpat == '{')
8518 brace_level++;
8519 else if (*endpat == '}')
8520 brace_level--;
8521 }
8522 if (pat == endpat) /* ignore single comma */
8523 continue;
8524 patlen = (int)(endpat - pat);
8525
8526 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008527 * detect special <buflocal[=X]> buffer-local patterns
8528 */
8529 is_buflocal = FALSE;
8530 buflocal_nr = 0;
8531
8532 if (patlen >= 7 && STRNCMP(pat, "<buffer", 7) == 0
8533 && pat[patlen - 1] == '>')
8534 {
8535 /* Error will be printed only for addition. printing and removing
8536 * will proceed silently. */
8537 is_buflocal = TRUE;
8538 if (patlen == 8)
8539 buflocal_nr = curbuf->b_fnum;
8540 else if (patlen > 9 && pat[7] == '=')
8541 {
8542 /* <buffer=abuf> */
8543 if (patlen == 13 && STRNICMP(pat, "<buffer=abuf>", 13))
8544 buflocal_nr = autocmd_bufnr;
8545 /* <buffer=123> */
8546 else if (skipdigits(pat + 8) == pat + patlen - 1)
8547 buflocal_nr = atoi((char *)pat + 8);
8548 }
8549 }
8550
8551 if (is_buflocal)
8552 {
8553 /* normalize pat into standard "<buffer>#N" form */
8554 sprintf((char *)buflocal_pat, "<buffer=%d>", buflocal_nr);
8555 pat = buflocal_pat; /* can modify pat and patlen */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008556 patlen = (int)STRLEN(buflocal_pat); /* but not endpat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008557 }
8558
8559 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008560 * Find AutoPat entries with this pattern.
8561 */
8562 prev_ap = &first_autopat[(int)event];
8563 while ((ap = *prev_ap) != NULL)
8564 {
8565 if (ap->pat != NULL)
8566 {
8567 /* Accept a pattern when:
8568 * - a group was specified and it's that group, or a group was
8569 * not specified and it's the current group, or a group was
8570 * not specified and we are listing
8571 * - the length of the pattern matches
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008572 * - the pattern matches.
8573 * For <buffer[=X]>, this condition works because we normalize
8574 * all buffer-local patterns.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008575 */
8576 if ((allgroups || ap->group == findgroup)
8577 && ap->patlen == patlen
8578 && STRNCMP(pat, ap->pat, patlen) == 0)
8579 {
8580 /*
8581 * Remove existing autocommands.
8582 * If adding any new autocmd's for this AutoPat, don't
8583 * delete the pattern from the autopat list, append to
8584 * this list.
8585 */
8586 if (forceit)
8587 {
8588 if (*cmd != NUL && ap->next == NULL)
8589 {
8590 au_remove_cmds(ap);
8591 break;
8592 }
8593 au_remove_pat(ap);
8594 }
8595
8596 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008597 * Show autocmd's for this autopat, or buflocals <buffer=X>
Bram Moolenaar071d4272004-06-13 20:20:40 +00008598 */
8599 else if (*cmd == NUL)
8600 show_autocmd(ap, event);
8601
8602 /*
8603 * Add autocmd to this autopat, if it's the last one.
8604 */
8605 else if (ap->next == NULL)
8606 break;
8607 }
8608 }
8609 prev_ap = &ap->next;
8610 }
8611
8612 /*
8613 * Add a new command.
8614 */
8615 if (*cmd != NUL)
8616 {
8617 /*
8618 * If the pattern we want to add a command to does appear at the
8619 * end of the list (or not is not in the list at all), add the
8620 * pattern at the end of the list.
8621 */
8622 if (ap == NULL)
8623 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008624 /* refuse to add buffer-local ap if buffer number is invalid */
8625 if (is_buflocal && (buflocal_nr == 0
8626 || buflist_findnr(buflocal_nr) == NULL))
8627 {
8628 EMSGN(_("E680: <buffer=%d>: invalid buffer number "),
8629 buflocal_nr);
8630 return FAIL;
8631 }
8632
Bram Moolenaar071d4272004-06-13 20:20:40 +00008633 ap = (AutoPat *)alloc((unsigned)sizeof(AutoPat));
8634 if (ap == NULL)
8635 return FAIL;
8636 ap->pat = vim_strnsave(pat, patlen);
8637 ap->patlen = patlen;
8638 if (ap->pat == NULL)
8639 {
8640 vim_free(ap);
8641 return FAIL;
8642 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008643
8644 if (is_buflocal)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008645 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008646 ap->buflocal_nr = buflocal_nr;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008647 ap->reg_prog = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008648 }
8649 else
8650 {
Bram Moolenaar748bf032005-02-02 23:04:36 +00008651 char_u *reg_pat;
8652
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008653 ap->buflocal_nr = 0;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008654 reg_pat = file_pat_to_reg_pat(pat, endpat,
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008655 &ap->allow_dirs, TRUE);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008656 if (reg_pat != NULL)
8657 ap->reg_prog = vim_regcomp(reg_pat, RE_MAGIC);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008658 vim_free(reg_pat);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008659 if (reg_pat == NULL || ap->reg_prog == NULL)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008660 {
8661 vim_free(ap->pat);
8662 vim_free(ap);
8663 return FAIL;
8664 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008665 }
8666 ap->cmds = NULL;
8667 *prev_ap = ap;
8668 ap->next = NULL;
8669 if (group == AUGROUP_ALL)
8670 ap->group = current_augroup;
8671 else
8672 ap->group = group;
8673 }
8674
8675 /*
8676 * Add the autocmd at the end of the AutoCmd list.
8677 */
8678 prev_ac = &(ap->cmds);
8679 while ((ac = *prev_ac) != NULL)
8680 prev_ac = &ac->next;
8681 ac = (AutoCmd *)alloc((unsigned)sizeof(AutoCmd));
8682 if (ac == NULL)
8683 return FAIL;
8684 ac->cmd = vim_strsave(cmd);
8685#ifdef FEAT_EVAL
8686 ac->scriptID = current_SID;
8687#endif
8688 if (ac->cmd == NULL)
8689 {
8690 vim_free(ac);
8691 return FAIL;
8692 }
8693 ac->next = NULL;
8694 *prev_ac = ac;
8695 ac->nested = nested;
8696 }
8697 }
8698
8699 au_cleanup(); /* may really delete removed patterns/commands now */
8700 return OK;
8701}
8702
8703/*
8704 * Implementation of ":doautocmd [group] event [fname]".
8705 * Return OK for success, FAIL for failure;
8706 */
8707 int
8708do_doautocmd(arg, do_msg)
8709 char_u *arg;
8710 int do_msg; /* give message for no matching autocmds? */
8711{
8712 char_u *fname;
8713 int nothing_done = TRUE;
8714 int group;
8715
8716 /*
8717 * Check for a legal group name. If not, use AUGROUP_ALL.
8718 */
8719 group = au_get_grouparg(&arg);
8720 if (arg == NULL) /* out of memory */
8721 return FAIL;
8722
8723 if (*arg == '*')
8724 {
8725 EMSG(_("E217: Can't execute autocommands for ALL events"));
8726 return FAIL;
8727 }
8728
8729 /*
8730 * Scan over the events.
8731 * If we find an illegal name, return here, don't do anything.
8732 */
8733 fname = find_end_event(arg, group != AUGROUP_ALL);
8734 if (fname == NULL)
8735 return FAIL;
8736
8737 fname = skipwhite(fname);
8738
8739 /*
8740 * Loop over the events.
8741 */
8742 while (*arg && !vim_iswhite(*arg))
8743 if (apply_autocmds_group(event_name2nr(arg, &arg),
8744 fname, NULL, TRUE, group, curbuf, NULL))
8745 nothing_done = FALSE;
8746
8747 if (nothing_done && do_msg)
8748 MSG(_("No matching autocommands"));
8749
8750#ifdef FEAT_EVAL
8751 return aborting() ? FAIL : OK;
8752#else
8753 return OK;
8754#endif
8755}
8756
8757/*
8758 * ":doautoall": execute autocommands for each loaded buffer.
8759 */
8760 void
8761ex_doautoall(eap)
8762 exarg_T *eap;
8763{
8764 int retval;
8765 aco_save_T aco;
8766 buf_T *buf;
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008767 char_u *arg = eap->arg;
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008768 int call_do_modelines = check_nomodeline(&arg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008769
8770 /*
8771 * This is a bit tricky: For some commands curwin->w_buffer needs to be
8772 * equal to curbuf, but for some buffers there may not be a window.
8773 * So we change the buffer for the current window for a moment. This
8774 * gives problems when the autocommands make changes to the list of
8775 * buffers or windows...
8776 */
8777 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8778 {
Bram Moolenaar3a847972008-07-08 09:36:58 +00008779 if (buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008780 {
8781 /* find a window for this buffer and save some values */
8782 aucmd_prepbuf(&aco, buf);
8783
8784 /* execute the autocommands for this buffer */
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008785 retval = do_doautocmd(arg, FALSE);
Bram Moolenaareeefcc72007-05-01 21:21:21 +00008786
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008787 if (call_do_modelines)
8788 {
8789 /* Execute the modeline settings, but don't set window-local
8790 * options if we are using the current window for another
8791 * buffer. */
8792 do_modelines(curwin == aucmd_win ? OPT_NOWIN : 0);
8793 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008794
8795 /* restore the current window */
8796 aucmd_restbuf(&aco);
8797
8798 /* stop if there is some error or buffer was deleted */
8799 if (retval == FAIL || !buf_valid(buf))
8800 break;
8801 }
8802 }
8803
8804 check_cursor(); /* just in case lines got deleted */
8805}
8806
8807/*
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008808 * Check *argp for <nomodeline>. When it is present return FALSE, otherwise
8809 * return TRUE and advance *argp to after it.
8810 * Thus return TRUE when do_modelines() should be called.
8811 */
8812 int
8813check_nomodeline(argp)
8814 char_u **argp;
8815{
8816 if (STRNCMP(*argp, "<nomodeline>", 12) == 0)
8817 {
8818 *argp = skipwhite(*argp + 12);
8819 return FALSE;
8820 }
8821 return TRUE;
8822}
8823
8824/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008825 * Prepare for executing autocommands for (hidden) buffer "buf".
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008826 * Search for a visible window containing the current buffer. If there isn't
8827 * one then use "aucmd_win".
Bram Moolenaar071d4272004-06-13 20:20:40 +00008828 * Set "curbuf" and "curwin" to match "buf".
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00008829 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008830 */
8831 void
8832aucmd_prepbuf(aco, buf)
8833 aco_save_T *aco; /* structure to save values in */
8834 buf_T *buf; /* new curbuf */
8835{
8836 win_T *win;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008837#ifdef FEAT_WINDOWS
8838 int save_ea;
8839#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008840
8841 /* Find a window that is for the new buffer */
8842 if (buf == curbuf) /* be quick when buf is curbuf */
8843 win = curwin;
8844 else
8845#ifdef FEAT_WINDOWS
8846 for (win = firstwin; win != NULL; win = win->w_next)
8847 if (win->w_buffer == buf)
8848 break;
8849#else
8850 win = NULL;
8851#endif
8852
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008853 /* Allocate "aucmd_win" when needed. If this fails (out of memory) fall
8854 * back to using the current window. */
8855 if (win == NULL && aucmd_win == NULL)
8856 {
8857 win_alloc_aucmd_win();
8858 if (aucmd_win == NULL)
8859 win = curwin;
8860 }
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008861 if (win == NULL && aucmd_win_used)
8862 /* Strange recursive autocommand, fall back to using the current
8863 * window. Expect a few side effects... */
8864 win = curwin;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008865
8866 aco->save_curwin = curwin;
8867 aco->save_curbuf = curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008868 if (win != NULL)
8869 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008870 /* There is a window for "buf" in the current tab page, make it the
8871 * curwin. This is preferred, it has the least side effects (esp. if
8872 * "buf" is curbuf). */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008873 aco->use_aucmd_win = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008874 curwin = win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008875 }
8876 else
8877 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008878 /* There is no window for "buf", use "aucmd_win". To minimize the side
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02008879 * effects, insert it in the current tab page.
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008880 * Anything related to a window (e.g., setting folds) may have
8881 * unexpected results. */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008882 aco->use_aucmd_win = TRUE;
8883 aucmd_win_used = TRUE;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008884 aucmd_win->w_buffer = buf;
Bram Moolenaarcdddaa42010-06-07 23:07:44 +02008885 aucmd_win->w_s = &buf->b_s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008886 ++buf->b_nwindows;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008887 win_init_empty(aucmd_win); /* set cursor and topline to safe values */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008888 vim_free(aucmd_win->w_localdir);
8889 aucmd_win->w_localdir = NULL;
8890
8891 /* Make sure w_localdir and globaldir are NULL to avoid a chdir() in
8892 * win_enter_ext(). */
8893 aucmd_win->w_localdir = NULL;
8894 aco->globaldir = globaldir;
8895 globaldir = NULL;
8896
Bram Moolenaar071d4272004-06-13 20:20:40 +00008897
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008898#ifdef FEAT_WINDOWS
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008899 /* Split the current window, put the aucmd_win in the upper half.
8900 * We don't want the BufEnter or WinEnter autocommands. */
8901 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008902 make_snapshot(SNAP_AUCMD_IDX);
8903 save_ea = p_ea;
8904 p_ea = FALSE;
8905 (void)win_split_ins(0, WSP_TOP, aucmd_win, 0);
8906 (void)win_comp_pos(); /* recompute window positions */
8907 p_ea = save_ea;
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008908 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008909#endif
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008910 curwin = aucmd_win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008911 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008912 curbuf = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008913 aco->new_curwin = curwin;
8914 aco->new_curbuf = curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008915}
8916
8917/*
8918 * Cleanup after executing autocommands for a (hidden) buffer.
8919 * Restore the window as it was (if possible).
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00008920 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008921 */
8922 void
8923aucmd_restbuf(aco)
8924 aco_save_T *aco; /* structure holding saved values */
8925{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008926#ifdef FEAT_WINDOWS
8927 int dummy;
8928#endif
8929
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008930 if (aco->use_aucmd_win)
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008931 {
8932 --curbuf->b_nwindows;
8933#ifdef FEAT_WINDOWS
8934 /* Find "aucmd_win", it can't be closed, but it may be in another tab
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008935 * page. Do not trigger autocommands here. */
8936 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008937 if (curwin != aucmd_win)
8938 {
8939 tabpage_T *tp;
8940 win_T *wp;
8941
8942 FOR_ALL_TAB_WINDOWS(tp, wp)
8943 {
8944 if (wp == aucmd_win)
8945 {
8946 if (tp != curtab)
Bram Moolenaar49e649f2013-05-06 04:50:35 +02008947 goto_tabpage_tp(tp, TRUE, TRUE);
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008948 win_goto(aucmd_win);
Bram Moolenaar28f29082012-02-11 23:45:37 +01008949 goto win_found;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008950 }
8951 }
8952 }
Bram Moolenaar28f29082012-02-11 23:45:37 +01008953win_found:
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008954
8955 /* Remove the window and frame from the tree of frames. */
8956 (void)winframe_remove(curwin, &dummy, NULL);
8957 win_remove(curwin, NULL);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008958 aucmd_win_used = FALSE;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008959 last_status(FALSE); /* may need to remove last status line */
8960 restore_snapshot(SNAP_AUCMD_IDX, FALSE);
8961 (void)win_comp_pos(); /* recompute window positions */
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008962 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008963
8964 if (win_valid(aco->save_curwin))
8965 curwin = aco->save_curwin;
8966 else
8967 /* Hmm, original window disappeared. Just use the first one. */
8968 curwin = firstwin;
8969# ifdef FEAT_EVAL
Bram Moolenaar429fa852013-04-15 12:27:36 +02008970 vars_clear(&aucmd_win->w_vars->dv_hashtab); /* free all w: variables */
8971 hash_init(&aucmd_win->w_vars->dv_hashtab); /* re-use the hashtab */
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008972# endif
8973#else
8974 curwin = aco->save_curwin;
8975#endif
8976 curbuf = curwin->w_buffer;
8977
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008978 vim_free(globaldir);
8979 globaldir = aco->globaldir;
8980
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008981 /* the buffer contents may have changed */
8982 check_cursor();
8983 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
8984 {
8985 curwin->w_topline = curbuf->b_ml.ml_line_count;
8986#ifdef FEAT_DIFF
8987 curwin->w_topfill = 0;
8988#endif
8989 }
8990#if defined(FEAT_GUI)
8991 /* Hide the scrollbars from the aucmd_win and update. */
8992 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_LEFT], FALSE);
8993 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_RIGHT], FALSE);
8994 gui_may_update_scrollbars();
8995#endif
8996 }
8997 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00008998 {
8999 /* restore curwin */
9000#ifdef FEAT_WINDOWS
9001 if (win_valid(aco->save_curwin))
9002#endif
9003 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009004 /* Restore the buffer which was previously edited by curwin, if
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009005 * it was changed, we are still the same window and the buffer is
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009006 * valid. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009007 if (curwin == aco->new_curwin
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009008 && curbuf != aco->new_curbuf
9009 && buf_valid(aco->new_curbuf)
9010 && aco->new_curbuf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009011 {
Bram Moolenaar7da9c372012-04-30 17:04:52 +02009012# if defined(FEAT_SYN_HL) || defined(FEAT_SPELL)
9013 if (curwin->w_s == &curbuf->b_s)
9014 curwin->w_s = &aco->new_curbuf->b_s;
9015# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009016 --curbuf->b_nwindows;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009017 curbuf = aco->new_curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009018 curwin->w_buffer = curbuf;
9019 ++curbuf->b_nwindows;
9020 }
9021
9022 curwin = aco->save_curwin;
9023 curbuf = curwin->w_buffer;
9024 }
9025 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009026}
9027
9028static int autocmd_nested = FALSE;
9029
9030/*
9031 * Execute autocommands for "event" and file name "fname".
9032 * Return TRUE if some commands were executed.
9033 */
9034 int
9035apply_autocmds(event, fname, fname_io, force, buf)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009036 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009037 char_u *fname; /* NULL or empty means use actual file name */
9038 char_u *fname_io; /* fname to use for <afile> on cmdline */
9039 int force; /* when TRUE, ignore autocmd_busy */
9040 buf_T *buf; /* buffer for <abuf> */
9041{
9042 return apply_autocmds_group(event, fname, fname_io, force,
9043 AUGROUP_ALL, buf, NULL);
9044}
9045
9046/*
9047 * Like apply_autocmds(), but with extra "eap" argument. This takes care of
9048 * setting v:filearg.
9049 */
9050 static int
9051apply_autocmds_exarg(event, fname, fname_io, force, buf, eap)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009052 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009053 char_u *fname;
9054 char_u *fname_io;
9055 int force;
9056 buf_T *buf;
9057 exarg_T *eap;
9058{
9059 return apply_autocmds_group(event, fname, fname_io, force,
9060 AUGROUP_ALL, buf, eap);
9061}
9062
9063/*
9064 * Like apply_autocmds(), but handles the caller's retval. If the script
9065 * processing is being aborted or if retval is FAIL when inside a try
9066 * conditional, no autocommands are executed. If otherwise the autocommands
9067 * cause the script to be aborted, retval is set to FAIL.
9068 */
9069 int
9070apply_autocmds_retval(event, fname, fname_io, force, buf, retval)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009071 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009072 char_u *fname; /* NULL or empty means use actual file name */
9073 char_u *fname_io; /* fname to use for <afile> on cmdline */
9074 int force; /* when TRUE, ignore autocmd_busy */
9075 buf_T *buf; /* buffer for <abuf> */
9076 int *retval; /* pointer to caller's retval */
9077{
9078 int did_cmd;
9079
Bram Moolenaar1e015462005-09-25 22:16:38 +00009080#ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00009081 if (should_abort(*retval))
9082 return FALSE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00009083#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009084
9085 did_cmd = apply_autocmds_group(event, fname, fname_io, force,
9086 AUGROUP_ALL, buf, NULL);
Bram Moolenaar1e015462005-09-25 22:16:38 +00009087 if (did_cmd
9088#ifdef FEAT_EVAL
9089 && aborting()
9090#endif
9091 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00009092 *retval = FAIL;
9093 return did_cmd;
9094}
9095
Bram Moolenaard35f9712005-12-18 22:02:33 +00009096/*
9097 * Return TRUE when there is a CursorHold autocommand defined.
9098 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009099 int
9100has_cursorhold()
9101{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009102 return (first_autopat[(int)(get_real_state() == NORMAL_BUSY
9103 ? EVENT_CURSORHOLD : EVENT_CURSORHOLDI)] != NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009104}
Bram Moolenaard35f9712005-12-18 22:02:33 +00009105
9106/*
9107 * Return TRUE if the CursorHold event can be triggered.
9108 */
9109 int
9110trigger_cursorhold()
9111{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009112 int state;
9113
Bram Moolenaar05334432011-07-20 18:29:39 +02009114 if (!did_cursorhold
9115 && has_cursorhold()
9116 && !Recording
9117 && typebuf.tb_len == 0
Bram Moolenaard29a9ee2006-09-14 09:07:34 +00009118#ifdef FEAT_INS_EXPAND
9119 && !ins_compl_active()
9120#endif
9121 )
Bram Moolenaar754b5602006-02-09 23:53:20 +00009122 {
9123 state = get_real_state();
9124 if (state == NORMAL_BUSY || (state & INSERT) != 0)
9125 return TRUE;
9126 }
9127 return FALSE;
Bram Moolenaard35f9712005-12-18 22:02:33 +00009128}
Bram Moolenaar754b5602006-02-09 23:53:20 +00009129
9130/*
9131 * Return TRUE when there is a CursorMoved autocommand defined.
9132 */
9133 int
9134has_cursormoved()
9135{
9136 return (first_autopat[(int)EVENT_CURSORMOVED] != NULL);
9137}
9138
9139/*
9140 * Return TRUE when there is a CursorMovedI autocommand defined.
9141 */
9142 int
9143has_cursormovedI()
9144{
9145 return (first_autopat[(int)EVENT_CURSORMOVEDI] != NULL);
9146}
Bram Moolenaar071d4272004-06-13 20:20:40 +00009147
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009148/*
Bram Moolenaar186628f2013-03-19 13:33:23 +01009149 * Return TRUE when there is a TextChanged autocommand defined.
9150 */
9151 int
9152has_textchanged()
9153{
9154 return (first_autopat[(int)EVENT_TEXTCHANGED] != NULL);
9155}
9156
9157/*
9158 * Return TRUE when there is a TextChangedI autocommand defined.
9159 */
9160 int
9161has_textchangedI()
9162{
9163 return (first_autopat[(int)EVENT_TEXTCHANGEDI] != NULL);
9164}
9165
9166/*
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009167 * Return TRUE when there is an InsertCharPre autocommand defined.
9168 */
9169 int
9170has_insertcharpre()
9171{
9172 return (first_autopat[(int)EVENT_INSERTCHARPRE] != NULL);
9173}
9174
Bram Moolenaar071d4272004-06-13 20:20:40 +00009175 static int
9176apply_autocmds_group(event, fname, fname_io, force, group, buf, eap)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009177 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009178 char_u *fname; /* NULL or empty means use actual file name */
9179 char_u *fname_io; /* fname to use for <afile> on cmdline, NULL means
9180 use fname */
9181 int force; /* when TRUE, ignore autocmd_busy */
9182 int group; /* group ID, or AUGROUP_ALL */
9183 buf_T *buf; /* buffer for <abuf> */
9184 exarg_T *eap; /* command arguments */
9185{
9186 char_u *sfname = NULL; /* short file name */
9187 char_u *tail;
9188 int save_changed;
9189 buf_T *old_curbuf;
9190 int retval = FALSE;
9191 char_u *save_sourcing_name;
9192 linenr_T save_sourcing_lnum;
9193 char_u *save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009194 int save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009195 int save_autocmd_bufnr;
9196 char_u *save_autocmd_match;
9197 int save_autocmd_busy;
9198 int save_autocmd_nested;
9199 static int nesting = 0;
9200 AutoPatCmd patcmd;
9201 AutoPat *ap;
9202#ifdef FEAT_EVAL
9203 scid_T save_current_SID;
9204 void *save_funccalp;
9205 char_u *save_cmdarg;
9206 long save_cmdbang;
9207#endif
9208 static int filechangeshell_busy = FALSE;
Bram Moolenaar05159a02005-02-26 23:04:13 +00009209#ifdef FEAT_PROFILE
9210 proftime_T wait_time;
9211#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009212
9213 /*
9214 * Quickly return if there are no autocommands for this event or
9215 * autocommands are blocked.
9216 */
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009217 if (first_autopat[(int)event] == NULL || autocmd_blocked > 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009218 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009219
9220 /*
9221 * When autocommands are busy, new autocommands are only executed when
9222 * explicitly enabled with the "nested" flag.
9223 */
9224 if (autocmd_busy && !(force || autocmd_nested))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009225 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009226
9227#ifdef FEAT_EVAL
9228 /*
Bram Moolenaar7263a772007-05-10 17:35:54 +00009229 * Quickly return when immediately aborting on error, or when an interrupt
Bram Moolenaar071d4272004-06-13 20:20:40 +00009230 * occurred or an exception was thrown but not caught.
9231 */
9232 if (aborting())
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009233 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009234#endif
9235
9236 /*
9237 * FileChangedShell never nests, because it can create an endless loop.
9238 */
Bram Moolenaar56718732006-03-15 22:53:57 +00009239 if (filechangeshell_busy && (event == EVENT_FILECHANGEDSHELL
9240 || event == EVENT_FILECHANGEDSHELLPOST))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009241 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009242
9243 /*
9244 * Ignore events in 'eventignore'.
9245 */
9246 if (event_ignored(event))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009247 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009248
9249 /*
9250 * Allow nesting of autocommands, but restrict the depth, because it's
9251 * possible to create an endless loop.
9252 */
9253 if (nesting == 10)
9254 {
9255 EMSG(_("E218: autocommand nesting too deep"));
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009256 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009257 }
9258
9259 /*
9260 * Check if these autocommands are disabled. Used when doing ":all" or
9261 * ":ball".
9262 */
9263 if ( (autocmd_no_enter
9264 && (event == EVENT_WINENTER || event == EVENT_BUFENTER))
9265 || (autocmd_no_leave
9266 && (event == EVENT_WINLEAVE || event == EVENT_BUFLEAVE)))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009267 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009268
9269 /*
9270 * Save the autocmd_* variables and info about the current buffer.
9271 */
9272 save_autocmd_fname = autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009273 save_autocmd_fname_full = autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009274 save_autocmd_bufnr = autocmd_bufnr;
9275 save_autocmd_match = autocmd_match;
9276 save_autocmd_busy = autocmd_busy;
9277 save_autocmd_nested = autocmd_nested;
9278 save_changed = curbuf->b_changed;
9279 old_curbuf = curbuf;
9280
9281 /*
9282 * Set the file name to be used for <afile>.
Bram Moolenaara0174af2008-01-02 20:08:25 +00009283 * Make a copy to avoid that changing a buffer name or directory makes it
9284 * invalid.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009285 */
9286 if (fname_io == NULL)
9287 {
9288 if (fname != NULL && *fname != NUL)
9289 autocmd_fname = fname;
9290 else if (buf != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009291 autocmd_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009292 else
9293 autocmd_fname = NULL;
9294 }
9295 else
9296 autocmd_fname = fname_io;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009297 if (autocmd_fname != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009298 autocmd_fname = vim_strsave(autocmd_fname);
9299 autocmd_fname_full = FALSE; /* call FullName_save() later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009300
9301 /*
9302 * Set the buffer number to be used for <abuf>.
9303 */
9304 if (buf == NULL)
9305 autocmd_bufnr = 0;
9306 else
9307 autocmd_bufnr = buf->b_fnum;
9308
9309 /*
9310 * When the file name is NULL or empty, use the file name of buffer "buf".
9311 * Always use the full path of the file name to match with, in case
9312 * "allow_dirs" is set.
9313 */
9314 if (fname == NULL || *fname == NUL)
9315 {
9316 if (buf == NULL)
9317 fname = NULL;
9318 else
9319 {
9320#ifdef FEAT_SYN_HL
9321 if (event == EVENT_SYNTAX)
9322 fname = buf->b_p_syn;
9323 else
9324#endif
9325 if (event == EVENT_FILETYPE)
9326 fname = buf->b_p_ft;
9327 else
9328 {
9329 if (buf->b_sfname != NULL)
9330 sfname = vim_strsave(buf->b_sfname);
9331 fname = buf->b_ffname;
9332 }
9333 }
9334 if (fname == NULL)
9335 fname = (char_u *)"";
9336 fname = vim_strsave(fname); /* make a copy, so we can change it */
9337 }
9338 else
9339 {
9340 sfname = vim_strsave(fname);
Bram Moolenaar5135d462009-04-29 16:03:38 +00009341 /* Don't try expanding FileType, Syntax, FuncUndefined, WindowID or
9342 * QuickFixCmd* */
Bram Moolenaar7c626922005-02-07 22:01:03 +00009343 if (event == EVENT_FILETYPE
9344 || event == EVENT_SYNTAX
Bram Moolenaar5135d462009-04-29 16:03:38 +00009345 || event == EVENT_FUNCUNDEFINED
Bram Moolenaar7c626922005-02-07 22:01:03 +00009346 || event == EVENT_REMOTEREPLY
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00009347 || event == EVENT_SPELLFILEMISSING
Bram Moolenaar7c626922005-02-07 22:01:03 +00009348 || event == EVENT_QUICKFIXCMDPRE
9349 || event == EVENT_QUICKFIXCMDPOST)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009350 fname = vim_strsave(fname);
9351 else
9352 fname = FullName_save(fname, FALSE);
9353 }
9354 if (fname == NULL) /* out of memory */
9355 {
9356 vim_free(sfname);
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009357 retval = FALSE;
9358 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009359 }
9360
9361#ifdef BACKSLASH_IN_FILENAME
9362 /*
9363 * Replace all backslashes with forward slashes. This makes the
9364 * autocommand patterns portable between Unix and MS-DOS.
9365 */
9366 if (sfname != NULL)
9367 forward_slash(sfname);
9368 forward_slash(fname);
9369#endif
9370
9371#ifdef VMS
9372 /* remove version for correct match */
9373 if (sfname != NULL)
9374 vms_remove_version(sfname);
9375 vms_remove_version(fname);
9376#endif
9377
9378 /*
9379 * Set the name to be used for <amatch>.
9380 */
9381 autocmd_match = fname;
9382
9383
9384 /* Don't redraw while doing auto commands. */
9385 ++RedrawingDisabled;
9386 save_sourcing_name = sourcing_name;
9387 sourcing_name = NULL; /* don't free this one */
9388 save_sourcing_lnum = sourcing_lnum;
9389 sourcing_lnum = 0; /* no line number here */
9390
9391#ifdef FEAT_EVAL
9392 save_current_SID = current_SID;
9393
Bram Moolenaar05159a02005-02-26 23:04:13 +00009394# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009395 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009396 prof_child_enter(&wait_time); /* doesn't count for the caller itself */
9397# endif
9398
Bram Moolenaar071d4272004-06-13 20:20:40 +00009399 /* Don't use local function variables, if called from a function */
9400 save_funccalp = save_funccal();
9401#endif
9402
9403 /*
9404 * When starting to execute autocommands, save the search patterns.
9405 */
9406 if (!autocmd_busy)
9407 {
9408 save_search_patterns();
9409 saveRedobuff();
9410 did_filetype = keep_filetype;
9411 }
9412
9413 /*
9414 * Note that we are applying autocmds. Some commands need to know.
9415 */
9416 autocmd_busy = TRUE;
9417 filechangeshell_busy = (event == EVENT_FILECHANGEDSHELL);
9418 ++nesting; /* see matching decrement below */
9419
9420 /* Remember that FileType was triggered. Used for did_filetype(). */
9421 if (event == EVENT_FILETYPE)
9422 did_filetype = TRUE;
9423
9424 tail = gettail(fname);
9425
9426 /* Find first autocommand that matches */
9427 patcmd.curpat = first_autopat[(int)event];
9428 patcmd.nextcmd = NULL;
9429 patcmd.group = group;
9430 patcmd.fname = fname;
9431 patcmd.sfname = sfname;
9432 patcmd.tail = tail;
9433 patcmd.event = event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009434 patcmd.arg_bufnr = autocmd_bufnr;
9435 patcmd.next = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009436 auto_next_pat(&patcmd, FALSE);
9437
9438 /* found one, start executing the autocommands */
9439 if (patcmd.curpat != NULL)
9440 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009441 /* add to active_apc_list */
9442 patcmd.next = active_apc_list;
9443 active_apc_list = &patcmd;
9444
Bram Moolenaar071d4272004-06-13 20:20:40 +00009445#ifdef FEAT_EVAL
9446 /* set v:cmdarg (only when there is a matching pattern) */
9447 save_cmdbang = get_vim_var_nr(VV_CMDBANG);
9448 if (eap != NULL)
9449 {
9450 save_cmdarg = set_cmdarg(eap, NULL);
9451 set_vim_var_nr(VV_CMDBANG, (long)eap->forceit);
9452 }
9453 else
9454 save_cmdarg = NULL; /* avoid gcc warning */
9455#endif
9456 retval = TRUE;
9457 /* mark the last pattern, to avoid an endless loop when more patterns
9458 * are added when executing autocommands */
9459 for (ap = patcmd.curpat; ap->next != NULL; ap = ap->next)
9460 ap->last = FALSE;
9461 ap->last = TRUE;
9462 check_lnums(TRUE); /* make sure cursor and topline are valid */
9463 do_cmdline(NULL, getnextac, (void *)&patcmd,
9464 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
9465#ifdef FEAT_EVAL
9466 if (eap != NULL)
9467 {
9468 (void)set_cmdarg(NULL, save_cmdarg);
9469 set_vim_var_nr(VV_CMDBANG, save_cmdbang);
9470 }
9471#endif
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009472 /* delete from active_apc_list */
9473 if (active_apc_list == &patcmd) /* just in case */
9474 active_apc_list = patcmd.next;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009475 }
9476
9477 --RedrawingDisabled;
9478 autocmd_busy = save_autocmd_busy;
9479 filechangeshell_busy = FALSE;
9480 autocmd_nested = save_autocmd_nested;
9481 vim_free(sourcing_name);
9482 sourcing_name = save_sourcing_name;
9483 sourcing_lnum = save_sourcing_lnum;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009484 vim_free(autocmd_fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009485 autocmd_fname = save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009486 autocmd_fname_full = save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009487 autocmd_bufnr = save_autocmd_bufnr;
9488 autocmd_match = save_autocmd_match;
9489#ifdef FEAT_EVAL
9490 current_SID = save_current_SID;
9491 restore_funccal(save_funccalp);
Bram Moolenaar05159a02005-02-26 23:04:13 +00009492# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009493 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009494 prof_child_exit(&wait_time);
9495# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009496#endif
9497 vim_free(fname);
9498 vim_free(sfname);
9499 --nesting; /* see matching increment above */
9500
9501 /*
9502 * When stopping to execute autocommands, restore the search patterns and
9503 * the redo buffer.
9504 */
9505 if (!autocmd_busy)
9506 {
9507 restore_search_patterns();
9508 restoreRedobuff();
9509 did_filetype = FALSE;
9510 }
9511
9512 /*
9513 * Some events don't set or reset the Changed flag.
9514 * Check if still in the same buffer!
9515 */
9516 if (curbuf == old_curbuf
9517 && (event == EVENT_BUFREADPOST
9518 || event == EVENT_BUFWRITEPOST
9519 || event == EVENT_FILEAPPENDPOST
9520 || event == EVENT_VIMLEAVE
9521 || event == EVENT_VIMLEAVEPRE))
9522 {
9523#ifdef FEAT_TITLE
9524 if (curbuf->b_changed != save_changed)
9525 need_maketitle = TRUE;
9526#endif
9527 curbuf->b_changed = save_changed;
9528 }
9529
9530 au_cleanup(); /* may really delete removed patterns/commands now */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009531
9532BYPASS_AU:
9533 /* When wiping out a buffer make sure all its buffer-local autocommands
9534 * are deleted. */
9535 if (event == EVENT_BUFWIPEOUT && buf != NULL)
9536 aubuflocal_remove(buf);
9537
Bram Moolenaar071d4272004-06-13 20:20:40 +00009538 return retval;
9539}
9540
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009541# ifdef FEAT_EVAL
9542static char_u *old_termresponse = NULL;
9543# endif
9544
9545/*
9546 * Block triggering autocommands until unblock_autocmd() is called.
9547 * Can be used recursively, so long as it's symmetric.
9548 */
9549 void
9550block_autocmds()
9551{
9552# ifdef FEAT_EVAL
9553 /* Remember the value of v:termresponse. */
9554 if (autocmd_blocked == 0)
9555 old_termresponse = get_vim_var_str(VV_TERMRESPONSE);
9556# endif
9557 ++autocmd_blocked;
9558}
9559
9560 void
9561unblock_autocmds()
9562{
9563 --autocmd_blocked;
9564
9565# ifdef FEAT_EVAL
9566 /* When v:termresponse was set while autocommands were blocked, trigger
9567 * the autocommands now. Esp. useful when executing a shell command
9568 * during startup (vimdiff). */
9569 if (autocmd_blocked == 0
9570 && get_vim_var_str(VV_TERMRESPONSE) != old_termresponse)
9571 apply_autocmds(EVENT_TERMRESPONSE, NULL, NULL, FALSE, curbuf);
9572# endif
9573}
9574
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009575 int
9576is_autocmd_blocked()
9577{
9578 return autocmd_blocked != 0;
9579}
9580
Bram Moolenaar071d4272004-06-13 20:20:40 +00009581/*
9582 * Find next autocommand pattern that matches.
9583 */
9584 static void
9585auto_next_pat(apc, stop_at_last)
9586 AutoPatCmd *apc;
9587 int stop_at_last; /* stop when 'last' flag is set */
9588{
9589 AutoPat *ap;
9590 AutoCmd *cp;
9591 char_u *name;
9592 char *s;
9593
9594 vim_free(sourcing_name);
9595 sourcing_name = NULL;
9596
9597 for (ap = apc->curpat; ap != NULL && !got_int; ap = ap->next)
9598 {
9599 apc->curpat = NULL;
9600
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009601 /* Only use a pattern when it has not been removed, has commands and
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009602 * the group matches. For buffer-local autocommands only check the
9603 * buffer number. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009604 if (ap->pat != NULL && ap->cmds != NULL
9605 && (apc->group == AUGROUP_ALL || apc->group == ap->group))
9606 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009607 /* execution-condition */
9608 if (ap->buflocal_nr == 0
Bram Moolenaar748bf032005-02-02 23:04:36 +00009609 ? (match_file_pat(NULL, ap->reg_prog, apc->fname,
9610 apc->sfname, apc->tail, ap->allow_dirs))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009611 : ap->buflocal_nr == apc->arg_bufnr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009612 {
9613 name = event_nr2name(apc->event);
9614 s = _("%s Auto commands for \"%s\"");
9615 sourcing_name = alloc((unsigned)(STRLEN(s)
9616 + STRLEN(name) + ap->patlen + 1));
9617 if (sourcing_name != NULL)
9618 {
9619 sprintf((char *)sourcing_name, s,
9620 (char *)name, (char *)ap->pat);
9621 if (p_verbose >= 8)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009622 {
9623 verbose_enter();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009624 smsg((char_u *)_("Executing %s"), sourcing_name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009625 verbose_leave();
9626 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009627 }
9628
9629 apc->curpat = ap;
9630 apc->nextcmd = ap->cmds;
9631 /* mark last command */
9632 for (cp = ap->cmds; cp->next != NULL; cp = cp->next)
9633 cp->last = FALSE;
9634 cp->last = TRUE;
9635 }
9636 line_breakcheck();
9637 if (apc->curpat != NULL) /* found a match */
9638 break;
9639 }
9640 if (stop_at_last && ap->last)
9641 break;
9642 }
9643}
9644
9645/*
9646 * Get next autocommand command.
9647 * Called by do_cmdline() to get the next line for ":if".
9648 * Returns allocated string, or NULL for end of autocommands.
9649 */
Bram Moolenaar21691f82012-12-05 19:13:18 +01009650 char_u *
Bram Moolenaar071d4272004-06-13 20:20:40 +00009651getnextac(c, cookie, indent)
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009652 int c UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009653 void *cookie;
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009654 int indent UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009655{
9656 AutoPatCmd *acp = (AutoPatCmd *)cookie;
9657 char_u *retval;
9658 AutoCmd *ac;
9659
9660 /* Can be called again after returning the last line. */
9661 if (acp->curpat == NULL)
9662 return NULL;
9663
9664 /* repeat until we find an autocommand to execute */
9665 for (;;)
9666 {
9667 /* skip removed commands */
9668 while (acp->nextcmd != NULL && acp->nextcmd->cmd == NULL)
9669 if (acp->nextcmd->last)
9670 acp->nextcmd = NULL;
9671 else
9672 acp->nextcmd = acp->nextcmd->next;
9673
9674 if (acp->nextcmd != NULL)
9675 break;
9676
9677 /* at end of commands, find next pattern that matches */
9678 if (acp->curpat->last)
9679 acp->curpat = NULL;
9680 else
9681 acp->curpat = acp->curpat->next;
9682 if (acp->curpat != NULL)
9683 auto_next_pat(acp, TRUE);
9684 if (acp->curpat == NULL)
9685 return NULL;
9686 }
9687
9688 ac = acp->nextcmd;
9689
9690 if (p_verbose >= 9)
9691 {
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009692 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009693 smsg((char_u *)_("autocommand %s"), ac->cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009694 msg_puts((char_u *)"\n"); /* don't overwrite this either */
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009695 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009696 }
9697 retval = vim_strsave(ac->cmd);
9698 autocmd_nested = ac->nested;
9699#ifdef FEAT_EVAL
9700 current_SID = ac->scriptID;
9701#endif
9702 if (ac->last)
9703 acp->nextcmd = NULL;
9704 else
9705 acp->nextcmd = ac->next;
9706 return retval;
9707}
9708
9709/*
9710 * Return TRUE if there is a matching autocommand for "fname".
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009711 * To account for buffer-local autocommands, function needs to know
9712 * in which buffer the file will be opened.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009713 */
9714 int
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009715has_autocmd(event, sfname, buf)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009716 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009717 char_u *sfname;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009718 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009719{
9720 AutoPat *ap;
9721 char_u *fname;
9722 char_u *tail = gettail(sfname);
9723 int retval = FALSE;
9724
9725 fname = FullName_save(sfname, FALSE);
9726 if (fname == NULL)
9727 return FALSE;
9728
9729#ifdef BACKSLASH_IN_FILENAME
9730 /*
9731 * Replace all backslashes with forward slashes. This makes the
9732 * autocommand patterns portable between Unix and MS-DOS.
9733 */
9734 sfname = vim_strsave(sfname);
9735 if (sfname != NULL)
9736 forward_slash(sfname);
9737 forward_slash(fname);
9738#endif
9739
9740 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
9741 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009742 && (ap->buflocal_nr == 0
Bram Moolenaar748bf032005-02-02 23:04:36 +00009743 ? match_file_pat(NULL, ap->reg_prog,
9744 fname, sfname, tail, ap->allow_dirs)
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009745 : buf != NULL && ap->buflocal_nr == buf->b_fnum
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009746 ))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009747 {
9748 retval = TRUE;
9749 break;
9750 }
9751
9752 vim_free(fname);
9753#ifdef BACKSLASH_IN_FILENAME
9754 vim_free(sfname);
9755#endif
9756
9757 return retval;
9758}
9759
9760#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
9761/*
9762 * Function given to ExpandGeneric() to obtain the list of autocommand group
9763 * names.
9764 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009765 char_u *
9766get_augroup_name(xp, idx)
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009767 expand_T *xp UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009768 int idx;
9769{
9770 if (idx == augroups.ga_len) /* add "END" add the end */
9771 return (char_u *)"END";
9772 if (idx >= augroups.ga_len) /* end of list */
9773 return NULL;
9774 if (AUGROUP_NAME(idx) == NULL) /* skip deleted entries */
9775 return (char_u *)"";
9776 return AUGROUP_NAME(idx); /* return a name */
9777}
9778
9779static int include_groups = FALSE;
9780
9781 char_u *
9782set_context_in_autocmd(xp, arg, doautocmd)
9783 expand_T *xp;
9784 char_u *arg;
Bram Moolenaard812df62008-11-09 12:46:09 +00009785 int doautocmd; /* TRUE for :doauto*, FALSE for :autocmd */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009786{
9787 char_u *p;
9788 int group;
9789
9790 /* check for a group name, skip it if present */
9791 include_groups = FALSE;
9792 p = arg;
9793 group = au_get_grouparg(&arg);
9794 if (group == AUGROUP_ERROR)
9795 return NULL;
9796 /* If there only is a group name that's what we expand. */
9797 if (*arg == NUL && group != AUGROUP_ALL && !vim_iswhite(arg[-1]))
9798 {
9799 arg = p;
9800 group = AUGROUP_ALL;
9801 }
9802
9803 /* skip over event name */
9804 for (p = arg; *p != NUL && !vim_iswhite(*p); ++p)
9805 if (*p == ',')
9806 arg = p + 1;
9807 if (*p == NUL)
9808 {
9809 if (group == AUGROUP_ALL)
9810 include_groups = TRUE;
9811 xp->xp_context = EXPAND_EVENTS; /* expand event name */
9812 xp->xp_pattern = arg;
9813 return NULL;
9814 }
9815
9816 /* skip over pattern */
9817 arg = skipwhite(p);
9818 while (*arg && (!vim_iswhite(*arg) || arg[-1] == '\\'))
9819 arg++;
9820 if (*arg)
9821 return arg; /* expand (next) command */
9822
9823 if (doautocmd)
9824 xp->xp_context = EXPAND_FILES; /* expand file names */
9825 else
9826 xp->xp_context = EXPAND_NOTHING; /* pattern is not expanded */
9827 return NULL;
9828}
9829
9830/*
9831 * Function given to ExpandGeneric() to obtain the list of event names.
9832 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009833 char_u *
9834get_event_name(xp, idx)
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009835 expand_T *xp UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009836 int idx;
9837{
9838 if (idx < augroups.ga_len) /* First list group names, if wanted */
9839 {
9840 if (!include_groups || AUGROUP_NAME(idx) == NULL)
9841 return (char_u *)""; /* skip deleted entries */
9842 return AUGROUP_NAME(idx); /* return a name */
9843 }
9844 return (char_u *)event_names[idx - augroups.ga_len].name;
9845}
9846
9847#endif /* FEAT_CMDL_COMPL */
9848
9849/*
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009850 * Return TRUE if autocmd is supported.
9851 */
9852 int
9853autocmd_supported(name)
9854 char_u *name;
9855{
9856 char_u *p;
9857
9858 return (event_name2nr(name, &p) != NUM_EVENTS);
9859}
9860
9861/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00009862 * Return TRUE if an autocommand is defined for a group, event and
9863 * pattern: The group can be omitted to accept any group. "event" and "pattern"
9864 * can be NULL to accept any event and pattern. "pattern" can be NULL to accept
9865 * any pattern. Buffer-local patterns <buffer> or <buffer=N> are accepted.
9866 * Used for:
9867 * exists("#Group") or
9868 * exists("#Group#Event") or
9869 * exists("#Group#Event#pat") or
9870 * exists("#Event") or
9871 * exists("#Event#pat")
Bram Moolenaar071d4272004-06-13 20:20:40 +00009872 */
9873 int
Bram Moolenaar195d6352005-12-19 22:08:24 +00009874au_exists(arg)
9875 char_u *arg;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009876{
Bram Moolenaar195d6352005-12-19 22:08:24 +00009877 char_u *arg_save;
9878 char_u *pattern = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009879 char_u *event_name;
9880 char_u *p;
Bram Moolenaar754b5602006-02-09 23:53:20 +00009881 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009882 AutoPat *ap;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009883 buf_T *buflocal_buf = NULL;
Bram Moolenaar195d6352005-12-19 22:08:24 +00009884 int group;
9885 int retval = FALSE;
9886
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009887 /* Make a copy so that we can change the '#' chars to a NUL. */
Bram Moolenaar195d6352005-12-19 22:08:24 +00009888 arg_save = vim_strsave(arg);
9889 if (arg_save == NULL)
9890 return FALSE;
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009891 p = vim_strchr(arg_save, '#');
Bram Moolenaar195d6352005-12-19 22:08:24 +00009892 if (p != NULL)
9893 *p++ = NUL;
9894
9895 /* First, look for an autocmd group name */
9896 group = au_find_group(arg_save);
9897 if (group == AUGROUP_ERROR)
9898 {
9899 /* Didn't match a group name, assume the first argument is an event. */
9900 group = AUGROUP_ALL;
9901 event_name = arg_save;
9902 }
9903 else
9904 {
9905 if (p == NULL)
9906 {
9907 /* "Group": group name is present and it's recognized */
9908 retval = TRUE;
9909 goto theend;
9910 }
9911
9912 /* Must be "Group#Event" or "Group#Event#pat". */
9913 event_name = p;
9914 p = vim_strchr(event_name, '#');
9915 if (p != NULL)
9916 *p++ = NUL; /* "Group#Event#pat" */
9917 }
9918
9919 pattern = p; /* "pattern" is NULL when there is no pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009920
9921 /* find the index (enum) for the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009922 event = event_name2nr(event_name, &p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009923
9924 /* return FALSE if the event name is not recognized */
Bram Moolenaar195d6352005-12-19 22:08:24 +00009925 if (event == NUM_EVENTS)
9926 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009927
9928 /* Find the first autocommand for this event.
9929 * If there isn't any, return FALSE;
9930 * If there is one and no pattern given, return TRUE; */
9931 ap = first_autopat[(int)event];
9932 if (ap == NULL)
Bram Moolenaar195d6352005-12-19 22:08:24 +00009933 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009934
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009935 /* if pattern is "<buffer>", special handling is needed which uses curbuf */
9936 /* for pattern "<buffer=N>, fnamecmp() will work fine */
Bram Moolenaar5b7880d2009-09-11 15:24:31 +00009937 if (pattern != NULL && STRICMP(pattern, "<buffer>") == 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009938 buflocal_buf = curbuf;
9939
Bram Moolenaar071d4272004-06-13 20:20:40 +00009940 /* Check if there is an autocommand with the given pattern. */
9941 for ( ; ap != NULL; ap = ap->next)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009942 /* only use a pattern when it has not been removed and has commands. */
9943 /* For buffer-local autocommands, fnamecmp() works fine. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009944 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaar195d6352005-12-19 22:08:24 +00009945 && (group == AUGROUP_ALL || ap->group == group)
Bram Moolenaar5b7880d2009-09-11 15:24:31 +00009946 && (pattern == NULL
9947 || (buflocal_buf == NULL
9948 ? fnamecmp(ap->pat, pattern) == 0
9949 : ap->buflocal_nr == buflocal_buf->b_fnum)))
Bram Moolenaar195d6352005-12-19 22:08:24 +00009950 {
9951 retval = TRUE;
9952 break;
9953 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009954
Bram Moolenaar195d6352005-12-19 22:08:24 +00009955theend:
9956 vim_free(arg_save);
9957 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009958}
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009959
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009960#else /* FEAT_AUTOCMD */
9961
9962/*
9963 * Prepare for executing commands for (hidden) buffer "buf".
9964 * This is the non-autocommand version, it simply saves "curbuf" and sets
9965 * "curbuf" and "curwin" to match "buf".
9966 */
9967 void
9968aucmd_prepbuf(aco, buf)
9969 aco_save_T *aco; /* structure to save values in */
9970 buf_T *buf; /* new curbuf */
9971{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009972 aco->save_curbuf = curbuf;
9973 --curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009974 curbuf = buf;
9975 curwin->w_buffer = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009976 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009977}
9978
9979/*
9980 * Restore after executing commands for a (hidden) buffer.
9981 * This is the non-autocommand version.
9982 */
9983 void
9984aucmd_restbuf(aco)
9985 aco_save_T *aco; /* structure holding saved values */
9986{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009987 --curbuf->b_nwindows;
9988 curbuf = aco->save_curbuf;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009989 curwin->w_buffer = curbuf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009990 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009991}
9992
Bram Moolenaar071d4272004-06-13 20:20:40 +00009993#endif /* FEAT_AUTOCMD */
9994
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009995
Bram Moolenaar071d4272004-06-13 20:20:40 +00009996#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN) || defined(PROTO)
9997/*
Bram Moolenaar748bf032005-02-02 23:04:36 +00009998 * Try matching a filename with a "pattern" ("prog" is NULL), or use the
9999 * precompiled regprog "prog" ("pattern" is NULL). That avoids calling
10000 * vim_regcomp() often.
Bram Moolenaar071d4272004-06-13 20:20:40 +000010001 * Used for autocommands and 'wildignore'.
10002 * Returns TRUE if there is a match, FALSE otherwise.
10003 */
10004 int
Bram Moolenaar748bf032005-02-02 23:04:36 +000010005match_file_pat(pattern, prog, fname, sfname, tail, allow_dirs)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010006 char_u *pattern; /* pattern to match with */
Bram Moolenaar748bf032005-02-02 23:04:36 +000010007 regprog_T *prog; /* pre-compiled regprog or NULL */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010008 char_u *fname; /* full path of file name */
10009 char_u *sfname; /* short file name or NULL */
10010 char_u *tail; /* tail of path */
10011 int allow_dirs; /* allow matching with dir */
10012{
10013 regmatch_T regmatch;
10014 int result = FALSE;
10015#ifdef FEAT_OSFILETYPE
10016 int no_pattern = FALSE; /* TRUE if check is filetype only */
10017 char_u *type_start;
10018 char_u c;
10019 int match = FALSE;
10020#endif
10021
Bram Moolenaar71afbfe2013-03-19 16:49:16 +010010022 regmatch.rm_ic = p_fic; /* ignore case if 'fileignorecase' is set */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010023#ifdef FEAT_OSFILETYPE
10024 if (*pattern == '<')
10025 {
10026 /* There is a filetype condition specified with this pattern.
10027 * Check the filetype matches first. If not, don't bother with the
10028 * pattern (set regprog to NULL).
10029 * Always use magic for the regexp.
10030 */
10031
10032 for (type_start = pattern + 1; (c = *pattern); pattern++)
10033 {
10034 if ((c == ';' || c == '>') && match == FALSE)
10035 {
10036 *pattern = NUL; /* Terminate the string */
Bram Moolenaar05334432011-07-20 18:29:39 +020010037 /* TODO: match with 'filetype' of buffer that "fname" comes
10038 * from. */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010039 match = mch_check_filetype(fname, type_start);
10040 *pattern = c; /* Restore the terminator */
10041 type_start = pattern + 1;
10042 }
10043 if (c == '>')
10044 break;
10045 }
10046
10047 /* (c should never be NUL, but check anyway) */
10048 if (match == FALSE || c == NUL)
10049 regmatch.regprog = NULL; /* Doesn't match - don't check pat. */
10050 else if (*pattern == NUL)
10051 {
10052 regmatch.regprog = NULL; /* Vim will try to free regprog later */
10053 no_pattern = TRUE; /* Always matches - don't check pat. */
10054 }
10055 else
10056 regmatch.regprog = vim_regcomp(pattern + 1, RE_MAGIC);
10057 }
10058 else
10059#endif
Bram Moolenaar748bf032005-02-02 23:04:36 +000010060 {
10061 if (prog != NULL)
10062 regmatch.regprog = prog;
10063 else
10064 regmatch.regprog = vim_regcomp(pattern, RE_MAGIC);
10065 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010066
10067 /*
10068 * Try for a match with the pattern with:
10069 * 1. the full file name, when the pattern has a '/'.
10070 * 2. the short file name, when the pattern has a '/'.
10071 * 3. the tail of the file name, when the pattern has no '/'.
10072 */
10073 if (
10074#ifdef FEAT_OSFILETYPE
10075 /* If the check is for a filetype only and we don't care
10076 * about the path then skip all the regexp stuff.
10077 */
10078 no_pattern ||
10079#endif
10080 (regmatch.regprog != NULL
10081 && ((allow_dirs
10082 && (vim_regexec(&regmatch, fname, (colnr_T)0)
10083 || (sfname != NULL
10084 && vim_regexec(&regmatch, sfname, (colnr_T)0))))
10085 || (!allow_dirs && vim_regexec(&regmatch, tail, (colnr_T)0)))))
10086 result = TRUE;
10087
Bram Moolenaar748bf032005-02-02 23:04:36 +000010088 if (prog == NULL)
Bram Moolenaar473de612013-06-08 18:19:48 +020010089 vim_regfree(regmatch.regprog);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010090 return result;
10091}
10092#endif
10093
10094#if defined(FEAT_WILDIGN) || defined(PROTO)
10095/*
10096 * Return TRUE if a file matches with a pattern in "list".
10097 * "list" is a comma-separated list of patterns, like 'wildignore'.
10098 * "sfname" is the short file name or NULL, "ffname" the long file name.
10099 */
10100 int
10101match_file_list(list, sfname, ffname)
10102 char_u *list;
10103 char_u *sfname;
10104 char_u *ffname;
10105{
10106 char_u buf[100];
10107 char_u *tail;
10108 char_u *regpat;
10109 char allow_dirs;
10110 int match;
10111 char_u *p;
10112
10113 tail = gettail(sfname);
10114
10115 /* try all patterns in 'wildignore' */
10116 p = list;
10117 while (*p)
10118 {
10119 copy_option_part(&p, buf, 100, ",");
10120 regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, FALSE);
10121 if (regpat == NULL)
10122 break;
Bram Moolenaar748bf032005-02-02 23:04:36 +000010123 match = match_file_pat(regpat, NULL, ffname, sfname,
10124 tail, (int)allow_dirs);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010125 vim_free(regpat);
10126 if (match)
10127 return TRUE;
10128 }
10129 return FALSE;
10130}
10131#endif
10132
10133/*
10134 * Convert the given pattern "pat" which has shell style wildcards in it, into
10135 * a regular expression, and return the result in allocated memory. If there
10136 * is a directory path separator to be matched, then TRUE is put in
10137 * allow_dirs, otherwise FALSE is put there -- webb.
10138 * Handle backslashes before special characters, like "\*" and "\ ".
10139 *
10140 * If FEAT_OSFILETYPE defined then pass initial <type> through unchanged. Eg:
10141 * '<html>myfile' becomes '<html>^myfile$' -- leonard.
10142 *
10143 * Returns NULL when out of memory.
10144 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010145 char_u *
10146file_pat_to_reg_pat(pat, pat_end, allow_dirs, no_bslash)
10147 char_u *pat;
10148 char_u *pat_end; /* first char after pattern or NULL */
10149 char *allow_dirs; /* Result passed back out in here */
Bram Moolenaar78a15312009-05-15 19:33:18 +000010150 int no_bslash UNUSED; /* Don't use a backward slash as pathsep */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010151{
10152 int size;
10153 char_u *endp;
10154 char_u *reg_pat;
10155 char_u *p;
10156 int i;
10157 int nested = 0;
10158 int add_dollar = TRUE;
10159#ifdef FEAT_OSFILETYPE
10160 int check_length = 0;
10161#endif
10162
10163 if (allow_dirs != NULL)
10164 *allow_dirs = FALSE;
10165 if (pat_end == NULL)
10166 pat_end = pat + STRLEN(pat);
10167
10168#ifdef FEAT_OSFILETYPE
10169 /* Find out how much of the string is the filetype check */
10170 if (*pat == '<')
10171 {
10172 /* Count chars until the next '>' */
10173 for (p = pat + 1; p < pat_end && *p != '>'; p++)
10174 ;
10175 if (p < pat_end)
10176 {
10177 /* Pattern is of the form <.*>.* */
10178 check_length = p - pat + 1;
10179 if (p + 1 >= pat_end)
10180 {
10181 /* The 'pattern' is a filetype check ONLY */
10182 reg_pat = (char_u *)alloc(check_length + 1);
10183 if (reg_pat != NULL)
10184 {
10185 mch_memmove(reg_pat, pat, (size_t)check_length);
10186 reg_pat[check_length] = NUL;
10187 }
10188 return reg_pat;
10189 }
10190 }
10191 /* else: there was no closing '>' - assume it was a normal pattern */
10192
10193 }
10194 pat += check_length;
10195 size = 2 + check_length;
10196#else
10197 size = 2; /* '^' at start, '$' at end */
10198#endif
10199
10200 for (p = pat; p < pat_end; p++)
10201 {
10202 switch (*p)
10203 {
10204 case '*':
10205 case '.':
10206 case ',':
10207 case '{':
10208 case '}':
10209 case '~':
10210 size += 2; /* extra backslash */
10211 break;
10212#ifdef BACKSLASH_IN_FILENAME
10213 case '\\':
10214 case '/':
10215 size += 4; /* could become "[\/]" */
10216 break;
10217#endif
10218 default:
10219 size++;
10220# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010221 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010222 {
10223 ++p;
10224 ++size;
10225 }
10226# endif
10227 break;
10228 }
10229 }
10230 reg_pat = alloc(size + 1);
10231 if (reg_pat == NULL)
10232 return NULL;
10233
10234#ifdef FEAT_OSFILETYPE
10235 /* Copy the type check in to the start. */
10236 if (check_length)
10237 mch_memmove(reg_pat, pat - check_length, (size_t)check_length);
10238 i = check_length;
10239#else
10240 i = 0;
10241#endif
10242
10243 if (pat[0] == '*')
10244 while (pat[0] == '*' && pat < pat_end - 1)
10245 pat++;
10246 else
10247 reg_pat[i++] = '^';
10248 endp = pat_end - 1;
10249 if (*endp == '*')
10250 {
10251 while (endp - pat > 0 && *endp == '*')
10252 endp--;
10253 add_dollar = FALSE;
10254 }
10255 for (p = pat; *p && nested >= 0 && p <= endp; p++)
10256 {
10257 switch (*p)
10258 {
10259 case '*':
10260 reg_pat[i++] = '.';
10261 reg_pat[i++] = '*';
Bram Moolenaar02743632005-07-25 20:42:36 +000010262 while (p[1] == '*') /* "**" matches like "*" */
10263 ++p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010264 break;
10265 case '.':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010266 case '~':
10267 reg_pat[i++] = '\\';
10268 reg_pat[i++] = *p;
10269 break;
10270 case '?':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010271 reg_pat[i++] = '.';
10272 break;
10273 case '\\':
10274 if (p[1] == NUL)
10275 break;
10276#ifdef BACKSLASH_IN_FILENAME
10277 if (!no_bslash)
10278 {
10279 /* translate:
10280 * "\x" to "\\x" e.g., "dir\file"
10281 * "\*" to "\\.*" e.g., "dir\*.c"
10282 * "\?" to "\\." e.g., "dir\??.c"
10283 * "\+" to "\+" e.g., "fileX\+.c"
10284 */
10285 if ((vim_isfilec(p[1]) || p[1] == '*' || p[1] == '?')
10286 && p[1] != '+')
10287 {
10288 reg_pat[i++] = '[';
10289 reg_pat[i++] = '\\';
10290 reg_pat[i++] = '/';
10291 reg_pat[i++] = ']';
10292 if (allow_dirs != NULL)
10293 *allow_dirs = TRUE;
10294 break;
10295 }
10296 }
10297#endif
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010298 /* Undo escaping from ExpandEscape():
10299 * foo\?bar -> foo?bar
10300 * foo\%bar -> foo%bar
10301 * foo\,bar -> foo,bar
10302 * foo\ bar -> foo bar
10303 * Don't unescape \, * and others that are also special in a
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010304 * regexp.
10305 * An escaped { must be unescaped since we use magic not
10306 * verymagic.
10307 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010308 if (*++p == '?'
10309#ifdef BACKSLASH_IN_FILENAME
10310 && no_bslash
10311#endif
10312 )
10313 reg_pat[i++] = '?';
10314 else
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010315 if (*p == ',' || *p == '%' || *p == '#'
10316 || *p == ' ' || *p == '{')
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010317 reg_pat[i++] = *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010318 else
10319 {
10320 if (allow_dirs != NULL && vim_ispathsep(*p)
10321#ifdef BACKSLASH_IN_FILENAME
10322 && (!no_bslash || *p != '\\')
10323#endif
10324 )
10325 *allow_dirs = TRUE;
10326 reg_pat[i++] = '\\';
10327 reg_pat[i++] = *p;
10328 }
10329 break;
10330#ifdef BACKSLASH_IN_FILENAME
10331 case '/':
10332 reg_pat[i++] = '[';
10333 reg_pat[i++] = '\\';
10334 reg_pat[i++] = '/';
10335 reg_pat[i++] = ']';
10336 if (allow_dirs != NULL)
10337 *allow_dirs = TRUE;
10338 break;
10339#endif
10340 case '{':
10341 reg_pat[i++] = '\\';
10342 reg_pat[i++] = '(';
10343 nested++;
10344 break;
10345 case '}':
10346 reg_pat[i++] = '\\';
10347 reg_pat[i++] = ')';
10348 --nested;
10349 break;
10350 case ',':
10351 if (nested)
10352 {
10353 reg_pat[i++] = '\\';
10354 reg_pat[i++] = '|';
10355 }
10356 else
10357 reg_pat[i++] = ',';
10358 break;
10359 default:
10360# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010361 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010362 reg_pat[i++] = *p++;
10363 else
10364# endif
10365 if (allow_dirs != NULL && vim_ispathsep(*p))
10366 *allow_dirs = TRUE;
10367 reg_pat[i++] = *p;
10368 break;
10369 }
10370 }
10371 if (add_dollar)
10372 reg_pat[i++] = '$';
10373 reg_pat[i] = NUL;
10374 if (nested != 0)
10375 {
10376 if (nested < 0)
10377 EMSG(_("E219: Missing {."));
10378 else
10379 EMSG(_("E220: Missing }."));
10380 vim_free(reg_pat);
10381 reg_pat = NULL;
10382 }
10383 return reg_pat;
10384}
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010385
10386#if defined(EINTR) || defined(PROTO)
10387/*
10388 * Version of read() that retries when interrupted by EINTR (possibly
10389 * by a SIGWINCH).
10390 */
10391 long
10392read_eintr(fd, buf, bufsize)
10393 int fd;
10394 void *buf;
10395 size_t bufsize;
10396{
10397 long ret;
10398
10399 for (;;)
10400 {
10401 ret = vim_read(fd, buf, bufsize);
10402 if (ret >= 0 || errno != EINTR)
10403 break;
10404 }
10405 return ret;
10406}
10407
10408/*
10409 * Version of write() that retries when interrupted by EINTR (possibly
10410 * by a SIGWINCH).
10411 */
10412 long
10413write_eintr(fd, buf, bufsize)
10414 int fd;
10415 void *buf;
10416 size_t bufsize;
10417{
10418 long ret = 0;
10419 long wlen;
10420
10421 /* Repeat the write() so long it didn't fail, other than being interrupted
10422 * by a signal. */
10423 while (ret < (long)bufsize)
10424 {
Bram Moolenaar9c263032010-12-17 18:06:06 +010010425 wlen = vim_write(fd, (char *)buf + ret, bufsize - ret);
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010426 if (wlen < 0)
10427 {
10428 if (errno != EINTR)
10429 break;
10430 }
10431 else
10432 ret += wlen;
10433 }
10434 return ret;
10435}
10436#endif