blob: a0b75572af1fe67b916644139301d776681a10af [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 {
507 /* Remember time of file.
508 * For RISCOS, also remember the filetype.
509 */
510 if (mch_stat((char *)fname, &st) >= 0)
511 {
512 buf_store_time(curbuf, &st, fname);
513 curbuf->b_mtime_read = curbuf->b_mtime;
514
515#if defined(RISCOS) && defined(FEAT_OSFILETYPE)
516 /* Read the filetype into the buffer local filetype option. */
517 mch_read_filetype(fname);
518#endif
519#ifdef UNIX
520 /*
521 * Use the protection bits of the original file for the swap file.
522 * This makes it possible for others to read the name of the
523 * edited file from the swapfile, but only if they can read the
524 * edited file.
525 * Remove the "write" and "execute" bits for group and others
526 * (they must not write the swapfile).
527 * Add the "read" and "write" bits for the user, otherwise we may
528 * not be able to write to the file ourselves.
529 * Setting the bits is done below, after creating the swap file.
530 */
531 swap_mode = (st.st_mode & 0644) | 0600;
532#endif
533#ifdef FEAT_CW_EDITOR
534 /* Get the FSSpec on MacOS
535 * TODO: Update it properly when the buffer name changes
536 */
537 (void)GetFSSpecFromPath(curbuf->b_ffname, &curbuf->b_FSSpec);
538#endif
539#ifdef VMS
540 curbuf->b_fab_rfm = st.st_fab_rfm;
Bram Moolenaard4755bb2004-09-02 19:12:26 +0000541 curbuf->b_fab_rat = st.st_fab_rat;
542 curbuf->b_fab_mrs = st.st_fab_mrs;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000543#endif
544 }
545 else
546 {
547 curbuf->b_mtime = 0;
548 curbuf->b_mtime_read = 0;
549 curbuf->b_orig_size = 0;
550 curbuf->b_orig_mode = 0;
551 }
552
553 /* Reset the "new file" flag. It will be set again below when the
554 * file doesn't exist. */
555 curbuf->b_flags &= ~(BF_NEW | BF_NEW_W);
556 }
557
558/*
559 * for UNIX: check readonly with perm and mch_access()
560 * for RISCOS: same as Unix, otherwise file gets re-datestamped!
561 * for MSDOS and Amiga: check readonly by trying to open the file for writing
562 */
563 file_readonly = FALSE;
564 if (read_stdin)
565 {
566#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
567 /* Force binary I/O on stdin to avoid CR-LF -> LF conversion. */
568 setmode(0, O_BINARY);
569#endif
570 }
571 else if (!read_buffer)
572 {
573#ifdef USE_MCH_ACCESS
574 if (
575# ifdef UNIX
576 !(perm & 0222) ||
577# endif
578 mch_access((char *)fname, W_OK))
579 file_readonly = TRUE;
580 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
581#else
582 if (!newfile
583 || readonlymode
584 || (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0)
585 {
586 file_readonly = TRUE;
587 /* try to open ro */
588 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
589 }
590#endif
591 }
592
593 if (fd < 0) /* cannot open at all */
594 {
595#ifndef UNIX
596 int isdir_f;
597#endif
598 msg_scroll = msg_save;
599#ifndef UNIX
600 /*
601 * On MSDOS and Amiga we can't open a directory, check here.
602 */
603 isdir_f = (mch_isdir(fname));
604 perm = mch_getperm(fname); /* check if the file exists */
605 if (isdir_f)
606 {
607 filemess(curbuf, sfname, (char_u *)_("is a directory"), 0);
608 curbuf->b_p_ro = TRUE; /* must use "w!" now */
609 }
610 else
611#endif
612 if (newfile)
613 {
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200614 if (perm < 0
615#ifdef ENOENT
616 && errno == ENOENT
617#endif
618 )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000619 {
620 /*
621 * Set the 'new-file' flag, so that when the file has
622 * been created by someone else, a ":w" will complain.
623 */
624 curbuf->b_flags |= BF_NEW;
625
626 /* Create a swap file now, so that other Vims are warned
627 * that we are editing this file. Don't do this for a
628 * "nofile" or "nowrite" buffer type. */
629#ifdef FEAT_QUICKFIX
630 if (!bt_dontwrite(curbuf))
631#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000632 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000633 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000634#ifdef FEAT_AUTOCMD
635 /* SwapExists autocommand may mess things up */
636 if (curbuf != old_curbuf
637 || (using_b_ffname
638 && (old_b_ffname != curbuf->b_ffname))
639 || (using_b_fname
640 && (old_b_fname != curbuf->b_fname)))
641 {
642 EMSG(_(e_auchangedbuf));
643 return FAIL;
644 }
645#endif
646 }
Bram Moolenaar5b962cf2005-12-12 21:58:40 +0000647 if (dir_of_file_exists(fname))
648 filemess(curbuf, sfname, (char_u *)_("[New File]"), 0);
649 else
650 filemess(curbuf, sfname,
651 (char_u *)_("[New DIRECTORY]"), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000652#ifdef FEAT_VIMINFO
653 /* Even though this is a new file, it might have been
654 * edited before and deleted. Get the old marks. */
655 check_marks_read();
656#endif
657#ifdef FEAT_MBYTE
658 if (eap != NULL && eap->force_enc != 0)
659 {
660 /* set forced 'fileencoding' */
661 fenc = enc_canonize(eap->cmd + eap->force_enc);
662 if (fenc != NULL)
663 set_string_option_direct((char_u *)"fenc", -1,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +0000664 fenc, OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000665 vim_free(fenc);
666 }
667#endif
668#ifdef FEAT_AUTOCMD
669 apply_autocmds_exarg(EVENT_BUFNEWFILE, sfname, sfname,
670 FALSE, curbuf, eap);
671#endif
672 /* remember the current fileformat */
673 save_file_ff(curbuf);
674
675#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
676 if (aborting()) /* autocmds may abort script processing */
677 return FAIL;
678#endif
679 return OK; /* a new file is not an error */
680 }
681 else
682 {
Bram Moolenaar202795b2005-10-11 20:29:39 +0000683 filemess(curbuf, sfname, (char_u *)(
684# ifdef EFBIG
685 (errno == EFBIG) ? _("[File too big]") :
686# endif
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200687# ifdef EOVERFLOW
688 (errno == EOVERFLOW) ? _("[File too big]") :
689# endif
Bram Moolenaar202795b2005-10-11 20:29:39 +0000690 _("[Permission Denied]")), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000691 curbuf->b_p_ro = TRUE; /* must use "w!" now */
692 }
693 }
694
695 return FAIL;
696 }
697
698 /*
699 * Only set the 'ro' flag for readonly files the first time they are
700 * loaded. Help files always get readonly mode
701 */
702 if ((check_readonly && file_readonly) || curbuf->b_help)
703 curbuf->b_p_ro = TRUE;
704
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000705 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000706 {
Bram Moolenaar690ffc02008-01-04 15:31:21 +0000707 /* Don't change 'eol' if reading from buffer as it will already be
708 * correctly set when reading stdin. */
709 if (!read_buffer)
710 {
711 curbuf->b_p_eol = TRUE;
712 curbuf->b_start_eol = TRUE;
713 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000714#ifdef FEAT_MBYTE
715 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000716 curbuf->b_start_bomb = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000717#endif
718 }
719
720 /* Create a swap file now, so that other Vims are warned that we are
721 * editing this file.
722 * Don't do this for a "nofile" or "nowrite" buffer type. */
723#ifdef FEAT_QUICKFIX
724 if (!bt_dontwrite(curbuf))
725#endif
726 {
727 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000728#ifdef FEAT_AUTOCMD
729 if (!read_stdin && (curbuf != old_curbuf
730 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
731 || (using_b_fname && (old_b_fname != curbuf->b_fname))))
732 {
733 EMSG(_(e_auchangedbuf));
734 if (!read_buffer)
735 close(fd);
736 return FAIL;
737 }
738#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000739#ifdef UNIX
740 /* Set swap file protection bits after creating it. */
Bram Moolenaarf061e0b2009-06-24 15:32:01 +0000741 if (swap_mode > 0 && curbuf->b_ml.ml_mfp != NULL
742 && curbuf->b_ml.ml_mfp->mf_fname != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000743 (void)mch_setperm(curbuf->b_ml.ml_mfp->mf_fname, (long)swap_mode);
744#endif
745 }
746
Bram Moolenaarb815dac2005-12-07 20:59:24 +0000747#if defined(HAS_SWAP_EXISTS_ACTION)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000748 /* If "Quit" selected at ATTENTION dialog, don't load the file */
749 if (swap_exists_action == SEA_QUIT)
750 {
751 if (!read_buffer && !read_stdin)
752 close(fd);
753 return FAIL;
754 }
755#endif
756
757 ++no_wait_return; /* don't wait for return yet */
758
759 /*
760 * Set '[ mark to the line above where the lines go (line 1 if zero).
761 */
762 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
763 curbuf->b_op_start.col = 0;
764
765#ifdef FEAT_AUTOCMD
766 if (!read_buffer)
767 {
768 int m = msg_scroll;
769 int n = msg_scrolled;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000770
771 /*
772 * The file must be closed again, the autocommands may want to change
773 * the file before reading it.
774 */
775 if (!read_stdin)
776 close(fd); /* ignore errors */
777
778 /*
779 * The output from the autocommands should not overwrite anything and
780 * should not be overwritten: Set msg_scroll, restore its value if no
781 * output was done.
782 */
783 msg_scroll = TRUE;
784 if (filtering)
785 apply_autocmds_exarg(EVENT_FILTERREADPRE, NULL, sfname,
786 FALSE, curbuf, eap);
787 else if (read_stdin)
788 apply_autocmds_exarg(EVENT_STDINREADPRE, NULL, sfname,
789 FALSE, curbuf, eap);
790 else if (newfile)
791 apply_autocmds_exarg(EVENT_BUFREADPRE, NULL, sfname,
792 FALSE, curbuf, eap);
793 else
794 apply_autocmds_exarg(EVENT_FILEREADPRE, sfname, sfname,
795 FALSE, NULL, eap);
796 if (msg_scrolled == n)
797 msg_scroll = m;
798
799#ifdef FEAT_EVAL
800 if (aborting()) /* autocmds may abort script processing */
801 {
802 --no_wait_return;
803 msg_scroll = msg_save;
804 curbuf->b_p_ro = TRUE; /* must use "w!" now */
805 return FAIL;
806 }
807#endif
808 /*
809 * Don't allow the autocommands to change the current buffer.
810 * Try to re-open the file.
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000811 *
812 * Don't allow the autocommands to change the buffer name either
813 * (cd for example) if it invalidates fname or sfname.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000814 */
815 if (!read_stdin && (curbuf != old_curbuf
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000816 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
817 || (using_b_fname && (old_b_fname != curbuf->b_fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000818 || (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) < 0))
819 {
820 --no_wait_return;
821 msg_scroll = msg_save;
822 if (fd < 0)
823 EMSG(_("E200: *ReadPre autocommands made the file unreadable"));
824 else
825 EMSG(_("E201: *ReadPre autocommands must not change current buffer"));
826 curbuf->b_p_ro = TRUE; /* must use "w!" now */
827 return FAIL;
828 }
829 }
830#endif /* FEAT_AUTOCMD */
831
832 /* Autocommands may add lines to the file, need to check if it is empty */
833 wasempty = (curbuf->b_ml.ml_flags & ML_EMPTY);
834
835 if (!recoverymode && !filtering && !(flags & READ_DUMMY))
836 {
837 /*
838 * Show the user that we are busy reading the input. Sometimes this
839 * may take a while. When reading from stdin another program may
840 * still be running, don't move the cursor to the last line, unless
841 * always using the GUI.
842 */
843 if (read_stdin)
844 {
845#ifndef ALWAYS_USE_GUI
846 mch_msg(_("Vim: Reading from stdin...\n"));
847#endif
848#ifdef FEAT_GUI
849 /* Also write a message in the GUI window, if there is one. */
850 if (gui.in_use && !gui.dying && !gui.starting)
851 {
852 p = (char_u *)_("Reading from stdin...");
853 gui_write(p, (int)STRLEN(p));
854 }
855#endif
856 }
857 else if (!read_buffer)
858 filemess(curbuf, sfname, (char_u *)"", 0);
859 }
860
861 msg_scroll = FALSE; /* overwrite the file message */
862
863 /*
864 * Set linecnt now, before the "retry" caused by a wrong guess for
865 * fileformat, and after the autocommands, which may change them.
866 */
867 linecnt = curbuf->b_ml.ml_line_count;
868
869#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000870 /* "++bad=" argument. */
871 if (eap != NULL && eap->bad_char != 0)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000872 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000873 bad_char_behavior = eap->bad_char;
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000874 if (set_options)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000875 curbuf->b_bad_char = eap->bad_char;
876 }
877 else
878 curbuf->b_bad_char = 0;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000879
Bram Moolenaar071d4272004-06-13 20:20:40 +0000880 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000881 * Decide which 'encoding' to use or use first.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000882 */
883 if (eap != NULL && eap->force_enc != 0)
884 {
885 fenc = enc_canonize(eap->cmd + eap->force_enc);
886 fenc_alloced = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000887 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000888 }
889 else if (curbuf->b_p_bin)
890 {
891 fenc = (char_u *)""; /* binary: don't convert */
892 fenc_alloced = FALSE;
893 }
894 else if (curbuf->b_help)
895 {
896 char_u firstline[80];
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000897 int fc;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000898
899 /* Help files are either utf-8 or latin1. Try utf-8 first, if this
900 * fails it must be latin1.
901 * Always do this when 'encoding' is "utf-8". Otherwise only do
902 * this when needed to avoid [converted] remarks all the time.
903 * It is needed when the first line contains non-ASCII characters.
904 * That is only in *.??x files. */
905 fenc = (char_u *)"latin1";
906 c = enc_utf8;
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000907 if (!c && !read_stdin)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000908 {
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000909 fc = fname[STRLEN(fname) - 1];
910 if (TOLOWER_ASC(fc) == 'x')
911 {
912 /* Read the first line (and a bit more). Immediately rewind to
913 * the start of the file. If the read() fails "len" is -1. */
Bram Moolenaar540fc6f2010-12-17 16:27:16 +0100914 len = read_eintr(fd, firstline, 80);
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000915 lseek(fd, (off_t)0L, SEEK_SET);
916 for (p = firstline; p < firstline + len; ++p)
917 if (*p >= 0x80)
918 {
919 c = TRUE;
920 break;
921 }
922 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000923 }
924
925 if (c)
926 {
927 fenc_next = fenc;
928 fenc = (char_u *)"utf-8";
929
930 /* When the file is utf-8 but a character doesn't fit in
931 * 'encoding' don't retry. In help text editing utf-8 bytes
932 * doesn't make sense. */
Bram Moolenaarf193fff2006-04-27 00:02:13 +0000933 if (!enc_utf8)
934 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000935 }
936 fenc_alloced = FALSE;
937 }
938 else if (*p_fencs == NUL)
939 {
940 fenc = curbuf->b_p_fenc; /* use format from buffer */
941 fenc_alloced = FALSE;
942 }
943 else
944 {
945 fenc_next = p_fencs; /* try items in 'fileencodings' */
946 fenc = next_fenc(&fenc_next);
947 fenc_alloced = TRUE;
948 }
949#endif
950
951 /*
952 * Jump back here to retry reading the file in different ways.
953 * Reasons to retry:
954 * - encoding conversion failed: try another one from "fenc_next"
955 * - BOM detected and fenc was set, need to setup conversion
956 * - "fileformat" check failed: try another
957 *
958 * Variables set for special retry actions:
959 * "file_rewind" Rewind the file to start reading it again.
960 * "advance_fenc" Advance "fenc" using "fenc_next".
961 * "skip_read" Re-use already read bytes (BOM detected).
962 * "did_iconv" iconv() conversion failed, try 'charconvert'.
963 * "keep_fileformat" Don't reset "fileformat".
964 *
965 * Other status indicators:
966 * "tmpname" When != NULL did conversion with 'charconvert'.
967 * Output file has to be deleted afterwards.
968 * "iconv_fd" When != -1 did conversion with iconv().
969 */
970retry:
971
972 if (file_rewind)
973 {
974 if (read_buffer)
975 {
976 read_buf_lnum = 1;
977 read_buf_col = 0;
978 }
979 else if (read_stdin || lseek(fd, (off_t)0L, SEEK_SET) != 0)
980 {
981 /* Can't rewind the file, give up. */
982 error = TRUE;
983 goto failed;
984 }
985 /* Delete the previously read lines. */
986 while (lnum > from)
987 ml_delete(lnum--, FALSE);
988 file_rewind = FALSE;
989#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000990 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000991 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000992 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000993 curbuf->b_start_bomb = FALSE;
994 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000995 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000996#endif
997 }
998
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200999#ifdef FEAT_CRYPT
1000 if (cryptkey != NULL)
1001 /* Need to reset the state, but keep the key, don't want to ask for it
1002 * again. */
1003 crypt_pop_state();
1004#endif
1005
Bram Moolenaar071d4272004-06-13 20:20:40 +00001006 /*
1007 * When retrying with another "fenc" and the first time "fileformat"
1008 * will be reset.
1009 */
1010 if (keep_fileformat)
1011 keep_fileformat = FALSE;
1012 else
1013 {
1014 if (eap != NULL && eap->force_ff != 0)
Bram Moolenaar1c860362008-11-12 15:05:21 +00001015 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001016 fileformat = get_fileformat_force(curbuf, eap);
Bram Moolenaar1c860362008-11-12 15:05:21 +00001017 try_unix = try_dos = try_mac = FALSE;
1018 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001019 else if (curbuf->b_p_bin)
1020 fileformat = EOL_UNIX; /* binary: use Unix format */
1021 else if (*p_ffs == NUL)
1022 fileformat = get_fileformat(curbuf);/* use format from buffer */
1023 else
1024 fileformat = EOL_UNKNOWN; /* detect from file */
1025 }
1026
1027#ifdef FEAT_MBYTE
1028# ifdef USE_ICONV
1029 if (iconv_fd != (iconv_t)-1)
1030 {
1031 /* aborted conversion with iconv(), close the descriptor */
1032 iconv_close(iconv_fd);
1033 iconv_fd = (iconv_t)-1;
1034 }
1035# endif
1036
1037 if (advance_fenc)
1038 {
1039 /*
1040 * Try the next entry in 'fileencodings'.
1041 */
1042 advance_fenc = FALSE;
1043
1044 if (eap != NULL && eap->force_enc != 0)
1045 {
1046 /* Conversion given with "++cc=" wasn't possible, read
1047 * without conversion. */
1048 notconverted = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001049 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001050 if (fenc_alloced)
1051 vim_free(fenc);
1052 fenc = (char_u *)"";
1053 fenc_alloced = FALSE;
1054 }
1055 else
1056 {
1057 if (fenc_alloced)
1058 vim_free(fenc);
1059 if (fenc_next != NULL)
1060 {
1061 fenc = next_fenc(&fenc_next);
1062 fenc_alloced = (fenc_next != NULL);
1063 }
1064 else
1065 {
1066 fenc = (char_u *)"";
1067 fenc_alloced = FALSE;
1068 }
1069 }
1070 if (tmpname != NULL)
1071 {
1072 mch_remove(tmpname); /* delete converted file */
1073 vim_free(tmpname);
1074 tmpname = NULL;
1075 }
1076 }
1077
1078 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001079 * Conversion may be required when the encoding of the file is different
1080 * from 'encoding' or 'encoding' is UTF-16, UCS-2 or UCS-4.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001081 */
1082 fio_flags = 0;
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001083 converted = need_conversion(fenc);
1084 if (converted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001085 {
1086
1087 /* "ucs-bom" means we need to check the first bytes of the file
1088 * for a BOM. */
1089 if (STRCMP(fenc, ENC_UCSBOM) == 0)
1090 fio_flags = FIO_UCSBOM;
1091
1092 /*
1093 * Check if UCS-2/4 or Latin1 to UTF-8 conversion needs to be
1094 * done. This is handled below after read(). Prepare the
1095 * fio_flags to avoid having to parse the string each time.
1096 * Also check for Unicode to Latin1 conversion, because iconv()
1097 * appears not to handle this correctly. This works just like
1098 * conversion to UTF-8 except how the resulting character is put in
1099 * the buffer.
1100 */
1101 else if (enc_utf8 || STRCMP(p_enc, "latin1") == 0)
1102 fio_flags = get_fio_flags(fenc);
1103
1104# ifdef WIN3264
1105 /*
1106 * Conversion from an MS-Windows codepage to UTF-8 or another codepage
1107 * is handled with MultiByteToWideChar().
1108 */
1109 if (fio_flags == 0)
1110 fio_flags = get_win_fio_flags(fenc);
1111# endif
1112
1113# ifdef MACOS_X
1114 /* Conversion from Apple MacRoman to latin1 or UTF-8 */
1115 if (fio_flags == 0)
1116 fio_flags = get_mac_fio_flags(fenc);
1117# endif
1118
1119# ifdef USE_ICONV
1120 /*
1121 * Try using iconv() if we can't convert internally.
1122 */
1123 if (fio_flags == 0
1124# ifdef FEAT_EVAL
1125 && !did_iconv
1126# endif
1127 )
1128 iconv_fd = (iconv_t)my_iconv_open(
1129 enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc);
1130# endif
1131
1132# ifdef FEAT_EVAL
1133 /*
1134 * Use the 'charconvert' expression when conversion is required
1135 * and we can't do it internally or with iconv().
1136 */
1137 if (fio_flags == 0 && !read_stdin && !read_buffer && *p_ccv != NUL
1138# ifdef USE_ICONV
1139 && iconv_fd == (iconv_t)-1
1140# endif
1141 )
1142 {
1143# ifdef USE_ICONV
1144 did_iconv = FALSE;
1145# endif
1146 /* Skip conversion when it's already done (retry for wrong
1147 * "fileformat"). */
1148 if (tmpname == NULL)
1149 {
1150 tmpname = readfile_charconvert(fname, fenc, &fd);
1151 if (tmpname == NULL)
1152 {
1153 /* Conversion failed. Try another one. */
1154 advance_fenc = TRUE;
1155 if (fd < 0)
1156 {
1157 /* Re-opening the original file failed! */
1158 EMSG(_("E202: Conversion made file unreadable!"));
1159 error = TRUE;
1160 goto failed;
1161 }
1162 goto retry;
1163 }
1164 }
1165 }
1166 else
1167# endif
1168 {
1169 if (fio_flags == 0
1170# ifdef USE_ICONV
1171 && iconv_fd == (iconv_t)-1
1172# endif
1173 )
1174 {
1175 /* Conversion wanted but we can't.
1176 * Try the next conversion in 'fileencodings' */
1177 advance_fenc = TRUE;
1178 goto retry;
1179 }
1180 }
1181 }
1182
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001183 /* Set "can_retry" when it's possible to rewind the file and try with
Bram Moolenaar071d4272004-06-13 20:20:40 +00001184 * another "fenc" value. It's FALSE when no other "fenc" to try, reading
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001185 * stdin or fixed at a specific encoding. */
1186 can_retry = (*fenc != NUL && !read_stdin && !keep_dest_enc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001187#endif
1188
1189 if (!skip_read)
1190 {
1191 linerest = 0;
1192 filesize = 0;
1193 skip_count = lines_to_skip;
1194 read_count = lines_to_read;
1195#ifdef FEAT_MBYTE
1196 conv_restlen = 0;
1197#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001198#ifdef FEAT_PERSISTENT_UNDO
Bram Moolenaar59f931e2010-07-24 20:27:03 +02001199 read_undo_file = (newfile && (flags & READ_KEEP_UNDO) == 0
1200 && curbuf->b_ffname != NULL
1201 && curbuf->b_p_udf
1202 && !filtering
1203 && !read_stdin
1204 && !read_buffer);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001205 if (read_undo_file)
1206 sha256_start(&sha_ctx);
1207#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001208 }
1209
1210 while (!error && !got_int)
1211 {
1212 /*
1213 * We allocate as much space for the file as we can get, plus
1214 * space for the old line plus room for one terminating NUL.
1215 * The amount is limited by the fact that read() only can read
1216 * upto max_unsigned characters (and other things).
1217 */
1218#if SIZEOF_INT <= 2
1219 if (linerest >= 0x7ff0)
1220 {
1221 ++split;
1222 *ptr = NL; /* split line by inserting a NL */
1223 size = 1;
1224 }
1225 else
1226#endif
1227 {
1228 if (!skip_read)
1229 {
1230#if SIZEOF_INT > 2
Bram Moolenaar311d9822007-02-27 15:48:28 +00001231# if defined(SSIZE_MAX) && (SSIZE_MAX < 0x10000L)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001232 size = SSIZE_MAX; /* use max I/O size, 52K */
1233# else
1234 size = 0x10000L; /* use buffer >= 64K */
1235# endif
1236#else
1237 size = 0x7ff0L - linerest; /* limit buffer to 32K */
1238#endif
1239
Bram Moolenaarc1e37902006-04-18 21:55:01 +00001240 for ( ; size >= 10; size = (long)((long_u)size >> 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001241 {
1242 if ((new_buffer = lalloc((long_u)(size + linerest + 1),
1243 FALSE)) != NULL)
1244 break;
1245 }
1246 if (new_buffer == NULL)
1247 {
1248 do_outofmem_msg((long_u)(size * 2 + linerest + 1));
1249 error = TRUE;
1250 break;
1251 }
1252 if (linerest) /* copy characters from the previous buffer */
1253 mch_memmove(new_buffer, ptr - linerest, (size_t)linerest);
1254 vim_free(buffer);
1255 buffer = new_buffer;
1256 ptr = buffer + linerest;
1257 line_start = buffer;
1258
1259#ifdef FEAT_MBYTE
1260 /* May need room to translate into.
1261 * For iconv() we don't really know the required space, use a
1262 * factor ICONV_MULT.
1263 * latin1 to utf-8: 1 byte becomes up to 2 bytes
1264 * utf-16 to utf-8: 2 bytes become up to 3 bytes, 4 bytes
1265 * become up to 4 bytes, size must be multiple of 2
1266 * ucs-2 to utf-8: 2 bytes become up to 3 bytes, size must be
1267 * multiple of 2
1268 * ucs-4 to utf-8: 4 bytes become up to 6 bytes, size must be
1269 * multiple of 4 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001270 real_size = (int)size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001271# ifdef USE_ICONV
1272 if (iconv_fd != (iconv_t)-1)
1273 size = size / ICONV_MULT;
1274 else
1275# endif
1276 if (fio_flags & FIO_LATIN1)
1277 size = size / 2;
1278 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1279 size = (size * 2 / 3) & ~1;
1280 else if (fio_flags & FIO_UCS4)
1281 size = (size * 2 / 3) & ~3;
1282 else if (fio_flags == FIO_UCSBOM)
1283 size = size / ICONV_MULT; /* worst case */
1284# ifdef WIN3264
1285 else if (fio_flags & FIO_CODEPAGE)
1286 size = size / ICONV_MULT; /* also worst case */
1287# endif
1288# ifdef MACOS_X
1289 else if (fio_flags & FIO_MACROMAN)
1290 size = size / ICONV_MULT; /* also worst case */
1291# endif
1292#endif
1293
1294#ifdef FEAT_MBYTE
1295 if (conv_restlen > 0)
1296 {
1297 /* Insert unconverted bytes from previous line. */
1298 mch_memmove(ptr, conv_rest, conv_restlen);
1299 ptr += conv_restlen;
1300 size -= conv_restlen;
1301 }
1302#endif
1303
1304 if (read_buffer)
1305 {
1306 /*
1307 * Read bytes from curbuf. Used for converting text read
1308 * from stdin.
1309 */
1310 if (read_buf_lnum > from)
1311 size = 0;
1312 else
1313 {
1314 int n, ni;
1315 long tlen;
1316
1317 tlen = 0;
1318 for (;;)
1319 {
1320 p = ml_get(read_buf_lnum) + read_buf_col;
1321 n = (int)STRLEN(p);
1322 if ((int)tlen + n + 1 > size)
1323 {
1324 /* Filled up to "size", append partial line.
1325 * Change NL to NUL to reverse the effect done
1326 * below. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001327 n = (int)(size - tlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001328 for (ni = 0; ni < n; ++ni)
1329 {
1330 if (p[ni] == NL)
1331 ptr[tlen++] = NUL;
1332 else
1333 ptr[tlen++] = p[ni];
1334 }
1335 read_buf_col += n;
1336 break;
1337 }
1338 else
1339 {
1340 /* Append whole line and new-line. Change NL
1341 * to NUL to reverse the effect done below. */
1342 for (ni = 0; ni < n; ++ni)
1343 {
1344 if (p[ni] == NL)
1345 ptr[tlen++] = NUL;
1346 else
1347 ptr[tlen++] = p[ni];
1348 }
1349 ptr[tlen++] = NL;
1350 read_buf_col = 0;
1351 if (++read_buf_lnum > from)
1352 {
1353 /* When the last line didn't have an
1354 * end-of-line don't add it now either. */
1355 if (!curbuf->b_p_eol)
1356 --tlen;
1357 size = tlen;
1358 break;
1359 }
1360 }
1361 }
1362 }
1363 }
1364 else
1365 {
1366 /*
1367 * Read bytes from the file.
1368 */
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01001369 size = read_eintr(fd, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001370 }
1371
1372 if (size <= 0)
1373 {
1374 if (size < 0) /* read error */
1375 error = TRUE;
1376#ifdef FEAT_MBYTE
1377 else if (conv_restlen > 0)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001378 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001379 /*
1380 * Reached end-of-file but some trailing bytes could
1381 * not be converted. Truncated file?
1382 */
1383
1384 /* When we did a conversion report an error. */
1385 if (fio_flags != 0
1386# ifdef USE_ICONV
1387 || iconv_fd != (iconv_t)-1
1388# endif
1389 )
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001390 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001391 if (conv_error == 0)
1392 conv_error = curbuf->b_ml.ml_line_count
1393 - linecnt + 1;
1394 }
1395 /* Remember the first linenr with an illegal byte */
1396 else if (illegal_byte == 0)
1397 illegal_byte = curbuf->b_ml.ml_line_count
1398 - linecnt + 1;
1399 if (bad_char_behavior == BAD_DROP)
1400 {
1401 *(ptr - conv_restlen) = NUL;
1402 conv_restlen = 0;
1403 }
1404 else
1405 {
1406 /* Replace the trailing bytes with the replacement
1407 * character if we were converting; if we weren't,
1408 * leave the UTF8 checking code to do it, as it
1409 * works slightly differently. */
1410 if (bad_char_behavior != BAD_KEEP && (fio_flags != 0
1411# ifdef USE_ICONV
1412 || iconv_fd != (iconv_t)-1
1413# endif
1414 ))
1415 {
1416 while (conv_restlen > 0)
1417 {
1418 *(--ptr) = bad_char_behavior;
1419 --conv_restlen;
1420 }
1421 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001422 fio_flags = 0; /* don't convert this */
Bram Moolenaarb21e5842006-04-16 18:30:08 +00001423# ifdef USE_ICONV
1424 if (iconv_fd != (iconv_t)-1)
1425 {
1426 iconv_close(iconv_fd);
1427 iconv_fd = (iconv_t)-1;
1428 }
1429# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001430 }
1431 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001432#endif
1433 }
1434
1435#ifdef FEAT_CRYPT
1436 /*
1437 * At start of file: Check for magic number of encryption.
1438 */
1439 if (filesize == 0)
1440 cryptkey = check_for_cryptkey(cryptkey, ptr, &size,
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001441 &filesize, newfile, sfname,
1442 &did_ask_for_key);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001443 /*
1444 * Decrypt the read bytes.
1445 */
1446 if (cryptkey != NULL && size > 0)
Bram Moolenaar04c9baf2010-06-01 23:37:39 +02001447 crypt_decode(ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001448#endif
1449 }
1450 skip_read = FALSE;
1451
1452#ifdef FEAT_MBYTE
1453 /*
1454 * At start of file (or after crypt magic number): Check for BOM.
1455 * Also check for a BOM for other Unicode encodings, but not after
1456 * converting with 'charconvert' or when a BOM has already been
1457 * found.
1458 */
1459 if ((filesize == 0
1460# ifdef FEAT_CRYPT
Bram Moolenaar40e6a712010-05-16 22:32:54 +02001461 || (filesize == (CRYPT_MAGIC_LEN
Bram Moolenaar80794b12010-06-13 05:20:42 +02001462 + crypt_salt_len[use_crypt_method]
Bram Moolenaar40e6a712010-05-16 22:32:54 +02001463 + crypt_seed_len[use_crypt_method])
1464 && cryptkey != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001465# endif
1466 )
1467 && (fio_flags == FIO_UCSBOM
1468 || (!curbuf->b_p_bomb
1469 && tmpname == NULL
1470 && (*fenc == 'u' || (*fenc == NUL && enc_utf8)))))
1471 {
1472 char_u *ccname;
1473 int blen;
1474
1475 /* no BOM detection in a short file or in binary mode */
1476 if (size < 2 || curbuf->b_p_bin)
1477 ccname = NULL;
1478 else
1479 ccname = check_for_bom(ptr, size, &blen,
1480 fio_flags == FIO_UCSBOM ? FIO_ALL : get_fio_flags(fenc));
1481 if (ccname != NULL)
1482 {
1483 /* Remove BOM from the text */
1484 filesize += blen;
1485 size -= blen;
1486 mch_memmove(ptr, ptr + blen, (size_t)size);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00001487 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001488 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001489 curbuf->b_p_bomb = TRUE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001490 curbuf->b_start_bomb = TRUE;
1491 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001492 }
1493
1494 if (fio_flags == FIO_UCSBOM)
1495 {
1496 if (ccname == NULL)
1497 {
1498 /* No BOM detected: retry with next encoding. */
1499 advance_fenc = TRUE;
1500 }
1501 else
1502 {
1503 /* BOM detected: set "fenc" and jump back */
1504 if (fenc_alloced)
1505 vim_free(fenc);
1506 fenc = ccname;
1507 fenc_alloced = FALSE;
1508 }
1509 /* retry reading without getting new bytes or rewinding */
1510 skip_read = TRUE;
1511 goto retry;
1512 }
1513 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001514
1515 /* Include not converted bytes. */
1516 ptr -= conv_restlen;
1517 size += conv_restlen;
1518 conv_restlen = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001519#endif
1520 /*
1521 * Break here for a read error or end-of-file.
1522 */
1523 if (size <= 0)
1524 break;
1525
1526#ifdef FEAT_MBYTE
1527
Bram Moolenaar071d4272004-06-13 20:20:40 +00001528# ifdef USE_ICONV
1529 if (iconv_fd != (iconv_t)-1)
1530 {
1531 /*
1532 * Attempt conversion of the read bytes to 'encoding' using
1533 * iconv().
1534 */
1535 const char *fromp;
1536 char *top;
1537 size_t from_size;
1538 size_t to_size;
1539
1540 fromp = (char *)ptr;
1541 from_size = size;
1542 ptr += size;
1543 top = (char *)ptr;
1544 to_size = real_size - size;
1545
1546 /*
1547 * If there is conversion error or not enough room try using
Bram Moolenaar19a09a12005-03-04 23:39:37 +00001548 * another conversion. Except for when there is no
1549 * alternative (help files).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001550 */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001551 while ((iconv(iconv_fd, (void *)&fromp, &from_size,
1552 &top, &to_size)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001553 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
1554 || from_size > CONV_RESTLEN)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001555 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001556 if (can_retry)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001557 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001558 if (conv_error == 0)
1559 conv_error = readfile_linenr(linecnt,
1560 ptr, (char_u *)top);
Bram Moolenaar42eeac32005-06-29 22:40:58 +00001561
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001562 /* Deal with a bad byte and continue with the next. */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001563 ++fromp;
1564 --from_size;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001565 if (bad_char_behavior == BAD_KEEP)
1566 {
1567 *top++ = *(fromp - 1);
1568 --to_size;
1569 }
1570 else if (bad_char_behavior != BAD_DROP)
1571 {
1572 *top++ = bad_char_behavior;
1573 --to_size;
1574 }
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001575 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001576
1577 if (from_size > 0)
1578 {
1579 /* Some remaining characters, keep them for the next
1580 * round. */
1581 mch_memmove(conv_rest, (char_u *)fromp, from_size);
1582 conv_restlen = (int)from_size;
1583 }
1584
1585 /* move the linerest to before the converted characters */
1586 line_start = ptr - linerest;
1587 mch_memmove(line_start, buffer, (size_t)linerest);
1588 size = (long)((char_u *)top - ptr);
1589 }
1590# endif
1591
1592# ifdef WIN3264
1593 if (fio_flags & FIO_CODEPAGE)
1594 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001595 char_u *src, *dst;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001596 WCHAR ucs2buf[3];
1597 int ucs2len;
1598 int codepage = FIO_GET_CP(fio_flags);
1599 int bytelen;
1600 int found_bad;
1601 char replstr[2];
1602
Bram Moolenaar071d4272004-06-13 20:20:40 +00001603 /*
1604 * Conversion from an MS-Windows codepage or UTF-8 to UTF-8 or
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001605 * a codepage, using standard MS-Windows functions. This
1606 * requires two steps:
1607 * 1. convert from 'fileencoding' to ucs-2
1608 * 2. convert from ucs-2 to 'encoding'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001609 *
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001610 * Because there may be illegal bytes AND an incomplete byte
1611 * sequence at the end, we may have to do the conversion one
1612 * character at a time to get it right.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001613 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001614
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001615 /* Replacement string for WideCharToMultiByte(). */
1616 if (bad_char_behavior > 0)
1617 replstr[0] = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001618 else
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001619 replstr[0] = '?';
1620 replstr[1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001621
1622 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001623 * Move the bytes to the end of the buffer, so that we have
1624 * room to put the result at the start.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001625 */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001626 src = ptr + real_size - size;
1627 mch_memmove(src, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001628
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001629 /*
1630 * Do the conversion.
1631 */
1632 dst = ptr;
1633 size = size;
1634 while (size > 0)
1635 {
1636 found_bad = FALSE;
1637
1638# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
1639 if (codepage == CP_UTF8)
1640 {
1641 /* Handle CP_UTF8 input ourselves to be able to handle
1642 * trailing bytes properly.
1643 * Get one UTF-8 character from src. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001644 bytelen = (int)utf_ptr2len_len(src, size);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001645 if (bytelen > size)
1646 {
1647 /* Only got some bytes of a character. Normally
1648 * it's put in "conv_rest", but if it's too long
1649 * deal with it as if they were illegal bytes. */
1650 if (bytelen <= CONV_RESTLEN)
1651 break;
1652
1653 /* weird overlong byte sequence */
1654 bytelen = size;
1655 found_bad = TRUE;
1656 }
1657 else
1658 {
Bram Moolenaarc01140a2006-03-24 22:21:52 +00001659 int u8c = utf_ptr2char(src);
1660
Bram Moolenaar86e01082005-12-29 22:45:34 +00001661 if (u8c > 0xffff || (*src >= 0x80 && bytelen == 1))
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001662 found_bad = TRUE;
1663 ucs2buf[0] = u8c;
1664 ucs2len = 1;
1665 }
1666 }
1667 else
1668# endif
1669 {
1670 /* We don't know how long the byte sequence is, try
1671 * from one to three bytes. */
1672 for (bytelen = 1; bytelen <= size && bytelen <= 3;
1673 ++bytelen)
1674 {
1675 ucs2len = MultiByteToWideChar(codepage,
1676 MB_ERR_INVALID_CHARS,
1677 (LPCSTR)src, bytelen,
1678 ucs2buf, 3);
1679 if (ucs2len > 0)
1680 break;
1681 }
1682 if (ucs2len == 0)
1683 {
1684 /* If we have only one byte then it's probably an
1685 * incomplete byte sequence. Otherwise discard
1686 * one byte as a bad character. */
1687 if (size == 1)
1688 break;
1689 found_bad = TRUE;
1690 bytelen = 1;
1691 }
1692 }
1693
1694 if (!found_bad)
1695 {
1696 int i;
1697
1698 /* Convert "ucs2buf[ucs2len]" to 'enc' in "dst". */
1699 if (enc_utf8)
1700 {
1701 /* From UCS-2 to UTF-8. Cannot fail. */
1702 for (i = 0; i < ucs2len; ++i)
1703 dst += utf_char2bytes(ucs2buf[i], dst);
1704 }
1705 else
1706 {
1707 BOOL bad = FALSE;
1708 int dstlen;
1709
1710 /* From UCS-2 to "enc_codepage". If the
1711 * conversion uses the default character "?",
1712 * the data doesn't fit in this encoding. */
1713 dstlen = WideCharToMultiByte(enc_codepage, 0,
1714 (LPCWSTR)ucs2buf, ucs2len,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001715 (LPSTR)dst, (int)(src - dst),
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001716 replstr, &bad);
1717 if (bad)
1718 found_bad = TRUE;
1719 else
1720 dst += dstlen;
1721 }
1722 }
1723
1724 if (found_bad)
1725 {
1726 /* Deal with bytes we can't convert. */
1727 if (can_retry)
1728 goto rewind_retry;
1729 if (conv_error == 0)
1730 conv_error = readfile_linenr(linecnt, ptr, dst);
1731 if (bad_char_behavior != BAD_DROP)
1732 {
1733 if (bad_char_behavior == BAD_KEEP)
1734 {
1735 mch_memmove(dst, src, bytelen);
1736 dst += bytelen;
1737 }
1738 else
1739 *dst++ = bad_char_behavior;
1740 }
1741 }
1742
1743 src += bytelen;
1744 size -= bytelen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001745 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001746
1747 if (size > 0)
1748 {
1749 /* An incomplete byte sequence remaining. */
1750 mch_memmove(conv_rest, src, size);
1751 conv_restlen = size;
1752 }
1753
1754 /* The new size is equal to how much "dst" was advanced. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001755 size = (long)(dst - ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001756 }
1757 else
1758# endif
Bram Moolenaar56718732006-03-15 22:53:57 +00001759# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001760 if (fio_flags & FIO_MACROMAN)
1761 {
1762 /*
1763 * Conversion from Apple MacRoman char encoding to UTF-8 or
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001764 * latin1. This is in os_mac_conv.c.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001765 */
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001766 if (macroman2enc(ptr, &size, real_size) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001767 goto rewind_retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001768 }
1769 else
1770# endif
1771 if (fio_flags != 0)
1772 {
1773 int u8c;
1774 char_u *dest;
1775 char_u *tail = NULL;
1776
1777 /*
1778 * "enc_utf8" set: Convert Unicode or Latin1 to UTF-8.
1779 * "enc_utf8" not set: Convert Unicode to Latin1.
1780 * Go from end to start through the buffer, because the number
1781 * of bytes may increase.
1782 * "dest" points to after where the UTF-8 bytes go, "p" points
1783 * to after the next character to convert.
1784 */
1785 dest = ptr + real_size;
1786 if (fio_flags == FIO_LATIN1 || fio_flags == FIO_UTF8)
1787 {
1788 p = ptr + size;
1789 if (fio_flags == FIO_UTF8)
1790 {
1791 /* Check for a trailing incomplete UTF-8 sequence */
1792 tail = ptr + size - 1;
1793 while (tail > ptr && (*tail & 0xc0) == 0x80)
1794 --tail;
1795 if (tail + utf_byte2len(*tail) <= ptr + size)
1796 tail = NULL;
1797 else
1798 p = tail;
1799 }
1800 }
1801 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1802 {
1803 /* Check for a trailing byte */
1804 p = ptr + (size & ~1);
1805 if (size & 1)
1806 tail = p;
1807 if ((fio_flags & FIO_UTF16) && p > ptr)
1808 {
1809 /* Check for a trailing leading word */
1810 if (fio_flags & FIO_ENDIAN_L)
1811 {
1812 u8c = (*--p << 8);
1813 u8c += *--p;
1814 }
1815 else
1816 {
1817 u8c = *--p;
1818 u8c += (*--p << 8);
1819 }
1820 if (u8c >= 0xd800 && u8c <= 0xdbff)
1821 tail = p;
1822 else
1823 p += 2;
1824 }
1825 }
1826 else /* FIO_UCS4 */
1827 {
1828 /* Check for trailing 1, 2 or 3 bytes */
1829 p = ptr + (size & ~3);
1830 if (size & 3)
1831 tail = p;
1832 }
1833
1834 /* If there is a trailing incomplete sequence move it to
1835 * conv_rest[]. */
1836 if (tail != NULL)
1837 {
1838 conv_restlen = (int)((ptr + size) - tail);
1839 mch_memmove(conv_rest, (char_u *)tail, conv_restlen);
1840 size -= conv_restlen;
1841 }
1842
1843
1844 while (p > ptr)
1845 {
1846 if (fio_flags & FIO_LATIN1)
1847 u8c = *--p;
1848 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1849 {
1850 if (fio_flags & FIO_ENDIAN_L)
1851 {
1852 u8c = (*--p << 8);
1853 u8c += *--p;
1854 }
1855 else
1856 {
1857 u8c = *--p;
1858 u8c += (*--p << 8);
1859 }
1860 if ((fio_flags & FIO_UTF16)
1861 && u8c >= 0xdc00 && u8c <= 0xdfff)
1862 {
1863 int u16c;
1864
1865 if (p == ptr)
1866 {
1867 /* Missing leading word. */
1868 if (can_retry)
1869 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001870 if (conv_error == 0)
1871 conv_error = readfile_linenr(linecnt,
1872 ptr, p);
1873 if (bad_char_behavior == BAD_DROP)
1874 continue;
1875 if (bad_char_behavior != BAD_KEEP)
1876 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001877 }
1878
1879 /* found second word of double-word, get the first
1880 * word and compute the resulting character */
1881 if (fio_flags & FIO_ENDIAN_L)
1882 {
1883 u16c = (*--p << 8);
1884 u16c += *--p;
1885 }
1886 else
1887 {
1888 u16c = *--p;
1889 u16c += (*--p << 8);
1890 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001891 u8c = 0x10000 + ((u16c & 0x3ff) << 10)
1892 + (u8c & 0x3ff);
1893
Bram Moolenaar071d4272004-06-13 20:20:40 +00001894 /* Check if the word is indeed a leading word. */
1895 if (u16c < 0xd800 || u16c > 0xdbff)
1896 {
1897 if (can_retry)
1898 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001899 if (conv_error == 0)
1900 conv_error = readfile_linenr(linecnt,
1901 ptr, p);
1902 if (bad_char_behavior == BAD_DROP)
1903 continue;
1904 if (bad_char_behavior != BAD_KEEP)
1905 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001906 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001907 }
1908 }
1909 else if (fio_flags & FIO_UCS4)
1910 {
1911 if (fio_flags & FIO_ENDIAN_L)
1912 {
1913 u8c = (*--p << 24);
1914 u8c += (*--p << 16);
1915 u8c += (*--p << 8);
1916 u8c += *--p;
1917 }
1918 else /* big endian */
1919 {
1920 u8c = *--p;
1921 u8c += (*--p << 8);
1922 u8c += (*--p << 16);
1923 u8c += (*--p << 24);
1924 }
1925 }
1926 else /* UTF-8 */
1927 {
1928 if (*--p < 0x80)
1929 u8c = *p;
1930 else
1931 {
1932 len = utf_head_off(ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001933 p -= len;
1934 u8c = utf_ptr2char(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001935 if (len == 0)
1936 {
1937 /* Not a valid UTF-8 character, retry with
1938 * another fenc when possible, otherwise just
1939 * report the error. */
1940 if (can_retry)
1941 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001942 if (conv_error == 0)
1943 conv_error = readfile_linenr(linecnt,
1944 ptr, p);
1945 if (bad_char_behavior == BAD_DROP)
1946 continue;
1947 if (bad_char_behavior != BAD_KEEP)
1948 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001949 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001950 }
1951 }
1952 if (enc_utf8) /* produce UTF-8 */
1953 {
1954 dest -= utf_char2len(u8c);
1955 (void)utf_char2bytes(u8c, dest);
1956 }
1957 else /* produce Latin1 */
1958 {
1959 --dest;
1960 if (u8c >= 0x100)
1961 {
1962 /* character doesn't fit in latin1, retry with
1963 * another fenc when possible, otherwise just
1964 * report the error. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001965 if (can_retry)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001966 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001967 if (conv_error == 0)
1968 conv_error = readfile_linenr(linecnt, ptr, p);
1969 if (bad_char_behavior == BAD_DROP)
1970 ++dest;
1971 else if (bad_char_behavior == BAD_KEEP)
1972 *dest = u8c;
1973 else if (eap != NULL && eap->bad_char != 0)
1974 *dest = bad_char_behavior;
1975 else
1976 *dest = 0xBF;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001977 }
1978 else
1979 *dest = u8c;
1980 }
1981 }
1982
1983 /* move the linerest to before the converted characters */
1984 line_start = dest - linerest;
1985 mch_memmove(line_start, buffer, (size_t)linerest);
1986 size = (long)((ptr + real_size) - dest);
1987 ptr = dest;
1988 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001989 else if (enc_utf8 && !curbuf->b_p_bin)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001990 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001991 int incomplete_tail = FALSE;
1992
1993 /* Reading UTF-8: Check if the bytes are valid UTF-8. */
1994 for (p = ptr; ; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001995 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001996 int todo = (int)((ptr + size) - p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001997 int l;
1998
1999 if (todo <= 0)
2000 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002001 if (*p >= 0x80)
2002 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002003 /* A length of 1 means it's an illegal byte. Accept
2004 * an incomplete character at the end though, the next
2005 * read() will get the next bytes, we'll check it
2006 * then. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002007 l = utf_ptr2len_len(p, todo);
Bram Moolenaarf453d352008-06-04 17:37:34 +00002008 if (l > todo && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002009 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002010 /* Avoid retrying with a different encoding when
2011 * a truncated file is more likely, or attempting
2012 * to read the rest of an incomplete sequence when
2013 * we have already done so. */
2014 if (p > ptr || filesize > 0)
2015 incomplete_tail = TRUE;
2016 /* Incomplete byte sequence, move it to conv_rest[]
2017 * and try to read the rest of it, unless we've
2018 * already done so. */
2019 if (p > ptr)
2020 {
2021 conv_restlen = todo;
2022 mch_memmove(conv_rest, p, conv_restlen);
2023 size -= conv_restlen;
2024 break;
2025 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002026 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002027 if (l == 1 || l > todo)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002028 {
2029 /* Illegal byte. If we can try another encoding
Bram Moolenaarf453d352008-06-04 17:37:34 +00002030 * do that, unless at EOF where a truncated
2031 * file is more likely than a conversion error. */
2032 if (can_retry && !incomplete_tail)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002033 break;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002034# ifdef USE_ICONV
2035 /* When we did a conversion report an error. */
2036 if (iconv_fd != (iconv_t)-1 && conv_error == 0)
2037 conv_error = readfile_linenr(linecnt, ptr, p);
2038# endif
Bram Moolenaarf453d352008-06-04 17:37:34 +00002039 /* Remember the first linenr with an illegal byte */
2040 if (conv_error == 0 && illegal_byte == 0)
2041 illegal_byte = readfile_linenr(linecnt, ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002042
2043 /* Drop, keep or replace the bad byte. */
2044 if (bad_char_behavior == BAD_DROP)
2045 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002046 mch_memmove(p, p + 1, todo - 1);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002047 --p;
2048 --size;
2049 }
2050 else if (bad_char_behavior != BAD_KEEP)
2051 *p = bad_char_behavior;
2052 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002053 else
2054 p += l - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002055 }
2056 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002057 if (p < ptr + size && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002058 {
2059 /* Detected a UTF-8 error. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002060rewind_retry:
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002061 /* Retry reading with another conversion. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002062# if defined(FEAT_EVAL) && defined(USE_ICONV)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002063 if (*p_ccv != NUL && iconv_fd != (iconv_t)-1)
2064 /* iconv() failed, try 'charconvert' */
2065 did_iconv = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002066 else
2067# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002068 /* use next item from 'fileencodings' */
2069 advance_fenc = TRUE;
2070 file_rewind = TRUE;
2071 goto retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002072 }
2073 }
2074#endif
2075
2076 /* count the number of characters (after conversion!) */
2077 filesize += size;
2078
2079 /*
2080 * when reading the first part of a file: guess EOL type
2081 */
2082 if (fileformat == EOL_UNKNOWN)
2083 {
2084 /* First try finding a NL, for Dos and Unix */
2085 if (try_dos || try_unix)
2086 {
2087 for (p = ptr; p < ptr + size; ++p)
2088 {
2089 if (*p == NL)
2090 {
2091 if (!try_unix
2092 || (try_dos && p > ptr && p[-1] == CAR))
2093 fileformat = EOL_DOS;
2094 else
2095 fileformat = EOL_UNIX;
2096 break;
2097 }
2098 }
2099
2100 /* Don't give in to EOL_UNIX if EOL_MAC is more likely */
2101 if (fileformat == EOL_UNIX && try_mac)
2102 {
2103 /* Need to reset the counters when retrying fenc. */
2104 try_mac = 1;
2105 try_unix = 1;
2106 for (; p >= ptr && *p != CAR; p--)
2107 ;
2108 if (p >= ptr)
2109 {
2110 for (p = ptr; p < ptr + size; ++p)
2111 {
2112 if (*p == NL)
2113 try_unix++;
2114 else if (*p == CAR)
2115 try_mac++;
2116 }
2117 if (try_mac > try_unix)
2118 fileformat = EOL_MAC;
2119 }
2120 }
2121 }
2122
2123 /* No NL found: may use Mac format */
2124 if (fileformat == EOL_UNKNOWN && try_mac)
2125 fileformat = EOL_MAC;
2126
2127 /* Still nothing found? Use first format in 'ffs' */
2128 if (fileformat == EOL_UNKNOWN)
2129 fileformat = default_fileformat();
2130
2131 /* if editing a new file: may set p_tx and p_ff */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002132 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002133 set_fileformat(fileformat, OPT_LOCAL);
2134 }
2135 }
2136
2137 /*
2138 * This loop is executed once for every character read.
2139 * Keep it fast!
2140 */
2141 if (fileformat == EOL_MAC)
2142 {
2143 --ptr;
2144 while (++ptr, --size >= 0)
2145 {
2146 /* catch most common case first */
2147 if ((c = *ptr) != NUL && c != CAR && c != NL)
2148 continue;
2149 if (c == NUL)
2150 *ptr = NL; /* NULs are replaced by newlines! */
2151 else if (c == NL)
2152 *ptr = CAR; /* NLs are replaced by CRs! */
2153 else
2154 {
2155 if (skip_count == 0)
2156 {
2157 *ptr = NUL; /* end of line */
2158 len = (colnr_T) (ptr - line_start + 1);
2159 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2160 {
2161 error = TRUE;
2162 break;
2163 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002164#ifdef FEAT_PERSISTENT_UNDO
2165 if (read_undo_file)
2166 sha256_update(&sha_ctx, line_start, len);
2167#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002168 ++lnum;
2169 if (--read_count == 0)
2170 {
2171 error = TRUE; /* break loop */
2172 line_start = ptr; /* nothing left to write */
2173 break;
2174 }
2175 }
2176 else
2177 --skip_count;
2178 line_start = ptr + 1;
2179 }
2180 }
2181 }
2182 else
2183 {
2184 --ptr;
2185 while (++ptr, --size >= 0)
2186 {
2187 if ((c = *ptr) != NUL && c != NL) /* catch most common case */
2188 continue;
2189 if (c == NUL)
2190 *ptr = NL; /* NULs are replaced by newlines! */
2191 else
2192 {
2193 if (skip_count == 0)
2194 {
2195 *ptr = NUL; /* end of line */
2196 len = (colnr_T)(ptr - line_start + 1);
2197 if (fileformat == EOL_DOS)
2198 {
2199 if (ptr[-1] == CAR) /* remove CR */
2200 {
2201 ptr[-1] = NUL;
2202 --len;
2203 }
2204 /*
2205 * Reading in Dos format, but no CR-LF found!
2206 * When 'fileformats' includes "unix", delete all
2207 * the lines read so far and start all over again.
2208 * Otherwise give an error message later.
2209 */
2210 else if (ff_error != EOL_DOS)
2211 {
2212 if ( try_unix
2213 && !read_stdin
2214 && (read_buffer
2215 || lseek(fd, (off_t)0L, SEEK_SET) == 0))
2216 {
2217 fileformat = EOL_UNIX;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002218 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002219 set_fileformat(EOL_UNIX, OPT_LOCAL);
2220 file_rewind = TRUE;
2221 keep_fileformat = TRUE;
2222 goto retry;
2223 }
2224 ff_error = EOL_DOS;
2225 }
2226 }
2227 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2228 {
2229 error = TRUE;
2230 break;
2231 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002232#ifdef FEAT_PERSISTENT_UNDO
2233 if (read_undo_file)
2234 sha256_update(&sha_ctx, line_start, len);
2235#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002236 ++lnum;
2237 if (--read_count == 0)
2238 {
2239 error = TRUE; /* break loop */
2240 line_start = ptr; /* nothing left to write */
2241 break;
2242 }
2243 }
2244 else
2245 --skip_count;
2246 line_start = ptr + 1;
2247 }
2248 }
2249 }
2250 linerest = (long)(ptr - line_start);
2251 ui_breakcheck();
2252 }
2253
2254failed:
2255 /* not an error, max. number of lines reached */
2256 if (error && read_count == 0)
2257 error = FALSE;
2258
2259 /*
2260 * If we get EOF in the middle of a line, note the fact and
2261 * complete the line ourselves.
2262 * In Dos format ignore a trailing CTRL-Z, unless 'binary' set.
2263 */
2264 if (!error
2265 && !got_int
2266 && linerest != 0
2267 && !(!curbuf->b_p_bin
2268 && fileformat == EOL_DOS
2269 && *line_start == Ctrl_Z
2270 && ptr == line_start + 1))
2271 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002272 /* remember for when writing */
2273 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002274 curbuf->b_p_eol = FALSE;
2275 *ptr = NUL;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002276 len = (colnr_T)(ptr - line_start + 1);
2277 if (ml_append(lnum, line_start, len, newfile) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002278 error = TRUE;
2279 else
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002280 {
2281#ifdef FEAT_PERSISTENT_UNDO
2282 if (read_undo_file)
2283 sha256_update(&sha_ctx, line_start, len);
2284#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002285 read_no_eol_lnum = ++lnum;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002286 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002287 }
2288
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002289 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002290 save_file_ff(curbuf); /* remember the current file format */
2291
2292#ifdef FEAT_CRYPT
Bram Moolenaar4cf35c22011-02-25 16:52:17 +01002293 crypt_method_used = use_crypt_method;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002294 if (cryptkey != NULL)
2295 {
2296 crypt_pop_state();
2297 if (cryptkey != curbuf->b_p_key)
2298 free_crypt_key(cryptkey);
2299 /* don't set cryptkey to NULL, it's used below as a flag that
2300 * encryption was used */
2301 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002302#endif
2303
2304#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002305 /* If editing a new file: set 'fenc' for the current buffer.
2306 * Also for ":read ++edit file". */
2307 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002308 set_string_option_direct((char_u *)"fenc", -1, fenc,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00002309 OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002310 if (fenc_alloced)
2311 vim_free(fenc);
2312# ifdef USE_ICONV
2313 if (iconv_fd != (iconv_t)-1)
2314 {
2315 iconv_close(iconv_fd);
2316 iconv_fd = (iconv_t)-1;
2317 }
2318# endif
2319#endif
2320
2321 if (!read_buffer && !read_stdin)
2322 close(fd); /* errors are ignored */
Bram Moolenaarf05da212009-11-17 16:13:15 +00002323#ifdef HAVE_FD_CLOEXEC
2324 else
2325 {
2326 int fdflags = fcntl(fd, F_GETFD);
2327 if (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0)
2328 fcntl(fd, F_SETFD, fdflags | FD_CLOEXEC);
2329 }
2330#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002331 vim_free(buffer);
2332
2333#ifdef HAVE_DUP
2334 if (read_stdin)
2335 {
2336 /* Use stderr for stdin, makes shell commands work. */
2337 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00002338 ignored = dup(2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002339 }
2340#endif
2341
2342#ifdef FEAT_MBYTE
2343 if (tmpname != NULL)
2344 {
2345 mch_remove(tmpname); /* delete converted file */
2346 vim_free(tmpname);
2347 }
2348#endif
2349 --no_wait_return; /* may wait for return now */
2350
2351 /*
2352 * In recovery mode everything but autocommands is skipped.
2353 */
2354 if (!recoverymode)
2355 {
2356 /* need to delete the last line, which comes from the empty buffer */
2357 if (newfile && wasempty && !(curbuf->b_ml.ml_flags & ML_EMPTY))
2358 {
2359#ifdef FEAT_NETBEANS_INTG
2360 netbeansFireChanges = 0;
2361#endif
2362 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
2363#ifdef FEAT_NETBEANS_INTG
2364 netbeansFireChanges = 1;
2365#endif
2366 --linecnt;
2367 }
2368 linecnt = curbuf->b_ml.ml_line_count - linecnt;
2369 if (filesize == 0)
2370 linecnt = 0;
2371 if (newfile || read_buffer)
Bram Moolenaar7263a772007-05-10 17:35:54 +00002372 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002373 redraw_curbuf_later(NOT_VALID);
Bram Moolenaar7263a772007-05-10 17:35:54 +00002374#ifdef FEAT_DIFF
2375 /* After reading the text into the buffer the diff info needs to
2376 * be updated. */
2377 diff_invalidate(curbuf);
2378#endif
2379#ifdef FEAT_FOLDING
2380 /* All folds in the window are invalid now. Mark them for update
2381 * before triggering autocommands. */
2382 foldUpdateAll(curwin);
2383#endif
2384 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002385 else if (linecnt) /* appended at least one line */
2386 appended_lines_mark(from, linecnt);
2387
Bram Moolenaar071d4272004-06-13 20:20:40 +00002388#ifndef ALWAYS_USE_GUI
2389 /*
2390 * If we were reading from the same terminal as where messages go,
2391 * the screen will have been messed up.
2392 * Switch on raw mode now and clear the screen.
2393 */
2394 if (read_stdin)
2395 {
2396 settmode(TMODE_RAW); /* set to raw mode */
2397 starttermcap();
2398 screenclear();
2399 }
2400#endif
2401
2402 if (got_int)
2403 {
2404 if (!(flags & READ_DUMMY))
2405 {
2406 filemess(curbuf, sfname, (char_u *)_(e_interr), 0);
2407 if (newfile)
2408 curbuf->b_p_ro = TRUE; /* must use "w!" now */
2409 }
2410 msg_scroll = msg_save;
2411#ifdef FEAT_VIMINFO
2412 check_marks_read();
2413#endif
2414 return OK; /* an interrupt isn't really an error */
2415 }
2416
2417 if (!filtering && !(flags & READ_DUMMY))
2418 {
2419 msg_add_fname(curbuf, sfname); /* fname in IObuff with quotes */
2420 c = FALSE;
2421
2422#ifdef UNIX
2423# ifdef S_ISFIFO
2424 if (S_ISFIFO(perm)) /* fifo or socket */
2425 {
2426 STRCAT(IObuff, _("[fifo/socket]"));
2427 c = TRUE;
2428 }
2429# else
2430# ifdef S_IFIFO
2431 if ((perm & S_IFMT) == S_IFIFO) /* fifo */
2432 {
2433 STRCAT(IObuff, _("[fifo]"));
2434 c = TRUE;
2435 }
2436# endif
2437# ifdef S_IFSOCK
2438 if ((perm & S_IFMT) == S_IFSOCK) /* or socket */
2439 {
2440 STRCAT(IObuff, _("[socket]"));
2441 c = TRUE;
2442 }
2443# endif
2444# endif
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002445# ifdef OPEN_CHR_FILES
2446 if (S_ISCHR(perm)) /* or character special */
2447 {
2448 STRCAT(IObuff, _("[character special]"));
2449 c = TRUE;
2450 }
2451# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002452#endif
2453 if (curbuf->b_p_ro)
2454 {
2455 STRCAT(IObuff, shortmess(SHM_RO) ? _("[RO]") : _("[readonly]"));
2456 c = TRUE;
2457 }
2458 if (read_no_eol_lnum)
2459 {
2460 msg_add_eol();
2461 c = TRUE;
2462 }
2463 if (ff_error == EOL_DOS)
2464 {
2465 STRCAT(IObuff, _("[CR missing]"));
2466 c = TRUE;
2467 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002468 if (split)
2469 {
2470 STRCAT(IObuff, _("[long lines split]"));
2471 c = TRUE;
2472 }
2473#ifdef FEAT_MBYTE
2474 if (notconverted)
2475 {
2476 STRCAT(IObuff, _("[NOT converted]"));
2477 c = TRUE;
2478 }
2479 else if (converted)
2480 {
2481 STRCAT(IObuff, _("[converted]"));
2482 c = TRUE;
2483 }
2484#endif
2485#ifdef FEAT_CRYPT
2486 if (cryptkey != NULL)
2487 {
Bram Moolenaar4cf35c22011-02-25 16:52:17 +01002488 if (crypt_method_used == 1)
2489 STRCAT(IObuff, _("[blowfish]"));
2490 else
2491 STRCAT(IObuff, _("[crypted]"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002492 c = TRUE;
2493 }
2494#endif
2495#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002496 if (conv_error != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002497 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002498 sprintf((char *)IObuff + STRLEN(IObuff),
2499 _("[CONVERSION ERROR in line %ld]"), (long)conv_error);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002500 c = TRUE;
2501 }
2502 else if (illegal_byte > 0)
2503 {
2504 sprintf((char *)IObuff + STRLEN(IObuff),
2505 _("[ILLEGAL BYTE in line %ld]"), (long)illegal_byte);
2506 c = TRUE;
2507 }
2508 else
2509#endif
2510 if (error)
2511 {
2512 STRCAT(IObuff, _("[READ ERRORS]"));
2513 c = TRUE;
2514 }
2515 if (msg_add_fileformat(fileformat))
2516 c = TRUE;
2517#ifdef FEAT_CRYPT
2518 if (cryptkey != NULL)
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002519 msg_add_lines(c, (long)linecnt, filesize
Bram Moolenaar80794b12010-06-13 05:20:42 +02002520 - CRYPT_MAGIC_LEN
2521 - crypt_salt_len[use_crypt_method]
2522 - crypt_seed_len[use_crypt_method]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002523 else
2524#endif
2525 msg_add_lines(c, (long)linecnt, filesize);
2526
2527 vim_free(keep_msg);
2528 keep_msg = NULL;
2529 msg_scrolled_ign = TRUE;
2530#ifdef ALWAYS_USE_GUI
2531 /* Don't show the message when reading stdin, it would end up in a
2532 * message box (which might be shown when exiting!) */
2533 if (read_stdin || read_buffer)
2534 p = msg_may_trunc(FALSE, IObuff);
2535 else
2536#endif
2537 p = msg_trunc_attr(IObuff, FALSE, 0);
2538 if (read_stdin || read_buffer || restart_edit != 0
Bram Moolenaar1c7715d2005-10-03 22:02:18 +00002539 || (msg_scrolled != 0 && !need_wait_return))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002540 /* Need to repeat the message after redrawing when:
2541 * - When reading from stdin (the screen will be cleared next).
2542 * - When restart_edit is set (otherwise there will be a delay
2543 * before redrawing).
2544 * - When the screen was scrolled but there is no wait-return
2545 * prompt. */
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002546 set_keep_msg(p, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002547 msg_scrolled_ign = FALSE;
2548 }
2549
2550 /* with errors writing the file requires ":w!" */
2551 if (newfile && (error
2552#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002553 || conv_error != 0
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002554 || (illegal_byte > 0 && bad_char_behavior != BAD_KEEP)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002555#endif
2556 ))
2557 curbuf->b_p_ro = TRUE;
2558
2559 u_clearline(); /* cannot use "U" command after adding lines */
2560
2561 /*
2562 * In Ex mode: cursor at last new line.
2563 * Otherwise: cursor at first new line.
2564 */
2565 if (exmode_active)
2566 curwin->w_cursor.lnum = from + linecnt;
2567 else
2568 curwin->w_cursor.lnum = from + 1;
2569 check_cursor_lnum();
2570 beginline(BL_WHITE | BL_FIX); /* on first non-blank */
2571
2572 /*
2573 * Set '[ and '] marks to the newly read lines.
2574 */
2575 curbuf->b_op_start.lnum = from + 1;
2576 curbuf->b_op_start.col = 0;
2577 curbuf->b_op_end.lnum = from + linecnt;
2578 curbuf->b_op_end.col = 0;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002579
2580#ifdef WIN32
2581 /*
2582 * Work around a weird problem: When a file has two links (only
2583 * possible on NTFS) and we write through one link, then stat() it
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00002584 * through the other link, the timestamp information may be wrong.
Bram Moolenaar03f48552006-02-28 23:52:23 +00002585 * It's correct again after reading the file, thus reset the timestamp
2586 * here.
2587 */
2588 if (newfile && !read_stdin && !read_buffer
2589 && mch_stat((char *)fname, &st) >= 0)
2590 {
2591 buf_store_time(curbuf, &st, fname);
2592 curbuf->b_mtime_read = curbuf->b_mtime;
2593 }
2594#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002595 }
2596 msg_scroll = msg_save;
2597
2598#ifdef FEAT_VIMINFO
2599 /*
2600 * Get the marks before executing autocommands, so they can be used there.
2601 */
2602 check_marks_read();
2603#endif
2604
Bram Moolenaar071d4272004-06-13 20:20:40 +00002605 /*
2606 * Trick: We remember if the last line of the read didn't have
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002607 * an eol even when 'binary' is off, for when writing it again with
2608 * 'binary' on. This is required for
Bram Moolenaar071d4272004-06-13 20:20:40 +00002609 * ":autocmd FileReadPost *.gz set bin|'[,']!gunzip" to work.
2610 */
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002611 curbuf->b_no_eol_lnum = read_no_eol_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002612
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02002613 /* When reloading a buffer put the cursor at the first line that is
2614 * different. */
2615 if (flags & READ_KEEP_UNDO)
2616 u_find_first_changed();
2617
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002618#ifdef FEAT_PERSISTENT_UNDO
2619 /*
2620 * When opening a new file locate undo info and read it.
2621 */
2622 if (read_undo_file)
2623 {
2624 char_u hash[UNDO_HASH_SIZE];
2625
2626 sha256_finish(&sha_ctx, hash);
Bram Moolenaar6ed8ed82010-05-30 20:40:11 +02002627 u_read_undo(NULL, hash, fname);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002628 }
2629#endif
2630
Bram Moolenaardf177f62005-02-22 08:39:57 +00002631#ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00002632 if (!read_stdin && !read_buffer)
2633 {
2634 int m = msg_scroll;
2635 int n = msg_scrolled;
2636
2637 /* Save the fileformat now, otherwise the buffer will be considered
2638 * modified if the format/encoding was automatically detected. */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002639 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002640 save_file_ff(curbuf);
2641
2642 /*
2643 * The output from the autocommands should not overwrite anything and
2644 * should not be overwritten: Set msg_scroll, restore its value if no
2645 * output was done.
2646 */
2647 msg_scroll = TRUE;
2648 if (filtering)
2649 apply_autocmds_exarg(EVENT_FILTERREADPOST, NULL, sfname,
2650 FALSE, curbuf, eap);
2651 else if (newfile)
2652 apply_autocmds_exarg(EVENT_BUFREADPOST, NULL, sfname,
2653 FALSE, curbuf, eap);
2654 else
2655 apply_autocmds_exarg(EVENT_FILEREADPOST, sfname, sfname,
2656 FALSE, NULL, eap);
2657 if (msg_scrolled == n)
2658 msg_scroll = m;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002659# ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002660 if (aborting()) /* autocmds may abort script processing */
2661 return FAIL;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002662# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002663 }
2664#endif
2665
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002666 /* Reset now, following writes should not omit the EOL. Also, the line
2667 * number will become invalid because of edits. */
2668 curbuf->b_no_eol_lnum = 0;
2669
Bram Moolenaar071d4272004-06-13 20:20:40 +00002670 if (recoverymode && error)
2671 return FAIL;
2672 return OK;
2673}
2674
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002675#ifdef OPEN_CHR_FILES
2676/*
2677 * Returns TRUE if the file name argument is of the form "/dev/fd/\d\+",
2678 * which is the name of files used for process substitution output by
2679 * some shells on some operating systems, e.g., bash on SunOS.
2680 * Do not accept "/dev/fd/[012]", opening these may hang Vim.
2681 */
2682 static int
2683is_dev_fd_file(fname)
2684 char_u *fname;
2685{
2686 return (STRNCMP(fname, "/dev/fd/", 8) == 0
2687 && VIM_ISDIGIT(fname[8])
2688 && *skipdigits(fname + 9) == NUL
2689 && (fname[9] != NUL
2690 || (fname[8] != '0' && fname[8] != '1' && fname[8] != '2')));
2691}
2692#endif
2693
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002694#ifdef FEAT_MBYTE
2695
2696/*
2697 * From the current line count and characters read after that, estimate the
2698 * line number where we are now.
2699 * Used for error messages that include a line number.
2700 */
2701 static linenr_T
2702readfile_linenr(linecnt, p, endp)
2703 linenr_T linecnt; /* line count before reading more bytes */
2704 char_u *p; /* start of more bytes read */
2705 char_u *endp; /* end of more bytes read */
2706{
2707 char_u *s;
2708 linenr_T lnum;
2709
2710 lnum = curbuf->b_ml.ml_line_count - linecnt + 1;
2711 for (s = p; s < endp; ++s)
2712 if (*s == '\n')
2713 ++lnum;
2714 return lnum;
2715}
2716#endif
2717
Bram Moolenaar071d4272004-06-13 20:20:40 +00002718/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00002719 * Fill "*eap" to force the 'fileencoding', 'fileformat' and 'binary to be
2720 * equal to the buffer "buf". Used for calling readfile().
Bram Moolenaar071d4272004-06-13 20:20:40 +00002721 * Returns OK or FAIL.
2722 */
2723 int
2724prep_exarg(eap, buf)
2725 exarg_T *eap;
2726 buf_T *buf;
2727{
2728 eap->cmd = alloc((unsigned)(STRLEN(buf->b_p_ff)
2729#ifdef FEAT_MBYTE
2730 + STRLEN(buf->b_p_fenc)
2731#endif
2732 + 15));
2733 if (eap->cmd == NULL)
2734 return FAIL;
2735
2736#ifdef FEAT_MBYTE
2737 sprintf((char *)eap->cmd, "e ++ff=%s ++enc=%s", buf->b_p_ff, buf->b_p_fenc);
2738 eap->force_enc = 14 + (int)STRLEN(buf->b_p_ff);
Bram Moolenaar195d6352005-12-19 22:08:24 +00002739 eap->bad_char = buf->b_bad_char;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002740#else
2741 sprintf((char *)eap->cmd, "e ++ff=%s", buf->b_p_ff);
2742#endif
2743 eap->force_ff = 7;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002744
2745 eap->force_bin = buf->b_p_bin ? FORCE_BIN : FORCE_NOBIN;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002746 eap->read_edit = FALSE;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002747 eap->forceit = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002748 return OK;
2749}
2750
2751#ifdef FEAT_MBYTE
2752/*
2753 * Find next fileencoding to use from 'fileencodings'.
2754 * "pp" points to fenc_next. It's advanced to the next item.
2755 * When there are no more items, an empty string is returned and *pp is set to
2756 * NULL.
2757 * When *pp is not set to NULL, the result is in allocated memory.
2758 */
2759 static char_u *
2760next_fenc(pp)
2761 char_u **pp;
2762{
2763 char_u *p;
2764 char_u *r;
2765
2766 if (**pp == NUL)
2767 {
2768 *pp = NULL;
2769 return (char_u *)"";
2770 }
2771 p = vim_strchr(*pp, ',');
2772 if (p == NULL)
2773 {
2774 r = enc_canonize(*pp);
2775 *pp += STRLEN(*pp);
2776 }
2777 else
2778 {
2779 r = vim_strnsave(*pp, (int)(p - *pp));
2780 *pp = p + 1;
2781 if (r != NULL)
2782 {
2783 p = enc_canonize(r);
2784 vim_free(r);
2785 r = p;
2786 }
2787 }
2788 if (r == NULL) /* out of memory */
2789 {
2790 r = (char_u *)"";
2791 *pp = NULL;
2792 }
2793 return r;
2794}
2795
2796# ifdef FEAT_EVAL
2797/*
2798 * Convert a file with the 'charconvert' expression.
2799 * This closes the file which is to be read, converts it and opens the
2800 * resulting file for reading.
2801 * Returns name of the resulting converted file (the caller should delete it
2802 * after reading it).
2803 * Returns NULL if the conversion failed ("*fdp" is not set) .
2804 */
2805 static char_u *
2806readfile_charconvert(fname, fenc, fdp)
2807 char_u *fname; /* name of input file */
2808 char_u *fenc; /* converted from */
2809 int *fdp; /* in/out: file descriptor of file */
2810{
2811 char_u *tmpname;
2812 char_u *errmsg = NULL;
2813
2814 tmpname = vim_tempname('r');
2815 if (tmpname == NULL)
2816 errmsg = (char_u *)_("Can't find temp file for conversion");
2817 else
2818 {
2819 close(*fdp); /* close the input file, ignore errors */
2820 *fdp = -1;
2821 if (eval_charconvert(fenc, enc_utf8 ? (char_u *)"utf-8" : p_enc,
2822 fname, tmpname) == FAIL)
2823 errmsg = (char_u *)_("Conversion with 'charconvert' failed");
2824 if (errmsg == NULL && (*fdp = mch_open((char *)tmpname,
2825 O_RDONLY | O_EXTRA, 0)) < 0)
2826 errmsg = (char_u *)_("can't read output of 'charconvert'");
2827 }
2828
2829 if (errmsg != NULL)
2830 {
2831 /* Don't use emsg(), it breaks mappings, the retry with
2832 * another type of conversion might still work. */
2833 MSG(errmsg);
2834 if (tmpname != NULL)
2835 {
2836 mch_remove(tmpname); /* delete converted file */
2837 vim_free(tmpname);
2838 tmpname = NULL;
2839 }
2840 }
2841
2842 /* If the input file is closed, open it (caller should check for error). */
2843 if (*fdp < 0)
2844 *fdp = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
2845
2846 return tmpname;
2847}
2848# endif
2849
2850#endif
2851
2852#ifdef FEAT_VIMINFO
2853/*
2854 * Read marks for the current buffer from the viminfo file, when we support
2855 * buffer marks and the buffer has a name.
2856 */
2857 static void
2858check_marks_read()
2859{
2860 if (!curbuf->b_marks_read && get_viminfo_parameter('\'') > 0
2861 && curbuf->b_ffname != NULL)
Bram Moolenaard812df62008-11-09 12:46:09 +00002862 read_viminfo(NULL, VIF_WANT_MARKS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002863
2864 /* Always set b_marks_read; needed when 'viminfo' is changed to include
2865 * the ' parameter after opening a buffer. */
2866 curbuf->b_marks_read = TRUE;
2867}
2868#endif
2869
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002870#if defined(FEAT_CRYPT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002871/*
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002872 * Get the crypt method used for a file from "ptr[len]", the magic text at the
2873 * start of the file.
2874 * Returns -1 when no encryption used.
2875 */
2876 static int
Bram Moolenaar49771f42010-07-20 17:32:38 +02002877crypt_method_from_magic(ptr, len)
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002878 char *ptr;
2879 int len;
2880{
2881 int i;
2882
2883 for (i = 0; i < (int)(sizeof(crypt_magic) / sizeof(crypt_magic[0])); i++)
2884 {
Bram Moolenaar80794b12010-06-13 05:20:42 +02002885 if (len < (CRYPT_MAGIC_LEN + crypt_salt_len[i] + crypt_seed_len[i]))
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002886 continue;
2887 if (memcmp(ptr, crypt_magic[i], CRYPT_MAGIC_LEN) == 0)
2888 return i;
2889 }
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002890
Bram Moolenaar442b4222010-05-24 21:34:22 +02002891 i = (int)STRLEN(crypt_magic_head);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002892 if (len >= i && memcmp(ptr, crypt_magic_head, i) == 0)
2893 EMSG(_("E821: File is encrypted with unknown method"));
2894
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002895 return -1;
2896}
2897
2898/*
2899 * Check for magic number used for encryption. Applies to the current buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002900 * If found, the magic number is removed from ptr[*sizep] and *sizep and
2901 * *filesizep are updated.
2902 * Return the (new) encryption key, NULL for no encryption.
2903 */
2904 static char_u *
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002905check_for_cryptkey(cryptkey, ptr, sizep, filesizep, newfile, fname, did_ask)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002906 char_u *cryptkey; /* previous encryption key or NULL */
2907 char_u *ptr; /* pointer to read bytes */
2908 long *sizep; /* length of read bytes */
Bram Moolenaar914703b2010-05-31 21:59:46 +02002909 off_t *filesizep; /* nr of bytes used from file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002910 int newfile; /* editing a new buffer */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002911 char_u *fname; /* file name to display */
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002912 int *did_ask; /* flag: whether already asked for key */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002913{
Bram Moolenaar49771f42010-07-20 17:32:38 +02002914 int method = crypt_method_from_magic((char *)ptr, *sizep);
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002915
2916 if (method >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002917 {
Bram Moolenaar49771f42010-07-20 17:32:38 +02002918 set_crypt_method(curbuf, method);
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002919 if (method > 0)
2920 (void)blowfish_self_test();
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002921 if (cryptkey == NULL && !*did_ask)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002922 {
2923 if (*curbuf->b_p_key)
2924 cryptkey = curbuf->b_p_key;
2925 else
2926 {
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002927 /* When newfile is TRUE, store the typed key in the 'key'
2928 * option and don't free it. bf needs hash of the key saved.
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002929 * Don't ask for the key again when first time Enter was hit.
2930 * Happens when retrying to detect encoding. */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002931 smsg((char_u *)_(need_key_msg), fname);
2932 msg_scroll = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002933 cryptkey = get_crypt_key(newfile, FALSE);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002934 *did_ask = TRUE;
2935
Bram Moolenaar071d4272004-06-13 20:20:40 +00002936 /* check if empty key entered */
2937 if (cryptkey != NULL && *cryptkey == NUL)
2938 {
2939 if (cryptkey != curbuf->b_p_key)
2940 vim_free(cryptkey);
2941 cryptkey = NULL;
2942 }
2943 }
2944 }
2945
2946 if (cryptkey != NULL)
2947 {
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002948 int seed_len = crypt_seed_len[method];
Bram Moolenaar80794b12010-06-13 05:20:42 +02002949 int salt_len = crypt_salt_len[method];
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002950
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002951 crypt_push_state();
2952 use_crypt_method = method;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002953 if (method == 0)
2954 crypt_init_keys(cryptkey);
2955 else
2956 {
Bram Moolenaar80794b12010-06-13 05:20:42 +02002957 bf_key_init(cryptkey, ptr + CRYPT_MAGIC_LEN, salt_len);
2958 bf_ofb_init(ptr + CRYPT_MAGIC_LEN + salt_len, seed_len);
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002959 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002960
2961 /* Remove magic number from the text */
Bram Moolenaar80794b12010-06-13 05:20:42 +02002962 *filesizep += CRYPT_MAGIC_LEN + salt_len + seed_len;
2963 *sizep -= CRYPT_MAGIC_LEN + salt_len + seed_len;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002964 mch_memmove(ptr, ptr + CRYPT_MAGIC_LEN + salt_len + seed_len,
2965 (size_t)*sizep);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002966 }
2967 }
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002968 /* When starting to edit a new file which does not have encryption, clear
2969 * the 'key' option, except when starting up (called with -x argument) */
Bram Moolenaarfa0ff9a2010-07-25 16:05:19 +02002970 else if (newfile && *curbuf->b_p_key != NUL && !starting)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002971 set_option_value((char_u *)"key", 0L, (char_u *)"", OPT_LOCAL);
2972
2973 return cryptkey;
2974}
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002975
2976/*
2977 * Check for magic number used for encryption. Applies to the current buffer.
2978 * If found and decryption is possible returns OK;
2979 */
2980 int
2981prepare_crypt_read(fp)
2982 FILE *fp;
2983{
2984 int method;
Bram Moolenaar80794b12010-06-13 05:20:42 +02002985 char_u buffer[CRYPT_MAGIC_LEN + CRYPT_SALT_LEN_MAX
2986 + CRYPT_SEED_LEN_MAX + 2];
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002987
2988 if (fread(buffer, CRYPT_MAGIC_LEN, 1, fp) != 1)
2989 return FAIL;
Bram Moolenaar49771f42010-07-20 17:32:38 +02002990 method = crypt_method_from_magic((char *)buffer,
Bram Moolenaar80794b12010-06-13 05:20:42 +02002991 CRYPT_MAGIC_LEN +
Bram Moolenaarcc448b32010-07-14 16:52:17 +02002992 CRYPT_SEED_LEN_MAX +
2993 CRYPT_SALT_LEN_MAX);
Bram Moolenaar49771f42010-07-20 17:32:38 +02002994 if (method < 0 || method != get_crypt_method(curbuf))
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002995 return FAIL;
2996
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002997 crypt_push_state();
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002998 if (method == 0)
2999 crypt_init_keys(curbuf->b_p_key);
3000 else
3001 {
Bram Moolenaar80794b12010-06-13 05:20:42 +02003002 int salt_len = crypt_salt_len[method];
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003003 int seed_len = crypt_seed_len[method];
3004
Bram Moolenaar80794b12010-06-13 05:20:42 +02003005 if (fread(buffer, salt_len + seed_len, 1, fp) != 1)
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003006 return FAIL;
Bram Moolenaar80794b12010-06-13 05:20:42 +02003007 bf_key_init(curbuf->b_p_key, buffer, salt_len);
3008 bf_ofb_init(buffer + salt_len, seed_len);
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003009 }
3010 return OK;
3011}
3012
3013/*
3014 * Prepare for writing encrypted bytes for buffer "buf".
3015 * Returns a pointer to an allocated header of length "*lenp".
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003016 * When out of memory returns NULL.
3017 * Otherwise calls crypt_push_state(), call crypt_pop_state() later.
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003018 */
3019 char_u *
3020prepare_crypt_write(buf, lenp)
3021 buf_T *buf;
3022 int *lenp;
3023{
3024 char_u *header;
Bram Moolenaar49771f42010-07-20 17:32:38 +02003025 int seed_len = crypt_seed_len[get_crypt_method(buf)];
3026 int salt_len = crypt_salt_len[get_crypt_method(buf)];
Bram Moolenaar80794b12010-06-13 05:20:42 +02003027 char_u *salt;
3028 char_u *seed;
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003029
Bram Moolenaar80794b12010-06-13 05:20:42 +02003030 header = alloc_clear(CRYPT_MAGIC_LEN + CRYPT_SALT_LEN_MAX
3031 + CRYPT_SEED_LEN_MAX + 2);
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003032 if (header != NULL)
3033 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003034 crypt_push_state();
Bram Moolenaar49771f42010-07-20 17:32:38 +02003035 use_crypt_method = get_crypt_method(buf); /* select zip or blowfish */
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003036 vim_strncpy(header, (char_u *)crypt_magic[use_crypt_method],
3037 CRYPT_MAGIC_LEN);
Bram Moolenaar49771f42010-07-20 17:32:38 +02003038 if (use_crypt_method == 0)
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003039 crypt_init_keys(buf->b_p_key);
3040 else
3041 {
Bram Moolenaar80794b12010-06-13 05:20:42 +02003042 /* Using blowfish, add salt and seed. */
3043 salt = header + CRYPT_MAGIC_LEN;
3044 seed = salt + salt_len;
3045 sha2_seed(salt, salt_len, seed, seed_len);
3046 bf_key_init(buf->b_p_key, salt, salt_len);
3047 bf_ofb_init(seed, seed_len);
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003048 }
3049 }
Bram Moolenaar80794b12010-06-13 05:20:42 +02003050 *lenp = CRYPT_MAGIC_LEN + salt_len + seed_len;
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003051 return header;
3052}
3053
Bram Moolenaar80794b12010-06-13 05:20:42 +02003054#endif /* FEAT_CRYPT */
3055
Bram Moolenaar071d4272004-06-13 20:20:40 +00003056#ifdef UNIX
3057 static void
3058set_file_time(fname, atime, mtime)
3059 char_u *fname;
3060 time_t atime; /* access time */
3061 time_t mtime; /* modification time */
3062{
3063# if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
3064 struct utimbuf buf;
3065
3066 buf.actime = atime;
3067 buf.modtime = mtime;
3068 (void)utime((char *)fname, &buf);
3069# else
3070# if defined(HAVE_UTIMES)
3071 struct timeval tvp[2];
3072
3073 tvp[0].tv_sec = atime;
3074 tvp[0].tv_usec = 0;
3075 tvp[1].tv_sec = mtime;
3076 tvp[1].tv_usec = 0;
3077# ifdef NeXT
3078 (void)utimes((char *)fname, tvp);
3079# else
3080 (void)utimes((char *)fname, (const struct timeval *)&tvp);
3081# endif
3082# endif
3083# endif
3084}
3085#endif /* UNIX */
3086
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003087#if defined(VMS) && !defined(MIN)
3088/* Older DECC compiler for VAX doesn't define MIN() */
3089# define MIN(a, b) ((a) < (b) ? (a) : (b))
3090#endif
3091
Bram Moolenaar071d4272004-06-13 20:20:40 +00003092/*
Bram Moolenaar5386a122007-06-28 20:02:32 +00003093 * Return TRUE if a file appears to be read-only from the file permissions.
3094 */
3095 int
3096check_file_readonly(fname, perm)
3097 char_u *fname; /* full path to file */
3098 int perm; /* known permissions on file */
3099{
3100#ifndef USE_MCH_ACCESS
3101 int fd = 0;
3102#endif
3103
3104 return (
3105#ifdef USE_MCH_ACCESS
3106# ifdef UNIX
3107 (perm & 0222) == 0 ||
3108# endif
3109 mch_access((char *)fname, W_OK)
3110#else
3111 (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0
3112 ? TRUE : (close(fd), FALSE)
3113#endif
3114 );
3115}
3116
3117
3118/*
Bram Moolenaar292ad192005-12-11 21:29:51 +00003119 * buf_write() - write to file "fname" lines "start" through "end"
Bram Moolenaar071d4272004-06-13 20:20:40 +00003120 *
3121 * We do our own buffering here because fwrite() is so slow.
3122 *
Bram Moolenaar292ad192005-12-11 21:29:51 +00003123 * If "forceit" is true, we don't care for errors when attempting backups.
3124 * In case of an error everything possible is done to restore the original
Bram Moolenaare37d50a2008-08-06 17:06:04 +00003125 * file. But when "forceit" is TRUE, we risk losing it.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003126 *
3127 * When "reset_changed" is TRUE and "append" == FALSE and "start" == 1 and
3128 * "end" == curbuf->b_ml.ml_line_count, reset curbuf->b_changed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003129 *
3130 * This function must NOT use NameBuff (because it's called by autowrite()).
3131 *
3132 * return FAIL for failure, OK otherwise
3133 */
3134 int
3135buf_write(buf, fname, sfname, start, end, eap, append, forceit,
3136 reset_changed, filtering)
3137 buf_T *buf;
3138 char_u *fname;
3139 char_u *sfname;
3140 linenr_T start, end;
3141 exarg_T *eap; /* for forced 'ff' and 'fenc', can be
3142 NULL! */
Bram Moolenaar292ad192005-12-11 21:29:51 +00003143 int append; /* append to the file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003144 int forceit;
3145 int reset_changed;
3146 int filtering;
3147{
3148 int fd;
3149 char_u *backup = NULL;
3150 int backup_copy = FALSE; /* copy the original file? */
3151 int dobackup;
3152 char_u *ffname;
3153 char_u *wfname = NULL; /* name of file to write to */
3154 char_u *s;
3155 char_u *ptr;
3156 char_u c;
3157 int len;
3158 linenr_T lnum;
3159 long nchars;
3160 char_u *errmsg = NULL;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003161 int errmsg_allocated = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003162 char_u *errnum = NULL;
3163 char_u *buffer;
3164 char_u smallbuf[SMBUFSIZE];
3165 char_u *backup_ext;
3166 int bufsize;
3167 long perm; /* file permissions */
3168 int retval = OK;
3169 int newfile = FALSE; /* TRUE if file doesn't exist yet */
3170 int msg_save = msg_scroll;
3171 int overwriting; /* TRUE if writing over original */
3172 int no_eol = FALSE; /* no end-of-line written */
3173 int device = FALSE; /* writing to a device */
3174 struct stat st_old;
3175 int prev_got_int = got_int;
3176 int file_readonly = FALSE; /* overwritten file is read-only */
3177 static char *err_readonly = "is read-only (cannot override: \"W\" in 'cpoptions')";
3178#if defined(UNIX) || defined(__EMX__XX) /*XXX fix me sometime? */
3179 int made_writable = FALSE; /* 'w' bit has been set */
3180#endif
3181 /* writing everything */
3182 int whole = (start == 1 && end == buf->b_ml.ml_line_count);
3183#ifdef FEAT_AUTOCMD
3184 linenr_T old_line_count = buf->b_ml.ml_line_count;
3185#endif
3186 int attr;
3187 int fileformat;
3188 int write_bin;
3189 struct bw_info write_info; /* info for buf_write_bytes() */
3190#ifdef FEAT_MBYTE
3191 int converted = FALSE;
3192 int notconverted = FALSE;
3193 char_u *fenc; /* effective 'fileencoding' */
3194 char_u *fenc_tofree = NULL; /* allocated "fenc" */
3195#endif
3196#ifdef HAS_BW_FLAGS
3197 int wb_flags = 0;
3198#endif
3199#ifdef HAVE_ACL
3200 vim_acl_T acl = NULL; /* ACL copied from original file to
3201 backup or new file */
3202#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003203#ifdef FEAT_PERSISTENT_UNDO
3204 int write_undo_file = FALSE;
3205 context_sha256_T sha_ctx;
3206#endif
Bram Moolenaar4cf35c22011-02-25 16:52:17 +01003207#ifdef FEAT_CRYPT
3208 int crypt_method_used;
3209#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003210
3211 if (fname == NULL || *fname == NUL) /* safety check */
3212 return FAIL;
Bram Moolenaar70d60e92009-12-31 13:53:33 +00003213 if (buf->b_ml.ml_mfp == NULL)
3214 {
3215 /* This can happen during startup when there is a stray "w" in the
3216 * vimrc file. */
3217 EMSG(_(e_emptybuf));
3218 return FAIL;
3219 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003220
3221 /*
3222 * Disallow writing from .exrc and .vimrc in current directory for
3223 * security reasons.
3224 */
3225 if (check_secure())
3226 return FAIL;
3227
3228 /* Avoid a crash for a long name. */
3229 if (STRLEN(fname) >= MAXPATHL)
3230 {
3231 EMSG(_(e_longname));
3232 return FAIL;
3233 }
3234
3235#ifdef FEAT_MBYTE
3236 /* must init bw_conv_buf and bw_iconv_fd before jumping to "fail" */
3237 write_info.bw_conv_buf = NULL;
3238 write_info.bw_conv_error = FALSE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003239 write_info.bw_conv_error_lnum = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003240 write_info.bw_restlen = 0;
3241# ifdef USE_ICONV
3242 write_info.bw_iconv_fd = (iconv_t)-1;
3243# endif
3244#endif
3245
Bram Moolenaardf177f62005-02-22 08:39:57 +00003246 /* After writing a file changedtick changes but we don't want to display
3247 * the line. */
3248 ex_no_reprint = TRUE;
3249
Bram Moolenaar071d4272004-06-13 20:20:40 +00003250 /*
3251 * If there is no file name yet, use the one for the written file.
3252 * BF_NOTEDITED is set to reflect this (in case the write fails).
3253 * Don't do this when the write is for a filter command.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003254 * Don't do this when appending.
3255 * Only do this when 'cpoptions' contains the 'F' flag.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003256 */
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003257 if (buf->b_ffname == NULL
3258 && reset_changed
Bram Moolenaar071d4272004-06-13 20:20:40 +00003259 && whole
3260 && buf == curbuf
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00003261#ifdef FEAT_QUICKFIX
3262 && !bt_nofile(buf)
3263#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003264 && !filtering
Bram Moolenaar292ad192005-12-11 21:29:51 +00003265 && (!append || vim_strchr(p_cpo, CPO_FNAMEAPP) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003266 && vim_strchr(p_cpo, CPO_FNAMEW) != NULL)
3267 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003268 if (set_rw_fname(fname, sfname) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003269 return FAIL;
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003270 buf = curbuf; /* just in case autocmds made "buf" invalid */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003271 }
3272
3273 if (sfname == NULL)
3274 sfname = fname;
3275 /*
3276 * For Unix: Use the short file name whenever possible.
3277 * Avoids problems with networks and when directory names are changed.
3278 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
3279 * another directory, which we don't detect
3280 */
3281 ffname = fname; /* remember full fname */
3282#ifdef UNIX
3283 fname = sfname;
3284#endif
3285
3286 if (buf->b_ffname != NULL && fnamecmp(ffname, buf->b_ffname) == 0)
3287 overwriting = TRUE;
3288 else
3289 overwriting = FALSE;
3290
3291 if (exiting)
3292 settmode(TMODE_COOK); /* when exiting allow typahead now */
3293
3294 ++no_wait_return; /* don't wait for return yet */
3295
3296 /*
3297 * Set '[ and '] marks to the lines to be written.
3298 */
3299 buf->b_op_start.lnum = start;
3300 buf->b_op_start.col = 0;
3301 buf->b_op_end.lnum = end;
3302 buf->b_op_end.col = 0;
3303
3304#ifdef FEAT_AUTOCMD
3305 {
3306 aco_save_T aco;
3307 int buf_ffname = FALSE;
3308 int buf_sfname = FALSE;
3309 int buf_fname_f = FALSE;
3310 int buf_fname_s = FALSE;
3311 int did_cmd = FALSE;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003312 int nofile_err = FALSE;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003313 int empty_memline = (buf->b_ml.ml_mfp == NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003314
3315 /*
3316 * Apply PRE aucocommands.
3317 * Set curbuf to the buffer to be written.
3318 * Careful: The autocommands may call buf_write() recursively!
3319 */
3320 if (ffname == buf->b_ffname)
3321 buf_ffname = TRUE;
3322 if (sfname == buf->b_sfname)
3323 buf_sfname = TRUE;
3324 if (fname == buf->b_ffname)
3325 buf_fname_f = TRUE;
3326 if (fname == buf->b_sfname)
3327 buf_fname_s = TRUE;
3328
3329 /* set curwin/curbuf to buf and save a few things */
3330 aucmd_prepbuf(&aco, buf);
3331
3332 if (append)
3333 {
3334 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD,
3335 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003336 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003337#ifdef FEAT_QUICKFIX
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00003338 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003339 nofile_err = TRUE;
3340 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003341#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003342 apply_autocmds_exarg(EVENT_FILEAPPENDPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003343 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003344 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003345 }
3346 else if (filtering)
3347 {
3348 apply_autocmds_exarg(EVENT_FILTERWRITEPRE,
3349 NULL, sfname, FALSE, curbuf, eap);
3350 }
3351 else if (reset_changed && whole)
3352 {
3353 if (!(did_cmd = apply_autocmds_exarg(EVENT_BUFWRITECMD,
3354 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003355 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003356#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003357 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003358 nofile_err = TRUE;
3359 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003360#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003361 apply_autocmds_exarg(EVENT_BUFWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003362 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003363 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003364 }
3365 else
3366 {
3367 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD,
3368 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003369 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003370#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003371 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003372 nofile_err = TRUE;
3373 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003374#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003375 apply_autocmds_exarg(EVENT_FILEWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003376 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003377 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003378 }
3379
3380 /* restore curwin/curbuf and a few other things */
3381 aucmd_restbuf(&aco);
3382
3383 /*
3384 * In three situations we return here and don't write the file:
3385 * 1. the autocommands deleted or unloaded the buffer.
3386 * 2. The autocommands abort script processing.
3387 * 3. If one of the "Cmd" autocommands was executed.
3388 */
3389 if (!buf_valid(buf))
3390 buf = NULL;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003391 if (buf == NULL || (buf->b_ml.ml_mfp == NULL && !empty_memline)
Bram Moolenaar1e015462005-09-25 22:16:38 +00003392 || did_cmd || nofile_err
3393#ifdef FEAT_EVAL
3394 || aborting()
3395#endif
3396 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003397 {
3398 --no_wait_return;
3399 msg_scroll = msg_save;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003400 if (nofile_err)
3401 EMSG(_("E676: No matching autocommands for acwrite buffer"));
3402
Bram Moolenaar1e015462005-09-25 22:16:38 +00003403 if (nofile_err
3404#ifdef FEAT_EVAL
3405 || aborting()
3406#endif
3407 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003408 /* An aborting error, interrupt or exception in the
3409 * autocommands. */
3410 return FAIL;
3411 if (did_cmd)
3412 {
3413 if (buf == NULL)
3414 /* The buffer was deleted. We assume it was written
3415 * (can't retry anyway). */
3416 return OK;
3417 if (overwriting)
3418 {
3419 /* Assume the buffer was written, update the timestamp. */
3420 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00003421 if (append)
3422 buf->b_flags &= ~BF_NEW;
3423 else
3424 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003425 }
Bram Moolenaar292ad192005-12-11 21:29:51 +00003426 if (reset_changed && buf->b_changed && !append
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003427 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003428 /* Buffer still changed, the autocommands didn't work
3429 * properly. */
3430 return FAIL;
3431 return OK;
3432 }
3433#ifdef FEAT_EVAL
3434 if (!aborting())
3435#endif
3436 EMSG(_("E203: Autocommands deleted or unloaded buffer to be written"));
3437 return FAIL;
3438 }
3439
3440 /*
3441 * The autocommands may have changed the number of lines in the file.
3442 * When writing the whole file, adjust the end.
3443 * When writing part of the file, assume that the autocommands only
3444 * changed the number of lines that are to be written (tricky!).
3445 */
3446 if (buf->b_ml.ml_line_count != old_line_count)
3447 {
3448 if (whole) /* write all */
3449 end = buf->b_ml.ml_line_count;
3450 else if (buf->b_ml.ml_line_count > old_line_count) /* more lines */
3451 end += buf->b_ml.ml_line_count - old_line_count;
3452 else /* less lines */
3453 {
3454 end -= old_line_count - buf->b_ml.ml_line_count;
3455 if (end < start)
3456 {
3457 --no_wait_return;
3458 msg_scroll = msg_save;
3459 EMSG(_("E204: Autocommand changed number of lines in unexpected way"));
3460 return FAIL;
3461 }
3462 }
3463 }
3464
3465 /*
3466 * The autocommands may have changed the name of the buffer, which may
3467 * be kept in fname, ffname and sfname.
3468 */
3469 if (buf_ffname)
3470 ffname = buf->b_ffname;
3471 if (buf_sfname)
3472 sfname = buf->b_sfname;
3473 if (buf_fname_f)
3474 fname = buf->b_ffname;
3475 if (buf_fname_s)
3476 fname = buf->b_sfname;
3477 }
3478#endif
3479
3480#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003481 if (netbeans_active() && isNetbeansBuffer(buf))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003482 {
3483 if (whole)
3484 {
3485 /*
3486 * b_changed can be 0 after an undo, but we still need to write
3487 * the buffer to NetBeans.
3488 */
3489 if (buf->b_changed || isNetbeansModified(buf))
3490 {
Bram Moolenaar009b2592004-10-24 19:18:58 +00003491 --no_wait_return; /* may wait for return now */
3492 msg_scroll = msg_save;
3493 netbeans_save_buffer(buf); /* no error checking... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003494 return retval;
3495 }
3496 else
3497 {
3498 errnum = (char_u *)"E656: ";
Bram Moolenaared0e7452008-06-27 19:17:34 +00003499 errmsg = (char_u *)_("NetBeans disallows writes of unmodified buffers");
Bram Moolenaar071d4272004-06-13 20:20:40 +00003500 buffer = NULL;
3501 goto fail;
3502 }
3503 }
3504 else
3505 {
3506 errnum = (char_u *)"E657: ";
3507 errmsg = (char_u *)_("Partial writes disallowed for NetBeans buffers");
3508 buffer = NULL;
3509 goto fail;
3510 }
3511 }
3512#endif
3513
3514 if (shortmess(SHM_OVER) && !exiting)
3515 msg_scroll = FALSE; /* overwrite previous file message */
3516 else
3517 msg_scroll = TRUE; /* don't overwrite previous file message */
3518 if (!filtering)
3519 filemess(buf,
3520#ifndef UNIX
3521 sfname,
3522#else
3523 fname,
3524#endif
3525 (char_u *)"", 0); /* show that we are busy */
3526 msg_scroll = FALSE; /* always overwrite the file message now */
3527
3528 buffer = alloc(BUFSIZE);
3529 if (buffer == NULL) /* can't allocate big buffer, use small
3530 * one (to be able to write when out of
3531 * memory) */
3532 {
3533 buffer = smallbuf;
3534 bufsize = SMBUFSIZE;
3535 }
3536 else
3537 bufsize = BUFSIZE;
3538
3539 /*
3540 * Get information about original file (if there is one).
3541 */
3542#if defined(UNIX) && !defined(ARCHIE)
Bram Moolenaar6f192452007-11-08 19:49:02 +00003543 st_old.st_dev = 0;
3544 st_old.st_ino = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003545 perm = -1;
3546 if (mch_stat((char *)fname, &st_old) < 0)
3547 newfile = TRUE;
3548 else
3549 {
3550 perm = st_old.st_mode;
3551 if (!S_ISREG(st_old.st_mode)) /* not a file */
3552 {
3553 if (S_ISDIR(st_old.st_mode))
3554 {
3555 errnum = (char_u *)"E502: ";
3556 errmsg = (char_u *)_("is a directory");
3557 goto fail;
3558 }
3559 if (mch_nodetype(fname) != NODE_WRITABLE)
3560 {
3561 errnum = (char_u *)"E503: ";
3562 errmsg = (char_u *)_("is not a file or writable device");
3563 goto fail;
3564 }
3565 /* It's a device of some kind (or a fifo) which we can write to
3566 * but for which we can't make a backup. */
3567 device = TRUE;
3568 newfile = TRUE;
3569 perm = -1;
3570 }
3571 }
3572#else /* !UNIX */
3573 /*
3574 * Check for a writable device name.
3575 */
3576 c = mch_nodetype(fname);
3577 if (c == NODE_OTHER)
3578 {
3579 errnum = (char_u *)"E503: ";
3580 errmsg = (char_u *)_("is not a file or writable device");
3581 goto fail;
3582 }
3583 if (c == NODE_WRITABLE)
3584 {
Bram Moolenaar043545e2006-10-10 16:44:07 +00003585# if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3586 /* MS-Windows allows opening a device, but we will probably get stuck
3587 * trying to write to it. */
3588 if (!p_odev)
3589 {
3590 errnum = (char_u *)"E796: ";
3591 errmsg = (char_u *)_("writing to device disabled with 'opendevice' option");
3592 goto fail;
3593 }
3594# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003595 device = TRUE;
3596 newfile = TRUE;
3597 perm = -1;
3598 }
3599 else
3600 {
3601 perm = mch_getperm(fname);
3602 if (perm < 0)
3603 newfile = TRUE;
3604 else if (mch_isdir(fname))
3605 {
3606 errnum = (char_u *)"E502: ";
3607 errmsg = (char_u *)_("is a directory");
3608 goto fail;
3609 }
3610 if (overwriting)
3611 (void)mch_stat((char *)fname, &st_old);
3612 }
3613#endif /* !UNIX */
3614
3615 if (!device && !newfile)
3616 {
3617 /*
3618 * Check if the file is really writable (when renaming the file to
3619 * make a backup we won't discover it later).
3620 */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003621 file_readonly = check_file_readonly(fname, (int)perm);
3622
Bram Moolenaar071d4272004-06-13 20:20:40 +00003623 if (!forceit && file_readonly)
3624 {
3625 if (vim_strchr(p_cpo, CPO_FWRITE) != NULL)
3626 {
3627 errnum = (char_u *)"E504: ";
3628 errmsg = (char_u *)_(err_readonly);
3629 }
3630 else
3631 {
3632 errnum = (char_u *)"E505: ";
3633 errmsg = (char_u *)_("is read-only (add ! to override)");
3634 }
3635 goto fail;
3636 }
3637
3638 /*
3639 * Check if the timestamp hasn't changed since reading the file.
3640 */
3641 if (overwriting)
3642 {
3643 retval = check_mtime(buf, &st_old);
3644 if (retval == FAIL)
3645 goto fail;
3646 }
3647 }
3648
3649#ifdef HAVE_ACL
3650 /*
3651 * For systems that support ACL: get the ACL from the original file.
3652 */
3653 if (!newfile)
3654 acl = mch_get_acl(fname);
3655#endif
3656
3657 /*
3658 * If 'backupskip' is not empty, don't make a backup for some files.
3659 */
3660 dobackup = (p_wb || p_bk || *p_pm != NUL);
3661#ifdef FEAT_WILDIGN
3662 if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname))
3663 dobackup = FALSE;
3664#endif
3665
3666 /*
3667 * Save the value of got_int and reset it. We don't want a previous
3668 * interruption cancel writing, only hitting CTRL-C while writing should
3669 * abort it.
3670 */
3671 prev_got_int = got_int;
3672 got_int = FALSE;
3673
3674 /* Mark the buffer as 'being saved' to prevent changed buffer warnings */
3675 buf->b_saving = TRUE;
3676
3677 /*
3678 * If we are not appending or filtering, the file exists, and the
3679 * 'writebackup', 'backup' or 'patchmode' option is set, need a backup.
3680 * When 'patchmode' is set also make a backup when appending.
3681 *
3682 * Do not make any backup, if 'writebackup' and 'backup' are both switched
3683 * off. This helps when editing large files on almost-full disks.
3684 */
3685 if (!(append && *p_pm == NUL) && !filtering && perm >= 0 && dobackup)
3686 {
3687#if defined(UNIX) || defined(WIN32)
3688 struct stat st;
3689#endif
3690
3691 if ((bkc_flags & BKC_YES) || append) /* "yes" */
3692 backup_copy = TRUE;
3693#if defined(UNIX) || defined(WIN32)
3694 else if ((bkc_flags & BKC_AUTO)) /* "auto" */
3695 {
3696 int i;
3697
3698# ifdef UNIX
3699 /*
3700 * Don't rename the file when:
3701 * - it's a hard link
3702 * - it's a symbolic link
3703 * - we don't have write permission in the directory
3704 * - we can't set the owner/group of the new file
3705 */
3706 if (st_old.st_nlink > 1
3707 || mch_lstat((char *)fname, &st) < 0
3708 || st.st_dev != st_old.st_dev
Bram Moolenaara5792f52005-11-23 21:25:05 +00003709 || st.st_ino != st_old.st_ino
3710# ifndef HAVE_FCHOWN
3711 || st.st_uid != st_old.st_uid
3712 || st.st_gid != st_old.st_gid
3713# endif
3714 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003715 backup_copy = TRUE;
3716 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003717# else
3718# ifdef WIN32
3719 /* On NTFS file systems hard links are possible. */
3720 if (mch_is_linked(fname))
3721 backup_copy = TRUE;
3722 else
3723# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003724# endif
3725 {
3726 /*
3727 * Check if we can create a file and set the owner/group to
3728 * the ones from the original file.
3729 * First find a file name that doesn't exist yet (use some
3730 * arbitrary numbers).
3731 */
3732 STRCPY(IObuff, fname);
3733 for (i = 4913; ; i += 123)
3734 {
3735 sprintf((char *)gettail(IObuff), "%d", i);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003736 if (mch_lstat((char *)IObuff, &st) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003737 break;
3738 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00003739 fd = mch_open((char *)IObuff,
3740 O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003741 if (fd < 0) /* can't write in directory */
3742 backup_copy = TRUE;
3743 else
3744 {
3745# ifdef UNIX
Bram Moolenaara5792f52005-11-23 21:25:05 +00003746# ifdef HAVE_FCHOWN
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00003747 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003748# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003749 if (mch_stat((char *)IObuff, &st) < 0
3750 || st.st_uid != st_old.st_uid
3751 || st.st_gid != st_old.st_gid
Bram Moolenaar78a15312009-05-15 19:33:18 +00003752 || (long)st.st_mode != perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003753 backup_copy = TRUE;
3754# endif
Bram Moolenaar98358622005-11-28 22:58:23 +00003755 /* Close the file before removing it, on MS-Windows we
3756 * can't delete an open file. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003757 close(fd);
Bram Moolenaar98358622005-11-28 22:58:23 +00003758 mch_remove(IObuff);
Bram Moolenaar3479c5d2010-08-08 18:46:06 +02003759# ifdef MSWIN
3760 /* MS-Windows may trigger a virus scanner to open the
3761 * file, we can't delete it then. Keep trying for half a
3762 * second. */
3763 {
3764 int try;
3765
3766 for (try = 0; try < 10; ++try)
3767 {
3768 if (mch_lstat((char *)IObuff, &st) < 0)
3769 break;
3770 ui_delay(50L, TRUE); /* wait 50 msec */
3771 mch_remove(IObuff);
3772 }
3773 }
3774# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003775 }
3776 }
3777 }
3778
3779# ifdef UNIX
3780 /*
3781 * Break symlinks and/or hardlinks if we've been asked to.
3782 */
3783 if ((bkc_flags & BKC_BREAKSYMLINK) || (bkc_flags & BKC_BREAKHARDLINK))
3784 {
3785 int lstat_res;
3786
3787 lstat_res = mch_lstat((char *)fname, &st);
3788
3789 /* Symlinks. */
3790 if ((bkc_flags & BKC_BREAKSYMLINK)
3791 && lstat_res == 0
3792 && st.st_ino != st_old.st_ino)
3793 backup_copy = FALSE;
3794
3795 /* Hardlinks. */
3796 if ((bkc_flags & BKC_BREAKHARDLINK)
3797 && st_old.st_nlink > 1
3798 && (lstat_res != 0 || st.st_ino == st_old.st_ino))
3799 backup_copy = FALSE;
3800 }
3801#endif
3802
3803#endif
3804
3805 /* make sure we have a valid backup extension to use */
3806 if (*p_bex == NUL)
3807 {
3808#ifdef RISCOS
3809 backup_ext = (char_u *)"/bak";
3810#else
3811 backup_ext = (char_u *)".bak";
3812#endif
3813 }
3814 else
3815 backup_ext = p_bex;
3816
3817 if (backup_copy
3818 && (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) >= 0)
3819 {
3820 int bfd;
3821 char_u *copybuf, *wp;
3822 int some_error = FALSE;
3823 struct stat st_new;
3824 char_u *dirp;
3825 char_u *rootname;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003826#if defined(UNIX) && !defined(SHORT_FNAME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003827 int did_set_shortname;
3828#endif
3829
3830 copybuf = alloc(BUFSIZE + 1);
3831 if (copybuf == NULL)
3832 {
3833 some_error = TRUE; /* out of memory */
3834 goto nobackup;
3835 }
3836
3837 /*
3838 * Try to make the backup in each directory in the 'bdir' option.
3839 *
3840 * Unix semantics has it, that we may have a writable file,
3841 * that cannot be recreated with a simple open(..., O_CREAT, ) e.g:
3842 * - the directory is not writable,
3843 * - the file may be a symbolic link,
3844 * - the file may belong to another user/group, etc.
3845 *
3846 * For these reasons, the existing writable file must be truncated
3847 * and reused. Creation of a backup COPY will be attempted.
3848 */
3849 dirp = p_bdir;
3850 while (*dirp)
3851 {
3852#ifdef UNIX
3853 st_new.st_ino = 0;
3854 st_new.st_dev = 0;
3855 st_new.st_gid = 0;
3856#endif
3857
3858 /*
3859 * Isolate one directory name, using an entry in 'bdir'.
3860 */
3861 (void)copy_option_part(&dirp, copybuf, BUFSIZE, ",");
3862 rootname = get_file_in_dir(fname, copybuf);
3863 if (rootname == NULL)
3864 {
3865 some_error = TRUE; /* out of memory */
3866 goto nobackup;
3867 }
3868
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003869#if defined(UNIX) && !defined(SHORT_FNAME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003870 did_set_shortname = FALSE;
3871#endif
3872
3873 /*
3874 * May try twice if 'shortname' not set.
3875 */
3876 for (;;)
3877 {
3878 /*
3879 * Make backup file name.
3880 */
3881 backup = buf_modname(
3882#ifdef SHORT_FNAME
3883 TRUE,
3884#else
3885 (buf->b_p_sn || buf->b_shortname),
3886#endif
3887 rootname, backup_ext, FALSE);
3888 if (backup == NULL)
3889 {
3890 vim_free(rootname);
3891 some_error = TRUE; /* out of memory */
3892 goto nobackup;
3893 }
3894
3895 /*
3896 * Check if backup file already exists.
3897 */
3898 if (mch_stat((char *)backup, &st_new) >= 0)
3899 {
3900#ifdef UNIX
3901 /*
3902 * Check if backup file is same as original file.
3903 * May happen when modname() gave the same file back.
3904 * E.g. silly link, or file name-length reached.
3905 * If we don't check here, we either ruin the file
3906 * when copying or erase it after writing. jw.
3907 */
3908 if (st_new.st_dev == st_old.st_dev
3909 && st_new.st_ino == st_old.st_ino)
3910 {
3911 vim_free(backup);
3912 backup = NULL; /* no backup file to delete */
3913# ifndef SHORT_FNAME
3914 /*
3915 * may try again with 'shortname' set
3916 */
3917 if (!(buf->b_shortname || buf->b_p_sn))
3918 {
3919 buf->b_shortname = TRUE;
3920 did_set_shortname = TRUE;
3921 continue;
3922 }
3923 /* setting shortname didn't help */
3924 if (did_set_shortname)
3925 buf->b_shortname = FALSE;
3926# endif
3927 break;
3928 }
3929#endif
3930
3931 /*
3932 * If we are not going to keep the backup file, don't
3933 * delete an existing one, try to use another name.
3934 * Change one character, just before the extension.
3935 */
3936 if (!p_bk)
3937 {
3938 wp = backup + STRLEN(backup) - 1
3939 - STRLEN(backup_ext);
3940 if (wp < backup) /* empty file name ??? */
3941 wp = backup;
3942 *wp = 'z';
3943 while (*wp > 'a'
3944 && mch_stat((char *)backup, &st_new) >= 0)
3945 --*wp;
3946 /* They all exist??? Must be something wrong. */
3947 if (*wp == 'a')
3948 {
3949 vim_free(backup);
3950 backup = NULL;
3951 }
3952 }
3953 }
3954 break;
3955 }
3956 vim_free(rootname);
3957
3958 /*
3959 * Try to create the backup file
3960 */
3961 if (backup != NULL)
3962 {
3963 /* remove old backup, if present */
3964 mch_remove(backup);
3965 /* Open with O_EXCL to avoid the file being created while
3966 * we were sleeping (symlink hacker attack?) */
3967 bfd = mch_open((char *)backup,
Bram Moolenaara5792f52005-11-23 21:25:05 +00003968 O_WRONLY|O_CREAT|O_EXTRA|O_EXCL|O_NOFOLLOW,
3969 perm & 0777);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003970 if (bfd < 0)
3971 {
3972 vim_free(backup);
3973 backup = NULL;
3974 }
3975 else
3976 {
3977 /* set file protection same as original file, but
3978 * strip s-bit */
3979 (void)mch_setperm(backup, perm & 0777);
3980
3981#ifdef UNIX
3982 /*
3983 * Try to set the group of the backup same as the
3984 * original file. If this fails, set the protection
3985 * bits for the group same as the protection bits for
3986 * others.
3987 */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003988 if (st_new.st_gid != st_old.st_gid
Bram Moolenaar071d4272004-06-13 20:20:40 +00003989# ifdef HAVE_FCHOWN /* sequent-ptx lacks fchown() */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003990 && fchown(bfd, (uid_t)-1, st_old.st_gid) != 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00003991# endif
3992 )
3993 mch_setperm(backup,
3994 (perm & 0707) | ((perm & 07) << 3));
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00003995# ifdef HAVE_SELINUX
3996 mch_copy_sec(fname, backup);
3997# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003998#endif
3999
4000 /*
4001 * copy the file.
4002 */
4003 write_info.bw_fd = bfd;
4004 write_info.bw_buf = copybuf;
4005#ifdef HAS_BW_FLAGS
4006 write_info.bw_flags = FIO_NOCONVERT;
4007#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004008 while ((write_info.bw_len = read_eintr(fd, copybuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004009 BUFSIZE)) > 0)
4010 {
4011 if (buf_write_bytes(&write_info) == FAIL)
4012 {
4013 errmsg = (char_u *)_("E506: Can't write to backup file (add ! to override)");
4014 break;
4015 }
4016 ui_breakcheck();
4017 if (got_int)
4018 {
4019 errmsg = (char_u *)_(e_interr);
4020 break;
4021 }
4022 }
4023
4024 if (close(bfd) < 0 && errmsg == NULL)
4025 errmsg = (char_u *)_("E507: Close error for backup file (add ! to override)");
4026 if (write_info.bw_len < 0)
4027 errmsg = (char_u *)_("E508: Can't read file for backup (add ! to override)");
4028#ifdef UNIX
4029 set_file_time(backup, st_old.st_atime, st_old.st_mtime);
4030#endif
4031#ifdef HAVE_ACL
4032 mch_set_acl(backup, acl);
4033#endif
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004034#ifdef HAVE_SELINUX
4035 mch_copy_sec(fname, backup);
4036#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004037 break;
4038 }
4039 }
4040 }
4041 nobackup:
4042 close(fd); /* ignore errors for closing read file */
4043 vim_free(copybuf);
4044
4045 if (backup == NULL && errmsg == NULL)
4046 errmsg = (char_u *)_("E509: Cannot create backup file (add ! to override)");
4047 /* ignore errors when forceit is TRUE */
4048 if ((some_error || errmsg != NULL) && !forceit)
4049 {
4050 retval = FAIL;
4051 goto fail;
4052 }
4053 errmsg = NULL;
4054 }
4055 else
4056 {
4057 char_u *dirp;
4058 char_u *p;
4059 char_u *rootname;
4060
4061 /*
4062 * Make a backup by renaming the original file.
4063 */
4064 /*
4065 * If 'cpoptions' includes the "W" flag, we don't want to
4066 * overwrite a read-only file. But rename may be possible
4067 * anyway, thus we need an extra check here.
4068 */
4069 if (file_readonly && vim_strchr(p_cpo, CPO_FWRITE) != NULL)
4070 {
4071 errnum = (char_u *)"E504: ";
4072 errmsg = (char_u *)_(err_readonly);
4073 goto fail;
4074 }
4075
4076 /*
4077 *
4078 * Form the backup file name - change path/fo.o.h to
4079 * path/fo.o.h.bak Try all directories in 'backupdir', first one
4080 * that works is used.
4081 */
4082 dirp = p_bdir;
4083 while (*dirp)
4084 {
4085 /*
4086 * Isolate one directory name and make the backup file name.
4087 */
4088 (void)copy_option_part(&dirp, IObuff, IOSIZE, ",");
4089 rootname = get_file_in_dir(fname, IObuff);
4090 if (rootname == NULL)
4091 backup = NULL;
4092 else
4093 {
4094 backup = buf_modname(
4095#ifdef SHORT_FNAME
4096 TRUE,
4097#else
4098 (buf->b_p_sn || buf->b_shortname),
4099#endif
4100 rootname, backup_ext, FALSE);
4101 vim_free(rootname);
4102 }
4103
4104 if (backup != NULL)
4105 {
4106 /*
4107 * If we are not going to keep the backup file, don't
4108 * delete an existing one, try to use another name.
4109 * Change one character, just before the extension.
4110 */
4111 if (!p_bk && mch_getperm(backup) >= 0)
4112 {
4113 p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext);
4114 if (p < backup) /* empty file name ??? */
4115 p = backup;
4116 *p = 'z';
4117 while (*p > 'a' && mch_getperm(backup) >= 0)
4118 --*p;
4119 /* They all exist??? Must be something wrong! */
4120 if (*p == 'a')
4121 {
4122 vim_free(backup);
4123 backup = NULL;
4124 }
4125 }
4126 }
4127 if (backup != NULL)
4128 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004129 /*
Bram Moolenaarbfd8fc02005-09-20 23:22:24 +00004130 * Delete any existing backup and move the current version
4131 * to the backup. For safety, we don't remove the backup
4132 * until the write has finished successfully. And if the
4133 * 'backup' option is set, leave it around.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004134 */
4135 /*
4136 * If the renaming of the original file to the backup file
4137 * works, quit here.
4138 */
4139 if (vim_rename(fname, backup) == 0)
4140 break;
4141
4142 vim_free(backup); /* don't do the rename below */
4143 backup = NULL;
4144 }
4145 }
4146 if (backup == NULL && !forceit)
4147 {
4148 errmsg = (char_u *)_("E510: Can't make backup file (add ! to override)");
4149 goto fail;
4150 }
4151 }
4152 }
4153
4154#if defined(UNIX) && !defined(ARCHIE)
4155 /* When using ":w!" and the file was read-only: make it writable */
4156 if (forceit && perm >= 0 && !(perm & 0200) && st_old.st_uid == getuid()
4157 && vim_strchr(p_cpo, CPO_FWRITE) == NULL)
4158 {
4159 perm |= 0200;
4160 (void)mch_setperm(fname, perm);
4161 made_writable = TRUE;
4162 }
4163#endif
4164
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004165 /* When using ":w!" and writing to the current file, 'readonly' makes no
Bram Moolenaar4399ef42005-02-12 14:29:27 +00004166 * sense, reset it, unless 'Z' appears in 'cpoptions'. */
4167 if (forceit && overwriting && vim_strchr(p_cpo, CPO_KEEPRO) == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004168 {
4169 buf->b_p_ro = FALSE;
4170#ifdef FEAT_TITLE
4171 need_maketitle = TRUE; /* set window title later */
4172#endif
4173#ifdef FEAT_WINDOWS
4174 status_redraw_all(); /* redraw status lines later */
4175#endif
4176 }
4177
4178 if (end > buf->b_ml.ml_line_count)
4179 end = buf->b_ml.ml_line_count;
4180 if (buf->b_ml.ml_flags & ML_EMPTY)
4181 start = end + 1;
4182
4183 /*
4184 * If the original file is being overwritten, there is a small chance that
4185 * we crash in the middle of writing. Therefore the file is preserved now.
4186 * This makes all block numbers positive so that recovery does not need
4187 * the original file.
4188 * Don't do this if there is a backup file and we are exiting.
4189 */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004190 if (reset_changed && !newfile && overwriting
Bram Moolenaar071d4272004-06-13 20:20:40 +00004191 && !(exiting && backup != NULL))
4192 {
4193 ml_preserve(buf, FALSE);
4194 if (got_int)
4195 {
4196 errmsg = (char_u *)_(e_interr);
4197 goto restore_backup;
4198 }
4199 }
4200
4201#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
4202 /*
4203 * Before risking to lose the original file verify if there's
4204 * a resource fork to preserve, and if cannot be done warn
4205 * the users. This happens when overwriting without backups.
4206 */
4207 if (backup == NULL && overwriting && !append)
4208 if (mch_has_resource_fork(fname))
4209 {
4210 errmsg = (char_u *)_("E460: The resource fork would be lost (add ! to override)");
4211 goto restore_backup;
4212 }
4213#endif
4214
4215#ifdef VMS
4216 vms_remove_version(fname); /* remove version */
4217#endif
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00004218 /* Default: write the file directly. May write to a temp file for
Bram Moolenaar071d4272004-06-13 20:20:40 +00004219 * multi-byte conversion. */
4220 wfname = fname;
4221
4222#ifdef FEAT_MBYTE
4223 /* Check for forced 'fileencoding' from "++opt=val" argument. */
4224 if (eap != NULL && eap->force_enc != 0)
4225 {
4226 fenc = eap->cmd + eap->force_enc;
4227 fenc = enc_canonize(fenc);
4228 fenc_tofree = fenc;
4229 }
4230 else
4231 fenc = buf->b_p_fenc;
4232
4233 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004234 * Check if the file needs to be converted.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004235 */
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004236 converted = need_conversion(fenc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004237
4238 /*
4239 * Check if UTF-8 to UCS-2/4 or Latin1 conversion needs to be done. Or
4240 * Latin1 to Unicode conversion. This is handled in buf_write_bytes().
4241 * Prepare the flags for it and allocate bw_conv_buf when needed.
4242 */
4243 if (converted && (enc_utf8 || STRCMP(p_enc, "latin1") == 0))
4244 {
4245 wb_flags = get_fio_flags(fenc);
4246 if (wb_flags & (FIO_UCS2 | FIO_UCS4 | FIO_UTF16 | FIO_UTF8))
4247 {
4248 /* Need to allocate a buffer to translate into. */
4249 if (wb_flags & (FIO_UCS2 | FIO_UTF16 | FIO_UTF8))
4250 write_info.bw_conv_buflen = bufsize * 2;
4251 else /* FIO_UCS4 */
4252 write_info.bw_conv_buflen = bufsize * 4;
4253 write_info.bw_conv_buf
4254 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4255 if (write_info.bw_conv_buf == NULL)
4256 end = 0;
4257 }
4258 }
4259
4260# ifdef WIN3264
4261 if (converted && wb_flags == 0 && (wb_flags = get_win_fio_flags(fenc)) != 0)
4262 {
4263 /* Convert UTF-8 -> UCS-2 and UCS-2 -> DBCS. Worst-case * 4: */
4264 write_info.bw_conv_buflen = bufsize * 4;
4265 write_info.bw_conv_buf
4266 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4267 if (write_info.bw_conv_buf == NULL)
4268 end = 0;
4269 }
4270# endif
4271
4272# ifdef MACOS_X
4273 if (converted && wb_flags == 0 && (wb_flags = get_mac_fio_flags(fenc)) != 0)
4274 {
4275 write_info.bw_conv_buflen = bufsize * 3;
4276 write_info.bw_conv_buf
4277 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4278 if (write_info.bw_conv_buf == NULL)
4279 end = 0;
4280 }
4281# endif
4282
4283# if defined(FEAT_EVAL) || defined(USE_ICONV)
4284 if (converted && wb_flags == 0)
4285 {
4286# ifdef USE_ICONV
4287 /*
4288 * Use iconv() conversion when conversion is needed and it's not done
4289 * internally.
4290 */
4291 write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc,
4292 enc_utf8 ? (char_u *)"utf-8" : p_enc);
4293 if (write_info.bw_iconv_fd != (iconv_t)-1)
4294 {
4295 /* We're going to use iconv(), allocate a buffer to convert in. */
4296 write_info.bw_conv_buflen = bufsize * ICONV_MULT;
4297 write_info.bw_conv_buf
4298 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4299 if (write_info.bw_conv_buf == NULL)
4300 end = 0;
4301 write_info.bw_first = TRUE;
4302 }
4303# ifdef FEAT_EVAL
4304 else
4305# endif
4306# endif
4307
4308# ifdef FEAT_EVAL
4309 /*
4310 * When the file needs to be converted with 'charconvert' after
4311 * writing, write to a temp file instead and let the conversion
4312 * overwrite the original file.
4313 */
4314 if (*p_ccv != NUL)
4315 {
4316 wfname = vim_tempname('w');
4317 if (wfname == NULL) /* Can't write without a tempfile! */
4318 {
4319 errmsg = (char_u *)_("E214: Can't find temp file for writing");
4320 goto restore_backup;
4321 }
4322 }
4323# endif
4324 }
4325# endif
4326 if (converted && wb_flags == 0
4327# ifdef USE_ICONV
4328 && write_info.bw_iconv_fd == (iconv_t)-1
4329# endif
4330# ifdef FEAT_EVAL
4331 && wfname == fname
4332# endif
4333 )
4334 {
4335 if (!forceit)
4336 {
4337 errmsg = (char_u *)_("E213: Cannot convert (add ! to write without conversion)");
4338 goto restore_backup;
4339 }
4340 notconverted = TRUE;
4341 }
4342#endif
4343
4344 /*
4345 * Open the file "wfname" for writing.
4346 * We may try to open the file twice: If we can't write to the
4347 * file and forceit is TRUE we delete the existing file and try to create
4348 * a new one. If this still fails we may have lost the original file!
4349 * (this may happen when the user reached his quotum for number of files).
4350 * Appending will fail if the file does not exist and forceit is FALSE.
4351 */
4352 while ((fd = mch_open((char *)wfname, O_WRONLY | O_EXTRA | (append
4353 ? (forceit ? (O_APPEND | O_CREAT) : O_APPEND)
4354 : (O_CREAT | O_TRUNC))
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00004355 , perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004356 {
4357 /*
4358 * A forced write will try to create a new file if the old one is
4359 * still readonly. This may also happen when the directory is
4360 * read-only. In that case the mch_remove() will fail.
4361 */
4362 if (errmsg == NULL)
4363 {
4364#ifdef UNIX
4365 struct stat st;
4366
4367 /* Don't delete the file when it's a hard or symbolic link. */
4368 if ((!newfile && st_old.st_nlink > 1)
4369 || (mch_lstat((char *)fname, &st) == 0
4370 && (st.st_dev != st_old.st_dev
4371 || st.st_ino != st_old.st_ino)))
4372 errmsg = (char_u *)_("E166: Can't open linked file for writing");
4373 else
4374#endif
4375 {
4376 errmsg = (char_u *)_("E212: Can't open file for writing");
4377 if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL
4378 && perm >= 0)
4379 {
4380#ifdef UNIX
4381 /* we write to the file, thus it should be marked
4382 writable after all */
4383 if (!(perm & 0200))
4384 made_writable = TRUE;
4385 perm |= 0200;
4386 if (st_old.st_uid != getuid() || st_old.st_gid != getgid())
4387 perm &= 0777;
4388#endif
4389 if (!append) /* don't remove when appending */
4390 mch_remove(wfname);
4391 continue;
4392 }
4393 }
4394 }
4395
4396restore_backup:
4397 {
4398 struct stat st;
4399
4400 /*
4401 * If we failed to open the file, we don't need a backup. Throw it
4402 * away. If we moved or removed the original file try to put the
4403 * backup in its place.
4404 */
4405 if (backup != NULL && wfname == fname)
4406 {
4407 if (backup_copy)
4408 {
4409 /*
4410 * There is a small chance that we removed the original,
4411 * try to move the copy in its place.
4412 * This may not work if the vim_rename() fails.
4413 * In that case we leave the copy around.
4414 */
4415 /* If file does not exist, put the copy in its place */
4416 if (mch_stat((char *)fname, &st) < 0)
4417 vim_rename(backup, fname);
4418 /* if original file does exist throw away the copy */
4419 if (mch_stat((char *)fname, &st) >= 0)
4420 mch_remove(backup);
4421 }
4422 else
4423 {
4424 /* try to put the original file back */
4425 vim_rename(backup, fname);
4426 }
4427 }
4428
4429 /* if original file no longer exists give an extra warning */
4430 if (!newfile && mch_stat((char *)fname, &st) < 0)
4431 end = 0;
4432 }
4433
4434#ifdef FEAT_MBYTE
4435 if (wfname != fname)
4436 vim_free(wfname);
4437#endif
4438 goto fail;
4439 }
4440 errmsg = NULL;
4441
4442#if defined(MACOS_CLASSIC) || defined(WIN3264)
4443 /* TODO: Is it need for MACOS_X? (Dany) */
4444 /*
4445 * On macintosh copy the original files attributes (i.e. the backup)
Bram Moolenaar7263a772007-05-10 17:35:54 +00004446 * This is done in order to preserve the resource fork and the
4447 * Finder attribute (label, comments, custom icons, file creator)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004448 */
4449 if (backup != NULL && overwriting && !append)
4450 {
4451 if (backup_copy)
4452 (void)mch_copy_file_attribute(wfname, backup);
4453 else
4454 (void)mch_copy_file_attribute(backup, wfname);
4455 }
4456
4457 if (!overwriting && !append)
4458 {
4459 if (buf->b_ffname != NULL)
4460 (void)mch_copy_file_attribute(buf->b_ffname, wfname);
Bram Moolenaar7263a772007-05-10 17:35:54 +00004461 /* Should copy resource fork */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004462 }
4463#endif
4464
4465 write_info.bw_fd = fd;
4466
4467#ifdef FEAT_CRYPT
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004468 if (*buf->b_p_key != NUL && !filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004469 {
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02004470 char_u *header;
4471 int header_len;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004472
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02004473 header = prepare_crypt_write(buf, &header_len);
4474 if (header == NULL)
4475 end = 0;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004476 else
4477 {
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02004478 /* Write magic number, so that Vim knows that this file is
4479 * encrypted when reading it again. This also undergoes utf-8 to
4480 * ucs-2/4 conversion when needed. */
4481 write_info.bw_buf = header;
4482 write_info.bw_len = header_len;
4483 write_info.bw_flags = FIO_NOCONVERT;
4484 if (buf_write_bytes(&write_info) == FAIL)
4485 end = 0;
4486 wb_flags |= FIO_ENCRYPTED;
4487 vim_free(header);
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004488 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004489 }
4490#endif
4491
4492 write_info.bw_buf = buffer;
4493 nchars = 0;
4494
4495 /* use "++bin", "++nobin" or 'binary' */
4496 if (eap != NULL && eap->force_bin != 0)
4497 write_bin = (eap->force_bin == FORCE_BIN);
4498 else
4499 write_bin = buf->b_p_bin;
4500
4501#ifdef FEAT_MBYTE
4502 /*
4503 * The BOM is written just after the encryption magic number.
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004504 * Skip it when appending and the file already existed, the BOM only makes
4505 * sense at the start of the file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004506 */
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004507 if (buf->b_p_bomb && !write_bin && (!append || perm < 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004508 {
4509 write_info.bw_len = make_bom(buffer, fenc);
4510 if (write_info.bw_len > 0)
4511 {
4512 /* don't convert, do encryption */
4513 write_info.bw_flags = FIO_NOCONVERT | wb_flags;
4514 if (buf_write_bytes(&write_info) == FAIL)
4515 end = 0;
4516 else
4517 nchars += write_info.bw_len;
4518 }
4519 }
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004520 write_info.bw_start_lnum = start;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004521#endif
4522
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004523#ifdef FEAT_PERSISTENT_UNDO
4524 write_undo_file = (buf->b_p_udf && overwriting && !append
4525 && !filtering && reset_changed);
4526 if (write_undo_file)
4527 /* Prepare for computing the hash value of the text. */
4528 sha256_start(&sha_ctx);
4529#endif
4530
Bram Moolenaar071d4272004-06-13 20:20:40 +00004531 write_info.bw_len = bufsize;
4532#ifdef HAS_BW_FLAGS
4533 write_info.bw_flags = wb_flags;
4534#endif
4535 fileformat = get_fileformat_force(buf, eap);
4536 s = buffer;
4537 len = 0;
4538 for (lnum = start; lnum <= end; ++lnum)
4539 {
4540 /*
4541 * The next while loop is done once for each character written.
4542 * Keep it fast!
4543 */
4544 ptr = ml_get_buf(buf, lnum, FALSE) - 1;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004545#ifdef FEAT_PERSISTENT_UNDO
4546 if (write_undo_file)
Bram Moolenaar442b4222010-05-24 21:34:22 +02004547 sha256_update(&sha_ctx, ptr + 1, (UINT32_T)(STRLEN(ptr + 1) + 1));
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004548#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004549 while ((c = *++ptr) != NUL)
4550 {
4551 if (c == NL)
4552 *s = NUL; /* replace newlines with NULs */
4553 else if (c == CAR && fileformat == EOL_MAC)
4554 *s = NL; /* Mac: replace CRs with NLs */
4555 else
4556 *s = c;
4557 ++s;
4558 if (++len != bufsize)
4559 continue;
4560 if (buf_write_bytes(&write_info) == FAIL)
4561 {
4562 end = 0; /* write error: break loop */
4563 break;
4564 }
4565 nchars += bufsize;
4566 s = buffer;
4567 len = 0;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004568#ifdef FEAT_MBYTE
4569 write_info.bw_start_lnum = lnum;
4570#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004571 }
4572 /* write failed or last line has no EOL: stop here */
4573 if (end == 0
4574 || (lnum == end
4575 && write_bin
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004576 && (lnum == buf->b_no_eol_lnum
Bram Moolenaar071d4272004-06-13 20:20:40 +00004577 || (lnum == buf->b_ml.ml_line_count && !buf->b_p_eol))))
4578 {
4579 ++lnum; /* written the line, count it */
4580 no_eol = TRUE;
4581 break;
4582 }
4583 if (fileformat == EOL_UNIX)
4584 *s++ = NL;
4585 else
4586 {
4587 *s++ = CAR; /* EOL_MAC or EOL_DOS: write CR */
4588 if (fileformat == EOL_DOS) /* write CR-NL */
4589 {
4590 if (++len == bufsize)
4591 {
4592 if (buf_write_bytes(&write_info) == FAIL)
4593 {
4594 end = 0; /* write error: break loop */
4595 break;
4596 }
4597 nchars += bufsize;
4598 s = buffer;
4599 len = 0;
4600 }
4601 *s++ = NL;
4602 }
4603 }
4604 if (++len == bufsize && end)
4605 {
4606 if (buf_write_bytes(&write_info) == FAIL)
4607 {
4608 end = 0; /* write error: break loop */
4609 break;
4610 }
4611 nchars += bufsize;
4612 s = buffer;
4613 len = 0;
4614
4615 ui_breakcheck();
4616 if (got_int)
4617 {
4618 end = 0; /* Interrupted, break loop */
4619 break;
4620 }
4621 }
4622#ifdef VMS
4623 /*
4624 * On VMS there is a problem: newlines get added when writing blocks
4625 * at a time. Fix it by writing a line at a time.
4626 * This is much slower!
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004627 * Explanation: VAX/DECC RTL insists that records in some RMS
4628 * structures end with a newline (carriage return) character, and if
4629 * they don't it adds one.
4630 * With other RMS structures it works perfect without this fix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004631 */
Bram Moolenaarb52e2602007-10-29 21:38:54 +00004632 if (buf->b_fab_rfm == FAB$C_VFC
4633 || ((buf->b_fab_rat & (FAB$M_FTN | FAB$M_CR)) != 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004634 {
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004635 int b2write;
4636
4637 buf->b_fab_mrs = (buf->b_fab_mrs == 0
4638 ? MIN(4096, bufsize)
4639 : MIN(buf->b_fab_mrs, bufsize));
4640
4641 b2write = len;
4642 while (b2write > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004643 {
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004644 write_info.bw_len = MIN(b2write, buf->b_fab_mrs);
4645 if (buf_write_bytes(&write_info) == FAIL)
4646 {
4647 end = 0;
4648 break;
4649 }
4650 b2write -= MIN(b2write, buf->b_fab_mrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004651 }
4652 write_info.bw_len = bufsize;
4653 nchars += len;
4654 s = buffer;
4655 len = 0;
4656 }
4657#endif
4658 }
4659 if (len > 0 && end > 0)
4660 {
4661 write_info.bw_len = len;
4662 if (buf_write_bytes(&write_info) == FAIL)
4663 end = 0; /* write error */
4664 nchars += len;
4665 }
4666
4667#if defined(UNIX) && defined(HAVE_FSYNC)
4668 /* On many journalling file systems there is a bug that causes both the
4669 * original and the backup file to be lost when halting the system right
4670 * after writing the file. That's because only the meta-data is
4671 * journalled. Syncing the file slows down the system, but assures it has
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004672 * been written to disk and we don't lose it.
4673 * For a device do try the fsync() but don't complain if it does not work
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00004674 * (could be a pipe).
4675 * If the 'fsync' option is FALSE, don't fsync(). Useful for laptops. */
4676 if (p_fs && fsync(fd) != 0 && !device)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004677 {
4678 errmsg = (char_u *)_("E667: Fsync failed");
4679 end = 0;
4680 }
4681#endif
4682
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004683#ifdef HAVE_SELINUX
4684 /* Probably need to set the security context. */
4685 if (!backup_copy)
4686 mch_copy_sec(backup, wfname);
4687#endif
4688
Bram Moolenaara5792f52005-11-23 21:25:05 +00004689#ifdef UNIX
4690 /* When creating a new file, set its owner/group to that of the original
4691 * file. Get the new device and inode number. */
4692 if (backup != NULL && !backup_copy)
4693 {
4694# ifdef HAVE_FCHOWN
4695 struct stat st;
4696
4697 /* don't change the owner when it's already OK, some systems remove
4698 * permission or ACL stuff */
4699 if (mch_stat((char *)wfname, &st) < 0
4700 || st.st_uid != st_old.st_uid
4701 || st.st_gid != st_old.st_gid)
4702 {
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004703 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004704 if (perm >= 0) /* set permission again, may have changed */
4705 (void)mch_setperm(wfname, perm);
4706 }
4707# endif
4708 buf_setino(buf);
4709 }
Bram Moolenaarf1726cc2009-05-13 18:48:16 +00004710 else if (!buf->b_dev_valid)
Bram Moolenaar8fa04452005-12-23 22:13:51 +00004711 /* Set the inode when creating a new file. */
4712 buf_setino(buf);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004713#endif
4714
Bram Moolenaar071d4272004-06-13 20:20:40 +00004715 if (close(fd) != 0)
4716 {
4717 errmsg = (char_u *)_("E512: Close failed");
4718 end = 0;
4719 }
4720
4721#ifdef UNIX
4722 if (made_writable)
4723 perm &= ~0200; /* reset 'w' bit for security reasons */
4724#endif
4725 if (perm >= 0) /* set perm. of new file same as old file */
4726 (void)mch_setperm(wfname, perm);
4727#ifdef RISCOS
4728 if (!append && !filtering)
4729 /* Set the filetype after writing the file. */
4730 mch_set_filetype(wfname, buf->b_p_oft);
4731#endif
4732#ifdef HAVE_ACL
4733 /* Probably need to set the ACL before changing the user (can't set the
4734 * ACL on a file the user doesn't own). */
4735 if (!backup_copy)
4736 mch_set_acl(wfname, acl);
4737#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004738#ifdef FEAT_CRYPT
Bram Moolenaar4cf35c22011-02-25 16:52:17 +01004739 crypt_method_used = use_crypt_method;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004740 if (wb_flags & FIO_ENCRYPTED)
4741 crypt_pop_state();
4742#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004743
Bram Moolenaar071d4272004-06-13 20:20:40 +00004744
4745#if defined(FEAT_MBYTE) && defined(FEAT_EVAL)
4746 if (wfname != fname)
4747 {
4748 /*
4749 * The file was written to a temp file, now it needs to be converted
4750 * with 'charconvert' to (overwrite) the output file.
4751 */
4752 if (end != 0)
4753 {
4754 if (eval_charconvert(enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc,
4755 wfname, fname) == FAIL)
4756 {
4757 write_info.bw_conv_error = TRUE;
4758 end = 0;
4759 }
4760 }
4761 mch_remove(wfname);
4762 vim_free(wfname);
4763 }
4764#endif
4765
4766 if (end == 0)
4767 {
4768 if (errmsg == NULL)
4769 {
4770#ifdef FEAT_MBYTE
4771 if (write_info.bw_conv_error)
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004772 {
4773 if (write_info.bw_conv_error_lnum == 0)
4774 errmsg = (char_u *)_("E513: write error, conversion failed (make 'fenc' empty to override)");
4775 else
4776 {
4777 errmsg_allocated = TRUE;
4778 errmsg = alloc(300);
4779 vim_snprintf((char *)errmsg, 300, _("E513: write error, conversion failed in line %ld (make 'fenc' empty to override)"),
4780 (long)write_info.bw_conv_error_lnum);
4781 }
4782 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004783 else
4784#endif
4785 if (got_int)
4786 errmsg = (char_u *)_(e_interr);
4787 else
4788 errmsg = (char_u *)_("E514: write error (file system full?)");
4789 }
4790
4791 /*
4792 * If we have a backup file, try to put it in place of the new file,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004793 * because the new file is probably corrupt. This avoids losing the
Bram Moolenaar071d4272004-06-13 20:20:40 +00004794 * original file when trying to make a backup when writing the file a
4795 * second time.
4796 * When "backup_copy" is set we need to copy the backup over the new
4797 * file. Otherwise rename the backup file.
4798 * If this is OK, don't give the extra warning message.
4799 */
4800 if (backup != NULL)
4801 {
4802 if (backup_copy)
4803 {
4804 /* This may take a while, if we were interrupted let the user
4805 * know we got the message. */
4806 if (got_int)
4807 {
4808 MSG(_(e_interr));
4809 out_flush();
4810 }
4811 if ((fd = mch_open((char *)backup, O_RDONLY | O_EXTRA, 0)) >= 0)
4812 {
4813 if ((write_info.bw_fd = mch_open((char *)fname,
Bram Moolenaar9be038d2005-03-08 22:34:32 +00004814 O_WRONLY | O_CREAT | O_TRUNC | O_EXTRA,
4815 perm & 0777)) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004816 {
4817 /* copy the file. */
4818 write_info.bw_buf = smallbuf;
4819#ifdef HAS_BW_FLAGS
4820 write_info.bw_flags = FIO_NOCONVERT;
4821#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004822 while ((write_info.bw_len = read_eintr(fd, smallbuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004823 SMBUFSIZE)) > 0)
4824 if (buf_write_bytes(&write_info) == FAIL)
4825 break;
4826
4827 if (close(write_info.bw_fd) >= 0
4828 && write_info.bw_len == 0)
4829 end = 1; /* success */
4830 }
4831 close(fd); /* ignore errors for closing read file */
4832 }
4833 }
4834 else
4835 {
4836 if (vim_rename(backup, fname) == 0)
4837 end = 1;
4838 }
4839 }
4840 goto fail;
4841 }
4842
4843 lnum -= start; /* compute number of written lines */
4844 --no_wait_return; /* may wait for return now */
4845
4846#if !(defined(UNIX) || defined(VMS))
4847 fname = sfname; /* use shortname now, for the messages */
4848#endif
4849 if (!filtering)
4850 {
4851 msg_add_fname(buf, fname); /* put fname in IObuff with quotes */
4852 c = FALSE;
4853#ifdef FEAT_MBYTE
4854 if (write_info.bw_conv_error)
4855 {
4856 STRCAT(IObuff, _(" CONVERSION ERROR"));
4857 c = TRUE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004858 if (write_info.bw_conv_error_lnum != 0)
Bram Moolenaara800b422010-06-27 01:15:55 +02004859 vim_snprintf_add((char *)IObuff, IOSIZE, _(" in line %ld;"),
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004860 (long)write_info.bw_conv_error_lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004861 }
4862 else if (notconverted)
4863 {
4864 STRCAT(IObuff, _("[NOT converted]"));
4865 c = TRUE;
4866 }
4867 else if (converted)
4868 {
4869 STRCAT(IObuff, _("[converted]"));
4870 c = TRUE;
4871 }
4872#endif
4873 if (device)
4874 {
4875 STRCAT(IObuff, _("[Device]"));
4876 c = TRUE;
4877 }
4878 else if (newfile)
4879 {
4880 STRCAT(IObuff, shortmess(SHM_NEW) ? _("[New]") : _("[New File]"));
4881 c = TRUE;
4882 }
4883 if (no_eol)
4884 {
4885 msg_add_eol();
4886 c = TRUE;
4887 }
4888 /* may add [unix/dos/mac] */
4889 if (msg_add_fileformat(fileformat))
4890 c = TRUE;
4891#ifdef FEAT_CRYPT
4892 if (wb_flags & FIO_ENCRYPTED)
4893 {
Bram Moolenaar4cf35c22011-02-25 16:52:17 +01004894 if (crypt_method_used == 1)
4895 STRCAT(IObuff, _("[blowfish]"));
4896 else
4897 STRCAT(IObuff, _("[crypted]"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004898 c = TRUE;
4899 }
4900#endif
4901 msg_add_lines(c, (long)lnum, nchars); /* add line/char count */
4902 if (!shortmess(SHM_WRITE))
4903 {
4904 if (append)
4905 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended"));
4906 else
4907 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written"));
4908 }
4909
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00004910 set_keep_msg(msg_trunc_attr(IObuff, FALSE, 0), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004911 }
4912
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004913 /* When written everything correctly: reset 'modified'. Unless not
4914 * writing to the original file and '+' is not in 'cpoptions'. */
Bram Moolenaar292ad192005-12-11 21:29:51 +00004915 if (reset_changed && whole && !append
Bram Moolenaar071d4272004-06-13 20:20:40 +00004916#ifdef FEAT_MBYTE
4917 && !write_info.bw_conv_error
4918#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004919 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL)
4920 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004921 {
4922 unchanged(buf, TRUE);
4923 u_unchanged(buf);
Bram Moolenaar730cde92010-06-27 05:18:54 +02004924 u_update_save_nr(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004925 }
4926
4927 /*
4928 * If written to the current file, update the timestamp of the swap file
4929 * and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
4930 */
4931 if (overwriting)
4932 {
4933 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00004934 if (append)
4935 buf->b_flags &= ~BF_NEW;
4936 else
4937 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004938 }
4939
4940 /*
4941 * If we kept a backup until now, and we are in patch mode, then we make
4942 * the backup file our 'original' file.
4943 */
4944 if (*p_pm && dobackup)
4945 {
4946 char *org = (char *)buf_modname(
4947#ifdef SHORT_FNAME
4948 TRUE,
4949#else
4950 (buf->b_p_sn || buf->b_shortname),
4951#endif
4952 fname, p_pm, FALSE);
4953
4954 if (backup != NULL)
4955 {
4956 struct stat st;
4957
4958 /*
4959 * If the original file does not exist yet
4960 * the current backup file becomes the original file
4961 */
4962 if (org == NULL)
4963 EMSG(_("E205: Patchmode: can't save original file"));
4964 else if (mch_stat(org, &st) < 0)
4965 {
4966 vim_rename(backup, (char_u *)org);
4967 vim_free(backup); /* don't delete the file */
4968 backup = NULL;
4969#ifdef UNIX
4970 set_file_time((char_u *)org, st_old.st_atime, st_old.st_mtime);
4971#endif
4972 }
4973 }
4974 /*
4975 * If there is no backup file, remember that a (new) file was
4976 * created.
4977 */
4978 else
4979 {
4980 int empty_fd;
4981
4982 if (org == NULL
Bram Moolenaara5792f52005-11-23 21:25:05 +00004983 || (empty_fd = mch_open(org,
4984 O_CREAT | O_EXTRA | O_EXCL | O_NOFOLLOW,
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00004985 perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004986 EMSG(_("E206: patchmode: can't touch empty original file"));
4987 else
4988 close(empty_fd);
4989 }
4990 if (org != NULL)
4991 {
4992 mch_setperm((char_u *)org, mch_getperm(fname) & 0777);
4993 vim_free(org);
4994 }
4995 }
4996
4997 /*
4998 * Remove the backup unless 'backup' option is set
4999 */
5000 if (!p_bk && backup != NULL && mch_remove(backup) != 0)
5001 EMSG(_("E207: Can't delete backup file"));
5002
5003#ifdef FEAT_SUN_WORKSHOP
5004 if (usingSunWorkShop)
5005 workshop_file_saved((char *) ffname);
5006#endif
5007
5008 goto nofail;
5009
5010 /*
5011 * Finish up. We get here either after failure or success.
5012 */
5013fail:
5014 --no_wait_return; /* may wait for return now */
5015nofail:
5016
5017 /* Done saving, we accept changed buffer warnings again */
5018 buf->b_saving = FALSE;
5019
5020 vim_free(backup);
5021 if (buffer != smallbuf)
5022 vim_free(buffer);
5023#ifdef FEAT_MBYTE
5024 vim_free(fenc_tofree);
5025 vim_free(write_info.bw_conv_buf);
5026# ifdef USE_ICONV
5027 if (write_info.bw_iconv_fd != (iconv_t)-1)
5028 {
5029 iconv_close(write_info.bw_iconv_fd);
5030 write_info.bw_iconv_fd = (iconv_t)-1;
5031 }
5032# endif
5033#endif
5034#ifdef HAVE_ACL
5035 mch_free_acl(acl);
5036#endif
5037
5038 if (errmsg != NULL)
5039 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005040 int numlen = errnum != NULL ? (int)STRLEN(errnum) : 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005041
5042 attr = hl_attr(HLF_E); /* set highlight for error messages */
5043 msg_add_fname(buf,
5044#ifndef UNIX
5045 sfname
5046#else
5047 fname
5048#endif
5049 ); /* put file name in IObuff with quotes */
5050 if (STRLEN(IObuff) + STRLEN(errmsg) + numlen >= IOSIZE)
5051 IObuff[IOSIZE - STRLEN(errmsg) - numlen - 1] = NUL;
5052 /* If the error message has the form "is ...", put the error number in
5053 * front of the file name. */
5054 if (errnum != NULL)
5055 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00005056 STRMOVE(IObuff + numlen, IObuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005057 mch_memmove(IObuff, errnum, (size_t)numlen);
5058 }
5059 STRCAT(IObuff, errmsg);
5060 emsg(IObuff);
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005061 if (errmsg_allocated)
5062 vim_free(errmsg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005063
5064 retval = FAIL;
5065 if (end == 0)
5066 {
5067 MSG_PUTS_ATTR(_("\nWARNING: Original file may be lost or damaged\n"),
5068 attr | MSG_HIST);
5069 MSG_PUTS_ATTR(_("don't quit the editor until the file is successfully written!"),
5070 attr | MSG_HIST);
5071
5072 /* Update the timestamp to avoid an "overwrite changed file"
5073 * prompt when writing again. */
5074 if (mch_stat((char *)fname, &st_old) >= 0)
5075 {
5076 buf_store_time(buf, &st_old, fname);
5077 buf->b_mtime_read = buf->b_mtime;
5078 }
5079 }
5080 }
5081 msg_scroll = msg_save;
5082
Bram Moolenaar55debbe2010-05-23 23:34:36 +02005083#ifdef FEAT_PERSISTENT_UNDO
5084 /*
5085 * When writing the whole file and 'undofile' is set, also write the undo
5086 * file.
5087 */
5088 if (retval == OK && write_undo_file)
5089 {
5090 char_u hash[UNDO_HASH_SIZE];
5091
5092 sha256_finish(&sha_ctx, hash);
5093 u_write_undo(NULL, FALSE, buf, hash);
5094 }
5095#endif
5096
Bram Moolenaar071d4272004-06-13 20:20:40 +00005097#ifdef FEAT_AUTOCMD
5098#ifdef FEAT_EVAL
5099 if (!should_abort(retval))
5100#else
5101 if (!got_int)
5102#endif
5103 {
5104 aco_save_T aco;
5105
Bram Moolenaar071d4272004-06-13 20:20:40 +00005106 /*
5107 * Apply POST autocommands.
5108 * Careful: The autocommands may call buf_write() recursively!
5109 */
5110 aucmd_prepbuf(&aco, buf);
5111
5112 if (append)
5113 apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname,
5114 FALSE, curbuf, eap);
5115 else if (filtering)
5116 apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname,
5117 FALSE, curbuf, eap);
5118 else if (reset_changed && whole)
5119 apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname,
5120 FALSE, curbuf, eap);
5121 else
5122 apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname,
5123 FALSE, curbuf, eap);
5124
5125 /* restore curwin/curbuf and a few other things */
5126 aucmd_restbuf(&aco);
5127
5128#ifdef FEAT_EVAL
5129 if (aborting()) /* autocmds may abort script processing */
5130 retval = FALSE;
5131#endif
5132 }
5133#endif
5134
5135 got_int |= prev_got_int;
5136
5137#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
5138 /* Update machine specific information. */
5139 mch_post_buffer_write(buf);
5140#endif
5141 return retval;
5142}
5143
5144/*
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005145 * Set the name of the current buffer. Use when the buffer doesn't have a
5146 * name and a ":r" or ":w" command with a file name is used.
5147 */
5148 static int
5149set_rw_fname(fname, sfname)
5150 char_u *fname;
5151 char_u *sfname;
5152{
5153#ifdef FEAT_AUTOCMD
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005154 buf_T *buf = curbuf;
5155
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005156 /* It's like the unnamed buffer is deleted.... */
5157 if (curbuf->b_p_bl)
5158 apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
5159 apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf);
5160# ifdef FEAT_EVAL
5161 if (aborting()) /* autocmds may abort script processing */
5162 return FAIL;
5163# endif
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005164 if (curbuf != buf)
5165 {
5166 /* We are in another buffer now, don't do the renaming. */
5167 EMSG(_(e_auchangedbuf));
5168 return FAIL;
5169 }
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005170#endif
5171
5172 if (setfname(curbuf, fname, sfname, FALSE) == OK)
5173 curbuf->b_flags |= BF_NOTEDITED;
5174
5175#ifdef FEAT_AUTOCMD
5176 /* ....and a new named one is created */
5177 apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, curbuf);
5178 if (curbuf->b_p_bl)
5179 apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf);
5180# ifdef FEAT_EVAL
5181 if (aborting()) /* autocmds may abort script processing */
5182 return FAIL;
5183# endif
5184
5185 /* Do filetype detection now if 'filetype' is empty. */
5186 if (*curbuf->b_p_ft == NUL)
5187 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005188 if (au_has_group((char_u *)"filetypedetect"))
Bram Moolenaar70836c82006-02-20 21:28:49 +00005189 (void)do_doautocmd((char_u *)"filetypedetect BufRead", FALSE);
Bram Moolenaara3227e22006-03-08 21:32:40 +00005190 do_modelines(0);
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005191 }
5192#endif
5193
5194 return OK;
5195}
5196
5197/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00005198 * Put file name into IObuff with quotes.
5199 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005200 void
Bram Moolenaar071d4272004-06-13 20:20:40 +00005201msg_add_fname(buf, fname)
5202 buf_T *buf;
5203 char_u *fname;
5204{
5205 if (fname == NULL)
5206 fname = (char_u *)"-stdin-";
5207 home_replace(buf, fname, IObuff + 1, IOSIZE - 4, TRUE);
5208 IObuff[0] = '"';
5209 STRCAT(IObuff, "\" ");
5210}
5211
5212/*
5213 * Append message for text mode to IObuff.
5214 * Return TRUE if something appended.
5215 */
5216 static int
5217msg_add_fileformat(eol_type)
5218 int eol_type;
5219{
5220#ifndef USE_CRNL
5221 if (eol_type == EOL_DOS)
5222 {
5223 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[dos]") : _("[dos format]"));
5224 return TRUE;
5225 }
5226#endif
5227#ifndef USE_CR
5228 if (eol_type == EOL_MAC)
5229 {
5230 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[mac]") : _("[mac format]"));
5231 return TRUE;
5232 }
5233#endif
5234#if defined(USE_CRNL) || defined(USE_CR)
5235 if (eol_type == EOL_UNIX)
5236 {
5237 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[unix]") : _("[unix format]"));
5238 return TRUE;
5239 }
5240#endif
5241 return FALSE;
5242}
5243
5244/*
5245 * Append line and character count to IObuff.
5246 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005247 void
Bram Moolenaar071d4272004-06-13 20:20:40 +00005248msg_add_lines(insert_space, lnum, nchars)
5249 int insert_space;
5250 long lnum;
Bram Moolenaar914703b2010-05-31 21:59:46 +02005251 off_t nchars;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005252{
5253 char_u *p;
5254
5255 p = IObuff + STRLEN(IObuff);
5256
5257 if (insert_space)
5258 *p++ = ' ';
5259 if (shortmess(SHM_LINES))
Bram Moolenaar914703b2010-05-31 21:59:46 +02005260 sprintf((char *)p,
5261#ifdef LONG_LONG_OFF_T
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005262 "%ldL, %lldC", lnum, nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005263#else
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005264 /* Explicit typecast avoids warning on Mac OS X 10.6 */
5265 "%ldL, %ldC", lnum, (long)nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005266#endif
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005267 );
Bram Moolenaar071d4272004-06-13 20:20:40 +00005268 else
5269 {
5270 if (lnum == 1)
5271 STRCPY(p, _("1 line, "));
5272 else
5273 sprintf((char *)p, _("%ld lines, "), lnum);
5274 p += STRLEN(p);
5275 if (nchars == 1)
5276 STRCPY(p, _("1 character"));
5277 else
Bram Moolenaar914703b2010-05-31 21:59:46 +02005278 sprintf((char *)p,
5279#ifdef LONG_LONG_OFF_T
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005280 _("%lld characters"), nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005281#else
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005282 /* Explicit typecast avoids warning on Mac OS X 10.6 */
5283 _("%ld characters"), (long)nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005284#endif
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005285 );
Bram Moolenaar071d4272004-06-13 20:20:40 +00005286 }
5287}
5288
5289/*
5290 * Append message for missing line separator to IObuff.
5291 */
5292 static void
5293msg_add_eol()
5294{
5295 STRCAT(IObuff, shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]"));
5296}
5297
5298/*
5299 * Check modification time of file, before writing to it.
5300 * The size isn't checked, because using a tool like "gzip" takes care of
5301 * using the same timestamp but can't set the size.
5302 */
5303 static int
5304check_mtime(buf, st)
5305 buf_T *buf;
5306 struct stat *st;
5307{
5308 if (buf->b_mtime_read != 0
5309 && time_differs((long)st->st_mtime, buf->b_mtime_read))
5310 {
5311 msg_scroll = TRUE; /* don't overwrite messages here */
5312 msg_silent = 0; /* must give this prompt */
5313 /* don't use emsg() here, don't want to flush the buffers */
5314 MSG_ATTR(_("WARNING: The file has been changed since reading it!!!"),
5315 hl_attr(HLF_E));
5316 if (ask_yesno((char_u *)_("Do you really want to write to it"),
5317 TRUE) == 'n')
5318 return FAIL;
5319 msg_scroll = FALSE; /* always overwrite the file message now */
5320 }
5321 return OK;
5322}
5323
5324 static int
5325time_differs(t1, t2)
5326 long t1, t2;
5327{
5328#if defined(__linux__) || defined(MSDOS) || defined(MSWIN)
5329 /* On a FAT filesystem, esp. under Linux, there are only 5 bits to store
5330 * the seconds. Since the roundoff is done when flushing the inode, the
5331 * time may change unexpectedly by one second!!! */
5332 return (t1 - t2 > 1 || t2 - t1 > 1);
5333#else
5334 return (t1 != t2);
5335#endif
5336}
5337
5338/*
5339 * Call write() to write a number of bytes to the file.
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005340 * Handles encryption and 'encoding' conversion.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005341 *
5342 * Return FAIL for failure, OK otherwise.
5343 */
5344 static int
5345buf_write_bytes(ip)
5346 struct bw_info *ip;
5347{
5348 int wlen;
5349 char_u *buf = ip->bw_buf; /* data to write */
5350 int len = ip->bw_len; /* length of data */
5351#ifdef HAS_BW_FLAGS
5352 int flags = ip->bw_flags; /* extra flags */
5353#endif
5354
5355#ifdef FEAT_MBYTE
5356 /*
5357 * Skip conversion when writing the crypt magic number or the BOM.
5358 */
5359 if (!(flags & FIO_NOCONVERT))
5360 {
5361 char_u *p;
5362 unsigned c;
5363 int n;
5364
5365 if (flags & FIO_UTF8)
5366 {
5367 /*
5368 * Convert latin1 in the buffer to UTF-8 in the file.
5369 */
5370 p = ip->bw_conv_buf; /* translate to buffer */
5371 for (wlen = 0; wlen < len; ++wlen)
5372 p += utf_char2bytes(buf[wlen], p);
5373 buf = ip->bw_conv_buf;
5374 len = (int)(p - ip->bw_conv_buf);
5375 }
5376 else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1))
5377 {
5378 /*
5379 * Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
5380 * Latin1 chars in the file.
5381 */
5382 if (flags & FIO_LATIN1)
5383 p = buf; /* translate in-place (can only get shorter) */
5384 else
5385 p = ip->bw_conv_buf; /* translate to buffer */
5386 for (wlen = 0; wlen < len; wlen += n)
5387 {
5388 if (wlen == 0 && ip->bw_restlen != 0)
5389 {
5390 int l;
5391
5392 /* Use remainder of previous call. Append the start of
5393 * buf[] to get a full sequence. Might still be too
5394 * short! */
5395 l = CONV_RESTLEN - ip->bw_restlen;
5396 if (l > len)
5397 l = len;
5398 mch_memmove(ip->bw_rest + ip->bw_restlen, buf, (size_t)l);
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005399 n = utf_ptr2len_len(ip->bw_rest, ip->bw_restlen + l);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005400 if (n > ip->bw_restlen + len)
5401 {
5402 /* We have an incomplete byte sequence at the end to
5403 * be written. We can't convert it without the
5404 * remaining bytes. Keep them for the next call. */
5405 if (ip->bw_restlen + len > CONV_RESTLEN)
5406 return FAIL;
5407 ip->bw_restlen += len;
5408 break;
5409 }
5410 if (n > 1)
5411 c = utf_ptr2char(ip->bw_rest);
5412 else
5413 c = ip->bw_rest[0];
5414 if (n >= ip->bw_restlen)
5415 {
5416 n -= ip->bw_restlen;
5417 ip->bw_restlen = 0;
5418 }
5419 else
5420 {
5421 ip->bw_restlen -= n;
5422 mch_memmove(ip->bw_rest, ip->bw_rest + n,
5423 (size_t)ip->bw_restlen);
5424 n = 0;
5425 }
5426 }
5427 else
5428 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005429 n = utf_ptr2len_len(buf + wlen, len - wlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005430 if (n > len - wlen)
5431 {
5432 /* We have an incomplete byte sequence at the end to
5433 * be written. We can't convert it without the
5434 * remaining bytes. Keep them for the next call. */
5435 if (len - wlen > CONV_RESTLEN)
5436 return FAIL;
5437 ip->bw_restlen = len - wlen;
5438 mch_memmove(ip->bw_rest, buf + wlen,
5439 (size_t)ip->bw_restlen);
5440 break;
5441 }
5442 if (n > 1)
5443 c = utf_ptr2char(buf + wlen);
5444 else
5445 c = buf[wlen];
5446 }
5447
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005448 if (ucs2bytes(c, &p, flags) && !ip->bw_conv_error)
5449 {
5450 ip->bw_conv_error = TRUE;
5451 ip->bw_conv_error_lnum = ip->bw_start_lnum;
5452 }
5453 if (c == NL)
5454 ++ip->bw_start_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005455 }
5456 if (flags & FIO_LATIN1)
5457 len = (int)(p - buf);
5458 else
5459 {
5460 buf = ip->bw_conv_buf;
5461 len = (int)(p - ip->bw_conv_buf);
5462 }
5463 }
5464
5465# ifdef WIN3264
5466 else if (flags & FIO_CODEPAGE)
5467 {
5468 /*
5469 * Convert UTF-8 or codepage to UCS-2 and then to MS-Windows
5470 * codepage.
5471 */
5472 char_u *from;
5473 size_t fromlen;
5474 char_u *to;
5475 int u8c;
5476 BOOL bad = FALSE;
5477 int needed;
5478
5479 if (ip->bw_restlen > 0)
5480 {
5481 /* Need to concatenate the remainder of the previous call and
5482 * the bytes of the current call. Use the end of the
5483 * conversion buffer for this. */
5484 fromlen = len + ip->bw_restlen;
5485 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5486 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5487 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5488 }
5489 else
5490 {
5491 from = buf;
5492 fromlen = len;
5493 }
5494
5495 to = ip->bw_conv_buf;
5496 if (enc_utf8)
5497 {
5498 /* Convert from UTF-8 to UCS-2, to the start of the buffer.
5499 * The buffer has been allocated to be big enough. */
5500 while (fromlen > 0)
5501 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005502 n = (int)utf_ptr2len_len(from, (int)fromlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005503 if (n > (int)fromlen) /* incomplete byte sequence */
5504 break;
5505 u8c = utf_ptr2char(from);
5506 *to++ = (u8c & 0xff);
5507 *to++ = (u8c >> 8);
5508 fromlen -= n;
5509 from += n;
5510 }
5511
5512 /* Copy remainder to ip->bw_rest[] to be used for the next
5513 * call. */
5514 if (fromlen > CONV_RESTLEN)
5515 {
5516 /* weird overlong sequence */
5517 ip->bw_conv_error = TRUE;
5518 return FAIL;
5519 }
5520 mch_memmove(ip->bw_rest, from, fromlen);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005521 ip->bw_restlen = (int)fromlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005522 }
5523 else
5524 {
5525 /* Convert from enc_codepage to UCS-2, to the start of the
5526 * buffer. The buffer has been allocated to be big enough. */
5527 ip->bw_restlen = 0;
5528 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005529 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005530 NULL, 0);
5531 if (needed == 0)
5532 {
5533 /* When conversion fails there may be a trailing byte. */
5534 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005535 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen - 1,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005536 NULL, 0);
5537 if (needed == 0)
5538 {
5539 /* Conversion doesn't work. */
5540 ip->bw_conv_error = TRUE;
5541 return FAIL;
5542 }
5543 /* Save the trailing byte for the next call. */
5544 ip->bw_rest[0] = from[fromlen - 1];
5545 ip->bw_restlen = 1;
5546 }
5547 needed = MultiByteToWideChar(enc_codepage, MB_ERR_INVALID_CHARS,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005548 (LPCSTR)from, (int)(fromlen - ip->bw_restlen),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005549 (LPWSTR)to, needed);
5550 if (needed == 0)
5551 {
5552 /* Safety check: Conversion doesn't work. */
5553 ip->bw_conv_error = TRUE;
5554 return FAIL;
5555 }
5556 to += needed * 2;
5557 }
5558
5559 fromlen = to - ip->bw_conv_buf;
5560 buf = to;
5561# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5562 if (FIO_GET_CP(flags) == CP_UTF8)
5563 {
5564 /* Convert from UCS-2 to UTF-8, using the remainder of the
5565 * conversion buffer. Fails when out of space. */
5566 for (from = ip->bw_conv_buf; fromlen > 1; fromlen -= 2)
5567 {
5568 u8c = *from++;
5569 u8c += (*from++ << 8);
5570 to += utf_char2bytes(u8c, to);
5571 if (to + 6 >= ip->bw_conv_buf + ip->bw_conv_buflen)
5572 {
5573 ip->bw_conv_error = TRUE;
5574 return FAIL;
5575 }
5576 }
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005577 len = (int)(to - buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005578 }
5579 else
5580#endif
5581 {
5582 /* Convert from UCS-2 to the codepage, using the remainder of
5583 * the conversion buffer. If the conversion uses the default
5584 * character "0", the data doesn't fit in this encoding, so
5585 * fail. */
5586 len = WideCharToMultiByte(FIO_GET_CP(flags), 0,
5587 (LPCWSTR)ip->bw_conv_buf, (int)fromlen / sizeof(WCHAR),
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005588 (LPSTR)to, (int)(ip->bw_conv_buflen - fromlen), 0,
5589 &bad);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005590 if (bad)
5591 {
5592 ip->bw_conv_error = TRUE;
5593 return FAIL;
5594 }
5595 }
5596 }
5597# endif
5598
Bram Moolenaar56718732006-03-15 22:53:57 +00005599# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00005600 else if (flags & FIO_MACROMAN)
5601 {
5602 /*
5603 * Convert UTF-8 or latin1 to Apple MacRoman.
5604 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005605 char_u *from;
5606 size_t fromlen;
5607
5608 if (ip->bw_restlen > 0)
5609 {
5610 /* Need to concatenate the remainder of the previous call and
5611 * the bytes of the current call. Use the end of the
5612 * conversion buffer for this. */
5613 fromlen = len + ip->bw_restlen;
5614 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5615 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5616 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5617 }
5618 else
5619 {
5620 from = buf;
5621 fromlen = len;
5622 }
5623
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00005624 if (enc2macroman(from, fromlen,
5625 ip->bw_conv_buf, &len, ip->bw_conv_buflen,
5626 ip->bw_rest, &ip->bw_restlen) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005627 {
5628 ip->bw_conv_error = TRUE;
5629 return FAIL;
5630 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005631 buf = ip->bw_conv_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005632 }
5633# endif
5634
5635# ifdef USE_ICONV
5636 if (ip->bw_iconv_fd != (iconv_t)-1)
5637 {
5638 const char *from;
5639 size_t fromlen;
5640 char *to;
5641 size_t tolen;
5642
5643 /* Convert with iconv(). */
5644 if (ip->bw_restlen > 0)
5645 {
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005646 char *fp;
5647
Bram Moolenaar071d4272004-06-13 20:20:40 +00005648 /* Need to concatenate the remainder of the previous call and
5649 * the bytes of the current call. Use the end of the
5650 * conversion buffer for this. */
5651 fromlen = len + ip->bw_restlen;
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005652 fp = (char *)ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5653 mch_memmove(fp, ip->bw_rest, (size_t)ip->bw_restlen);
5654 mch_memmove(fp + ip->bw_restlen, buf, (size_t)len);
5655 from = fp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005656 tolen = ip->bw_conv_buflen - fromlen;
5657 }
5658 else
5659 {
5660 from = (const char *)buf;
5661 fromlen = len;
5662 tolen = ip->bw_conv_buflen;
5663 }
5664 to = (char *)ip->bw_conv_buf;
5665
5666 if (ip->bw_first)
5667 {
5668 size_t save_len = tolen;
5669
5670 /* output the initial shift state sequence */
5671 (void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen);
5672
5673 /* There is a bug in iconv() on Linux (which appears to be
5674 * wide-spread) which sets "to" to NULL and messes up "tolen".
5675 */
5676 if (to == NULL)
5677 {
5678 to = (char *)ip->bw_conv_buf;
5679 tolen = save_len;
5680 }
5681 ip->bw_first = FALSE;
5682 }
5683
5684 /*
5685 * If iconv() has an error or there is not enough room, fail.
5686 */
5687 if ((iconv(ip->bw_iconv_fd, (void *)&from, &fromlen, &to, &tolen)
5688 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
5689 || fromlen > CONV_RESTLEN)
5690 {
5691 ip->bw_conv_error = TRUE;
5692 return FAIL;
5693 }
5694
5695 /* copy remainder to ip->bw_rest[] to be used for the next call. */
5696 if (fromlen > 0)
5697 mch_memmove(ip->bw_rest, (void *)from, fromlen);
5698 ip->bw_restlen = (int)fromlen;
5699
5700 buf = ip->bw_conv_buf;
5701 len = (int)((char_u *)to - ip->bw_conv_buf);
5702 }
5703# endif
5704 }
5705#endif /* FEAT_MBYTE */
5706
5707#ifdef FEAT_CRYPT
5708 if (flags & FIO_ENCRYPTED) /* encrypt the data */
Bram Moolenaar04c9baf2010-06-01 23:37:39 +02005709 crypt_encode(buf, len, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005710#endif
5711
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005712 wlen = write_eintr(ip->bw_fd, buf, len);
5713 return (wlen < len) ? FAIL : OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005714}
5715
5716#ifdef FEAT_MBYTE
5717/*
5718 * Convert a Unicode character to bytes.
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005719 * Return TRUE for an error, FALSE when it's OK.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005720 */
5721 static int
5722ucs2bytes(c, pp, flags)
5723 unsigned c; /* in: character */
5724 char_u **pp; /* in/out: pointer to result */
5725 int flags; /* FIO_ flags */
5726{
5727 char_u *p = *pp;
5728 int error = FALSE;
5729 int cc;
5730
5731
5732 if (flags & FIO_UCS4)
5733 {
5734 if (flags & FIO_ENDIAN_L)
5735 {
5736 *p++ = c;
5737 *p++ = (c >> 8);
5738 *p++ = (c >> 16);
5739 *p++ = (c >> 24);
5740 }
5741 else
5742 {
5743 *p++ = (c >> 24);
5744 *p++ = (c >> 16);
5745 *p++ = (c >> 8);
5746 *p++ = c;
5747 }
5748 }
5749 else if (flags & (FIO_UCS2 | FIO_UTF16))
5750 {
5751 if (c >= 0x10000)
5752 {
5753 if (flags & FIO_UTF16)
5754 {
5755 /* Make two words, ten bits of the character in each. First
5756 * word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff */
5757 c -= 0x10000;
5758 if (c >= 0x100000)
5759 error = TRUE;
5760 cc = ((c >> 10) & 0x3ff) + 0xd800;
5761 if (flags & FIO_ENDIAN_L)
5762 {
5763 *p++ = cc;
5764 *p++ = ((unsigned)cc >> 8);
5765 }
5766 else
5767 {
5768 *p++ = ((unsigned)cc >> 8);
5769 *p++ = cc;
5770 }
5771 c = (c & 0x3ff) + 0xdc00;
5772 }
5773 else
5774 error = TRUE;
5775 }
5776 if (flags & FIO_ENDIAN_L)
5777 {
5778 *p++ = c;
5779 *p++ = (c >> 8);
5780 }
5781 else
5782 {
5783 *p++ = (c >> 8);
5784 *p++ = c;
5785 }
5786 }
5787 else /* Latin1 */
5788 {
5789 if (c >= 0x100)
5790 {
5791 error = TRUE;
5792 *p++ = 0xBF;
5793 }
5794 else
5795 *p++ = c;
5796 }
5797
5798 *pp = p;
5799 return error;
5800}
5801
5802/*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005803 * Return TRUE if file encoding "fenc" requires conversion from or to
5804 * 'encoding'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005805 */
5806 static int
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005807need_conversion(fenc)
5808 char_u *fenc;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005809{
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005810 int same_encoding;
5811 int enc_flags;
5812 int fenc_flags;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005813
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005814 if (*fenc == NUL || STRCMP(p_enc, fenc) == 0)
Bram Moolenaar442b4222010-05-24 21:34:22 +02005815 {
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005816 same_encoding = TRUE;
Bram Moolenaar442b4222010-05-24 21:34:22 +02005817 fenc_flags = 0;
5818 }
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005819 else
5820 {
5821 /* Ignore difference between "ansi" and "latin1", "ucs-4" and
5822 * "ucs-4be", etc. */
5823 enc_flags = get_fio_flags(p_enc);
5824 fenc_flags = get_fio_flags(fenc);
5825 same_encoding = (enc_flags != 0 && fenc_flags == enc_flags);
5826 }
5827 if (same_encoding)
5828 {
5829 /* Specified encoding matches with 'encoding'. This requires
5830 * conversion when 'encoding' is Unicode but not UTF-8. */
5831 return enc_unicode != 0;
5832 }
5833
5834 /* Encodings differ. However, conversion is not needed when 'enc' is any
5835 * Unicode encoding and the file is UTF-8. */
5836 return !(enc_utf8 && fenc_flags == FIO_UTF8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005837}
5838
5839/*
5840 * Check "ptr" for a unicode encoding and return the FIO_ flags needed for the
5841 * internal conversion.
5842 * if "ptr" is an empty string, use 'encoding'.
5843 */
5844 static int
5845get_fio_flags(ptr)
5846 char_u *ptr;
5847{
5848 int prop;
5849
5850 if (*ptr == NUL)
5851 ptr = p_enc;
5852
5853 prop = enc_canon_props(ptr);
5854 if (prop & ENC_UNICODE)
5855 {
5856 if (prop & ENC_2BYTE)
5857 {
5858 if (prop & ENC_ENDIAN_L)
5859 return FIO_UCS2 | FIO_ENDIAN_L;
5860 return FIO_UCS2;
5861 }
5862 if (prop & ENC_4BYTE)
5863 {
5864 if (prop & ENC_ENDIAN_L)
5865 return FIO_UCS4 | FIO_ENDIAN_L;
5866 return FIO_UCS4;
5867 }
5868 if (prop & ENC_2WORD)
5869 {
5870 if (prop & ENC_ENDIAN_L)
5871 return FIO_UTF16 | FIO_ENDIAN_L;
5872 return FIO_UTF16;
5873 }
5874 return FIO_UTF8;
5875 }
5876 if (prop & ENC_LATIN1)
5877 return FIO_LATIN1;
5878 /* must be ENC_DBCS, requires iconv() */
5879 return 0;
5880}
5881
5882#ifdef WIN3264
5883/*
5884 * Check "ptr" for a MS-Windows codepage name and return the FIO_ flags needed
5885 * for the conversion MS-Windows can do for us. Also accept "utf-8".
5886 * Used for conversion between 'encoding' and 'fileencoding'.
5887 */
5888 static int
5889get_win_fio_flags(ptr)
5890 char_u *ptr;
5891{
5892 int cp;
5893
5894 /* Cannot do this when 'encoding' is not utf-8 and not a codepage. */
5895 if (!enc_utf8 && enc_codepage <= 0)
5896 return 0;
5897
5898 cp = encname2codepage(ptr);
5899 if (cp == 0)
5900 {
5901# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5902 if (STRCMP(ptr, "utf-8") == 0)
5903 cp = CP_UTF8;
5904 else
5905# endif
5906 return 0;
5907 }
5908 return FIO_PUT_CP(cp) | FIO_CODEPAGE;
5909}
5910#endif
5911
5912#ifdef MACOS_X
5913/*
5914 * Check "ptr" for a Carbon supported encoding and return the FIO_ flags
5915 * needed for the internal conversion to/from utf-8 or latin1.
5916 */
5917 static int
5918get_mac_fio_flags(ptr)
5919 char_u *ptr;
5920{
5921 if ((enc_utf8 || STRCMP(p_enc, "latin1") == 0)
5922 && (enc_canon_props(ptr) & ENC_MACROMAN))
5923 return FIO_MACROMAN;
5924 return 0;
5925}
5926#endif
5927
5928/*
5929 * Check for a Unicode BOM (Byte Order Mark) at the start of p[size].
5930 * "size" must be at least 2.
5931 * Return the name of the encoding and set "*lenp" to the length.
5932 * Returns NULL when no BOM found.
5933 */
5934 static char_u *
5935check_for_bom(p, size, lenp, flags)
5936 char_u *p;
5937 long size;
5938 int *lenp;
5939 int flags;
5940{
5941 char *name = NULL;
5942 int len = 2;
5943
5944 if (p[0] == 0xef && p[1] == 0xbb && size >= 3 && p[2] == 0xbf
Bram Moolenaaree0f5a62008-07-24 20:09:16 +00005945 && (flags == FIO_ALL || flags == FIO_UTF8 || flags == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005946 {
5947 name = "utf-8"; /* EF BB BF */
5948 len = 3;
5949 }
5950 else if (p[0] == 0xff && p[1] == 0xfe)
5951 {
5952 if (size >= 4 && p[2] == 0 && p[3] == 0
5953 && (flags == FIO_ALL || flags == (FIO_UCS4 | FIO_ENDIAN_L)))
5954 {
5955 name = "ucs-4le"; /* FF FE 00 00 */
5956 len = 4;
5957 }
Bram Moolenaar223a1892008-11-11 20:57:11 +00005958 else if (flags == (FIO_UCS2 | FIO_ENDIAN_L))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005959 name = "ucs-2le"; /* FF FE */
Bram Moolenaar223a1892008-11-11 20:57:11 +00005960 else if (flags == FIO_ALL || flags == (FIO_UTF16 | FIO_ENDIAN_L))
5961 /* utf-16le is preferred, it also works for ucs-2le text */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005962 name = "utf-16le"; /* FF FE */
5963 }
5964 else if (p[0] == 0xfe && p[1] == 0xff
5965 && (flags == FIO_ALL || flags == FIO_UCS2 || flags == FIO_UTF16))
5966 {
Bram Moolenaarffd82c52008-02-20 17:15:26 +00005967 /* Default to utf-16, it works also for ucs-2 text. */
5968 if (flags == FIO_UCS2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005969 name = "ucs-2"; /* FE FF */
Bram Moolenaarffd82c52008-02-20 17:15:26 +00005970 else
5971 name = "utf-16"; /* FE FF */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005972 }
5973 else if (size >= 4 && p[0] == 0 && p[1] == 0 && p[2] == 0xfe
5974 && p[3] == 0xff && (flags == FIO_ALL || flags == FIO_UCS4))
5975 {
5976 name = "ucs-4"; /* 00 00 FE FF */
5977 len = 4;
5978 }
5979
5980 *lenp = len;
5981 return (char_u *)name;
5982}
5983
5984/*
5985 * Generate a BOM in "buf[4]" for encoding "name".
5986 * Return the length of the BOM (zero when no BOM).
5987 */
5988 static int
5989make_bom(buf, name)
5990 char_u *buf;
5991 char_u *name;
5992{
5993 int flags;
5994 char_u *p;
5995
5996 flags = get_fio_flags(name);
5997
5998 /* Can't put a BOM in a non-Unicode file. */
5999 if (flags == FIO_LATIN1 || flags == 0)
6000 return 0;
6001
6002 if (flags == FIO_UTF8) /* UTF-8 */
6003 {
6004 buf[0] = 0xef;
6005 buf[1] = 0xbb;
6006 buf[2] = 0xbf;
6007 return 3;
6008 }
6009 p = buf;
6010 (void)ucs2bytes(0xfeff, &p, flags);
6011 return (int)(p - buf);
6012}
6013#endif
6014
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00006015#if defined(FEAT_VIMINFO) || defined(FEAT_BROWSE) || \
Bram Moolenaara0174af2008-01-02 20:08:25 +00006016 defined(FEAT_QUICKFIX) || defined(FEAT_AUTOCMD) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006017/*
6018 * Try to find a shortname by comparing the fullname with the current
6019 * directory.
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006020 * Returns "full_path" or pointer into "full_path" if shortened.
6021 */
6022 char_u *
6023shorten_fname1(full_path)
6024 char_u *full_path;
6025{
6026 char_u dirname[MAXPATHL];
6027 char_u *p = full_path;
6028
6029 if (mch_dirname(dirname, MAXPATHL) == OK)
6030 {
6031 p = shorten_fname(full_path, dirname);
6032 if (p == NULL || *p == NUL)
6033 p = full_path;
6034 }
6035 return p;
6036}
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00006037#endif
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006038
6039/*
6040 * Try to find a shortname by comparing the fullname with the current
6041 * directory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006042 * Returns NULL if not shorter name possible, pointer into "full_path"
6043 * otherwise.
6044 */
6045 char_u *
6046shorten_fname(full_path, dir_name)
6047 char_u *full_path;
6048 char_u *dir_name;
6049{
6050 int len;
6051 char_u *p;
6052
6053 if (full_path == NULL)
6054 return NULL;
6055 len = (int)STRLEN(dir_name);
6056 if (fnamencmp(dir_name, full_path, len) == 0)
6057 {
6058 p = full_path + len;
6059#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
6060 /*
6061 * MSDOS: when a file is in the root directory, dir_name will end in a
6062 * slash, since C: by itself does not define a specific dir. In this
6063 * case p may already be correct. <negri>
6064 */
6065 if (!((len > 2) && (*(p - 2) == ':')))
6066#endif
6067 {
6068 if (vim_ispathsep(*p))
6069 ++p;
6070#ifndef VMS /* the path separator is always part of the path */
6071 else
6072 p = NULL;
6073#endif
6074 }
6075 }
6076#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
6077 /*
6078 * When using a file in the current drive, remove the drive name:
6079 * "A:\dir\file" -> "\dir\file". This helps when moving a session file on
6080 * a floppy from "A:\dir" to "B:\dir".
6081 */
6082 else if (len > 3
6083 && TOUPPER_LOC(full_path[0]) == TOUPPER_LOC(dir_name[0])
6084 && full_path[1] == ':'
6085 && vim_ispathsep(full_path[2]))
6086 p = full_path + 2;
6087#endif
6088 else
6089 p = NULL;
6090 return p;
6091}
6092
6093/*
6094 * Shorten filenames for all buffers.
6095 * When "force" is TRUE: Use full path from now on for files currently being
6096 * edited, both for file name and swap file name. Try to shorten the file
6097 * names a bit, if safe to do so.
6098 * When "force" is FALSE: Only try to shorten absolute file names.
6099 * For buffers that have buftype "nofile" or "scratch": never change the file
6100 * name.
6101 */
6102 void
6103shorten_fnames(force)
6104 int force;
6105{
6106 char_u dirname[MAXPATHL];
6107 buf_T *buf;
6108 char_u *p;
6109
6110 mch_dirname(dirname, MAXPATHL);
6111 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
6112 {
6113 if (buf->b_fname != NULL
6114#ifdef FEAT_QUICKFIX
6115 && !bt_nofile(buf)
6116#endif
6117 && !path_with_url(buf->b_fname)
6118 && (force
6119 || buf->b_sfname == NULL
6120 || mch_isFullName(buf->b_sfname)))
6121 {
6122 vim_free(buf->b_sfname);
6123 buf->b_sfname = NULL;
6124 p = shorten_fname(buf->b_ffname, dirname);
6125 if (p != NULL)
6126 {
6127 buf->b_sfname = vim_strsave(p);
6128 buf->b_fname = buf->b_sfname;
6129 }
6130 if (p == NULL || buf->b_fname == NULL)
6131 buf->b_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006132 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00006133
6134 /* Always make the swap file name a full path, a "nofile" buffer may
6135 * also have a swap file. */
6136 mf_fullname(buf->b_ml.ml_mfp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006137 }
6138#ifdef FEAT_WINDOWS
6139 status_redraw_all();
Bram Moolenaar49d7bf12006-02-17 21:45:41 +00006140 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006141#endif
6142}
6143
6144#if (defined(FEAT_DND) && defined(FEAT_GUI_GTK)) \
6145 || defined(FEAT_GUI_MSWIN) \
6146 || defined(FEAT_GUI_MAC) \
6147 || defined(PROTO)
6148/*
6149 * Shorten all filenames in "fnames[count]" by current directory.
6150 */
6151 void
6152shorten_filenames(fnames, count)
6153 char_u **fnames;
6154 int count;
6155{
6156 int i;
6157 char_u dirname[MAXPATHL];
6158 char_u *p;
6159
6160 if (fnames == NULL || count < 1)
6161 return;
6162 mch_dirname(dirname, sizeof(dirname));
6163 for (i = 0; i < count; ++i)
6164 {
6165 if ((p = shorten_fname(fnames[i], dirname)) != NULL)
6166 {
6167 /* shorten_fname() returns pointer in given "fnames[i]". If free
6168 * "fnames[i]" first, "p" becomes invalid. So we need to copy
6169 * "p" first then free fnames[i]. */
6170 p = vim_strsave(p);
6171 vim_free(fnames[i]);
6172 fnames[i] = p;
6173 }
6174 }
6175}
6176#endif
6177
6178/*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006179 * add extension to file name - change path/fo.o.h to path/fo.o.h.ext or
Bram Moolenaar071d4272004-06-13 20:20:40 +00006180 * fo_o_h.ext for MSDOS or when shortname option set.
6181 *
6182 * Assumed that fname is a valid name found in the filesystem we assure that
6183 * the return value is a different name and ends in 'ext'.
6184 * "ext" MUST be at most 4 characters long if it starts with a dot, 3
6185 * characters otherwise.
6186 * Space for the returned name is allocated, must be freed later.
6187 * Returns NULL when out of memory.
6188 */
6189 char_u *
6190modname(fname, ext, prepend_dot)
6191 char_u *fname, *ext;
6192 int prepend_dot; /* may prepend a '.' to file name */
6193{
6194 return buf_modname(
6195#ifdef SHORT_FNAME
6196 TRUE,
6197#else
6198 (curbuf->b_p_sn || curbuf->b_shortname),
6199#endif
6200 fname, ext, prepend_dot);
6201}
6202
6203 char_u *
6204buf_modname(shortname, fname, ext, prepend_dot)
6205 int shortname; /* use 8.3 file name */
6206 char_u *fname, *ext;
6207 int prepend_dot; /* may prepend a '.' to file name */
6208{
6209 char_u *retval;
6210 char_u *s;
6211 char_u *e;
6212 char_u *ptr;
6213 int fnamelen, extlen;
6214
6215 extlen = (int)STRLEN(ext);
6216
6217 /*
6218 * If there is no file name we must get the name of the current directory
6219 * (we need the full path in case :cd is used).
6220 */
6221 if (fname == NULL || *fname == NUL)
6222 {
6223 retval = alloc((unsigned)(MAXPATHL + extlen + 3));
6224 if (retval == NULL)
6225 return NULL;
6226 if (mch_dirname(retval, MAXPATHL) == FAIL ||
6227 (fnamelen = (int)STRLEN(retval)) == 0)
6228 {
6229 vim_free(retval);
6230 return NULL;
6231 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006232 if (!after_pathsep(retval, retval + fnamelen))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006233 {
6234 retval[fnamelen++] = PATHSEP;
6235 retval[fnamelen] = NUL;
6236 }
6237#ifndef SHORT_FNAME
6238 prepend_dot = FALSE; /* nothing to prepend a dot to */
6239#endif
6240 }
6241 else
6242 {
6243 fnamelen = (int)STRLEN(fname);
6244 retval = alloc((unsigned)(fnamelen + extlen + 3));
6245 if (retval == NULL)
6246 return NULL;
6247 STRCPY(retval, fname);
6248#ifdef VMS
6249 vms_remove_version(retval); /* we do not need versions here */
6250#endif
6251 }
6252
6253 /*
6254 * search backwards until we hit a '/', '\' or ':' replacing all '.'
6255 * by '_' for MSDOS or when shortname option set and ext starts with a dot.
6256 * Then truncate what is after the '/', '\' or ':' to 8 characters for
6257 * MSDOS and 26 characters for AMIGA, a lot more for UNIX.
6258 */
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006259 for (ptr = retval + fnamelen; ptr > retval; mb_ptr_back(retval, ptr))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006260 {
6261#ifndef RISCOS
6262 if (*ext == '.'
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006263# ifdef USE_LONG_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00006264 && (!USE_LONG_FNAME || shortname)
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006265# else
6266# ifndef SHORT_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00006267 && shortname
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006268# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006269# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006270 )
6271 if (*ptr == '.') /* replace '.' by '_' */
6272 *ptr = '_';
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006273#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006274 if (vim_ispathsep(*ptr))
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006275 {
6276 ++ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006277 break;
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006278 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006279 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006280
6281 /* the file name has at most BASENAMELEN characters. */
6282#ifndef SHORT_FNAME
6283 if (STRLEN(ptr) > (unsigned)BASENAMELEN)
6284 ptr[BASENAMELEN] = '\0';
6285#endif
6286
6287 s = ptr + STRLEN(ptr);
6288
6289 /*
6290 * For 8.3 file names we may have to reduce the length.
6291 */
6292#ifdef USE_LONG_FNAME
6293 if (!USE_LONG_FNAME || shortname)
6294#else
6295# ifndef SHORT_FNAME
6296 if (shortname)
6297# endif
6298#endif
6299 {
6300 /*
6301 * If there is no file name, or the file name ends in '/', and the
6302 * extension starts with '.', put a '_' before the dot, because just
6303 * ".ext" is invalid.
6304 */
6305 if (fname == NULL || *fname == NUL
6306 || vim_ispathsep(fname[STRLEN(fname) - 1]))
6307 {
6308#ifdef RISCOS
6309 if (*ext == '/')
6310#else
6311 if (*ext == '.')
6312#endif
6313 *s++ = '_';
6314 }
6315 /*
6316 * If the extension starts with '.', truncate the base name at 8
6317 * characters
6318 */
6319#ifdef RISCOS
6320 /* We normally use '/', but swap files are '_' */
6321 else if (*ext == '/' || *ext == '_')
6322#else
6323 else if (*ext == '.')
6324#endif
6325 {
Bram Moolenaar78a15312009-05-15 19:33:18 +00006326 if ((size_t)(s - ptr) > (size_t)8)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006327 {
6328 s = ptr + 8;
6329 *s = '\0';
6330 }
6331 }
6332 /*
6333 * If the extension doesn't start with '.', and the file name
6334 * doesn't have an extension yet, append a '.'
6335 */
6336#ifdef RISCOS
6337 else if ((e = vim_strchr(ptr, '/')) == NULL)
6338 *s++ = '/';
6339#else
6340 else if ((e = vim_strchr(ptr, '.')) == NULL)
6341 *s++ = '.';
6342#endif
6343 /*
6344 * If the extension doesn't start with '.', and there already is an
Bram Moolenaar7263a772007-05-10 17:35:54 +00006345 * extension, it may need to be truncated
Bram Moolenaar071d4272004-06-13 20:20:40 +00006346 */
6347 else if ((int)STRLEN(e) + extlen > 4)
6348 s = e + 4 - extlen;
6349 }
6350#if defined(OS2) || defined(USE_LONG_FNAME) || defined(WIN3264)
6351 /*
6352 * If there is no file name, and the extension starts with '.', put a
6353 * '_' before the dot, because just ".ext" may be invalid if it's on a
6354 * FAT partition, and on HPFS it doesn't matter.
6355 */
6356 else if ((fname == NULL || *fname == NUL) && *ext == '.')
6357 *s++ = '_';
6358#endif
6359
6360 /*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006361 * Append the extension.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006362 * ext can start with '.' and cannot exceed 3 more characters.
6363 */
6364 STRCPY(s, ext);
6365
6366#ifndef SHORT_FNAME
6367 /*
6368 * Prepend the dot.
6369 */
6370 if (prepend_dot && !shortname && *(e = gettail(retval)) !=
6371#ifdef RISCOS
6372 '/'
6373#else
6374 '.'
6375#endif
6376#ifdef USE_LONG_FNAME
6377 && USE_LONG_FNAME
6378#endif
6379 )
6380 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006381 STRMOVE(e + 1, e);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006382#ifdef RISCOS
6383 *e = '/';
6384#else
6385 *e = '.';
6386#endif
6387 }
6388#endif
6389
6390 /*
6391 * Check that, after appending the extension, the file name is really
6392 * different.
6393 */
6394 if (fname != NULL && STRCMP(fname, retval) == 0)
6395 {
6396 /* we search for a character that can be replaced by '_' */
6397 while (--s >= ptr)
6398 {
6399 if (*s != '_')
6400 {
6401 *s = '_';
6402 break;
6403 }
6404 }
6405 if (s < ptr) /* fname was "________.<ext>", how tricky! */
6406 *ptr = 'v';
6407 }
6408 return retval;
6409}
6410
6411/*
6412 * Like fgets(), but if the file line is too long, it is truncated and the
6413 * rest of the line is thrown away. Returns TRUE for end-of-file.
6414 */
6415 int
6416vim_fgets(buf, size, fp)
6417 char_u *buf;
6418 int size;
6419 FILE *fp;
6420{
6421 char *eof;
6422#define FGETS_SIZE 200
6423 char tbuf[FGETS_SIZE];
6424
6425 buf[size - 2] = NUL;
6426#ifdef USE_CR
6427 eof = fgets_cr((char *)buf, size, fp);
6428#else
6429 eof = fgets((char *)buf, size, fp);
6430#endif
6431 if (buf[size - 2] != NUL && buf[size - 2] != '\n')
6432 {
6433 buf[size - 1] = NUL; /* Truncate the line */
6434
6435 /* Now throw away the rest of the line: */
6436 do
6437 {
6438 tbuf[FGETS_SIZE - 2] = NUL;
6439#ifdef USE_CR
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006440 ignoredp = fgets_cr((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006441#else
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006442 ignoredp = fgets((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006443#endif
6444 } while (tbuf[FGETS_SIZE - 2] != NUL && tbuf[FGETS_SIZE - 2] != '\n');
6445 }
6446 return (eof == NULL);
6447}
6448
6449#if defined(USE_CR) || defined(PROTO)
6450/*
6451 * Like vim_fgets(), but accept any line terminator: CR, CR-LF or LF.
6452 * Returns TRUE for end-of-file.
6453 * Only used for the Mac, because it's much slower than vim_fgets().
6454 */
6455 int
6456tag_fgets(buf, size, fp)
6457 char_u *buf;
6458 int size;
6459 FILE *fp;
6460{
6461 int i = 0;
6462 int c;
6463 int eof = FALSE;
6464
6465 for (;;)
6466 {
6467 c = fgetc(fp);
6468 if (c == EOF)
6469 {
6470 eof = TRUE;
6471 break;
6472 }
6473 if (c == '\r')
6474 {
6475 /* Always store a NL for end-of-line. */
6476 if (i < size - 1)
6477 buf[i++] = '\n';
6478 c = fgetc(fp);
6479 if (c != '\n') /* Macintosh format: single CR. */
6480 ungetc(c, fp);
6481 break;
6482 }
6483 if (i < size - 1)
6484 buf[i++] = c;
6485 if (c == '\n')
6486 break;
6487 }
6488 buf[i] = NUL;
6489 return eof;
6490}
6491#endif
6492
6493/*
6494 * rename() only works if both files are on the same file system, this
6495 * function will (attempts to?) copy the file across if rename fails -- webb
6496 * Return -1 for failure, 0 for success.
6497 */
6498 int
6499vim_rename(from, to)
6500 char_u *from;
6501 char_u *to;
6502{
6503 int fd_in;
6504 int fd_out;
6505 int n;
6506 char *errmsg = NULL;
6507 char *buffer;
6508#ifdef AMIGA
6509 BPTR flock;
6510#endif
6511 struct stat st;
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006512 long perm;
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006513#ifdef HAVE_ACL
6514 vim_acl_T acl; /* ACL from original file */
6515#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006516#if defined(UNIX) || defined(CASE_INSENSITIVE_FILENAME)
6517 int use_tmp_file = FALSE;
6518#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006519
6520 /*
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006521 * When the names are identical, there is nothing to do. When they refer
6522 * to the same file (ignoring case and slash/backslash differences) but
6523 * the file name differs we need to go through a temp file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006524 */
6525 if (fnamecmp(from, to) == 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006526 {
6527#ifdef CASE_INSENSITIVE_FILENAME
6528 if (STRCMP(gettail(from), gettail(to)) != 0)
6529 use_tmp_file = TRUE;
6530 else
6531#endif
6532 return 0;
6533 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006534
6535 /*
6536 * Fail if the "from" file doesn't exist. Avoids that "to" is deleted.
6537 */
6538 if (mch_stat((char *)from, &st) < 0)
6539 return -1;
6540
Bram Moolenaar3576da72008-12-30 15:15:57 +00006541#ifdef UNIX
6542 {
6543 struct stat st_to;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006544
6545 /* It's possible for the source and destination to be the same file.
6546 * This happens when "from" and "to" differ in case and are on a FAT32
6547 * filesystem. In that case go through a temp file name. */
6548 if (mch_stat((char *)to, &st_to) >= 0
6549 && st.st_dev == st_to.st_dev
6550 && st.st_ino == st_to.st_ino)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006551 use_tmp_file = TRUE;
6552 }
6553#endif
6554
6555#if defined(UNIX) || defined(CASE_INSENSITIVE_FILENAME)
6556 if (use_tmp_file)
6557 {
6558 char tempname[MAXPATHL + 1];
6559
6560 /*
6561 * Find a name that doesn't exist and is in the same directory.
6562 * Rename "from" to "tempname" and then rename "tempname" to "to".
6563 */
6564 if (STRLEN(from) >= MAXPATHL - 5)
6565 return -1;
6566 STRCPY(tempname, from);
6567 for (n = 123; n < 99999; ++n)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006568 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006569 sprintf((char *)gettail((char_u *)tempname), "%d", n);
6570 if (mch_stat(tempname, &st) < 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006571 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006572 if (mch_rename((char *)from, tempname) == 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006573 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006574 if (mch_rename(tempname, (char *)to) == 0)
6575 return 0;
6576 /* Strange, the second step failed. Try moving the
6577 * file back and return failure. */
6578 mch_rename(tempname, (char *)from);
Bram Moolenaar3576da72008-12-30 15:15:57 +00006579 return -1;
6580 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006581 /* If it fails for one temp name it will most likely fail
6582 * for any temp name, give up. */
6583 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006584 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006585 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006586 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006587 }
6588#endif
6589
Bram Moolenaar071d4272004-06-13 20:20:40 +00006590 /*
6591 * Delete the "to" file, this is required on some systems to make the
6592 * mch_rename() work, on other systems it makes sure that we don't have
6593 * two files when the mch_rename() fails.
6594 */
6595
6596#ifdef AMIGA
6597 /*
6598 * With MSDOS-compatible filesystems (crossdos, messydos) it is possible
6599 * that the name of the "to" file is the same as the "from" file, even
Bram Moolenaar7263a772007-05-10 17:35:54 +00006600 * though the names are different. To avoid the chance of accidentally
Bram Moolenaar071d4272004-06-13 20:20:40 +00006601 * deleting the "from" file (horror!) we lock it during the remove.
6602 *
6603 * When used for making a backup before writing the file: This should not
6604 * happen with ":w", because startscript() should detect this problem and
6605 * set buf->b_shortname, causing modname() to return a correct ".bak" file
6606 * name. This problem does exist with ":w filename", but then the
6607 * original file will be somewhere else so the backup isn't really
6608 * important. If autoscripting is off the rename may fail.
6609 */
6610 flock = Lock((UBYTE *)from, (long)ACCESS_READ);
6611#endif
6612 mch_remove(to);
6613#ifdef AMIGA
6614 if (flock)
6615 UnLock(flock);
6616#endif
6617
6618 /*
6619 * First try a normal rename, return if it works.
6620 */
6621 if (mch_rename((char *)from, (char *)to) == 0)
6622 return 0;
6623
6624 /*
6625 * Rename() failed, try copying the file.
6626 */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006627 perm = mch_getperm(from);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006628#ifdef HAVE_ACL
6629 /* For systems that support ACL: get the ACL from the original file. */
6630 acl = mch_get_acl(from);
6631#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006632 fd_in = mch_open((char *)from, O_RDONLY|O_EXTRA, 0);
6633 if (fd_in == -1)
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006634 {
6635#ifdef HAVE_ACL
6636 mch_free_acl(acl);
6637#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006638 return -1;
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006639 }
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006640
6641 /* Create the new file with same permissions as the original. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00006642 fd_out = mch_open((char *)to,
6643 O_CREAT|O_EXCL|O_WRONLY|O_EXTRA|O_NOFOLLOW, (int)perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006644 if (fd_out == -1)
6645 {
6646 close(fd_in);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006647#ifdef HAVE_ACL
6648 mch_free_acl(acl);
6649#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006650 return -1;
6651 }
6652
6653 buffer = (char *)alloc(BUFSIZE);
6654 if (buffer == NULL)
6655 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006656 close(fd_out);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006657 close(fd_in);
6658#ifdef HAVE_ACL
6659 mch_free_acl(acl);
6660#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006661 return -1;
6662 }
6663
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01006664 while ((n = read_eintr(fd_in, buffer, BUFSIZE)) > 0)
6665 if (write_eintr(fd_out, buffer, n) != n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006666 {
6667 errmsg = _("E208: Error writing to \"%s\"");
6668 break;
6669 }
6670
6671 vim_free(buffer);
6672 close(fd_in);
6673 if (close(fd_out) < 0)
6674 errmsg = _("E209: Error closing \"%s\"");
6675 if (n < 0)
6676 {
6677 errmsg = _("E210: Error reading \"%s\"");
6678 to = from;
6679 }
Bram Moolenaar7263a772007-05-10 17:35:54 +00006680#ifndef UNIX /* for Unix mch_open() already set the permission */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006681 mch_setperm(to, perm);
Bram Moolenaarc6039d82005-12-02 00:44:04 +00006682#endif
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006683#ifdef HAVE_ACL
6684 mch_set_acl(to, acl);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006685 mch_free_acl(acl);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006686#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006687 if (errmsg != NULL)
6688 {
6689 EMSG2(errmsg, to);
6690 return -1;
6691 }
6692 mch_remove(from);
6693 return 0;
6694}
6695
6696static int already_warned = FALSE;
6697
6698/*
6699 * Check if any not hidden buffer has been changed.
6700 * Postpone the check if there are characters in the stuff buffer, a global
6701 * command is being executed, a mapping is being executed or an autocommand is
6702 * busy.
6703 * Returns TRUE if some message was written (screen should be redrawn and
6704 * cursor positioned).
6705 */
6706 int
6707check_timestamps(focus)
6708 int focus; /* called for GUI focus event */
6709{
6710 buf_T *buf;
6711 int didit = 0;
6712 int n;
6713
6714 /* Don't check timestamps while system() or another low-level function may
6715 * cause us to lose and gain focus. */
6716 if (no_check_timestamps > 0)
6717 return FALSE;
6718
6719 /* Avoid doing a check twice. The OK/Reload dialog can cause a focus
6720 * event and we would keep on checking if the file is steadily growing.
6721 * Do check again after typing something. */
6722 if (focus && did_check_timestamps)
6723 {
6724 need_check_timestamps = TRUE;
6725 return FALSE;
6726 }
6727
6728 if (!stuff_empty() || global_busy || !typebuf_typed()
6729#ifdef FEAT_AUTOCMD
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006730 || autocmd_busy || curbuf_lock > 0 || allbuf_lock > 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00006731#endif
6732 )
6733 need_check_timestamps = TRUE; /* check later */
6734 else
6735 {
6736 ++no_wait_return;
6737 did_check_timestamps = TRUE;
6738 already_warned = FALSE;
6739 for (buf = firstbuf; buf != NULL; )
6740 {
6741 /* Only check buffers in a window. */
6742 if (buf->b_nwindows > 0)
6743 {
6744 n = buf_check_timestamp(buf, focus);
6745 if (didit < n)
6746 didit = n;
6747 if (n > 0 && !buf_valid(buf))
6748 {
6749 /* Autocommands have removed the buffer, start at the
6750 * first one again. */
6751 buf = firstbuf;
6752 continue;
6753 }
6754 }
6755 buf = buf->b_next;
6756 }
6757 --no_wait_return;
6758 need_check_timestamps = FALSE;
6759 if (need_wait_return && didit == 2)
6760 {
6761 /* make sure msg isn't overwritten */
6762 msg_puts((char_u *)"\n");
6763 out_flush();
6764 }
6765 }
6766 return didit;
6767}
6768
6769/*
6770 * Move all the lines from buffer "frombuf" to buffer "tobuf".
6771 * Return OK or FAIL. When FAIL "tobuf" is incomplete and/or "frombuf" is not
6772 * empty.
6773 */
6774 static int
6775move_lines(frombuf, tobuf)
6776 buf_T *frombuf;
6777 buf_T *tobuf;
6778{
6779 buf_T *tbuf = curbuf;
6780 int retval = OK;
6781 linenr_T lnum;
6782 char_u *p;
6783
6784 /* Copy the lines in "frombuf" to "tobuf". */
6785 curbuf = tobuf;
6786 for (lnum = 1; lnum <= frombuf->b_ml.ml_line_count; ++lnum)
6787 {
6788 p = vim_strsave(ml_get_buf(frombuf, lnum, FALSE));
6789 if (p == NULL || ml_append(lnum - 1, p, 0, FALSE) == FAIL)
6790 {
6791 vim_free(p);
6792 retval = FAIL;
6793 break;
6794 }
6795 vim_free(p);
6796 }
6797
6798 /* Delete all the lines in "frombuf". */
6799 if (retval != FAIL)
6800 {
6801 curbuf = frombuf;
Bram Moolenaar9460b9d2007-01-09 14:37:01 +00006802 for (lnum = curbuf->b_ml.ml_line_count; lnum > 0; --lnum)
6803 if (ml_delete(lnum, FALSE) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006804 {
6805 /* Oops! We could try putting back the saved lines, but that
6806 * might fail again... */
6807 retval = FAIL;
6808 break;
6809 }
6810 }
6811
6812 curbuf = tbuf;
6813 return retval;
6814}
6815
6816/*
6817 * Check if buffer "buf" has been changed.
6818 * Also check if the file for a new buffer unexpectedly appeared.
6819 * return 1 if a changed buffer was found.
6820 * return 2 if a message has been displayed.
6821 * return 0 otherwise.
6822 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006823 int
6824buf_check_timestamp(buf, focus)
6825 buf_T *buf;
Bram Moolenaar78a15312009-05-15 19:33:18 +00006826 int focus UNUSED; /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006827{
6828 struct stat st;
6829 int stat_res;
6830 int retval = 0;
6831 char_u *path;
6832 char_u *tbuf;
6833 char *mesg = NULL;
Bram Moolenaar44ecf652005-03-07 23:09:59 +00006834 char *mesg2 = "";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006835 int helpmesg = FALSE;
6836 int reload = FALSE;
6837#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6838 int can_reload = FALSE;
6839#endif
Bram Moolenaar914703b2010-05-31 21:59:46 +02006840 off_t orig_size = buf->b_orig_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006841 int orig_mode = buf->b_orig_mode;
6842#ifdef FEAT_GUI
6843 int save_mouse_correct = need_mouse_correct;
6844#endif
6845#ifdef FEAT_AUTOCMD
6846 static int busy = FALSE;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006847 int n;
6848 char_u *s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006849#endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006850 char *reason;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006851
6852 /* If there is no file name, the buffer is not loaded, 'buftype' is
6853 * set, we are in the middle of a save or being called recursively: ignore
6854 * this buffer. */
6855 if (buf->b_ffname == NULL
6856 || buf->b_ml.ml_mfp == NULL
6857#if defined(FEAT_QUICKFIX)
6858 || *buf->b_p_bt != NUL
6859#endif
6860 || buf->b_saving
6861#ifdef FEAT_AUTOCMD
6862 || busy
6863#endif
Bram Moolenaar009b2592004-10-24 19:18:58 +00006864#ifdef FEAT_NETBEANS_INTG
6865 || isNetbeansBuffer(buf)
6866#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006867 )
6868 return 0;
6869
6870 if ( !(buf->b_flags & BF_NOTEDITED)
6871 && buf->b_mtime != 0
6872 && ((stat_res = mch_stat((char *)buf->b_ffname, &st)) < 0
6873 || time_differs((long)st.st_mtime, buf->b_mtime)
6874#ifdef HAVE_ST_MODE
6875 || (int)st.st_mode != buf->b_orig_mode
6876#else
6877 || mch_getperm(buf->b_ffname) != buf->b_orig_mode
6878#endif
6879 ))
6880 {
6881 retval = 1;
6882
Bram Moolenaar316059c2006-01-14 21:18:42 +00006883 /* set b_mtime to stop further warnings (e.g., when executing
6884 * FileChangedShell autocmd) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006885 if (stat_res < 0)
6886 {
6887 buf->b_mtime = 0;
6888 buf->b_orig_size = 0;
6889 buf->b_orig_mode = 0;
6890 }
6891 else
6892 buf_store_time(buf, &st, buf->b_ffname);
6893
6894 /* Don't do anything for a directory. Might contain the file
6895 * explorer. */
6896 if (mch_isdir(buf->b_fname))
6897 ;
6898
6899 /*
6900 * If 'autoread' is set, the buffer has no changes and the file still
6901 * exists, reload the buffer. Use the buffer-local option value if it
6902 * was set, the global option value otherwise.
6903 */
6904 else if ((buf->b_p_ar >= 0 ? buf->b_p_ar : p_ar)
6905 && !bufIsChanged(buf) && stat_res >= 0)
6906 reload = TRUE;
6907 else
6908 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006909 if (stat_res < 0)
6910 reason = "deleted";
6911 else if (bufIsChanged(buf))
6912 reason = "conflict";
6913 else if (orig_size != buf->b_orig_size || buf_contents_changed(buf))
6914 reason = "changed";
6915 else if (orig_mode != buf->b_orig_mode)
6916 reason = "mode";
6917 else
6918 reason = "time";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006919
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006920#ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006921 /*
6922 * Only give the warning if there are no FileChangedShell
6923 * autocommands.
6924 * Avoid being called recursively by setting "busy".
6925 */
6926 busy = TRUE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00006927# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006928 set_vim_var_string(VV_FCS_REASON, (char_u *)reason, -1);
6929 set_vim_var_string(VV_FCS_CHOICE, (char_u *)"", -1);
Bram Moolenaar1e015462005-09-25 22:16:38 +00006930# endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006931 ++allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006932 n = apply_autocmds(EVENT_FILECHANGEDSHELL,
6933 buf->b_fname, buf->b_fname, FALSE, buf);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006934 --allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006935 busy = FALSE;
6936 if (n)
6937 {
6938 if (!buf_valid(buf))
6939 EMSG(_("E246: FileChangedShell autocommand deleted buffer"));
Bram Moolenaar1e015462005-09-25 22:16:38 +00006940# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006941 s = get_vim_var_str(VV_FCS_CHOICE);
6942 if (STRCMP(s, "reload") == 0 && *reason != 'd')
6943 reload = TRUE;
6944 else if (STRCMP(s, "ask") == 0)
6945 n = FALSE;
6946 else
Bram Moolenaar1e015462005-09-25 22:16:38 +00006947# endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006948 return 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006949 }
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006950 if (!n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006951#endif
6952 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006953 if (*reason == 'd')
6954 mesg = _("E211: File \"%s\" no longer available");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006955 else
6956 {
6957 helpmesg = TRUE;
6958#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6959 can_reload = TRUE;
6960#endif
6961 /*
6962 * Check if the file contents really changed to avoid
6963 * giving a warning when only the timestamp was set (e.g.,
6964 * checked out of CVS). Always warn when the buffer was
6965 * changed.
6966 */
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006967 if (reason[2] == 'n')
6968 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006969 mesg = _("W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006970 mesg2 = _("See \":help W12\" for more info.");
6971 }
6972 else if (reason[1] == 'h')
6973 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006974 mesg = _("W11: Warning: File \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006975 mesg2 = _("See \":help W11\" for more info.");
6976 }
6977 else if (*reason == 'm')
6978 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006979 mesg = _("W16: Warning: Mode of file \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006980 mesg2 = _("See \":help W16\" for more info.");
6981 }
Bram Moolenaar85388b52009-06-24 09:58:32 +00006982 else
6983 /* Only timestamp changed, store it to avoid a warning
6984 * in check_mtime() later. */
6985 buf->b_mtime_read = buf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006986 }
6987 }
6988 }
6989
6990 }
6991 else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W)
6992 && vim_fexists(buf->b_ffname))
6993 {
6994 retval = 1;
6995 mesg = _("W13: Warning: File \"%s\" has been created after editing started");
6996 buf->b_flags |= BF_NEW_W;
6997#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6998 can_reload = TRUE;
6999#endif
7000 }
7001
7002 if (mesg != NULL)
7003 {
7004 path = home_replace_save(buf, buf->b_fname);
7005 if (path != NULL)
7006 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007007 if (!helpmesg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007008 mesg2 = "";
7009 tbuf = alloc((unsigned)(STRLEN(path) + STRLEN(mesg)
7010 + STRLEN(mesg2) + 2));
7011 sprintf((char *)tbuf, mesg, path);
Bram Moolenaar496c5262009-03-18 14:42:00 +00007012#ifdef FEAT_EVAL
7013 /* Set warningmsg here, before the unimportant and output-specific
7014 * mesg2 has been appended. */
7015 set_vim_var_string(VV_WARNINGMSG, tbuf, -1);
7016#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007017#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
7018 if (can_reload)
7019 {
7020 if (*mesg2 != NUL)
7021 {
7022 STRCAT(tbuf, "\n");
7023 STRCAT(tbuf, mesg2);
7024 }
7025 if (do_dialog(VIM_WARNING, (char_u *)_("Warning"), tbuf,
Bram Moolenaard2c340a2011-01-17 20:08:11 +01007026 (char_u *)_("&OK\n&Load File"), 1, NULL, TRUE) == 2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007027 reload = TRUE;
7028 }
7029 else
7030#endif
7031 if (State > NORMAL_BUSY || (State & CMDLINE) || already_warned)
7032 {
7033 if (*mesg2 != NUL)
7034 {
7035 STRCAT(tbuf, "; ");
7036 STRCAT(tbuf, mesg2);
7037 }
7038 EMSG(tbuf);
7039 retval = 2;
7040 }
7041 else
7042 {
Bram Moolenaared203462004-06-16 11:19:22 +00007043# ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00007044 if (!autocmd_busy)
Bram Moolenaared203462004-06-16 11:19:22 +00007045# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007046 {
7047 msg_start();
7048 msg_puts_attr(tbuf, hl_attr(HLF_E) + MSG_HIST);
7049 if (*mesg2 != NUL)
7050 msg_puts_attr((char_u *)mesg2,
7051 hl_attr(HLF_W) + MSG_HIST);
7052 msg_clr_eos();
7053 (void)msg_end();
7054 if (emsg_silent == 0)
7055 {
7056 out_flush();
Bram Moolenaared203462004-06-16 11:19:22 +00007057# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00007058 if (!focus)
Bram Moolenaared203462004-06-16 11:19:22 +00007059# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007060 /* give the user some time to think about it */
7061 ui_delay(1000L, TRUE);
7062
7063 /* don't redraw and erase the message */
7064 redraw_cmdline = FALSE;
7065 }
7066 }
7067 already_warned = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007068 }
7069
7070 vim_free(path);
7071 vim_free(tbuf);
7072 }
7073 }
7074
7075 if (reload)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007076 /* Reload the buffer. */
Bram Moolenaar316059c2006-01-14 21:18:42 +00007077 buf_reload(buf, orig_mode);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007078
Bram Moolenaar56718732006-03-15 22:53:57 +00007079#ifdef FEAT_AUTOCMD
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00007080 /* Trigger FileChangedShell when the file was changed in any way. */
7081 if (buf_valid(buf) && retval != 0)
Bram Moolenaar56718732006-03-15 22:53:57 +00007082 (void)apply_autocmds(EVENT_FILECHANGEDSHELLPOST,
7083 buf->b_fname, buf->b_fname, FALSE, buf);
7084#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007085#ifdef FEAT_GUI
7086 /* restore this in case an autocommand has set it; it would break
7087 * 'mousefocus' */
7088 need_mouse_correct = save_mouse_correct;
7089#endif
7090
7091 return retval;
7092}
7093
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007094/*
7095 * Reload a buffer that is already loaded.
7096 * Used when the file was changed outside of Vim.
Bram Moolenaar316059c2006-01-14 21:18:42 +00007097 * "orig_mode" is buf->b_orig_mode before the need for reloading was detected.
7098 * buf->b_orig_mode may have been reset already.
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007099 */
7100 void
Bram Moolenaar316059c2006-01-14 21:18:42 +00007101buf_reload(buf, orig_mode)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007102 buf_T *buf;
Bram Moolenaar316059c2006-01-14 21:18:42 +00007103 int orig_mode;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007104{
7105 exarg_T ea;
7106 pos_T old_cursor;
7107 linenr_T old_topline;
7108 int old_ro = buf->b_p_ro;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007109 buf_T *savebuf;
7110 int saved = OK;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007111 aco_save_T aco;
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007112 int flags = READ_NEW;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007113
7114 /* set curwin/curbuf for "buf" and save some things */
7115 aucmd_prepbuf(&aco, buf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007116
7117 /* We only want to read the text from the file, not reset the syntax
7118 * highlighting, clear marks, diff status, etc. Force the fileformat
7119 * and encoding to be the same. */
7120 if (prep_exarg(&ea, buf) == OK)
7121 {
7122 old_cursor = curwin->w_cursor;
7123 old_topline = curwin->w_topline;
7124
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007125 if (p_ur < 0 || curbuf->b_ml.ml_line_count <= p_ur)
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007126 {
7127 /* Save all the text, so that the reload can be undone.
7128 * Sync first so that this is a separate undo-able action. */
7129 u_sync(FALSE);
7130 saved = u_savecommon(0, curbuf->b_ml.ml_line_count + 1, 0, TRUE);
7131 flags |= READ_KEEP_UNDO;
7132 }
7133
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007134 /*
7135 * To behave like when a new file is edited (matters for
7136 * BufReadPost autocommands) we first need to delete the current
7137 * buffer contents. But if reading the file fails we should keep
7138 * the old contents. Can't use memory only, the file might be
7139 * too big. Use a hidden buffer to move the buffer contents to.
7140 */
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007141 if (bufempty() || saved == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007142 savebuf = NULL;
7143 else
7144 {
7145 /* Allocate a buffer without putting it in the buffer list. */
7146 savebuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007147 if (savebuf != NULL && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007148 {
7149 /* Open the memline. */
7150 curbuf = savebuf;
7151 curwin->w_buffer = savebuf;
Bram Moolenaar4770d092006-01-12 23:22:24 +00007152 saved = ml_open(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007153 curbuf = buf;
7154 curwin->w_buffer = buf;
7155 }
Bram Moolenaar8424a622006-04-19 21:23:36 +00007156 if (savebuf == NULL || saved == FAIL || buf != curbuf
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007157 || move_lines(buf, savebuf) == FAIL)
7158 {
7159 EMSG2(_("E462: Could not prepare for reloading \"%s\""),
7160 buf->b_fname);
7161 saved = FAIL;
7162 }
7163 }
7164
7165 if (saved == OK)
7166 {
7167 curbuf->b_flags |= BF_CHECK_RO; /* check for RO again */
7168#ifdef FEAT_AUTOCMD
7169 keep_filetype = TRUE; /* don't detect 'filetype' */
7170#endif
7171 if (readfile(buf->b_ffname, buf->b_fname, (linenr_T)0,
7172 (linenr_T)0,
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007173 (linenr_T)MAXLNUM, &ea, flags) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007174 {
7175#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
7176 if (!aborting())
7177#endif
7178 EMSG2(_("E321: Could not reload \"%s\""), buf->b_fname);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007179 if (savebuf != NULL && buf_valid(savebuf) && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007180 {
7181 /* Put the text back from the save buffer. First
7182 * delete any lines that readfile() added. */
7183 while (!bufempty())
Bram Moolenaar8424a622006-04-19 21:23:36 +00007184 if (ml_delete(buf->b_ml.ml_line_count, FALSE) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007185 break;
7186 (void)move_lines(savebuf, buf);
7187 }
7188 }
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007189 else if (buf == curbuf) /* "buf" still valid */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007190 {
7191 /* Mark the buffer as unmodified and free undo info. */
7192 unchanged(buf, TRUE);
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007193 if ((flags & READ_KEEP_UNDO) == 0)
7194 {
7195 u_blockfree(buf);
7196 u_clearall(buf);
7197 }
7198 else
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007199 {
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007200 /* Mark all undo states as changed. */
7201 u_unchanged(curbuf);
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007202 }
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007203 }
7204 }
7205 vim_free(ea.cmd);
7206
Bram Moolenaar8424a622006-04-19 21:23:36 +00007207 if (savebuf != NULL && buf_valid(savebuf))
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007208 wipe_buffer(savebuf, FALSE);
7209
7210#ifdef FEAT_DIFF
7211 /* Invalidate diff info if necessary. */
Bram Moolenaar8424a622006-04-19 21:23:36 +00007212 diff_invalidate(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007213#endif
7214
7215 /* Restore the topline and cursor position and check it (lines may
7216 * have been removed). */
7217 if (old_topline > curbuf->b_ml.ml_line_count)
7218 curwin->w_topline = curbuf->b_ml.ml_line_count;
7219 else
7220 curwin->w_topline = old_topline;
7221 curwin->w_cursor = old_cursor;
7222 check_cursor();
7223 update_topline();
7224#ifdef FEAT_AUTOCMD
7225 keep_filetype = FALSE;
7226#endif
7227#ifdef FEAT_FOLDING
7228 {
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007229 win_T *wp;
7230 tabpage_T *tp;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007231
7232 /* Update folds unless they are defined manually. */
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007233 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007234 if (wp->w_buffer == curwin->w_buffer
7235 && !foldmethodIsManual(wp))
7236 foldUpdateAll(wp);
7237 }
7238#endif
7239 /* If the mode didn't change and 'readonly' was set, keep the old
7240 * value; the user probably used the ":view" command. But don't
7241 * reset it, might have had a read error. */
7242 if (orig_mode == curbuf->b_orig_mode)
7243 curbuf->b_p_ro |= old_ro;
7244 }
7245
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007246 /* restore curwin/curbuf and a few other things */
7247 aucmd_restbuf(&aco);
7248 /* Careful: autocommands may have made "buf" invalid! */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007249}
7250
Bram Moolenaar071d4272004-06-13 20:20:40 +00007251 void
7252buf_store_time(buf, st, fname)
7253 buf_T *buf;
7254 struct stat *st;
Bram Moolenaar78a15312009-05-15 19:33:18 +00007255 char_u *fname UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007256{
7257 buf->b_mtime = (long)st->st_mtime;
Bram Moolenaar914703b2010-05-31 21:59:46 +02007258 buf->b_orig_size = st->st_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007259#ifdef HAVE_ST_MODE
7260 buf->b_orig_mode = (int)st->st_mode;
7261#else
7262 buf->b_orig_mode = mch_getperm(fname);
7263#endif
7264}
7265
7266/*
7267 * Adjust the line with missing eol, used for the next write.
7268 * Used for do_filter(), when the input lines for the filter are deleted.
7269 */
7270 void
7271write_lnum_adjust(offset)
7272 linenr_T offset;
7273{
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01007274 if (curbuf->b_no_eol_lnum != 0) /* only if there is a missing eol */
7275 curbuf->b_no_eol_lnum += offset;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007276}
7277
7278#if defined(TEMPDIRNAMES) || defined(PROTO)
7279static long temp_count = 0; /* Temp filename counter. */
7280
7281/*
7282 * Delete the temp directory and all files it contains.
7283 */
7284 void
7285vim_deltempdir()
7286{
7287 char_u **files;
7288 int file_count;
7289 int i;
7290
7291 if (vim_tempdir != NULL)
7292 {
7293 sprintf((char *)NameBuff, "%s*", vim_tempdir);
7294 if (gen_expand_wildcards(1, &NameBuff, &file_count, &files,
7295 EW_DIR|EW_FILE|EW_SILENT) == OK)
7296 {
7297 for (i = 0; i < file_count; ++i)
7298 mch_remove(files[i]);
7299 FreeWild(file_count, files);
7300 }
7301 gettail(NameBuff)[-1] = NUL;
7302 (void)mch_rmdir(NameBuff);
7303
7304 vim_free(vim_tempdir);
7305 vim_tempdir = NULL;
7306 }
7307}
7308#endif
7309
Bram Moolenaar4592dee2009-11-18 19:11:58 +00007310#ifdef TEMPDIRNAMES
Bram Moolenaar071d4272004-06-13 20:20:40 +00007311/*
Bram Moolenaareaf03392009-11-17 11:08:52 +00007312 * Directory "tempdir" was created. Expand this name to a full path and put
7313 * it in "vim_tempdir". This avoids that using ":cd" would confuse us.
7314 * "tempdir" must be no longer than MAXPATHL.
7315 */
7316 static void
7317vim_settempdir(tempdir)
7318 char_u *tempdir;
7319{
7320 char_u *buf;
7321
7322 buf = alloc((unsigned)MAXPATHL + 2);
7323 if (buf != NULL)
7324 {
7325 if (vim_FullName(tempdir, buf, MAXPATHL, FALSE) == FAIL)
7326 STRCPY(buf, tempdir);
7327# ifdef __EMX__
7328 if (vim_strchr(buf, '/') != NULL)
7329 STRCAT(buf, "/");
7330 else
7331# endif
7332 add_pathsep(buf);
7333 vim_tempdir = vim_strsave(buf);
7334 vim_free(buf);
7335 }
7336}
Bram Moolenaar4592dee2009-11-18 19:11:58 +00007337#endif
Bram Moolenaareaf03392009-11-17 11:08:52 +00007338
7339/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007340 * vim_tempname(): Return a unique name that can be used for a temp file.
7341 *
7342 * The temp file is NOT created.
7343 *
7344 * The returned pointer is to allocated memory.
7345 * The returned pointer is NULL if no valid name was found.
7346 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007347 char_u *
7348vim_tempname(extra_char)
Bram Moolenaar78a15312009-05-15 19:33:18 +00007349 int extra_char UNUSED; /* char to use in the name instead of '?' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007350{
7351#ifdef USE_TMPNAM
7352 char_u itmp[L_tmpnam]; /* use tmpnam() */
7353#else
7354 char_u itmp[TEMPNAMELEN];
7355#endif
7356
7357#ifdef TEMPDIRNAMES
7358 static char *(tempdirs[]) = {TEMPDIRNAMES};
7359 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007360# ifndef EEXIST
7361 struct stat st;
7362# endif
7363
7364 /*
7365 * This will create a directory for private use by this instance of Vim.
7366 * This is done once, and the same directory is used for all temp files.
7367 * This method avoids security problems because of symlink attacks et al.
7368 * It's also a bit faster, because we only need to check for an existing
7369 * file when creating the directory and not for each temp file.
7370 */
7371 if (vim_tempdir == NULL)
7372 {
7373 /*
7374 * Try the entries in TEMPDIRNAMES to create the temp directory.
7375 */
Bram Moolenaar78a15312009-05-15 19:33:18 +00007376 for (i = 0; i < (int)(sizeof(tempdirs) / sizeof(char *)); ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007377 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007378# ifndef HAVE_MKDTEMP
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007379 size_t itmplen;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007380 long nr;
7381 long off;
7382# endif
7383
Bram Moolenaar071d4272004-06-13 20:20:40 +00007384 /* expand $TMP, leave room for "/v1100000/999999999" */
7385 expand_env((char_u *)tempdirs[i], itmp, TEMPNAMELEN - 20);
7386 if (mch_isdir(itmp)) /* directory exists */
7387 {
7388# ifdef __EMX__
7389 /* If $TMP contains a forward slash (perhaps using bash or
7390 * tcsh), don't add a backslash, use a forward slash!
7391 * Adding 2 backslashes didn't work. */
7392 if (vim_strchr(itmp, '/') != NULL)
7393 STRCAT(itmp, "/");
7394 else
7395# endif
7396 add_pathsep(itmp);
7397
Bram Moolenaareaf03392009-11-17 11:08:52 +00007398# ifdef HAVE_MKDTEMP
7399 /* Leave room for filename */
7400 STRCAT(itmp, "vXXXXXX");
7401 if (mkdtemp((char *)itmp) != NULL)
7402 vim_settempdir(itmp);
7403# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007404 /* Get an arbitrary number of up to 6 digits. When it's
7405 * unlikely that it already exists it will be faster,
7406 * otherwise it doesn't matter. The use of mkdir() avoids any
7407 * security problems because of the predictable number. */
7408 nr = (mch_get_pid() + (long)time(NULL)) % 1000000L;
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007409 itmplen = STRLEN(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007410
7411 /* Try up to 10000 different values until we find a name that
7412 * doesn't exist. */
7413 for (off = 0; off < 10000L; ++off)
7414 {
7415 int r;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007416# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007417 mode_t umask_save;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007418# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007419
Bram Moolenaareaf03392009-11-17 11:08:52 +00007420 sprintf((char *)itmp + itmplen, "v%ld", nr + off);
7421# ifndef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007422 /* If mkdir() does not set errno to EEXIST, check for
7423 * existing file here. There is a race condition then,
7424 * although it's fail-safe. */
7425 if (mch_stat((char *)itmp, &st) >= 0)
7426 continue;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007427# endif
7428# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007429 /* Make sure the umask doesn't remove the executable bit.
7430 * "repl" has been reported to use "177". */
7431 umask_save = umask(077);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007432# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007433 r = vim_mkdir(itmp, 0700);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007434# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007435 (void)umask(umask_save);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007436# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007437 if (r == 0)
7438 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007439 vim_settempdir(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007440 break;
7441 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007442# ifdef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007443 /* If the mkdir() didn't fail because the file/dir exists,
7444 * we probably can't create any dir here, try another
7445 * place. */
7446 if (errno != EEXIST)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007447# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007448 break;
7449 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007450# endif /* HAVE_MKDTEMP */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007451 if (vim_tempdir != NULL)
7452 break;
7453 }
7454 }
7455 }
7456
7457 if (vim_tempdir != NULL)
7458 {
7459 /* There is no need to check if the file exists, because we own the
7460 * directory and nobody else creates a file in it. */
7461 sprintf((char *)itmp, "%s%ld", vim_tempdir, temp_count++);
7462 return vim_strsave(itmp);
7463 }
7464
7465 return NULL;
7466
7467#else /* TEMPDIRNAMES */
7468
7469# ifdef WIN3264
7470 char szTempFile[_MAX_PATH + 1];
7471 char buf4[4];
7472 char_u *retval;
7473 char_u *p;
7474
7475 STRCPY(itmp, "");
7476 if (GetTempPath(_MAX_PATH, szTempFile) == 0)
Bram Moolenaarb1891912011-02-09 14:47:03 +01007477 {
7478 szTempFile[0] = '.'; /* GetTempPath() failed, use current dir */
7479 szTempFile[1] = NUL;
7480 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007481 strcpy(buf4, "VIM");
7482 buf4[2] = extra_char; /* make it "VIa", "VIb", etc. */
7483 if (GetTempFileName(szTempFile, buf4, 0, itmp) == 0)
7484 return NULL;
7485 /* GetTempFileName() will create the file, we don't want that */
7486 (void)DeleteFile(itmp);
7487
7488 /* Backslashes in a temp file name cause problems when filtering with
7489 * "sh". NOTE: This also checks 'shellcmdflag' to help those people who
7490 * didn't set 'shellslash'. */
7491 retval = vim_strsave(itmp);
7492 if (*p_shcf == '-' || p_ssl)
7493 for (p = retval; *p; ++p)
7494 if (*p == '\\')
7495 *p = '/';
7496 return retval;
7497
7498# else /* WIN3264 */
7499
7500# ifdef USE_TMPNAM
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007501 char_u *p;
7502
Bram Moolenaar071d4272004-06-13 20:20:40 +00007503 /* tmpnam() will make its own name */
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007504 p = tmpnam((char *)itmp);
7505 if (p == NULL || *p == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007506 return NULL;
7507# else
7508 char_u *p;
7509
7510# ifdef VMS_TEMPNAM
7511 /* mktemp() is not working on VMS. It seems to be
7512 * a do-nothing function. Therefore we use tempnam().
7513 */
7514 sprintf((char *)itmp, "VIM%c", extra_char);
7515 p = (char_u *)tempnam("tmp:", (char *)itmp);
7516 if (p != NULL)
7517 {
7518 /* VMS will use '.LOG' if we don't explicitly specify an extension,
7519 * and VIM will then be unable to find the file later */
7520 STRCPY(itmp, p);
7521 STRCAT(itmp, ".txt");
7522 free(p);
7523 }
7524 else
7525 return NULL;
7526# else
7527 STRCPY(itmp, TEMPNAME);
7528 if ((p = vim_strchr(itmp, '?')) != NULL)
7529 *p = extra_char;
7530 if (mktemp((char *)itmp) == NULL)
7531 return NULL;
7532# endif
7533# endif
7534
7535 return vim_strsave(itmp);
7536# endif /* WIN3264 */
7537#endif /* TEMPDIRNAMES */
7538}
7539
7540#if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
7541/*
7542 * Convert all backslashes in fname to forward slashes in-place.
7543 */
7544 void
7545forward_slash(fname)
7546 char_u *fname;
7547{
7548 char_u *p;
7549
7550 for (p = fname; *p != NUL; ++p)
7551# ifdef FEAT_MBYTE
7552 /* The Big5 encoding can have '\' in the trail byte. */
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00007553 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007554 ++p;
7555 else
7556# endif
7557 if (*p == '\\')
7558 *p = '/';
7559}
7560#endif
7561
7562
7563/*
7564 * Code for automatic commands.
7565 *
7566 * Only included when "FEAT_AUTOCMD" has been defined.
7567 */
7568
7569#if defined(FEAT_AUTOCMD) || defined(PROTO)
7570
7571/*
7572 * The autocommands are stored in a list for each event.
7573 * Autocommands for the same pattern, that are consecutive, are joined
7574 * together, to avoid having to match the pattern too often.
7575 * The result is an array of Autopat lists, which point to AutoCmd lists:
7576 *
7577 * first_autopat[0] --> Autopat.next --> Autopat.next --> NULL
7578 * Autopat.cmds Autopat.cmds
7579 * | |
7580 * V V
7581 * AutoCmd.next AutoCmd.next
7582 * | |
7583 * V V
7584 * AutoCmd.next NULL
7585 * |
7586 * V
7587 * NULL
7588 *
7589 * first_autopat[1] --> Autopat.next --> NULL
7590 * Autopat.cmds
7591 * |
7592 * V
7593 * AutoCmd.next
7594 * |
7595 * V
7596 * NULL
7597 * etc.
7598 *
7599 * The order of AutoCmds is important, this is the order in which they were
7600 * defined and will have to be executed.
7601 */
7602typedef struct AutoCmd
7603{
7604 char_u *cmd; /* The command to be executed (NULL
7605 when command has been removed) */
7606 char nested; /* If autocommands nest here */
7607 char last; /* last command in list */
7608#ifdef FEAT_EVAL
7609 scid_T scriptID; /* script ID where defined */
7610#endif
7611 struct AutoCmd *next; /* Next AutoCmd in list */
7612} AutoCmd;
7613
7614typedef struct AutoPat
7615{
7616 int group; /* group ID */
7617 char_u *pat; /* pattern as typed (NULL when pattern
7618 has been removed) */
7619 int patlen; /* strlen() of pat */
Bram Moolenaar748bf032005-02-02 23:04:36 +00007620 regprog_T *reg_prog; /* compiled regprog for pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007621 char allow_dirs; /* Pattern may match whole path */
7622 char last; /* last pattern for apply_autocmds() */
7623 AutoCmd *cmds; /* list of commands to do */
7624 struct AutoPat *next; /* next AutoPat in AutoPat list */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007625 int buflocal_nr; /* !=0 for buffer-local AutoPat */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007626} AutoPat;
7627
7628static struct event_name
7629{
7630 char *name; /* event name */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007631 event_T event; /* event number */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007632} event_names[] =
7633{
7634 {"BufAdd", EVENT_BUFADD},
7635 {"BufCreate", EVENT_BUFADD},
7636 {"BufDelete", EVENT_BUFDELETE},
7637 {"BufEnter", EVENT_BUFENTER},
7638 {"BufFilePost", EVENT_BUFFILEPOST},
7639 {"BufFilePre", EVENT_BUFFILEPRE},
7640 {"BufHidden", EVENT_BUFHIDDEN},
7641 {"BufLeave", EVENT_BUFLEAVE},
7642 {"BufNew", EVENT_BUFNEW},
7643 {"BufNewFile", EVENT_BUFNEWFILE},
7644 {"BufRead", EVENT_BUFREADPOST},
7645 {"BufReadCmd", EVENT_BUFREADCMD},
7646 {"BufReadPost", EVENT_BUFREADPOST},
7647 {"BufReadPre", EVENT_BUFREADPRE},
7648 {"BufUnload", EVENT_BUFUNLOAD},
7649 {"BufWinEnter", EVENT_BUFWINENTER},
7650 {"BufWinLeave", EVENT_BUFWINLEAVE},
7651 {"BufWipeout", EVENT_BUFWIPEOUT},
7652 {"BufWrite", EVENT_BUFWRITEPRE},
7653 {"BufWritePost", EVENT_BUFWRITEPOST},
7654 {"BufWritePre", EVENT_BUFWRITEPRE},
7655 {"BufWriteCmd", EVENT_BUFWRITECMD},
7656 {"CmdwinEnter", EVENT_CMDWINENTER},
7657 {"CmdwinLeave", EVENT_CMDWINLEAVE},
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007658 {"ColorScheme", EVENT_COLORSCHEME},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007659 {"CursorHold", EVENT_CURSORHOLD},
7660 {"CursorHoldI", EVENT_CURSORHOLDI},
7661 {"CursorMoved", EVENT_CURSORMOVED},
7662 {"CursorMovedI", EVENT_CURSORMOVEDI},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007663 {"EncodingChanged", EVENT_ENCODINGCHANGED},
7664 {"FileEncoding", EVENT_ENCODINGCHANGED},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007665 {"FileAppendPost", EVENT_FILEAPPENDPOST},
7666 {"FileAppendPre", EVENT_FILEAPPENDPRE},
7667 {"FileAppendCmd", EVENT_FILEAPPENDCMD},
7668 {"FileChangedShell",EVENT_FILECHANGEDSHELL},
Bram Moolenaar56718732006-03-15 22:53:57 +00007669 {"FileChangedShellPost",EVENT_FILECHANGEDSHELLPOST},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007670 {"FileChangedRO", EVENT_FILECHANGEDRO},
7671 {"FileReadPost", EVENT_FILEREADPOST},
7672 {"FileReadPre", EVENT_FILEREADPRE},
7673 {"FileReadCmd", EVENT_FILEREADCMD},
7674 {"FileType", EVENT_FILETYPE},
7675 {"FileWritePost", EVENT_FILEWRITEPOST},
7676 {"FileWritePre", EVENT_FILEWRITEPRE},
7677 {"FileWriteCmd", EVENT_FILEWRITECMD},
7678 {"FilterReadPost", EVENT_FILTERREADPOST},
7679 {"FilterReadPre", EVENT_FILTERREADPRE},
7680 {"FilterWritePost", EVENT_FILTERWRITEPOST},
7681 {"FilterWritePre", EVENT_FILTERWRITEPRE},
7682 {"FocusGained", EVENT_FOCUSGAINED},
7683 {"FocusLost", EVENT_FOCUSLOST},
7684 {"FuncUndefined", EVENT_FUNCUNDEFINED},
7685 {"GUIEnter", EVENT_GUIENTER},
Bram Moolenaar265e5072006-08-29 16:13:22 +00007686 {"GUIFailed", EVENT_GUIFAILED},
Bram Moolenaar843ee412004-06-30 16:16:41 +00007687 {"InsertChange", EVENT_INSERTCHANGE},
7688 {"InsertEnter", EVENT_INSERTENTER},
7689 {"InsertLeave", EVENT_INSERTLEAVE},
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00007690 {"MenuPopup", EVENT_MENUPOPUP},
Bram Moolenaar7c626922005-02-07 22:01:03 +00007691 {"QuickFixCmdPost", EVENT_QUICKFIXCMDPOST},
7692 {"QuickFixCmdPre", EVENT_QUICKFIXCMDPRE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007693 {"RemoteReply", EVENT_REMOTEREPLY},
Bram Moolenaar9372a112005-12-06 19:59:18 +00007694 {"SessionLoadPost", EVENT_SESSIONLOADPOST},
Bram Moolenaar5c4bab02006-03-10 21:37:46 +00007695 {"ShellCmdPost", EVENT_SHELLCMDPOST},
7696 {"ShellFilterPost", EVENT_SHELLFILTERPOST},
Bram Moolenaara2031822006-03-07 22:29:51 +00007697 {"SourcePre", EVENT_SOURCEPRE},
Bram Moolenaar8dd1aa52007-01-16 20:33:19 +00007698 {"SourceCmd", EVENT_SOURCECMD},
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00007699 {"SpellFileMissing",EVENT_SPELLFILEMISSING},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007700 {"StdinReadPost", EVENT_STDINREADPOST},
7701 {"StdinReadPre", EVENT_STDINREADPRE},
Bram Moolenaarb815dac2005-12-07 20:59:24 +00007702 {"SwapExists", EVENT_SWAPEXISTS},
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00007703 {"Syntax", EVENT_SYNTAX},
Bram Moolenaar70836c82006-02-20 21:28:49 +00007704 {"TabEnter", EVENT_TABENTER},
7705 {"TabLeave", EVENT_TABLEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007706 {"TermChanged", EVENT_TERMCHANGED},
7707 {"TermResponse", EVENT_TERMRESPONSE},
7708 {"User", EVENT_USER},
7709 {"VimEnter", EVENT_VIMENTER},
7710 {"VimLeave", EVENT_VIMLEAVE},
7711 {"VimLeavePre", EVENT_VIMLEAVEPRE},
7712 {"WinEnter", EVENT_WINENTER},
7713 {"WinLeave", EVENT_WINLEAVE},
Bram Moolenaar56718732006-03-15 22:53:57 +00007714 {"VimResized", EVENT_VIMRESIZED},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007715 {NULL, (event_T)0}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007716};
7717
7718static AutoPat *first_autopat[NUM_EVENTS] =
7719{
7720 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7721 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7722 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7723 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00007724 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7725 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007726};
7727
7728/*
7729 * struct used to keep status while executing autocommands for an event.
7730 */
7731typedef struct AutoPatCmd
7732{
7733 AutoPat *curpat; /* next AutoPat to examine */
7734 AutoCmd *nextcmd; /* next AutoCmd to execute */
7735 int group; /* group being used */
7736 char_u *fname; /* fname to match with */
7737 char_u *sfname; /* sfname to match with */
7738 char_u *tail; /* tail of fname */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007739 event_T event; /* current event */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007740 int arg_bufnr; /* initially equal to <abuf>, set to zero when
7741 buf is deleted */
7742 struct AutoPatCmd *next; /* chain of active apc-s for auto-invalidation*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00007743} AutoPatCmd;
7744
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007745static AutoPatCmd *active_apc_list = NULL; /* stack of active autocommands */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007746
Bram Moolenaar071d4272004-06-13 20:20:40 +00007747/*
7748 * augroups stores a list of autocmd group names.
7749 */
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007750static garray_T augroups = {0, 0, sizeof(char_u *), 10, NULL};
Bram Moolenaar071d4272004-06-13 20:20:40 +00007751#define AUGROUP_NAME(i) (((char_u **)augroups.ga_data)[i])
7752
7753/*
7754 * The ID of the current group. Group 0 is the default one.
7755 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007756static int current_augroup = AUGROUP_DEFAULT;
7757
7758static int au_need_clean = FALSE; /* need to delete marked patterns */
7759
Bram Moolenaar754b5602006-02-09 23:53:20 +00007760static void show_autocmd __ARGS((AutoPat *ap, event_T event));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007761static void au_remove_pat __ARGS((AutoPat *ap));
7762static void au_remove_cmds __ARGS((AutoPat *ap));
7763static void au_cleanup __ARGS((void));
7764static int au_new_group __ARGS((char_u *name));
7765static void au_del_group __ARGS((char_u *name));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007766static event_T event_name2nr __ARGS((char_u *start, char_u **end));
7767static char_u *event_nr2name __ARGS((event_T event));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007768static char_u *find_end_event __ARGS((char_u *arg, int have_group));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007769static int event_ignored __ARGS((event_T event));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007770static int au_get_grouparg __ARGS((char_u **argp));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007771static int do_autocmd_event __ARGS((event_T event, char_u *pat, int nested, char_u *cmd, int forceit, int group));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007772static char_u *getnextac __ARGS((int c, void *cookie, int indent));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007773static 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 +00007774static void auto_next_pat __ARGS((AutoPatCmd *apc, int stop_at_last));
7775
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007776
Bram Moolenaar754b5602006-02-09 23:53:20 +00007777static event_T last_event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007778static int last_group;
Bram Moolenaar78ab3312007-09-29 12:16:41 +00007779static int autocmd_blocked = 0; /* block all autocmds */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007780
7781/*
7782 * Show the autocommands for one AutoPat.
7783 */
7784 static void
7785show_autocmd(ap, event)
7786 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007787 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007788{
7789 AutoCmd *ac;
7790
7791 /* Check for "got_int" (here and at various places below), which is set
7792 * when "q" has been hit for the "--more--" prompt */
7793 if (got_int)
7794 return;
7795 if (ap->pat == NULL) /* pattern has been removed */
7796 return;
7797
7798 msg_putchar('\n');
7799 if (got_int)
7800 return;
7801 if (event != last_event || ap->group != last_group)
7802 {
7803 if (ap->group != AUGROUP_DEFAULT)
7804 {
7805 if (AUGROUP_NAME(ap->group) == NULL)
7806 msg_puts_attr((char_u *)_("--Deleted--"), hl_attr(HLF_E));
7807 else
7808 msg_puts_attr(AUGROUP_NAME(ap->group), hl_attr(HLF_T));
7809 msg_puts((char_u *)" ");
7810 }
7811 msg_puts_attr(event_nr2name(event), hl_attr(HLF_T));
7812 last_event = event;
7813 last_group = ap->group;
7814 msg_putchar('\n');
7815 if (got_int)
7816 return;
7817 }
7818 msg_col = 4;
7819 msg_outtrans(ap->pat);
7820
7821 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7822 {
7823 if (ac->cmd != NULL) /* skip removed commands */
7824 {
7825 if (msg_col >= 14)
7826 msg_putchar('\n');
7827 msg_col = 14;
7828 if (got_int)
7829 return;
7830 msg_outtrans(ac->cmd);
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00007831#ifdef FEAT_EVAL
7832 if (p_verbose > 0)
7833 last_set_msg(ac->scriptID);
7834#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007835 if (got_int)
7836 return;
7837 if (ac->next != NULL)
7838 {
7839 msg_putchar('\n');
7840 if (got_int)
7841 return;
7842 }
7843 }
7844 }
7845}
7846
7847/*
7848 * Mark an autocommand pattern for deletion.
7849 */
7850 static void
7851au_remove_pat(ap)
7852 AutoPat *ap;
7853{
7854 vim_free(ap->pat);
7855 ap->pat = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007856 ap->buflocal_nr = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007857 au_need_clean = TRUE;
7858}
7859
7860/*
7861 * Mark all commands for a pattern for deletion.
7862 */
7863 static void
7864au_remove_cmds(ap)
7865 AutoPat *ap;
7866{
7867 AutoCmd *ac;
7868
7869 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7870 {
7871 vim_free(ac->cmd);
7872 ac->cmd = NULL;
7873 }
7874 au_need_clean = TRUE;
7875}
7876
7877/*
7878 * Cleanup autocommands and patterns that have been deleted.
7879 * This is only done when not executing autocommands.
7880 */
7881 static void
7882au_cleanup()
7883{
7884 AutoPat *ap, **prev_ap;
7885 AutoCmd *ac, **prev_ac;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007886 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007887
7888 if (autocmd_busy || !au_need_clean)
7889 return;
7890
7891 /* loop over all events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007892 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7893 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007894 {
7895 /* loop over all autocommand patterns */
7896 prev_ap = &(first_autopat[(int)event]);
7897 for (ap = *prev_ap; ap != NULL; ap = *prev_ap)
7898 {
7899 /* loop over all commands for this pattern */
7900 prev_ac = &(ap->cmds);
7901 for (ac = *prev_ac; ac != NULL; ac = *prev_ac)
7902 {
7903 /* remove the command if the pattern is to be deleted or when
7904 * the command has been marked for deletion */
7905 if (ap->pat == NULL || ac->cmd == NULL)
7906 {
7907 *prev_ac = ac->next;
7908 vim_free(ac->cmd);
7909 vim_free(ac);
7910 }
7911 else
7912 prev_ac = &(ac->next);
7913 }
7914
7915 /* remove the pattern if it has been marked for deletion */
7916 if (ap->pat == NULL)
7917 {
7918 *prev_ap = ap->next;
Bram Moolenaar748bf032005-02-02 23:04:36 +00007919 vim_free(ap->reg_prog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007920 vim_free(ap);
7921 }
7922 else
7923 prev_ap = &(ap->next);
7924 }
7925 }
7926
7927 au_need_clean = FALSE;
7928}
7929
7930/*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007931 * Called when buffer is freed, to remove/invalidate related buffer-local
7932 * autocmds.
7933 */
7934 void
7935aubuflocal_remove(buf)
7936 buf_T *buf;
7937{
7938 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007939 event_T event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007940 AutoPatCmd *apc;
7941
7942 /* invalidate currently executing autocommands */
7943 for (apc = active_apc_list; apc; apc = apc->next)
7944 if (buf->b_fnum == apc->arg_bufnr)
7945 apc->arg_bufnr = 0;
7946
7947 /* invalidate buflocals looping through events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007948 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7949 event = (event_T)((int)event + 1))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007950 /* loop over all autocommand patterns */
7951 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
7952 if (ap->buflocal_nr == buf->b_fnum)
7953 {
7954 au_remove_pat(ap);
7955 if (p_verbose >= 6)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007956 {
7957 verbose_enter();
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007958 smsg((char_u *)
7959 _("auto-removing autocommand: %s <buffer=%d>"),
7960 event_nr2name(event), buf->b_fnum);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007961 verbose_leave();
7962 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007963 }
7964 au_cleanup();
7965}
7966
7967/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007968 * Add an autocmd group name.
7969 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
7970 */
7971 static int
7972au_new_group(name)
7973 char_u *name;
7974{
7975 int i;
7976
7977 i = au_find_group(name);
7978 if (i == AUGROUP_ERROR) /* the group doesn't exist yet, add it */
7979 {
7980 /* First try using a free entry. */
7981 for (i = 0; i < augroups.ga_len; ++i)
7982 if (AUGROUP_NAME(i) == NULL)
7983 break;
7984 if (i == augroups.ga_len && ga_grow(&augroups, 1) == FAIL)
7985 return AUGROUP_ERROR;
7986
7987 AUGROUP_NAME(i) = vim_strsave(name);
7988 if (AUGROUP_NAME(i) == NULL)
7989 return AUGROUP_ERROR;
7990 if (i == augroups.ga_len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007991 ++augroups.ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007992 }
7993
7994 return i;
7995}
7996
7997 static void
7998au_del_group(name)
7999 char_u *name;
8000{
8001 int i;
8002
8003 i = au_find_group(name);
8004 if (i == AUGROUP_ERROR) /* the group doesn't exist */
8005 EMSG2(_("E367: No such group: \"%s\""), name);
8006 else
8007 {
8008 vim_free(AUGROUP_NAME(i));
8009 AUGROUP_NAME(i) = NULL;
8010 }
8011}
8012
8013/*
8014 * Find the ID of an autocmd group name.
8015 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
8016 */
8017 static int
8018au_find_group(name)
8019 char_u *name;
8020{
8021 int i;
8022
8023 for (i = 0; i < augroups.ga_len; ++i)
8024 if (AUGROUP_NAME(i) != NULL && STRCMP(AUGROUP_NAME(i), name) == 0)
8025 return i;
8026 return AUGROUP_ERROR;
8027}
8028
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008029/*
8030 * Return TRUE if augroup "name" exists.
8031 */
8032 int
8033au_has_group(name)
8034 char_u *name;
8035{
8036 return au_find_group(name) != AUGROUP_ERROR;
8037}
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008038
Bram Moolenaar071d4272004-06-13 20:20:40 +00008039/*
8040 * ":augroup {name}".
8041 */
8042 void
8043do_augroup(arg, del_group)
8044 char_u *arg;
8045 int del_group;
8046{
8047 int i;
8048
8049 if (del_group)
8050 {
8051 if (*arg == NUL)
8052 EMSG(_(e_argreq));
8053 else
8054 au_del_group(arg);
8055 }
8056 else if (STRICMP(arg, "end") == 0) /* ":aug end": back to group 0 */
8057 current_augroup = AUGROUP_DEFAULT;
8058 else if (*arg) /* ":aug xxx": switch to group xxx */
8059 {
8060 i = au_new_group(arg);
8061 if (i != AUGROUP_ERROR)
8062 current_augroup = i;
8063 }
8064 else /* ":aug": list the group names */
8065 {
8066 msg_start();
8067 for (i = 0; i < augroups.ga_len; ++i)
8068 {
8069 if (AUGROUP_NAME(i) != NULL)
8070 {
8071 msg_puts(AUGROUP_NAME(i));
8072 msg_puts((char_u *)" ");
8073 }
8074 }
8075 msg_clr_eos();
8076 msg_end();
8077 }
8078}
8079
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008080#if defined(EXITFREE) || defined(PROTO)
8081 void
8082free_all_autocmds()
8083{
8084 for (current_augroup = -1; current_augroup < augroups.ga_len;
8085 ++current_augroup)
8086 do_autocmd((char_u *)"", TRUE);
8087 ga_clear_strings(&augroups);
8088}
8089#endif
8090
Bram Moolenaar071d4272004-06-13 20:20:40 +00008091/*
8092 * Return the event number for event name "start".
8093 * Return NUM_EVENTS if the event name was not found.
8094 * Return a pointer to the next event name in "end".
8095 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008096 static event_T
Bram Moolenaar071d4272004-06-13 20:20:40 +00008097event_name2nr(start, end)
8098 char_u *start;
8099 char_u **end;
8100{
8101 char_u *p;
8102 int i;
8103 int len;
8104
8105 /* the event name ends with end of line, a blank or a comma */
8106 for (p = start; *p && !vim_iswhite(*p) && *p != ','; ++p)
8107 ;
8108 for (i = 0; event_names[i].name != NULL; ++i)
8109 {
8110 len = (int)STRLEN(event_names[i].name);
8111 if (len == p - start && STRNICMP(event_names[i].name, start, len) == 0)
8112 break;
8113 }
8114 if (*p == ',')
8115 ++p;
8116 *end = p;
8117 if (event_names[i].name == NULL)
8118 return NUM_EVENTS;
8119 return event_names[i].event;
8120}
8121
8122/*
8123 * Return the name for event "event".
8124 */
8125 static char_u *
8126event_nr2name(event)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008127 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008128{
8129 int i;
8130
8131 for (i = 0; event_names[i].name != NULL; ++i)
8132 if (event_names[i].event == event)
8133 return (char_u *)event_names[i].name;
8134 return (char_u *)"Unknown";
8135}
8136
8137/*
8138 * Scan over the events. "*" stands for all events.
8139 */
8140 static char_u *
8141find_end_event(arg, have_group)
8142 char_u *arg;
8143 int have_group; /* TRUE when group name was found */
8144{
8145 char_u *pat;
8146 char_u *p;
8147
8148 if (*arg == '*')
8149 {
8150 if (arg[1] && !vim_iswhite(arg[1]))
8151 {
8152 EMSG2(_("E215: Illegal character after *: %s"), arg);
8153 return NULL;
8154 }
8155 pat = arg + 1;
8156 }
8157 else
8158 {
8159 for (pat = arg; *pat && !vim_iswhite(*pat); pat = p)
8160 {
8161 if ((int)event_name2nr(pat, &p) >= (int)NUM_EVENTS)
8162 {
8163 if (have_group)
8164 EMSG2(_("E216: No such event: %s"), pat);
8165 else
8166 EMSG2(_("E216: No such group or event: %s"), pat);
8167 return NULL;
8168 }
8169 }
8170 }
8171 return pat;
8172}
8173
8174/*
8175 * Return TRUE if "event" is included in 'eventignore'.
8176 */
8177 static int
8178event_ignored(event)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008179 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008180{
8181 char_u *p = p_ei;
8182
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008183 while (*p != NUL)
8184 {
8185 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8186 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008187 if (event_name2nr(p, &p) == event)
8188 return TRUE;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008189 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008190
8191 return FALSE;
8192}
8193
8194/*
8195 * Return OK when the contents of p_ei is valid, FAIL otherwise.
8196 */
8197 int
8198check_ei()
8199{
8200 char_u *p = p_ei;
8201
Bram Moolenaar071d4272004-06-13 20:20:40 +00008202 while (*p)
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008203 {
8204 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8205 {
8206 p += 3;
8207 if (*p == ',')
8208 ++p;
8209 }
8210 else if (event_name2nr(p, &p) == NUM_EVENTS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008211 return FAIL;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008212 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008213
8214 return OK;
8215}
8216
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008217# if defined(FEAT_SYN_HL) || defined(PROTO)
8218
8219/*
8220 * Add "what" to 'eventignore' to skip loading syntax highlighting for every
8221 * buffer loaded into the window. "what" must start with a comma.
8222 * Returns the old value of 'eventignore' in allocated memory.
8223 */
8224 char_u *
8225au_event_disable(what)
8226 char *what;
8227{
8228 char_u *new_ei;
8229 char_u *save_ei;
8230
8231 save_ei = vim_strsave(p_ei);
8232 if (save_ei != NULL)
8233 {
Bram Moolenaara5792f52005-11-23 21:25:05 +00008234 new_ei = vim_strnsave(p_ei, (int)(STRLEN(p_ei) + STRLEN(what)));
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008235 if (new_ei != NULL)
8236 {
Bram Moolenaar8cac9fd2010-03-02 12:48:05 +01008237 if (*what == ',' && *p_ei == NUL)
8238 STRCPY(new_ei, what + 1);
8239 else
8240 STRCAT(new_ei, what);
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008241 set_string_option_direct((char_u *)"ei", -1, new_ei,
8242 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008243 vim_free(new_ei);
8244 }
8245 }
8246 return save_ei;
8247}
8248
8249 void
8250au_event_restore(old_ei)
8251 char_u *old_ei;
8252{
8253 if (old_ei != NULL)
8254 {
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008255 set_string_option_direct((char_u *)"ei", -1, old_ei,
8256 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008257 vim_free(old_ei);
8258 }
8259}
8260# endif /* FEAT_SYN_HL */
8261
Bram Moolenaar071d4272004-06-13 20:20:40 +00008262/*
8263 * do_autocmd() -- implements the :autocmd command. Can be used in the
8264 * following ways:
8265 *
8266 * :autocmd <event> <pat> <cmd> Add <cmd> to the list of commands that
8267 * will be automatically executed for <event>
8268 * when editing a file matching <pat>, in
8269 * the current group.
8270 * :autocmd <event> <pat> Show the auto-commands associated with
8271 * <event> and <pat>.
8272 * :autocmd <event> Show the auto-commands associated with
8273 * <event>.
8274 * :autocmd Show all auto-commands.
8275 * :autocmd! <event> <pat> <cmd> Remove all auto-commands associated with
8276 * <event> and <pat>, and add the command
8277 * <cmd>, for the current group.
8278 * :autocmd! <event> <pat> Remove all auto-commands associated with
8279 * <event> and <pat> for the current group.
8280 * :autocmd! <event> Remove all auto-commands associated with
8281 * <event> for the current group.
8282 * :autocmd! Remove ALL auto-commands for the current
8283 * group.
8284 *
8285 * Multiple events and patterns may be given separated by commas. Here are
8286 * some examples:
8287 * :autocmd bufread,bufenter *.c,*.h set tw=0 smartindent noic
8288 * :autocmd bufleave * set tw=79 nosmartindent ic infercase
8289 *
8290 * :autocmd * *.c show all autocommands for *.c files.
Bram Moolenaard35f9712005-12-18 22:02:33 +00008291 *
8292 * Mostly a {group} argument can optionally appear before <event>.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008293 */
8294 void
8295do_autocmd(arg, forceit)
8296 char_u *arg;
8297 int forceit;
8298{
8299 char_u *pat;
8300 char_u *envpat = NULL;
8301 char_u *cmd;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008302 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008303 int need_free = FALSE;
8304 int nested = FALSE;
8305 int group;
8306
8307 /*
8308 * Check for a legal group name. If not, use AUGROUP_ALL.
8309 */
8310 group = au_get_grouparg(&arg);
8311 if (arg == NULL) /* out of memory */
8312 return;
8313
8314 /*
8315 * Scan over the events.
8316 * If we find an illegal name, return here, don't do anything.
8317 */
8318 pat = find_end_event(arg, group != AUGROUP_ALL);
8319 if (pat == NULL)
8320 return;
8321
8322 /*
8323 * Scan over the pattern. Put a NUL at the end.
8324 */
8325 pat = skipwhite(pat);
8326 cmd = pat;
8327 while (*cmd && (!vim_iswhite(*cmd) || cmd[-1] == '\\'))
8328 cmd++;
8329 if (*cmd)
8330 *cmd++ = NUL;
8331
8332 /* Expand environment variables in the pattern. Set 'shellslash', we want
8333 * forward slashes here. */
8334 if (vim_strchr(pat, '$') != NULL || vim_strchr(pat, '~') != NULL)
8335 {
8336#ifdef BACKSLASH_IN_FILENAME
8337 int p_ssl_save = p_ssl;
8338
8339 p_ssl = TRUE;
8340#endif
8341 envpat = expand_env_save(pat);
8342#ifdef BACKSLASH_IN_FILENAME
8343 p_ssl = p_ssl_save;
8344#endif
8345 if (envpat != NULL)
8346 pat = envpat;
8347 }
8348
8349 /*
8350 * Check for "nested" flag.
8351 */
8352 cmd = skipwhite(cmd);
8353 if (*cmd != NUL && STRNCMP(cmd, "nested", 6) == 0 && vim_iswhite(cmd[6]))
8354 {
8355 nested = TRUE;
8356 cmd = skipwhite(cmd + 6);
8357 }
8358
8359 /*
8360 * Find the start of the commands.
8361 * Expand <sfile> in it.
8362 */
8363 if (*cmd != NUL)
8364 {
8365 cmd = expand_sfile(cmd);
8366 if (cmd == NULL) /* some error */
8367 return;
8368 need_free = TRUE;
8369 }
8370
8371 /*
8372 * Print header when showing autocommands.
8373 */
8374 if (!forceit && *cmd == NUL)
8375 {
8376 /* Highlight title */
8377 MSG_PUTS_TITLE(_("\n--- Auto-Commands ---"));
8378 }
8379
8380 /*
8381 * Loop over the events.
8382 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008383 last_event = (event_T)-1; /* for listing the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008384 last_group = AUGROUP_ERROR; /* for listing the group name */
8385 if (*arg == '*' || *arg == NUL)
8386 {
Bram Moolenaar754b5602006-02-09 23:53:20 +00008387 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8388 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008389 if (do_autocmd_event(event, pat,
8390 nested, cmd, forceit, group) == FAIL)
8391 break;
8392 }
8393 else
8394 {
8395 while (*arg && !vim_iswhite(*arg))
8396 if (do_autocmd_event(event_name2nr(arg, &arg), pat,
8397 nested, cmd, forceit, group) == FAIL)
8398 break;
8399 }
8400
8401 if (need_free)
8402 vim_free(cmd);
8403 vim_free(envpat);
8404}
8405
8406/*
8407 * Find the group ID in a ":autocmd" or ":doautocmd" argument.
8408 * The "argp" argument is advanced to the following argument.
8409 *
8410 * Returns the group ID, AUGROUP_ERROR for error (out of memory).
8411 */
8412 static int
8413au_get_grouparg(argp)
8414 char_u **argp;
8415{
8416 char_u *group_name;
8417 char_u *p;
8418 char_u *arg = *argp;
8419 int group = AUGROUP_ALL;
8420
8421 p = skiptowhite(arg);
8422 if (p > arg)
8423 {
8424 group_name = vim_strnsave(arg, (int)(p - arg));
8425 if (group_name == NULL) /* out of memory */
8426 return AUGROUP_ERROR;
8427 group = au_find_group(group_name);
8428 if (group == AUGROUP_ERROR)
8429 group = AUGROUP_ALL; /* no match, use all groups */
8430 else
8431 *argp = skipwhite(p); /* match, skip over group name */
8432 vim_free(group_name);
8433 }
8434 return group;
8435}
8436
8437/*
8438 * do_autocmd() for one event.
8439 * If *pat == NUL do for all patterns.
8440 * If *cmd == NUL show entries.
8441 * If forceit == TRUE delete entries.
8442 * If group is not AUGROUP_ALL, only use this group.
8443 */
8444 static int
8445do_autocmd_event(event, pat, nested, cmd, forceit, group)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008446 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008447 char_u *pat;
8448 int nested;
8449 char_u *cmd;
8450 int forceit;
8451 int group;
8452{
8453 AutoPat *ap;
8454 AutoPat **prev_ap;
8455 AutoCmd *ac;
8456 AutoCmd **prev_ac;
8457 int brace_level;
8458 char_u *endpat;
8459 int findgroup;
8460 int allgroups;
8461 int patlen;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00008462 int is_buflocal;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008463 int buflocal_nr;
8464 char_u buflocal_pat[25]; /* for "<buffer=X>" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008465
8466 if (group == AUGROUP_ALL)
8467 findgroup = current_augroup;
8468 else
8469 findgroup = group;
8470 allgroups = (group == AUGROUP_ALL && !forceit && *cmd == NUL);
8471
8472 /*
8473 * Show or delete all patterns for an event.
8474 */
8475 if (*pat == NUL)
8476 {
8477 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8478 {
8479 if (forceit) /* delete the AutoPat, if it's in the current group */
8480 {
8481 if (ap->group == findgroup)
8482 au_remove_pat(ap);
8483 }
8484 else if (group == AUGROUP_ALL || ap->group == group)
8485 show_autocmd(ap, event);
8486 }
8487 }
8488
8489 /*
8490 * Loop through all the specified patterns.
8491 */
8492 for ( ; *pat; pat = (*endpat == ',' ? endpat + 1 : endpat))
8493 {
8494 /*
8495 * Find end of the pattern.
8496 * Watch out for a comma in braces, like "*.\{obj,o\}".
8497 */
8498 brace_level = 0;
8499 for (endpat = pat; *endpat && (*endpat != ',' || brace_level
8500 || endpat[-1] == '\\'); ++endpat)
8501 {
8502 if (*endpat == '{')
8503 brace_level++;
8504 else if (*endpat == '}')
8505 brace_level--;
8506 }
8507 if (pat == endpat) /* ignore single comma */
8508 continue;
8509 patlen = (int)(endpat - pat);
8510
8511 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008512 * detect special <buflocal[=X]> buffer-local patterns
8513 */
8514 is_buflocal = FALSE;
8515 buflocal_nr = 0;
8516
8517 if (patlen >= 7 && STRNCMP(pat, "<buffer", 7) == 0
8518 && pat[patlen - 1] == '>')
8519 {
8520 /* Error will be printed only for addition. printing and removing
8521 * will proceed silently. */
8522 is_buflocal = TRUE;
8523 if (patlen == 8)
8524 buflocal_nr = curbuf->b_fnum;
8525 else if (patlen > 9 && pat[7] == '=')
8526 {
8527 /* <buffer=abuf> */
8528 if (patlen == 13 && STRNICMP(pat, "<buffer=abuf>", 13))
8529 buflocal_nr = autocmd_bufnr;
8530 /* <buffer=123> */
8531 else if (skipdigits(pat + 8) == pat + patlen - 1)
8532 buflocal_nr = atoi((char *)pat + 8);
8533 }
8534 }
8535
8536 if (is_buflocal)
8537 {
8538 /* normalize pat into standard "<buffer>#N" form */
8539 sprintf((char *)buflocal_pat, "<buffer=%d>", buflocal_nr);
8540 pat = buflocal_pat; /* can modify pat and patlen */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008541 patlen = (int)STRLEN(buflocal_pat); /* but not endpat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008542 }
8543
8544 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008545 * Find AutoPat entries with this pattern.
8546 */
8547 prev_ap = &first_autopat[(int)event];
8548 while ((ap = *prev_ap) != NULL)
8549 {
8550 if (ap->pat != NULL)
8551 {
8552 /* Accept a pattern when:
8553 * - a group was specified and it's that group, or a group was
8554 * not specified and it's the current group, or a group was
8555 * not specified and we are listing
8556 * - the length of the pattern matches
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008557 * - the pattern matches.
8558 * For <buffer[=X]>, this condition works because we normalize
8559 * all buffer-local patterns.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008560 */
8561 if ((allgroups || ap->group == findgroup)
8562 && ap->patlen == patlen
8563 && STRNCMP(pat, ap->pat, patlen) == 0)
8564 {
8565 /*
8566 * Remove existing autocommands.
8567 * If adding any new autocmd's for this AutoPat, don't
8568 * delete the pattern from the autopat list, append to
8569 * this list.
8570 */
8571 if (forceit)
8572 {
8573 if (*cmd != NUL && ap->next == NULL)
8574 {
8575 au_remove_cmds(ap);
8576 break;
8577 }
8578 au_remove_pat(ap);
8579 }
8580
8581 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008582 * Show autocmd's for this autopat, or buflocals <buffer=X>
Bram Moolenaar071d4272004-06-13 20:20:40 +00008583 */
8584 else if (*cmd == NUL)
8585 show_autocmd(ap, event);
8586
8587 /*
8588 * Add autocmd to this autopat, if it's the last one.
8589 */
8590 else if (ap->next == NULL)
8591 break;
8592 }
8593 }
8594 prev_ap = &ap->next;
8595 }
8596
8597 /*
8598 * Add a new command.
8599 */
8600 if (*cmd != NUL)
8601 {
8602 /*
8603 * If the pattern we want to add a command to does appear at the
8604 * end of the list (or not is not in the list at all), add the
8605 * pattern at the end of the list.
8606 */
8607 if (ap == NULL)
8608 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008609 /* refuse to add buffer-local ap if buffer number is invalid */
8610 if (is_buflocal && (buflocal_nr == 0
8611 || buflist_findnr(buflocal_nr) == NULL))
8612 {
8613 EMSGN(_("E680: <buffer=%d>: invalid buffer number "),
8614 buflocal_nr);
8615 return FAIL;
8616 }
8617
Bram Moolenaar071d4272004-06-13 20:20:40 +00008618 ap = (AutoPat *)alloc((unsigned)sizeof(AutoPat));
8619 if (ap == NULL)
8620 return FAIL;
8621 ap->pat = vim_strnsave(pat, patlen);
8622 ap->patlen = patlen;
8623 if (ap->pat == NULL)
8624 {
8625 vim_free(ap);
8626 return FAIL;
8627 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008628
8629 if (is_buflocal)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008630 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008631 ap->buflocal_nr = buflocal_nr;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008632 ap->reg_prog = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008633 }
8634 else
8635 {
Bram Moolenaar748bf032005-02-02 23:04:36 +00008636 char_u *reg_pat;
8637
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008638 ap->buflocal_nr = 0;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008639 reg_pat = file_pat_to_reg_pat(pat, endpat,
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008640 &ap->allow_dirs, TRUE);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008641 if (reg_pat != NULL)
8642 ap->reg_prog = vim_regcomp(reg_pat, RE_MAGIC);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008643 vim_free(reg_pat);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008644 if (reg_pat == NULL || ap->reg_prog == NULL)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008645 {
8646 vim_free(ap->pat);
8647 vim_free(ap);
8648 return FAIL;
8649 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008650 }
8651 ap->cmds = NULL;
8652 *prev_ap = ap;
8653 ap->next = NULL;
8654 if (group == AUGROUP_ALL)
8655 ap->group = current_augroup;
8656 else
8657 ap->group = group;
8658 }
8659
8660 /*
8661 * Add the autocmd at the end of the AutoCmd list.
8662 */
8663 prev_ac = &(ap->cmds);
8664 while ((ac = *prev_ac) != NULL)
8665 prev_ac = &ac->next;
8666 ac = (AutoCmd *)alloc((unsigned)sizeof(AutoCmd));
8667 if (ac == NULL)
8668 return FAIL;
8669 ac->cmd = vim_strsave(cmd);
8670#ifdef FEAT_EVAL
8671 ac->scriptID = current_SID;
8672#endif
8673 if (ac->cmd == NULL)
8674 {
8675 vim_free(ac);
8676 return FAIL;
8677 }
8678 ac->next = NULL;
8679 *prev_ac = ac;
8680 ac->nested = nested;
8681 }
8682 }
8683
8684 au_cleanup(); /* may really delete removed patterns/commands now */
8685 return OK;
8686}
8687
8688/*
8689 * Implementation of ":doautocmd [group] event [fname]".
8690 * Return OK for success, FAIL for failure;
8691 */
8692 int
8693do_doautocmd(arg, do_msg)
8694 char_u *arg;
8695 int do_msg; /* give message for no matching autocmds? */
8696{
8697 char_u *fname;
8698 int nothing_done = TRUE;
8699 int group;
8700
8701 /*
8702 * Check for a legal group name. If not, use AUGROUP_ALL.
8703 */
8704 group = au_get_grouparg(&arg);
8705 if (arg == NULL) /* out of memory */
8706 return FAIL;
8707
8708 if (*arg == '*')
8709 {
8710 EMSG(_("E217: Can't execute autocommands for ALL events"));
8711 return FAIL;
8712 }
8713
8714 /*
8715 * Scan over the events.
8716 * If we find an illegal name, return here, don't do anything.
8717 */
8718 fname = find_end_event(arg, group != AUGROUP_ALL);
8719 if (fname == NULL)
8720 return FAIL;
8721
8722 fname = skipwhite(fname);
8723
8724 /*
8725 * Loop over the events.
8726 */
8727 while (*arg && !vim_iswhite(*arg))
8728 if (apply_autocmds_group(event_name2nr(arg, &arg),
8729 fname, NULL, TRUE, group, curbuf, NULL))
8730 nothing_done = FALSE;
8731
8732 if (nothing_done && do_msg)
8733 MSG(_("No matching autocommands"));
8734
8735#ifdef FEAT_EVAL
8736 return aborting() ? FAIL : OK;
8737#else
8738 return OK;
8739#endif
8740}
8741
8742/*
8743 * ":doautoall": execute autocommands for each loaded buffer.
8744 */
8745 void
8746ex_doautoall(eap)
8747 exarg_T *eap;
8748{
8749 int retval;
8750 aco_save_T aco;
8751 buf_T *buf;
8752
8753 /*
8754 * This is a bit tricky: For some commands curwin->w_buffer needs to be
8755 * equal to curbuf, but for some buffers there may not be a window.
8756 * So we change the buffer for the current window for a moment. This
8757 * gives problems when the autocommands make changes to the list of
8758 * buffers or windows...
8759 */
8760 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8761 {
Bram Moolenaar3a847972008-07-08 09:36:58 +00008762 if (buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008763 {
8764 /* find a window for this buffer and save some values */
8765 aucmd_prepbuf(&aco, buf);
8766
8767 /* execute the autocommands for this buffer */
8768 retval = do_doautocmd(eap->arg, FALSE);
Bram Moolenaareeefcc72007-05-01 21:21:21 +00008769
8770 /* Execute the modeline settings, but don't set window-local
8771 * options if we are using the current window for another buffer. */
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008772 do_modelines(curwin == aucmd_win ? OPT_NOWIN : 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008773
8774 /* restore the current window */
8775 aucmd_restbuf(&aco);
8776
8777 /* stop if there is some error or buffer was deleted */
8778 if (retval == FAIL || !buf_valid(buf))
8779 break;
8780 }
8781 }
8782
8783 check_cursor(); /* just in case lines got deleted */
8784}
8785
8786/*
8787 * Prepare for executing autocommands for (hidden) buffer "buf".
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008788 * Search for a visible window containing the current buffer. If there isn't
8789 * one then use "aucmd_win".
Bram Moolenaar071d4272004-06-13 20:20:40 +00008790 * Set "curbuf" and "curwin" to match "buf".
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00008791 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008792 */
8793 void
8794aucmd_prepbuf(aco, buf)
8795 aco_save_T *aco; /* structure to save values in */
8796 buf_T *buf; /* new curbuf */
8797{
8798 win_T *win;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008799#ifdef FEAT_WINDOWS
8800 int save_ea;
8801#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008802
8803 /* Find a window that is for the new buffer */
8804 if (buf == curbuf) /* be quick when buf is curbuf */
8805 win = curwin;
8806 else
8807#ifdef FEAT_WINDOWS
8808 for (win = firstwin; win != NULL; win = win->w_next)
8809 if (win->w_buffer == buf)
8810 break;
8811#else
8812 win = NULL;
8813#endif
8814
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008815 /* Allocate "aucmd_win" when needed. If this fails (out of memory) fall
8816 * back to using the current window. */
8817 if (win == NULL && aucmd_win == NULL)
8818 {
8819 win_alloc_aucmd_win();
8820 if (aucmd_win == NULL)
8821 win = curwin;
8822 }
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008823 if (win == NULL && aucmd_win_used)
8824 /* Strange recursive autocommand, fall back to using the current
8825 * window. Expect a few side effects... */
8826 win = curwin;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008827
8828 aco->save_curwin = curwin;
8829 aco->save_curbuf = curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008830 if (win != NULL)
8831 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008832 /* There is a window for "buf" in the current tab page, make it the
8833 * curwin. This is preferred, it has the least side effects (esp. if
8834 * "buf" is curbuf). */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008835 aco->use_aucmd_win = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008836 curwin = win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008837 }
8838 else
8839 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008840 /* There is no window for "buf", use "aucmd_win". To minimize the side
8841 * effects, insert it in a the current tab page.
8842 * Anything related to a window (e.g., setting folds) may have
8843 * unexpected results. */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008844 aco->use_aucmd_win = TRUE;
8845 aucmd_win_used = TRUE;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008846 aucmd_win->w_buffer = buf;
Bram Moolenaarcdddaa42010-06-07 23:07:44 +02008847 aucmd_win->w_s = &buf->b_s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008848 ++buf->b_nwindows;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008849 win_init_empty(aucmd_win); /* set cursor and topline to safe values */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008850 vim_free(aucmd_win->w_localdir);
8851 aucmd_win->w_localdir = NULL;
8852
8853 /* Make sure w_localdir and globaldir are NULL to avoid a chdir() in
8854 * win_enter_ext(). */
8855 aucmd_win->w_localdir = NULL;
8856 aco->globaldir = globaldir;
8857 globaldir = NULL;
8858
Bram Moolenaar071d4272004-06-13 20:20:40 +00008859
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008860#ifdef FEAT_WINDOWS
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008861 /* Split the current window, put the aucmd_win in the upper half.
8862 * We don't want the BufEnter or WinEnter autocommands. */
8863 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008864 make_snapshot(SNAP_AUCMD_IDX);
8865 save_ea = p_ea;
8866 p_ea = FALSE;
8867 (void)win_split_ins(0, WSP_TOP, aucmd_win, 0);
8868 (void)win_comp_pos(); /* recompute window positions */
8869 p_ea = save_ea;
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008870 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008871#endif
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008872 curwin = aucmd_win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008873 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008874 curbuf = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008875 aco->new_curwin = curwin;
8876 aco->new_curbuf = curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008877}
8878
8879/*
8880 * Cleanup after executing autocommands for a (hidden) buffer.
8881 * Restore the window as it was (if possible).
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00008882 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008883 */
8884 void
8885aucmd_restbuf(aco)
8886 aco_save_T *aco; /* structure holding saved values */
8887{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008888#ifdef FEAT_WINDOWS
8889 int dummy;
8890#endif
8891
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008892 if (aco->use_aucmd_win)
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008893 {
8894 --curbuf->b_nwindows;
8895#ifdef FEAT_WINDOWS
8896 /* Find "aucmd_win", it can't be closed, but it may be in another tab
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008897 * page. Do not trigger autocommands here. */
8898 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008899 if (curwin != aucmd_win)
8900 {
8901 tabpage_T *tp;
8902 win_T *wp;
8903
8904 FOR_ALL_TAB_WINDOWS(tp, wp)
8905 {
8906 if (wp == aucmd_win)
8907 {
8908 if (tp != curtab)
8909 goto_tabpage_tp(tp);
8910 win_goto(aucmd_win);
8911 break;
8912 }
8913 }
8914 }
8915
8916 /* Remove the window and frame from the tree of frames. */
8917 (void)winframe_remove(curwin, &dummy, NULL);
8918 win_remove(curwin, NULL);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008919 aucmd_win_used = FALSE;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008920 last_status(FALSE); /* may need to remove last status line */
8921 restore_snapshot(SNAP_AUCMD_IDX, FALSE);
8922 (void)win_comp_pos(); /* recompute window positions */
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008923 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008924
8925 if (win_valid(aco->save_curwin))
8926 curwin = aco->save_curwin;
8927 else
8928 /* Hmm, original window disappeared. Just use the first one. */
8929 curwin = firstwin;
8930# ifdef FEAT_EVAL
8931 vars_clear(&aucmd_win->w_vars.dv_hashtab); /* free all w: variables */
Bram Moolenaar50daf402009-11-17 13:57:22 +00008932 hash_init(&aucmd_win->w_vars.dv_hashtab); /* re-use the hashtab */
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008933# endif
8934#else
8935 curwin = aco->save_curwin;
8936#endif
8937 curbuf = curwin->w_buffer;
8938
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008939 vim_free(globaldir);
8940 globaldir = aco->globaldir;
8941
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008942 /* the buffer contents may have changed */
8943 check_cursor();
8944 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
8945 {
8946 curwin->w_topline = curbuf->b_ml.ml_line_count;
8947#ifdef FEAT_DIFF
8948 curwin->w_topfill = 0;
8949#endif
8950 }
8951#if defined(FEAT_GUI)
8952 /* Hide the scrollbars from the aucmd_win and update. */
8953 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_LEFT], FALSE);
8954 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_RIGHT], FALSE);
8955 gui_may_update_scrollbars();
8956#endif
8957 }
8958 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00008959 {
8960 /* restore curwin */
8961#ifdef FEAT_WINDOWS
8962 if (win_valid(aco->save_curwin))
8963#endif
8964 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008965 /* Restore the buffer which was previously edited by curwin, if
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008966 * it was changed, we are still the same window and the buffer is
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008967 * valid. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008968 if (curwin == aco->new_curwin
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008969 && curbuf != aco->new_curbuf
8970 && buf_valid(aco->new_curbuf)
8971 && aco->new_curbuf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008972 {
8973 --curbuf->b_nwindows;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008974 curbuf = aco->new_curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008975 curwin->w_buffer = curbuf;
8976 ++curbuf->b_nwindows;
8977 }
8978
8979 curwin = aco->save_curwin;
8980 curbuf = curwin->w_buffer;
8981 }
8982 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008983}
8984
8985static int autocmd_nested = FALSE;
8986
8987/*
8988 * Execute autocommands for "event" and file name "fname".
8989 * Return TRUE if some commands were executed.
8990 */
8991 int
8992apply_autocmds(event, fname, fname_io, force, buf)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008993 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008994 char_u *fname; /* NULL or empty means use actual file name */
8995 char_u *fname_io; /* fname to use for <afile> on cmdline */
8996 int force; /* when TRUE, ignore autocmd_busy */
8997 buf_T *buf; /* buffer for <abuf> */
8998{
8999 return apply_autocmds_group(event, fname, fname_io, force,
9000 AUGROUP_ALL, buf, NULL);
9001}
9002
9003/*
9004 * Like apply_autocmds(), but with extra "eap" argument. This takes care of
9005 * setting v:filearg.
9006 */
9007 static int
9008apply_autocmds_exarg(event, fname, fname_io, force, buf, eap)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009009 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009010 char_u *fname;
9011 char_u *fname_io;
9012 int force;
9013 buf_T *buf;
9014 exarg_T *eap;
9015{
9016 return apply_autocmds_group(event, fname, fname_io, force,
9017 AUGROUP_ALL, buf, eap);
9018}
9019
9020/*
9021 * Like apply_autocmds(), but handles the caller's retval. If the script
9022 * processing is being aborted or if retval is FAIL when inside a try
9023 * conditional, no autocommands are executed. If otherwise the autocommands
9024 * cause the script to be aborted, retval is set to FAIL.
9025 */
9026 int
9027apply_autocmds_retval(event, fname, fname_io, force, buf, retval)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009028 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009029 char_u *fname; /* NULL or empty means use actual file name */
9030 char_u *fname_io; /* fname to use for <afile> on cmdline */
9031 int force; /* when TRUE, ignore autocmd_busy */
9032 buf_T *buf; /* buffer for <abuf> */
9033 int *retval; /* pointer to caller's retval */
9034{
9035 int did_cmd;
9036
Bram Moolenaar1e015462005-09-25 22:16:38 +00009037#ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00009038 if (should_abort(*retval))
9039 return FALSE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00009040#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009041
9042 did_cmd = apply_autocmds_group(event, fname, fname_io, force,
9043 AUGROUP_ALL, buf, NULL);
Bram Moolenaar1e015462005-09-25 22:16:38 +00009044 if (did_cmd
9045#ifdef FEAT_EVAL
9046 && aborting()
9047#endif
9048 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00009049 *retval = FAIL;
9050 return did_cmd;
9051}
9052
Bram Moolenaard35f9712005-12-18 22:02:33 +00009053/*
9054 * Return TRUE when there is a CursorHold autocommand defined.
9055 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009056 int
9057has_cursorhold()
9058{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009059 return (first_autopat[(int)(get_real_state() == NORMAL_BUSY
9060 ? EVENT_CURSORHOLD : EVENT_CURSORHOLDI)] != NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009061}
Bram Moolenaard35f9712005-12-18 22:02:33 +00009062
9063/*
9064 * Return TRUE if the CursorHold event can be triggered.
9065 */
9066 int
9067trigger_cursorhold()
9068{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009069 int state;
9070
Bram Moolenaard29a9ee2006-09-14 09:07:34 +00009071 if (!did_cursorhold && has_cursorhold() && !Recording
9072#ifdef FEAT_INS_EXPAND
9073 && !ins_compl_active()
9074#endif
9075 )
Bram Moolenaar754b5602006-02-09 23:53:20 +00009076 {
9077 state = get_real_state();
9078 if (state == NORMAL_BUSY || (state & INSERT) != 0)
9079 return TRUE;
9080 }
9081 return FALSE;
Bram Moolenaard35f9712005-12-18 22:02:33 +00009082}
Bram Moolenaar754b5602006-02-09 23:53:20 +00009083
9084/*
9085 * Return TRUE when there is a CursorMoved autocommand defined.
9086 */
9087 int
9088has_cursormoved()
9089{
9090 return (first_autopat[(int)EVENT_CURSORMOVED] != NULL);
9091}
9092
9093/*
9094 * Return TRUE when there is a CursorMovedI autocommand defined.
9095 */
9096 int
9097has_cursormovedI()
9098{
9099 return (first_autopat[(int)EVENT_CURSORMOVEDI] != NULL);
9100}
Bram Moolenaar071d4272004-06-13 20:20:40 +00009101
9102 static int
9103apply_autocmds_group(event, fname, fname_io, force, group, buf, eap)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009104 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009105 char_u *fname; /* NULL or empty means use actual file name */
9106 char_u *fname_io; /* fname to use for <afile> on cmdline, NULL means
9107 use fname */
9108 int force; /* when TRUE, ignore autocmd_busy */
9109 int group; /* group ID, or AUGROUP_ALL */
9110 buf_T *buf; /* buffer for <abuf> */
9111 exarg_T *eap; /* command arguments */
9112{
9113 char_u *sfname = NULL; /* short file name */
9114 char_u *tail;
9115 int save_changed;
9116 buf_T *old_curbuf;
9117 int retval = FALSE;
9118 char_u *save_sourcing_name;
9119 linenr_T save_sourcing_lnum;
9120 char_u *save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009121 int save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009122 int save_autocmd_bufnr;
9123 char_u *save_autocmd_match;
9124 int save_autocmd_busy;
9125 int save_autocmd_nested;
9126 static int nesting = 0;
9127 AutoPatCmd patcmd;
9128 AutoPat *ap;
9129#ifdef FEAT_EVAL
9130 scid_T save_current_SID;
9131 void *save_funccalp;
9132 char_u *save_cmdarg;
9133 long save_cmdbang;
9134#endif
9135 static int filechangeshell_busy = FALSE;
Bram Moolenaar05159a02005-02-26 23:04:13 +00009136#ifdef FEAT_PROFILE
9137 proftime_T wait_time;
9138#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009139
9140 /*
9141 * Quickly return if there are no autocommands for this event or
9142 * autocommands are blocked.
9143 */
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009144 if (first_autopat[(int)event] == NULL || autocmd_blocked > 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009145 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009146
9147 /*
9148 * When autocommands are busy, new autocommands are only executed when
9149 * explicitly enabled with the "nested" flag.
9150 */
9151 if (autocmd_busy && !(force || autocmd_nested))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009152 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009153
9154#ifdef FEAT_EVAL
9155 /*
Bram Moolenaar7263a772007-05-10 17:35:54 +00009156 * Quickly return when immediately aborting on error, or when an interrupt
Bram Moolenaar071d4272004-06-13 20:20:40 +00009157 * occurred or an exception was thrown but not caught.
9158 */
9159 if (aborting())
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009160 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009161#endif
9162
9163 /*
9164 * FileChangedShell never nests, because it can create an endless loop.
9165 */
Bram Moolenaar56718732006-03-15 22:53:57 +00009166 if (filechangeshell_busy && (event == EVENT_FILECHANGEDSHELL
9167 || event == EVENT_FILECHANGEDSHELLPOST))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009168 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009169
9170 /*
9171 * Ignore events in 'eventignore'.
9172 */
9173 if (event_ignored(event))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009174 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009175
9176 /*
9177 * Allow nesting of autocommands, but restrict the depth, because it's
9178 * possible to create an endless loop.
9179 */
9180 if (nesting == 10)
9181 {
9182 EMSG(_("E218: autocommand nesting too deep"));
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009183 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009184 }
9185
9186 /*
9187 * Check if these autocommands are disabled. Used when doing ":all" or
9188 * ":ball".
9189 */
9190 if ( (autocmd_no_enter
9191 && (event == EVENT_WINENTER || event == EVENT_BUFENTER))
9192 || (autocmd_no_leave
9193 && (event == EVENT_WINLEAVE || event == EVENT_BUFLEAVE)))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009194 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009195
9196 /*
9197 * Save the autocmd_* variables and info about the current buffer.
9198 */
9199 save_autocmd_fname = autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009200 save_autocmd_fname_full = autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009201 save_autocmd_bufnr = autocmd_bufnr;
9202 save_autocmd_match = autocmd_match;
9203 save_autocmd_busy = autocmd_busy;
9204 save_autocmd_nested = autocmd_nested;
9205 save_changed = curbuf->b_changed;
9206 old_curbuf = curbuf;
9207
9208 /*
9209 * Set the file name to be used for <afile>.
Bram Moolenaara0174af2008-01-02 20:08:25 +00009210 * Make a copy to avoid that changing a buffer name or directory makes it
9211 * invalid.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009212 */
9213 if (fname_io == NULL)
9214 {
9215 if (fname != NULL && *fname != NUL)
9216 autocmd_fname = fname;
9217 else if (buf != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009218 autocmd_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009219 else
9220 autocmd_fname = NULL;
9221 }
9222 else
9223 autocmd_fname = fname_io;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009224 if (autocmd_fname != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009225 autocmd_fname = vim_strsave(autocmd_fname);
9226 autocmd_fname_full = FALSE; /* call FullName_save() later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009227
9228 /*
9229 * Set the buffer number to be used for <abuf>.
9230 */
9231 if (buf == NULL)
9232 autocmd_bufnr = 0;
9233 else
9234 autocmd_bufnr = buf->b_fnum;
9235
9236 /*
9237 * When the file name is NULL or empty, use the file name of buffer "buf".
9238 * Always use the full path of the file name to match with, in case
9239 * "allow_dirs" is set.
9240 */
9241 if (fname == NULL || *fname == NUL)
9242 {
9243 if (buf == NULL)
9244 fname = NULL;
9245 else
9246 {
9247#ifdef FEAT_SYN_HL
9248 if (event == EVENT_SYNTAX)
9249 fname = buf->b_p_syn;
9250 else
9251#endif
9252 if (event == EVENT_FILETYPE)
9253 fname = buf->b_p_ft;
9254 else
9255 {
9256 if (buf->b_sfname != NULL)
9257 sfname = vim_strsave(buf->b_sfname);
9258 fname = buf->b_ffname;
9259 }
9260 }
9261 if (fname == NULL)
9262 fname = (char_u *)"";
9263 fname = vim_strsave(fname); /* make a copy, so we can change it */
9264 }
9265 else
9266 {
9267 sfname = vim_strsave(fname);
Bram Moolenaar5135d462009-04-29 16:03:38 +00009268 /* Don't try expanding FileType, Syntax, FuncUndefined, WindowID or
9269 * QuickFixCmd* */
Bram Moolenaar7c626922005-02-07 22:01:03 +00009270 if (event == EVENT_FILETYPE
9271 || event == EVENT_SYNTAX
Bram Moolenaar5135d462009-04-29 16:03:38 +00009272 || event == EVENT_FUNCUNDEFINED
Bram Moolenaar7c626922005-02-07 22:01:03 +00009273 || event == EVENT_REMOTEREPLY
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00009274 || event == EVENT_SPELLFILEMISSING
Bram Moolenaar7c626922005-02-07 22:01:03 +00009275 || event == EVENT_QUICKFIXCMDPRE
9276 || event == EVENT_QUICKFIXCMDPOST)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009277 fname = vim_strsave(fname);
9278 else
9279 fname = FullName_save(fname, FALSE);
9280 }
9281 if (fname == NULL) /* out of memory */
9282 {
9283 vim_free(sfname);
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009284 retval = FALSE;
9285 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009286 }
9287
9288#ifdef BACKSLASH_IN_FILENAME
9289 /*
9290 * Replace all backslashes with forward slashes. This makes the
9291 * autocommand patterns portable between Unix and MS-DOS.
9292 */
9293 if (sfname != NULL)
9294 forward_slash(sfname);
9295 forward_slash(fname);
9296#endif
9297
9298#ifdef VMS
9299 /* remove version for correct match */
9300 if (sfname != NULL)
9301 vms_remove_version(sfname);
9302 vms_remove_version(fname);
9303#endif
9304
9305 /*
9306 * Set the name to be used for <amatch>.
9307 */
9308 autocmd_match = fname;
9309
9310
9311 /* Don't redraw while doing auto commands. */
9312 ++RedrawingDisabled;
9313 save_sourcing_name = sourcing_name;
9314 sourcing_name = NULL; /* don't free this one */
9315 save_sourcing_lnum = sourcing_lnum;
9316 sourcing_lnum = 0; /* no line number here */
9317
9318#ifdef FEAT_EVAL
9319 save_current_SID = current_SID;
9320
Bram Moolenaar05159a02005-02-26 23:04:13 +00009321# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009322 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009323 prof_child_enter(&wait_time); /* doesn't count for the caller itself */
9324# endif
9325
Bram Moolenaar071d4272004-06-13 20:20:40 +00009326 /* Don't use local function variables, if called from a function */
9327 save_funccalp = save_funccal();
9328#endif
9329
9330 /*
9331 * When starting to execute autocommands, save the search patterns.
9332 */
9333 if (!autocmd_busy)
9334 {
9335 save_search_patterns();
9336 saveRedobuff();
9337 did_filetype = keep_filetype;
9338 }
9339
9340 /*
9341 * Note that we are applying autocmds. Some commands need to know.
9342 */
9343 autocmd_busy = TRUE;
9344 filechangeshell_busy = (event == EVENT_FILECHANGEDSHELL);
9345 ++nesting; /* see matching decrement below */
9346
9347 /* Remember that FileType was triggered. Used for did_filetype(). */
9348 if (event == EVENT_FILETYPE)
9349 did_filetype = TRUE;
9350
9351 tail = gettail(fname);
9352
9353 /* Find first autocommand that matches */
9354 patcmd.curpat = first_autopat[(int)event];
9355 patcmd.nextcmd = NULL;
9356 patcmd.group = group;
9357 patcmd.fname = fname;
9358 patcmd.sfname = sfname;
9359 patcmd.tail = tail;
9360 patcmd.event = event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009361 patcmd.arg_bufnr = autocmd_bufnr;
9362 patcmd.next = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009363 auto_next_pat(&patcmd, FALSE);
9364
9365 /* found one, start executing the autocommands */
9366 if (patcmd.curpat != NULL)
9367 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009368 /* add to active_apc_list */
9369 patcmd.next = active_apc_list;
9370 active_apc_list = &patcmd;
9371
Bram Moolenaar071d4272004-06-13 20:20:40 +00009372#ifdef FEAT_EVAL
9373 /* set v:cmdarg (only when there is a matching pattern) */
9374 save_cmdbang = get_vim_var_nr(VV_CMDBANG);
9375 if (eap != NULL)
9376 {
9377 save_cmdarg = set_cmdarg(eap, NULL);
9378 set_vim_var_nr(VV_CMDBANG, (long)eap->forceit);
9379 }
9380 else
9381 save_cmdarg = NULL; /* avoid gcc warning */
9382#endif
9383 retval = TRUE;
9384 /* mark the last pattern, to avoid an endless loop when more patterns
9385 * are added when executing autocommands */
9386 for (ap = patcmd.curpat; ap->next != NULL; ap = ap->next)
9387 ap->last = FALSE;
9388 ap->last = TRUE;
9389 check_lnums(TRUE); /* make sure cursor and topline are valid */
9390 do_cmdline(NULL, getnextac, (void *)&patcmd,
9391 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
9392#ifdef FEAT_EVAL
9393 if (eap != NULL)
9394 {
9395 (void)set_cmdarg(NULL, save_cmdarg);
9396 set_vim_var_nr(VV_CMDBANG, save_cmdbang);
9397 }
9398#endif
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009399 /* delete from active_apc_list */
9400 if (active_apc_list == &patcmd) /* just in case */
9401 active_apc_list = patcmd.next;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009402 }
9403
9404 --RedrawingDisabled;
9405 autocmd_busy = save_autocmd_busy;
9406 filechangeshell_busy = FALSE;
9407 autocmd_nested = save_autocmd_nested;
9408 vim_free(sourcing_name);
9409 sourcing_name = save_sourcing_name;
9410 sourcing_lnum = save_sourcing_lnum;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009411 vim_free(autocmd_fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009412 autocmd_fname = save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009413 autocmd_fname_full = save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009414 autocmd_bufnr = save_autocmd_bufnr;
9415 autocmd_match = save_autocmd_match;
9416#ifdef FEAT_EVAL
9417 current_SID = save_current_SID;
9418 restore_funccal(save_funccalp);
Bram Moolenaar05159a02005-02-26 23:04:13 +00009419# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009420 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009421 prof_child_exit(&wait_time);
9422# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009423#endif
9424 vim_free(fname);
9425 vim_free(sfname);
9426 --nesting; /* see matching increment above */
9427
9428 /*
9429 * When stopping to execute autocommands, restore the search patterns and
9430 * the redo buffer.
9431 */
9432 if (!autocmd_busy)
9433 {
9434 restore_search_patterns();
9435 restoreRedobuff();
9436 did_filetype = FALSE;
9437 }
9438
9439 /*
9440 * Some events don't set or reset the Changed flag.
9441 * Check if still in the same buffer!
9442 */
9443 if (curbuf == old_curbuf
9444 && (event == EVENT_BUFREADPOST
9445 || event == EVENT_BUFWRITEPOST
9446 || event == EVENT_FILEAPPENDPOST
9447 || event == EVENT_VIMLEAVE
9448 || event == EVENT_VIMLEAVEPRE))
9449 {
9450#ifdef FEAT_TITLE
9451 if (curbuf->b_changed != save_changed)
9452 need_maketitle = TRUE;
9453#endif
9454 curbuf->b_changed = save_changed;
9455 }
9456
9457 au_cleanup(); /* may really delete removed patterns/commands now */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009458
9459BYPASS_AU:
9460 /* When wiping out a buffer make sure all its buffer-local autocommands
9461 * are deleted. */
9462 if (event == EVENT_BUFWIPEOUT && buf != NULL)
9463 aubuflocal_remove(buf);
9464
Bram Moolenaar071d4272004-06-13 20:20:40 +00009465 return retval;
9466}
9467
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009468# ifdef FEAT_EVAL
9469static char_u *old_termresponse = NULL;
9470# endif
9471
9472/*
9473 * Block triggering autocommands until unblock_autocmd() is called.
9474 * Can be used recursively, so long as it's symmetric.
9475 */
9476 void
9477block_autocmds()
9478{
9479# ifdef FEAT_EVAL
9480 /* Remember the value of v:termresponse. */
9481 if (autocmd_blocked == 0)
9482 old_termresponse = get_vim_var_str(VV_TERMRESPONSE);
9483# endif
9484 ++autocmd_blocked;
9485}
9486
9487 void
9488unblock_autocmds()
9489{
9490 --autocmd_blocked;
9491
9492# ifdef FEAT_EVAL
9493 /* When v:termresponse was set while autocommands were blocked, trigger
9494 * the autocommands now. Esp. useful when executing a shell command
9495 * during startup (vimdiff). */
9496 if (autocmd_blocked == 0
9497 && get_vim_var_str(VV_TERMRESPONSE) != old_termresponse)
9498 apply_autocmds(EVENT_TERMRESPONSE, NULL, NULL, FALSE, curbuf);
9499# endif
9500}
9501
Bram Moolenaar071d4272004-06-13 20:20:40 +00009502/*
9503 * Find next autocommand pattern that matches.
9504 */
9505 static void
9506auto_next_pat(apc, stop_at_last)
9507 AutoPatCmd *apc;
9508 int stop_at_last; /* stop when 'last' flag is set */
9509{
9510 AutoPat *ap;
9511 AutoCmd *cp;
9512 char_u *name;
9513 char *s;
9514
9515 vim_free(sourcing_name);
9516 sourcing_name = NULL;
9517
9518 for (ap = apc->curpat; ap != NULL && !got_int; ap = ap->next)
9519 {
9520 apc->curpat = NULL;
9521
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009522 /* Only use a pattern when it has not been removed, has commands and
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009523 * the group matches. For buffer-local autocommands only check the
9524 * buffer number. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009525 if (ap->pat != NULL && ap->cmds != NULL
9526 && (apc->group == AUGROUP_ALL || apc->group == ap->group))
9527 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009528 /* execution-condition */
9529 if (ap->buflocal_nr == 0
Bram Moolenaar748bf032005-02-02 23:04:36 +00009530 ? (match_file_pat(NULL, ap->reg_prog, apc->fname,
9531 apc->sfname, apc->tail, ap->allow_dirs))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009532 : ap->buflocal_nr == apc->arg_bufnr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009533 {
9534 name = event_nr2name(apc->event);
9535 s = _("%s Auto commands for \"%s\"");
9536 sourcing_name = alloc((unsigned)(STRLEN(s)
9537 + STRLEN(name) + ap->patlen + 1));
9538 if (sourcing_name != NULL)
9539 {
9540 sprintf((char *)sourcing_name, s,
9541 (char *)name, (char *)ap->pat);
9542 if (p_verbose >= 8)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009543 {
9544 verbose_enter();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009545 smsg((char_u *)_("Executing %s"), sourcing_name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009546 verbose_leave();
9547 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009548 }
9549
9550 apc->curpat = ap;
9551 apc->nextcmd = ap->cmds;
9552 /* mark last command */
9553 for (cp = ap->cmds; cp->next != NULL; cp = cp->next)
9554 cp->last = FALSE;
9555 cp->last = TRUE;
9556 }
9557 line_breakcheck();
9558 if (apc->curpat != NULL) /* found a match */
9559 break;
9560 }
9561 if (stop_at_last && ap->last)
9562 break;
9563 }
9564}
9565
9566/*
9567 * Get next autocommand command.
9568 * Called by do_cmdline() to get the next line for ":if".
9569 * Returns allocated string, or NULL for end of autocommands.
9570 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009571 static char_u *
9572getnextac(c, cookie, indent)
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009573 int c UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009574 void *cookie;
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009575 int indent UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009576{
9577 AutoPatCmd *acp = (AutoPatCmd *)cookie;
9578 char_u *retval;
9579 AutoCmd *ac;
9580
9581 /* Can be called again after returning the last line. */
9582 if (acp->curpat == NULL)
9583 return NULL;
9584
9585 /* repeat until we find an autocommand to execute */
9586 for (;;)
9587 {
9588 /* skip removed commands */
9589 while (acp->nextcmd != NULL && acp->nextcmd->cmd == NULL)
9590 if (acp->nextcmd->last)
9591 acp->nextcmd = NULL;
9592 else
9593 acp->nextcmd = acp->nextcmd->next;
9594
9595 if (acp->nextcmd != NULL)
9596 break;
9597
9598 /* at end of commands, find next pattern that matches */
9599 if (acp->curpat->last)
9600 acp->curpat = NULL;
9601 else
9602 acp->curpat = acp->curpat->next;
9603 if (acp->curpat != NULL)
9604 auto_next_pat(acp, TRUE);
9605 if (acp->curpat == NULL)
9606 return NULL;
9607 }
9608
9609 ac = acp->nextcmd;
9610
9611 if (p_verbose >= 9)
9612 {
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009613 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009614 smsg((char_u *)_("autocommand %s"), ac->cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009615 msg_puts((char_u *)"\n"); /* don't overwrite this either */
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009616 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009617 }
9618 retval = vim_strsave(ac->cmd);
9619 autocmd_nested = ac->nested;
9620#ifdef FEAT_EVAL
9621 current_SID = ac->scriptID;
9622#endif
9623 if (ac->last)
9624 acp->nextcmd = NULL;
9625 else
9626 acp->nextcmd = ac->next;
9627 return retval;
9628}
9629
9630/*
9631 * Return TRUE if there is a matching autocommand for "fname".
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009632 * To account for buffer-local autocommands, function needs to know
9633 * in which buffer the file will be opened.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009634 */
9635 int
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009636has_autocmd(event, sfname, buf)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009637 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009638 char_u *sfname;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009639 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009640{
9641 AutoPat *ap;
9642 char_u *fname;
9643 char_u *tail = gettail(sfname);
9644 int retval = FALSE;
9645
9646 fname = FullName_save(sfname, FALSE);
9647 if (fname == NULL)
9648 return FALSE;
9649
9650#ifdef BACKSLASH_IN_FILENAME
9651 /*
9652 * Replace all backslashes with forward slashes. This makes the
9653 * autocommand patterns portable between Unix and MS-DOS.
9654 */
9655 sfname = vim_strsave(sfname);
9656 if (sfname != NULL)
9657 forward_slash(sfname);
9658 forward_slash(fname);
9659#endif
9660
9661 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
9662 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009663 && (ap->buflocal_nr == 0
Bram Moolenaar748bf032005-02-02 23:04:36 +00009664 ? match_file_pat(NULL, ap->reg_prog,
9665 fname, sfname, tail, ap->allow_dirs)
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009666 : buf != NULL && ap->buflocal_nr == buf->b_fnum
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009667 ))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009668 {
9669 retval = TRUE;
9670 break;
9671 }
9672
9673 vim_free(fname);
9674#ifdef BACKSLASH_IN_FILENAME
9675 vim_free(sfname);
9676#endif
9677
9678 return retval;
9679}
9680
9681#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
9682/*
9683 * Function given to ExpandGeneric() to obtain the list of autocommand group
9684 * names.
9685 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009686 char_u *
9687get_augroup_name(xp, idx)
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009688 expand_T *xp UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009689 int idx;
9690{
9691 if (idx == augroups.ga_len) /* add "END" add the end */
9692 return (char_u *)"END";
9693 if (idx >= augroups.ga_len) /* end of list */
9694 return NULL;
9695 if (AUGROUP_NAME(idx) == NULL) /* skip deleted entries */
9696 return (char_u *)"";
9697 return AUGROUP_NAME(idx); /* return a name */
9698}
9699
9700static int include_groups = FALSE;
9701
9702 char_u *
9703set_context_in_autocmd(xp, arg, doautocmd)
9704 expand_T *xp;
9705 char_u *arg;
Bram Moolenaard812df62008-11-09 12:46:09 +00009706 int doautocmd; /* TRUE for :doauto*, FALSE for :autocmd */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009707{
9708 char_u *p;
9709 int group;
9710
9711 /* check for a group name, skip it if present */
9712 include_groups = FALSE;
9713 p = arg;
9714 group = au_get_grouparg(&arg);
9715 if (group == AUGROUP_ERROR)
9716 return NULL;
9717 /* If there only is a group name that's what we expand. */
9718 if (*arg == NUL && group != AUGROUP_ALL && !vim_iswhite(arg[-1]))
9719 {
9720 arg = p;
9721 group = AUGROUP_ALL;
9722 }
9723
9724 /* skip over event name */
9725 for (p = arg; *p != NUL && !vim_iswhite(*p); ++p)
9726 if (*p == ',')
9727 arg = p + 1;
9728 if (*p == NUL)
9729 {
9730 if (group == AUGROUP_ALL)
9731 include_groups = TRUE;
9732 xp->xp_context = EXPAND_EVENTS; /* expand event name */
9733 xp->xp_pattern = arg;
9734 return NULL;
9735 }
9736
9737 /* skip over pattern */
9738 arg = skipwhite(p);
9739 while (*arg && (!vim_iswhite(*arg) || arg[-1] == '\\'))
9740 arg++;
9741 if (*arg)
9742 return arg; /* expand (next) command */
9743
9744 if (doautocmd)
9745 xp->xp_context = EXPAND_FILES; /* expand file names */
9746 else
9747 xp->xp_context = EXPAND_NOTHING; /* pattern is not expanded */
9748 return NULL;
9749}
9750
9751/*
9752 * Function given to ExpandGeneric() to obtain the list of event names.
9753 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009754 char_u *
9755get_event_name(xp, idx)
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009756 expand_T *xp UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009757 int idx;
9758{
9759 if (idx < augroups.ga_len) /* First list group names, if wanted */
9760 {
9761 if (!include_groups || AUGROUP_NAME(idx) == NULL)
9762 return (char_u *)""; /* skip deleted entries */
9763 return AUGROUP_NAME(idx); /* return a name */
9764 }
9765 return (char_u *)event_names[idx - augroups.ga_len].name;
9766}
9767
9768#endif /* FEAT_CMDL_COMPL */
9769
9770/*
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009771 * Return TRUE if autocmd is supported.
9772 */
9773 int
9774autocmd_supported(name)
9775 char_u *name;
9776{
9777 char_u *p;
9778
9779 return (event_name2nr(name, &p) != NUM_EVENTS);
9780}
9781
9782/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00009783 * Return TRUE if an autocommand is defined for a group, event and
9784 * pattern: The group can be omitted to accept any group. "event" and "pattern"
9785 * can be NULL to accept any event and pattern. "pattern" can be NULL to accept
9786 * any pattern. Buffer-local patterns <buffer> or <buffer=N> are accepted.
9787 * Used for:
9788 * exists("#Group") or
9789 * exists("#Group#Event") or
9790 * exists("#Group#Event#pat") or
9791 * exists("#Event") or
9792 * exists("#Event#pat")
Bram Moolenaar071d4272004-06-13 20:20:40 +00009793 */
9794 int
Bram Moolenaar195d6352005-12-19 22:08:24 +00009795au_exists(arg)
9796 char_u *arg;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009797{
Bram Moolenaar195d6352005-12-19 22:08:24 +00009798 char_u *arg_save;
9799 char_u *pattern = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009800 char_u *event_name;
9801 char_u *p;
Bram Moolenaar754b5602006-02-09 23:53:20 +00009802 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009803 AutoPat *ap;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009804 buf_T *buflocal_buf = NULL;
Bram Moolenaar195d6352005-12-19 22:08:24 +00009805 int group;
9806 int retval = FALSE;
9807
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009808 /* Make a copy so that we can change the '#' chars to a NUL. */
Bram Moolenaar195d6352005-12-19 22:08:24 +00009809 arg_save = vim_strsave(arg);
9810 if (arg_save == NULL)
9811 return FALSE;
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009812 p = vim_strchr(arg_save, '#');
Bram Moolenaar195d6352005-12-19 22:08:24 +00009813 if (p != NULL)
9814 *p++ = NUL;
9815
9816 /* First, look for an autocmd group name */
9817 group = au_find_group(arg_save);
9818 if (group == AUGROUP_ERROR)
9819 {
9820 /* Didn't match a group name, assume the first argument is an event. */
9821 group = AUGROUP_ALL;
9822 event_name = arg_save;
9823 }
9824 else
9825 {
9826 if (p == NULL)
9827 {
9828 /* "Group": group name is present and it's recognized */
9829 retval = TRUE;
9830 goto theend;
9831 }
9832
9833 /* Must be "Group#Event" or "Group#Event#pat". */
9834 event_name = p;
9835 p = vim_strchr(event_name, '#');
9836 if (p != NULL)
9837 *p++ = NUL; /* "Group#Event#pat" */
9838 }
9839
9840 pattern = p; /* "pattern" is NULL when there is no pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009841
9842 /* find the index (enum) for the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009843 event = event_name2nr(event_name, &p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009844
9845 /* return FALSE if the event name is not recognized */
Bram Moolenaar195d6352005-12-19 22:08:24 +00009846 if (event == NUM_EVENTS)
9847 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009848
9849 /* Find the first autocommand for this event.
9850 * If there isn't any, return FALSE;
9851 * If there is one and no pattern given, return TRUE; */
9852 ap = first_autopat[(int)event];
9853 if (ap == NULL)
Bram Moolenaar195d6352005-12-19 22:08:24 +00009854 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009855
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009856 /* if pattern is "<buffer>", special handling is needed which uses curbuf */
9857 /* for pattern "<buffer=N>, fnamecmp() will work fine */
Bram Moolenaar5b7880d2009-09-11 15:24:31 +00009858 if (pattern != NULL && STRICMP(pattern, "<buffer>") == 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009859 buflocal_buf = curbuf;
9860
Bram Moolenaar071d4272004-06-13 20:20:40 +00009861 /* Check if there is an autocommand with the given pattern. */
9862 for ( ; ap != NULL; ap = ap->next)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009863 /* only use a pattern when it has not been removed and has commands. */
9864 /* For buffer-local autocommands, fnamecmp() works fine. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009865 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaar195d6352005-12-19 22:08:24 +00009866 && (group == AUGROUP_ALL || ap->group == group)
Bram Moolenaar5b7880d2009-09-11 15:24:31 +00009867 && (pattern == NULL
9868 || (buflocal_buf == NULL
9869 ? fnamecmp(ap->pat, pattern) == 0
9870 : ap->buflocal_nr == buflocal_buf->b_fnum)))
Bram Moolenaar195d6352005-12-19 22:08:24 +00009871 {
9872 retval = TRUE;
9873 break;
9874 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009875
Bram Moolenaar195d6352005-12-19 22:08:24 +00009876theend:
9877 vim_free(arg_save);
9878 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009879}
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009880
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009881#else /* FEAT_AUTOCMD */
9882
9883/*
9884 * Prepare for executing commands for (hidden) buffer "buf".
9885 * This is the non-autocommand version, it simply saves "curbuf" and sets
9886 * "curbuf" and "curwin" to match "buf".
9887 */
9888 void
9889aucmd_prepbuf(aco, buf)
9890 aco_save_T *aco; /* structure to save values in */
9891 buf_T *buf; /* new curbuf */
9892{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009893 aco->save_curbuf = curbuf;
9894 --curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009895 curbuf = buf;
9896 curwin->w_buffer = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009897 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009898}
9899
9900/*
9901 * Restore after executing commands for a (hidden) buffer.
9902 * This is the non-autocommand version.
9903 */
9904 void
9905aucmd_restbuf(aco)
9906 aco_save_T *aco; /* structure holding saved values */
9907{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009908 --curbuf->b_nwindows;
9909 curbuf = aco->save_curbuf;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009910 curwin->w_buffer = curbuf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009911 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009912}
9913
Bram Moolenaar071d4272004-06-13 20:20:40 +00009914#endif /* FEAT_AUTOCMD */
9915
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009916
Bram Moolenaar071d4272004-06-13 20:20:40 +00009917#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN) || defined(PROTO)
9918/*
Bram Moolenaar748bf032005-02-02 23:04:36 +00009919 * Try matching a filename with a "pattern" ("prog" is NULL), or use the
9920 * precompiled regprog "prog" ("pattern" is NULL). That avoids calling
9921 * vim_regcomp() often.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009922 * Used for autocommands and 'wildignore'.
9923 * Returns TRUE if there is a match, FALSE otherwise.
9924 */
9925 int
Bram Moolenaar748bf032005-02-02 23:04:36 +00009926match_file_pat(pattern, prog, fname, sfname, tail, allow_dirs)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009927 char_u *pattern; /* pattern to match with */
Bram Moolenaar748bf032005-02-02 23:04:36 +00009928 regprog_T *prog; /* pre-compiled regprog or NULL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009929 char_u *fname; /* full path of file name */
9930 char_u *sfname; /* short file name or NULL */
9931 char_u *tail; /* tail of path */
9932 int allow_dirs; /* allow matching with dir */
9933{
9934 regmatch_T regmatch;
9935 int result = FALSE;
9936#ifdef FEAT_OSFILETYPE
9937 int no_pattern = FALSE; /* TRUE if check is filetype only */
9938 char_u *type_start;
9939 char_u c;
9940 int match = FALSE;
9941#endif
9942
9943#ifdef CASE_INSENSITIVE_FILENAME
9944 regmatch.rm_ic = TRUE; /* Always ignore case */
9945#else
9946 regmatch.rm_ic = FALSE; /* Don't ever ignore case */
9947#endif
9948#ifdef FEAT_OSFILETYPE
9949 if (*pattern == '<')
9950 {
9951 /* There is a filetype condition specified with this pattern.
9952 * Check the filetype matches first. If not, don't bother with the
9953 * pattern (set regprog to NULL).
9954 * Always use magic for the regexp.
9955 */
9956
9957 for (type_start = pattern + 1; (c = *pattern); pattern++)
9958 {
9959 if ((c == ';' || c == '>') && match == FALSE)
9960 {
9961 *pattern = NUL; /* Terminate the string */
9962 match = mch_check_filetype(fname, type_start);
9963 *pattern = c; /* Restore the terminator */
9964 type_start = pattern + 1;
9965 }
9966 if (c == '>')
9967 break;
9968 }
9969
9970 /* (c should never be NUL, but check anyway) */
9971 if (match == FALSE || c == NUL)
9972 regmatch.regprog = NULL; /* Doesn't match - don't check pat. */
9973 else if (*pattern == NUL)
9974 {
9975 regmatch.regprog = NULL; /* Vim will try to free regprog later */
9976 no_pattern = TRUE; /* Always matches - don't check pat. */
9977 }
9978 else
9979 regmatch.regprog = vim_regcomp(pattern + 1, RE_MAGIC);
9980 }
9981 else
9982#endif
Bram Moolenaar748bf032005-02-02 23:04:36 +00009983 {
9984 if (prog != NULL)
9985 regmatch.regprog = prog;
9986 else
9987 regmatch.regprog = vim_regcomp(pattern, RE_MAGIC);
9988 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009989
9990 /*
9991 * Try for a match with the pattern with:
9992 * 1. the full file name, when the pattern has a '/'.
9993 * 2. the short file name, when the pattern has a '/'.
9994 * 3. the tail of the file name, when the pattern has no '/'.
9995 */
9996 if (
9997#ifdef FEAT_OSFILETYPE
9998 /* If the check is for a filetype only and we don't care
9999 * about the path then skip all the regexp stuff.
10000 */
10001 no_pattern ||
10002#endif
10003 (regmatch.regprog != NULL
10004 && ((allow_dirs
10005 && (vim_regexec(&regmatch, fname, (colnr_T)0)
10006 || (sfname != NULL
10007 && vim_regexec(&regmatch, sfname, (colnr_T)0))))
10008 || (!allow_dirs && vim_regexec(&regmatch, tail, (colnr_T)0)))))
10009 result = TRUE;
10010
Bram Moolenaar748bf032005-02-02 23:04:36 +000010011 if (prog == NULL)
10012 vim_free(regmatch.regprog);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010013 return result;
10014}
10015#endif
10016
10017#if defined(FEAT_WILDIGN) || defined(PROTO)
10018/*
10019 * Return TRUE if a file matches with a pattern in "list".
10020 * "list" is a comma-separated list of patterns, like 'wildignore'.
10021 * "sfname" is the short file name or NULL, "ffname" the long file name.
10022 */
10023 int
10024match_file_list(list, sfname, ffname)
10025 char_u *list;
10026 char_u *sfname;
10027 char_u *ffname;
10028{
10029 char_u buf[100];
10030 char_u *tail;
10031 char_u *regpat;
10032 char allow_dirs;
10033 int match;
10034 char_u *p;
10035
10036 tail = gettail(sfname);
10037
10038 /* try all patterns in 'wildignore' */
10039 p = list;
10040 while (*p)
10041 {
10042 copy_option_part(&p, buf, 100, ",");
10043 regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, FALSE);
10044 if (regpat == NULL)
10045 break;
Bram Moolenaar748bf032005-02-02 23:04:36 +000010046 match = match_file_pat(regpat, NULL, ffname, sfname,
10047 tail, (int)allow_dirs);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010048 vim_free(regpat);
10049 if (match)
10050 return TRUE;
10051 }
10052 return FALSE;
10053}
10054#endif
10055
10056/*
10057 * Convert the given pattern "pat" which has shell style wildcards in it, into
10058 * a regular expression, and return the result in allocated memory. If there
10059 * is a directory path separator to be matched, then TRUE is put in
10060 * allow_dirs, otherwise FALSE is put there -- webb.
10061 * Handle backslashes before special characters, like "\*" and "\ ".
10062 *
10063 * If FEAT_OSFILETYPE defined then pass initial <type> through unchanged. Eg:
10064 * '<html>myfile' becomes '<html>^myfile$' -- leonard.
10065 *
10066 * Returns NULL when out of memory.
10067 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010068 char_u *
10069file_pat_to_reg_pat(pat, pat_end, allow_dirs, no_bslash)
10070 char_u *pat;
10071 char_u *pat_end; /* first char after pattern or NULL */
10072 char *allow_dirs; /* Result passed back out in here */
Bram Moolenaar78a15312009-05-15 19:33:18 +000010073 int no_bslash UNUSED; /* Don't use a backward slash as pathsep */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010074{
10075 int size;
10076 char_u *endp;
10077 char_u *reg_pat;
10078 char_u *p;
10079 int i;
10080 int nested = 0;
10081 int add_dollar = TRUE;
10082#ifdef FEAT_OSFILETYPE
10083 int check_length = 0;
10084#endif
10085
10086 if (allow_dirs != NULL)
10087 *allow_dirs = FALSE;
10088 if (pat_end == NULL)
10089 pat_end = pat + STRLEN(pat);
10090
10091#ifdef FEAT_OSFILETYPE
10092 /* Find out how much of the string is the filetype check */
10093 if (*pat == '<')
10094 {
10095 /* Count chars until the next '>' */
10096 for (p = pat + 1; p < pat_end && *p != '>'; p++)
10097 ;
10098 if (p < pat_end)
10099 {
10100 /* Pattern is of the form <.*>.* */
10101 check_length = p - pat + 1;
10102 if (p + 1 >= pat_end)
10103 {
10104 /* The 'pattern' is a filetype check ONLY */
10105 reg_pat = (char_u *)alloc(check_length + 1);
10106 if (reg_pat != NULL)
10107 {
10108 mch_memmove(reg_pat, pat, (size_t)check_length);
10109 reg_pat[check_length] = NUL;
10110 }
10111 return reg_pat;
10112 }
10113 }
10114 /* else: there was no closing '>' - assume it was a normal pattern */
10115
10116 }
10117 pat += check_length;
10118 size = 2 + check_length;
10119#else
10120 size = 2; /* '^' at start, '$' at end */
10121#endif
10122
10123 for (p = pat; p < pat_end; p++)
10124 {
10125 switch (*p)
10126 {
10127 case '*':
10128 case '.':
10129 case ',':
10130 case '{':
10131 case '}':
10132 case '~':
10133 size += 2; /* extra backslash */
10134 break;
10135#ifdef BACKSLASH_IN_FILENAME
10136 case '\\':
10137 case '/':
10138 size += 4; /* could become "[\/]" */
10139 break;
10140#endif
10141 default:
10142 size++;
10143# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010144 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010145 {
10146 ++p;
10147 ++size;
10148 }
10149# endif
10150 break;
10151 }
10152 }
10153 reg_pat = alloc(size + 1);
10154 if (reg_pat == NULL)
10155 return NULL;
10156
10157#ifdef FEAT_OSFILETYPE
10158 /* Copy the type check in to the start. */
10159 if (check_length)
10160 mch_memmove(reg_pat, pat - check_length, (size_t)check_length);
10161 i = check_length;
10162#else
10163 i = 0;
10164#endif
10165
10166 if (pat[0] == '*')
10167 while (pat[0] == '*' && pat < pat_end - 1)
10168 pat++;
10169 else
10170 reg_pat[i++] = '^';
10171 endp = pat_end - 1;
10172 if (*endp == '*')
10173 {
10174 while (endp - pat > 0 && *endp == '*')
10175 endp--;
10176 add_dollar = FALSE;
10177 }
10178 for (p = pat; *p && nested >= 0 && p <= endp; p++)
10179 {
10180 switch (*p)
10181 {
10182 case '*':
10183 reg_pat[i++] = '.';
10184 reg_pat[i++] = '*';
Bram Moolenaar02743632005-07-25 20:42:36 +000010185 while (p[1] == '*') /* "**" matches like "*" */
10186 ++p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010187 break;
10188 case '.':
10189#ifdef RISCOS
10190 if (allow_dirs != NULL)
10191 *allow_dirs = TRUE;
10192 /* FALLTHROUGH */
10193#endif
10194 case '~':
10195 reg_pat[i++] = '\\';
10196 reg_pat[i++] = *p;
10197 break;
10198 case '?':
10199#ifdef RISCOS
10200 case '#':
10201#endif
10202 reg_pat[i++] = '.';
10203 break;
10204 case '\\':
10205 if (p[1] == NUL)
10206 break;
10207#ifdef BACKSLASH_IN_FILENAME
10208 if (!no_bslash)
10209 {
10210 /* translate:
10211 * "\x" to "\\x" e.g., "dir\file"
10212 * "\*" to "\\.*" e.g., "dir\*.c"
10213 * "\?" to "\\." e.g., "dir\??.c"
10214 * "\+" to "\+" e.g., "fileX\+.c"
10215 */
10216 if ((vim_isfilec(p[1]) || p[1] == '*' || p[1] == '?')
10217 && p[1] != '+')
10218 {
10219 reg_pat[i++] = '[';
10220 reg_pat[i++] = '\\';
10221 reg_pat[i++] = '/';
10222 reg_pat[i++] = ']';
10223 if (allow_dirs != NULL)
10224 *allow_dirs = TRUE;
10225 break;
10226 }
10227 }
10228#endif
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010229 /* Undo escaping from ExpandEscape():
10230 * foo\?bar -> foo?bar
10231 * foo\%bar -> foo%bar
10232 * foo\,bar -> foo,bar
10233 * foo\ bar -> foo bar
10234 * Don't unescape \, * and others that are also special in a
10235 * regexp. */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010236 if (*++p == '?'
10237#ifdef BACKSLASH_IN_FILENAME
10238 && no_bslash
10239#endif
10240 )
10241 reg_pat[i++] = '?';
10242 else
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010243 if (*p == ',' || *p == '%' || *p == '#' || *p == ' ')
10244 reg_pat[i++] = *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010245 else
10246 {
10247 if (allow_dirs != NULL && vim_ispathsep(*p)
10248#ifdef BACKSLASH_IN_FILENAME
10249 && (!no_bslash || *p != '\\')
10250#endif
10251 )
10252 *allow_dirs = TRUE;
10253 reg_pat[i++] = '\\';
10254 reg_pat[i++] = *p;
10255 }
10256 break;
10257#ifdef BACKSLASH_IN_FILENAME
10258 case '/':
10259 reg_pat[i++] = '[';
10260 reg_pat[i++] = '\\';
10261 reg_pat[i++] = '/';
10262 reg_pat[i++] = ']';
10263 if (allow_dirs != NULL)
10264 *allow_dirs = TRUE;
10265 break;
10266#endif
10267 case '{':
10268 reg_pat[i++] = '\\';
10269 reg_pat[i++] = '(';
10270 nested++;
10271 break;
10272 case '}':
10273 reg_pat[i++] = '\\';
10274 reg_pat[i++] = ')';
10275 --nested;
10276 break;
10277 case ',':
10278 if (nested)
10279 {
10280 reg_pat[i++] = '\\';
10281 reg_pat[i++] = '|';
10282 }
10283 else
10284 reg_pat[i++] = ',';
10285 break;
10286 default:
10287# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010288 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010289 reg_pat[i++] = *p++;
10290 else
10291# endif
10292 if (allow_dirs != NULL && vim_ispathsep(*p))
10293 *allow_dirs = TRUE;
10294 reg_pat[i++] = *p;
10295 break;
10296 }
10297 }
10298 if (add_dollar)
10299 reg_pat[i++] = '$';
10300 reg_pat[i] = NUL;
10301 if (nested != 0)
10302 {
10303 if (nested < 0)
10304 EMSG(_("E219: Missing {."));
10305 else
10306 EMSG(_("E220: Missing }."));
10307 vim_free(reg_pat);
10308 reg_pat = NULL;
10309 }
10310 return reg_pat;
10311}
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010312
10313#if defined(EINTR) || defined(PROTO)
10314/*
10315 * Version of read() that retries when interrupted by EINTR (possibly
10316 * by a SIGWINCH).
10317 */
10318 long
10319read_eintr(fd, buf, bufsize)
10320 int fd;
10321 void *buf;
10322 size_t bufsize;
10323{
10324 long ret;
10325
10326 for (;;)
10327 {
10328 ret = vim_read(fd, buf, bufsize);
10329 if (ret >= 0 || errno != EINTR)
10330 break;
10331 }
10332 return ret;
10333}
10334
10335/*
10336 * Version of write() that retries when interrupted by EINTR (possibly
10337 * by a SIGWINCH).
10338 */
10339 long
10340write_eintr(fd, buf, bufsize)
10341 int fd;
10342 void *buf;
10343 size_t bufsize;
10344{
10345 long ret = 0;
10346 long wlen;
10347
10348 /* Repeat the write() so long it didn't fail, other than being interrupted
10349 * by a signal. */
10350 while (ret < (long)bufsize)
10351 {
Bram Moolenaar9c263032010-12-17 18:06:06 +010010352 wlen = vim_write(fd, (char *)buf + ret, bufsize - ret);
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010353 if (wlen < 0)
10354 {
10355 if (errno != EINTR)
10356 break;
10357 }
10358 else
10359 ret += wlen;
10360 }
10361 return ret;
10362}
10363#endif