blob: bfc11d0d954a3497a3e69ce4a957e4b7cd595872 [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
14#if defined(MSDOS) || defined(WIN16) || defined(WIN32) || defined(_WIN64)
Bram Moolenaar362e1a32006-03-06 23:29:24 +000015# include "vimio.h" /* for lseek(), must be before vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +000016#endif
17
18#if defined __EMX__
Bram Moolenaar362e1a32006-03-06 23:29:24 +000019# include "vimio.h" /* for mktemp(), CJW 1997-12-03 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000020#endif
21
22#include "vim.h"
23
Bram Moolenaarf4888d02009-12-02 12:31:27 +000024#if defined(__TANDEM) || defined(__MINT__)
Bram Moolenaar071d4272004-06-13 20:20:40 +000025# include <limits.h> /* for SSIZE_MAX */
26#endif
27
28#if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
29# include <utime.h> /* for struct utimbuf */
30#endif
31
32#define BUFSIZE 8192 /* size of normal write buffer */
33#define SMBUFSIZE 256 /* size of emergency write buffer */
34
35#ifdef FEAT_CRYPT
Bram Moolenaar40e6a712010-05-16 22:32:54 +020036/* crypt_magic[0] is pkzip crypt, crypt_magic[1] is sha2+blowfish */
Bram Moolenaarf50a2532010-05-21 15:36:08 +020037static char *crypt_magic[] = {"VimCrypt~01!", "VimCrypt~02!"};
38static char crypt_magic_head[] = "VimCrypt~";
39# define CRYPT_MAGIC_LEN 12 /* must be multiple of 4! */
Bram Moolenaar80794b12010-06-13 05:20:42 +020040
41/* For blowfish, after the magic header, we store 8 bytes of salt and then 8
42 * bytes of seed (initialisation vector). */
43static int crypt_salt_len[] = {0, 8};
Bram Moolenaarf50a2532010-05-21 15:36:08 +020044static int crypt_seed_len[] = {0, 8};
Bram Moolenaar80794b12010-06-13 05:20:42 +020045#define CRYPT_SALT_LEN_MAX 8
Bram Moolenaar40e6a712010-05-16 22:32:54 +020046#define CRYPT_SEED_LEN_MAX 8
Bram Moolenaar071d4272004-06-13 20:20:40 +000047#endif
48
49/* Is there any system that doesn't have access()? */
Bram Moolenaar9372a112005-12-06 19:59:18 +000050#define USE_MCH_ACCESS
Bram Moolenaar071d4272004-06-13 20:20:40 +000051
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +000052#if defined(sun) && defined(S_ISCHR)
53# define OPEN_CHR_FILES
54static int is_dev_fd_file(char_u *fname);
55#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000056#ifdef FEAT_MBYTE
57static char_u *next_fenc __ARGS((char_u **pp));
58# ifdef FEAT_EVAL
59static char_u *readfile_charconvert __ARGS((char_u *fname, char_u *fenc, int *fdp));
60# endif
61#endif
62#ifdef FEAT_VIMINFO
63static void check_marks_read __ARGS((void));
64#endif
65#ifdef FEAT_CRYPT
Bram Moolenaar40e6a712010-05-16 22:32:54 +020066static int get_crypt_method __ARGS((char *ptr, int len));
Bram Moolenaar914703b2010-05-31 21:59:46 +020067static char_u *check_for_cryptkey __ARGS((char_u *cryptkey, char_u *ptr, long *sizep, off_t *filesizep, int newfile, int *did_ask));
Bram Moolenaar071d4272004-06-13 20:20:40 +000068#endif
69#ifdef UNIX
70static void set_file_time __ARGS((char_u *fname, time_t atime, time_t mtime));
71#endif
Bram Moolenaar2d3f4892006-01-20 23:02:51 +000072static int set_rw_fname __ARGS((char_u *fname, char_u *sfname));
Bram Moolenaar071d4272004-06-13 20:20:40 +000073static int msg_add_fileformat __ARGS((int eol_type));
Bram Moolenaar071d4272004-06-13 20:20:40 +000074static void msg_add_eol __ARGS((void));
75static int check_mtime __ARGS((buf_T *buf, struct stat *s));
76static int time_differs __ARGS((long t1, long t2));
77#ifdef FEAT_AUTOCMD
Bram Moolenaar754b5602006-02-09 23:53:20 +000078static 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 +000079static int au_find_group __ARGS((char_u *name));
80
81# define AUGROUP_DEFAULT -1 /* default autocmd group */
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +000082# define AUGROUP_ERROR -2 /* erroneous autocmd group */
Bram Moolenaar70836c82006-02-20 21:28:49 +000083# define AUGROUP_ALL -3 /* all autocmd groups */
Bram Moolenaar071d4272004-06-13 20:20:40 +000084#endif
85
86#if defined(FEAT_CRYPT) || defined(FEAT_MBYTE)
87# define HAS_BW_FLAGS
88# define FIO_LATIN1 0x01 /* convert Latin1 */
89# define FIO_UTF8 0x02 /* convert UTF-8 */
90# define FIO_UCS2 0x04 /* convert UCS-2 */
91# define FIO_UCS4 0x08 /* convert UCS-4 */
92# define FIO_UTF16 0x10 /* convert UTF-16 */
93# ifdef WIN3264
94# define FIO_CODEPAGE 0x20 /* convert MS-Windows codepage */
95# define FIO_PUT_CP(x) (((x) & 0xffff) << 16) /* put codepage in top word */
96# define FIO_GET_CP(x) (((x)>>16) & 0xffff) /* get codepage from top word */
97# endif
98# ifdef MACOS_X
99# define FIO_MACROMAN 0x20 /* convert MacRoman */
100# endif
101# define FIO_ENDIAN_L 0x80 /* little endian */
102# define FIO_ENCRYPTED 0x1000 /* encrypt written bytes */
103# define FIO_NOCONVERT 0x2000 /* skip encoding conversion */
104# define FIO_UCSBOM 0x4000 /* check for BOM at start of file */
105# define FIO_ALL -1 /* allow all formats */
106#endif
107
108/* When converting, a read() or write() may leave some bytes to be converted
109 * for the next call. The value is guessed... */
110#define CONV_RESTLEN 30
111
112/* We have to guess how much a sequence of bytes may expand when converting
113 * with iconv() to be able to allocate a buffer. */
114#define ICONV_MULT 8
115
116/*
117 * Structure to pass arguments from buf_write() to buf_write_bytes().
118 */
119struct bw_info
120{
121 int bw_fd; /* file descriptor */
122 char_u *bw_buf; /* buffer with data to be written */
Bram Moolenaard089d9b2007-09-30 12:02:55 +0000123 int bw_len; /* length of data */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000124#ifdef HAS_BW_FLAGS
125 int bw_flags; /* FIO_ flags */
126#endif
127#ifdef FEAT_MBYTE
128 char_u bw_rest[CONV_RESTLEN]; /* not converted bytes */
129 int bw_restlen; /* nr of bytes in bw_rest[] */
130 int bw_first; /* first write call */
131 char_u *bw_conv_buf; /* buffer for writing converted chars */
132 int bw_conv_buflen; /* size of bw_conv_buf */
133 int bw_conv_error; /* set for conversion error */
Bram Moolenaar32b485f2009-07-29 16:06:27 +0000134 linenr_T bw_conv_error_lnum; /* first line with error or zero */
135 linenr_T bw_start_lnum; /* line number at start of buffer */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000136# ifdef USE_ICONV
137 iconv_t bw_iconv_fd; /* descriptor for iconv() or -1 */
138# endif
139#endif
140};
141
142static int buf_write_bytes __ARGS((struct bw_info *ip));
143
144#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000145static linenr_T readfile_linenr __ARGS((linenr_T linecnt, char_u *p, char_u *endp));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000146static int ucs2bytes __ARGS((unsigned c, char_u **pp, int flags));
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +0000147static int need_conversion __ARGS((char_u *fenc));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000148static int get_fio_flags __ARGS((char_u *ptr));
149static char_u *check_for_bom __ARGS((char_u *p, long size, int *lenp, int flags));
150static int make_bom __ARGS((char_u *buf, char_u *name));
151# ifdef WIN3264
152static int get_win_fio_flags __ARGS((char_u *ptr));
153# endif
154# ifdef MACOS_X
155static int get_mac_fio_flags __ARGS((char_u *ptr));
156# endif
157#endif
158static int move_lines __ARGS((buf_T *frombuf, buf_T *tobuf));
Bram Moolenaar4592dee2009-11-18 19:11:58 +0000159#ifdef TEMPDIRNAMES
Bram Moolenaareaf03392009-11-17 11:08:52 +0000160static void vim_settempdir __ARGS((char_u *tempdir));
Bram Moolenaar4592dee2009-11-18 19:11:58 +0000161#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000162#ifdef FEAT_AUTOCMD
163static char *e_auchangedbuf = N_("E812: Autocommands changed buffer or buffer name");
164#endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000165
Bram Moolenaar071d4272004-06-13 20:20:40 +0000166 void
167filemess(buf, name, s, attr)
168 buf_T *buf;
169 char_u *name;
170 char_u *s;
171 int attr;
172{
173 int msg_scroll_save;
174
175 if (msg_silent != 0)
176 return;
177 msg_add_fname(buf, name); /* put file name in IObuff with quotes */
178 /* If it's extremely long, truncate it. */
179 if (STRLEN(IObuff) > IOSIZE - 80)
180 IObuff[IOSIZE - 80] = NUL;
181 STRCAT(IObuff, s);
182 /*
183 * For the first message may have to start a new line.
184 * For further ones overwrite the previous one, reset msg_scroll before
185 * calling filemess().
186 */
187 msg_scroll_save = msg_scroll;
188 if (shortmess(SHM_OVERALL) && !exiting && p_verbose == 0)
189 msg_scroll = FALSE;
190 if (!msg_scroll) /* wait a bit when overwriting an error msg */
191 check_for_delay(FALSE);
192 msg_start();
193 msg_scroll = msg_scroll_save;
194 msg_scrolled_ign = TRUE;
195 /* may truncate the message to avoid a hit-return prompt */
196 msg_outtrans_attr(msg_may_trunc(FALSE, IObuff), attr);
197 msg_clr_eos();
198 out_flush();
199 msg_scrolled_ign = FALSE;
200}
201
202/*
203 * Read lines from file "fname" into the buffer after line "from".
204 *
205 * 1. We allocate blocks with lalloc, as big as possible.
206 * 2. Each block is filled with characters from the file with a single read().
207 * 3. The lines are inserted in the buffer with ml_append().
208 *
209 * (caller must check that fname != NULL, unless READ_STDIN is used)
210 *
211 * "lines_to_skip" is the number of lines that must be skipped
212 * "lines_to_read" is the number of lines that are appended
213 * When not recovering lines_to_skip is 0 and lines_to_read MAXLNUM.
214 *
215 * flags:
216 * READ_NEW starting to edit a new buffer
217 * READ_FILTER reading filter output
218 * READ_STDIN read from stdin instead of a file
219 * READ_BUFFER read from curbuf instead of a file (converting after reading
220 * stdin)
221 * READ_DUMMY read into a dummy buffer (to check if file contents changed)
222 *
223 * return FAIL for failure, OK otherwise
224 */
225 int
226readfile(fname, sfname, from, lines_to_skip, lines_to_read, eap, flags)
227 char_u *fname;
228 char_u *sfname;
229 linenr_T from;
230 linenr_T lines_to_skip;
231 linenr_T lines_to_read;
232 exarg_T *eap; /* can be NULL! */
233 int flags;
234{
235 int fd = 0;
236 int newfile = (flags & READ_NEW);
237 int check_readonly;
238 int filtering = (flags & READ_FILTER);
239 int read_stdin = (flags & READ_STDIN);
240 int read_buffer = (flags & READ_BUFFER);
Bram Moolenaar690ffc02008-01-04 15:31:21 +0000241 int set_options = newfile || read_buffer
242 || (eap != NULL && eap->read_edit);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000243 linenr_T read_buf_lnum = 1; /* next line to read from curbuf */
244 colnr_T read_buf_col = 0; /* next char to read from this line */
245 char_u c;
246 linenr_T lnum = from;
247 char_u *ptr = NULL; /* pointer into read buffer */
248 char_u *buffer = NULL; /* read buffer */
249 char_u *new_buffer = NULL; /* init to shut up gcc */
250 char_u *line_start = NULL; /* init to shut up gcc */
251 int wasempty; /* buffer was empty before reading */
252 colnr_T len;
253 long size = 0;
254 char_u *p;
Bram Moolenaar914703b2010-05-31 21:59:46 +0200255 off_t filesize = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000256 int skip_read = FALSE;
257#ifdef FEAT_CRYPT
258 char_u *cryptkey = NULL;
Bram Moolenaarf50a2532010-05-21 15:36:08 +0200259 int did_ask_for_key = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000260#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +0200261#ifdef FEAT_PERSISTENT_UNDO
262 context_sha256_T sha_ctx;
263 int read_undo_file = FALSE;
264#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000265 int split = 0; /* number of split lines */
266#define UNKNOWN 0x0fffffff /* file size is unknown */
267 linenr_T linecnt;
268 int error = FALSE; /* errors encountered */
269 int ff_error = EOL_UNKNOWN; /* file format with errors */
270 long linerest = 0; /* remaining chars in line */
271#ifdef UNIX
272 int perm = 0;
273 int swap_mode = -1; /* protection bits for swap file */
274#else
275 int perm;
276#endif
277 int fileformat = 0; /* end-of-line format */
278 int keep_fileformat = FALSE;
279 struct stat st;
280 int file_readonly;
281 linenr_T skip_count = 0;
282 linenr_T read_count = 0;
283 int msg_save = msg_scroll;
284 linenr_T read_no_eol_lnum = 0; /* non-zero lnum when last line of
285 * last read was missing the eol */
286 int try_mac = (vim_strchr(p_ffs, 'm') != NULL);
287 int try_dos = (vim_strchr(p_ffs, 'd') != NULL);
288 int try_unix = (vim_strchr(p_ffs, 'x') != NULL);
289 int file_rewind = FALSE;
290#ifdef FEAT_MBYTE
291 int can_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000292 linenr_T conv_error = 0; /* line nr with conversion error */
293 linenr_T illegal_byte = 0; /* line nr with illegal byte */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000294 int keep_dest_enc = FALSE; /* don't retry when char doesn't fit
295 in destination encoding */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000296 int bad_char_behavior = BAD_REPLACE;
297 /* BAD_KEEP, BAD_DROP or character to
298 * replace with */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000299 char_u *tmpname = NULL; /* name of 'charconvert' output file */
300 int fio_flags = 0;
301 char_u *fenc; /* fileencoding to use */
302 int fenc_alloced; /* fenc_next is in allocated memory */
303 char_u *fenc_next = NULL; /* next item in 'fencs' or NULL */
304 int advance_fenc = FALSE;
305 long real_size = 0;
306# ifdef USE_ICONV
307 iconv_t iconv_fd = (iconv_t)-1; /* descriptor for iconv() or -1 */
308# ifdef FEAT_EVAL
309 int did_iconv = FALSE; /* TRUE when iconv() failed and trying
310 'charconvert' next */
311# endif
312# endif
313 int converted = FALSE; /* TRUE if conversion done */
314 int notconverted = FALSE; /* TRUE if conversion wanted but it
315 wasn't possible */
316 char_u conv_rest[CONV_RESTLEN];
317 int conv_restlen = 0; /* nr of bytes in conv_rest[] */
318#endif
319
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000320#ifdef FEAT_AUTOCMD
321 /* Remember the initial values of curbuf, curbuf->b_ffname and
322 * curbuf->b_fname to detect whether they are altered as a result of
323 * executing nasty autocommands. Also check if "fname" and "sfname"
324 * point to one of these values. */
325 buf_T *old_curbuf = curbuf;
326 char_u *old_b_ffname = curbuf->b_ffname;
327 char_u *old_b_fname = curbuf->b_fname;
328 int using_b_ffname = (fname == curbuf->b_ffname)
329 || (sfname == curbuf->b_ffname);
330 int using_b_fname = (fname == curbuf->b_fname)
331 || (sfname == curbuf->b_fname);
332#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000333 write_no_eol_lnum = 0; /* in case it was set by the previous read */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000334
335 /*
336 * If there is no file name yet, use the one for the read file.
337 * BF_NOTEDITED is set to reflect this.
338 * Don't do this for a read from a filter.
339 * Only do this when 'cpoptions' contains the 'f' flag.
340 */
341 if (curbuf->b_ffname == NULL
342 && !filtering
343 && fname != NULL
344 && vim_strchr(p_cpo, CPO_FNAMER) != NULL
345 && !(flags & READ_DUMMY))
346 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000347 if (set_rw_fname(fname, sfname) == FAIL)
348 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000349 }
350
Bram Moolenaardf177f62005-02-22 08:39:57 +0000351 /* After reading a file the cursor line changes but we don't want to
352 * display the line. */
353 ex_no_reprint = TRUE;
354
Bram Moolenaar55b7cf82006-09-09 12:52:42 +0000355 /* don't display the file info for another buffer now */
356 need_fileinfo = FALSE;
357
Bram Moolenaar071d4272004-06-13 20:20:40 +0000358 /*
359 * For Unix: Use the short file name whenever possible.
360 * Avoids problems with networks and when directory names are changed.
361 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
362 * another directory, which we don't detect.
363 */
364 if (sfname == NULL)
365 sfname = fname;
366#if defined(UNIX) || defined(__EMX__)
367 fname = sfname;
368#endif
369
370#ifdef FEAT_AUTOCMD
371 /*
372 * The BufReadCmd and FileReadCmd events intercept the reading process by
373 * executing the associated commands instead.
374 */
375 if (!filtering && !read_stdin && !read_buffer)
376 {
377 pos_T pos;
378
379 pos = curbuf->b_op_start;
380
381 /* Set '[ mark to the line above where the lines go (line 1 if zero). */
382 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
383 curbuf->b_op_start.col = 0;
384
385 if (newfile)
386 {
387 if (apply_autocmds_exarg(EVENT_BUFREADCMD, NULL, sfname,
388 FALSE, curbuf, eap))
389#ifdef FEAT_EVAL
390 return aborting() ? FAIL : OK;
391#else
392 return OK;
393#endif
394 }
395 else if (apply_autocmds_exarg(EVENT_FILEREADCMD, sfname, sfname,
396 FALSE, NULL, eap))
397#ifdef FEAT_EVAL
398 return aborting() ? FAIL : OK;
399#else
400 return OK;
401#endif
402
403 curbuf->b_op_start = pos;
404 }
405#endif
406
407 if ((shortmess(SHM_OVER) || curbuf->b_help) && p_verbose == 0)
408 msg_scroll = FALSE; /* overwrite previous file message */
409 else
410 msg_scroll = TRUE; /* don't overwrite previous file message */
411
412 /*
413 * If the name ends in a path separator, we can't open it. Check here,
414 * because reading the file may actually work, but then creating the swap
415 * file may destroy it! Reported on MS-DOS and Win 95.
416 * If the name is too long we might crash further on, quit here.
417 */
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000418 if (fname != NULL && *fname != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000419 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000420 p = fname + STRLEN(fname);
421 if (after_pathsep(fname, p) || STRLEN(fname) >= MAXPATHL)
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000422 {
423 filemess(curbuf, fname, (char_u *)_("Illegal file name"), 0);
424 msg_end();
425 msg_scroll = msg_save;
426 return FAIL;
427 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000428 }
429
430#ifdef UNIX
431 /*
432 * On Unix it is possible to read a directory, so we have to
433 * check for it before the mch_open().
434 */
435 if (!read_stdin && !read_buffer)
436 {
437 perm = mch_getperm(fname);
438 if (perm >= 0 && !S_ISREG(perm) /* not a regular file ... */
439# ifdef S_ISFIFO
440 && !S_ISFIFO(perm) /* ... or fifo */
441# endif
442# ifdef S_ISSOCK
443 && !S_ISSOCK(perm) /* ... or socket */
444# endif
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +0000445# ifdef OPEN_CHR_FILES
446 && !(S_ISCHR(perm) && is_dev_fd_file(fname))
447 /* ... or a character special file named /dev/fd/<n> */
448# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000449 )
450 {
451 if (S_ISDIR(perm))
452 filemess(curbuf, fname, (char_u *)_("is a directory"), 0);
453 else
454 filemess(curbuf, fname, (char_u *)_("is not a file"), 0);
455 msg_end();
456 msg_scroll = msg_save;
457 return FAIL;
458 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000459
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000460# if defined(MSDOS) || defined(MSWIN) || defined(OS2)
461 /*
462 * MS-Windows allows opening a device, but we will probably get stuck
463 * trying to read it.
464 */
465 if (!p_odev && mch_nodetype(fname) == NODE_WRITABLE)
466 {
Bram Moolenaar5386a122007-06-28 20:02:32 +0000467 filemess(curbuf, fname, (char_u *)_("is a device (disabled with 'opendevice' option)"), 0);
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000468 msg_end();
469 msg_scroll = msg_save;
470 return FAIL;
471 }
472# endif
Bram Moolenaar043545e2006-10-10 16:44:07 +0000473 }
474#endif
475
Bram Moolenaar071d4272004-06-13 20:20:40 +0000476 /* set default 'fileformat' */
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000477 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000478 {
479 if (eap != NULL && eap->force_ff != 0)
480 set_fileformat(get_fileformat_force(curbuf, eap), OPT_LOCAL);
481 else if (*p_ffs != NUL)
482 set_fileformat(default_fileformat(), OPT_LOCAL);
483 }
484
485 /* set or reset 'binary' */
486 if (eap != NULL && eap->force_bin != 0)
487 {
488 int oldval = curbuf->b_p_bin;
489
490 curbuf->b_p_bin = (eap->force_bin == FORCE_BIN);
491 set_options_bin(oldval, curbuf->b_p_bin, OPT_LOCAL);
492 }
493
494 /*
495 * When opening a new file we take the readonly flag from the file.
496 * Default is r/w, can be set to r/o below.
497 * Don't reset it when in readonly mode
498 * Only set/reset b_p_ro when BF_CHECK_RO is set.
499 */
500 check_readonly = (newfile && (curbuf->b_flags & BF_CHECK_RO));
Bram Moolenaar4399ef42005-02-12 14:29:27 +0000501 if (check_readonly && !readonlymode)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000502 curbuf->b_p_ro = FALSE;
503
504 if (newfile && !read_stdin && !read_buffer)
505 {
506 /* Remember time of file.
507 * For RISCOS, also remember the filetype.
508 */
509 if (mch_stat((char *)fname, &st) >= 0)
510 {
511 buf_store_time(curbuf, &st, fname);
512 curbuf->b_mtime_read = curbuf->b_mtime;
513
514#if defined(RISCOS) && defined(FEAT_OSFILETYPE)
515 /* Read the filetype into the buffer local filetype option. */
516 mch_read_filetype(fname);
517#endif
518#ifdef UNIX
519 /*
520 * Use the protection bits of the original file for the swap file.
521 * This makes it possible for others to read the name of the
522 * edited file from the swapfile, but only if they can read the
523 * edited file.
524 * Remove the "write" and "execute" bits for group and others
525 * (they must not write the swapfile).
526 * Add the "read" and "write" bits for the user, otherwise we may
527 * not be able to write to the file ourselves.
528 * Setting the bits is done below, after creating the swap file.
529 */
530 swap_mode = (st.st_mode & 0644) | 0600;
531#endif
532#ifdef FEAT_CW_EDITOR
533 /* Get the FSSpec on MacOS
534 * TODO: Update it properly when the buffer name changes
535 */
536 (void)GetFSSpecFromPath(curbuf->b_ffname, &curbuf->b_FSSpec);
537#endif
538#ifdef VMS
539 curbuf->b_fab_rfm = st.st_fab_rfm;
Bram Moolenaard4755bb2004-09-02 19:12:26 +0000540 curbuf->b_fab_rat = st.st_fab_rat;
541 curbuf->b_fab_mrs = st.st_fab_mrs;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000542#endif
543 }
544 else
545 {
546 curbuf->b_mtime = 0;
547 curbuf->b_mtime_read = 0;
548 curbuf->b_orig_size = 0;
549 curbuf->b_orig_mode = 0;
550 }
551
552 /* Reset the "new file" flag. It will be set again below when the
553 * file doesn't exist. */
554 curbuf->b_flags &= ~(BF_NEW | BF_NEW_W);
555 }
556
557/*
558 * for UNIX: check readonly with perm and mch_access()
559 * for RISCOS: same as Unix, otherwise file gets re-datestamped!
560 * for MSDOS and Amiga: check readonly by trying to open the file for writing
561 */
562 file_readonly = FALSE;
563 if (read_stdin)
564 {
565#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
566 /* Force binary I/O on stdin to avoid CR-LF -> LF conversion. */
567 setmode(0, O_BINARY);
568#endif
569 }
570 else if (!read_buffer)
571 {
572#ifdef USE_MCH_ACCESS
573 if (
574# ifdef UNIX
575 !(perm & 0222) ||
576# endif
577 mch_access((char *)fname, W_OK))
578 file_readonly = TRUE;
579 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
580#else
581 if (!newfile
582 || readonlymode
583 || (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0)
584 {
585 file_readonly = TRUE;
586 /* try to open ro */
587 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
588 }
589#endif
590 }
591
592 if (fd < 0) /* cannot open at all */
593 {
594#ifndef UNIX
595 int isdir_f;
596#endif
597 msg_scroll = msg_save;
598#ifndef UNIX
599 /*
600 * On MSDOS and Amiga we can't open a directory, check here.
601 */
602 isdir_f = (mch_isdir(fname));
603 perm = mch_getperm(fname); /* check if the file exists */
604 if (isdir_f)
605 {
606 filemess(curbuf, sfname, (char_u *)_("is a directory"), 0);
607 curbuf->b_p_ro = TRUE; /* must use "w!" now */
608 }
609 else
610#endif
611 if (newfile)
612 {
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200613 if (perm < 0
614#ifdef ENOENT
615 && errno == ENOENT
616#endif
617 )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000618 {
619 /*
620 * Set the 'new-file' flag, so that when the file has
621 * been created by someone else, a ":w" will complain.
622 */
623 curbuf->b_flags |= BF_NEW;
624
625 /* Create a swap file now, so that other Vims are warned
626 * that we are editing this file. Don't do this for a
627 * "nofile" or "nowrite" buffer type. */
628#ifdef FEAT_QUICKFIX
629 if (!bt_dontwrite(curbuf))
630#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000631 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000632 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000633#ifdef FEAT_AUTOCMD
634 /* SwapExists autocommand may mess things up */
635 if (curbuf != old_curbuf
636 || (using_b_ffname
637 && (old_b_ffname != curbuf->b_ffname))
638 || (using_b_fname
639 && (old_b_fname != curbuf->b_fname)))
640 {
641 EMSG(_(e_auchangedbuf));
642 return FAIL;
643 }
644#endif
645 }
Bram Moolenaar5b962cf2005-12-12 21:58:40 +0000646 if (dir_of_file_exists(fname))
647 filemess(curbuf, sfname, (char_u *)_("[New File]"), 0);
648 else
649 filemess(curbuf, sfname,
650 (char_u *)_("[New DIRECTORY]"), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000651#ifdef FEAT_VIMINFO
652 /* Even though this is a new file, it might have been
653 * edited before and deleted. Get the old marks. */
654 check_marks_read();
655#endif
656#ifdef FEAT_MBYTE
657 if (eap != NULL && eap->force_enc != 0)
658 {
659 /* set forced 'fileencoding' */
660 fenc = enc_canonize(eap->cmd + eap->force_enc);
661 if (fenc != NULL)
662 set_string_option_direct((char_u *)"fenc", -1,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +0000663 fenc, OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000664 vim_free(fenc);
665 }
666#endif
667#ifdef FEAT_AUTOCMD
668 apply_autocmds_exarg(EVENT_BUFNEWFILE, sfname, sfname,
669 FALSE, curbuf, eap);
670#endif
671 /* remember the current fileformat */
672 save_file_ff(curbuf);
673
674#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
675 if (aborting()) /* autocmds may abort script processing */
676 return FAIL;
677#endif
678 return OK; /* a new file is not an error */
679 }
680 else
681 {
Bram Moolenaar202795b2005-10-11 20:29:39 +0000682 filemess(curbuf, sfname, (char_u *)(
683# ifdef EFBIG
684 (errno == EFBIG) ? _("[File too big]") :
685# endif
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200686# ifdef EOVERFLOW
687 (errno == EOVERFLOW) ? _("[File too big]") :
688# endif
Bram Moolenaar202795b2005-10-11 20:29:39 +0000689 _("[Permission Denied]")), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000690 curbuf->b_p_ro = TRUE; /* must use "w!" now */
691 }
692 }
693
694 return FAIL;
695 }
696
697 /*
698 * Only set the 'ro' flag for readonly files the first time they are
699 * loaded. Help files always get readonly mode
700 */
701 if ((check_readonly && file_readonly) || curbuf->b_help)
702 curbuf->b_p_ro = TRUE;
703
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000704 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000705 {
Bram Moolenaar690ffc02008-01-04 15:31:21 +0000706 /* Don't change 'eol' if reading from buffer as it will already be
707 * correctly set when reading stdin. */
708 if (!read_buffer)
709 {
710 curbuf->b_p_eol = TRUE;
711 curbuf->b_start_eol = TRUE;
712 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000713#ifdef FEAT_MBYTE
714 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000715 curbuf->b_start_bomb = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000716#endif
717 }
718
719 /* Create a swap file now, so that other Vims are warned that we are
720 * editing this file.
721 * Don't do this for a "nofile" or "nowrite" buffer type. */
722#ifdef FEAT_QUICKFIX
723 if (!bt_dontwrite(curbuf))
724#endif
725 {
726 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000727#ifdef FEAT_AUTOCMD
728 if (!read_stdin && (curbuf != old_curbuf
729 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
730 || (using_b_fname && (old_b_fname != curbuf->b_fname))))
731 {
732 EMSG(_(e_auchangedbuf));
733 if (!read_buffer)
734 close(fd);
735 return FAIL;
736 }
737#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000738#ifdef UNIX
739 /* Set swap file protection bits after creating it. */
Bram Moolenaarf061e0b2009-06-24 15:32:01 +0000740 if (swap_mode > 0 && curbuf->b_ml.ml_mfp != NULL
741 && curbuf->b_ml.ml_mfp->mf_fname != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000742 (void)mch_setperm(curbuf->b_ml.ml_mfp->mf_fname, (long)swap_mode);
743#endif
744 }
745
Bram Moolenaarb815dac2005-12-07 20:59:24 +0000746#if defined(HAS_SWAP_EXISTS_ACTION)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000747 /* If "Quit" selected at ATTENTION dialog, don't load the file */
748 if (swap_exists_action == SEA_QUIT)
749 {
750 if (!read_buffer && !read_stdin)
751 close(fd);
752 return FAIL;
753 }
754#endif
755
756 ++no_wait_return; /* don't wait for return yet */
757
758 /*
759 * Set '[ mark to the line above where the lines go (line 1 if zero).
760 */
761 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
762 curbuf->b_op_start.col = 0;
763
764#ifdef FEAT_AUTOCMD
765 if (!read_buffer)
766 {
767 int m = msg_scroll;
768 int n = msg_scrolled;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000769
770 /*
771 * The file must be closed again, the autocommands may want to change
772 * the file before reading it.
773 */
774 if (!read_stdin)
775 close(fd); /* ignore errors */
776
777 /*
778 * The output from the autocommands should not overwrite anything and
779 * should not be overwritten: Set msg_scroll, restore its value if no
780 * output was done.
781 */
782 msg_scroll = TRUE;
783 if (filtering)
784 apply_autocmds_exarg(EVENT_FILTERREADPRE, NULL, sfname,
785 FALSE, curbuf, eap);
786 else if (read_stdin)
787 apply_autocmds_exarg(EVENT_STDINREADPRE, NULL, sfname,
788 FALSE, curbuf, eap);
789 else if (newfile)
790 apply_autocmds_exarg(EVENT_BUFREADPRE, NULL, sfname,
791 FALSE, curbuf, eap);
792 else
793 apply_autocmds_exarg(EVENT_FILEREADPRE, sfname, sfname,
794 FALSE, NULL, eap);
795 if (msg_scrolled == n)
796 msg_scroll = m;
797
798#ifdef FEAT_EVAL
799 if (aborting()) /* autocmds may abort script processing */
800 {
801 --no_wait_return;
802 msg_scroll = msg_save;
803 curbuf->b_p_ro = TRUE; /* must use "w!" now */
804 return FAIL;
805 }
806#endif
807 /*
808 * Don't allow the autocommands to change the current buffer.
809 * Try to re-open the file.
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000810 *
811 * Don't allow the autocommands to change the buffer name either
812 * (cd for example) if it invalidates fname or sfname.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000813 */
814 if (!read_stdin && (curbuf != old_curbuf
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000815 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
816 || (using_b_fname && (old_b_fname != curbuf->b_fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000817 || (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) < 0))
818 {
819 --no_wait_return;
820 msg_scroll = msg_save;
821 if (fd < 0)
822 EMSG(_("E200: *ReadPre autocommands made the file unreadable"));
823 else
824 EMSG(_("E201: *ReadPre autocommands must not change current buffer"));
825 curbuf->b_p_ro = TRUE; /* must use "w!" now */
826 return FAIL;
827 }
828 }
829#endif /* FEAT_AUTOCMD */
830
831 /* Autocommands may add lines to the file, need to check if it is empty */
832 wasempty = (curbuf->b_ml.ml_flags & ML_EMPTY);
833
834 if (!recoverymode && !filtering && !(flags & READ_DUMMY))
835 {
836 /*
837 * Show the user that we are busy reading the input. Sometimes this
838 * may take a while. When reading from stdin another program may
839 * still be running, don't move the cursor to the last line, unless
840 * always using the GUI.
841 */
842 if (read_stdin)
843 {
844#ifndef ALWAYS_USE_GUI
845 mch_msg(_("Vim: Reading from stdin...\n"));
846#endif
847#ifdef FEAT_GUI
848 /* Also write a message in the GUI window, if there is one. */
849 if (gui.in_use && !gui.dying && !gui.starting)
850 {
851 p = (char_u *)_("Reading from stdin...");
852 gui_write(p, (int)STRLEN(p));
853 }
854#endif
855 }
856 else if (!read_buffer)
857 filemess(curbuf, sfname, (char_u *)"", 0);
858 }
859
860 msg_scroll = FALSE; /* overwrite the file message */
861
862 /*
863 * Set linecnt now, before the "retry" caused by a wrong guess for
864 * fileformat, and after the autocommands, which may change them.
865 */
866 linecnt = curbuf->b_ml.ml_line_count;
867
868#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000869 /* "++bad=" argument. */
870 if (eap != NULL && eap->bad_char != 0)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000871 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000872 bad_char_behavior = eap->bad_char;
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000873 if (set_options)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000874 curbuf->b_bad_char = eap->bad_char;
875 }
876 else
877 curbuf->b_bad_char = 0;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000878
Bram Moolenaar071d4272004-06-13 20:20:40 +0000879 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000880 * Decide which 'encoding' to use or use first.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000881 */
882 if (eap != NULL && eap->force_enc != 0)
883 {
884 fenc = enc_canonize(eap->cmd + eap->force_enc);
885 fenc_alloced = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000886 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000887 }
888 else if (curbuf->b_p_bin)
889 {
890 fenc = (char_u *)""; /* binary: don't convert */
891 fenc_alloced = FALSE;
892 }
893 else if (curbuf->b_help)
894 {
895 char_u firstline[80];
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000896 int fc;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000897
898 /* Help files are either utf-8 or latin1. Try utf-8 first, if this
899 * fails it must be latin1.
900 * Always do this when 'encoding' is "utf-8". Otherwise only do
901 * this when needed to avoid [converted] remarks all the time.
902 * It is needed when the first line contains non-ASCII characters.
903 * That is only in *.??x files. */
904 fenc = (char_u *)"latin1";
905 c = enc_utf8;
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000906 if (!c && !read_stdin)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000907 {
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000908 fc = fname[STRLEN(fname) - 1];
909 if (TOLOWER_ASC(fc) == 'x')
910 {
911 /* Read the first line (and a bit more). Immediately rewind to
912 * the start of the file. If the read() fails "len" is -1. */
913 len = vim_read(fd, firstline, 80);
914 lseek(fd, (off_t)0L, SEEK_SET);
915 for (p = firstline; p < firstline + len; ++p)
916 if (*p >= 0x80)
917 {
918 c = TRUE;
919 break;
920 }
921 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000922 }
923
924 if (c)
925 {
926 fenc_next = fenc;
927 fenc = (char_u *)"utf-8";
928
929 /* When the file is utf-8 but a character doesn't fit in
930 * 'encoding' don't retry. In help text editing utf-8 bytes
931 * doesn't make sense. */
Bram Moolenaarf193fff2006-04-27 00:02:13 +0000932 if (!enc_utf8)
933 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000934 }
935 fenc_alloced = FALSE;
936 }
937 else if (*p_fencs == NUL)
938 {
939 fenc = curbuf->b_p_fenc; /* use format from buffer */
940 fenc_alloced = FALSE;
941 }
942 else
943 {
944 fenc_next = p_fencs; /* try items in 'fileencodings' */
945 fenc = next_fenc(&fenc_next);
946 fenc_alloced = TRUE;
947 }
948#endif
949
950 /*
951 * Jump back here to retry reading the file in different ways.
952 * Reasons to retry:
953 * - encoding conversion failed: try another one from "fenc_next"
954 * - BOM detected and fenc was set, need to setup conversion
955 * - "fileformat" check failed: try another
956 *
957 * Variables set for special retry actions:
958 * "file_rewind" Rewind the file to start reading it again.
959 * "advance_fenc" Advance "fenc" using "fenc_next".
960 * "skip_read" Re-use already read bytes (BOM detected).
961 * "did_iconv" iconv() conversion failed, try 'charconvert'.
962 * "keep_fileformat" Don't reset "fileformat".
963 *
964 * Other status indicators:
965 * "tmpname" When != NULL did conversion with 'charconvert'.
966 * Output file has to be deleted afterwards.
967 * "iconv_fd" When != -1 did conversion with iconv().
968 */
969retry:
970
971 if (file_rewind)
972 {
973 if (read_buffer)
974 {
975 read_buf_lnum = 1;
976 read_buf_col = 0;
977 }
978 else if (read_stdin || lseek(fd, (off_t)0L, SEEK_SET) != 0)
979 {
980 /* Can't rewind the file, give up. */
981 error = TRUE;
982 goto failed;
983 }
984 /* Delete the previously read lines. */
985 while (lnum > from)
986 ml_delete(lnum--, FALSE);
987 file_rewind = FALSE;
988#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000989 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000990 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000991 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000992 curbuf->b_start_bomb = FALSE;
993 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000994 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000995#endif
996 }
997
998 /*
999 * When retrying with another "fenc" and the first time "fileformat"
1000 * will be reset.
1001 */
1002 if (keep_fileformat)
1003 keep_fileformat = FALSE;
1004 else
1005 {
1006 if (eap != NULL && eap->force_ff != 0)
Bram Moolenaar1c860362008-11-12 15:05:21 +00001007 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001008 fileformat = get_fileformat_force(curbuf, eap);
Bram Moolenaar1c860362008-11-12 15:05:21 +00001009 try_unix = try_dos = try_mac = FALSE;
1010 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001011 else if (curbuf->b_p_bin)
1012 fileformat = EOL_UNIX; /* binary: use Unix format */
1013 else if (*p_ffs == NUL)
1014 fileformat = get_fileformat(curbuf);/* use format from buffer */
1015 else
1016 fileformat = EOL_UNKNOWN; /* detect from file */
1017 }
1018
1019#ifdef FEAT_MBYTE
1020# ifdef USE_ICONV
1021 if (iconv_fd != (iconv_t)-1)
1022 {
1023 /* aborted conversion with iconv(), close the descriptor */
1024 iconv_close(iconv_fd);
1025 iconv_fd = (iconv_t)-1;
1026 }
1027# endif
1028
1029 if (advance_fenc)
1030 {
1031 /*
1032 * Try the next entry in 'fileencodings'.
1033 */
1034 advance_fenc = FALSE;
1035
1036 if (eap != NULL && eap->force_enc != 0)
1037 {
1038 /* Conversion given with "++cc=" wasn't possible, read
1039 * without conversion. */
1040 notconverted = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001041 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001042 if (fenc_alloced)
1043 vim_free(fenc);
1044 fenc = (char_u *)"";
1045 fenc_alloced = FALSE;
1046 }
1047 else
1048 {
1049 if (fenc_alloced)
1050 vim_free(fenc);
1051 if (fenc_next != NULL)
1052 {
1053 fenc = next_fenc(&fenc_next);
1054 fenc_alloced = (fenc_next != NULL);
1055 }
1056 else
1057 {
1058 fenc = (char_u *)"";
1059 fenc_alloced = FALSE;
1060 }
1061 }
1062 if (tmpname != NULL)
1063 {
1064 mch_remove(tmpname); /* delete converted file */
1065 vim_free(tmpname);
1066 tmpname = NULL;
1067 }
1068 }
1069
1070 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001071 * Conversion may be required when the encoding of the file is different
1072 * from 'encoding' or 'encoding' is UTF-16, UCS-2 or UCS-4.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001073 */
1074 fio_flags = 0;
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001075 converted = need_conversion(fenc);
1076 if (converted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001077 {
1078
1079 /* "ucs-bom" means we need to check the first bytes of the file
1080 * for a BOM. */
1081 if (STRCMP(fenc, ENC_UCSBOM) == 0)
1082 fio_flags = FIO_UCSBOM;
1083
1084 /*
1085 * Check if UCS-2/4 or Latin1 to UTF-8 conversion needs to be
1086 * done. This is handled below after read(). Prepare the
1087 * fio_flags to avoid having to parse the string each time.
1088 * Also check for Unicode to Latin1 conversion, because iconv()
1089 * appears not to handle this correctly. This works just like
1090 * conversion to UTF-8 except how the resulting character is put in
1091 * the buffer.
1092 */
1093 else if (enc_utf8 || STRCMP(p_enc, "latin1") == 0)
1094 fio_flags = get_fio_flags(fenc);
1095
1096# ifdef WIN3264
1097 /*
1098 * Conversion from an MS-Windows codepage to UTF-8 or another codepage
1099 * is handled with MultiByteToWideChar().
1100 */
1101 if (fio_flags == 0)
1102 fio_flags = get_win_fio_flags(fenc);
1103# endif
1104
1105# ifdef MACOS_X
1106 /* Conversion from Apple MacRoman to latin1 or UTF-8 */
1107 if (fio_flags == 0)
1108 fio_flags = get_mac_fio_flags(fenc);
1109# endif
1110
1111# ifdef USE_ICONV
1112 /*
1113 * Try using iconv() if we can't convert internally.
1114 */
1115 if (fio_flags == 0
1116# ifdef FEAT_EVAL
1117 && !did_iconv
1118# endif
1119 )
1120 iconv_fd = (iconv_t)my_iconv_open(
1121 enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc);
1122# endif
1123
1124# ifdef FEAT_EVAL
1125 /*
1126 * Use the 'charconvert' expression when conversion is required
1127 * and we can't do it internally or with iconv().
1128 */
1129 if (fio_flags == 0 && !read_stdin && !read_buffer && *p_ccv != NUL
1130# ifdef USE_ICONV
1131 && iconv_fd == (iconv_t)-1
1132# endif
1133 )
1134 {
1135# ifdef USE_ICONV
1136 did_iconv = FALSE;
1137# endif
1138 /* Skip conversion when it's already done (retry for wrong
1139 * "fileformat"). */
1140 if (tmpname == NULL)
1141 {
1142 tmpname = readfile_charconvert(fname, fenc, &fd);
1143 if (tmpname == NULL)
1144 {
1145 /* Conversion failed. Try another one. */
1146 advance_fenc = TRUE;
1147 if (fd < 0)
1148 {
1149 /* Re-opening the original file failed! */
1150 EMSG(_("E202: Conversion made file unreadable!"));
1151 error = TRUE;
1152 goto failed;
1153 }
1154 goto retry;
1155 }
1156 }
1157 }
1158 else
1159# endif
1160 {
1161 if (fio_flags == 0
1162# ifdef USE_ICONV
1163 && iconv_fd == (iconv_t)-1
1164# endif
1165 )
1166 {
1167 /* Conversion wanted but we can't.
1168 * Try the next conversion in 'fileencodings' */
1169 advance_fenc = TRUE;
1170 goto retry;
1171 }
1172 }
1173 }
1174
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001175 /* Set "can_retry" when it's possible to rewind the file and try with
Bram Moolenaar071d4272004-06-13 20:20:40 +00001176 * another "fenc" value. It's FALSE when no other "fenc" to try, reading
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001177 * stdin or fixed at a specific encoding. */
1178 can_retry = (*fenc != NUL && !read_stdin && !keep_dest_enc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001179#endif
1180
1181 if (!skip_read)
1182 {
1183 linerest = 0;
1184 filesize = 0;
1185 skip_count = lines_to_skip;
1186 read_count = lines_to_read;
1187#ifdef FEAT_MBYTE
1188 conv_restlen = 0;
1189#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001190#ifdef FEAT_PERSISTENT_UNDO
1191 read_undo_file = (newfile && curbuf->b_ffname != NULL && curbuf->b_p_udf
1192 && !filtering && !read_stdin && !read_buffer);
1193 if (read_undo_file)
1194 sha256_start(&sha_ctx);
1195#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001196 }
1197
1198 while (!error && !got_int)
1199 {
1200 /*
1201 * We allocate as much space for the file as we can get, plus
1202 * space for the old line plus room for one terminating NUL.
1203 * The amount is limited by the fact that read() only can read
1204 * upto max_unsigned characters (and other things).
1205 */
1206#if SIZEOF_INT <= 2
1207 if (linerest >= 0x7ff0)
1208 {
1209 ++split;
1210 *ptr = NL; /* split line by inserting a NL */
1211 size = 1;
1212 }
1213 else
1214#endif
1215 {
1216 if (!skip_read)
1217 {
1218#if SIZEOF_INT > 2
Bram Moolenaar311d9822007-02-27 15:48:28 +00001219# if defined(SSIZE_MAX) && (SSIZE_MAX < 0x10000L)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001220 size = SSIZE_MAX; /* use max I/O size, 52K */
1221# else
1222 size = 0x10000L; /* use buffer >= 64K */
1223# endif
1224#else
1225 size = 0x7ff0L - linerest; /* limit buffer to 32K */
1226#endif
1227
Bram Moolenaarc1e37902006-04-18 21:55:01 +00001228 for ( ; size >= 10; size = (long)((long_u)size >> 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001229 {
1230 if ((new_buffer = lalloc((long_u)(size + linerest + 1),
1231 FALSE)) != NULL)
1232 break;
1233 }
1234 if (new_buffer == NULL)
1235 {
1236 do_outofmem_msg((long_u)(size * 2 + linerest + 1));
1237 error = TRUE;
1238 break;
1239 }
1240 if (linerest) /* copy characters from the previous buffer */
1241 mch_memmove(new_buffer, ptr - linerest, (size_t)linerest);
1242 vim_free(buffer);
1243 buffer = new_buffer;
1244 ptr = buffer + linerest;
1245 line_start = buffer;
1246
1247#ifdef FEAT_MBYTE
1248 /* May need room to translate into.
1249 * For iconv() we don't really know the required space, use a
1250 * factor ICONV_MULT.
1251 * latin1 to utf-8: 1 byte becomes up to 2 bytes
1252 * utf-16 to utf-8: 2 bytes become up to 3 bytes, 4 bytes
1253 * become up to 4 bytes, size must be multiple of 2
1254 * ucs-2 to utf-8: 2 bytes become up to 3 bytes, size must be
1255 * multiple of 2
1256 * ucs-4 to utf-8: 4 bytes become up to 6 bytes, size must be
1257 * multiple of 4 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001258 real_size = (int)size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001259# ifdef USE_ICONV
1260 if (iconv_fd != (iconv_t)-1)
1261 size = size / ICONV_MULT;
1262 else
1263# endif
1264 if (fio_flags & FIO_LATIN1)
1265 size = size / 2;
1266 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1267 size = (size * 2 / 3) & ~1;
1268 else if (fio_flags & FIO_UCS4)
1269 size = (size * 2 / 3) & ~3;
1270 else if (fio_flags == FIO_UCSBOM)
1271 size = size / ICONV_MULT; /* worst case */
1272# ifdef WIN3264
1273 else if (fio_flags & FIO_CODEPAGE)
1274 size = size / ICONV_MULT; /* also worst case */
1275# endif
1276# ifdef MACOS_X
1277 else if (fio_flags & FIO_MACROMAN)
1278 size = size / ICONV_MULT; /* also worst case */
1279# endif
1280#endif
1281
1282#ifdef FEAT_MBYTE
1283 if (conv_restlen > 0)
1284 {
1285 /* Insert unconverted bytes from previous line. */
1286 mch_memmove(ptr, conv_rest, conv_restlen);
1287 ptr += conv_restlen;
1288 size -= conv_restlen;
1289 }
1290#endif
1291
1292 if (read_buffer)
1293 {
1294 /*
1295 * Read bytes from curbuf. Used for converting text read
1296 * from stdin.
1297 */
1298 if (read_buf_lnum > from)
1299 size = 0;
1300 else
1301 {
1302 int n, ni;
1303 long tlen;
1304
1305 tlen = 0;
1306 for (;;)
1307 {
1308 p = ml_get(read_buf_lnum) + read_buf_col;
1309 n = (int)STRLEN(p);
1310 if ((int)tlen + n + 1 > size)
1311 {
1312 /* Filled up to "size", append partial line.
1313 * Change NL to NUL to reverse the effect done
1314 * below. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001315 n = (int)(size - tlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001316 for (ni = 0; ni < n; ++ni)
1317 {
1318 if (p[ni] == NL)
1319 ptr[tlen++] = NUL;
1320 else
1321 ptr[tlen++] = p[ni];
1322 }
1323 read_buf_col += n;
1324 break;
1325 }
1326 else
1327 {
1328 /* Append whole line and new-line. Change NL
1329 * to NUL to reverse the effect done below. */
1330 for (ni = 0; ni < n; ++ni)
1331 {
1332 if (p[ni] == NL)
1333 ptr[tlen++] = NUL;
1334 else
1335 ptr[tlen++] = p[ni];
1336 }
1337 ptr[tlen++] = NL;
1338 read_buf_col = 0;
1339 if (++read_buf_lnum > from)
1340 {
1341 /* When the last line didn't have an
1342 * end-of-line don't add it now either. */
1343 if (!curbuf->b_p_eol)
1344 --tlen;
1345 size = tlen;
1346 break;
1347 }
1348 }
1349 }
1350 }
1351 }
1352 else
1353 {
1354 /*
1355 * Read bytes from the file.
1356 */
1357 size = vim_read(fd, ptr, size);
1358 }
1359
1360 if (size <= 0)
1361 {
1362 if (size < 0) /* read error */
1363 error = TRUE;
1364#ifdef FEAT_MBYTE
1365 else if (conv_restlen > 0)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001366 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001367 /*
1368 * Reached end-of-file but some trailing bytes could
1369 * not be converted. Truncated file?
1370 */
1371
1372 /* When we did a conversion report an error. */
1373 if (fio_flags != 0
1374# ifdef USE_ICONV
1375 || iconv_fd != (iconv_t)-1
1376# endif
1377 )
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001378 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001379 if (conv_error == 0)
1380 conv_error = curbuf->b_ml.ml_line_count
1381 - linecnt + 1;
1382 }
1383 /* Remember the first linenr with an illegal byte */
1384 else if (illegal_byte == 0)
1385 illegal_byte = curbuf->b_ml.ml_line_count
1386 - linecnt + 1;
1387 if (bad_char_behavior == BAD_DROP)
1388 {
1389 *(ptr - conv_restlen) = NUL;
1390 conv_restlen = 0;
1391 }
1392 else
1393 {
1394 /* Replace the trailing bytes with the replacement
1395 * character if we were converting; if we weren't,
1396 * leave the UTF8 checking code to do it, as it
1397 * works slightly differently. */
1398 if (bad_char_behavior != BAD_KEEP && (fio_flags != 0
1399# ifdef USE_ICONV
1400 || iconv_fd != (iconv_t)-1
1401# endif
1402 ))
1403 {
1404 while (conv_restlen > 0)
1405 {
1406 *(--ptr) = bad_char_behavior;
1407 --conv_restlen;
1408 }
1409 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001410 fio_flags = 0; /* don't convert this */
Bram Moolenaarb21e5842006-04-16 18:30:08 +00001411# ifdef USE_ICONV
1412 if (iconv_fd != (iconv_t)-1)
1413 {
1414 iconv_close(iconv_fd);
1415 iconv_fd = (iconv_t)-1;
1416 }
1417# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001418 }
1419 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001420#endif
1421 }
1422
1423#ifdef FEAT_CRYPT
1424 /*
1425 * At start of file: Check for magic number of encryption.
1426 */
1427 if (filesize == 0)
1428 cryptkey = check_for_cryptkey(cryptkey, ptr, &size,
Bram Moolenaarf50a2532010-05-21 15:36:08 +02001429 &filesize, newfile, &did_ask_for_key);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001430 /*
1431 * Decrypt the read bytes.
1432 */
1433 if (cryptkey != NULL && size > 0)
Bram Moolenaar04c9baf2010-06-01 23:37:39 +02001434 crypt_decode(ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001435#endif
1436 }
1437 skip_read = FALSE;
1438
1439#ifdef FEAT_MBYTE
1440 /*
1441 * At start of file (or after crypt magic number): Check for BOM.
1442 * Also check for a BOM for other Unicode encodings, but not after
1443 * converting with 'charconvert' or when a BOM has already been
1444 * found.
1445 */
1446 if ((filesize == 0
1447# ifdef FEAT_CRYPT
Bram Moolenaar40e6a712010-05-16 22:32:54 +02001448 || (filesize == (CRYPT_MAGIC_LEN
Bram Moolenaar80794b12010-06-13 05:20:42 +02001449 + crypt_salt_len[use_crypt_method]
Bram Moolenaar40e6a712010-05-16 22:32:54 +02001450 + crypt_seed_len[use_crypt_method])
1451 && cryptkey != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001452# endif
1453 )
1454 && (fio_flags == FIO_UCSBOM
1455 || (!curbuf->b_p_bomb
1456 && tmpname == NULL
1457 && (*fenc == 'u' || (*fenc == NUL && enc_utf8)))))
1458 {
1459 char_u *ccname;
1460 int blen;
1461
1462 /* no BOM detection in a short file or in binary mode */
1463 if (size < 2 || curbuf->b_p_bin)
1464 ccname = NULL;
1465 else
1466 ccname = check_for_bom(ptr, size, &blen,
1467 fio_flags == FIO_UCSBOM ? FIO_ALL : get_fio_flags(fenc));
1468 if (ccname != NULL)
1469 {
1470 /* Remove BOM from the text */
1471 filesize += blen;
1472 size -= blen;
1473 mch_memmove(ptr, ptr + blen, (size_t)size);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00001474 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001475 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001476 curbuf->b_p_bomb = TRUE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001477 curbuf->b_start_bomb = TRUE;
1478 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001479 }
1480
1481 if (fio_flags == FIO_UCSBOM)
1482 {
1483 if (ccname == NULL)
1484 {
1485 /* No BOM detected: retry with next encoding. */
1486 advance_fenc = TRUE;
1487 }
1488 else
1489 {
1490 /* BOM detected: set "fenc" and jump back */
1491 if (fenc_alloced)
1492 vim_free(fenc);
1493 fenc = ccname;
1494 fenc_alloced = FALSE;
1495 }
1496 /* retry reading without getting new bytes or rewinding */
1497 skip_read = TRUE;
1498 goto retry;
1499 }
1500 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001501
1502 /* Include not converted bytes. */
1503 ptr -= conv_restlen;
1504 size += conv_restlen;
1505 conv_restlen = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001506#endif
1507 /*
1508 * Break here for a read error or end-of-file.
1509 */
1510 if (size <= 0)
1511 break;
1512
1513#ifdef FEAT_MBYTE
1514
Bram Moolenaar071d4272004-06-13 20:20:40 +00001515# ifdef USE_ICONV
1516 if (iconv_fd != (iconv_t)-1)
1517 {
1518 /*
1519 * Attempt conversion of the read bytes to 'encoding' using
1520 * iconv().
1521 */
1522 const char *fromp;
1523 char *top;
1524 size_t from_size;
1525 size_t to_size;
1526
1527 fromp = (char *)ptr;
1528 from_size = size;
1529 ptr += size;
1530 top = (char *)ptr;
1531 to_size = real_size - size;
1532
1533 /*
1534 * If there is conversion error or not enough room try using
Bram Moolenaar19a09a12005-03-04 23:39:37 +00001535 * another conversion. Except for when there is no
1536 * alternative (help files).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001537 */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001538 while ((iconv(iconv_fd, (void *)&fromp, &from_size,
1539 &top, &to_size)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001540 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
1541 || from_size > CONV_RESTLEN)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001542 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001543 if (can_retry)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001544 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001545 if (conv_error == 0)
1546 conv_error = readfile_linenr(linecnt,
1547 ptr, (char_u *)top);
Bram Moolenaar42eeac32005-06-29 22:40:58 +00001548
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001549 /* Deal with a bad byte and continue with the next. */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001550 ++fromp;
1551 --from_size;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001552 if (bad_char_behavior == BAD_KEEP)
1553 {
1554 *top++ = *(fromp - 1);
1555 --to_size;
1556 }
1557 else if (bad_char_behavior != BAD_DROP)
1558 {
1559 *top++ = bad_char_behavior;
1560 --to_size;
1561 }
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001562 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001563
1564 if (from_size > 0)
1565 {
1566 /* Some remaining characters, keep them for the next
1567 * round. */
1568 mch_memmove(conv_rest, (char_u *)fromp, from_size);
1569 conv_restlen = (int)from_size;
1570 }
1571
1572 /* move the linerest to before the converted characters */
1573 line_start = ptr - linerest;
1574 mch_memmove(line_start, buffer, (size_t)linerest);
1575 size = (long)((char_u *)top - ptr);
1576 }
1577# endif
1578
1579# ifdef WIN3264
1580 if (fio_flags & FIO_CODEPAGE)
1581 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001582 char_u *src, *dst;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001583 WCHAR ucs2buf[3];
1584 int ucs2len;
1585 int codepage = FIO_GET_CP(fio_flags);
1586 int bytelen;
1587 int found_bad;
1588 char replstr[2];
1589
Bram Moolenaar071d4272004-06-13 20:20:40 +00001590 /*
1591 * Conversion from an MS-Windows codepage or UTF-8 to UTF-8 or
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001592 * a codepage, using standard MS-Windows functions. This
1593 * requires two steps:
1594 * 1. convert from 'fileencoding' to ucs-2
1595 * 2. convert from ucs-2 to 'encoding'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001596 *
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001597 * Because there may be illegal bytes AND an incomplete byte
1598 * sequence at the end, we may have to do the conversion one
1599 * character at a time to get it right.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001600 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001601
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001602 /* Replacement string for WideCharToMultiByte(). */
1603 if (bad_char_behavior > 0)
1604 replstr[0] = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001605 else
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001606 replstr[0] = '?';
1607 replstr[1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001608
1609 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001610 * Move the bytes to the end of the buffer, so that we have
1611 * room to put the result at the start.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001612 */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001613 src = ptr + real_size - size;
1614 mch_memmove(src, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001615
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001616 /*
1617 * Do the conversion.
1618 */
1619 dst = ptr;
1620 size = size;
1621 while (size > 0)
1622 {
1623 found_bad = FALSE;
1624
1625# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
1626 if (codepage == CP_UTF8)
1627 {
1628 /* Handle CP_UTF8 input ourselves to be able to handle
1629 * trailing bytes properly.
1630 * Get one UTF-8 character from src. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001631 bytelen = (int)utf_ptr2len_len(src, size);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001632 if (bytelen > size)
1633 {
1634 /* Only got some bytes of a character. Normally
1635 * it's put in "conv_rest", but if it's too long
1636 * deal with it as if they were illegal bytes. */
1637 if (bytelen <= CONV_RESTLEN)
1638 break;
1639
1640 /* weird overlong byte sequence */
1641 bytelen = size;
1642 found_bad = TRUE;
1643 }
1644 else
1645 {
Bram Moolenaarc01140a2006-03-24 22:21:52 +00001646 int u8c = utf_ptr2char(src);
1647
Bram Moolenaar86e01082005-12-29 22:45:34 +00001648 if (u8c > 0xffff || (*src >= 0x80 && bytelen == 1))
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001649 found_bad = TRUE;
1650 ucs2buf[0] = u8c;
1651 ucs2len = 1;
1652 }
1653 }
1654 else
1655# endif
1656 {
1657 /* We don't know how long the byte sequence is, try
1658 * from one to three bytes. */
1659 for (bytelen = 1; bytelen <= size && bytelen <= 3;
1660 ++bytelen)
1661 {
1662 ucs2len = MultiByteToWideChar(codepage,
1663 MB_ERR_INVALID_CHARS,
1664 (LPCSTR)src, bytelen,
1665 ucs2buf, 3);
1666 if (ucs2len > 0)
1667 break;
1668 }
1669 if (ucs2len == 0)
1670 {
1671 /* If we have only one byte then it's probably an
1672 * incomplete byte sequence. Otherwise discard
1673 * one byte as a bad character. */
1674 if (size == 1)
1675 break;
1676 found_bad = TRUE;
1677 bytelen = 1;
1678 }
1679 }
1680
1681 if (!found_bad)
1682 {
1683 int i;
1684
1685 /* Convert "ucs2buf[ucs2len]" to 'enc' in "dst". */
1686 if (enc_utf8)
1687 {
1688 /* From UCS-2 to UTF-8. Cannot fail. */
1689 for (i = 0; i < ucs2len; ++i)
1690 dst += utf_char2bytes(ucs2buf[i], dst);
1691 }
1692 else
1693 {
1694 BOOL bad = FALSE;
1695 int dstlen;
1696
1697 /* From UCS-2 to "enc_codepage". If the
1698 * conversion uses the default character "?",
1699 * the data doesn't fit in this encoding. */
1700 dstlen = WideCharToMultiByte(enc_codepage, 0,
1701 (LPCWSTR)ucs2buf, ucs2len,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001702 (LPSTR)dst, (int)(src - dst),
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001703 replstr, &bad);
1704 if (bad)
1705 found_bad = TRUE;
1706 else
1707 dst += dstlen;
1708 }
1709 }
1710
1711 if (found_bad)
1712 {
1713 /* Deal with bytes we can't convert. */
1714 if (can_retry)
1715 goto rewind_retry;
1716 if (conv_error == 0)
1717 conv_error = readfile_linenr(linecnt, ptr, dst);
1718 if (bad_char_behavior != BAD_DROP)
1719 {
1720 if (bad_char_behavior == BAD_KEEP)
1721 {
1722 mch_memmove(dst, src, bytelen);
1723 dst += bytelen;
1724 }
1725 else
1726 *dst++ = bad_char_behavior;
1727 }
1728 }
1729
1730 src += bytelen;
1731 size -= bytelen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001732 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001733
1734 if (size > 0)
1735 {
1736 /* An incomplete byte sequence remaining. */
1737 mch_memmove(conv_rest, src, size);
1738 conv_restlen = size;
1739 }
1740
1741 /* The new size is equal to how much "dst" was advanced. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001742 size = (long)(dst - ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001743 }
1744 else
1745# endif
Bram Moolenaar56718732006-03-15 22:53:57 +00001746# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001747 if (fio_flags & FIO_MACROMAN)
1748 {
1749 /*
1750 * Conversion from Apple MacRoman char encoding to UTF-8 or
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001751 * latin1. This is in os_mac_conv.c.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001752 */
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001753 if (macroman2enc(ptr, &size, real_size) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001754 goto rewind_retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001755 }
1756 else
1757# endif
1758 if (fio_flags != 0)
1759 {
1760 int u8c;
1761 char_u *dest;
1762 char_u *tail = NULL;
1763
1764 /*
1765 * "enc_utf8" set: Convert Unicode or Latin1 to UTF-8.
1766 * "enc_utf8" not set: Convert Unicode to Latin1.
1767 * Go from end to start through the buffer, because the number
1768 * of bytes may increase.
1769 * "dest" points to after where the UTF-8 bytes go, "p" points
1770 * to after the next character to convert.
1771 */
1772 dest = ptr + real_size;
1773 if (fio_flags == FIO_LATIN1 || fio_flags == FIO_UTF8)
1774 {
1775 p = ptr + size;
1776 if (fio_flags == FIO_UTF8)
1777 {
1778 /* Check for a trailing incomplete UTF-8 sequence */
1779 tail = ptr + size - 1;
1780 while (tail > ptr && (*tail & 0xc0) == 0x80)
1781 --tail;
1782 if (tail + utf_byte2len(*tail) <= ptr + size)
1783 tail = NULL;
1784 else
1785 p = tail;
1786 }
1787 }
1788 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1789 {
1790 /* Check for a trailing byte */
1791 p = ptr + (size & ~1);
1792 if (size & 1)
1793 tail = p;
1794 if ((fio_flags & FIO_UTF16) && p > ptr)
1795 {
1796 /* Check for a trailing leading word */
1797 if (fio_flags & FIO_ENDIAN_L)
1798 {
1799 u8c = (*--p << 8);
1800 u8c += *--p;
1801 }
1802 else
1803 {
1804 u8c = *--p;
1805 u8c += (*--p << 8);
1806 }
1807 if (u8c >= 0xd800 && u8c <= 0xdbff)
1808 tail = p;
1809 else
1810 p += 2;
1811 }
1812 }
1813 else /* FIO_UCS4 */
1814 {
1815 /* Check for trailing 1, 2 or 3 bytes */
1816 p = ptr + (size & ~3);
1817 if (size & 3)
1818 tail = p;
1819 }
1820
1821 /* If there is a trailing incomplete sequence move it to
1822 * conv_rest[]. */
1823 if (tail != NULL)
1824 {
1825 conv_restlen = (int)((ptr + size) - tail);
1826 mch_memmove(conv_rest, (char_u *)tail, conv_restlen);
1827 size -= conv_restlen;
1828 }
1829
1830
1831 while (p > ptr)
1832 {
1833 if (fio_flags & FIO_LATIN1)
1834 u8c = *--p;
1835 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1836 {
1837 if (fio_flags & FIO_ENDIAN_L)
1838 {
1839 u8c = (*--p << 8);
1840 u8c += *--p;
1841 }
1842 else
1843 {
1844 u8c = *--p;
1845 u8c += (*--p << 8);
1846 }
1847 if ((fio_flags & FIO_UTF16)
1848 && u8c >= 0xdc00 && u8c <= 0xdfff)
1849 {
1850 int u16c;
1851
1852 if (p == ptr)
1853 {
1854 /* Missing leading word. */
1855 if (can_retry)
1856 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001857 if (conv_error == 0)
1858 conv_error = readfile_linenr(linecnt,
1859 ptr, p);
1860 if (bad_char_behavior == BAD_DROP)
1861 continue;
1862 if (bad_char_behavior != BAD_KEEP)
1863 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001864 }
1865
1866 /* found second word of double-word, get the first
1867 * word and compute the resulting character */
1868 if (fio_flags & FIO_ENDIAN_L)
1869 {
1870 u16c = (*--p << 8);
1871 u16c += *--p;
1872 }
1873 else
1874 {
1875 u16c = *--p;
1876 u16c += (*--p << 8);
1877 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001878 u8c = 0x10000 + ((u16c & 0x3ff) << 10)
1879 + (u8c & 0x3ff);
1880
Bram Moolenaar071d4272004-06-13 20:20:40 +00001881 /* Check if the word is indeed a leading word. */
1882 if (u16c < 0xd800 || u16c > 0xdbff)
1883 {
1884 if (can_retry)
1885 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001886 if (conv_error == 0)
1887 conv_error = readfile_linenr(linecnt,
1888 ptr, p);
1889 if (bad_char_behavior == BAD_DROP)
1890 continue;
1891 if (bad_char_behavior != BAD_KEEP)
1892 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001893 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001894 }
1895 }
1896 else if (fio_flags & FIO_UCS4)
1897 {
1898 if (fio_flags & FIO_ENDIAN_L)
1899 {
1900 u8c = (*--p << 24);
1901 u8c += (*--p << 16);
1902 u8c += (*--p << 8);
1903 u8c += *--p;
1904 }
1905 else /* big endian */
1906 {
1907 u8c = *--p;
1908 u8c += (*--p << 8);
1909 u8c += (*--p << 16);
1910 u8c += (*--p << 24);
1911 }
1912 }
1913 else /* UTF-8 */
1914 {
1915 if (*--p < 0x80)
1916 u8c = *p;
1917 else
1918 {
1919 len = utf_head_off(ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001920 p -= len;
1921 u8c = utf_ptr2char(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001922 if (len == 0)
1923 {
1924 /* Not a valid UTF-8 character, retry with
1925 * another fenc when possible, otherwise just
1926 * report the error. */
1927 if (can_retry)
1928 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001929 if (conv_error == 0)
1930 conv_error = readfile_linenr(linecnt,
1931 ptr, p);
1932 if (bad_char_behavior == BAD_DROP)
1933 continue;
1934 if (bad_char_behavior != BAD_KEEP)
1935 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001936 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001937 }
1938 }
1939 if (enc_utf8) /* produce UTF-8 */
1940 {
1941 dest -= utf_char2len(u8c);
1942 (void)utf_char2bytes(u8c, dest);
1943 }
1944 else /* produce Latin1 */
1945 {
1946 --dest;
1947 if (u8c >= 0x100)
1948 {
1949 /* character doesn't fit in latin1, retry with
1950 * another fenc when possible, otherwise just
1951 * report the error. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001952 if (can_retry)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001953 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001954 if (conv_error == 0)
1955 conv_error = readfile_linenr(linecnt, ptr, p);
1956 if (bad_char_behavior == BAD_DROP)
1957 ++dest;
1958 else if (bad_char_behavior == BAD_KEEP)
1959 *dest = u8c;
1960 else if (eap != NULL && eap->bad_char != 0)
1961 *dest = bad_char_behavior;
1962 else
1963 *dest = 0xBF;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001964 }
1965 else
1966 *dest = u8c;
1967 }
1968 }
1969
1970 /* move the linerest to before the converted characters */
1971 line_start = dest - linerest;
1972 mch_memmove(line_start, buffer, (size_t)linerest);
1973 size = (long)((ptr + real_size) - dest);
1974 ptr = dest;
1975 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001976 else if (enc_utf8 && !curbuf->b_p_bin)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001977 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001978 int incomplete_tail = FALSE;
1979
1980 /* Reading UTF-8: Check if the bytes are valid UTF-8. */
1981 for (p = ptr; ; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001982 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001983 int todo = (int)((ptr + size) - p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001984 int l;
1985
1986 if (todo <= 0)
1987 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001988 if (*p >= 0x80)
1989 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001990 /* A length of 1 means it's an illegal byte. Accept
1991 * an incomplete character at the end though, the next
1992 * read() will get the next bytes, we'll check it
1993 * then. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001994 l = utf_ptr2len_len(p, todo);
Bram Moolenaarf453d352008-06-04 17:37:34 +00001995 if (l > todo && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001996 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001997 /* Avoid retrying with a different encoding when
1998 * a truncated file is more likely, or attempting
1999 * to read the rest of an incomplete sequence when
2000 * we have already done so. */
2001 if (p > ptr || filesize > 0)
2002 incomplete_tail = TRUE;
2003 /* Incomplete byte sequence, move it to conv_rest[]
2004 * and try to read the rest of it, unless we've
2005 * already done so. */
2006 if (p > ptr)
2007 {
2008 conv_restlen = todo;
2009 mch_memmove(conv_rest, p, conv_restlen);
2010 size -= conv_restlen;
2011 break;
2012 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002013 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002014 if (l == 1 || l > todo)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002015 {
2016 /* Illegal byte. If we can try another encoding
Bram Moolenaarf453d352008-06-04 17:37:34 +00002017 * do that, unless at EOF where a truncated
2018 * file is more likely than a conversion error. */
2019 if (can_retry && !incomplete_tail)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002020 break;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002021# ifdef USE_ICONV
2022 /* When we did a conversion report an error. */
2023 if (iconv_fd != (iconv_t)-1 && conv_error == 0)
2024 conv_error = readfile_linenr(linecnt, ptr, p);
2025# endif
Bram Moolenaarf453d352008-06-04 17:37:34 +00002026 /* Remember the first linenr with an illegal byte */
2027 if (conv_error == 0 && illegal_byte == 0)
2028 illegal_byte = readfile_linenr(linecnt, ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002029
2030 /* Drop, keep or replace the bad byte. */
2031 if (bad_char_behavior == BAD_DROP)
2032 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002033 mch_memmove(p, p + 1, todo - 1);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002034 --p;
2035 --size;
2036 }
2037 else if (bad_char_behavior != BAD_KEEP)
2038 *p = bad_char_behavior;
2039 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002040 else
2041 p += l - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002042 }
2043 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002044 if (p < ptr + size && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002045 {
2046 /* Detected a UTF-8 error. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002047rewind_retry:
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002048 /* Retry reading with another conversion. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002049# if defined(FEAT_EVAL) && defined(USE_ICONV)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002050 if (*p_ccv != NUL && iconv_fd != (iconv_t)-1)
2051 /* iconv() failed, try 'charconvert' */
2052 did_iconv = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002053 else
2054# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002055 /* use next item from 'fileencodings' */
2056 advance_fenc = TRUE;
2057 file_rewind = TRUE;
2058 goto retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002059 }
2060 }
2061#endif
2062
2063 /* count the number of characters (after conversion!) */
2064 filesize += size;
2065
2066 /*
2067 * when reading the first part of a file: guess EOL type
2068 */
2069 if (fileformat == EOL_UNKNOWN)
2070 {
2071 /* First try finding a NL, for Dos and Unix */
2072 if (try_dos || try_unix)
2073 {
2074 for (p = ptr; p < ptr + size; ++p)
2075 {
2076 if (*p == NL)
2077 {
2078 if (!try_unix
2079 || (try_dos && p > ptr && p[-1] == CAR))
2080 fileformat = EOL_DOS;
2081 else
2082 fileformat = EOL_UNIX;
2083 break;
2084 }
2085 }
2086
2087 /* Don't give in to EOL_UNIX if EOL_MAC is more likely */
2088 if (fileformat == EOL_UNIX && try_mac)
2089 {
2090 /* Need to reset the counters when retrying fenc. */
2091 try_mac = 1;
2092 try_unix = 1;
2093 for (; p >= ptr && *p != CAR; p--)
2094 ;
2095 if (p >= ptr)
2096 {
2097 for (p = ptr; p < ptr + size; ++p)
2098 {
2099 if (*p == NL)
2100 try_unix++;
2101 else if (*p == CAR)
2102 try_mac++;
2103 }
2104 if (try_mac > try_unix)
2105 fileformat = EOL_MAC;
2106 }
2107 }
2108 }
2109
2110 /* No NL found: may use Mac format */
2111 if (fileformat == EOL_UNKNOWN && try_mac)
2112 fileformat = EOL_MAC;
2113
2114 /* Still nothing found? Use first format in 'ffs' */
2115 if (fileformat == EOL_UNKNOWN)
2116 fileformat = default_fileformat();
2117
2118 /* if editing a new file: may set p_tx and p_ff */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002119 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002120 set_fileformat(fileformat, OPT_LOCAL);
2121 }
2122 }
2123
2124 /*
2125 * This loop is executed once for every character read.
2126 * Keep it fast!
2127 */
2128 if (fileformat == EOL_MAC)
2129 {
2130 --ptr;
2131 while (++ptr, --size >= 0)
2132 {
2133 /* catch most common case first */
2134 if ((c = *ptr) != NUL && c != CAR && c != NL)
2135 continue;
2136 if (c == NUL)
2137 *ptr = NL; /* NULs are replaced by newlines! */
2138 else if (c == NL)
2139 *ptr = CAR; /* NLs are replaced by CRs! */
2140 else
2141 {
2142 if (skip_count == 0)
2143 {
2144 *ptr = NUL; /* end of line */
2145 len = (colnr_T) (ptr - line_start + 1);
2146 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2147 {
2148 error = TRUE;
2149 break;
2150 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002151#ifdef FEAT_PERSISTENT_UNDO
2152 if (read_undo_file)
2153 sha256_update(&sha_ctx, line_start, len);
2154#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002155 ++lnum;
2156 if (--read_count == 0)
2157 {
2158 error = TRUE; /* break loop */
2159 line_start = ptr; /* nothing left to write */
2160 break;
2161 }
2162 }
2163 else
2164 --skip_count;
2165 line_start = ptr + 1;
2166 }
2167 }
2168 }
2169 else
2170 {
2171 --ptr;
2172 while (++ptr, --size >= 0)
2173 {
2174 if ((c = *ptr) != NUL && c != NL) /* catch most common case */
2175 continue;
2176 if (c == NUL)
2177 *ptr = NL; /* NULs are replaced by newlines! */
2178 else
2179 {
2180 if (skip_count == 0)
2181 {
2182 *ptr = NUL; /* end of line */
2183 len = (colnr_T)(ptr - line_start + 1);
2184 if (fileformat == EOL_DOS)
2185 {
2186 if (ptr[-1] == CAR) /* remove CR */
2187 {
2188 ptr[-1] = NUL;
2189 --len;
2190 }
2191 /*
2192 * Reading in Dos format, but no CR-LF found!
2193 * When 'fileformats' includes "unix", delete all
2194 * the lines read so far and start all over again.
2195 * Otherwise give an error message later.
2196 */
2197 else if (ff_error != EOL_DOS)
2198 {
2199 if ( try_unix
2200 && !read_stdin
2201 && (read_buffer
2202 || lseek(fd, (off_t)0L, SEEK_SET) == 0))
2203 {
2204 fileformat = EOL_UNIX;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002205 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002206 set_fileformat(EOL_UNIX, OPT_LOCAL);
2207 file_rewind = TRUE;
2208 keep_fileformat = TRUE;
2209 goto retry;
2210 }
2211 ff_error = EOL_DOS;
2212 }
2213 }
2214 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2215 {
2216 error = TRUE;
2217 break;
2218 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002219#ifdef FEAT_PERSISTENT_UNDO
2220 if (read_undo_file)
2221 sha256_update(&sha_ctx, line_start, len);
2222#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002223 ++lnum;
2224 if (--read_count == 0)
2225 {
2226 error = TRUE; /* break loop */
2227 line_start = ptr; /* nothing left to write */
2228 break;
2229 }
2230 }
2231 else
2232 --skip_count;
2233 line_start = ptr + 1;
2234 }
2235 }
2236 }
2237 linerest = (long)(ptr - line_start);
2238 ui_breakcheck();
2239 }
2240
2241failed:
2242 /* not an error, max. number of lines reached */
2243 if (error && read_count == 0)
2244 error = FALSE;
2245
2246 /*
2247 * If we get EOF in the middle of a line, note the fact and
2248 * complete the line ourselves.
2249 * In Dos format ignore a trailing CTRL-Z, unless 'binary' set.
2250 */
2251 if (!error
2252 && !got_int
2253 && linerest != 0
2254 && !(!curbuf->b_p_bin
2255 && fileformat == EOL_DOS
2256 && *line_start == Ctrl_Z
2257 && ptr == line_start + 1))
2258 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002259 /* remember for when writing */
2260 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002261 curbuf->b_p_eol = FALSE;
2262 *ptr = NUL;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002263 len = (colnr_T)(ptr - line_start + 1);
2264 if (ml_append(lnum, line_start, len, newfile) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002265 error = TRUE;
2266 else
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002267 {
2268#ifdef FEAT_PERSISTENT_UNDO
2269 if (read_undo_file)
2270 sha256_update(&sha_ctx, line_start, len);
2271#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002272 read_no_eol_lnum = ++lnum;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002273 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002274 }
2275
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002276 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002277 save_file_ff(curbuf); /* remember the current file format */
2278
2279#ifdef FEAT_CRYPT
2280 if (cryptkey != curbuf->b_p_key)
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002281 free_crypt_key(cryptkey);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002282#endif
2283
2284#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002285 /* If editing a new file: set 'fenc' for the current buffer.
2286 * Also for ":read ++edit file". */
2287 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002288 set_string_option_direct((char_u *)"fenc", -1, fenc,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00002289 OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002290 if (fenc_alloced)
2291 vim_free(fenc);
2292# ifdef USE_ICONV
2293 if (iconv_fd != (iconv_t)-1)
2294 {
2295 iconv_close(iconv_fd);
2296 iconv_fd = (iconv_t)-1;
2297 }
2298# endif
2299#endif
2300
2301 if (!read_buffer && !read_stdin)
2302 close(fd); /* errors are ignored */
Bram Moolenaarf05da212009-11-17 16:13:15 +00002303#ifdef HAVE_FD_CLOEXEC
2304 else
2305 {
2306 int fdflags = fcntl(fd, F_GETFD);
2307 if (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0)
2308 fcntl(fd, F_SETFD, fdflags | FD_CLOEXEC);
2309 }
2310#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002311 vim_free(buffer);
2312
2313#ifdef HAVE_DUP
2314 if (read_stdin)
2315 {
2316 /* Use stderr for stdin, makes shell commands work. */
2317 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00002318 ignored = dup(2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002319 }
2320#endif
2321
2322#ifdef FEAT_MBYTE
2323 if (tmpname != NULL)
2324 {
2325 mch_remove(tmpname); /* delete converted file */
2326 vim_free(tmpname);
2327 }
2328#endif
2329 --no_wait_return; /* may wait for return now */
2330
2331 /*
2332 * In recovery mode everything but autocommands is skipped.
2333 */
2334 if (!recoverymode)
2335 {
2336 /* need to delete the last line, which comes from the empty buffer */
2337 if (newfile && wasempty && !(curbuf->b_ml.ml_flags & ML_EMPTY))
2338 {
2339#ifdef FEAT_NETBEANS_INTG
2340 netbeansFireChanges = 0;
2341#endif
2342 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
2343#ifdef FEAT_NETBEANS_INTG
2344 netbeansFireChanges = 1;
2345#endif
2346 --linecnt;
2347 }
2348 linecnt = curbuf->b_ml.ml_line_count - linecnt;
2349 if (filesize == 0)
2350 linecnt = 0;
2351 if (newfile || read_buffer)
Bram Moolenaar7263a772007-05-10 17:35:54 +00002352 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002353 redraw_curbuf_later(NOT_VALID);
Bram Moolenaar7263a772007-05-10 17:35:54 +00002354#ifdef FEAT_DIFF
2355 /* After reading the text into the buffer the diff info needs to
2356 * be updated. */
2357 diff_invalidate(curbuf);
2358#endif
2359#ifdef FEAT_FOLDING
2360 /* All folds in the window are invalid now. Mark them for update
2361 * before triggering autocommands. */
2362 foldUpdateAll(curwin);
2363#endif
2364 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002365 else if (linecnt) /* appended at least one line */
2366 appended_lines_mark(from, linecnt);
2367
Bram Moolenaar071d4272004-06-13 20:20:40 +00002368#ifndef ALWAYS_USE_GUI
2369 /*
2370 * If we were reading from the same terminal as where messages go,
2371 * the screen will have been messed up.
2372 * Switch on raw mode now and clear the screen.
2373 */
2374 if (read_stdin)
2375 {
2376 settmode(TMODE_RAW); /* set to raw mode */
2377 starttermcap();
2378 screenclear();
2379 }
2380#endif
2381
2382 if (got_int)
2383 {
2384 if (!(flags & READ_DUMMY))
2385 {
2386 filemess(curbuf, sfname, (char_u *)_(e_interr), 0);
2387 if (newfile)
2388 curbuf->b_p_ro = TRUE; /* must use "w!" now */
2389 }
2390 msg_scroll = msg_save;
2391#ifdef FEAT_VIMINFO
2392 check_marks_read();
2393#endif
2394 return OK; /* an interrupt isn't really an error */
2395 }
2396
2397 if (!filtering && !(flags & READ_DUMMY))
2398 {
2399 msg_add_fname(curbuf, sfname); /* fname in IObuff with quotes */
2400 c = FALSE;
2401
2402#ifdef UNIX
2403# ifdef S_ISFIFO
2404 if (S_ISFIFO(perm)) /* fifo or socket */
2405 {
2406 STRCAT(IObuff, _("[fifo/socket]"));
2407 c = TRUE;
2408 }
2409# else
2410# ifdef S_IFIFO
2411 if ((perm & S_IFMT) == S_IFIFO) /* fifo */
2412 {
2413 STRCAT(IObuff, _("[fifo]"));
2414 c = TRUE;
2415 }
2416# endif
2417# ifdef S_IFSOCK
2418 if ((perm & S_IFMT) == S_IFSOCK) /* or socket */
2419 {
2420 STRCAT(IObuff, _("[socket]"));
2421 c = TRUE;
2422 }
2423# endif
2424# endif
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002425# ifdef OPEN_CHR_FILES
2426 if (S_ISCHR(perm)) /* or character special */
2427 {
2428 STRCAT(IObuff, _("[character special]"));
2429 c = TRUE;
2430 }
2431# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002432#endif
2433 if (curbuf->b_p_ro)
2434 {
2435 STRCAT(IObuff, shortmess(SHM_RO) ? _("[RO]") : _("[readonly]"));
2436 c = TRUE;
2437 }
2438 if (read_no_eol_lnum)
2439 {
2440 msg_add_eol();
2441 c = TRUE;
2442 }
2443 if (ff_error == EOL_DOS)
2444 {
2445 STRCAT(IObuff, _("[CR missing]"));
2446 c = TRUE;
2447 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002448 if (split)
2449 {
2450 STRCAT(IObuff, _("[long lines split]"));
2451 c = TRUE;
2452 }
2453#ifdef FEAT_MBYTE
2454 if (notconverted)
2455 {
2456 STRCAT(IObuff, _("[NOT converted]"));
2457 c = TRUE;
2458 }
2459 else if (converted)
2460 {
2461 STRCAT(IObuff, _("[converted]"));
2462 c = TRUE;
2463 }
2464#endif
2465#ifdef FEAT_CRYPT
2466 if (cryptkey != NULL)
2467 {
2468 STRCAT(IObuff, _("[crypted]"));
2469 c = TRUE;
2470 }
2471#endif
2472#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002473 if (conv_error != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002474 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002475 sprintf((char *)IObuff + STRLEN(IObuff),
2476 _("[CONVERSION ERROR in line %ld]"), (long)conv_error);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002477 c = TRUE;
2478 }
2479 else if (illegal_byte > 0)
2480 {
2481 sprintf((char *)IObuff + STRLEN(IObuff),
2482 _("[ILLEGAL BYTE in line %ld]"), (long)illegal_byte);
2483 c = TRUE;
2484 }
2485 else
2486#endif
2487 if (error)
2488 {
2489 STRCAT(IObuff, _("[READ ERRORS]"));
2490 c = TRUE;
2491 }
2492 if (msg_add_fileformat(fileformat))
2493 c = TRUE;
2494#ifdef FEAT_CRYPT
2495 if (cryptkey != NULL)
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002496 msg_add_lines(c, (long)linecnt, filesize
Bram Moolenaar80794b12010-06-13 05:20:42 +02002497 - CRYPT_MAGIC_LEN
2498 - crypt_salt_len[use_crypt_method]
2499 - crypt_seed_len[use_crypt_method]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002500 else
2501#endif
2502 msg_add_lines(c, (long)linecnt, filesize);
2503
2504 vim_free(keep_msg);
2505 keep_msg = NULL;
2506 msg_scrolled_ign = TRUE;
2507#ifdef ALWAYS_USE_GUI
2508 /* Don't show the message when reading stdin, it would end up in a
2509 * message box (which might be shown when exiting!) */
2510 if (read_stdin || read_buffer)
2511 p = msg_may_trunc(FALSE, IObuff);
2512 else
2513#endif
2514 p = msg_trunc_attr(IObuff, FALSE, 0);
2515 if (read_stdin || read_buffer || restart_edit != 0
Bram Moolenaar1c7715d2005-10-03 22:02:18 +00002516 || (msg_scrolled != 0 && !need_wait_return))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002517 /* Need to repeat the message after redrawing when:
2518 * - When reading from stdin (the screen will be cleared next).
2519 * - When restart_edit is set (otherwise there will be a delay
2520 * before redrawing).
2521 * - When the screen was scrolled but there is no wait-return
2522 * prompt. */
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002523 set_keep_msg(p, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002524 msg_scrolled_ign = FALSE;
2525 }
2526
2527 /* with errors writing the file requires ":w!" */
2528 if (newfile && (error
2529#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002530 || conv_error != 0
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002531 || (illegal_byte > 0 && bad_char_behavior != BAD_KEEP)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002532#endif
2533 ))
2534 curbuf->b_p_ro = TRUE;
2535
2536 u_clearline(); /* cannot use "U" command after adding lines */
2537
2538 /*
2539 * In Ex mode: cursor at last new line.
2540 * Otherwise: cursor at first new line.
2541 */
2542 if (exmode_active)
2543 curwin->w_cursor.lnum = from + linecnt;
2544 else
2545 curwin->w_cursor.lnum = from + 1;
2546 check_cursor_lnum();
2547 beginline(BL_WHITE | BL_FIX); /* on first non-blank */
2548
2549 /*
2550 * Set '[ and '] marks to the newly read lines.
2551 */
2552 curbuf->b_op_start.lnum = from + 1;
2553 curbuf->b_op_start.col = 0;
2554 curbuf->b_op_end.lnum = from + linecnt;
2555 curbuf->b_op_end.col = 0;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002556
2557#ifdef WIN32
2558 /*
2559 * Work around a weird problem: When a file has two links (only
2560 * possible on NTFS) and we write through one link, then stat() it
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00002561 * through the other link, the timestamp information may be wrong.
Bram Moolenaar03f48552006-02-28 23:52:23 +00002562 * It's correct again after reading the file, thus reset the timestamp
2563 * here.
2564 */
2565 if (newfile && !read_stdin && !read_buffer
2566 && mch_stat((char *)fname, &st) >= 0)
2567 {
2568 buf_store_time(curbuf, &st, fname);
2569 curbuf->b_mtime_read = curbuf->b_mtime;
2570 }
2571#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002572 }
2573 msg_scroll = msg_save;
2574
2575#ifdef FEAT_VIMINFO
2576 /*
2577 * Get the marks before executing autocommands, so they can be used there.
2578 */
2579 check_marks_read();
2580#endif
2581
Bram Moolenaar071d4272004-06-13 20:20:40 +00002582 /*
2583 * Trick: We remember if the last line of the read didn't have
2584 * an eol for when writing it again. This is required for
2585 * ":autocmd FileReadPost *.gz set bin|'[,']!gunzip" to work.
2586 */
2587 write_no_eol_lnum = read_no_eol_lnum;
2588
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002589#ifdef FEAT_PERSISTENT_UNDO
2590 /*
2591 * When opening a new file locate undo info and read it.
2592 */
2593 if (read_undo_file)
2594 {
2595 char_u hash[UNDO_HASH_SIZE];
2596
2597 sha256_finish(&sha_ctx, hash);
Bram Moolenaar6ed8ed82010-05-30 20:40:11 +02002598 u_read_undo(NULL, hash, fname);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002599 }
2600#endif
2601
Bram Moolenaardf177f62005-02-22 08:39:57 +00002602#ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00002603 if (!read_stdin && !read_buffer)
2604 {
2605 int m = msg_scroll;
2606 int n = msg_scrolled;
2607
2608 /* Save the fileformat now, otherwise the buffer will be considered
2609 * modified if the format/encoding was automatically detected. */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002610 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002611 save_file_ff(curbuf);
2612
2613 /*
2614 * The output from the autocommands should not overwrite anything and
2615 * should not be overwritten: Set msg_scroll, restore its value if no
2616 * output was done.
2617 */
2618 msg_scroll = TRUE;
2619 if (filtering)
2620 apply_autocmds_exarg(EVENT_FILTERREADPOST, NULL, sfname,
2621 FALSE, curbuf, eap);
2622 else if (newfile)
2623 apply_autocmds_exarg(EVENT_BUFREADPOST, NULL, sfname,
2624 FALSE, curbuf, eap);
2625 else
2626 apply_autocmds_exarg(EVENT_FILEREADPOST, sfname, sfname,
2627 FALSE, NULL, eap);
2628 if (msg_scrolled == n)
2629 msg_scroll = m;
2630#ifdef FEAT_EVAL
2631 if (aborting()) /* autocmds may abort script processing */
2632 return FAIL;
2633#endif
2634 }
2635#endif
2636
2637 if (recoverymode && error)
2638 return FAIL;
2639 return OK;
2640}
2641
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002642#ifdef OPEN_CHR_FILES
2643/*
2644 * Returns TRUE if the file name argument is of the form "/dev/fd/\d\+",
2645 * which is the name of files used for process substitution output by
2646 * some shells on some operating systems, e.g., bash on SunOS.
2647 * Do not accept "/dev/fd/[012]", opening these may hang Vim.
2648 */
2649 static int
2650is_dev_fd_file(fname)
2651 char_u *fname;
2652{
2653 return (STRNCMP(fname, "/dev/fd/", 8) == 0
2654 && VIM_ISDIGIT(fname[8])
2655 && *skipdigits(fname + 9) == NUL
2656 && (fname[9] != NUL
2657 || (fname[8] != '0' && fname[8] != '1' && fname[8] != '2')));
2658}
2659#endif
2660
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002661#ifdef FEAT_MBYTE
2662
2663/*
2664 * From the current line count and characters read after that, estimate the
2665 * line number where we are now.
2666 * Used for error messages that include a line number.
2667 */
2668 static linenr_T
2669readfile_linenr(linecnt, p, endp)
2670 linenr_T linecnt; /* line count before reading more bytes */
2671 char_u *p; /* start of more bytes read */
2672 char_u *endp; /* end of more bytes read */
2673{
2674 char_u *s;
2675 linenr_T lnum;
2676
2677 lnum = curbuf->b_ml.ml_line_count - linecnt + 1;
2678 for (s = p; s < endp; ++s)
2679 if (*s == '\n')
2680 ++lnum;
2681 return lnum;
2682}
2683#endif
2684
Bram Moolenaar071d4272004-06-13 20:20:40 +00002685/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00002686 * Fill "*eap" to force the 'fileencoding', 'fileformat' and 'binary to be
2687 * equal to the buffer "buf". Used for calling readfile().
Bram Moolenaar071d4272004-06-13 20:20:40 +00002688 * Returns OK or FAIL.
2689 */
2690 int
2691prep_exarg(eap, buf)
2692 exarg_T *eap;
2693 buf_T *buf;
2694{
2695 eap->cmd = alloc((unsigned)(STRLEN(buf->b_p_ff)
2696#ifdef FEAT_MBYTE
2697 + STRLEN(buf->b_p_fenc)
2698#endif
2699 + 15));
2700 if (eap->cmd == NULL)
2701 return FAIL;
2702
2703#ifdef FEAT_MBYTE
2704 sprintf((char *)eap->cmd, "e ++ff=%s ++enc=%s", buf->b_p_ff, buf->b_p_fenc);
2705 eap->force_enc = 14 + (int)STRLEN(buf->b_p_ff);
Bram Moolenaar195d6352005-12-19 22:08:24 +00002706 eap->bad_char = buf->b_bad_char;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002707#else
2708 sprintf((char *)eap->cmd, "e ++ff=%s", buf->b_p_ff);
2709#endif
2710 eap->force_ff = 7;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002711
2712 eap->force_bin = buf->b_p_bin ? FORCE_BIN : FORCE_NOBIN;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002713 eap->read_edit = FALSE;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002714 eap->forceit = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002715 return OK;
2716}
2717
2718#ifdef FEAT_MBYTE
2719/*
2720 * Find next fileencoding to use from 'fileencodings'.
2721 * "pp" points to fenc_next. It's advanced to the next item.
2722 * When there are no more items, an empty string is returned and *pp is set to
2723 * NULL.
2724 * When *pp is not set to NULL, the result is in allocated memory.
2725 */
2726 static char_u *
2727next_fenc(pp)
2728 char_u **pp;
2729{
2730 char_u *p;
2731 char_u *r;
2732
2733 if (**pp == NUL)
2734 {
2735 *pp = NULL;
2736 return (char_u *)"";
2737 }
2738 p = vim_strchr(*pp, ',');
2739 if (p == NULL)
2740 {
2741 r = enc_canonize(*pp);
2742 *pp += STRLEN(*pp);
2743 }
2744 else
2745 {
2746 r = vim_strnsave(*pp, (int)(p - *pp));
2747 *pp = p + 1;
2748 if (r != NULL)
2749 {
2750 p = enc_canonize(r);
2751 vim_free(r);
2752 r = p;
2753 }
2754 }
2755 if (r == NULL) /* out of memory */
2756 {
2757 r = (char_u *)"";
2758 *pp = NULL;
2759 }
2760 return r;
2761}
2762
2763# ifdef FEAT_EVAL
2764/*
2765 * Convert a file with the 'charconvert' expression.
2766 * This closes the file which is to be read, converts it and opens the
2767 * resulting file for reading.
2768 * Returns name of the resulting converted file (the caller should delete it
2769 * after reading it).
2770 * Returns NULL if the conversion failed ("*fdp" is not set) .
2771 */
2772 static char_u *
2773readfile_charconvert(fname, fenc, fdp)
2774 char_u *fname; /* name of input file */
2775 char_u *fenc; /* converted from */
2776 int *fdp; /* in/out: file descriptor of file */
2777{
2778 char_u *tmpname;
2779 char_u *errmsg = NULL;
2780
2781 tmpname = vim_tempname('r');
2782 if (tmpname == NULL)
2783 errmsg = (char_u *)_("Can't find temp file for conversion");
2784 else
2785 {
2786 close(*fdp); /* close the input file, ignore errors */
2787 *fdp = -1;
2788 if (eval_charconvert(fenc, enc_utf8 ? (char_u *)"utf-8" : p_enc,
2789 fname, tmpname) == FAIL)
2790 errmsg = (char_u *)_("Conversion with 'charconvert' failed");
2791 if (errmsg == NULL && (*fdp = mch_open((char *)tmpname,
2792 O_RDONLY | O_EXTRA, 0)) < 0)
2793 errmsg = (char_u *)_("can't read output of 'charconvert'");
2794 }
2795
2796 if (errmsg != NULL)
2797 {
2798 /* Don't use emsg(), it breaks mappings, the retry with
2799 * another type of conversion might still work. */
2800 MSG(errmsg);
2801 if (tmpname != NULL)
2802 {
2803 mch_remove(tmpname); /* delete converted file */
2804 vim_free(tmpname);
2805 tmpname = NULL;
2806 }
2807 }
2808
2809 /* If the input file is closed, open it (caller should check for error). */
2810 if (*fdp < 0)
2811 *fdp = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
2812
2813 return tmpname;
2814}
2815# endif
2816
2817#endif
2818
2819#ifdef FEAT_VIMINFO
2820/*
2821 * Read marks for the current buffer from the viminfo file, when we support
2822 * buffer marks and the buffer has a name.
2823 */
2824 static void
2825check_marks_read()
2826{
2827 if (!curbuf->b_marks_read && get_viminfo_parameter('\'') > 0
2828 && curbuf->b_ffname != NULL)
Bram Moolenaard812df62008-11-09 12:46:09 +00002829 read_viminfo(NULL, VIF_WANT_MARKS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002830
2831 /* Always set b_marks_read; needed when 'viminfo' is changed to include
2832 * the ' parameter after opening a buffer. */
2833 curbuf->b_marks_read = TRUE;
2834}
2835#endif
2836
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002837#if defined(FEAT_CRYPT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002838/*
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002839 * Get the crypt method used for a file from "ptr[len]", the magic text at the
2840 * start of the file.
2841 * Returns -1 when no encryption used.
2842 */
2843 static int
2844get_crypt_method(ptr, len)
2845 char *ptr;
2846 int len;
2847{
2848 int i;
2849
2850 for (i = 0; i < (int)(sizeof(crypt_magic) / sizeof(crypt_magic[0])); i++)
2851 {
Bram Moolenaar80794b12010-06-13 05:20:42 +02002852 if (len < (CRYPT_MAGIC_LEN + crypt_salt_len[i] + crypt_seed_len[i]))
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002853 continue;
2854 if (memcmp(ptr, crypt_magic[i], CRYPT_MAGIC_LEN) == 0)
2855 return i;
2856 }
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002857
Bram Moolenaar442b4222010-05-24 21:34:22 +02002858 i = (int)STRLEN(crypt_magic_head);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002859 if (len >= i && memcmp(ptr, crypt_magic_head, i) == 0)
2860 EMSG(_("E821: File is encrypted with unknown method"));
2861
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002862 return -1;
2863}
2864
2865/*
2866 * Check for magic number used for encryption. Applies to the current buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002867 * If found, the magic number is removed from ptr[*sizep] and *sizep and
2868 * *filesizep are updated.
2869 * Return the (new) encryption key, NULL for no encryption.
2870 */
2871 static char_u *
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002872check_for_cryptkey(cryptkey, ptr, sizep, filesizep, newfile, did_ask)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002873 char_u *cryptkey; /* previous encryption key or NULL */
2874 char_u *ptr; /* pointer to read bytes */
2875 long *sizep; /* length of read bytes */
Bram Moolenaar914703b2010-05-31 21:59:46 +02002876 off_t *filesizep; /* nr of bytes used from file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002877 int newfile; /* editing a new buffer */
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002878 int *did_ask; /* flag: whether already asked for key */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002879{
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002880 int method = get_crypt_method((char *)ptr, *sizep);
2881
2882 if (method >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002883 {
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002884 curbuf->b_p_cm = method;
2885 use_crypt_method = method;
2886 if (method > 0)
2887 (void)blowfish_self_test();
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002888 if (cryptkey == NULL && !*did_ask)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002889 {
2890 if (*curbuf->b_p_key)
2891 cryptkey = curbuf->b_p_key;
2892 else
2893 {
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002894 /* When newfile is TRUE, store the typed key in the 'key'
2895 * option and don't free it. bf needs hash of the key saved.
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002896 * Don't ask for the key again when first time Enter was hit.
2897 * Happens when retrying to detect encoding. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002898 cryptkey = get_crypt_key(newfile, FALSE);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002899 *did_ask = TRUE;
2900
Bram Moolenaar071d4272004-06-13 20:20:40 +00002901 /* check if empty key entered */
2902 if (cryptkey != NULL && *cryptkey == NUL)
2903 {
2904 if (cryptkey != curbuf->b_p_key)
2905 vim_free(cryptkey);
2906 cryptkey = NULL;
2907 }
2908 }
2909 }
2910
2911 if (cryptkey != NULL)
2912 {
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002913 int seed_len = crypt_seed_len[method];
Bram Moolenaar80794b12010-06-13 05:20:42 +02002914 int salt_len = crypt_salt_len[method];
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002915
2916 if (method == 0)
2917 crypt_init_keys(cryptkey);
2918 else
2919 {
Bram Moolenaar80794b12010-06-13 05:20:42 +02002920 bf_key_init(cryptkey, ptr + CRYPT_MAGIC_LEN, salt_len);
2921 bf_ofb_init(ptr + CRYPT_MAGIC_LEN + salt_len, seed_len);
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002922 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002923
2924 /* Remove magic number from the text */
Bram Moolenaar80794b12010-06-13 05:20:42 +02002925 *filesizep += CRYPT_MAGIC_LEN + salt_len + seed_len;
2926 *sizep -= CRYPT_MAGIC_LEN + salt_len + seed_len;
2927 mch_memmove(ptr, ptr + CRYPT_MAGIC_LEN + salt_len + seed_len, (size_t)*sizep);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002928 }
2929 }
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002930 /* When starting to edit a new file which does not have encryption, clear
2931 * the 'key' option, except when starting up (called with -x argument) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002932 else if (newfile && *curbuf->b_p_key && !starting)
2933 set_option_value((char_u *)"key", 0L, (char_u *)"", OPT_LOCAL);
2934
2935 return cryptkey;
2936}
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002937
2938/*
2939 * Check for magic number used for encryption. Applies to the current buffer.
2940 * If found and decryption is possible returns OK;
2941 */
2942 int
2943prepare_crypt_read(fp)
2944 FILE *fp;
2945{
2946 int method;
Bram Moolenaar80794b12010-06-13 05:20:42 +02002947 char_u buffer[CRYPT_MAGIC_LEN + CRYPT_SALT_LEN_MAX
2948 + CRYPT_SEED_LEN_MAX + 2];
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002949
2950 if (fread(buffer, CRYPT_MAGIC_LEN, 1, fp) != 1)
2951 return FAIL;
2952 method = get_crypt_method((char *)buffer,
Bram Moolenaar80794b12010-06-13 05:20:42 +02002953 CRYPT_MAGIC_LEN +
2954 CRYPT_SEED_LEN_MAX +
2955 CRYPT_SALT_LEN_MAX);
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002956 if (method < 0 || method != curbuf->b_p_cm)
2957 return FAIL;
2958
2959 if (method == 0)
2960 crypt_init_keys(curbuf->b_p_key);
2961 else
2962 {
Bram Moolenaar80794b12010-06-13 05:20:42 +02002963 int salt_len = crypt_salt_len[method];
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002964 int seed_len = crypt_seed_len[method];
2965
Bram Moolenaar80794b12010-06-13 05:20:42 +02002966 if (fread(buffer, salt_len + seed_len, 1, fp) != 1)
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002967 return FAIL;
Bram Moolenaar80794b12010-06-13 05:20:42 +02002968 bf_key_init(curbuf->b_p_key, buffer, salt_len);
2969 bf_ofb_init(buffer + salt_len, seed_len);
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002970 }
2971 return OK;
2972}
2973
2974/*
2975 * Prepare for writing encrypted bytes for buffer "buf".
2976 * Returns a pointer to an allocated header of length "*lenp".
2977 */
2978 char_u *
2979prepare_crypt_write(buf, lenp)
2980 buf_T *buf;
2981 int *lenp;
2982{
2983 char_u *header;
2984 int seed_len = crypt_seed_len[buf->b_p_cm];
Bram Moolenaar80794b12010-06-13 05:20:42 +02002985 int salt_len = crypt_salt_len[buf->b_p_cm];
2986 char_u *salt;
2987 char_u *seed;
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002988
Bram Moolenaar80794b12010-06-13 05:20:42 +02002989 header = alloc_clear(CRYPT_MAGIC_LEN + CRYPT_SALT_LEN_MAX
2990 + CRYPT_SEED_LEN_MAX + 2);
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002991 if (header != NULL)
2992 {
2993 use_crypt_method = buf->b_p_cm; /* select pkzip or blowfish */
2994 vim_strncpy(header, (char_u *)crypt_magic[use_crypt_method],
2995 CRYPT_MAGIC_LEN);
2996 if (buf->b_p_cm == 0)
2997 crypt_init_keys(buf->b_p_key);
2998 else
2999 {
Bram Moolenaar80794b12010-06-13 05:20:42 +02003000 /* Using blowfish, add salt and seed. */
3001 salt = header + CRYPT_MAGIC_LEN;
3002 seed = salt + salt_len;
3003 sha2_seed(salt, salt_len, seed, seed_len);
3004 bf_key_init(buf->b_p_key, salt, salt_len);
3005 bf_ofb_init(seed, seed_len);
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003006 }
3007 }
Bram Moolenaar80794b12010-06-13 05:20:42 +02003008 *lenp = CRYPT_MAGIC_LEN + salt_len + seed_len;
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003009 return header;
3010}
3011
Bram Moolenaar80794b12010-06-13 05:20:42 +02003012#endif /* FEAT_CRYPT */
3013
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003014/*
3015 * Like fwrite() but crypt the bytes when 'key' is set.
3016 * Returns 1 if successful.
3017 */
3018 size_t
3019fwrite_crypt(buf, ptr, len, fp)
Bram Moolenaar80794b12010-06-13 05:20:42 +02003020 buf_T *buf UNUSED;
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003021 char_u *ptr;
3022 size_t len;
3023 FILE *fp;
3024{
Bram Moolenaar80794b12010-06-13 05:20:42 +02003025#ifdef FEAT_CRYPT
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003026 char_u *copy;
3027 char_u small_buf[100];
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003028 size_t i;
3029
3030 if (*buf->b_p_key == NUL)
3031 return fwrite(ptr, len, (size_t)1, fp);
3032 if (len < 100)
3033 copy = small_buf; /* no malloc()/free() for short strings */
3034 else
3035 {
3036 copy = lalloc(len, FALSE);
3037 if (copy == NULL)
3038 return 0;
3039 }
Bram Moolenaar04c9baf2010-06-01 23:37:39 +02003040 crypt_encode(ptr, len, copy);
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003041 i = fwrite(copy, len, (size_t)1, fp);
3042 if (copy != small_buf)
3043 vim_free(copy);
3044 return i;
Bram Moolenaar80794b12010-06-13 05:20:42 +02003045#else
3046 return fwrite(ptr, len, (size_t)1, fp);
3047#endif
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003048}
3049
3050/*
3051 * Read a string of length "len" from "fd".
3052 * When 'key' is set decrypt the bytes.
3053 */
3054 char_u *
3055read_string_decrypt(buf, fd, len)
Bram Moolenaar80794b12010-06-13 05:20:42 +02003056 buf_T *buf UNUSED;
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003057 FILE *fd;
3058 int len;
3059{
3060 char_u *ptr;
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003061
3062 ptr = read_string(fd, len);
Bram Moolenaar80794b12010-06-13 05:20:42 +02003063#ifdef FEAT_CRYPT
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003064 if (ptr != NULL || *buf->b_p_key != NUL)
Bram Moolenaar04c9baf2010-06-01 23:37:39 +02003065 crypt_decode(ptr, len);
Bram Moolenaar80794b12010-06-13 05:20:42 +02003066#endif
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003067 return ptr;
3068}
3069
Bram Moolenaar071d4272004-06-13 20:20:40 +00003070
3071#ifdef UNIX
3072 static void
3073set_file_time(fname, atime, mtime)
3074 char_u *fname;
3075 time_t atime; /* access time */
3076 time_t mtime; /* modification time */
3077{
3078# if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
3079 struct utimbuf buf;
3080
3081 buf.actime = atime;
3082 buf.modtime = mtime;
3083 (void)utime((char *)fname, &buf);
3084# else
3085# if defined(HAVE_UTIMES)
3086 struct timeval tvp[2];
3087
3088 tvp[0].tv_sec = atime;
3089 tvp[0].tv_usec = 0;
3090 tvp[1].tv_sec = mtime;
3091 tvp[1].tv_usec = 0;
3092# ifdef NeXT
3093 (void)utimes((char *)fname, tvp);
3094# else
3095 (void)utimes((char *)fname, (const struct timeval *)&tvp);
3096# endif
3097# endif
3098# endif
3099}
3100#endif /* UNIX */
3101
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003102#if defined(VMS) && !defined(MIN)
3103/* Older DECC compiler for VAX doesn't define MIN() */
3104# define MIN(a, b) ((a) < (b) ? (a) : (b))
3105#endif
3106
Bram Moolenaar071d4272004-06-13 20:20:40 +00003107/*
Bram Moolenaar5386a122007-06-28 20:02:32 +00003108 * Return TRUE if a file appears to be read-only from the file permissions.
3109 */
3110 int
3111check_file_readonly(fname, perm)
3112 char_u *fname; /* full path to file */
3113 int perm; /* known permissions on file */
3114{
3115#ifndef USE_MCH_ACCESS
3116 int fd = 0;
3117#endif
3118
3119 return (
3120#ifdef USE_MCH_ACCESS
3121# ifdef UNIX
3122 (perm & 0222) == 0 ||
3123# endif
3124 mch_access((char *)fname, W_OK)
3125#else
3126 (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0
3127 ? TRUE : (close(fd), FALSE)
3128#endif
3129 );
3130}
3131
3132
3133/*
Bram Moolenaar292ad192005-12-11 21:29:51 +00003134 * buf_write() - write to file "fname" lines "start" through "end"
Bram Moolenaar071d4272004-06-13 20:20:40 +00003135 *
3136 * We do our own buffering here because fwrite() is so slow.
3137 *
Bram Moolenaar292ad192005-12-11 21:29:51 +00003138 * If "forceit" is true, we don't care for errors when attempting backups.
3139 * In case of an error everything possible is done to restore the original
Bram Moolenaare37d50a2008-08-06 17:06:04 +00003140 * file. But when "forceit" is TRUE, we risk losing it.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003141 *
3142 * When "reset_changed" is TRUE and "append" == FALSE and "start" == 1 and
3143 * "end" == curbuf->b_ml.ml_line_count, reset curbuf->b_changed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003144 *
3145 * This function must NOT use NameBuff (because it's called by autowrite()).
3146 *
3147 * return FAIL for failure, OK otherwise
3148 */
3149 int
3150buf_write(buf, fname, sfname, start, end, eap, append, forceit,
3151 reset_changed, filtering)
3152 buf_T *buf;
3153 char_u *fname;
3154 char_u *sfname;
3155 linenr_T start, end;
3156 exarg_T *eap; /* for forced 'ff' and 'fenc', can be
3157 NULL! */
Bram Moolenaar292ad192005-12-11 21:29:51 +00003158 int append; /* append to the file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003159 int forceit;
3160 int reset_changed;
3161 int filtering;
3162{
3163 int fd;
3164 char_u *backup = NULL;
3165 int backup_copy = FALSE; /* copy the original file? */
3166 int dobackup;
3167 char_u *ffname;
3168 char_u *wfname = NULL; /* name of file to write to */
3169 char_u *s;
3170 char_u *ptr;
3171 char_u c;
3172 int len;
3173 linenr_T lnum;
3174 long nchars;
3175 char_u *errmsg = NULL;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003176 int errmsg_allocated = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003177 char_u *errnum = NULL;
3178 char_u *buffer;
3179 char_u smallbuf[SMBUFSIZE];
3180 char_u *backup_ext;
3181 int bufsize;
3182 long perm; /* file permissions */
3183 int retval = OK;
3184 int newfile = FALSE; /* TRUE if file doesn't exist yet */
3185 int msg_save = msg_scroll;
3186 int overwriting; /* TRUE if writing over original */
3187 int no_eol = FALSE; /* no end-of-line written */
3188 int device = FALSE; /* writing to a device */
3189 struct stat st_old;
3190 int prev_got_int = got_int;
3191 int file_readonly = FALSE; /* overwritten file is read-only */
3192 static char *err_readonly = "is read-only (cannot override: \"W\" in 'cpoptions')";
3193#if defined(UNIX) || defined(__EMX__XX) /*XXX fix me sometime? */
3194 int made_writable = FALSE; /* 'w' bit has been set */
3195#endif
3196 /* writing everything */
3197 int whole = (start == 1 && end == buf->b_ml.ml_line_count);
3198#ifdef FEAT_AUTOCMD
3199 linenr_T old_line_count = buf->b_ml.ml_line_count;
3200#endif
3201 int attr;
3202 int fileformat;
3203 int write_bin;
3204 struct bw_info write_info; /* info for buf_write_bytes() */
3205#ifdef FEAT_MBYTE
3206 int converted = FALSE;
3207 int notconverted = FALSE;
3208 char_u *fenc; /* effective 'fileencoding' */
3209 char_u *fenc_tofree = NULL; /* allocated "fenc" */
3210#endif
3211#ifdef HAS_BW_FLAGS
3212 int wb_flags = 0;
3213#endif
3214#ifdef HAVE_ACL
3215 vim_acl_T acl = NULL; /* ACL copied from original file to
3216 backup or new file */
3217#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003218#ifdef FEAT_PERSISTENT_UNDO
3219 int write_undo_file = FALSE;
3220 context_sha256_T sha_ctx;
3221#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003222
3223 if (fname == NULL || *fname == NUL) /* safety check */
3224 return FAIL;
Bram Moolenaar70d60e92009-12-31 13:53:33 +00003225 if (buf->b_ml.ml_mfp == NULL)
3226 {
3227 /* This can happen during startup when there is a stray "w" in the
3228 * vimrc file. */
3229 EMSG(_(e_emptybuf));
3230 return FAIL;
3231 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003232
3233 /*
3234 * Disallow writing from .exrc and .vimrc in current directory for
3235 * security reasons.
3236 */
3237 if (check_secure())
3238 return FAIL;
3239
3240 /* Avoid a crash for a long name. */
3241 if (STRLEN(fname) >= MAXPATHL)
3242 {
3243 EMSG(_(e_longname));
3244 return FAIL;
3245 }
3246
3247#ifdef FEAT_MBYTE
3248 /* must init bw_conv_buf and bw_iconv_fd before jumping to "fail" */
3249 write_info.bw_conv_buf = NULL;
3250 write_info.bw_conv_error = FALSE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003251 write_info.bw_conv_error_lnum = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003252 write_info.bw_restlen = 0;
3253# ifdef USE_ICONV
3254 write_info.bw_iconv_fd = (iconv_t)-1;
3255# endif
3256#endif
3257
Bram Moolenaardf177f62005-02-22 08:39:57 +00003258 /* After writing a file changedtick changes but we don't want to display
3259 * the line. */
3260 ex_no_reprint = TRUE;
3261
Bram Moolenaar071d4272004-06-13 20:20:40 +00003262 /*
3263 * If there is no file name yet, use the one for the written file.
3264 * BF_NOTEDITED is set to reflect this (in case the write fails).
3265 * Don't do this when the write is for a filter command.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003266 * Don't do this when appending.
3267 * Only do this when 'cpoptions' contains the 'F' flag.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003268 */
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003269 if (buf->b_ffname == NULL
3270 && reset_changed
Bram Moolenaar071d4272004-06-13 20:20:40 +00003271 && whole
3272 && buf == curbuf
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00003273#ifdef FEAT_QUICKFIX
3274 && !bt_nofile(buf)
3275#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003276 && !filtering
Bram Moolenaar292ad192005-12-11 21:29:51 +00003277 && (!append || vim_strchr(p_cpo, CPO_FNAMEAPP) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003278 && vim_strchr(p_cpo, CPO_FNAMEW) != NULL)
3279 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003280 if (set_rw_fname(fname, sfname) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003281 return FAIL;
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003282 buf = curbuf; /* just in case autocmds made "buf" invalid */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003283 }
3284
3285 if (sfname == NULL)
3286 sfname = fname;
3287 /*
3288 * For Unix: Use the short file name whenever possible.
3289 * Avoids problems with networks and when directory names are changed.
3290 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
3291 * another directory, which we don't detect
3292 */
3293 ffname = fname; /* remember full fname */
3294#ifdef UNIX
3295 fname = sfname;
3296#endif
3297
3298 if (buf->b_ffname != NULL && fnamecmp(ffname, buf->b_ffname) == 0)
3299 overwriting = TRUE;
3300 else
3301 overwriting = FALSE;
3302
3303 if (exiting)
3304 settmode(TMODE_COOK); /* when exiting allow typahead now */
3305
3306 ++no_wait_return; /* don't wait for return yet */
3307
3308 /*
3309 * Set '[ and '] marks to the lines to be written.
3310 */
3311 buf->b_op_start.lnum = start;
3312 buf->b_op_start.col = 0;
3313 buf->b_op_end.lnum = end;
3314 buf->b_op_end.col = 0;
3315
3316#ifdef FEAT_AUTOCMD
3317 {
3318 aco_save_T aco;
3319 int buf_ffname = FALSE;
3320 int buf_sfname = FALSE;
3321 int buf_fname_f = FALSE;
3322 int buf_fname_s = FALSE;
3323 int did_cmd = FALSE;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003324 int nofile_err = FALSE;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003325 int empty_memline = (buf->b_ml.ml_mfp == NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003326
3327 /*
3328 * Apply PRE aucocommands.
3329 * Set curbuf to the buffer to be written.
3330 * Careful: The autocommands may call buf_write() recursively!
3331 */
3332 if (ffname == buf->b_ffname)
3333 buf_ffname = TRUE;
3334 if (sfname == buf->b_sfname)
3335 buf_sfname = TRUE;
3336 if (fname == buf->b_ffname)
3337 buf_fname_f = TRUE;
3338 if (fname == buf->b_sfname)
3339 buf_fname_s = TRUE;
3340
3341 /* set curwin/curbuf to buf and save a few things */
3342 aucmd_prepbuf(&aco, buf);
3343
3344 if (append)
3345 {
3346 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD,
3347 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003348 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003349#ifdef FEAT_QUICKFIX
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00003350 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003351 nofile_err = TRUE;
3352 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003353#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003354 apply_autocmds_exarg(EVENT_FILEAPPENDPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003355 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003356 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003357 }
3358 else if (filtering)
3359 {
3360 apply_autocmds_exarg(EVENT_FILTERWRITEPRE,
3361 NULL, sfname, FALSE, curbuf, eap);
3362 }
3363 else if (reset_changed && whole)
3364 {
3365 if (!(did_cmd = apply_autocmds_exarg(EVENT_BUFWRITECMD,
3366 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003367 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003368#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003369 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003370 nofile_err = TRUE;
3371 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003372#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003373 apply_autocmds_exarg(EVENT_BUFWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003374 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003375 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003376 }
3377 else
3378 {
3379 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD,
3380 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003381 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003382#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003383 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003384 nofile_err = TRUE;
3385 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003386#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003387 apply_autocmds_exarg(EVENT_FILEWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003388 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003389 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003390 }
3391
3392 /* restore curwin/curbuf and a few other things */
3393 aucmd_restbuf(&aco);
3394
3395 /*
3396 * In three situations we return here and don't write the file:
3397 * 1. the autocommands deleted or unloaded the buffer.
3398 * 2. The autocommands abort script processing.
3399 * 3. If one of the "Cmd" autocommands was executed.
3400 */
3401 if (!buf_valid(buf))
3402 buf = NULL;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003403 if (buf == NULL || (buf->b_ml.ml_mfp == NULL && !empty_memline)
Bram Moolenaar1e015462005-09-25 22:16:38 +00003404 || did_cmd || nofile_err
3405#ifdef FEAT_EVAL
3406 || aborting()
3407#endif
3408 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003409 {
3410 --no_wait_return;
3411 msg_scroll = msg_save;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003412 if (nofile_err)
3413 EMSG(_("E676: No matching autocommands for acwrite buffer"));
3414
Bram Moolenaar1e015462005-09-25 22:16:38 +00003415 if (nofile_err
3416#ifdef FEAT_EVAL
3417 || aborting()
3418#endif
3419 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003420 /* An aborting error, interrupt or exception in the
3421 * autocommands. */
3422 return FAIL;
3423 if (did_cmd)
3424 {
3425 if (buf == NULL)
3426 /* The buffer was deleted. We assume it was written
3427 * (can't retry anyway). */
3428 return OK;
3429 if (overwriting)
3430 {
3431 /* Assume the buffer was written, update the timestamp. */
3432 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00003433 if (append)
3434 buf->b_flags &= ~BF_NEW;
3435 else
3436 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003437 }
Bram Moolenaar292ad192005-12-11 21:29:51 +00003438 if (reset_changed && buf->b_changed && !append
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003439 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003440 /* Buffer still changed, the autocommands didn't work
3441 * properly. */
3442 return FAIL;
3443 return OK;
3444 }
3445#ifdef FEAT_EVAL
3446 if (!aborting())
3447#endif
3448 EMSG(_("E203: Autocommands deleted or unloaded buffer to be written"));
3449 return FAIL;
3450 }
3451
3452 /*
3453 * The autocommands may have changed the number of lines in the file.
3454 * When writing the whole file, adjust the end.
3455 * When writing part of the file, assume that the autocommands only
3456 * changed the number of lines that are to be written (tricky!).
3457 */
3458 if (buf->b_ml.ml_line_count != old_line_count)
3459 {
3460 if (whole) /* write all */
3461 end = buf->b_ml.ml_line_count;
3462 else if (buf->b_ml.ml_line_count > old_line_count) /* more lines */
3463 end += buf->b_ml.ml_line_count - old_line_count;
3464 else /* less lines */
3465 {
3466 end -= old_line_count - buf->b_ml.ml_line_count;
3467 if (end < start)
3468 {
3469 --no_wait_return;
3470 msg_scroll = msg_save;
3471 EMSG(_("E204: Autocommand changed number of lines in unexpected way"));
3472 return FAIL;
3473 }
3474 }
3475 }
3476
3477 /*
3478 * The autocommands may have changed the name of the buffer, which may
3479 * be kept in fname, ffname and sfname.
3480 */
3481 if (buf_ffname)
3482 ffname = buf->b_ffname;
3483 if (buf_sfname)
3484 sfname = buf->b_sfname;
3485 if (buf_fname_f)
3486 fname = buf->b_ffname;
3487 if (buf_fname_s)
3488 fname = buf->b_sfname;
3489 }
3490#endif
3491
3492#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003493 if (netbeans_active() && isNetbeansBuffer(buf))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003494 {
3495 if (whole)
3496 {
3497 /*
3498 * b_changed can be 0 after an undo, but we still need to write
3499 * the buffer to NetBeans.
3500 */
3501 if (buf->b_changed || isNetbeansModified(buf))
3502 {
Bram Moolenaar009b2592004-10-24 19:18:58 +00003503 --no_wait_return; /* may wait for return now */
3504 msg_scroll = msg_save;
3505 netbeans_save_buffer(buf); /* no error checking... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003506 return retval;
3507 }
3508 else
3509 {
3510 errnum = (char_u *)"E656: ";
Bram Moolenaared0e7452008-06-27 19:17:34 +00003511 errmsg = (char_u *)_("NetBeans disallows writes of unmodified buffers");
Bram Moolenaar071d4272004-06-13 20:20:40 +00003512 buffer = NULL;
3513 goto fail;
3514 }
3515 }
3516 else
3517 {
3518 errnum = (char_u *)"E657: ";
3519 errmsg = (char_u *)_("Partial writes disallowed for NetBeans buffers");
3520 buffer = NULL;
3521 goto fail;
3522 }
3523 }
3524#endif
3525
3526 if (shortmess(SHM_OVER) && !exiting)
3527 msg_scroll = FALSE; /* overwrite previous file message */
3528 else
3529 msg_scroll = TRUE; /* don't overwrite previous file message */
3530 if (!filtering)
3531 filemess(buf,
3532#ifndef UNIX
3533 sfname,
3534#else
3535 fname,
3536#endif
3537 (char_u *)"", 0); /* show that we are busy */
3538 msg_scroll = FALSE; /* always overwrite the file message now */
3539
3540 buffer = alloc(BUFSIZE);
3541 if (buffer == NULL) /* can't allocate big buffer, use small
3542 * one (to be able to write when out of
3543 * memory) */
3544 {
3545 buffer = smallbuf;
3546 bufsize = SMBUFSIZE;
3547 }
3548 else
3549 bufsize = BUFSIZE;
3550
3551 /*
3552 * Get information about original file (if there is one).
3553 */
3554#if defined(UNIX) && !defined(ARCHIE)
Bram Moolenaar6f192452007-11-08 19:49:02 +00003555 st_old.st_dev = 0;
3556 st_old.st_ino = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003557 perm = -1;
3558 if (mch_stat((char *)fname, &st_old) < 0)
3559 newfile = TRUE;
3560 else
3561 {
3562 perm = st_old.st_mode;
3563 if (!S_ISREG(st_old.st_mode)) /* not a file */
3564 {
3565 if (S_ISDIR(st_old.st_mode))
3566 {
3567 errnum = (char_u *)"E502: ";
3568 errmsg = (char_u *)_("is a directory");
3569 goto fail;
3570 }
3571 if (mch_nodetype(fname) != NODE_WRITABLE)
3572 {
3573 errnum = (char_u *)"E503: ";
3574 errmsg = (char_u *)_("is not a file or writable device");
3575 goto fail;
3576 }
3577 /* It's a device of some kind (or a fifo) which we can write to
3578 * but for which we can't make a backup. */
3579 device = TRUE;
3580 newfile = TRUE;
3581 perm = -1;
3582 }
3583 }
3584#else /* !UNIX */
3585 /*
3586 * Check for a writable device name.
3587 */
3588 c = mch_nodetype(fname);
3589 if (c == NODE_OTHER)
3590 {
3591 errnum = (char_u *)"E503: ";
3592 errmsg = (char_u *)_("is not a file or writable device");
3593 goto fail;
3594 }
3595 if (c == NODE_WRITABLE)
3596 {
Bram Moolenaar043545e2006-10-10 16:44:07 +00003597# if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3598 /* MS-Windows allows opening a device, but we will probably get stuck
3599 * trying to write to it. */
3600 if (!p_odev)
3601 {
3602 errnum = (char_u *)"E796: ";
3603 errmsg = (char_u *)_("writing to device disabled with 'opendevice' option");
3604 goto fail;
3605 }
3606# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003607 device = TRUE;
3608 newfile = TRUE;
3609 perm = -1;
3610 }
3611 else
3612 {
3613 perm = mch_getperm(fname);
3614 if (perm < 0)
3615 newfile = TRUE;
3616 else if (mch_isdir(fname))
3617 {
3618 errnum = (char_u *)"E502: ";
3619 errmsg = (char_u *)_("is a directory");
3620 goto fail;
3621 }
3622 if (overwriting)
3623 (void)mch_stat((char *)fname, &st_old);
3624 }
3625#endif /* !UNIX */
3626
3627 if (!device && !newfile)
3628 {
3629 /*
3630 * Check if the file is really writable (when renaming the file to
3631 * make a backup we won't discover it later).
3632 */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003633 file_readonly = check_file_readonly(fname, (int)perm);
3634
Bram Moolenaar071d4272004-06-13 20:20:40 +00003635 if (!forceit && file_readonly)
3636 {
3637 if (vim_strchr(p_cpo, CPO_FWRITE) != NULL)
3638 {
3639 errnum = (char_u *)"E504: ";
3640 errmsg = (char_u *)_(err_readonly);
3641 }
3642 else
3643 {
3644 errnum = (char_u *)"E505: ";
3645 errmsg = (char_u *)_("is read-only (add ! to override)");
3646 }
3647 goto fail;
3648 }
3649
3650 /*
3651 * Check if the timestamp hasn't changed since reading the file.
3652 */
3653 if (overwriting)
3654 {
3655 retval = check_mtime(buf, &st_old);
3656 if (retval == FAIL)
3657 goto fail;
3658 }
3659 }
3660
3661#ifdef HAVE_ACL
3662 /*
3663 * For systems that support ACL: get the ACL from the original file.
3664 */
3665 if (!newfile)
3666 acl = mch_get_acl(fname);
3667#endif
3668
3669 /*
3670 * If 'backupskip' is not empty, don't make a backup for some files.
3671 */
3672 dobackup = (p_wb || p_bk || *p_pm != NUL);
3673#ifdef FEAT_WILDIGN
3674 if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname))
3675 dobackup = FALSE;
3676#endif
3677
3678 /*
3679 * Save the value of got_int and reset it. We don't want a previous
3680 * interruption cancel writing, only hitting CTRL-C while writing should
3681 * abort it.
3682 */
3683 prev_got_int = got_int;
3684 got_int = FALSE;
3685
3686 /* Mark the buffer as 'being saved' to prevent changed buffer warnings */
3687 buf->b_saving = TRUE;
3688
3689 /*
3690 * If we are not appending or filtering, the file exists, and the
3691 * 'writebackup', 'backup' or 'patchmode' option is set, need a backup.
3692 * When 'patchmode' is set also make a backup when appending.
3693 *
3694 * Do not make any backup, if 'writebackup' and 'backup' are both switched
3695 * off. This helps when editing large files on almost-full disks.
3696 */
3697 if (!(append && *p_pm == NUL) && !filtering && perm >= 0 && dobackup)
3698 {
3699#if defined(UNIX) || defined(WIN32)
3700 struct stat st;
3701#endif
3702
3703 if ((bkc_flags & BKC_YES) || append) /* "yes" */
3704 backup_copy = TRUE;
3705#if defined(UNIX) || defined(WIN32)
3706 else if ((bkc_flags & BKC_AUTO)) /* "auto" */
3707 {
3708 int i;
3709
3710# ifdef UNIX
3711 /*
3712 * Don't rename the file when:
3713 * - it's a hard link
3714 * - it's a symbolic link
3715 * - we don't have write permission in the directory
3716 * - we can't set the owner/group of the new file
3717 */
3718 if (st_old.st_nlink > 1
3719 || mch_lstat((char *)fname, &st) < 0
3720 || st.st_dev != st_old.st_dev
Bram Moolenaara5792f52005-11-23 21:25:05 +00003721 || st.st_ino != st_old.st_ino
3722# ifndef HAVE_FCHOWN
3723 || st.st_uid != st_old.st_uid
3724 || st.st_gid != st_old.st_gid
3725# endif
3726 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003727 backup_copy = TRUE;
3728 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003729# else
3730# ifdef WIN32
3731 /* On NTFS file systems hard links are possible. */
3732 if (mch_is_linked(fname))
3733 backup_copy = TRUE;
3734 else
3735# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003736# endif
3737 {
3738 /*
3739 * Check if we can create a file and set the owner/group to
3740 * the ones from the original file.
3741 * First find a file name that doesn't exist yet (use some
3742 * arbitrary numbers).
3743 */
3744 STRCPY(IObuff, fname);
3745 for (i = 4913; ; i += 123)
3746 {
3747 sprintf((char *)gettail(IObuff), "%d", i);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003748 if (mch_lstat((char *)IObuff, &st) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003749 break;
3750 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00003751 fd = mch_open((char *)IObuff,
3752 O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003753 if (fd < 0) /* can't write in directory */
3754 backup_copy = TRUE;
3755 else
3756 {
3757# ifdef UNIX
Bram Moolenaara5792f52005-11-23 21:25:05 +00003758# ifdef HAVE_FCHOWN
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00003759 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003760# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003761 if (mch_stat((char *)IObuff, &st) < 0
3762 || st.st_uid != st_old.st_uid
3763 || st.st_gid != st_old.st_gid
Bram Moolenaar78a15312009-05-15 19:33:18 +00003764 || (long)st.st_mode != perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003765 backup_copy = TRUE;
3766# endif
Bram Moolenaar98358622005-11-28 22:58:23 +00003767 /* Close the file before removing it, on MS-Windows we
3768 * can't delete an open file. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003769 close(fd);
Bram Moolenaar98358622005-11-28 22:58:23 +00003770 mch_remove(IObuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003771 }
3772 }
3773 }
3774
3775# ifdef UNIX
3776 /*
3777 * Break symlinks and/or hardlinks if we've been asked to.
3778 */
3779 if ((bkc_flags & BKC_BREAKSYMLINK) || (bkc_flags & BKC_BREAKHARDLINK))
3780 {
3781 int lstat_res;
3782
3783 lstat_res = mch_lstat((char *)fname, &st);
3784
3785 /* Symlinks. */
3786 if ((bkc_flags & BKC_BREAKSYMLINK)
3787 && lstat_res == 0
3788 && st.st_ino != st_old.st_ino)
3789 backup_copy = FALSE;
3790
3791 /* Hardlinks. */
3792 if ((bkc_flags & BKC_BREAKHARDLINK)
3793 && st_old.st_nlink > 1
3794 && (lstat_res != 0 || st.st_ino == st_old.st_ino))
3795 backup_copy = FALSE;
3796 }
3797#endif
3798
3799#endif
3800
3801 /* make sure we have a valid backup extension to use */
3802 if (*p_bex == NUL)
3803 {
3804#ifdef RISCOS
3805 backup_ext = (char_u *)"/bak";
3806#else
3807 backup_ext = (char_u *)".bak";
3808#endif
3809 }
3810 else
3811 backup_ext = p_bex;
3812
3813 if (backup_copy
3814 && (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) >= 0)
3815 {
3816 int bfd;
3817 char_u *copybuf, *wp;
3818 int some_error = FALSE;
3819 struct stat st_new;
3820 char_u *dirp;
3821 char_u *rootname;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003822#if defined(UNIX) && !defined(SHORT_FNAME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003823 int did_set_shortname;
3824#endif
3825
3826 copybuf = alloc(BUFSIZE + 1);
3827 if (copybuf == NULL)
3828 {
3829 some_error = TRUE; /* out of memory */
3830 goto nobackup;
3831 }
3832
3833 /*
3834 * Try to make the backup in each directory in the 'bdir' option.
3835 *
3836 * Unix semantics has it, that we may have a writable file,
3837 * that cannot be recreated with a simple open(..., O_CREAT, ) e.g:
3838 * - the directory is not writable,
3839 * - the file may be a symbolic link,
3840 * - the file may belong to another user/group, etc.
3841 *
3842 * For these reasons, the existing writable file must be truncated
3843 * and reused. Creation of a backup COPY will be attempted.
3844 */
3845 dirp = p_bdir;
3846 while (*dirp)
3847 {
3848#ifdef UNIX
3849 st_new.st_ino = 0;
3850 st_new.st_dev = 0;
3851 st_new.st_gid = 0;
3852#endif
3853
3854 /*
3855 * Isolate one directory name, using an entry in 'bdir'.
3856 */
3857 (void)copy_option_part(&dirp, copybuf, BUFSIZE, ",");
3858 rootname = get_file_in_dir(fname, copybuf);
3859 if (rootname == NULL)
3860 {
3861 some_error = TRUE; /* out of memory */
3862 goto nobackup;
3863 }
3864
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003865#if defined(UNIX) && !defined(SHORT_FNAME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003866 did_set_shortname = FALSE;
3867#endif
3868
3869 /*
3870 * May try twice if 'shortname' not set.
3871 */
3872 for (;;)
3873 {
3874 /*
3875 * Make backup file name.
3876 */
3877 backup = buf_modname(
3878#ifdef SHORT_FNAME
3879 TRUE,
3880#else
3881 (buf->b_p_sn || buf->b_shortname),
3882#endif
3883 rootname, backup_ext, FALSE);
3884 if (backup == NULL)
3885 {
3886 vim_free(rootname);
3887 some_error = TRUE; /* out of memory */
3888 goto nobackup;
3889 }
3890
3891 /*
3892 * Check if backup file already exists.
3893 */
3894 if (mch_stat((char *)backup, &st_new) >= 0)
3895 {
3896#ifdef UNIX
3897 /*
3898 * Check if backup file is same as original file.
3899 * May happen when modname() gave the same file back.
3900 * E.g. silly link, or file name-length reached.
3901 * If we don't check here, we either ruin the file
3902 * when copying or erase it after writing. jw.
3903 */
3904 if (st_new.st_dev == st_old.st_dev
3905 && st_new.st_ino == st_old.st_ino)
3906 {
3907 vim_free(backup);
3908 backup = NULL; /* no backup file to delete */
3909# ifndef SHORT_FNAME
3910 /*
3911 * may try again with 'shortname' set
3912 */
3913 if (!(buf->b_shortname || buf->b_p_sn))
3914 {
3915 buf->b_shortname = TRUE;
3916 did_set_shortname = TRUE;
3917 continue;
3918 }
3919 /* setting shortname didn't help */
3920 if (did_set_shortname)
3921 buf->b_shortname = FALSE;
3922# endif
3923 break;
3924 }
3925#endif
3926
3927 /*
3928 * If we are not going to keep the backup file, don't
3929 * delete an existing one, try to use another name.
3930 * Change one character, just before the extension.
3931 */
3932 if (!p_bk)
3933 {
3934 wp = backup + STRLEN(backup) - 1
3935 - STRLEN(backup_ext);
3936 if (wp < backup) /* empty file name ??? */
3937 wp = backup;
3938 *wp = 'z';
3939 while (*wp > 'a'
3940 && mch_stat((char *)backup, &st_new) >= 0)
3941 --*wp;
3942 /* They all exist??? Must be something wrong. */
3943 if (*wp == 'a')
3944 {
3945 vim_free(backup);
3946 backup = NULL;
3947 }
3948 }
3949 }
3950 break;
3951 }
3952 vim_free(rootname);
3953
3954 /*
3955 * Try to create the backup file
3956 */
3957 if (backup != NULL)
3958 {
3959 /* remove old backup, if present */
3960 mch_remove(backup);
3961 /* Open with O_EXCL to avoid the file being created while
3962 * we were sleeping (symlink hacker attack?) */
3963 bfd = mch_open((char *)backup,
Bram Moolenaara5792f52005-11-23 21:25:05 +00003964 O_WRONLY|O_CREAT|O_EXTRA|O_EXCL|O_NOFOLLOW,
3965 perm & 0777);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003966 if (bfd < 0)
3967 {
3968 vim_free(backup);
3969 backup = NULL;
3970 }
3971 else
3972 {
3973 /* set file protection same as original file, but
3974 * strip s-bit */
3975 (void)mch_setperm(backup, perm & 0777);
3976
3977#ifdef UNIX
3978 /*
3979 * Try to set the group of the backup same as the
3980 * original file. If this fails, set the protection
3981 * bits for the group same as the protection bits for
3982 * others.
3983 */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003984 if (st_new.st_gid != st_old.st_gid
Bram Moolenaar071d4272004-06-13 20:20:40 +00003985# ifdef HAVE_FCHOWN /* sequent-ptx lacks fchown() */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003986 && fchown(bfd, (uid_t)-1, st_old.st_gid) != 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00003987# endif
3988 )
3989 mch_setperm(backup,
3990 (perm & 0707) | ((perm & 07) << 3));
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00003991# ifdef HAVE_SELINUX
3992 mch_copy_sec(fname, backup);
3993# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003994#endif
3995
3996 /*
3997 * copy the file.
3998 */
3999 write_info.bw_fd = bfd;
4000 write_info.bw_buf = copybuf;
4001#ifdef HAS_BW_FLAGS
4002 write_info.bw_flags = FIO_NOCONVERT;
4003#endif
4004 while ((write_info.bw_len = vim_read(fd, copybuf,
4005 BUFSIZE)) > 0)
4006 {
4007 if (buf_write_bytes(&write_info) == FAIL)
4008 {
4009 errmsg = (char_u *)_("E506: Can't write to backup file (add ! to override)");
4010 break;
4011 }
4012 ui_breakcheck();
4013 if (got_int)
4014 {
4015 errmsg = (char_u *)_(e_interr);
4016 break;
4017 }
4018 }
4019
4020 if (close(bfd) < 0 && errmsg == NULL)
4021 errmsg = (char_u *)_("E507: Close error for backup file (add ! to override)");
4022 if (write_info.bw_len < 0)
4023 errmsg = (char_u *)_("E508: Can't read file for backup (add ! to override)");
4024#ifdef UNIX
4025 set_file_time(backup, st_old.st_atime, st_old.st_mtime);
4026#endif
4027#ifdef HAVE_ACL
4028 mch_set_acl(backup, acl);
4029#endif
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004030#ifdef HAVE_SELINUX
4031 mch_copy_sec(fname, backup);
4032#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004033 break;
4034 }
4035 }
4036 }
4037 nobackup:
4038 close(fd); /* ignore errors for closing read file */
4039 vim_free(copybuf);
4040
4041 if (backup == NULL && errmsg == NULL)
4042 errmsg = (char_u *)_("E509: Cannot create backup file (add ! to override)");
4043 /* ignore errors when forceit is TRUE */
4044 if ((some_error || errmsg != NULL) && !forceit)
4045 {
4046 retval = FAIL;
4047 goto fail;
4048 }
4049 errmsg = NULL;
4050 }
4051 else
4052 {
4053 char_u *dirp;
4054 char_u *p;
4055 char_u *rootname;
4056
4057 /*
4058 * Make a backup by renaming the original file.
4059 */
4060 /*
4061 * If 'cpoptions' includes the "W" flag, we don't want to
4062 * overwrite a read-only file. But rename may be possible
4063 * anyway, thus we need an extra check here.
4064 */
4065 if (file_readonly && vim_strchr(p_cpo, CPO_FWRITE) != NULL)
4066 {
4067 errnum = (char_u *)"E504: ";
4068 errmsg = (char_u *)_(err_readonly);
4069 goto fail;
4070 }
4071
4072 /*
4073 *
4074 * Form the backup file name - change path/fo.o.h to
4075 * path/fo.o.h.bak Try all directories in 'backupdir', first one
4076 * that works is used.
4077 */
4078 dirp = p_bdir;
4079 while (*dirp)
4080 {
4081 /*
4082 * Isolate one directory name and make the backup file name.
4083 */
4084 (void)copy_option_part(&dirp, IObuff, IOSIZE, ",");
4085 rootname = get_file_in_dir(fname, IObuff);
4086 if (rootname == NULL)
4087 backup = NULL;
4088 else
4089 {
4090 backup = buf_modname(
4091#ifdef SHORT_FNAME
4092 TRUE,
4093#else
4094 (buf->b_p_sn || buf->b_shortname),
4095#endif
4096 rootname, backup_ext, FALSE);
4097 vim_free(rootname);
4098 }
4099
4100 if (backup != NULL)
4101 {
4102 /*
4103 * If we are not going to keep the backup file, don't
4104 * delete an existing one, try to use another name.
4105 * Change one character, just before the extension.
4106 */
4107 if (!p_bk && mch_getperm(backup) >= 0)
4108 {
4109 p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext);
4110 if (p < backup) /* empty file name ??? */
4111 p = backup;
4112 *p = 'z';
4113 while (*p > 'a' && mch_getperm(backup) >= 0)
4114 --*p;
4115 /* They all exist??? Must be something wrong! */
4116 if (*p == 'a')
4117 {
4118 vim_free(backup);
4119 backup = NULL;
4120 }
4121 }
4122 }
4123 if (backup != NULL)
4124 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004125 /*
Bram Moolenaarbfd8fc02005-09-20 23:22:24 +00004126 * Delete any existing backup and move the current version
4127 * to the backup. For safety, we don't remove the backup
4128 * until the write has finished successfully. And if the
4129 * 'backup' option is set, leave it around.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004130 */
4131 /*
4132 * If the renaming of the original file to the backup file
4133 * works, quit here.
4134 */
4135 if (vim_rename(fname, backup) == 0)
4136 break;
4137
4138 vim_free(backup); /* don't do the rename below */
4139 backup = NULL;
4140 }
4141 }
4142 if (backup == NULL && !forceit)
4143 {
4144 errmsg = (char_u *)_("E510: Can't make backup file (add ! to override)");
4145 goto fail;
4146 }
4147 }
4148 }
4149
4150#if defined(UNIX) && !defined(ARCHIE)
4151 /* When using ":w!" and the file was read-only: make it writable */
4152 if (forceit && perm >= 0 && !(perm & 0200) && st_old.st_uid == getuid()
4153 && vim_strchr(p_cpo, CPO_FWRITE) == NULL)
4154 {
4155 perm |= 0200;
4156 (void)mch_setperm(fname, perm);
4157 made_writable = TRUE;
4158 }
4159#endif
4160
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004161 /* When using ":w!" and writing to the current file, 'readonly' makes no
Bram Moolenaar4399ef42005-02-12 14:29:27 +00004162 * sense, reset it, unless 'Z' appears in 'cpoptions'. */
4163 if (forceit && overwriting && vim_strchr(p_cpo, CPO_KEEPRO) == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004164 {
4165 buf->b_p_ro = FALSE;
4166#ifdef FEAT_TITLE
4167 need_maketitle = TRUE; /* set window title later */
4168#endif
4169#ifdef FEAT_WINDOWS
4170 status_redraw_all(); /* redraw status lines later */
4171#endif
4172 }
4173
4174 if (end > buf->b_ml.ml_line_count)
4175 end = buf->b_ml.ml_line_count;
4176 if (buf->b_ml.ml_flags & ML_EMPTY)
4177 start = end + 1;
4178
4179 /*
4180 * If the original file is being overwritten, there is a small chance that
4181 * we crash in the middle of writing. Therefore the file is preserved now.
4182 * This makes all block numbers positive so that recovery does not need
4183 * the original file.
4184 * Don't do this if there is a backup file and we are exiting.
4185 */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004186 if (reset_changed && !newfile && overwriting
Bram Moolenaar071d4272004-06-13 20:20:40 +00004187 && !(exiting && backup != NULL))
4188 {
4189 ml_preserve(buf, FALSE);
4190 if (got_int)
4191 {
4192 errmsg = (char_u *)_(e_interr);
4193 goto restore_backup;
4194 }
4195 }
4196
4197#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
4198 /*
4199 * Before risking to lose the original file verify if there's
4200 * a resource fork to preserve, and if cannot be done warn
4201 * the users. This happens when overwriting without backups.
4202 */
4203 if (backup == NULL && overwriting && !append)
4204 if (mch_has_resource_fork(fname))
4205 {
4206 errmsg = (char_u *)_("E460: The resource fork would be lost (add ! to override)");
4207 goto restore_backup;
4208 }
4209#endif
4210
4211#ifdef VMS
4212 vms_remove_version(fname); /* remove version */
4213#endif
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00004214 /* Default: write the file directly. May write to a temp file for
Bram Moolenaar071d4272004-06-13 20:20:40 +00004215 * multi-byte conversion. */
4216 wfname = fname;
4217
4218#ifdef FEAT_MBYTE
4219 /* Check for forced 'fileencoding' from "++opt=val" argument. */
4220 if (eap != NULL && eap->force_enc != 0)
4221 {
4222 fenc = eap->cmd + eap->force_enc;
4223 fenc = enc_canonize(fenc);
4224 fenc_tofree = fenc;
4225 }
4226 else
4227 fenc = buf->b_p_fenc;
4228
4229 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004230 * Check if the file needs to be converted.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004231 */
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004232 converted = need_conversion(fenc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004233
4234 /*
4235 * Check if UTF-8 to UCS-2/4 or Latin1 conversion needs to be done. Or
4236 * Latin1 to Unicode conversion. This is handled in buf_write_bytes().
4237 * Prepare the flags for it and allocate bw_conv_buf when needed.
4238 */
4239 if (converted && (enc_utf8 || STRCMP(p_enc, "latin1") == 0))
4240 {
4241 wb_flags = get_fio_flags(fenc);
4242 if (wb_flags & (FIO_UCS2 | FIO_UCS4 | FIO_UTF16 | FIO_UTF8))
4243 {
4244 /* Need to allocate a buffer to translate into. */
4245 if (wb_flags & (FIO_UCS2 | FIO_UTF16 | FIO_UTF8))
4246 write_info.bw_conv_buflen = bufsize * 2;
4247 else /* FIO_UCS4 */
4248 write_info.bw_conv_buflen = bufsize * 4;
4249 write_info.bw_conv_buf
4250 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4251 if (write_info.bw_conv_buf == NULL)
4252 end = 0;
4253 }
4254 }
4255
4256# ifdef WIN3264
4257 if (converted && wb_flags == 0 && (wb_flags = get_win_fio_flags(fenc)) != 0)
4258 {
4259 /* Convert UTF-8 -> UCS-2 and UCS-2 -> DBCS. Worst-case * 4: */
4260 write_info.bw_conv_buflen = bufsize * 4;
4261 write_info.bw_conv_buf
4262 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4263 if (write_info.bw_conv_buf == NULL)
4264 end = 0;
4265 }
4266# endif
4267
4268# ifdef MACOS_X
4269 if (converted && wb_flags == 0 && (wb_flags = get_mac_fio_flags(fenc)) != 0)
4270 {
4271 write_info.bw_conv_buflen = bufsize * 3;
4272 write_info.bw_conv_buf
4273 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4274 if (write_info.bw_conv_buf == NULL)
4275 end = 0;
4276 }
4277# endif
4278
4279# if defined(FEAT_EVAL) || defined(USE_ICONV)
4280 if (converted && wb_flags == 0)
4281 {
4282# ifdef USE_ICONV
4283 /*
4284 * Use iconv() conversion when conversion is needed and it's not done
4285 * internally.
4286 */
4287 write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc,
4288 enc_utf8 ? (char_u *)"utf-8" : p_enc);
4289 if (write_info.bw_iconv_fd != (iconv_t)-1)
4290 {
4291 /* We're going to use iconv(), allocate a buffer to convert in. */
4292 write_info.bw_conv_buflen = bufsize * ICONV_MULT;
4293 write_info.bw_conv_buf
4294 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4295 if (write_info.bw_conv_buf == NULL)
4296 end = 0;
4297 write_info.bw_first = TRUE;
4298 }
4299# ifdef FEAT_EVAL
4300 else
4301# endif
4302# endif
4303
4304# ifdef FEAT_EVAL
4305 /*
4306 * When the file needs to be converted with 'charconvert' after
4307 * writing, write to a temp file instead and let the conversion
4308 * overwrite the original file.
4309 */
4310 if (*p_ccv != NUL)
4311 {
4312 wfname = vim_tempname('w');
4313 if (wfname == NULL) /* Can't write without a tempfile! */
4314 {
4315 errmsg = (char_u *)_("E214: Can't find temp file for writing");
4316 goto restore_backup;
4317 }
4318 }
4319# endif
4320 }
4321# endif
4322 if (converted && wb_flags == 0
4323# ifdef USE_ICONV
4324 && write_info.bw_iconv_fd == (iconv_t)-1
4325# endif
4326# ifdef FEAT_EVAL
4327 && wfname == fname
4328# endif
4329 )
4330 {
4331 if (!forceit)
4332 {
4333 errmsg = (char_u *)_("E213: Cannot convert (add ! to write without conversion)");
4334 goto restore_backup;
4335 }
4336 notconverted = TRUE;
4337 }
4338#endif
4339
4340 /*
4341 * Open the file "wfname" for writing.
4342 * We may try to open the file twice: If we can't write to the
4343 * file and forceit is TRUE we delete the existing file and try to create
4344 * a new one. If this still fails we may have lost the original file!
4345 * (this may happen when the user reached his quotum for number of files).
4346 * Appending will fail if the file does not exist and forceit is FALSE.
4347 */
4348 while ((fd = mch_open((char *)wfname, O_WRONLY | O_EXTRA | (append
4349 ? (forceit ? (O_APPEND | O_CREAT) : O_APPEND)
4350 : (O_CREAT | O_TRUNC))
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00004351 , perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004352 {
4353 /*
4354 * A forced write will try to create a new file if the old one is
4355 * still readonly. This may also happen when the directory is
4356 * read-only. In that case the mch_remove() will fail.
4357 */
4358 if (errmsg == NULL)
4359 {
4360#ifdef UNIX
4361 struct stat st;
4362
4363 /* Don't delete the file when it's a hard or symbolic link. */
4364 if ((!newfile && st_old.st_nlink > 1)
4365 || (mch_lstat((char *)fname, &st) == 0
4366 && (st.st_dev != st_old.st_dev
4367 || st.st_ino != st_old.st_ino)))
4368 errmsg = (char_u *)_("E166: Can't open linked file for writing");
4369 else
4370#endif
4371 {
4372 errmsg = (char_u *)_("E212: Can't open file for writing");
4373 if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL
4374 && perm >= 0)
4375 {
4376#ifdef UNIX
4377 /* we write to the file, thus it should be marked
4378 writable after all */
4379 if (!(perm & 0200))
4380 made_writable = TRUE;
4381 perm |= 0200;
4382 if (st_old.st_uid != getuid() || st_old.st_gid != getgid())
4383 perm &= 0777;
4384#endif
4385 if (!append) /* don't remove when appending */
4386 mch_remove(wfname);
4387 continue;
4388 }
4389 }
4390 }
4391
4392restore_backup:
4393 {
4394 struct stat st;
4395
4396 /*
4397 * If we failed to open the file, we don't need a backup. Throw it
4398 * away. If we moved or removed the original file try to put the
4399 * backup in its place.
4400 */
4401 if (backup != NULL && wfname == fname)
4402 {
4403 if (backup_copy)
4404 {
4405 /*
4406 * There is a small chance that we removed the original,
4407 * try to move the copy in its place.
4408 * This may not work if the vim_rename() fails.
4409 * In that case we leave the copy around.
4410 */
4411 /* If file does not exist, put the copy in its place */
4412 if (mch_stat((char *)fname, &st) < 0)
4413 vim_rename(backup, fname);
4414 /* if original file does exist throw away the copy */
4415 if (mch_stat((char *)fname, &st) >= 0)
4416 mch_remove(backup);
4417 }
4418 else
4419 {
4420 /* try to put the original file back */
4421 vim_rename(backup, fname);
4422 }
4423 }
4424
4425 /* if original file no longer exists give an extra warning */
4426 if (!newfile && mch_stat((char *)fname, &st) < 0)
4427 end = 0;
4428 }
4429
4430#ifdef FEAT_MBYTE
4431 if (wfname != fname)
4432 vim_free(wfname);
4433#endif
4434 goto fail;
4435 }
4436 errmsg = NULL;
4437
4438#if defined(MACOS_CLASSIC) || defined(WIN3264)
4439 /* TODO: Is it need for MACOS_X? (Dany) */
4440 /*
4441 * On macintosh copy the original files attributes (i.e. the backup)
Bram Moolenaar7263a772007-05-10 17:35:54 +00004442 * This is done in order to preserve the resource fork and the
4443 * Finder attribute (label, comments, custom icons, file creator)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004444 */
4445 if (backup != NULL && overwriting && !append)
4446 {
4447 if (backup_copy)
4448 (void)mch_copy_file_attribute(wfname, backup);
4449 else
4450 (void)mch_copy_file_attribute(backup, wfname);
4451 }
4452
4453 if (!overwriting && !append)
4454 {
4455 if (buf->b_ffname != NULL)
4456 (void)mch_copy_file_attribute(buf->b_ffname, wfname);
Bram Moolenaar7263a772007-05-10 17:35:54 +00004457 /* Should copy resource fork */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004458 }
4459#endif
4460
4461 write_info.bw_fd = fd;
4462
4463#ifdef FEAT_CRYPT
4464 if (*buf->b_p_key && !filtering)
4465 {
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02004466 char_u *header;
4467 int header_len;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004468
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02004469 header = prepare_crypt_write(buf, &header_len);
4470 if (header == NULL)
4471 end = 0;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004472 else
4473 {
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02004474 /* Write magic number, so that Vim knows that this file is
4475 * encrypted when reading it again. This also undergoes utf-8 to
4476 * ucs-2/4 conversion when needed. */
4477 write_info.bw_buf = header;
4478 write_info.bw_len = header_len;
4479 write_info.bw_flags = FIO_NOCONVERT;
4480 if (buf_write_bytes(&write_info) == FAIL)
4481 end = 0;
4482 wb_flags |= FIO_ENCRYPTED;
4483 vim_free(header);
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004484 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004485 }
4486#endif
4487
4488 write_info.bw_buf = buffer;
4489 nchars = 0;
4490
4491 /* use "++bin", "++nobin" or 'binary' */
4492 if (eap != NULL && eap->force_bin != 0)
4493 write_bin = (eap->force_bin == FORCE_BIN);
4494 else
4495 write_bin = buf->b_p_bin;
4496
4497#ifdef FEAT_MBYTE
4498 /*
4499 * The BOM is written just after the encryption magic number.
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004500 * Skip it when appending and the file already existed, the BOM only makes
4501 * sense at the start of the file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004502 */
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004503 if (buf->b_p_bomb && !write_bin && (!append || perm < 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004504 {
4505 write_info.bw_len = make_bom(buffer, fenc);
4506 if (write_info.bw_len > 0)
4507 {
4508 /* don't convert, do encryption */
4509 write_info.bw_flags = FIO_NOCONVERT | wb_flags;
4510 if (buf_write_bytes(&write_info) == FAIL)
4511 end = 0;
4512 else
4513 nchars += write_info.bw_len;
4514 }
4515 }
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004516 write_info.bw_start_lnum = start;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004517#endif
4518
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004519#ifdef FEAT_PERSISTENT_UNDO
4520 write_undo_file = (buf->b_p_udf && overwriting && !append
4521 && !filtering && reset_changed);
4522 if (write_undo_file)
4523 /* Prepare for computing the hash value of the text. */
4524 sha256_start(&sha_ctx);
4525#endif
4526
Bram Moolenaar071d4272004-06-13 20:20:40 +00004527 write_info.bw_len = bufsize;
4528#ifdef HAS_BW_FLAGS
4529 write_info.bw_flags = wb_flags;
4530#endif
4531 fileformat = get_fileformat_force(buf, eap);
4532 s = buffer;
4533 len = 0;
4534 for (lnum = start; lnum <= end; ++lnum)
4535 {
4536 /*
4537 * The next while loop is done once for each character written.
4538 * Keep it fast!
4539 */
4540 ptr = ml_get_buf(buf, lnum, FALSE) - 1;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004541#ifdef FEAT_PERSISTENT_UNDO
4542 if (write_undo_file)
Bram Moolenaar442b4222010-05-24 21:34:22 +02004543 sha256_update(&sha_ctx, ptr + 1, (UINT32_T)(STRLEN(ptr + 1) + 1));
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004544#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004545 while ((c = *++ptr) != NUL)
4546 {
4547 if (c == NL)
4548 *s = NUL; /* replace newlines with NULs */
4549 else if (c == CAR && fileformat == EOL_MAC)
4550 *s = NL; /* Mac: replace CRs with NLs */
4551 else
4552 *s = c;
4553 ++s;
4554 if (++len != bufsize)
4555 continue;
4556 if (buf_write_bytes(&write_info) == FAIL)
4557 {
4558 end = 0; /* write error: break loop */
4559 break;
4560 }
4561 nchars += bufsize;
4562 s = buffer;
4563 len = 0;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004564#ifdef FEAT_MBYTE
4565 write_info.bw_start_lnum = lnum;
4566#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004567 }
4568 /* write failed or last line has no EOL: stop here */
4569 if (end == 0
4570 || (lnum == end
4571 && write_bin
4572 && (lnum == write_no_eol_lnum
4573 || (lnum == buf->b_ml.ml_line_count && !buf->b_p_eol))))
4574 {
4575 ++lnum; /* written the line, count it */
4576 no_eol = TRUE;
4577 break;
4578 }
4579 if (fileformat == EOL_UNIX)
4580 *s++ = NL;
4581 else
4582 {
4583 *s++ = CAR; /* EOL_MAC or EOL_DOS: write CR */
4584 if (fileformat == EOL_DOS) /* write CR-NL */
4585 {
4586 if (++len == bufsize)
4587 {
4588 if (buf_write_bytes(&write_info) == FAIL)
4589 {
4590 end = 0; /* write error: break loop */
4591 break;
4592 }
4593 nchars += bufsize;
4594 s = buffer;
4595 len = 0;
4596 }
4597 *s++ = NL;
4598 }
4599 }
4600 if (++len == bufsize && end)
4601 {
4602 if (buf_write_bytes(&write_info) == FAIL)
4603 {
4604 end = 0; /* write error: break loop */
4605 break;
4606 }
4607 nchars += bufsize;
4608 s = buffer;
4609 len = 0;
4610
4611 ui_breakcheck();
4612 if (got_int)
4613 {
4614 end = 0; /* Interrupted, break loop */
4615 break;
4616 }
4617 }
4618#ifdef VMS
4619 /*
4620 * On VMS there is a problem: newlines get added when writing blocks
4621 * at a time. Fix it by writing a line at a time.
4622 * This is much slower!
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004623 * Explanation: VAX/DECC RTL insists that records in some RMS
4624 * structures end with a newline (carriage return) character, and if
4625 * they don't it adds one.
4626 * With other RMS structures it works perfect without this fix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004627 */
Bram Moolenaarb52e2602007-10-29 21:38:54 +00004628 if (buf->b_fab_rfm == FAB$C_VFC
4629 || ((buf->b_fab_rat & (FAB$M_FTN | FAB$M_CR)) != 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004630 {
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004631 int b2write;
4632
4633 buf->b_fab_mrs = (buf->b_fab_mrs == 0
4634 ? MIN(4096, bufsize)
4635 : MIN(buf->b_fab_mrs, bufsize));
4636
4637 b2write = len;
4638 while (b2write > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004639 {
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004640 write_info.bw_len = MIN(b2write, buf->b_fab_mrs);
4641 if (buf_write_bytes(&write_info) == FAIL)
4642 {
4643 end = 0;
4644 break;
4645 }
4646 b2write -= MIN(b2write, buf->b_fab_mrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004647 }
4648 write_info.bw_len = bufsize;
4649 nchars += len;
4650 s = buffer;
4651 len = 0;
4652 }
4653#endif
4654 }
4655 if (len > 0 && end > 0)
4656 {
4657 write_info.bw_len = len;
4658 if (buf_write_bytes(&write_info) == FAIL)
4659 end = 0; /* write error */
4660 nchars += len;
4661 }
4662
4663#if defined(UNIX) && defined(HAVE_FSYNC)
4664 /* On many journalling file systems there is a bug that causes both the
4665 * original and the backup file to be lost when halting the system right
4666 * after writing the file. That's because only the meta-data is
4667 * journalled. Syncing the file slows down the system, but assures it has
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004668 * been written to disk and we don't lose it.
4669 * For a device do try the fsync() but don't complain if it does not work
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00004670 * (could be a pipe).
4671 * If the 'fsync' option is FALSE, don't fsync(). Useful for laptops. */
4672 if (p_fs && fsync(fd) != 0 && !device)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004673 {
4674 errmsg = (char_u *)_("E667: Fsync failed");
4675 end = 0;
4676 }
4677#endif
4678
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004679#ifdef HAVE_SELINUX
4680 /* Probably need to set the security context. */
4681 if (!backup_copy)
4682 mch_copy_sec(backup, wfname);
4683#endif
4684
Bram Moolenaara5792f52005-11-23 21:25:05 +00004685#ifdef UNIX
4686 /* When creating a new file, set its owner/group to that of the original
4687 * file. Get the new device and inode number. */
4688 if (backup != NULL && !backup_copy)
4689 {
4690# ifdef HAVE_FCHOWN
4691 struct stat st;
4692
4693 /* don't change the owner when it's already OK, some systems remove
4694 * permission or ACL stuff */
4695 if (mch_stat((char *)wfname, &st) < 0
4696 || st.st_uid != st_old.st_uid
4697 || st.st_gid != st_old.st_gid)
4698 {
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004699 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004700 if (perm >= 0) /* set permission again, may have changed */
4701 (void)mch_setperm(wfname, perm);
4702 }
4703# endif
4704 buf_setino(buf);
4705 }
Bram Moolenaarf1726cc2009-05-13 18:48:16 +00004706 else if (!buf->b_dev_valid)
Bram Moolenaar8fa04452005-12-23 22:13:51 +00004707 /* Set the inode when creating a new file. */
4708 buf_setino(buf);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004709#endif
4710
Bram Moolenaar071d4272004-06-13 20:20:40 +00004711 if (close(fd) != 0)
4712 {
4713 errmsg = (char_u *)_("E512: Close failed");
4714 end = 0;
4715 }
4716
4717#ifdef UNIX
4718 if (made_writable)
4719 perm &= ~0200; /* reset 'w' bit for security reasons */
4720#endif
4721 if (perm >= 0) /* set perm. of new file same as old file */
4722 (void)mch_setperm(wfname, perm);
4723#ifdef RISCOS
4724 if (!append && !filtering)
4725 /* Set the filetype after writing the file. */
4726 mch_set_filetype(wfname, buf->b_p_oft);
4727#endif
4728#ifdef HAVE_ACL
4729 /* Probably need to set the ACL before changing the user (can't set the
4730 * ACL on a file the user doesn't own). */
4731 if (!backup_copy)
4732 mch_set_acl(wfname, acl);
4733#endif
4734
Bram Moolenaar071d4272004-06-13 20:20:40 +00004735
4736#if defined(FEAT_MBYTE) && defined(FEAT_EVAL)
4737 if (wfname != fname)
4738 {
4739 /*
4740 * The file was written to a temp file, now it needs to be converted
4741 * with 'charconvert' to (overwrite) the output file.
4742 */
4743 if (end != 0)
4744 {
4745 if (eval_charconvert(enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc,
4746 wfname, fname) == FAIL)
4747 {
4748 write_info.bw_conv_error = TRUE;
4749 end = 0;
4750 }
4751 }
4752 mch_remove(wfname);
4753 vim_free(wfname);
4754 }
4755#endif
4756
4757 if (end == 0)
4758 {
4759 if (errmsg == NULL)
4760 {
4761#ifdef FEAT_MBYTE
4762 if (write_info.bw_conv_error)
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004763 {
4764 if (write_info.bw_conv_error_lnum == 0)
4765 errmsg = (char_u *)_("E513: write error, conversion failed (make 'fenc' empty to override)");
4766 else
4767 {
4768 errmsg_allocated = TRUE;
4769 errmsg = alloc(300);
4770 vim_snprintf((char *)errmsg, 300, _("E513: write error, conversion failed in line %ld (make 'fenc' empty to override)"),
4771 (long)write_info.bw_conv_error_lnum);
4772 }
4773 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004774 else
4775#endif
4776 if (got_int)
4777 errmsg = (char_u *)_(e_interr);
4778 else
4779 errmsg = (char_u *)_("E514: write error (file system full?)");
4780 }
4781
4782 /*
4783 * If we have a backup file, try to put it in place of the new file,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004784 * because the new file is probably corrupt. This avoids losing the
Bram Moolenaar071d4272004-06-13 20:20:40 +00004785 * original file when trying to make a backup when writing the file a
4786 * second time.
4787 * When "backup_copy" is set we need to copy the backup over the new
4788 * file. Otherwise rename the backup file.
4789 * If this is OK, don't give the extra warning message.
4790 */
4791 if (backup != NULL)
4792 {
4793 if (backup_copy)
4794 {
4795 /* This may take a while, if we were interrupted let the user
4796 * know we got the message. */
4797 if (got_int)
4798 {
4799 MSG(_(e_interr));
4800 out_flush();
4801 }
4802 if ((fd = mch_open((char *)backup, O_RDONLY | O_EXTRA, 0)) >= 0)
4803 {
4804 if ((write_info.bw_fd = mch_open((char *)fname,
Bram Moolenaar9be038d2005-03-08 22:34:32 +00004805 O_WRONLY | O_CREAT | O_TRUNC | O_EXTRA,
4806 perm & 0777)) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004807 {
4808 /* copy the file. */
4809 write_info.bw_buf = smallbuf;
4810#ifdef HAS_BW_FLAGS
4811 write_info.bw_flags = FIO_NOCONVERT;
4812#endif
4813 while ((write_info.bw_len = vim_read(fd, smallbuf,
4814 SMBUFSIZE)) > 0)
4815 if (buf_write_bytes(&write_info) == FAIL)
4816 break;
4817
4818 if (close(write_info.bw_fd) >= 0
4819 && write_info.bw_len == 0)
4820 end = 1; /* success */
4821 }
4822 close(fd); /* ignore errors for closing read file */
4823 }
4824 }
4825 else
4826 {
4827 if (vim_rename(backup, fname) == 0)
4828 end = 1;
4829 }
4830 }
4831 goto fail;
4832 }
4833
4834 lnum -= start; /* compute number of written lines */
4835 --no_wait_return; /* may wait for return now */
4836
4837#if !(defined(UNIX) || defined(VMS))
4838 fname = sfname; /* use shortname now, for the messages */
4839#endif
4840 if (!filtering)
4841 {
4842 msg_add_fname(buf, fname); /* put fname in IObuff with quotes */
4843 c = FALSE;
4844#ifdef FEAT_MBYTE
4845 if (write_info.bw_conv_error)
4846 {
4847 STRCAT(IObuff, _(" CONVERSION ERROR"));
4848 c = TRUE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004849 if (write_info.bw_conv_error_lnum != 0)
4850 {
Bram Moolenaarc0662022009-09-11 13:04:24 +00004851 size_t l = STRLEN(IObuff);
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004852 vim_snprintf((char *)IObuff + l, IOSIZE - l, _(" in line %ld;"),
4853 (long)write_info.bw_conv_error_lnum);
4854 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004855 }
4856 else if (notconverted)
4857 {
4858 STRCAT(IObuff, _("[NOT converted]"));
4859 c = TRUE;
4860 }
4861 else if (converted)
4862 {
4863 STRCAT(IObuff, _("[converted]"));
4864 c = TRUE;
4865 }
4866#endif
4867 if (device)
4868 {
4869 STRCAT(IObuff, _("[Device]"));
4870 c = TRUE;
4871 }
4872 else if (newfile)
4873 {
4874 STRCAT(IObuff, shortmess(SHM_NEW) ? _("[New]") : _("[New File]"));
4875 c = TRUE;
4876 }
4877 if (no_eol)
4878 {
4879 msg_add_eol();
4880 c = TRUE;
4881 }
4882 /* may add [unix/dos/mac] */
4883 if (msg_add_fileformat(fileformat))
4884 c = TRUE;
4885#ifdef FEAT_CRYPT
4886 if (wb_flags & FIO_ENCRYPTED)
4887 {
4888 STRCAT(IObuff, _("[crypted]"));
4889 c = TRUE;
4890 }
4891#endif
4892 msg_add_lines(c, (long)lnum, nchars); /* add line/char count */
4893 if (!shortmess(SHM_WRITE))
4894 {
4895 if (append)
4896 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended"));
4897 else
4898 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written"));
4899 }
4900
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00004901 set_keep_msg(msg_trunc_attr(IObuff, FALSE, 0), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004902 }
4903
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004904 /* When written everything correctly: reset 'modified'. Unless not
4905 * writing to the original file and '+' is not in 'cpoptions'. */
Bram Moolenaar292ad192005-12-11 21:29:51 +00004906 if (reset_changed && whole && !append
Bram Moolenaar071d4272004-06-13 20:20:40 +00004907#ifdef FEAT_MBYTE
4908 && !write_info.bw_conv_error
4909#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004910 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL)
4911 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004912 {
4913 unchanged(buf, TRUE);
4914 u_unchanged(buf);
4915 }
4916
4917 /*
4918 * If written to the current file, update the timestamp of the swap file
4919 * and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
4920 */
4921 if (overwriting)
4922 {
4923 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00004924 if (append)
4925 buf->b_flags &= ~BF_NEW;
4926 else
4927 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004928 }
4929
4930 /*
4931 * If we kept a backup until now, and we are in patch mode, then we make
4932 * the backup file our 'original' file.
4933 */
4934 if (*p_pm && dobackup)
4935 {
4936 char *org = (char *)buf_modname(
4937#ifdef SHORT_FNAME
4938 TRUE,
4939#else
4940 (buf->b_p_sn || buf->b_shortname),
4941#endif
4942 fname, p_pm, FALSE);
4943
4944 if (backup != NULL)
4945 {
4946 struct stat st;
4947
4948 /*
4949 * If the original file does not exist yet
4950 * the current backup file becomes the original file
4951 */
4952 if (org == NULL)
4953 EMSG(_("E205: Patchmode: can't save original file"));
4954 else if (mch_stat(org, &st) < 0)
4955 {
4956 vim_rename(backup, (char_u *)org);
4957 vim_free(backup); /* don't delete the file */
4958 backup = NULL;
4959#ifdef UNIX
4960 set_file_time((char_u *)org, st_old.st_atime, st_old.st_mtime);
4961#endif
4962 }
4963 }
4964 /*
4965 * If there is no backup file, remember that a (new) file was
4966 * created.
4967 */
4968 else
4969 {
4970 int empty_fd;
4971
4972 if (org == NULL
Bram Moolenaara5792f52005-11-23 21:25:05 +00004973 || (empty_fd = mch_open(org,
4974 O_CREAT | O_EXTRA | O_EXCL | O_NOFOLLOW,
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00004975 perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004976 EMSG(_("E206: patchmode: can't touch empty original file"));
4977 else
4978 close(empty_fd);
4979 }
4980 if (org != NULL)
4981 {
4982 mch_setperm((char_u *)org, mch_getperm(fname) & 0777);
4983 vim_free(org);
4984 }
4985 }
4986
4987 /*
4988 * Remove the backup unless 'backup' option is set
4989 */
4990 if (!p_bk && backup != NULL && mch_remove(backup) != 0)
4991 EMSG(_("E207: Can't delete backup file"));
4992
4993#ifdef FEAT_SUN_WORKSHOP
4994 if (usingSunWorkShop)
4995 workshop_file_saved((char *) ffname);
4996#endif
4997
4998 goto nofail;
4999
5000 /*
5001 * Finish up. We get here either after failure or success.
5002 */
5003fail:
5004 --no_wait_return; /* may wait for return now */
5005nofail:
5006
5007 /* Done saving, we accept changed buffer warnings again */
5008 buf->b_saving = FALSE;
5009
5010 vim_free(backup);
5011 if (buffer != smallbuf)
5012 vim_free(buffer);
5013#ifdef FEAT_MBYTE
5014 vim_free(fenc_tofree);
5015 vim_free(write_info.bw_conv_buf);
5016# ifdef USE_ICONV
5017 if (write_info.bw_iconv_fd != (iconv_t)-1)
5018 {
5019 iconv_close(write_info.bw_iconv_fd);
5020 write_info.bw_iconv_fd = (iconv_t)-1;
5021 }
5022# endif
5023#endif
5024#ifdef HAVE_ACL
5025 mch_free_acl(acl);
5026#endif
5027
5028 if (errmsg != NULL)
5029 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005030 int numlen = errnum != NULL ? (int)STRLEN(errnum) : 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005031
5032 attr = hl_attr(HLF_E); /* set highlight for error messages */
5033 msg_add_fname(buf,
5034#ifndef UNIX
5035 sfname
5036#else
5037 fname
5038#endif
5039 ); /* put file name in IObuff with quotes */
5040 if (STRLEN(IObuff) + STRLEN(errmsg) + numlen >= IOSIZE)
5041 IObuff[IOSIZE - STRLEN(errmsg) - numlen - 1] = NUL;
5042 /* If the error message has the form "is ...", put the error number in
5043 * front of the file name. */
5044 if (errnum != NULL)
5045 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00005046 STRMOVE(IObuff + numlen, IObuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005047 mch_memmove(IObuff, errnum, (size_t)numlen);
5048 }
5049 STRCAT(IObuff, errmsg);
5050 emsg(IObuff);
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005051 if (errmsg_allocated)
5052 vim_free(errmsg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005053
5054 retval = FAIL;
5055 if (end == 0)
5056 {
5057 MSG_PUTS_ATTR(_("\nWARNING: Original file may be lost or damaged\n"),
5058 attr | MSG_HIST);
5059 MSG_PUTS_ATTR(_("don't quit the editor until the file is successfully written!"),
5060 attr | MSG_HIST);
5061
5062 /* Update the timestamp to avoid an "overwrite changed file"
5063 * prompt when writing again. */
5064 if (mch_stat((char *)fname, &st_old) >= 0)
5065 {
5066 buf_store_time(buf, &st_old, fname);
5067 buf->b_mtime_read = buf->b_mtime;
5068 }
5069 }
5070 }
5071 msg_scroll = msg_save;
5072
Bram Moolenaar55debbe2010-05-23 23:34:36 +02005073#ifdef FEAT_PERSISTENT_UNDO
5074 /*
5075 * When writing the whole file and 'undofile' is set, also write the undo
5076 * file.
5077 */
5078 if (retval == OK && write_undo_file)
5079 {
5080 char_u hash[UNDO_HASH_SIZE];
5081
5082 sha256_finish(&sha_ctx, hash);
5083 u_write_undo(NULL, FALSE, buf, hash);
5084 }
5085#endif
5086
Bram Moolenaar071d4272004-06-13 20:20:40 +00005087#ifdef FEAT_AUTOCMD
5088#ifdef FEAT_EVAL
5089 if (!should_abort(retval))
5090#else
5091 if (!got_int)
5092#endif
5093 {
5094 aco_save_T aco;
5095
5096 write_no_eol_lnum = 0; /* in case it was set by the previous read */
5097
5098 /*
5099 * Apply POST autocommands.
5100 * Careful: The autocommands may call buf_write() recursively!
5101 */
5102 aucmd_prepbuf(&aco, buf);
5103
5104 if (append)
5105 apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname,
5106 FALSE, curbuf, eap);
5107 else if (filtering)
5108 apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname,
5109 FALSE, curbuf, eap);
5110 else if (reset_changed && whole)
5111 apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname,
5112 FALSE, curbuf, eap);
5113 else
5114 apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname,
5115 FALSE, curbuf, eap);
5116
5117 /* restore curwin/curbuf and a few other things */
5118 aucmd_restbuf(&aco);
5119
5120#ifdef FEAT_EVAL
5121 if (aborting()) /* autocmds may abort script processing */
5122 retval = FALSE;
5123#endif
5124 }
5125#endif
5126
5127 got_int |= prev_got_int;
5128
5129#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
5130 /* Update machine specific information. */
5131 mch_post_buffer_write(buf);
5132#endif
5133 return retval;
5134}
5135
5136/*
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005137 * Set the name of the current buffer. Use when the buffer doesn't have a
5138 * name and a ":r" or ":w" command with a file name is used.
5139 */
5140 static int
5141set_rw_fname(fname, sfname)
5142 char_u *fname;
5143 char_u *sfname;
5144{
5145#ifdef FEAT_AUTOCMD
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005146 buf_T *buf = curbuf;
5147
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005148 /* It's like the unnamed buffer is deleted.... */
5149 if (curbuf->b_p_bl)
5150 apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
5151 apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf);
5152# ifdef FEAT_EVAL
5153 if (aborting()) /* autocmds may abort script processing */
5154 return FAIL;
5155# endif
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005156 if (curbuf != buf)
5157 {
5158 /* We are in another buffer now, don't do the renaming. */
5159 EMSG(_(e_auchangedbuf));
5160 return FAIL;
5161 }
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005162#endif
5163
5164 if (setfname(curbuf, fname, sfname, FALSE) == OK)
5165 curbuf->b_flags |= BF_NOTEDITED;
5166
5167#ifdef FEAT_AUTOCMD
5168 /* ....and a new named one is created */
5169 apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, curbuf);
5170 if (curbuf->b_p_bl)
5171 apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf);
5172# ifdef FEAT_EVAL
5173 if (aborting()) /* autocmds may abort script processing */
5174 return FAIL;
5175# endif
5176
5177 /* Do filetype detection now if 'filetype' is empty. */
5178 if (*curbuf->b_p_ft == NUL)
5179 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005180 if (au_has_group((char_u *)"filetypedetect"))
Bram Moolenaar70836c82006-02-20 21:28:49 +00005181 (void)do_doautocmd((char_u *)"filetypedetect BufRead", FALSE);
Bram Moolenaara3227e22006-03-08 21:32:40 +00005182 do_modelines(0);
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005183 }
5184#endif
5185
5186 return OK;
5187}
5188
5189/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00005190 * Put file name into IObuff with quotes.
5191 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005192 void
Bram Moolenaar071d4272004-06-13 20:20:40 +00005193msg_add_fname(buf, fname)
5194 buf_T *buf;
5195 char_u *fname;
5196{
5197 if (fname == NULL)
5198 fname = (char_u *)"-stdin-";
5199 home_replace(buf, fname, IObuff + 1, IOSIZE - 4, TRUE);
5200 IObuff[0] = '"';
5201 STRCAT(IObuff, "\" ");
5202}
5203
5204/*
5205 * Append message for text mode to IObuff.
5206 * Return TRUE if something appended.
5207 */
5208 static int
5209msg_add_fileformat(eol_type)
5210 int eol_type;
5211{
5212#ifndef USE_CRNL
5213 if (eol_type == EOL_DOS)
5214 {
5215 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[dos]") : _("[dos format]"));
5216 return TRUE;
5217 }
5218#endif
5219#ifndef USE_CR
5220 if (eol_type == EOL_MAC)
5221 {
5222 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[mac]") : _("[mac format]"));
5223 return TRUE;
5224 }
5225#endif
5226#if defined(USE_CRNL) || defined(USE_CR)
5227 if (eol_type == EOL_UNIX)
5228 {
5229 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[unix]") : _("[unix format]"));
5230 return TRUE;
5231 }
5232#endif
5233 return FALSE;
5234}
5235
5236/*
5237 * Append line and character count to IObuff.
5238 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005239 void
Bram Moolenaar071d4272004-06-13 20:20:40 +00005240msg_add_lines(insert_space, lnum, nchars)
5241 int insert_space;
5242 long lnum;
Bram Moolenaar914703b2010-05-31 21:59:46 +02005243 off_t nchars;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005244{
5245 char_u *p;
5246
5247 p = IObuff + STRLEN(IObuff);
5248
5249 if (insert_space)
5250 *p++ = ' ';
5251 if (shortmess(SHM_LINES))
Bram Moolenaar914703b2010-05-31 21:59:46 +02005252 sprintf((char *)p,
5253#ifdef LONG_LONG_OFF_T
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005254 "%ldL, %lldC", lnum, nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005255#else
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005256 /* Explicit typecast avoids warning on Mac OS X 10.6 */
5257 "%ldL, %ldC", lnum, (long)nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005258#endif
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005259 );
Bram Moolenaar071d4272004-06-13 20:20:40 +00005260 else
5261 {
5262 if (lnum == 1)
5263 STRCPY(p, _("1 line, "));
5264 else
5265 sprintf((char *)p, _("%ld lines, "), lnum);
5266 p += STRLEN(p);
5267 if (nchars == 1)
5268 STRCPY(p, _("1 character"));
5269 else
Bram Moolenaar914703b2010-05-31 21:59:46 +02005270 sprintf((char *)p,
5271#ifdef LONG_LONG_OFF_T
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005272 _("%lld characters"), nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005273#else
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005274 /* Explicit typecast avoids warning on Mac OS X 10.6 */
5275 _("%ld characters"), (long)nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005276#endif
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005277 );
Bram Moolenaar071d4272004-06-13 20:20:40 +00005278 }
5279}
5280
5281/*
5282 * Append message for missing line separator to IObuff.
5283 */
5284 static void
5285msg_add_eol()
5286{
5287 STRCAT(IObuff, shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]"));
5288}
5289
5290/*
5291 * Check modification time of file, before writing to it.
5292 * The size isn't checked, because using a tool like "gzip" takes care of
5293 * using the same timestamp but can't set the size.
5294 */
5295 static int
5296check_mtime(buf, st)
5297 buf_T *buf;
5298 struct stat *st;
5299{
5300 if (buf->b_mtime_read != 0
5301 && time_differs((long)st->st_mtime, buf->b_mtime_read))
5302 {
5303 msg_scroll = TRUE; /* don't overwrite messages here */
5304 msg_silent = 0; /* must give this prompt */
5305 /* don't use emsg() here, don't want to flush the buffers */
5306 MSG_ATTR(_("WARNING: The file has been changed since reading it!!!"),
5307 hl_attr(HLF_E));
5308 if (ask_yesno((char_u *)_("Do you really want to write to it"),
5309 TRUE) == 'n')
5310 return FAIL;
5311 msg_scroll = FALSE; /* always overwrite the file message now */
5312 }
5313 return OK;
5314}
5315
5316 static int
5317time_differs(t1, t2)
5318 long t1, t2;
5319{
5320#if defined(__linux__) || defined(MSDOS) || defined(MSWIN)
5321 /* On a FAT filesystem, esp. under Linux, there are only 5 bits to store
5322 * the seconds. Since the roundoff is done when flushing the inode, the
5323 * time may change unexpectedly by one second!!! */
5324 return (t1 - t2 > 1 || t2 - t1 > 1);
5325#else
5326 return (t1 != t2);
5327#endif
5328}
5329
5330/*
5331 * Call write() to write a number of bytes to the file.
5332 * Also handles encryption and 'encoding' conversion.
5333 *
5334 * Return FAIL for failure, OK otherwise.
5335 */
5336 static int
5337buf_write_bytes(ip)
5338 struct bw_info *ip;
5339{
5340 int wlen;
5341 char_u *buf = ip->bw_buf; /* data to write */
5342 int len = ip->bw_len; /* length of data */
5343#ifdef HAS_BW_FLAGS
5344 int flags = ip->bw_flags; /* extra flags */
5345#endif
5346
5347#ifdef FEAT_MBYTE
5348 /*
5349 * Skip conversion when writing the crypt magic number or the BOM.
5350 */
5351 if (!(flags & FIO_NOCONVERT))
5352 {
5353 char_u *p;
5354 unsigned c;
5355 int n;
5356
5357 if (flags & FIO_UTF8)
5358 {
5359 /*
5360 * Convert latin1 in the buffer to UTF-8 in the file.
5361 */
5362 p = ip->bw_conv_buf; /* translate to buffer */
5363 for (wlen = 0; wlen < len; ++wlen)
5364 p += utf_char2bytes(buf[wlen], p);
5365 buf = ip->bw_conv_buf;
5366 len = (int)(p - ip->bw_conv_buf);
5367 }
5368 else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1))
5369 {
5370 /*
5371 * Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
5372 * Latin1 chars in the file.
5373 */
5374 if (flags & FIO_LATIN1)
5375 p = buf; /* translate in-place (can only get shorter) */
5376 else
5377 p = ip->bw_conv_buf; /* translate to buffer */
5378 for (wlen = 0; wlen < len; wlen += n)
5379 {
5380 if (wlen == 0 && ip->bw_restlen != 0)
5381 {
5382 int l;
5383
5384 /* Use remainder of previous call. Append the start of
5385 * buf[] to get a full sequence. Might still be too
5386 * short! */
5387 l = CONV_RESTLEN - ip->bw_restlen;
5388 if (l > len)
5389 l = len;
5390 mch_memmove(ip->bw_rest + ip->bw_restlen, buf, (size_t)l);
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005391 n = utf_ptr2len_len(ip->bw_rest, ip->bw_restlen + l);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005392 if (n > ip->bw_restlen + len)
5393 {
5394 /* We have an incomplete byte sequence at the end to
5395 * be written. We can't convert it without the
5396 * remaining bytes. Keep them for the next call. */
5397 if (ip->bw_restlen + len > CONV_RESTLEN)
5398 return FAIL;
5399 ip->bw_restlen += len;
5400 break;
5401 }
5402 if (n > 1)
5403 c = utf_ptr2char(ip->bw_rest);
5404 else
5405 c = ip->bw_rest[0];
5406 if (n >= ip->bw_restlen)
5407 {
5408 n -= ip->bw_restlen;
5409 ip->bw_restlen = 0;
5410 }
5411 else
5412 {
5413 ip->bw_restlen -= n;
5414 mch_memmove(ip->bw_rest, ip->bw_rest + n,
5415 (size_t)ip->bw_restlen);
5416 n = 0;
5417 }
5418 }
5419 else
5420 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005421 n = utf_ptr2len_len(buf + wlen, len - wlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005422 if (n > len - wlen)
5423 {
5424 /* We have an incomplete byte sequence at the end to
5425 * be written. We can't convert it without the
5426 * remaining bytes. Keep them for the next call. */
5427 if (len - wlen > CONV_RESTLEN)
5428 return FAIL;
5429 ip->bw_restlen = len - wlen;
5430 mch_memmove(ip->bw_rest, buf + wlen,
5431 (size_t)ip->bw_restlen);
5432 break;
5433 }
5434 if (n > 1)
5435 c = utf_ptr2char(buf + wlen);
5436 else
5437 c = buf[wlen];
5438 }
5439
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005440 if (ucs2bytes(c, &p, flags) && !ip->bw_conv_error)
5441 {
5442 ip->bw_conv_error = TRUE;
5443 ip->bw_conv_error_lnum = ip->bw_start_lnum;
5444 }
5445 if (c == NL)
5446 ++ip->bw_start_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005447 }
5448 if (flags & FIO_LATIN1)
5449 len = (int)(p - buf);
5450 else
5451 {
5452 buf = ip->bw_conv_buf;
5453 len = (int)(p - ip->bw_conv_buf);
5454 }
5455 }
5456
5457# ifdef WIN3264
5458 else if (flags & FIO_CODEPAGE)
5459 {
5460 /*
5461 * Convert UTF-8 or codepage to UCS-2 and then to MS-Windows
5462 * codepage.
5463 */
5464 char_u *from;
5465 size_t fromlen;
5466 char_u *to;
5467 int u8c;
5468 BOOL bad = FALSE;
5469 int needed;
5470
5471 if (ip->bw_restlen > 0)
5472 {
5473 /* Need to concatenate the remainder of the previous call and
5474 * the bytes of the current call. Use the end of the
5475 * conversion buffer for this. */
5476 fromlen = len + ip->bw_restlen;
5477 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5478 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5479 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5480 }
5481 else
5482 {
5483 from = buf;
5484 fromlen = len;
5485 }
5486
5487 to = ip->bw_conv_buf;
5488 if (enc_utf8)
5489 {
5490 /* Convert from UTF-8 to UCS-2, to the start of the buffer.
5491 * The buffer has been allocated to be big enough. */
5492 while (fromlen > 0)
5493 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005494 n = (int)utf_ptr2len_len(from, (int)fromlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005495 if (n > (int)fromlen) /* incomplete byte sequence */
5496 break;
5497 u8c = utf_ptr2char(from);
5498 *to++ = (u8c & 0xff);
5499 *to++ = (u8c >> 8);
5500 fromlen -= n;
5501 from += n;
5502 }
5503
5504 /* Copy remainder to ip->bw_rest[] to be used for the next
5505 * call. */
5506 if (fromlen > CONV_RESTLEN)
5507 {
5508 /* weird overlong sequence */
5509 ip->bw_conv_error = TRUE;
5510 return FAIL;
5511 }
5512 mch_memmove(ip->bw_rest, from, fromlen);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005513 ip->bw_restlen = (int)fromlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005514 }
5515 else
5516 {
5517 /* Convert from enc_codepage to UCS-2, to the start of the
5518 * buffer. The buffer has been allocated to be big enough. */
5519 ip->bw_restlen = 0;
5520 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005521 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005522 NULL, 0);
5523 if (needed == 0)
5524 {
5525 /* When conversion fails there may be a trailing byte. */
5526 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005527 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen - 1,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005528 NULL, 0);
5529 if (needed == 0)
5530 {
5531 /* Conversion doesn't work. */
5532 ip->bw_conv_error = TRUE;
5533 return FAIL;
5534 }
5535 /* Save the trailing byte for the next call. */
5536 ip->bw_rest[0] = from[fromlen - 1];
5537 ip->bw_restlen = 1;
5538 }
5539 needed = MultiByteToWideChar(enc_codepage, MB_ERR_INVALID_CHARS,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005540 (LPCSTR)from, (int)(fromlen - ip->bw_restlen),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005541 (LPWSTR)to, needed);
5542 if (needed == 0)
5543 {
5544 /* Safety check: Conversion doesn't work. */
5545 ip->bw_conv_error = TRUE;
5546 return FAIL;
5547 }
5548 to += needed * 2;
5549 }
5550
5551 fromlen = to - ip->bw_conv_buf;
5552 buf = to;
5553# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5554 if (FIO_GET_CP(flags) == CP_UTF8)
5555 {
5556 /* Convert from UCS-2 to UTF-8, using the remainder of the
5557 * conversion buffer. Fails when out of space. */
5558 for (from = ip->bw_conv_buf; fromlen > 1; fromlen -= 2)
5559 {
5560 u8c = *from++;
5561 u8c += (*from++ << 8);
5562 to += utf_char2bytes(u8c, to);
5563 if (to + 6 >= ip->bw_conv_buf + ip->bw_conv_buflen)
5564 {
5565 ip->bw_conv_error = TRUE;
5566 return FAIL;
5567 }
5568 }
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005569 len = (int)(to - buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005570 }
5571 else
5572#endif
5573 {
5574 /* Convert from UCS-2 to the codepage, using the remainder of
5575 * the conversion buffer. If the conversion uses the default
5576 * character "0", the data doesn't fit in this encoding, so
5577 * fail. */
5578 len = WideCharToMultiByte(FIO_GET_CP(flags), 0,
5579 (LPCWSTR)ip->bw_conv_buf, (int)fromlen / sizeof(WCHAR),
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005580 (LPSTR)to, (int)(ip->bw_conv_buflen - fromlen), 0,
5581 &bad);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005582 if (bad)
5583 {
5584 ip->bw_conv_error = TRUE;
5585 return FAIL;
5586 }
5587 }
5588 }
5589# endif
5590
Bram Moolenaar56718732006-03-15 22:53:57 +00005591# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00005592 else if (flags & FIO_MACROMAN)
5593 {
5594 /*
5595 * Convert UTF-8 or latin1 to Apple MacRoman.
5596 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005597 char_u *from;
5598 size_t fromlen;
5599
5600 if (ip->bw_restlen > 0)
5601 {
5602 /* Need to concatenate the remainder of the previous call and
5603 * the bytes of the current call. Use the end of the
5604 * conversion buffer for this. */
5605 fromlen = len + ip->bw_restlen;
5606 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5607 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5608 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5609 }
5610 else
5611 {
5612 from = buf;
5613 fromlen = len;
5614 }
5615
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00005616 if (enc2macroman(from, fromlen,
5617 ip->bw_conv_buf, &len, ip->bw_conv_buflen,
5618 ip->bw_rest, &ip->bw_restlen) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005619 {
5620 ip->bw_conv_error = TRUE;
5621 return FAIL;
5622 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005623 buf = ip->bw_conv_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005624 }
5625# endif
5626
5627# ifdef USE_ICONV
5628 if (ip->bw_iconv_fd != (iconv_t)-1)
5629 {
5630 const char *from;
5631 size_t fromlen;
5632 char *to;
5633 size_t tolen;
5634
5635 /* Convert with iconv(). */
5636 if (ip->bw_restlen > 0)
5637 {
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005638 char *fp;
5639
Bram Moolenaar071d4272004-06-13 20:20:40 +00005640 /* Need to concatenate the remainder of the previous call and
5641 * the bytes of the current call. Use the end of the
5642 * conversion buffer for this. */
5643 fromlen = len + ip->bw_restlen;
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005644 fp = (char *)ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5645 mch_memmove(fp, ip->bw_rest, (size_t)ip->bw_restlen);
5646 mch_memmove(fp + ip->bw_restlen, buf, (size_t)len);
5647 from = fp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005648 tolen = ip->bw_conv_buflen - fromlen;
5649 }
5650 else
5651 {
5652 from = (const char *)buf;
5653 fromlen = len;
5654 tolen = ip->bw_conv_buflen;
5655 }
5656 to = (char *)ip->bw_conv_buf;
5657
5658 if (ip->bw_first)
5659 {
5660 size_t save_len = tolen;
5661
5662 /* output the initial shift state sequence */
5663 (void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen);
5664
5665 /* There is a bug in iconv() on Linux (which appears to be
5666 * wide-spread) which sets "to" to NULL and messes up "tolen".
5667 */
5668 if (to == NULL)
5669 {
5670 to = (char *)ip->bw_conv_buf;
5671 tolen = save_len;
5672 }
5673 ip->bw_first = FALSE;
5674 }
5675
5676 /*
5677 * If iconv() has an error or there is not enough room, fail.
5678 */
5679 if ((iconv(ip->bw_iconv_fd, (void *)&from, &fromlen, &to, &tolen)
5680 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
5681 || fromlen > CONV_RESTLEN)
5682 {
5683 ip->bw_conv_error = TRUE;
5684 return FAIL;
5685 }
5686
5687 /* copy remainder to ip->bw_rest[] to be used for the next call. */
5688 if (fromlen > 0)
5689 mch_memmove(ip->bw_rest, (void *)from, fromlen);
5690 ip->bw_restlen = (int)fromlen;
5691
5692 buf = ip->bw_conv_buf;
5693 len = (int)((char_u *)to - ip->bw_conv_buf);
5694 }
5695# endif
5696 }
5697#endif /* FEAT_MBYTE */
5698
5699#ifdef FEAT_CRYPT
5700 if (flags & FIO_ENCRYPTED) /* encrypt the data */
Bram Moolenaar04c9baf2010-06-01 23:37:39 +02005701 crypt_encode(buf, len, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005702#endif
5703
5704 /* Repeat the write(), it may be interrupted by a signal. */
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005705 while (len > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005706 {
5707 wlen = vim_write(ip->bw_fd, buf, len);
5708 if (wlen <= 0) /* error! */
5709 return FAIL;
5710 len -= wlen;
5711 buf += wlen;
5712 }
5713 return OK;
5714}
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
6664 while ((n = vim_read(fd_in, buffer, BUFSIZE)) > 0)
6665 if (vim_write(fd_out, buffer, n) != n)
6666 {
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,
7026 (char_u *)_("&OK\n&Load File"), 1, NULL) == 2)
7027 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;
7112
7113 /* set curwin/curbuf for "buf" and save some things */
7114 aucmd_prepbuf(&aco, buf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007115
7116 /* We only want to read the text from the file, not reset the syntax
7117 * highlighting, clear marks, diff status, etc. Force the fileformat
7118 * and encoding to be the same. */
7119 if (prep_exarg(&ea, buf) == OK)
7120 {
7121 old_cursor = curwin->w_cursor;
7122 old_topline = curwin->w_topline;
7123
7124 /*
7125 * To behave like when a new file is edited (matters for
7126 * BufReadPost autocommands) we first need to delete the current
7127 * buffer contents. But if reading the file fails we should keep
7128 * the old contents. Can't use memory only, the file might be
7129 * too big. Use a hidden buffer to move the buffer contents to.
7130 */
7131 if (bufempty())
7132 savebuf = NULL;
7133 else
7134 {
7135 /* Allocate a buffer without putting it in the buffer list. */
7136 savebuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007137 if (savebuf != NULL && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007138 {
7139 /* Open the memline. */
7140 curbuf = savebuf;
7141 curwin->w_buffer = savebuf;
Bram Moolenaar4770d092006-01-12 23:22:24 +00007142 saved = ml_open(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007143 curbuf = buf;
7144 curwin->w_buffer = buf;
7145 }
Bram Moolenaar8424a622006-04-19 21:23:36 +00007146 if (savebuf == NULL || saved == FAIL || buf != curbuf
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007147 || move_lines(buf, savebuf) == FAIL)
7148 {
7149 EMSG2(_("E462: Could not prepare for reloading \"%s\""),
7150 buf->b_fname);
7151 saved = FAIL;
7152 }
7153 }
7154
7155 if (saved == OK)
7156 {
7157 curbuf->b_flags |= BF_CHECK_RO; /* check for RO again */
7158#ifdef FEAT_AUTOCMD
7159 keep_filetype = TRUE; /* don't detect 'filetype' */
7160#endif
7161 if (readfile(buf->b_ffname, buf->b_fname, (linenr_T)0,
7162 (linenr_T)0,
7163 (linenr_T)MAXLNUM, &ea, READ_NEW) == FAIL)
7164 {
7165#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
7166 if (!aborting())
7167#endif
7168 EMSG2(_("E321: Could not reload \"%s\""), buf->b_fname);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007169 if (savebuf != NULL && buf_valid(savebuf) && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007170 {
7171 /* Put the text back from the save buffer. First
7172 * delete any lines that readfile() added. */
7173 while (!bufempty())
Bram Moolenaar8424a622006-04-19 21:23:36 +00007174 if (ml_delete(buf->b_ml.ml_line_count, FALSE) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007175 break;
7176 (void)move_lines(savebuf, buf);
7177 }
7178 }
Bram Moolenaar8424a622006-04-19 21:23:36 +00007179 else if (buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007180 {
7181 /* Mark the buffer as unmodified and free undo info. */
7182 unchanged(buf, TRUE);
7183 u_blockfree(buf);
7184 u_clearall(buf);
7185 }
7186 }
7187 vim_free(ea.cmd);
7188
Bram Moolenaar8424a622006-04-19 21:23:36 +00007189 if (savebuf != NULL && buf_valid(savebuf))
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007190 wipe_buffer(savebuf, FALSE);
7191
7192#ifdef FEAT_DIFF
7193 /* Invalidate diff info if necessary. */
Bram Moolenaar8424a622006-04-19 21:23:36 +00007194 diff_invalidate(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007195#endif
7196
7197 /* Restore the topline and cursor position and check it (lines may
7198 * have been removed). */
7199 if (old_topline > curbuf->b_ml.ml_line_count)
7200 curwin->w_topline = curbuf->b_ml.ml_line_count;
7201 else
7202 curwin->w_topline = old_topline;
7203 curwin->w_cursor = old_cursor;
7204 check_cursor();
7205 update_topline();
7206#ifdef FEAT_AUTOCMD
7207 keep_filetype = FALSE;
7208#endif
7209#ifdef FEAT_FOLDING
7210 {
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007211 win_T *wp;
7212 tabpage_T *tp;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007213
7214 /* Update folds unless they are defined manually. */
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007215 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007216 if (wp->w_buffer == curwin->w_buffer
7217 && !foldmethodIsManual(wp))
7218 foldUpdateAll(wp);
7219 }
7220#endif
7221 /* If the mode didn't change and 'readonly' was set, keep the old
7222 * value; the user probably used the ":view" command. But don't
7223 * reset it, might have had a read error. */
7224 if (orig_mode == curbuf->b_orig_mode)
7225 curbuf->b_p_ro |= old_ro;
7226 }
7227
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007228 /* restore curwin/curbuf and a few other things */
7229 aucmd_restbuf(&aco);
7230 /* Careful: autocommands may have made "buf" invalid! */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007231}
7232
Bram Moolenaar071d4272004-06-13 20:20:40 +00007233 void
7234buf_store_time(buf, st, fname)
7235 buf_T *buf;
7236 struct stat *st;
Bram Moolenaar78a15312009-05-15 19:33:18 +00007237 char_u *fname UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007238{
7239 buf->b_mtime = (long)st->st_mtime;
Bram Moolenaar914703b2010-05-31 21:59:46 +02007240 buf->b_orig_size = st->st_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007241#ifdef HAVE_ST_MODE
7242 buf->b_orig_mode = (int)st->st_mode;
7243#else
7244 buf->b_orig_mode = mch_getperm(fname);
7245#endif
7246}
7247
7248/*
7249 * Adjust the line with missing eol, used for the next write.
7250 * Used for do_filter(), when the input lines for the filter are deleted.
7251 */
7252 void
7253write_lnum_adjust(offset)
7254 linenr_T offset;
7255{
Bram Moolenaardf177f62005-02-22 08:39:57 +00007256 if (write_no_eol_lnum != 0) /* only if there is a missing eol */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007257 write_no_eol_lnum += offset;
7258}
7259
7260#if defined(TEMPDIRNAMES) || defined(PROTO)
7261static long temp_count = 0; /* Temp filename counter. */
7262
7263/*
7264 * Delete the temp directory and all files it contains.
7265 */
7266 void
7267vim_deltempdir()
7268{
7269 char_u **files;
7270 int file_count;
7271 int i;
7272
7273 if (vim_tempdir != NULL)
7274 {
7275 sprintf((char *)NameBuff, "%s*", vim_tempdir);
7276 if (gen_expand_wildcards(1, &NameBuff, &file_count, &files,
7277 EW_DIR|EW_FILE|EW_SILENT) == OK)
7278 {
7279 for (i = 0; i < file_count; ++i)
7280 mch_remove(files[i]);
7281 FreeWild(file_count, files);
7282 }
7283 gettail(NameBuff)[-1] = NUL;
7284 (void)mch_rmdir(NameBuff);
7285
7286 vim_free(vim_tempdir);
7287 vim_tempdir = NULL;
7288 }
7289}
7290#endif
7291
Bram Moolenaar4592dee2009-11-18 19:11:58 +00007292#ifdef TEMPDIRNAMES
Bram Moolenaar071d4272004-06-13 20:20:40 +00007293/*
Bram Moolenaareaf03392009-11-17 11:08:52 +00007294 * Directory "tempdir" was created. Expand this name to a full path and put
7295 * it in "vim_tempdir". This avoids that using ":cd" would confuse us.
7296 * "tempdir" must be no longer than MAXPATHL.
7297 */
7298 static void
7299vim_settempdir(tempdir)
7300 char_u *tempdir;
7301{
7302 char_u *buf;
7303
7304 buf = alloc((unsigned)MAXPATHL + 2);
7305 if (buf != NULL)
7306 {
7307 if (vim_FullName(tempdir, buf, MAXPATHL, FALSE) == FAIL)
7308 STRCPY(buf, tempdir);
7309# ifdef __EMX__
7310 if (vim_strchr(buf, '/') != NULL)
7311 STRCAT(buf, "/");
7312 else
7313# endif
7314 add_pathsep(buf);
7315 vim_tempdir = vim_strsave(buf);
7316 vim_free(buf);
7317 }
7318}
Bram Moolenaar4592dee2009-11-18 19:11:58 +00007319#endif
Bram Moolenaareaf03392009-11-17 11:08:52 +00007320
7321/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007322 * vim_tempname(): Return a unique name that can be used for a temp file.
7323 *
7324 * The temp file is NOT created.
7325 *
7326 * The returned pointer is to allocated memory.
7327 * The returned pointer is NULL if no valid name was found.
7328 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007329 char_u *
7330vim_tempname(extra_char)
Bram Moolenaar78a15312009-05-15 19:33:18 +00007331 int extra_char UNUSED; /* char to use in the name instead of '?' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007332{
7333#ifdef USE_TMPNAM
7334 char_u itmp[L_tmpnam]; /* use tmpnam() */
7335#else
7336 char_u itmp[TEMPNAMELEN];
7337#endif
7338
7339#ifdef TEMPDIRNAMES
7340 static char *(tempdirs[]) = {TEMPDIRNAMES};
7341 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007342# ifndef EEXIST
7343 struct stat st;
7344# endif
7345
7346 /*
7347 * This will create a directory for private use by this instance of Vim.
7348 * This is done once, and the same directory is used for all temp files.
7349 * This method avoids security problems because of symlink attacks et al.
7350 * It's also a bit faster, because we only need to check for an existing
7351 * file when creating the directory and not for each temp file.
7352 */
7353 if (vim_tempdir == NULL)
7354 {
7355 /*
7356 * Try the entries in TEMPDIRNAMES to create the temp directory.
7357 */
Bram Moolenaar78a15312009-05-15 19:33:18 +00007358 for (i = 0; i < (int)(sizeof(tempdirs) / sizeof(char *)); ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007359 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007360# ifndef HAVE_MKDTEMP
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007361 size_t itmplen;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007362 long nr;
7363 long off;
7364# endif
7365
Bram Moolenaar071d4272004-06-13 20:20:40 +00007366 /* expand $TMP, leave room for "/v1100000/999999999" */
7367 expand_env((char_u *)tempdirs[i], itmp, TEMPNAMELEN - 20);
7368 if (mch_isdir(itmp)) /* directory exists */
7369 {
7370# ifdef __EMX__
7371 /* If $TMP contains a forward slash (perhaps using bash or
7372 * tcsh), don't add a backslash, use a forward slash!
7373 * Adding 2 backslashes didn't work. */
7374 if (vim_strchr(itmp, '/') != NULL)
7375 STRCAT(itmp, "/");
7376 else
7377# endif
7378 add_pathsep(itmp);
7379
Bram Moolenaareaf03392009-11-17 11:08:52 +00007380# ifdef HAVE_MKDTEMP
7381 /* Leave room for filename */
7382 STRCAT(itmp, "vXXXXXX");
7383 if (mkdtemp((char *)itmp) != NULL)
7384 vim_settempdir(itmp);
7385# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007386 /* Get an arbitrary number of up to 6 digits. When it's
7387 * unlikely that it already exists it will be faster,
7388 * otherwise it doesn't matter. The use of mkdir() avoids any
7389 * security problems because of the predictable number. */
7390 nr = (mch_get_pid() + (long)time(NULL)) % 1000000L;
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007391 itmplen = STRLEN(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007392
7393 /* Try up to 10000 different values until we find a name that
7394 * doesn't exist. */
7395 for (off = 0; off < 10000L; ++off)
7396 {
7397 int r;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007398# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007399 mode_t umask_save;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007400# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007401
Bram Moolenaareaf03392009-11-17 11:08:52 +00007402 sprintf((char *)itmp + itmplen, "v%ld", nr + off);
7403# ifndef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007404 /* If mkdir() does not set errno to EEXIST, check for
7405 * existing file here. There is a race condition then,
7406 * although it's fail-safe. */
7407 if (mch_stat((char *)itmp, &st) >= 0)
7408 continue;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007409# endif
7410# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007411 /* Make sure the umask doesn't remove the executable bit.
7412 * "repl" has been reported to use "177". */
7413 umask_save = umask(077);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007414# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007415 r = vim_mkdir(itmp, 0700);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007416# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007417 (void)umask(umask_save);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007418# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007419 if (r == 0)
7420 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007421 vim_settempdir(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007422 break;
7423 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007424# ifdef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007425 /* If the mkdir() didn't fail because the file/dir exists,
7426 * we probably can't create any dir here, try another
7427 * place. */
7428 if (errno != EEXIST)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007429# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007430 break;
7431 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007432# endif /* HAVE_MKDTEMP */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007433 if (vim_tempdir != NULL)
7434 break;
7435 }
7436 }
7437 }
7438
7439 if (vim_tempdir != NULL)
7440 {
7441 /* There is no need to check if the file exists, because we own the
7442 * directory and nobody else creates a file in it. */
7443 sprintf((char *)itmp, "%s%ld", vim_tempdir, temp_count++);
7444 return vim_strsave(itmp);
7445 }
7446
7447 return NULL;
7448
7449#else /* TEMPDIRNAMES */
7450
7451# ifdef WIN3264
7452 char szTempFile[_MAX_PATH + 1];
7453 char buf4[4];
7454 char_u *retval;
7455 char_u *p;
7456
7457 STRCPY(itmp, "");
7458 if (GetTempPath(_MAX_PATH, szTempFile) == 0)
7459 szTempFile[0] = NUL; /* GetTempPath() failed, use current dir */
7460 strcpy(buf4, "VIM");
7461 buf4[2] = extra_char; /* make it "VIa", "VIb", etc. */
7462 if (GetTempFileName(szTempFile, buf4, 0, itmp) == 0)
7463 return NULL;
7464 /* GetTempFileName() will create the file, we don't want that */
7465 (void)DeleteFile(itmp);
7466
7467 /* Backslashes in a temp file name cause problems when filtering with
7468 * "sh". NOTE: This also checks 'shellcmdflag' to help those people who
7469 * didn't set 'shellslash'. */
7470 retval = vim_strsave(itmp);
7471 if (*p_shcf == '-' || p_ssl)
7472 for (p = retval; *p; ++p)
7473 if (*p == '\\')
7474 *p = '/';
7475 return retval;
7476
7477# else /* WIN3264 */
7478
7479# ifdef USE_TMPNAM
7480 /* tmpnam() will make its own name */
7481 if (*tmpnam((char *)itmp) == NUL)
7482 return NULL;
7483# else
7484 char_u *p;
7485
7486# ifdef VMS_TEMPNAM
7487 /* mktemp() is not working on VMS. It seems to be
7488 * a do-nothing function. Therefore we use tempnam().
7489 */
7490 sprintf((char *)itmp, "VIM%c", extra_char);
7491 p = (char_u *)tempnam("tmp:", (char *)itmp);
7492 if (p != NULL)
7493 {
7494 /* VMS will use '.LOG' if we don't explicitly specify an extension,
7495 * and VIM will then be unable to find the file later */
7496 STRCPY(itmp, p);
7497 STRCAT(itmp, ".txt");
7498 free(p);
7499 }
7500 else
7501 return NULL;
7502# else
7503 STRCPY(itmp, TEMPNAME);
7504 if ((p = vim_strchr(itmp, '?')) != NULL)
7505 *p = extra_char;
7506 if (mktemp((char *)itmp) == NULL)
7507 return NULL;
7508# endif
7509# endif
7510
7511 return vim_strsave(itmp);
7512# endif /* WIN3264 */
7513#endif /* TEMPDIRNAMES */
7514}
7515
7516#if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
7517/*
7518 * Convert all backslashes in fname to forward slashes in-place.
7519 */
7520 void
7521forward_slash(fname)
7522 char_u *fname;
7523{
7524 char_u *p;
7525
7526 for (p = fname; *p != NUL; ++p)
7527# ifdef FEAT_MBYTE
7528 /* The Big5 encoding can have '\' in the trail byte. */
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00007529 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007530 ++p;
7531 else
7532# endif
7533 if (*p == '\\')
7534 *p = '/';
7535}
7536#endif
7537
7538
7539/*
7540 * Code for automatic commands.
7541 *
7542 * Only included when "FEAT_AUTOCMD" has been defined.
7543 */
7544
7545#if defined(FEAT_AUTOCMD) || defined(PROTO)
7546
7547/*
7548 * The autocommands are stored in a list for each event.
7549 * Autocommands for the same pattern, that are consecutive, are joined
7550 * together, to avoid having to match the pattern too often.
7551 * The result is an array of Autopat lists, which point to AutoCmd lists:
7552 *
7553 * first_autopat[0] --> Autopat.next --> Autopat.next --> NULL
7554 * Autopat.cmds Autopat.cmds
7555 * | |
7556 * V V
7557 * AutoCmd.next AutoCmd.next
7558 * | |
7559 * V V
7560 * AutoCmd.next NULL
7561 * |
7562 * V
7563 * NULL
7564 *
7565 * first_autopat[1] --> Autopat.next --> NULL
7566 * Autopat.cmds
7567 * |
7568 * V
7569 * AutoCmd.next
7570 * |
7571 * V
7572 * NULL
7573 * etc.
7574 *
7575 * The order of AutoCmds is important, this is the order in which they were
7576 * defined and will have to be executed.
7577 */
7578typedef struct AutoCmd
7579{
7580 char_u *cmd; /* The command to be executed (NULL
7581 when command has been removed) */
7582 char nested; /* If autocommands nest here */
7583 char last; /* last command in list */
7584#ifdef FEAT_EVAL
7585 scid_T scriptID; /* script ID where defined */
7586#endif
7587 struct AutoCmd *next; /* Next AutoCmd in list */
7588} AutoCmd;
7589
7590typedef struct AutoPat
7591{
7592 int group; /* group ID */
7593 char_u *pat; /* pattern as typed (NULL when pattern
7594 has been removed) */
7595 int patlen; /* strlen() of pat */
Bram Moolenaar748bf032005-02-02 23:04:36 +00007596 regprog_T *reg_prog; /* compiled regprog for pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007597 char allow_dirs; /* Pattern may match whole path */
7598 char last; /* last pattern for apply_autocmds() */
7599 AutoCmd *cmds; /* list of commands to do */
7600 struct AutoPat *next; /* next AutoPat in AutoPat list */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007601 int buflocal_nr; /* !=0 for buffer-local AutoPat */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007602} AutoPat;
7603
7604static struct event_name
7605{
7606 char *name; /* event name */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007607 event_T event; /* event number */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007608} event_names[] =
7609{
7610 {"BufAdd", EVENT_BUFADD},
7611 {"BufCreate", EVENT_BUFADD},
7612 {"BufDelete", EVENT_BUFDELETE},
7613 {"BufEnter", EVENT_BUFENTER},
7614 {"BufFilePost", EVENT_BUFFILEPOST},
7615 {"BufFilePre", EVENT_BUFFILEPRE},
7616 {"BufHidden", EVENT_BUFHIDDEN},
7617 {"BufLeave", EVENT_BUFLEAVE},
7618 {"BufNew", EVENT_BUFNEW},
7619 {"BufNewFile", EVENT_BUFNEWFILE},
7620 {"BufRead", EVENT_BUFREADPOST},
7621 {"BufReadCmd", EVENT_BUFREADCMD},
7622 {"BufReadPost", EVENT_BUFREADPOST},
7623 {"BufReadPre", EVENT_BUFREADPRE},
7624 {"BufUnload", EVENT_BUFUNLOAD},
7625 {"BufWinEnter", EVENT_BUFWINENTER},
7626 {"BufWinLeave", EVENT_BUFWINLEAVE},
7627 {"BufWipeout", EVENT_BUFWIPEOUT},
7628 {"BufWrite", EVENT_BUFWRITEPRE},
7629 {"BufWritePost", EVENT_BUFWRITEPOST},
7630 {"BufWritePre", EVENT_BUFWRITEPRE},
7631 {"BufWriteCmd", EVENT_BUFWRITECMD},
7632 {"CmdwinEnter", EVENT_CMDWINENTER},
7633 {"CmdwinLeave", EVENT_CMDWINLEAVE},
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007634 {"ColorScheme", EVENT_COLORSCHEME},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007635 {"CursorHold", EVENT_CURSORHOLD},
7636 {"CursorHoldI", EVENT_CURSORHOLDI},
7637 {"CursorMoved", EVENT_CURSORMOVED},
7638 {"CursorMovedI", EVENT_CURSORMOVEDI},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007639 {"EncodingChanged", EVENT_ENCODINGCHANGED},
7640 {"FileEncoding", EVENT_ENCODINGCHANGED},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007641 {"FileAppendPost", EVENT_FILEAPPENDPOST},
7642 {"FileAppendPre", EVENT_FILEAPPENDPRE},
7643 {"FileAppendCmd", EVENT_FILEAPPENDCMD},
7644 {"FileChangedShell",EVENT_FILECHANGEDSHELL},
Bram Moolenaar56718732006-03-15 22:53:57 +00007645 {"FileChangedShellPost",EVENT_FILECHANGEDSHELLPOST},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007646 {"FileChangedRO", EVENT_FILECHANGEDRO},
7647 {"FileReadPost", EVENT_FILEREADPOST},
7648 {"FileReadPre", EVENT_FILEREADPRE},
7649 {"FileReadCmd", EVENT_FILEREADCMD},
7650 {"FileType", EVENT_FILETYPE},
7651 {"FileWritePost", EVENT_FILEWRITEPOST},
7652 {"FileWritePre", EVENT_FILEWRITEPRE},
7653 {"FileWriteCmd", EVENT_FILEWRITECMD},
7654 {"FilterReadPost", EVENT_FILTERREADPOST},
7655 {"FilterReadPre", EVENT_FILTERREADPRE},
7656 {"FilterWritePost", EVENT_FILTERWRITEPOST},
7657 {"FilterWritePre", EVENT_FILTERWRITEPRE},
7658 {"FocusGained", EVENT_FOCUSGAINED},
7659 {"FocusLost", EVENT_FOCUSLOST},
7660 {"FuncUndefined", EVENT_FUNCUNDEFINED},
7661 {"GUIEnter", EVENT_GUIENTER},
Bram Moolenaar265e5072006-08-29 16:13:22 +00007662 {"GUIFailed", EVENT_GUIFAILED},
Bram Moolenaar843ee412004-06-30 16:16:41 +00007663 {"InsertChange", EVENT_INSERTCHANGE},
7664 {"InsertEnter", EVENT_INSERTENTER},
7665 {"InsertLeave", EVENT_INSERTLEAVE},
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00007666 {"MenuPopup", EVENT_MENUPOPUP},
Bram Moolenaar7c626922005-02-07 22:01:03 +00007667 {"QuickFixCmdPost", EVENT_QUICKFIXCMDPOST},
7668 {"QuickFixCmdPre", EVENT_QUICKFIXCMDPRE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007669 {"RemoteReply", EVENT_REMOTEREPLY},
Bram Moolenaar9372a112005-12-06 19:59:18 +00007670 {"SessionLoadPost", EVENT_SESSIONLOADPOST},
Bram Moolenaar5c4bab02006-03-10 21:37:46 +00007671 {"ShellCmdPost", EVENT_SHELLCMDPOST},
7672 {"ShellFilterPost", EVENT_SHELLFILTERPOST},
Bram Moolenaara2031822006-03-07 22:29:51 +00007673 {"SourcePre", EVENT_SOURCEPRE},
Bram Moolenaar8dd1aa52007-01-16 20:33:19 +00007674 {"SourceCmd", EVENT_SOURCECMD},
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00007675 {"SpellFileMissing",EVENT_SPELLFILEMISSING},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007676 {"StdinReadPost", EVENT_STDINREADPOST},
7677 {"StdinReadPre", EVENT_STDINREADPRE},
Bram Moolenaarb815dac2005-12-07 20:59:24 +00007678 {"SwapExists", EVENT_SWAPEXISTS},
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00007679 {"Syntax", EVENT_SYNTAX},
Bram Moolenaar70836c82006-02-20 21:28:49 +00007680 {"TabEnter", EVENT_TABENTER},
7681 {"TabLeave", EVENT_TABLEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007682 {"TermChanged", EVENT_TERMCHANGED},
7683 {"TermResponse", EVENT_TERMRESPONSE},
7684 {"User", EVENT_USER},
7685 {"VimEnter", EVENT_VIMENTER},
7686 {"VimLeave", EVENT_VIMLEAVE},
7687 {"VimLeavePre", EVENT_VIMLEAVEPRE},
7688 {"WinEnter", EVENT_WINENTER},
7689 {"WinLeave", EVENT_WINLEAVE},
Bram Moolenaar56718732006-03-15 22:53:57 +00007690 {"VimResized", EVENT_VIMRESIZED},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007691 {NULL, (event_T)0}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007692};
7693
7694static AutoPat *first_autopat[NUM_EVENTS] =
7695{
7696 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7697 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7698 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7699 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00007700 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7701 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007702};
7703
7704/*
7705 * struct used to keep status while executing autocommands for an event.
7706 */
7707typedef struct AutoPatCmd
7708{
7709 AutoPat *curpat; /* next AutoPat to examine */
7710 AutoCmd *nextcmd; /* next AutoCmd to execute */
7711 int group; /* group being used */
7712 char_u *fname; /* fname to match with */
7713 char_u *sfname; /* sfname to match with */
7714 char_u *tail; /* tail of fname */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007715 event_T event; /* current event */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007716 int arg_bufnr; /* initially equal to <abuf>, set to zero when
7717 buf is deleted */
7718 struct AutoPatCmd *next; /* chain of active apc-s for auto-invalidation*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00007719} AutoPatCmd;
7720
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007721static AutoPatCmd *active_apc_list = NULL; /* stack of active autocommands */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007722
Bram Moolenaar071d4272004-06-13 20:20:40 +00007723/*
7724 * augroups stores a list of autocmd group names.
7725 */
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007726static garray_T augroups = {0, 0, sizeof(char_u *), 10, NULL};
Bram Moolenaar071d4272004-06-13 20:20:40 +00007727#define AUGROUP_NAME(i) (((char_u **)augroups.ga_data)[i])
7728
7729/*
7730 * The ID of the current group. Group 0 is the default one.
7731 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007732static int current_augroup = AUGROUP_DEFAULT;
7733
7734static int au_need_clean = FALSE; /* need to delete marked patterns */
7735
Bram Moolenaar754b5602006-02-09 23:53:20 +00007736static void show_autocmd __ARGS((AutoPat *ap, event_T event));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007737static void au_remove_pat __ARGS((AutoPat *ap));
7738static void au_remove_cmds __ARGS((AutoPat *ap));
7739static void au_cleanup __ARGS((void));
7740static int au_new_group __ARGS((char_u *name));
7741static void au_del_group __ARGS((char_u *name));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007742static event_T event_name2nr __ARGS((char_u *start, char_u **end));
7743static char_u *event_nr2name __ARGS((event_T event));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007744static char_u *find_end_event __ARGS((char_u *arg, int have_group));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007745static int event_ignored __ARGS((event_T event));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007746static int au_get_grouparg __ARGS((char_u **argp));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007747static 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 +00007748static char_u *getnextac __ARGS((int c, void *cookie, int indent));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007749static 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 +00007750static void auto_next_pat __ARGS((AutoPatCmd *apc, int stop_at_last));
7751
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007752
Bram Moolenaar754b5602006-02-09 23:53:20 +00007753static event_T last_event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007754static int last_group;
Bram Moolenaar78ab3312007-09-29 12:16:41 +00007755static int autocmd_blocked = 0; /* block all autocmds */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007756
7757/*
7758 * Show the autocommands for one AutoPat.
7759 */
7760 static void
7761show_autocmd(ap, event)
7762 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007763 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007764{
7765 AutoCmd *ac;
7766
7767 /* Check for "got_int" (here and at various places below), which is set
7768 * when "q" has been hit for the "--more--" prompt */
7769 if (got_int)
7770 return;
7771 if (ap->pat == NULL) /* pattern has been removed */
7772 return;
7773
7774 msg_putchar('\n');
7775 if (got_int)
7776 return;
7777 if (event != last_event || ap->group != last_group)
7778 {
7779 if (ap->group != AUGROUP_DEFAULT)
7780 {
7781 if (AUGROUP_NAME(ap->group) == NULL)
7782 msg_puts_attr((char_u *)_("--Deleted--"), hl_attr(HLF_E));
7783 else
7784 msg_puts_attr(AUGROUP_NAME(ap->group), hl_attr(HLF_T));
7785 msg_puts((char_u *)" ");
7786 }
7787 msg_puts_attr(event_nr2name(event), hl_attr(HLF_T));
7788 last_event = event;
7789 last_group = ap->group;
7790 msg_putchar('\n');
7791 if (got_int)
7792 return;
7793 }
7794 msg_col = 4;
7795 msg_outtrans(ap->pat);
7796
7797 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7798 {
7799 if (ac->cmd != NULL) /* skip removed commands */
7800 {
7801 if (msg_col >= 14)
7802 msg_putchar('\n');
7803 msg_col = 14;
7804 if (got_int)
7805 return;
7806 msg_outtrans(ac->cmd);
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00007807#ifdef FEAT_EVAL
7808 if (p_verbose > 0)
7809 last_set_msg(ac->scriptID);
7810#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007811 if (got_int)
7812 return;
7813 if (ac->next != NULL)
7814 {
7815 msg_putchar('\n');
7816 if (got_int)
7817 return;
7818 }
7819 }
7820 }
7821}
7822
7823/*
7824 * Mark an autocommand pattern for deletion.
7825 */
7826 static void
7827au_remove_pat(ap)
7828 AutoPat *ap;
7829{
7830 vim_free(ap->pat);
7831 ap->pat = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007832 ap->buflocal_nr = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007833 au_need_clean = TRUE;
7834}
7835
7836/*
7837 * Mark all commands for a pattern for deletion.
7838 */
7839 static void
7840au_remove_cmds(ap)
7841 AutoPat *ap;
7842{
7843 AutoCmd *ac;
7844
7845 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7846 {
7847 vim_free(ac->cmd);
7848 ac->cmd = NULL;
7849 }
7850 au_need_clean = TRUE;
7851}
7852
7853/*
7854 * Cleanup autocommands and patterns that have been deleted.
7855 * This is only done when not executing autocommands.
7856 */
7857 static void
7858au_cleanup()
7859{
7860 AutoPat *ap, **prev_ap;
7861 AutoCmd *ac, **prev_ac;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007862 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007863
7864 if (autocmd_busy || !au_need_clean)
7865 return;
7866
7867 /* loop over all events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007868 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7869 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007870 {
7871 /* loop over all autocommand patterns */
7872 prev_ap = &(first_autopat[(int)event]);
7873 for (ap = *prev_ap; ap != NULL; ap = *prev_ap)
7874 {
7875 /* loop over all commands for this pattern */
7876 prev_ac = &(ap->cmds);
7877 for (ac = *prev_ac; ac != NULL; ac = *prev_ac)
7878 {
7879 /* remove the command if the pattern is to be deleted or when
7880 * the command has been marked for deletion */
7881 if (ap->pat == NULL || ac->cmd == NULL)
7882 {
7883 *prev_ac = ac->next;
7884 vim_free(ac->cmd);
7885 vim_free(ac);
7886 }
7887 else
7888 prev_ac = &(ac->next);
7889 }
7890
7891 /* remove the pattern if it has been marked for deletion */
7892 if (ap->pat == NULL)
7893 {
7894 *prev_ap = ap->next;
Bram Moolenaar748bf032005-02-02 23:04:36 +00007895 vim_free(ap->reg_prog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007896 vim_free(ap);
7897 }
7898 else
7899 prev_ap = &(ap->next);
7900 }
7901 }
7902
7903 au_need_clean = FALSE;
7904}
7905
7906/*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007907 * Called when buffer is freed, to remove/invalidate related buffer-local
7908 * autocmds.
7909 */
7910 void
7911aubuflocal_remove(buf)
7912 buf_T *buf;
7913{
7914 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007915 event_T event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007916 AutoPatCmd *apc;
7917
7918 /* invalidate currently executing autocommands */
7919 for (apc = active_apc_list; apc; apc = apc->next)
7920 if (buf->b_fnum == apc->arg_bufnr)
7921 apc->arg_bufnr = 0;
7922
7923 /* invalidate buflocals looping through events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007924 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7925 event = (event_T)((int)event + 1))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007926 /* loop over all autocommand patterns */
7927 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
7928 if (ap->buflocal_nr == buf->b_fnum)
7929 {
7930 au_remove_pat(ap);
7931 if (p_verbose >= 6)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007932 {
7933 verbose_enter();
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007934 smsg((char_u *)
7935 _("auto-removing autocommand: %s <buffer=%d>"),
7936 event_nr2name(event), buf->b_fnum);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007937 verbose_leave();
7938 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007939 }
7940 au_cleanup();
7941}
7942
7943/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007944 * Add an autocmd group name.
7945 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
7946 */
7947 static int
7948au_new_group(name)
7949 char_u *name;
7950{
7951 int i;
7952
7953 i = au_find_group(name);
7954 if (i == AUGROUP_ERROR) /* the group doesn't exist yet, add it */
7955 {
7956 /* First try using a free entry. */
7957 for (i = 0; i < augroups.ga_len; ++i)
7958 if (AUGROUP_NAME(i) == NULL)
7959 break;
7960 if (i == augroups.ga_len && ga_grow(&augroups, 1) == FAIL)
7961 return AUGROUP_ERROR;
7962
7963 AUGROUP_NAME(i) = vim_strsave(name);
7964 if (AUGROUP_NAME(i) == NULL)
7965 return AUGROUP_ERROR;
7966 if (i == augroups.ga_len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007967 ++augroups.ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007968 }
7969
7970 return i;
7971}
7972
7973 static void
7974au_del_group(name)
7975 char_u *name;
7976{
7977 int i;
7978
7979 i = au_find_group(name);
7980 if (i == AUGROUP_ERROR) /* the group doesn't exist */
7981 EMSG2(_("E367: No such group: \"%s\""), name);
7982 else
7983 {
7984 vim_free(AUGROUP_NAME(i));
7985 AUGROUP_NAME(i) = NULL;
7986 }
7987}
7988
7989/*
7990 * Find the ID of an autocmd group name.
7991 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
7992 */
7993 static int
7994au_find_group(name)
7995 char_u *name;
7996{
7997 int i;
7998
7999 for (i = 0; i < augroups.ga_len; ++i)
8000 if (AUGROUP_NAME(i) != NULL && STRCMP(AUGROUP_NAME(i), name) == 0)
8001 return i;
8002 return AUGROUP_ERROR;
8003}
8004
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008005/*
8006 * Return TRUE if augroup "name" exists.
8007 */
8008 int
8009au_has_group(name)
8010 char_u *name;
8011{
8012 return au_find_group(name) != AUGROUP_ERROR;
8013}
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008014
Bram Moolenaar071d4272004-06-13 20:20:40 +00008015/*
8016 * ":augroup {name}".
8017 */
8018 void
8019do_augroup(arg, del_group)
8020 char_u *arg;
8021 int del_group;
8022{
8023 int i;
8024
8025 if (del_group)
8026 {
8027 if (*arg == NUL)
8028 EMSG(_(e_argreq));
8029 else
8030 au_del_group(arg);
8031 }
8032 else if (STRICMP(arg, "end") == 0) /* ":aug end": back to group 0 */
8033 current_augroup = AUGROUP_DEFAULT;
8034 else if (*arg) /* ":aug xxx": switch to group xxx */
8035 {
8036 i = au_new_group(arg);
8037 if (i != AUGROUP_ERROR)
8038 current_augroup = i;
8039 }
8040 else /* ":aug": list the group names */
8041 {
8042 msg_start();
8043 for (i = 0; i < augroups.ga_len; ++i)
8044 {
8045 if (AUGROUP_NAME(i) != NULL)
8046 {
8047 msg_puts(AUGROUP_NAME(i));
8048 msg_puts((char_u *)" ");
8049 }
8050 }
8051 msg_clr_eos();
8052 msg_end();
8053 }
8054}
8055
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008056#if defined(EXITFREE) || defined(PROTO)
8057 void
8058free_all_autocmds()
8059{
8060 for (current_augroup = -1; current_augroup < augroups.ga_len;
8061 ++current_augroup)
8062 do_autocmd((char_u *)"", TRUE);
8063 ga_clear_strings(&augroups);
8064}
8065#endif
8066
Bram Moolenaar071d4272004-06-13 20:20:40 +00008067/*
8068 * Return the event number for event name "start".
8069 * Return NUM_EVENTS if the event name was not found.
8070 * Return a pointer to the next event name in "end".
8071 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008072 static event_T
Bram Moolenaar071d4272004-06-13 20:20:40 +00008073event_name2nr(start, end)
8074 char_u *start;
8075 char_u **end;
8076{
8077 char_u *p;
8078 int i;
8079 int len;
8080
8081 /* the event name ends with end of line, a blank or a comma */
8082 for (p = start; *p && !vim_iswhite(*p) && *p != ','; ++p)
8083 ;
8084 for (i = 0; event_names[i].name != NULL; ++i)
8085 {
8086 len = (int)STRLEN(event_names[i].name);
8087 if (len == p - start && STRNICMP(event_names[i].name, start, len) == 0)
8088 break;
8089 }
8090 if (*p == ',')
8091 ++p;
8092 *end = p;
8093 if (event_names[i].name == NULL)
8094 return NUM_EVENTS;
8095 return event_names[i].event;
8096}
8097
8098/*
8099 * Return the name for event "event".
8100 */
8101 static char_u *
8102event_nr2name(event)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008103 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008104{
8105 int i;
8106
8107 for (i = 0; event_names[i].name != NULL; ++i)
8108 if (event_names[i].event == event)
8109 return (char_u *)event_names[i].name;
8110 return (char_u *)"Unknown";
8111}
8112
8113/*
8114 * Scan over the events. "*" stands for all events.
8115 */
8116 static char_u *
8117find_end_event(arg, have_group)
8118 char_u *arg;
8119 int have_group; /* TRUE when group name was found */
8120{
8121 char_u *pat;
8122 char_u *p;
8123
8124 if (*arg == '*')
8125 {
8126 if (arg[1] && !vim_iswhite(arg[1]))
8127 {
8128 EMSG2(_("E215: Illegal character after *: %s"), arg);
8129 return NULL;
8130 }
8131 pat = arg + 1;
8132 }
8133 else
8134 {
8135 for (pat = arg; *pat && !vim_iswhite(*pat); pat = p)
8136 {
8137 if ((int)event_name2nr(pat, &p) >= (int)NUM_EVENTS)
8138 {
8139 if (have_group)
8140 EMSG2(_("E216: No such event: %s"), pat);
8141 else
8142 EMSG2(_("E216: No such group or event: %s"), pat);
8143 return NULL;
8144 }
8145 }
8146 }
8147 return pat;
8148}
8149
8150/*
8151 * Return TRUE if "event" is included in 'eventignore'.
8152 */
8153 static int
8154event_ignored(event)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008155 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008156{
8157 char_u *p = p_ei;
8158
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008159 while (*p != NUL)
8160 {
8161 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8162 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008163 if (event_name2nr(p, &p) == event)
8164 return TRUE;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008165 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008166
8167 return FALSE;
8168}
8169
8170/*
8171 * Return OK when the contents of p_ei is valid, FAIL otherwise.
8172 */
8173 int
8174check_ei()
8175{
8176 char_u *p = p_ei;
8177
Bram Moolenaar071d4272004-06-13 20:20:40 +00008178 while (*p)
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008179 {
8180 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8181 {
8182 p += 3;
8183 if (*p == ',')
8184 ++p;
8185 }
8186 else if (event_name2nr(p, &p) == NUM_EVENTS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008187 return FAIL;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008188 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008189
8190 return OK;
8191}
8192
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008193# if defined(FEAT_SYN_HL) || defined(PROTO)
8194
8195/*
8196 * Add "what" to 'eventignore' to skip loading syntax highlighting for every
8197 * buffer loaded into the window. "what" must start with a comma.
8198 * Returns the old value of 'eventignore' in allocated memory.
8199 */
8200 char_u *
8201au_event_disable(what)
8202 char *what;
8203{
8204 char_u *new_ei;
8205 char_u *save_ei;
8206
8207 save_ei = vim_strsave(p_ei);
8208 if (save_ei != NULL)
8209 {
Bram Moolenaara5792f52005-11-23 21:25:05 +00008210 new_ei = vim_strnsave(p_ei, (int)(STRLEN(p_ei) + STRLEN(what)));
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008211 if (new_ei != NULL)
8212 {
Bram Moolenaar8cac9fd2010-03-02 12:48:05 +01008213 if (*what == ',' && *p_ei == NUL)
8214 STRCPY(new_ei, what + 1);
8215 else
8216 STRCAT(new_ei, what);
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008217 set_string_option_direct((char_u *)"ei", -1, new_ei,
8218 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008219 vim_free(new_ei);
8220 }
8221 }
8222 return save_ei;
8223}
8224
8225 void
8226au_event_restore(old_ei)
8227 char_u *old_ei;
8228{
8229 if (old_ei != NULL)
8230 {
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008231 set_string_option_direct((char_u *)"ei", -1, old_ei,
8232 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008233 vim_free(old_ei);
8234 }
8235}
8236# endif /* FEAT_SYN_HL */
8237
Bram Moolenaar071d4272004-06-13 20:20:40 +00008238/*
8239 * do_autocmd() -- implements the :autocmd command. Can be used in the
8240 * following ways:
8241 *
8242 * :autocmd <event> <pat> <cmd> Add <cmd> to the list of commands that
8243 * will be automatically executed for <event>
8244 * when editing a file matching <pat>, in
8245 * the current group.
8246 * :autocmd <event> <pat> Show the auto-commands associated with
8247 * <event> and <pat>.
8248 * :autocmd <event> Show the auto-commands associated with
8249 * <event>.
8250 * :autocmd Show all auto-commands.
8251 * :autocmd! <event> <pat> <cmd> Remove all auto-commands associated with
8252 * <event> and <pat>, and add the command
8253 * <cmd>, for the current group.
8254 * :autocmd! <event> <pat> Remove all auto-commands associated with
8255 * <event> and <pat> for the current group.
8256 * :autocmd! <event> Remove all auto-commands associated with
8257 * <event> for the current group.
8258 * :autocmd! Remove ALL auto-commands for the current
8259 * group.
8260 *
8261 * Multiple events and patterns may be given separated by commas. Here are
8262 * some examples:
8263 * :autocmd bufread,bufenter *.c,*.h set tw=0 smartindent noic
8264 * :autocmd bufleave * set tw=79 nosmartindent ic infercase
8265 *
8266 * :autocmd * *.c show all autocommands for *.c files.
Bram Moolenaard35f9712005-12-18 22:02:33 +00008267 *
8268 * Mostly a {group} argument can optionally appear before <event>.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008269 */
8270 void
8271do_autocmd(arg, forceit)
8272 char_u *arg;
8273 int forceit;
8274{
8275 char_u *pat;
8276 char_u *envpat = NULL;
8277 char_u *cmd;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008278 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008279 int need_free = FALSE;
8280 int nested = FALSE;
8281 int group;
8282
8283 /*
8284 * Check for a legal group name. If not, use AUGROUP_ALL.
8285 */
8286 group = au_get_grouparg(&arg);
8287 if (arg == NULL) /* out of memory */
8288 return;
8289
8290 /*
8291 * Scan over the events.
8292 * If we find an illegal name, return here, don't do anything.
8293 */
8294 pat = find_end_event(arg, group != AUGROUP_ALL);
8295 if (pat == NULL)
8296 return;
8297
8298 /*
8299 * Scan over the pattern. Put a NUL at the end.
8300 */
8301 pat = skipwhite(pat);
8302 cmd = pat;
8303 while (*cmd && (!vim_iswhite(*cmd) || cmd[-1] == '\\'))
8304 cmd++;
8305 if (*cmd)
8306 *cmd++ = NUL;
8307
8308 /* Expand environment variables in the pattern. Set 'shellslash', we want
8309 * forward slashes here. */
8310 if (vim_strchr(pat, '$') != NULL || vim_strchr(pat, '~') != NULL)
8311 {
8312#ifdef BACKSLASH_IN_FILENAME
8313 int p_ssl_save = p_ssl;
8314
8315 p_ssl = TRUE;
8316#endif
8317 envpat = expand_env_save(pat);
8318#ifdef BACKSLASH_IN_FILENAME
8319 p_ssl = p_ssl_save;
8320#endif
8321 if (envpat != NULL)
8322 pat = envpat;
8323 }
8324
8325 /*
8326 * Check for "nested" flag.
8327 */
8328 cmd = skipwhite(cmd);
8329 if (*cmd != NUL && STRNCMP(cmd, "nested", 6) == 0 && vim_iswhite(cmd[6]))
8330 {
8331 nested = TRUE;
8332 cmd = skipwhite(cmd + 6);
8333 }
8334
8335 /*
8336 * Find the start of the commands.
8337 * Expand <sfile> in it.
8338 */
8339 if (*cmd != NUL)
8340 {
8341 cmd = expand_sfile(cmd);
8342 if (cmd == NULL) /* some error */
8343 return;
8344 need_free = TRUE;
8345 }
8346
8347 /*
8348 * Print header when showing autocommands.
8349 */
8350 if (!forceit && *cmd == NUL)
8351 {
8352 /* Highlight title */
8353 MSG_PUTS_TITLE(_("\n--- Auto-Commands ---"));
8354 }
8355
8356 /*
8357 * Loop over the events.
8358 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008359 last_event = (event_T)-1; /* for listing the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008360 last_group = AUGROUP_ERROR; /* for listing the group name */
8361 if (*arg == '*' || *arg == NUL)
8362 {
Bram Moolenaar754b5602006-02-09 23:53:20 +00008363 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8364 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008365 if (do_autocmd_event(event, pat,
8366 nested, cmd, forceit, group) == FAIL)
8367 break;
8368 }
8369 else
8370 {
8371 while (*arg && !vim_iswhite(*arg))
8372 if (do_autocmd_event(event_name2nr(arg, &arg), pat,
8373 nested, cmd, forceit, group) == FAIL)
8374 break;
8375 }
8376
8377 if (need_free)
8378 vim_free(cmd);
8379 vim_free(envpat);
8380}
8381
8382/*
8383 * Find the group ID in a ":autocmd" or ":doautocmd" argument.
8384 * The "argp" argument is advanced to the following argument.
8385 *
8386 * Returns the group ID, AUGROUP_ERROR for error (out of memory).
8387 */
8388 static int
8389au_get_grouparg(argp)
8390 char_u **argp;
8391{
8392 char_u *group_name;
8393 char_u *p;
8394 char_u *arg = *argp;
8395 int group = AUGROUP_ALL;
8396
8397 p = skiptowhite(arg);
8398 if (p > arg)
8399 {
8400 group_name = vim_strnsave(arg, (int)(p - arg));
8401 if (group_name == NULL) /* out of memory */
8402 return AUGROUP_ERROR;
8403 group = au_find_group(group_name);
8404 if (group == AUGROUP_ERROR)
8405 group = AUGROUP_ALL; /* no match, use all groups */
8406 else
8407 *argp = skipwhite(p); /* match, skip over group name */
8408 vim_free(group_name);
8409 }
8410 return group;
8411}
8412
8413/*
8414 * do_autocmd() for one event.
8415 * If *pat == NUL do for all patterns.
8416 * If *cmd == NUL show entries.
8417 * If forceit == TRUE delete entries.
8418 * If group is not AUGROUP_ALL, only use this group.
8419 */
8420 static int
8421do_autocmd_event(event, pat, nested, cmd, forceit, group)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008422 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008423 char_u *pat;
8424 int nested;
8425 char_u *cmd;
8426 int forceit;
8427 int group;
8428{
8429 AutoPat *ap;
8430 AutoPat **prev_ap;
8431 AutoCmd *ac;
8432 AutoCmd **prev_ac;
8433 int brace_level;
8434 char_u *endpat;
8435 int findgroup;
8436 int allgroups;
8437 int patlen;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00008438 int is_buflocal;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008439 int buflocal_nr;
8440 char_u buflocal_pat[25]; /* for "<buffer=X>" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008441
8442 if (group == AUGROUP_ALL)
8443 findgroup = current_augroup;
8444 else
8445 findgroup = group;
8446 allgroups = (group == AUGROUP_ALL && !forceit && *cmd == NUL);
8447
8448 /*
8449 * Show or delete all patterns for an event.
8450 */
8451 if (*pat == NUL)
8452 {
8453 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8454 {
8455 if (forceit) /* delete the AutoPat, if it's in the current group */
8456 {
8457 if (ap->group == findgroup)
8458 au_remove_pat(ap);
8459 }
8460 else if (group == AUGROUP_ALL || ap->group == group)
8461 show_autocmd(ap, event);
8462 }
8463 }
8464
8465 /*
8466 * Loop through all the specified patterns.
8467 */
8468 for ( ; *pat; pat = (*endpat == ',' ? endpat + 1 : endpat))
8469 {
8470 /*
8471 * Find end of the pattern.
8472 * Watch out for a comma in braces, like "*.\{obj,o\}".
8473 */
8474 brace_level = 0;
8475 for (endpat = pat; *endpat && (*endpat != ',' || brace_level
8476 || endpat[-1] == '\\'); ++endpat)
8477 {
8478 if (*endpat == '{')
8479 brace_level++;
8480 else if (*endpat == '}')
8481 brace_level--;
8482 }
8483 if (pat == endpat) /* ignore single comma */
8484 continue;
8485 patlen = (int)(endpat - pat);
8486
8487 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008488 * detect special <buflocal[=X]> buffer-local patterns
8489 */
8490 is_buflocal = FALSE;
8491 buflocal_nr = 0;
8492
8493 if (patlen >= 7 && STRNCMP(pat, "<buffer", 7) == 0
8494 && pat[patlen - 1] == '>')
8495 {
8496 /* Error will be printed only for addition. printing and removing
8497 * will proceed silently. */
8498 is_buflocal = TRUE;
8499 if (patlen == 8)
8500 buflocal_nr = curbuf->b_fnum;
8501 else if (patlen > 9 && pat[7] == '=')
8502 {
8503 /* <buffer=abuf> */
8504 if (patlen == 13 && STRNICMP(pat, "<buffer=abuf>", 13))
8505 buflocal_nr = autocmd_bufnr;
8506 /* <buffer=123> */
8507 else if (skipdigits(pat + 8) == pat + patlen - 1)
8508 buflocal_nr = atoi((char *)pat + 8);
8509 }
8510 }
8511
8512 if (is_buflocal)
8513 {
8514 /* normalize pat into standard "<buffer>#N" form */
8515 sprintf((char *)buflocal_pat, "<buffer=%d>", buflocal_nr);
8516 pat = buflocal_pat; /* can modify pat and patlen */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008517 patlen = (int)STRLEN(buflocal_pat); /* but not endpat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008518 }
8519
8520 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008521 * Find AutoPat entries with this pattern.
8522 */
8523 prev_ap = &first_autopat[(int)event];
8524 while ((ap = *prev_ap) != NULL)
8525 {
8526 if (ap->pat != NULL)
8527 {
8528 /* Accept a pattern when:
8529 * - a group was specified and it's that group, or a group was
8530 * not specified and it's the current group, or a group was
8531 * not specified and we are listing
8532 * - the length of the pattern matches
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008533 * - the pattern matches.
8534 * For <buffer[=X]>, this condition works because we normalize
8535 * all buffer-local patterns.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008536 */
8537 if ((allgroups || ap->group == findgroup)
8538 && ap->patlen == patlen
8539 && STRNCMP(pat, ap->pat, patlen) == 0)
8540 {
8541 /*
8542 * Remove existing autocommands.
8543 * If adding any new autocmd's for this AutoPat, don't
8544 * delete the pattern from the autopat list, append to
8545 * this list.
8546 */
8547 if (forceit)
8548 {
8549 if (*cmd != NUL && ap->next == NULL)
8550 {
8551 au_remove_cmds(ap);
8552 break;
8553 }
8554 au_remove_pat(ap);
8555 }
8556
8557 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008558 * Show autocmd's for this autopat, or buflocals <buffer=X>
Bram Moolenaar071d4272004-06-13 20:20:40 +00008559 */
8560 else if (*cmd == NUL)
8561 show_autocmd(ap, event);
8562
8563 /*
8564 * Add autocmd to this autopat, if it's the last one.
8565 */
8566 else if (ap->next == NULL)
8567 break;
8568 }
8569 }
8570 prev_ap = &ap->next;
8571 }
8572
8573 /*
8574 * Add a new command.
8575 */
8576 if (*cmd != NUL)
8577 {
8578 /*
8579 * If the pattern we want to add a command to does appear at the
8580 * end of the list (or not is not in the list at all), add the
8581 * pattern at the end of the list.
8582 */
8583 if (ap == NULL)
8584 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008585 /* refuse to add buffer-local ap if buffer number is invalid */
8586 if (is_buflocal && (buflocal_nr == 0
8587 || buflist_findnr(buflocal_nr) == NULL))
8588 {
8589 EMSGN(_("E680: <buffer=%d>: invalid buffer number "),
8590 buflocal_nr);
8591 return FAIL;
8592 }
8593
Bram Moolenaar071d4272004-06-13 20:20:40 +00008594 ap = (AutoPat *)alloc((unsigned)sizeof(AutoPat));
8595 if (ap == NULL)
8596 return FAIL;
8597 ap->pat = vim_strnsave(pat, patlen);
8598 ap->patlen = patlen;
8599 if (ap->pat == NULL)
8600 {
8601 vim_free(ap);
8602 return FAIL;
8603 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008604
8605 if (is_buflocal)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008606 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008607 ap->buflocal_nr = buflocal_nr;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008608 ap->reg_prog = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008609 }
8610 else
8611 {
Bram Moolenaar748bf032005-02-02 23:04:36 +00008612 char_u *reg_pat;
8613
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008614 ap->buflocal_nr = 0;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008615 reg_pat = file_pat_to_reg_pat(pat, endpat,
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008616 &ap->allow_dirs, TRUE);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008617 if (reg_pat != NULL)
8618 ap->reg_prog = vim_regcomp(reg_pat, RE_MAGIC);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008619 vim_free(reg_pat);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008620 if (reg_pat == NULL || ap->reg_prog == NULL)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008621 {
8622 vim_free(ap->pat);
8623 vim_free(ap);
8624 return FAIL;
8625 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008626 }
8627 ap->cmds = NULL;
8628 *prev_ap = ap;
8629 ap->next = NULL;
8630 if (group == AUGROUP_ALL)
8631 ap->group = current_augroup;
8632 else
8633 ap->group = group;
8634 }
8635
8636 /*
8637 * Add the autocmd at the end of the AutoCmd list.
8638 */
8639 prev_ac = &(ap->cmds);
8640 while ((ac = *prev_ac) != NULL)
8641 prev_ac = &ac->next;
8642 ac = (AutoCmd *)alloc((unsigned)sizeof(AutoCmd));
8643 if (ac == NULL)
8644 return FAIL;
8645 ac->cmd = vim_strsave(cmd);
8646#ifdef FEAT_EVAL
8647 ac->scriptID = current_SID;
8648#endif
8649 if (ac->cmd == NULL)
8650 {
8651 vim_free(ac);
8652 return FAIL;
8653 }
8654 ac->next = NULL;
8655 *prev_ac = ac;
8656 ac->nested = nested;
8657 }
8658 }
8659
8660 au_cleanup(); /* may really delete removed patterns/commands now */
8661 return OK;
8662}
8663
8664/*
8665 * Implementation of ":doautocmd [group] event [fname]".
8666 * Return OK for success, FAIL for failure;
8667 */
8668 int
8669do_doautocmd(arg, do_msg)
8670 char_u *arg;
8671 int do_msg; /* give message for no matching autocmds? */
8672{
8673 char_u *fname;
8674 int nothing_done = TRUE;
8675 int group;
8676
8677 /*
8678 * Check for a legal group name. If not, use AUGROUP_ALL.
8679 */
8680 group = au_get_grouparg(&arg);
8681 if (arg == NULL) /* out of memory */
8682 return FAIL;
8683
8684 if (*arg == '*')
8685 {
8686 EMSG(_("E217: Can't execute autocommands for ALL events"));
8687 return FAIL;
8688 }
8689
8690 /*
8691 * Scan over the events.
8692 * If we find an illegal name, return here, don't do anything.
8693 */
8694 fname = find_end_event(arg, group != AUGROUP_ALL);
8695 if (fname == NULL)
8696 return FAIL;
8697
8698 fname = skipwhite(fname);
8699
8700 /*
8701 * Loop over the events.
8702 */
8703 while (*arg && !vim_iswhite(*arg))
8704 if (apply_autocmds_group(event_name2nr(arg, &arg),
8705 fname, NULL, TRUE, group, curbuf, NULL))
8706 nothing_done = FALSE;
8707
8708 if (nothing_done && do_msg)
8709 MSG(_("No matching autocommands"));
8710
8711#ifdef FEAT_EVAL
8712 return aborting() ? FAIL : OK;
8713#else
8714 return OK;
8715#endif
8716}
8717
8718/*
8719 * ":doautoall": execute autocommands for each loaded buffer.
8720 */
8721 void
8722ex_doautoall(eap)
8723 exarg_T *eap;
8724{
8725 int retval;
8726 aco_save_T aco;
8727 buf_T *buf;
8728
8729 /*
8730 * This is a bit tricky: For some commands curwin->w_buffer needs to be
8731 * equal to curbuf, but for some buffers there may not be a window.
8732 * So we change the buffer for the current window for a moment. This
8733 * gives problems when the autocommands make changes to the list of
8734 * buffers or windows...
8735 */
8736 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8737 {
Bram Moolenaar3a847972008-07-08 09:36:58 +00008738 if (buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008739 {
8740 /* find a window for this buffer and save some values */
8741 aucmd_prepbuf(&aco, buf);
8742
8743 /* execute the autocommands for this buffer */
8744 retval = do_doautocmd(eap->arg, FALSE);
Bram Moolenaareeefcc72007-05-01 21:21:21 +00008745
8746 /* Execute the modeline settings, but don't set window-local
8747 * options if we are using the current window for another buffer. */
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008748 do_modelines(curwin == aucmd_win ? OPT_NOWIN : 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008749
8750 /* restore the current window */
8751 aucmd_restbuf(&aco);
8752
8753 /* stop if there is some error or buffer was deleted */
8754 if (retval == FAIL || !buf_valid(buf))
8755 break;
8756 }
8757 }
8758
8759 check_cursor(); /* just in case lines got deleted */
8760}
8761
8762/*
8763 * Prepare for executing autocommands for (hidden) buffer "buf".
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008764 * Search for a visible window containing the current buffer. If there isn't
8765 * one then use "aucmd_win".
Bram Moolenaar071d4272004-06-13 20:20:40 +00008766 * Set "curbuf" and "curwin" to match "buf".
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00008767 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008768 */
8769 void
8770aucmd_prepbuf(aco, buf)
8771 aco_save_T *aco; /* structure to save values in */
8772 buf_T *buf; /* new curbuf */
8773{
8774 win_T *win;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008775#ifdef FEAT_WINDOWS
8776 int save_ea;
8777#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008778
8779 /* Find a window that is for the new buffer */
8780 if (buf == curbuf) /* be quick when buf is curbuf */
8781 win = curwin;
8782 else
8783#ifdef FEAT_WINDOWS
8784 for (win = firstwin; win != NULL; win = win->w_next)
8785 if (win->w_buffer == buf)
8786 break;
8787#else
8788 win = NULL;
8789#endif
8790
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008791 /* Allocate "aucmd_win" when needed. If this fails (out of memory) fall
8792 * back to using the current window. */
8793 if (win == NULL && aucmd_win == NULL)
8794 {
8795 win_alloc_aucmd_win();
8796 if (aucmd_win == NULL)
8797 win = curwin;
8798 }
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008799 if (win == NULL && aucmd_win_used)
8800 /* Strange recursive autocommand, fall back to using the current
8801 * window. Expect a few side effects... */
8802 win = curwin;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008803
8804 aco->save_curwin = curwin;
8805 aco->save_curbuf = curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008806 if (win != NULL)
8807 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008808 /* There is a window for "buf" in the current tab page, make it the
8809 * curwin. This is preferred, it has the least side effects (esp. if
8810 * "buf" is curbuf). */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008811 aco->use_aucmd_win = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008812 curwin = win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008813 }
8814 else
8815 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008816 /* There is no window for "buf", use "aucmd_win". To minimize the side
8817 * effects, insert it in a the current tab page.
8818 * Anything related to a window (e.g., setting folds) may have
8819 * unexpected results. */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008820 aco->use_aucmd_win = TRUE;
8821 aucmd_win_used = TRUE;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008822 aucmd_win->w_buffer = buf;
Bram Moolenaarcdddaa42010-06-07 23:07:44 +02008823 aucmd_win->w_s = &buf->b_s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008824 ++buf->b_nwindows;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008825 win_init_empty(aucmd_win); /* set cursor and topline to safe values */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008826 vim_free(aucmd_win->w_localdir);
8827 aucmd_win->w_localdir = NULL;
8828
8829 /* Make sure w_localdir and globaldir are NULL to avoid a chdir() in
8830 * win_enter_ext(). */
8831 aucmd_win->w_localdir = NULL;
8832 aco->globaldir = globaldir;
8833 globaldir = NULL;
8834
Bram Moolenaar071d4272004-06-13 20:20:40 +00008835
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008836#ifdef FEAT_WINDOWS
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008837 /* Split the current window, put the aucmd_win in the upper half.
8838 * We don't want the BufEnter or WinEnter autocommands. */
8839 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008840 make_snapshot(SNAP_AUCMD_IDX);
8841 save_ea = p_ea;
8842 p_ea = FALSE;
8843 (void)win_split_ins(0, WSP_TOP, aucmd_win, 0);
8844 (void)win_comp_pos(); /* recompute window positions */
8845 p_ea = save_ea;
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008846 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008847#endif
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008848 curwin = aucmd_win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008849 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008850 curbuf = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008851 aco->new_curwin = curwin;
8852 aco->new_curbuf = curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008853}
8854
8855/*
8856 * Cleanup after executing autocommands for a (hidden) buffer.
8857 * Restore the window as it was (if possible).
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00008858 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008859 */
8860 void
8861aucmd_restbuf(aco)
8862 aco_save_T *aco; /* structure holding saved values */
8863{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008864#ifdef FEAT_WINDOWS
8865 int dummy;
8866#endif
8867
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008868 if (aco->use_aucmd_win)
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008869 {
8870 --curbuf->b_nwindows;
8871#ifdef FEAT_WINDOWS
8872 /* Find "aucmd_win", it can't be closed, but it may be in another tab
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008873 * page. Do not trigger autocommands here. */
8874 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008875 if (curwin != aucmd_win)
8876 {
8877 tabpage_T *tp;
8878 win_T *wp;
8879
8880 FOR_ALL_TAB_WINDOWS(tp, wp)
8881 {
8882 if (wp == aucmd_win)
8883 {
8884 if (tp != curtab)
8885 goto_tabpage_tp(tp);
8886 win_goto(aucmd_win);
8887 break;
8888 }
8889 }
8890 }
8891
8892 /* Remove the window and frame from the tree of frames. */
8893 (void)winframe_remove(curwin, &dummy, NULL);
8894 win_remove(curwin, NULL);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008895 aucmd_win_used = FALSE;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008896 last_status(FALSE); /* may need to remove last status line */
8897 restore_snapshot(SNAP_AUCMD_IDX, FALSE);
8898 (void)win_comp_pos(); /* recompute window positions */
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008899 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008900
8901 if (win_valid(aco->save_curwin))
8902 curwin = aco->save_curwin;
8903 else
8904 /* Hmm, original window disappeared. Just use the first one. */
8905 curwin = firstwin;
8906# ifdef FEAT_EVAL
8907 vars_clear(&aucmd_win->w_vars.dv_hashtab); /* free all w: variables */
Bram Moolenaar50daf402009-11-17 13:57:22 +00008908 hash_init(&aucmd_win->w_vars.dv_hashtab); /* re-use the hashtab */
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008909# endif
8910#else
8911 curwin = aco->save_curwin;
8912#endif
8913 curbuf = curwin->w_buffer;
8914
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008915 vim_free(globaldir);
8916 globaldir = aco->globaldir;
8917
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008918 /* the buffer contents may have changed */
8919 check_cursor();
8920 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
8921 {
8922 curwin->w_topline = curbuf->b_ml.ml_line_count;
8923#ifdef FEAT_DIFF
8924 curwin->w_topfill = 0;
8925#endif
8926 }
8927#if defined(FEAT_GUI)
8928 /* Hide the scrollbars from the aucmd_win and update. */
8929 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_LEFT], FALSE);
8930 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_RIGHT], FALSE);
8931 gui_may_update_scrollbars();
8932#endif
8933 }
8934 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00008935 {
8936 /* restore curwin */
8937#ifdef FEAT_WINDOWS
8938 if (win_valid(aco->save_curwin))
8939#endif
8940 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008941 /* Restore the buffer which was previously edited by curwin, if
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008942 * it was changed, we are still the same window and the buffer is
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008943 * valid. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008944 if (curwin == aco->new_curwin
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008945 && curbuf != aco->new_curbuf
8946 && buf_valid(aco->new_curbuf)
8947 && aco->new_curbuf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008948 {
8949 --curbuf->b_nwindows;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008950 curbuf = aco->new_curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008951 curwin->w_buffer = curbuf;
8952 ++curbuf->b_nwindows;
8953 }
8954
8955 curwin = aco->save_curwin;
8956 curbuf = curwin->w_buffer;
8957 }
8958 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008959}
8960
8961static int autocmd_nested = FALSE;
8962
8963/*
8964 * Execute autocommands for "event" and file name "fname".
8965 * Return TRUE if some commands were executed.
8966 */
8967 int
8968apply_autocmds(event, fname, fname_io, force, buf)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008969 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008970 char_u *fname; /* NULL or empty means use actual file name */
8971 char_u *fname_io; /* fname to use for <afile> on cmdline */
8972 int force; /* when TRUE, ignore autocmd_busy */
8973 buf_T *buf; /* buffer for <abuf> */
8974{
8975 return apply_autocmds_group(event, fname, fname_io, force,
8976 AUGROUP_ALL, buf, NULL);
8977}
8978
8979/*
8980 * Like apply_autocmds(), but with extra "eap" argument. This takes care of
8981 * setting v:filearg.
8982 */
8983 static int
8984apply_autocmds_exarg(event, fname, fname_io, force, buf, eap)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008985 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008986 char_u *fname;
8987 char_u *fname_io;
8988 int force;
8989 buf_T *buf;
8990 exarg_T *eap;
8991{
8992 return apply_autocmds_group(event, fname, fname_io, force,
8993 AUGROUP_ALL, buf, eap);
8994}
8995
8996/*
8997 * Like apply_autocmds(), but handles the caller's retval. If the script
8998 * processing is being aborted or if retval is FAIL when inside a try
8999 * conditional, no autocommands are executed. If otherwise the autocommands
9000 * cause the script to be aborted, retval is set to FAIL.
9001 */
9002 int
9003apply_autocmds_retval(event, fname, fname_io, force, buf, retval)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009004 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009005 char_u *fname; /* NULL or empty means use actual file name */
9006 char_u *fname_io; /* fname to use for <afile> on cmdline */
9007 int force; /* when TRUE, ignore autocmd_busy */
9008 buf_T *buf; /* buffer for <abuf> */
9009 int *retval; /* pointer to caller's retval */
9010{
9011 int did_cmd;
9012
Bram Moolenaar1e015462005-09-25 22:16:38 +00009013#ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00009014 if (should_abort(*retval))
9015 return FALSE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00009016#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009017
9018 did_cmd = apply_autocmds_group(event, fname, fname_io, force,
9019 AUGROUP_ALL, buf, NULL);
Bram Moolenaar1e015462005-09-25 22:16:38 +00009020 if (did_cmd
9021#ifdef FEAT_EVAL
9022 && aborting()
9023#endif
9024 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00009025 *retval = FAIL;
9026 return did_cmd;
9027}
9028
Bram Moolenaard35f9712005-12-18 22:02:33 +00009029/*
9030 * Return TRUE when there is a CursorHold autocommand defined.
9031 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009032 int
9033has_cursorhold()
9034{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009035 return (first_autopat[(int)(get_real_state() == NORMAL_BUSY
9036 ? EVENT_CURSORHOLD : EVENT_CURSORHOLDI)] != NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009037}
Bram Moolenaard35f9712005-12-18 22:02:33 +00009038
9039/*
9040 * Return TRUE if the CursorHold event can be triggered.
9041 */
9042 int
9043trigger_cursorhold()
9044{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009045 int state;
9046
Bram Moolenaard29a9ee2006-09-14 09:07:34 +00009047 if (!did_cursorhold && has_cursorhold() && !Recording
9048#ifdef FEAT_INS_EXPAND
9049 && !ins_compl_active()
9050#endif
9051 )
Bram Moolenaar754b5602006-02-09 23:53:20 +00009052 {
9053 state = get_real_state();
9054 if (state == NORMAL_BUSY || (state & INSERT) != 0)
9055 return TRUE;
9056 }
9057 return FALSE;
Bram Moolenaard35f9712005-12-18 22:02:33 +00009058}
Bram Moolenaar754b5602006-02-09 23:53:20 +00009059
9060/*
9061 * Return TRUE when there is a CursorMoved autocommand defined.
9062 */
9063 int
9064has_cursormoved()
9065{
9066 return (first_autopat[(int)EVENT_CURSORMOVED] != NULL);
9067}
9068
9069/*
9070 * Return TRUE when there is a CursorMovedI autocommand defined.
9071 */
9072 int
9073has_cursormovedI()
9074{
9075 return (first_autopat[(int)EVENT_CURSORMOVEDI] != NULL);
9076}
Bram Moolenaar071d4272004-06-13 20:20:40 +00009077
9078 static int
9079apply_autocmds_group(event, fname, fname_io, force, group, buf, eap)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009080 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009081 char_u *fname; /* NULL or empty means use actual file name */
9082 char_u *fname_io; /* fname to use for <afile> on cmdline, NULL means
9083 use fname */
9084 int force; /* when TRUE, ignore autocmd_busy */
9085 int group; /* group ID, or AUGROUP_ALL */
9086 buf_T *buf; /* buffer for <abuf> */
9087 exarg_T *eap; /* command arguments */
9088{
9089 char_u *sfname = NULL; /* short file name */
9090 char_u *tail;
9091 int save_changed;
9092 buf_T *old_curbuf;
9093 int retval = FALSE;
9094 char_u *save_sourcing_name;
9095 linenr_T save_sourcing_lnum;
9096 char_u *save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009097 int save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009098 int save_autocmd_bufnr;
9099 char_u *save_autocmd_match;
9100 int save_autocmd_busy;
9101 int save_autocmd_nested;
9102 static int nesting = 0;
9103 AutoPatCmd patcmd;
9104 AutoPat *ap;
9105#ifdef FEAT_EVAL
9106 scid_T save_current_SID;
9107 void *save_funccalp;
9108 char_u *save_cmdarg;
9109 long save_cmdbang;
9110#endif
9111 static int filechangeshell_busy = FALSE;
Bram Moolenaar05159a02005-02-26 23:04:13 +00009112#ifdef FEAT_PROFILE
9113 proftime_T wait_time;
9114#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009115
9116 /*
9117 * Quickly return if there are no autocommands for this event or
9118 * autocommands are blocked.
9119 */
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009120 if (first_autopat[(int)event] == NULL || autocmd_blocked > 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009121 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009122
9123 /*
9124 * When autocommands are busy, new autocommands are only executed when
9125 * explicitly enabled with the "nested" flag.
9126 */
9127 if (autocmd_busy && !(force || autocmd_nested))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009128 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009129
9130#ifdef FEAT_EVAL
9131 /*
Bram Moolenaar7263a772007-05-10 17:35:54 +00009132 * Quickly return when immediately aborting on error, or when an interrupt
Bram Moolenaar071d4272004-06-13 20:20:40 +00009133 * occurred or an exception was thrown but not caught.
9134 */
9135 if (aborting())
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009136 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009137#endif
9138
9139 /*
9140 * FileChangedShell never nests, because it can create an endless loop.
9141 */
Bram Moolenaar56718732006-03-15 22:53:57 +00009142 if (filechangeshell_busy && (event == EVENT_FILECHANGEDSHELL
9143 || event == EVENT_FILECHANGEDSHELLPOST))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009144 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009145
9146 /*
9147 * Ignore events in 'eventignore'.
9148 */
9149 if (event_ignored(event))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009150 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009151
9152 /*
9153 * Allow nesting of autocommands, but restrict the depth, because it's
9154 * possible to create an endless loop.
9155 */
9156 if (nesting == 10)
9157 {
9158 EMSG(_("E218: autocommand nesting too deep"));
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009159 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009160 }
9161
9162 /*
9163 * Check if these autocommands are disabled. Used when doing ":all" or
9164 * ":ball".
9165 */
9166 if ( (autocmd_no_enter
9167 && (event == EVENT_WINENTER || event == EVENT_BUFENTER))
9168 || (autocmd_no_leave
9169 && (event == EVENT_WINLEAVE || event == EVENT_BUFLEAVE)))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009170 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009171
9172 /*
9173 * Save the autocmd_* variables and info about the current buffer.
9174 */
9175 save_autocmd_fname = autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009176 save_autocmd_fname_full = autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009177 save_autocmd_bufnr = autocmd_bufnr;
9178 save_autocmd_match = autocmd_match;
9179 save_autocmd_busy = autocmd_busy;
9180 save_autocmd_nested = autocmd_nested;
9181 save_changed = curbuf->b_changed;
9182 old_curbuf = curbuf;
9183
9184 /*
9185 * Set the file name to be used for <afile>.
Bram Moolenaara0174af2008-01-02 20:08:25 +00009186 * Make a copy to avoid that changing a buffer name or directory makes it
9187 * invalid.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009188 */
9189 if (fname_io == NULL)
9190 {
9191 if (fname != NULL && *fname != NUL)
9192 autocmd_fname = fname;
9193 else if (buf != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009194 autocmd_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009195 else
9196 autocmd_fname = NULL;
9197 }
9198 else
9199 autocmd_fname = fname_io;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009200 if (autocmd_fname != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009201 autocmd_fname = vim_strsave(autocmd_fname);
9202 autocmd_fname_full = FALSE; /* call FullName_save() later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009203
9204 /*
9205 * Set the buffer number to be used for <abuf>.
9206 */
9207 if (buf == NULL)
9208 autocmd_bufnr = 0;
9209 else
9210 autocmd_bufnr = buf->b_fnum;
9211
9212 /*
9213 * When the file name is NULL or empty, use the file name of buffer "buf".
9214 * Always use the full path of the file name to match with, in case
9215 * "allow_dirs" is set.
9216 */
9217 if (fname == NULL || *fname == NUL)
9218 {
9219 if (buf == NULL)
9220 fname = NULL;
9221 else
9222 {
9223#ifdef FEAT_SYN_HL
9224 if (event == EVENT_SYNTAX)
9225 fname = buf->b_p_syn;
9226 else
9227#endif
9228 if (event == EVENT_FILETYPE)
9229 fname = buf->b_p_ft;
9230 else
9231 {
9232 if (buf->b_sfname != NULL)
9233 sfname = vim_strsave(buf->b_sfname);
9234 fname = buf->b_ffname;
9235 }
9236 }
9237 if (fname == NULL)
9238 fname = (char_u *)"";
9239 fname = vim_strsave(fname); /* make a copy, so we can change it */
9240 }
9241 else
9242 {
9243 sfname = vim_strsave(fname);
Bram Moolenaar5135d462009-04-29 16:03:38 +00009244 /* Don't try expanding FileType, Syntax, FuncUndefined, WindowID or
9245 * QuickFixCmd* */
Bram Moolenaar7c626922005-02-07 22:01:03 +00009246 if (event == EVENT_FILETYPE
9247 || event == EVENT_SYNTAX
Bram Moolenaar5135d462009-04-29 16:03:38 +00009248 || event == EVENT_FUNCUNDEFINED
Bram Moolenaar7c626922005-02-07 22:01:03 +00009249 || event == EVENT_REMOTEREPLY
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00009250 || event == EVENT_SPELLFILEMISSING
Bram Moolenaar7c626922005-02-07 22:01:03 +00009251 || event == EVENT_QUICKFIXCMDPRE
9252 || event == EVENT_QUICKFIXCMDPOST)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009253 fname = vim_strsave(fname);
9254 else
9255 fname = FullName_save(fname, FALSE);
9256 }
9257 if (fname == NULL) /* out of memory */
9258 {
9259 vim_free(sfname);
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009260 retval = FALSE;
9261 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009262 }
9263
9264#ifdef BACKSLASH_IN_FILENAME
9265 /*
9266 * Replace all backslashes with forward slashes. This makes the
9267 * autocommand patterns portable between Unix and MS-DOS.
9268 */
9269 if (sfname != NULL)
9270 forward_slash(sfname);
9271 forward_slash(fname);
9272#endif
9273
9274#ifdef VMS
9275 /* remove version for correct match */
9276 if (sfname != NULL)
9277 vms_remove_version(sfname);
9278 vms_remove_version(fname);
9279#endif
9280
9281 /*
9282 * Set the name to be used for <amatch>.
9283 */
9284 autocmd_match = fname;
9285
9286
9287 /* Don't redraw while doing auto commands. */
9288 ++RedrawingDisabled;
9289 save_sourcing_name = sourcing_name;
9290 sourcing_name = NULL; /* don't free this one */
9291 save_sourcing_lnum = sourcing_lnum;
9292 sourcing_lnum = 0; /* no line number here */
9293
9294#ifdef FEAT_EVAL
9295 save_current_SID = current_SID;
9296
Bram Moolenaar05159a02005-02-26 23:04:13 +00009297# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009298 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009299 prof_child_enter(&wait_time); /* doesn't count for the caller itself */
9300# endif
9301
Bram Moolenaar071d4272004-06-13 20:20:40 +00009302 /* Don't use local function variables, if called from a function */
9303 save_funccalp = save_funccal();
9304#endif
9305
9306 /*
9307 * When starting to execute autocommands, save the search patterns.
9308 */
9309 if (!autocmd_busy)
9310 {
9311 save_search_patterns();
9312 saveRedobuff();
9313 did_filetype = keep_filetype;
9314 }
9315
9316 /*
9317 * Note that we are applying autocmds. Some commands need to know.
9318 */
9319 autocmd_busy = TRUE;
9320 filechangeshell_busy = (event == EVENT_FILECHANGEDSHELL);
9321 ++nesting; /* see matching decrement below */
9322
9323 /* Remember that FileType was triggered. Used for did_filetype(). */
9324 if (event == EVENT_FILETYPE)
9325 did_filetype = TRUE;
9326
9327 tail = gettail(fname);
9328
9329 /* Find first autocommand that matches */
9330 patcmd.curpat = first_autopat[(int)event];
9331 patcmd.nextcmd = NULL;
9332 patcmd.group = group;
9333 patcmd.fname = fname;
9334 patcmd.sfname = sfname;
9335 patcmd.tail = tail;
9336 patcmd.event = event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009337 patcmd.arg_bufnr = autocmd_bufnr;
9338 patcmd.next = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009339 auto_next_pat(&patcmd, FALSE);
9340
9341 /* found one, start executing the autocommands */
9342 if (patcmd.curpat != NULL)
9343 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009344 /* add to active_apc_list */
9345 patcmd.next = active_apc_list;
9346 active_apc_list = &patcmd;
9347
Bram Moolenaar071d4272004-06-13 20:20:40 +00009348#ifdef FEAT_EVAL
9349 /* set v:cmdarg (only when there is a matching pattern) */
9350 save_cmdbang = get_vim_var_nr(VV_CMDBANG);
9351 if (eap != NULL)
9352 {
9353 save_cmdarg = set_cmdarg(eap, NULL);
9354 set_vim_var_nr(VV_CMDBANG, (long)eap->forceit);
9355 }
9356 else
9357 save_cmdarg = NULL; /* avoid gcc warning */
9358#endif
9359 retval = TRUE;
9360 /* mark the last pattern, to avoid an endless loop when more patterns
9361 * are added when executing autocommands */
9362 for (ap = patcmd.curpat; ap->next != NULL; ap = ap->next)
9363 ap->last = FALSE;
9364 ap->last = TRUE;
9365 check_lnums(TRUE); /* make sure cursor and topline are valid */
9366 do_cmdline(NULL, getnextac, (void *)&patcmd,
9367 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
9368#ifdef FEAT_EVAL
9369 if (eap != NULL)
9370 {
9371 (void)set_cmdarg(NULL, save_cmdarg);
9372 set_vim_var_nr(VV_CMDBANG, save_cmdbang);
9373 }
9374#endif
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009375 /* delete from active_apc_list */
9376 if (active_apc_list == &patcmd) /* just in case */
9377 active_apc_list = patcmd.next;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009378 }
9379
9380 --RedrawingDisabled;
9381 autocmd_busy = save_autocmd_busy;
9382 filechangeshell_busy = FALSE;
9383 autocmd_nested = save_autocmd_nested;
9384 vim_free(sourcing_name);
9385 sourcing_name = save_sourcing_name;
9386 sourcing_lnum = save_sourcing_lnum;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009387 vim_free(autocmd_fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009388 autocmd_fname = save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009389 autocmd_fname_full = save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009390 autocmd_bufnr = save_autocmd_bufnr;
9391 autocmd_match = save_autocmd_match;
9392#ifdef FEAT_EVAL
9393 current_SID = save_current_SID;
9394 restore_funccal(save_funccalp);
Bram Moolenaar05159a02005-02-26 23:04:13 +00009395# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009396 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009397 prof_child_exit(&wait_time);
9398# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009399#endif
9400 vim_free(fname);
9401 vim_free(sfname);
9402 --nesting; /* see matching increment above */
9403
9404 /*
9405 * When stopping to execute autocommands, restore the search patterns and
9406 * the redo buffer.
9407 */
9408 if (!autocmd_busy)
9409 {
9410 restore_search_patterns();
9411 restoreRedobuff();
9412 did_filetype = FALSE;
9413 }
9414
9415 /*
9416 * Some events don't set or reset the Changed flag.
9417 * Check if still in the same buffer!
9418 */
9419 if (curbuf == old_curbuf
9420 && (event == EVENT_BUFREADPOST
9421 || event == EVENT_BUFWRITEPOST
9422 || event == EVENT_FILEAPPENDPOST
9423 || event == EVENT_VIMLEAVE
9424 || event == EVENT_VIMLEAVEPRE))
9425 {
9426#ifdef FEAT_TITLE
9427 if (curbuf->b_changed != save_changed)
9428 need_maketitle = TRUE;
9429#endif
9430 curbuf->b_changed = save_changed;
9431 }
9432
9433 au_cleanup(); /* may really delete removed patterns/commands now */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009434
9435BYPASS_AU:
9436 /* When wiping out a buffer make sure all its buffer-local autocommands
9437 * are deleted. */
9438 if (event == EVENT_BUFWIPEOUT && buf != NULL)
9439 aubuflocal_remove(buf);
9440
Bram Moolenaar071d4272004-06-13 20:20:40 +00009441 return retval;
9442}
9443
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009444# ifdef FEAT_EVAL
9445static char_u *old_termresponse = NULL;
9446# endif
9447
9448/*
9449 * Block triggering autocommands until unblock_autocmd() is called.
9450 * Can be used recursively, so long as it's symmetric.
9451 */
9452 void
9453block_autocmds()
9454{
9455# ifdef FEAT_EVAL
9456 /* Remember the value of v:termresponse. */
9457 if (autocmd_blocked == 0)
9458 old_termresponse = get_vim_var_str(VV_TERMRESPONSE);
9459# endif
9460 ++autocmd_blocked;
9461}
9462
9463 void
9464unblock_autocmds()
9465{
9466 --autocmd_blocked;
9467
9468# ifdef FEAT_EVAL
9469 /* When v:termresponse was set while autocommands were blocked, trigger
9470 * the autocommands now. Esp. useful when executing a shell command
9471 * during startup (vimdiff). */
9472 if (autocmd_blocked == 0
9473 && get_vim_var_str(VV_TERMRESPONSE) != old_termresponse)
9474 apply_autocmds(EVENT_TERMRESPONSE, NULL, NULL, FALSE, curbuf);
9475# endif
9476}
9477
Bram Moolenaar071d4272004-06-13 20:20:40 +00009478/*
9479 * Find next autocommand pattern that matches.
9480 */
9481 static void
9482auto_next_pat(apc, stop_at_last)
9483 AutoPatCmd *apc;
9484 int stop_at_last; /* stop when 'last' flag is set */
9485{
9486 AutoPat *ap;
9487 AutoCmd *cp;
9488 char_u *name;
9489 char *s;
9490
9491 vim_free(sourcing_name);
9492 sourcing_name = NULL;
9493
9494 for (ap = apc->curpat; ap != NULL && !got_int; ap = ap->next)
9495 {
9496 apc->curpat = NULL;
9497
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009498 /* Only use a pattern when it has not been removed, has commands and
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009499 * the group matches. For buffer-local autocommands only check the
9500 * buffer number. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009501 if (ap->pat != NULL && ap->cmds != NULL
9502 && (apc->group == AUGROUP_ALL || apc->group == ap->group))
9503 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009504 /* execution-condition */
9505 if (ap->buflocal_nr == 0
Bram Moolenaar748bf032005-02-02 23:04:36 +00009506 ? (match_file_pat(NULL, ap->reg_prog, apc->fname,
9507 apc->sfname, apc->tail, ap->allow_dirs))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009508 : ap->buflocal_nr == apc->arg_bufnr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009509 {
9510 name = event_nr2name(apc->event);
9511 s = _("%s Auto commands for \"%s\"");
9512 sourcing_name = alloc((unsigned)(STRLEN(s)
9513 + STRLEN(name) + ap->patlen + 1));
9514 if (sourcing_name != NULL)
9515 {
9516 sprintf((char *)sourcing_name, s,
9517 (char *)name, (char *)ap->pat);
9518 if (p_verbose >= 8)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009519 {
9520 verbose_enter();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009521 smsg((char_u *)_("Executing %s"), sourcing_name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009522 verbose_leave();
9523 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009524 }
9525
9526 apc->curpat = ap;
9527 apc->nextcmd = ap->cmds;
9528 /* mark last command */
9529 for (cp = ap->cmds; cp->next != NULL; cp = cp->next)
9530 cp->last = FALSE;
9531 cp->last = TRUE;
9532 }
9533 line_breakcheck();
9534 if (apc->curpat != NULL) /* found a match */
9535 break;
9536 }
9537 if (stop_at_last && ap->last)
9538 break;
9539 }
9540}
9541
9542/*
9543 * Get next autocommand command.
9544 * Called by do_cmdline() to get the next line for ":if".
9545 * Returns allocated string, or NULL for end of autocommands.
9546 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009547 static char_u *
9548getnextac(c, cookie, indent)
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009549 int c UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009550 void *cookie;
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009551 int indent UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009552{
9553 AutoPatCmd *acp = (AutoPatCmd *)cookie;
9554 char_u *retval;
9555 AutoCmd *ac;
9556
9557 /* Can be called again after returning the last line. */
9558 if (acp->curpat == NULL)
9559 return NULL;
9560
9561 /* repeat until we find an autocommand to execute */
9562 for (;;)
9563 {
9564 /* skip removed commands */
9565 while (acp->nextcmd != NULL && acp->nextcmd->cmd == NULL)
9566 if (acp->nextcmd->last)
9567 acp->nextcmd = NULL;
9568 else
9569 acp->nextcmd = acp->nextcmd->next;
9570
9571 if (acp->nextcmd != NULL)
9572 break;
9573
9574 /* at end of commands, find next pattern that matches */
9575 if (acp->curpat->last)
9576 acp->curpat = NULL;
9577 else
9578 acp->curpat = acp->curpat->next;
9579 if (acp->curpat != NULL)
9580 auto_next_pat(acp, TRUE);
9581 if (acp->curpat == NULL)
9582 return NULL;
9583 }
9584
9585 ac = acp->nextcmd;
9586
9587 if (p_verbose >= 9)
9588 {
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009589 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009590 smsg((char_u *)_("autocommand %s"), ac->cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009591 msg_puts((char_u *)"\n"); /* don't overwrite this either */
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009592 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009593 }
9594 retval = vim_strsave(ac->cmd);
9595 autocmd_nested = ac->nested;
9596#ifdef FEAT_EVAL
9597 current_SID = ac->scriptID;
9598#endif
9599 if (ac->last)
9600 acp->nextcmd = NULL;
9601 else
9602 acp->nextcmd = ac->next;
9603 return retval;
9604}
9605
9606/*
9607 * Return TRUE if there is a matching autocommand for "fname".
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009608 * To account for buffer-local autocommands, function needs to know
9609 * in which buffer the file will be opened.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009610 */
9611 int
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009612has_autocmd(event, sfname, buf)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009613 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009614 char_u *sfname;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009615 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009616{
9617 AutoPat *ap;
9618 char_u *fname;
9619 char_u *tail = gettail(sfname);
9620 int retval = FALSE;
9621
9622 fname = FullName_save(sfname, FALSE);
9623 if (fname == NULL)
9624 return FALSE;
9625
9626#ifdef BACKSLASH_IN_FILENAME
9627 /*
9628 * Replace all backslashes with forward slashes. This makes the
9629 * autocommand patterns portable between Unix and MS-DOS.
9630 */
9631 sfname = vim_strsave(sfname);
9632 if (sfname != NULL)
9633 forward_slash(sfname);
9634 forward_slash(fname);
9635#endif
9636
9637 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
9638 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009639 && (ap->buflocal_nr == 0
Bram Moolenaar748bf032005-02-02 23:04:36 +00009640 ? match_file_pat(NULL, ap->reg_prog,
9641 fname, sfname, tail, ap->allow_dirs)
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009642 : buf != NULL && ap->buflocal_nr == buf->b_fnum
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009643 ))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009644 {
9645 retval = TRUE;
9646 break;
9647 }
9648
9649 vim_free(fname);
9650#ifdef BACKSLASH_IN_FILENAME
9651 vim_free(sfname);
9652#endif
9653
9654 return retval;
9655}
9656
9657#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
9658/*
9659 * Function given to ExpandGeneric() to obtain the list of autocommand group
9660 * names.
9661 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009662 char_u *
9663get_augroup_name(xp, idx)
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009664 expand_T *xp UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009665 int idx;
9666{
9667 if (idx == augroups.ga_len) /* add "END" add the end */
9668 return (char_u *)"END";
9669 if (idx >= augroups.ga_len) /* end of list */
9670 return NULL;
9671 if (AUGROUP_NAME(idx) == NULL) /* skip deleted entries */
9672 return (char_u *)"";
9673 return AUGROUP_NAME(idx); /* return a name */
9674}
9675
9676static int include_groups = FALSE;
9677
9678 char_u *
9679set_context_in_autocmd(xp, arg, doautocmd)
9680 expand_T *xp;
9681 char_u *arg;
Bram Moolenaard812df62008-11-09 12:46:09 +00009682 int doautocmd; /* TRUE for :doauto*, FALSE for :autocmd */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009683{
9684 char_u *p;
9685 int group;
9686
9687 /* check for a group name, skip it if present */
9688 include_groups = FALSE;
9689 p = arg;
9690 group = au_get_grouparg(&arg);
9691 if (group == AUGROUP_ERROR)
9692 return NULL;
9693 /* If there only is a group name that's what we expand. */
9694 if (*arg == NUL && group != AUGROUP_ALL && !vim_iswhite(arg[-1]))
9695 {
9696 arg = p;
9697 group = AUGROUP_ALL;
9698 }
9699
9700 /* skip over event name */
9701 for (p = arg; *p != NUL && !vim_iswhite(*p); ++p)
9702 if (*p == ',')
9703 arg = p + 1;
9704 if (*p == NUL)
9705 {
9706 if (group == AUGROUP_ALL)
9707 include_groups = TRUE;
9708 xp->xp_context = EXPAND_EVENTS; /* expand event name */
9709 xp->xp_pattern = arg;
9710 return NULL;
9711 }
9712
9713 /* skip over pattern */
9714 arg = skipwhite(p);
9715 while (*arg && (!vim_iswhite(*arg) || arg[-1] == '\\'))
9716 arg++;
9717 if (*arg)
9718 return arg; /* expand (next) command */
9719
9720 if (doautocmd)
9721 xp->xp_context = EXPAND_FILES; /* expand file names */
9722 else
9723 xp->xp_context = EXPAND_NOTHING; /* pattern is not expanded */
9724 return NULL;
9725}
9726
9727/*
9728 * Function given to ExpandGeneric() to obtain the list of event names.
9729 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009730 char_u *
9731get_event_name(xp, idx)
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009732 expand_T *xp UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009733 int idx;
9734{
9735 if (idx < augroups.ga_len) /* First list group names, if wanted */
9736 {
9737 if (!include_groups || AUGROUP_NAME(idx) == NULL)
9738 return (char_u *)""; /* skip deleted entries */
9739 return AUGROUP_NAME(idx); /* return a name */
9740 }
9741 return (char_u *)event_names[idx - augroups.ga_len].name;
9742}
9743
9744#endif /* FEAT_CMDL_COMPL */
9745
9746/*
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009747 * Return TRUE if autocmd is supported.
9748 */
9749 int
9750autocmd_supported(name)
9751 char_u *name;
9752{
9753 char_u *p;
9754
9755 return (event_name2nr(name, &p) != NUM_EVENTS);
9756}
9757
9758/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00009759 * Return TRUE if an autocommand is defined for a group, event and
9760 * pattern: The group can be omitted to accept any group. "event" and "pattern"
9761 * can be NULL to accept any event and pattern. "pattern" can be NULL to accept
9762 * any pattern. Buffer-local patterns <buffer> or <buffer=N> are accepted.
9763 * Used for:
9764 * exists("#Group") or
9765 * exists("#Group#Event") or
9766 * exists("#Group#Event#pat") or
9767 * exists("#Event") or
9768 * exists("#Event#pat")
Bram Moolenaar071d4272004-06-13 20:20:40 +00009769 */
9770 int
Bram Moolenaar195d6352005-12-19 22:08:24 +00009771au_exists(arg)
9772 char_u *arg;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009773{
Bram Moolenaar195d6352005-12-19 22:08:24 +00009774 char_u *arg_save;
9775 char_u *pattern = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009776 char_u *event_name;
9777 char_u *p;
Bram Moolenaar754b5602006-02-09 23:53:20 +00009778 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009779 AutoPat *ap;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009780 buf_T *buflocal_buf = NULL;
Bram Moolenaar195d6352005-12-19 22:08:24 +00009781 int group;
9782 int retval = FALSE;
9783
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009784 /* Make a copy so that we can change the '#' chars to a NUL. */
Bram Moolenaar195d6352005-12-19 22:08:24 +00009785 arg_save = vim_strsave(arg);
9786 if (arg_save == NULL)
9787 return FALSE;
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009788 p = vim_strchr(arg_save, '#');
Bram Moolenaar195d6352005-12-19 22:08:24 +00009789 if (p != NULL)
9790 *p++ = NUL;
9791
9792 /* First, look for an autocmd group name */
9793 group = au_find_group(arg_save);
9794 if (group == AUGROUP_ERROR)
9795 {
9796 /* Didn't match a group name, assume the first argument is an event. */
9797 group = AUGROUP_ALL;
9798 event_name = arg_save;
9799 }
9800 else
9801 {
9802 if (p == NULL)
9803 {
9804 /* "Group": group name is present and it's recognized */
9805 retval = TRUE;
9806 goto theend;
9807 }
9808
9809 /* Must be "Group#Event" or "Group#Event#pat". */
9810 event_name = p;
9811 p = vim_strchr(event_name, '#');
9812 if (p != NULL)
9813 *p++ = NUL; /* "Group#Event#pat" */
9814 }
9815
9816 pattern = p; /* "pattern" is NULL when there is no pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009817
9818 /* find the index (enum) for the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009819 event = event_name2nr(event_name, &p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009820
9821 /* return FALSE if the event name is not recognized */
Bram Moolenaar195d6352005-12-19 22:08:24 +00009822 if (event == NUM_EVENTS)
9823 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009824
9825 /* Find the first autocommand for this event.
9826 * If there isn't any, return FALSE;
9827 * If there is one and no pattern given, return TRUE; */
9828 ap = first_autopat[(int)event];
9829 if (ap == NULL)
Bram Moolenaar195d6352005-12-19 22:08:24 +00009830 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009831
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009832 /* if pattern is "<buffer>", special handling is needed which uses curbuf */
9833 /* for pattern "<buffer=N>, fnamecmp() will work fine */
Bram Moolenaar5b7880d2009-09-11 15:24:31 +00009834 if (pattern != NULL && STRICMP(pattern, "<buffer>") == 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009835 buflocal_buf = curbuf;
9836
Bram Moolenaar071d4272004-06-13 20:20:40 +00009837 /* Check if there is an autocommand with the given pattern. */
9838 for ( ; ap != NULL; ap = ap->next)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009839 /* only use a pattern when it has not been removed and has commands. */
9840 /* For buffer-local autocommands, fnamecmp() works fine. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009841 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaar195d6352005-12-19 22:08:24 +00009842 && (group == AUGROUP_ALL || ap->group == group)
Bram Moolenaar5b7880d2009-09-11 15:24:31 +00009843 && (pattern == NULL
9844 || (buflocal_buf == NULL
9845 ? fnamecmp(ap->pat, pattern) == 0
9846 : ap->buflocal_nr == buflocal_buf->b_fnum)))
Bram Moolenaar195d6352005-12-19 22:08:24 +00009847 {
9848 retval = TRUE;
9849 break;
9850 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009851
Bram Moolenaar195d6352005-12-19 22:08:24 +00009852theend:
9853 vim_free(arg_save);
9854 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009855}
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009856
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009857#else /* FEAT_AUTOCMD */
9858
9859/*
9860 * Prepare for executing commands for (hidden) buffer "buf".
9861 * This is the non-autocommand version, it simply saves "curbuf" and sets
9862 * "curbuf" and "curwin" to match "buf".
9863 */
9864 void
9865aucmd_prepbuf(aco, buf)
9866 aco_save_T *aco; /* structure to save values in */
9867 buf_T *buf; /* new curbuf */
9868{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009869 aco->save_curbuf = curbuf;
9870 --curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009871 curbuf = buf;
9872 curwin->w_buffer = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009873 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009874}
9875
9876/*
9877 * Restore after executing commands for a (hidden) buffer.
9878 * This is the non-autocommand version.
9879 */
9880 void
9881aucmd_restbuf(aco)
9882 aco_save_T *aco; /* structure holding saved values */
9883{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009884 --curbuf->b_nwindows;
9885 curbuf = aco->save_curbuf;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009886 curwin->w_buffer = curbuf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009887 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009888}
9889
Bram Moolenaar071d4272004-06-13 20:20:40 +00009890#endif /* FEAT_AUTOCMD */
9891
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009892
Bram Moolenaar071d4272004-06-13 20:20:40 +00009893#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN) || defined(PROTO)
9894/*
Bram Moolenaar748bf032005-02-02 23:04:36 +00009895 * Try matching a filename with a "pattern" ("prog" is NULL), or use the
9896 * precompiled regprog "prog" ("pattern" is NULL). That avoids calling
9897 * vim_regcomp() often.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009898 * Used for autocommands and 'wildignore'.
9899 * Returns TRUE if there is a match, FALSE otherwise.
9900 */
9901 int
Bram Moolenaar748bf032005-02-02 23:04:36 +00009902match_file_pat(pattern, prog, fname, sfname, tail, allow_dirs)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009903 char_u *pattern; /* pattern to match with */
Bram Moolenaar748bf032005-02-02 23:04:36 +00009904 regprog_T *prog; /* pre-compiled regprog or NULL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009905 char_u *fname; /* full path of file name */
9906 char_u *sfname; /* short file name or NULL */
9907 char_u *tail; /* tail of path */
9908 int allow_dirs; /* allow matching with dir */
9909{
9910 regmatch_T regmatch;
9911 int result = FALSE;
9912#ifdef FEAT_OSFILETYPE
9913 int no_pattern = FALSE; /* TRUE if check is filetype only */
9914 char_u *type_start;
9915 char_u c;
9916 int match = FALSE;
9917#endif
9918
9919#ifdef CASE_INSENSITIVE_FILENAME
9920 regmatch.rm_ic = TRUE; /* Always ignore case */
9921#else
9922 regmatch.rm_ic = FALSE; /* Don't ever ignore case */
9923#endif
9924#ifdef FEAT_OSFILETYPE
9925 if (*pattern == '<')
9926 {
9927 /* There is a filetype condition specified with this pattern.
9928 * Check the filetype matches first. If not, don't bother with the
9929 * pattern (set regprog to NULL).
9930 * Always use magic for the regexp.
9931 */
9932
9933 for (type_start = pattern + 1; (c = *pattern); pattern++)
9934 {
9935 if ((c == ';' || c == '>') && match == FALSE)
9936 {
9937 *pattern = NUL; /* Terminate the string */
9938 match = mch_check_filetype(fname, type_start);
9939 *pattern = c; /* Restore the terminator */
9940 type_start = pattern + 1;
9941 }
9942 if (c == '>')
9943 break;
9944 }
9945
9946 /* (c should never be NUL, but check anyway) */
9947 if (match == FALSE || c == NUL)
9948 regmatch.regprog = NULL; /* Doesn't match - don't check pat. */
9949 else if (*pattern == NUL)
9950 {
9951 regmatch.regprog = NULL; /* Vim will try to free regprog later */
9952 no_pattern = TRUE; /* Always matches - don't check pat. */
9953 }
9954 else
9955 regmatch.regprog = vim_regcomp(pattern + 1, RE_MAGIC);
9956 }
9957 else
9958#endif
Bram Moolenaar748bf032005-02-02 23:04:36 +00009959 {
9960 if (prog != NULL)
9961 regmatch.regprog = prog;
9962 else
9963 regmatch.regprog = vim_regcomp(pattern, RE_MAGIC);
9964 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009965
9966 /*
9967 * Try for a match with the pattern with:
9968 * 1. the full file name, when the pattern has a '/'.
9969 * 2. the short file name, when the pattern has a '/'.
9970 * 3. the tail of the file name, when the pattern has no '/'.
9971 */
9972 if (
9973#ifdef FEAT_OSFILETYPE
9974 /* If the check is for a filetype only and we don't care
9975 * about the path then skip all the regexp stuff.
9976 */
9977 no_pattern ||
9978#endif
9979 (regmatch.regprog != NULL
9980 && ((allow_dirs
9981 && (vim_regexec(&regmatch, fname, (colnr_T)0)
9982 || (sfname != NULL
9983 && vim_regexec(&regmatch, sfname, (colnr_T)0))))
9984 || (!allow_dirs && vim_regexec(&regmatch, tail, (colnr_T)0)))))
9985 result = TRUE;
9986
Bram Moolenaar748bf032005-02-02 23:04:36 +00009987 if (prog == NULL)
9988 vim_free(regmatch.regprog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009989 return result;
9990}
9991#endif
9992
9993#if defined(FEAT_WILDIGN) || defined(PROTO)
9994/*
9995 * Return TRUE if a file matches with a pattern in "list".
9996 * "list" is a comma-separated list of patterns, like 'wildignore'.
9997 * "sfname" is the short file name or NULL, "ffname" the long file name.
9998 */
9999 int
10000match_file_list(list, sfname, ffname)
10001 char_u *list;
10002 char_u *sfname;
10003 char_u *ffname;
10004{
10005 char_u buf[100];
10006 char_u *tail;
10007 char_u *regpat;
10008 char allow_dirs;
10009 int match;
10010 char_u *p;
10011
10012 tail = gettail(sfname);
10013
10014 /* try all patterns in 'wildignore' */
10015 p = list;
10016 while (*p)
10017 {
10018 copy_option_part(&p, buf, 100, ",");
10019 regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, FALSE);
10020 if (regpat == NULL)
10021 break;
Bram Moolenaar748bf032005-02-02 23:04:36 +000010022 match = match_file_pat(regpat, NULL, ffname, sfname,
10023 tail, (int)allow_dirs);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010024 vim_free(regpat);
10025 if (match)
10026 return TRUE;
10027 }
10028 return FALSE;
10029}
10030#endif
10031
10032/*
10033 * Convert the given pattern "pat" which has shell style wildcards in it, into
10034 * a regular expression, and return the result in allocated memory. If there
10035 * is a directory path separator to be matched, then TRUE is put in
10036 * allow_dirs, otherwise FALSE is put there -- webb.
10037 * Handle backslashes before special characters, like "\*" and "\ ".
10038 *
10039 * If FEAT_OSFILETYPE defined then pass initial <type> through unchanged. Eg:
10040 * '<html>myfile' becomes '<html>^myfile$' -- leonard.
10041 *
10042 * Returns NULL when out of memory.
10043 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010044 char_u *
10045file_pat_to_reg_pat(pat, pat_end, allow_dirs, no_bslash)
10046 char_u *pat;
10047 char_u *pat_end; /* first char after pattern or NULL */
10048 char *allow_dirs; /* Result passed back out in here */
Bram Moolenaar78a15312009-05-15 19:33:18 +000010049 int no_bslash UNUSED; /* Don't use a backward slash as pathsep */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010050{
10051 int size;
10052 char_u *endp;
10053 char_u *reg_pat;
10054 char_u *p;
10055 int i;
10056 int nested = 0;
10057 int add_dollar = TRUE;
10058#ifdef FEAT_OSFILETYPE
10059 int check_length = 0;
10060#endif
10061
10062 if (allow_dirs != NULL)
10063 *allow_dirs = FALSE;
10064 if (pat_end == NULL)
10065 pat_end = pat + STRLEN(pat);
10066
10067#ifdef FEAT_OSFILETYPE
10068 /* Find out how much of the string is the filetype check */
10069 if (*pat == '<')
10070 {
10071 /* Count chars until the next '>' */
10072 for (p = pat + 1; p < pat_end && *p != '>'; p++)
10073 ;
10074 if (p < pat_end)
10075 {
10076 /* Pattern is of the form <.*>.* */
10077 check_length = p - pat + 1;
10078 if (p + 1 >= pat_end)
10079 {
10080 /* The 'pattern' is a filetype check ONLY */
10081 reg_pat = (char_u *)alloc(check_length + 1);
10082 if (reg_pat != NULL)
10083 {
10084 mch_memmove(reg_pat, pat, (size_t)check_length);
10085 reg_pat[check_length] = NUL;
10086 }
10087 return reg_pat;
10088 }
10089 }
10090 /* else: there was no closing '>' - assume it was a normal pattern */
10091
10092 }
10093 pat += check_length;
10094 size = 2 + check_length;
10095#else
10096 size = 2; /* '^' at start, '$' at end */
10097#endif
10098
10099 for (p = pat; p < pat_end; p++)
10100 {
10101 switch (*p)
10102 {
10103 case '*':
10104 case '.':
10105 case ',':
10106 case '{':
10107 case '}':
10108 case '~':
10109 size += 2; /* extra backslash */
10110 break;
10111#ifdef BACKSLASH_IN_FILENAME
10112 case '\\':
10113 case '/':
10114 size += 4; /* could become "[\/]" */
10115 break;
10116#endif
10117 default:
10118 size++;
10119# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010120 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010121 {
10122 ++p;
10123 ++size;
10124 }
10125# endif
10126 break;
10127 }
10128 }
10129 reg_pat = alloc(size + 1);
10130 if (reg_pat == NULL)
10131 return NULL;
10132
10133#ifdef FEAT_OSFILETYPE
10134 /* Copy the type check in to the start. */
10135 if (check_length)
10136 mch_memmove(reg_pat, pat - check_length, (size_t)check_length);
10137 i = check_length;
10138#else
10139 i = 0;
10140#endif
10141
10142 if (pat[0] == '*')
10143 while (pat[0] == '*' && pat < pat_end - 1)
10144 pat++;
10145 else
10146 reg_pat[i++] = '^';
10147 endp = pat_end - 1;
10148 if (*endp == '*')
10149 {
10150 while (endp - pat > 0 && *endp == '*')
10151 endp--;
10152 add_dollar = FALSE;
10153 }
10154 for (p = pat; *p && nested >= 0 && p <= endp; p++)
10155 {
10156 switch (*p)
10157 {
10158 case '*':
10159 reg_pat[i++] = '.';
10160 reg_pat[i++] = '*';
Bram Moolenaar02743632005-07-25 20:42:36 +000010161 while (p[1] == '*') /* "**" matches like "*" */
10162 ++p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010163 break;
10164 case '.':
10165#ifdef RISCOS
10166 if (allow_dirs != NULL)
10167 *allow_dirs = TRUE;
10168 /* FALLTHROUGH */
10169#endif
10170 case '~':
10171 reg_pat[i++] = '\\';
10172 reg_pat[i++] = *p;
10173 break;
10174 case '?':
10175#ifdef RISCOS
10176 case '#':
10177#endif
10178 reg_pat[i++] = '.';
10179 break;
10180 case '\\':
10181 if (p[1] == NUL)
10182 break;
10183#ifdef BACKSLASH_IN_FILENAME
10184 if (!no_bslash)
10185 {
10186 /* translate:
10187 * "\x" to "\\x" e.g., "dir\file"
10188 * "\*" to "\\.*" e.g., "dir\*.c"
10189 * "\?" to "\\." e.g., "dir\??.c"
10190 * "\+" to "\+" e.g., "fileX\+.c"
10191 */
10192 if ((vim_isfilec(p[1]) || p[1] == '*' || p[1] == '?')
10193 && p[1] != '+')
10194 {
10195 reg_pat[i++] = '[';
10196 reg_pat[i++] = '\\';
10197 reg_pat[i++] = '/';
10198 reg_pat[i++] = ']';
10199 if (allow_dirs != NULL)
10200 *allow_dirs = TRUE;
10201 break;
10202 }
10203 }
10204#endif
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010205 /* Undo escaping from ExpandEscape():
10206 * foo\?bar -> foo?bar
10207 * foo\%bar -> foo%bar
10208 * foo\,bar -> foo,bar
10209 * foo\ bar -> foo bar
10210 * Don't unescape \, * and others that are also special in a
10211 * regexp. */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010212 if (*++p == '?'
10213#ifdef BACKSLASH_IN_FILENAME
10214 && no_bslash
10215#endif
10216 )
10217 reg_pat[i++] = '?';
10218 else
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010219 if (*p == ',' || *p == '%' || *p == '#' || *p == ' ')
10220 reg_pat[i++] = *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010221 else
10222 {
10223 if (allow_dirs != NULL && vim_ispathsep(*p)
10224#ifdef BACKSLASH_IN_FILENAME
10225 && (!no_bslash || *p != '\\')
10226#endif
10227 )
10228 *allow_dirs = TRUE;
10229 reg_pat[i++] = '\\';
10230 reg_pat[i++] = *p;
10231 }
10232 break;
10233#ifdef BACKSLASH_IN_FILENAME
10234 case '/':
10235 reg_pat[i++] = '[';
10236 reg_pat[i++] = '\\';
10237 reg_pat[i++] = '/';
10238 reg_pat[i++] = ']';
10239 if (allow_dirs != NULL)
10240 *allow_dirs = TRUE;
10241 break;
10242#endif
10243 case '{':
10244 reg_pat[i++] = '\\';
10245 reg_pat[i++] = '(';
10246 nested++;
10247 break;
10248 case '}':
10249 reg_pat[i++] = '\\';
10250 reg_pat[i++] = ')';
10251 --nested;
10252 break;
10253 case ',':
10254 if (nested)
10255 {
10256 reg_pat[i++] = '\\';
10257 reg_pat[i++] = '|';
10258 }
10259 else
10260 reg_pat[i++] = ',';
10261 break;
10262 default:
10263# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010264 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010265 reg_pat[i++] = *p++;
10266 else
10267# endif
10268 if (allow_dirs != NULL && vim_ispathsep(*p))
10269 *allow_dirs = TRUE;
10270 reg_pat[i++] = *p;
10271 break;
10272 }
10273 }
10274 if (add_dollar)
10275 reg_pat[i++] = '$';
10276 reg_pat[i] = NUL;
10277 if (nested != 0)
10278 {
10279 if (nested < 0)
10280 EMSG(_("E219: Missing {."));
10281 else
10282 EMSG(_("E220: Missing }."));
10283 vim_free(reg_pat);
10284 reg_pat = NULL;
10285 }
10286 return reg_pat;
10287}