blob: 967f49ea43f9a6954f0d708a798125de85864026 [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 Moolenaara8ffcbb2010-06-21 06:15:46 +020067static char_u *check_for_cryptkey __ARGS((char_u *cryptkey, char_u *ptr, long *sizep, off_t *filesizep, int newfile, char_u *fname, int *did_ask));
Bram Moolenaar071d4272004-06-13 20:20:40 +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
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200998#ifdef FEAT_CRYPT
999 if (cryptkey != NULL)
1000 /* Need to reset the state, but keep the key, don't want to ask for it
1001 * again. */
1002 crypt_pop_state();
1003#endif
1004
Bram Moolenaar071d4272004-06-13 20:20:40 +00001005 /*
1006 * When retrying with another "fenc" and the first time "fileformat"
1007 * will be reset.
1008 */
1009 if (keep_fileformat)
1010 keep_fileformat = FALSE;
1011 else
1012 {
1013 if (eap != NULL && eap->force_ff != 0)
Bram Moolenaar1c860362008-11-12 15:05:21 +00001014 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001015 fileformat = get_fileformat_force(curbuf, eap);
Bram Moolenaar1c860362008-11-12 15:05:21 +00001016 try_unix = try_dos = try_mac = FALSE;
1017 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001018 else if (curbuf->b_p_bin)
1019 fileformat = EOL_UNIX; /* binary: use Unix format */
1020 else if (*p_ffs == NUL)
1021 fileformat = get_fileformat(curbuf);/* use format from buffer */
1022 else
1023 fileformat = EOL_UNKNOWN; /* detect from file */
1024 }
1025
1026#ifdef FEAT_MBYTE
1027# ifdef USE_ICONV
1028 if (iconv_fd != (iconv_t)-1)
1029 {
1030 /* aborted conversion with iconv(), close the descriptor */
1031 iconv_close(iconv_fd);
1032 iconv_fd = (iconv_t)-1;
1033 }
1034# endif
1035
1036 if (advance_fenc)
1037 {
1038 /*
1039 * Try the next entry in 'fileencodings'.
1040 */
1041 advance_fenc = FALSE;
1042
1043 if (eap != NULL && eap->force_enc != 0)
1044 {
1045 /* Conversion given with "++cc=" wasn't possible, read
1046 * without conversion. */
1047 notconverted = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001048 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001049 if (fenc_alloced)
1050 vim_free(fenc);
1051 fenc = (char_u *)"";
1052 fenc_alloced = FALSE;
1053 }
1054 else
1055 {
1056 if (fenc_alloced)
1057 vim_free(fenc);
1058 if (fenc_next != NULL)
1059 {
1060 fenc = next_fenc(&fenc_next);
1061 fenc_alloced = (fenc_next != NULL);
1062 }
1063 else
1064 {
1065 fenc = (char_u *)"";
1066 fenc_alloced = FALSE;
1067 }
1068 }
1069 if (tmpname != NULL)
1070 {
1071 mch_remove(tmpname); /* delete converted file */
1072 vim_free(tmpname);
1073 tmpname = NULL;
1074 }
1075 }
1076
1077 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001078 * Conversion may be required when the encoding of the file is different
1079 * from 'encoding' or 'encoding' is UTF-16, UCS-2 or UCS-4.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001080 */
1081 fio_flags = 0;
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001082 converted = need_conversion(fenc);
1083 if (converted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001084 {
1085
1086 /* "ucs-bom" means we need to check the first bytes of the file
1087 * for a BOM. */
1088 if (STRCMP(fenc, ENC_UCSBOM) == 0)
1089 fio_flags = FIO_UCSBOM;
1090
1091 /*
1092 * Check if UCS-2/4 or Latin1 to UTF-8 conversion needs to be
1093 * done. This is handled below after read(). Prepare the
1094 * fio_flags to avoid having to parse the string each time.
1095 * Also check for Unicode to Latin1 conversion, because iconv()
1096 * appears not to handle this correctly. This works just like
1097 * conversion to UTF-8 except how the resulting character is put in
1098 * the buffer.
1099 */
1100 else if (enc_utf8 || STRCMP(p_enc, "latin1") == 0)
1101 fio_flags = get_fio_flags(fenc);
1102
1103# ifdef WIN3264
1104 /*
1105 * Conversion from an MS-Windows codepage to UTF-8 or another codepage
1106 * is handled with MultiByteToWideChar().
1107 */
1108 if (fio_flags == 0)
1109 fio_flags = get_win_fio_flags(fenc);
1110# endif
1111
1112# ifdef MACOS_X
1113 /* Conversion from Apple MacRoman to latin1 or UTF-8 */
1114 if (fio_flags == 0)
1115 fio_flags = get_mac_fio_flags(fenc);
1116# endif
1117
1118# ifdef USE_ICONV
1119 /*
1120 * Try using iconv() if we can't convert internally.
1121 */
1122 if (fio_flags == 0
1123# ifdef FEAT_EVAL
1124 && !did_iconv
1125# endif
1126 )
1127 iconv_fd = (iconv_t)my_iconv_open(
1128 enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc);
1129# endif
1130
1131# ifdef FEAT_EVAL
1132 /*
1133 * Use the 'charconvert' expression when conversion is required
1134 * and we can't do it internally or with iconv().
1135 */
1136 if (fio_flags == 0 && !read_stdin && !read_buffer && *p_ccv != NUL
1137# ifdef USE_ICONV
1138 && iconv_fd == (iconv_t)-1
1139# endif
1140 )
1141 {
1142# ifdef USE_ICONV
1143 did_iconv = FALSE;
1144# endif
1145 /* Skip conversion when it's already done (retry for wrong
1146 * "fileformat"). */
1147 if (tmpname == NULL)
1148 {
1149 tmpname = readfile_charconvert(fname, fenc, &fd);
1150 if (tmpname == NULL)
1151 {
1152 /* Conversion failed. Try another one. */
1153 advance_fenc = TRUE;
1154 if (fd < 0)
1155 {
1156 /* Re-opening the original file failed! */
1157 EMSG(_("E202: Conversion made file unreadable!"));
1158 error = TRUE;
1159 goto failed;
1160 }
1161 goto retry;
1162 }
1163 }
1164 }
1165 else
1166# endif
1167 {
1168 if (fio_flags == 0
1169# ifdef USE_ICONV
1170 && iconv_fd == (iconv_t)-1
1171# endif
1172 )
1173 {
1174 /* Conversion wanted but we can't.
1175 * Try the next conversion in 'fileencodings' */
1176 advance_fenc = TRUE;
1177 goto retry;
1178 }
1179 }
1180 }
1181
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001182 /* Set "can_retry" when it's possible to rewind the file and try with
Bram Moolenaar071d4272004-06-13 20:20:40 +00001183 * another "fenc" value. It's FALSE when no other "fenc" to try, reading
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001184 * stdin or fixed at a specific encoding. */
1185 can_retry = (*fenc != NUL && !read_stdin && !keep_dest_enc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001186#endif
1187
1188 if (!skip_read)
1189 {
1190 linerest = 0;
1191 filesize = 0;
1192 skip_count = lines_to_skip;
1193 read_count = lines_to_read;
1194#ifdef FEAT_MBYTE
1195 conv_restlen = 0;
1196#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001197#ifdef FEAT_PERSISTENT_UNDO
1198 read_undo_file = (newfile && curbuf->b_ffname != NULL && curbuf->b_p_udf
1199 && !filtering && !read_stdin && !read_buffer);
1200 if (read_undo_file)
1201 sha256_start(&sha_ctx);
1202#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001203 }
1204
1205 while (!error && !got_int)
1206 {
1207 /*
1208 * We allocate as much space for the file as we can get, plus
1209 * space for the old line plus room for one terminating NUL.
1210 * The amount is limited by the fact that read() only can read
1211 * upto max_unsigned characters (and other things).
1212 */
1213#if SIZEOF_INT <= 2
1214 if (linerest >= 0x7ff0)
1215 {
1216 ++split;
1217 *ptr = NL; /* split line by inserting a NL */
1218 size = 1;
1219 }
1220 else
1221#endif
1222 {
1223 if (!skip_read)
1224 {
1225#if SIZEOF_INT > 2
Bram Moolenaar311d9822007-02-27 15:48:28 +00001226# if defined(SSIZE_MAX) && (SSIZE_MAX < 0x10000L)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001227 size = SSIZE_MAX; /* use max I/O size, 52K */
1228# else
1229 size = 0x10000L; /* use buffer >= 64K */
1230# endif
1231#else
1232 size = 0x7ff0L - linerest; /* limit buffer to 32K */
1233#endif
1234
Bram Moolenaarc1e37902006-04-18 21:55:01 +00001235 for ( ; size >= 10; size = (long)((long_u)size >> 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001236 {
1237 if ((new_buffer = lalloc((long_u)(size + linerest + 1),
1238 FALSE)) != NULL)
1239 break;
1240 }
1241 if (new_buffer == NULL)
1242 {
1243 do_outofmem_msg((long_u)(size * 2 + linerest + 1));
1244 error = TRUE;
1245 break;
1246 }
1247 if (linerest) /* copy characters from the previous buffer */
1248 mch_memmove(new_buffer, ptr - linerest, (size_t)linerest);
1249 vim_free(buffer);
1250 buffer = new_buffer;
1251 ptr = buffer + linerest;
1252 line_start = buffer;
1253
1254#ifdef FEAT_MBYTE
1255 /* May need room to translate into.
1256 * For iconv() we don't really know the required space, use a
1257 * factor ICONV_MULT.
1258 * latin1 to utf-8: 1 byte becomes up to 2 bytes
1259 * utf-16 to utf-8: 2 bytes become up to 3 bytes, 4 bytes
1260 * become up to 4 bytes, size must be multiple of 2
1261 * ucs-2 to utf-8: 2 bytes become up to 3 bytes, size must be
1262 * multiple of 2
1263 * ucs-4 to utf-8: 4 bytes become up to 6 bytes, size must be
1264 * multiple of 4 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001265 real_size = (int)size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001266# ifdef USE_ICONV
1267 if (iconv_fd != (iconv_t)-1)
1268 size = size / ICONV_MULT;
1269 else
1270# endif
1271 if (fio_flags & FIO_LATIN1)
1272 size = size / 2;
1273 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1274 size = (size * 2 / 3) & ~1;
1275 else if (fio_flags & FIO_UCS4)
1276 size = (size * 2 / 3) & ~3;
1277 else if (fio_flags == FIO_UCSBOM)
1278 size = size / ICONV_MULT; /* worst case */
1279# ifdef WIN3264
1280 else if (fio_flags & FIO_CODEPAGE)
1281 size = size / ICONV_MULT; /* also worst case */
1282# endif
1283# ifdef MACOS_X
1284 else if (fio_flags & FIO_MACROMAN)
1285 size = size / ICONV_MULT; /* also worst case */
1286# endif
1287#endif
1288
1289#ifdef FEAT_MBYTE
1290 if (conv_restlen > 0)
1291 {
1292 /* Insert unconverted bytes from previous line. */
1293 mch_memmove(ptr, conv_rest, conv_restlen);
1294 ptr += conv_restlen;
1295 size -= conv_restlen;
1296 }
1297#endif
1298
1299 if (read_buffer)
1300 {
1301 /*
1302 * Read bytes from curbuf. Used for converting text read
1303 * from stdin.
1304 */
1305 if (read_buf_lnum > from)
1306 size = 0;
1307 else
1308 {
1309 int n, ni;
1310 long tlen;
1311
1312 tlen = 0;
1313 for (;;)
1314 {
1315 p = ml_get(read_buf_lnum) + read_buf_col;
1316 n = (int)STRLEN(p);
1317 if ((int)tlen + n + 1 > size)
1318 {
1319 /* Filled up to "size", append partial line.
1320 * Change NL to NUL to reverse the effect done
1321 * below. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001322 n = (int)(size - tlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001323 for (ni = 0; ni < n; ++ni)
1324 {
1325 if (p[ni] == NL)
1326 ptr[tlen++] = NUL;
1327 else
1328 ptr[tlen++] = p[ni];
1329 }
1330 read_buf_col += n;
1331 break;
1332 }
1333 else
1334 {
1335 /* Append whole line and new-line. Change NL
1336 * to NUL to reverse the effect done below. */
1337 for (ni = 0; ni < n; ++ni)
1338 {
1339 if (p[ni] == NL)
1340 ptr[tlen++] = NUL;
1341 else
1342 ptr[tlen++] = p[ni];
1343 }
1344 ptr[tlen++] = NL;
1345 read_buf_col = 0;
1346 if (++read_buf_lnum > from)
1347 {
1348 /* When the last line didn't have an
1349 * end-of-line don't add it now either. */
1350 if (!curbuf->b_p_eol)
1351 --tlen;
1352 size = tlen;
1353 break;
1354 }
1355 }
1356 }
1357 }
1358 }
1359 else
1360 {
1361 /*
1362 * Read bytes from the file.
1363 */
1364 size = vim_read(fd, ptr, size);
1365 }
1366
1367 if (size <= 0)
1368 {
1369 if (size < 0) /* read error */
1370 error = TRUE;
1371#ifdef FEAT_MBYTE
1372 else if (conv_restlen > 0)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001373 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001374 /*
1375 * Reached end-of-file but some trailing bytes could
1376 * not be converted. Truncated file?
1377 */
1378
1379 /* When we did a conversion report an error. */
1380 if (fio_flags != 0
1381# ifdef USE_ICONV
1382 || iconv_fd != (iconv_t)-1
1383# endif
1384 )
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001385 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001386 if (conv_error == 0)
1387 conv_error = curbuf->b_ml.ml_line_count
1388 - linecnt + 1;
1389 }
1390 /* Remember the first linenr with an illegal byte */
1391 else if (illegal_byte == 0)
1392 illegal_byte = curbuf->b_ml.ml_line_count
1393 - linecnt + 1;
1394 if (bad_char_behavior == BAD_DROP)
1395 {
1396 *(ptr - conv_restlen) = NUL;
1397 conv_restlen = 0;
1398 }
1399 else
1400 {
1401 /* Replace the trailing bytes with the replacement
1402 * character if we were converting; if we weren't,
1403 * leave the UTF8 checking code to do it, as it
1404 * works slightly differently. */
1405 if (bad_char_behavior != BAD_KEEP && (fio_flags != 0
1406# ifdef USE_ICONV
1407 || iconv_fd != (iconv_t)-1
1408# endif
1409 ))
1410 {
1411 while (conv_restlen > 0)
1412 {
1413 *(--ptr) = bad_char_behavior;
1414 --conv_restlen;
1415 }
1416 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001417 fio_flags = 0; /* don't convert this */
Bram Moolenaarb21e5842006-04-16 18:30:08 +00001418# ifdef USE_ICONV
1419 if (iconv_fd != (iconv_t)-1)
1420 {
1421 iconv_close(iconv_fd);
1422 iconv_fd = (iconv_t)-1;
1423 }
1424# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001425 }
1426 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001427#endif
1428 }
1429
1430#ifdef FEAT_CRYPT
1431 /*
1432 * At start of file: Check for magic number of encryption.
1433 */
1434 if (filesize == 0)
1435 cryptkey = check_for_cryptkey(cryptkey, ptr, &size,
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001436 &filesize, newfile, sfname,
1437 &did_ask_for_key);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001438 /*
1439 * Decrypt the read bytes.
1440 */
1441 if (cryptkey != NULL && size > 0)
Bram Moolenaar04c9baf2010-06-01 23:37:39 +02001442 crypt_decode(ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001443#endif
1444 }
1445 skip_read = FALSE;
1446
1447#ifdef FEAT_MBYTE
1448 /*
1449 * At start of file (or after crypt magic number): Check for BOM.
1450 * Also check for a BOM for other Unicode encodings, but not after
1451 * converting with 'charconvert' or when a BOM has already been
1452 * found.
1453 */
1454 if ((filesize == 0
1455# ifdef FEAT_CRYPT
Bram Moolenaar40e6a712010-05-16 22:32:54 +02001456 || (filesize == (CRYPT_MAGIC_LEN
Bram Moolenaar80794b12010-06-13 05:20:42 +02001457 + crypt_salt_len[use_crypt_method]
Bram Moolenaar40e6a712010-05-16 22:32:54 +02001458 + crypt_seed_len[use_crypt_method])
1459 && cryptkey != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001460# endif
1461 )
1462 && (fio_flags == FIO_UCSBOM
1463 || (!curbuf->b_p_bomb
1464 && tmpname == NULL
1465 && (*fenc == 'u' || (*fenc == NUL && enc_utf8)))))
1466 {
1467 char_u *ccname;
1468 int blen;
1469
1470 /* no BOM detection in a short file or in binary mode */
1471 if (size < 2 || curbuf->b_p_bin)
1472 ccname = NULL;
1473 else
1474 ccname = check_for_bom(ptr, size, &blen,
1475 fio_flags == FIO_UCSBOM ? FIO_ALL : get_fio_flags(fenc));
1476 if (ccname != NULL)
1477 {
1478 /* Remove BOM from the text */
1479 filesize += blen;
1480 size -= blen;
1481 mch_memmove(ptr, ptr + blen, (size_t)size);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00001482 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001483 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001484 curbuf->b_p_bomb = TRUE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001485 curbuf->b_start_bomb = TRUE;
1486 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001487 }
1488
1489 if (fio_flags == FIO_UCSBOM)
1490 {
1491 if (ccname == NULL)
1492 {
1493 /* No BOM detected: retry with next encoding. */
1494 advance_fenc = TRUE;
1495 }
1496 else
1497 {
1498 /* BOM detected: set "fenc" and jump back */
1499 if (fenc_alloced)
1500 vim_free(fenc);
1501 fenc = ccname;
1502 fenc_alloced = FALSE;
1503 }
1504 /* retry reading without getting new bytes or rewinding */
1505 skip_read = TRUE;
1506 goto retry;
1507 }
1508 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001509
1510 /* Include not converted bytes. */
1511 ptr -= conv_restlen;
1512 size += conv_restlen;
1513 conv_restlen = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001514#endif
1515 /*
1516 * Break here for a read error or end-of-file.
1517 */
1518 if (size <= 0)
1519 break;
1520
1521#ifdef FEAT_MBYTE
1522
Bram Moolenaar071d4272004-06-13 20:20:40 +00001523# ifdef USE_ICONV
1524 if (iconv_fd != (iconv_t)-1)
1525 {
1526 /*
1527 * Attempt conversion of the read bytes to 'encoding' using
1528 * iconv().
1529 */
1530 const char *fromp;
1531 char *top;
1532 size_t from_size;
1533 size_t to_size;
1534
1535 fromp = (char *)ptr;
1536 from_size = size;
1537 ptr += size;
1538 top = (char *)ptr;
1539 to_size = real_size - size;
1540
1541 /*
1542 * If there is conversion error or not enough room try using
Bram Moolenaar19a09a12005-03-04 23:39:37 +00001543 * another conversion. Except for when there is no
1544 * alternative (help files).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001545 */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001546 while ((iconv(iconv_fd, (void *)&fromp, &from_size,
1547 &top, &to_size)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001548 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
1549 || from_size > CONV_RESTLEN)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001550 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001551 if (can_retry)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001552 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001553 if (conv_error == 0)
1554 conv_error = readfile_linenr(linecnt,
1555 ptr, (char_u *)top);
Bram Moolenaar42eeac32005-06-29 22:40:58 +00001556
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001557 /* Deal with a bad byte and continue with the next. */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001558 ++fromp;
1559 --from_size;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001560 if (bad_char_behavior == BAD_KEEP)
1561 {
1562 *top++ = *(fromp - 1);
1563 --to_size;
1564 }
1565 else if (bad_char_behavior != BAD_DROP)
1566 {
1567 *top++ = bad_char_behavior;
1568 --to_size;
1569 }
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001570 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001571
1572 if (from_size > 0)
1573 {
1574 /* Some remaining characters, keep them for the next
1575 * round. */
1576 mch_memmove(conv_rest, (char_u *)fromp, from_size);
1577 conv_restlen = (int)from_size;
1578 }
1579
1580 /* move the linerest to before the converted characters */
1581 line_start = ptr - linerest;
1582 mch_memmove(line_start, buffer, (size_t)linerest);
1583 size = (long)((char_u *)top - ptr);
1584 }
1585# endif
1586
1587# ifdef WIN3264
1588 if (fio_flags & FIO_CODEPAGE)
1589 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001590 char_u *src, *dst;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001591 WCHAR ucs2buf[3];
1592 int ucs2len;
1593 int codepage = FIO_GET_CP(fio_flags);
1594 int bytelen;
1595 int found_bad;
1596 char replstr[2];
1597
Bram Moolenaar071d4272004-06-13 20:20:40 +00001598 /*
1599 * Conversion from an MS-Windows codepage or UTF-8 to UTF-8 or
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001600 * a codepage, using standard MS-Windows functions. This
1601 * requires two steps:
1602 * 1. convert from 'fileencoding' to ucs-2
1603 * 2. convert from ucs-2 to 'encoding'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001604 *
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001605 * Because there may be illegal bytes AND an incomplete byte
1606 * sequence at the end, we may have to do the conversion one
1607 * character at a time to get it right.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001608 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001609
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001610 /* Replacement string for WideCharToMultiByte(). */
1611 if (bad_char_behavior > 0)
1612 replstr[0] = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001613 else
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001614 replstr[0] = '?';
1615 replstr[1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001616
1617 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001618 * Move the bytes to the end of the buffer, so that we have
1619 * room to put the result at the start.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001620 */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001621 src = ptr + real_size - size;
1622 mch_memmove(src, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001623
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001624 /*
1625 * Do the conversion.
1626 */
1627 dst = ptr;
1628 size = size;
1629 while (size > 0)
1630 {
1631 found_bad = FALSE;
1632
1633# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
1634 if (codepage == CP_UTF8)
1635 {
1636 /* Handle CP_UTF8 input ourselves to be able to handle
1637 * trailing bytes properly.
1638 * Get one UTF-8 character from src. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001639 bytelen = (int)utf_ptr2len_len(src, size);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001640 if (bytelen > size)
1641 {
1642 /* Only got some bytes of a character. Normally
1643 * it's put in "conv_rest", but if it's too long
1644 * deal with it as if they were illegal bytes. */
1645 if (bytelen <= CONV_RESTLEN)
1646 break;
1647
1648 /* weird overlong byte sequence */
1649 bytelen = size;
1650 found_bad = TRUE;
1651 }
1652 else
1653 {
Bram Moolenaarc01140a2006-03-24 22:21:52 +00001654 int u8c = utf_ptr2char(src);
1655
Bram Moolenaar86e01082005-12-29 22:45:34 +00001656 if (u8c > 0xffff || (*src >= 0x80 && bytelen == 1))
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001657 found_bad = TRUE;
1658 ucs2buf[0] = u8c;
1659 ucs2len = 1;
1660 }
1661 }
1662 else
1663# endif
1664 {
1665 /* We don't know how long the byte sequence is, try
1666 * from one to three bytes. */
1667 for (bytelen = 1; bytelen <= size && bytelen <= 3;
1668 ++bytelen)
1669 {
1670 ucs2len = MultiByteToWideChar(codepage,
1671 MB_ERR_INVALID_CHARS,
1672 (LPCSTR)src, bytelen,
1673 ucs2buf, 3);
1674 if (ucs2len > 0)
1675 break;
1676 }
1677 if (ucs2len == 0)
1678 {
1679 /* If we have only one byte then it's probably an
1680 * incomplete byte sequence. Otherwise discard
1681 * one byte as a bad character. */
1682 if (size == 1)
1683 break;
1684 found_bad = TRUE;
1685 bytelen = 1;
1686 }
1687 }
1688
1689 if (!found_bad)
1690 {
1691 int i;
1692
1693 /* Convert "ucs2buf[ucs2len]" to 'enc' in "dst". */
1694 if (enc_utf8)
1695 {
1696 /* From UCS-2 to UTF-8. Cannot fail. */
1697 for (i = 0; i < ucs2len; ++i)
1698 dst += utf_char2bytes(ucs2buf[i], dst);
1699 }
1700 else
1701 {
1702 BOOL bad = FALSE;
1703 int dstlen;
1704
1705 /* From UCS-2 to "enc_codepage". If the
1706 * conversion uses the default character "?",
1707 * the data doesn't fit in this encoding. */
1708 dstlen = WideCharToMultiByte(enc_codepage, 0,
1709 (LPCWSTR)ucs2buf, ucs2len,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001710 (LPSTR)dst, (int)(src - dst),
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001711 replstr, &bad);
1712 if (bad)
1713 found_bad = TRUE;
1714 else
1715 dst += dstlen;
1716 }
1717 }
1718
1719 if (found_bad)
1720 {
1721 /* Deal with bytes we can't convert. */
1722 if (can_retry)
1723 goto rewind_retry;
1724 if (conv_error == 0)
1725 conv_error = readfile_linenr(linecnt, ptr, dst);
1726 if (bad_char_behavior != BAD_DROP)
1727 {
1728 if (bad_char_behavior == BAD_KEEP)
1729 {
1730 mch_memmove(dst, src, bytelen);
1731 dst += bytelen;
1732 }
1733 else
1734 *dst++ = bad_char_behavior;
1735 }
1736 }
1737
1738 src += bytelen;
1739 size -= bytelen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001740 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001741
1742 if (size > 0)
1743 {
1744 /* An incomplete byte sequence remaining. */
1745 mch_memmove(conv_rest, src, size);
1746 conv_restlen = size;
1747 }
1748
1749 /* The new size is equal to how much "dst" was advanced. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001750 size = (long)(dst - ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001751 }
1752 else
1753# endif
Bram Moolenaar56718732006-03-15 22:53:57 +00001754# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001755 if (fio_flags & FIO_MACROMAN)
1756 {
1757 /*
1758 * Conversion from Apple MacRoman char encoding to UTF-8 or
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001759 * latin1. This is in os_mac_conv.c.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001760 */
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001761 if (macroman2enc(ptr, &size, real_size) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001762 goto rewind_retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001763 }
1764 else
1765# endif
1766 if (fio_flags != 0)
1767 {
1768 int u8c;
1769 char_u *dest;
1770 char_u *tail = NULL;
1771
1772 /*
1773 * "enc_utf8" set: Convert Unicode or Latin1 to UTF-8.
1774 * "enc_utf8" not set: Convert Unicode to Latin1.
1775 * Go from end to start through the buffer, because the number
1776 * of bytes may increase.
1777 * "dest" points to after where the UTF-8 bytes go, "p" points
1778 * to after the next character to convert.
1779 */
1780 dest = ptr + real_size;
1781 if (fio_flags == FIO_LATIN1 || fio_flags == FIO_UTF8)
1782 {
1783 p = ptr + size;
1784 if (fio_flags == FIO_UTF8)
1785 {
1786 /* Check for a trailing incomplete UTF-8 sequence */
1787 tail = ptr + size - 1;
1788 while (tail > ptr && (*tail & 0xc0) == 0x80)
1789 --tail;
1790 if (tail + utf_byte2len(*tail) <= ptr + size)
1791 tail = NULL;
1792 else
1793 p = tail;
1794 }
1795 }
1796 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1797 {
1798 /* Check for a trailing byte */
1799 p = ptr + (size & ~1);
1800 if (size & 1)
1801 tail = p;
1802 if ((fio_flags & FIO_UTF16) && p > ptr)
1803 {
1804 /* Check for a trailing leading word */
1805 if (fio_flags & FIO_ENDIAN_L)
1806 {
1807 u8c = (*--p << 8);
1808 u8c += *--p;
1809 }
1810 else
1811 {
1812 u8c = *--p;
1813 u8c += (*--p << 8);
1814 }
1815 if (u8c >= 0xd800 && u8c <= 0xdbff)
1816 tail = p;
1817 else
1818 p += 2;
1819 }
1820 }
1821 else /* FIO_UCS4 */
1822 {
1823 /* Check for trailing 1, 2 or 3 bytes */
1824 p = ptr + (size & ~3);
1825 if (size & 3)
1826 tail = p;
1827 }
1828
1829 /* If there is a trailing incomplete sequence move it to
1830 * conv_rest[]. */
1831 if (tail != NULL)
1832 {
1833 conv_restlen = (int)((ptr + size) - tail);
1834 mch_memmove(conv_rest, (char_u *)tail, conv_restlen);
1835 size -= conv_restlen;
1836 }
1837
1838
1839 while (p > ptr)
1840 {
1841 if (fio_flags & FIO_LATIN1)
1842 u8c = *--p;
1843 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1844 {
1845 if (fio_flags & FIO_ENDIAN_L)
1846 {
1847 u8c = (*--p << 8);
1848 u8c += *--p;
1849 }
1850 else
1851 {
1852 u8c = *--p;
1853 u8c += (*--p << 8);
1854 }
1855 if ((fio_flags & FIO_UTF16)
1856 && u8c >= 0xdc00 && u8c <= 0xdfff)
1857 {
1858 int u16c;
1859
1860 if (p == ptr)
1861 {
1862 /* Missing leading word. */
1863 if (can_retry)
1864 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001865 if (conv_error == 0)
1866 conv_error = readfile_linenr(linecnt,
1867 ptr, p);
1868 if (bad_char_behavior == BAD_DROP)
1869 continue;
1870 if (bad_char_behavior != BAD_KEEP)
1871 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001872 }
1873
1874 /* found second word of double-word, get the first
1875 * word and compute the resulting character */
1876 if (fio_flags & FIO_ENDIAN_L)
1877 {
1878 u16c = (*--p << 8);
1879 u16c += *--p;
1880 }
1881 else
1882 {
1883 u16c = *--p;
1884 u16c += (*--p << 8);
1885 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001886 u8c = 0x10000 + ((u16c & 0x3ff) << 10)
1887 + (u8c & 0x3ff);
1888
Bram Moolenaar071d4272004-06-13 20:20:40 +00001889 /* Check if the word is indeed a leading word. */
1890 if (u16c < 0xd800 || u16c > 0xdbff)
1891 {
1892 if (can_retry)
1893 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001894 if (conv_error == 0)
1895 conv_error = readfile_linenr(linecnt,
1896 ptr, p);
1897 if (bad_char_behavior == BAD_DROP)
1898 continue;
1899 if (bad_char_behavior != BAD_KEEP)
1900 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001901 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001902 }
1903 }
1904 else if (fio_flags & FIO_UCS4)
1905 {
1906 if (fio_flags & FIO_ENDIAN_L)
1907 {
1908 u8c = (*--p << 24);
1909 u8c += (*--p << 16);
1910 u8c += (*--p << 8);
1911 u8c += *--p;
1912 }
1913 else /* big endian */
1914 {
1915 u8c = *--p;
1916 u8c += (*--p << 8);
1917 u8c += (*--p << 16);
1918 u8c += (*--p << 24);
1919 }
1920 }
1921 else /* UTF-8 */
1922 {
1923 if (*--p < 0x80)
1924 u8c = *p;
1925 else
1926 {
1927 len = utf_head_off(ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001928 p -= len;
1929 u8c = utf_ptr2char(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001930 if (len == 0)
1931 {
1932 /* Not a valid UTF-8 character, retry with
1933 * another fenc when possible, otherwise just
1934 * report the error. */
1935 if (can_retry)
1936 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001937 if (conv_error == 0)
1938 conv_error = readfile_linenr(linecnt,
1939 ptr, p);
1940 if (bad_char_behavior == BAD_DROP)
1941 continue;
1942 if (bad_char_behavior != BAD_KEEP)
1943 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001944 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001945 }
1946 }
1947 if (enc_utf8) /* produce UTF-8 */
1948 {
1949 dest -= utf_char2len(u8c);
1950 (void)utf_char2bytes(u8c, dest);
1951 }
1952 else /* produce Latin1 */
1953 {
1954 --dest;
1955 if (u8c >= 0x100)
1956 {
1957 /* character doesn't fit in latin1, retry with
1958 * another fenc when possible, otherwise just
1959 * report the error. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001960 if (can_retry)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001961 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001962 if (conv_error == 0)
1963 conv_error = readfile_linenr(linecnt, ptr, p);
1964 if (bad_char_behavior == BAD_DROP)
1965 ++dest;
1966 else if (bad_char_behavior == BAD_KEEP)
1967 *dest = u8c;
1968 else if (eap != NULL && eap->bad_char != 0)
1969 *dest = bad_char_behavior;
1970 else
1971 *dest = 0xBF;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001972 }
1973 else
1974 *dest = u8c;
1975 }
1976 }
1977
1978 /* move the linerest to before the converted characters */
1979 line_start = dest - linerest;
1980 mch_memmove(line_start, buffer, (size_t)linerest);
1981 size = (long)((ptr + real_size) - dest);
1982 ptr = dest;
1983 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001984 else if (enc_utf8 && !curbuf->b_p_bin)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001985 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001986 int incomplete_tail = FALSE;
1987
1988 /* Reading UTF-8: Check if the bytes are valid UTF-8. */
1989 for (p = ptr; ; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001990 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001991 int todo = (int)((ptr + size) - p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001992 int l;
1993
1994 if (todo <= 0)
1995 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001996 if (*p >= 0x80)
1997 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001998 /* A length of 1 means it's an illegal byte. Accept
1999 * an incomplete character at the end though, the next
2000 * read() will get the next bytes, we'll check it
2001 * then. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002002 l = utf_ptr2len_len(p, todo);
Bram Moolenaarf453d352008-06-04 17:37:34 +00002003 if (l > todo && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002004 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002005 /* Avoid retrying with a different encoding when
2006 * a truncated file is more likely, or attempting
2007 * to read the rest of an incomplete sequence when
2008 * we have already done so. */
2009 if (p > ptr || filesize > 0)
2010 incomplete_tail = TRUE;
2011 /* Incomplete byte sequence, move it to conv_rest[]
2012 * and try to read the rest of it, unless we've
2013 * already done so. */
2014 if (p > ptr)
2015 {
2016 conv_restlen = todo;
2017 mch_memmove(conv_rest, p, conv_restlen);
2018 size -= conv_restlen;
2019 break;
2020 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002021 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002022 if (l == 1 || l > todo)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002023 {
2024 /* Illegal byte. If we can try another encoding
Bram Moolenaarf453d352008-06-04 17:37:34 +00002025 * do that, unless at EOF where a truncated
2026 * file is more likely than a conversion error. */
2027 if (can_retry && !incomplete_tail)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002028 break;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002029# ifdef USE_ICONV
2030 /* When we did a conversion report an error. */
2031 if (iconv_fd != (iconv_t)-1 && conv_error == 0)
2032 conv_error = readfile_linenr(linecnt, ptr, p);
2033# endif
Bram Moolenaarf453d352008-06-04 17:37:34 +00002034 /* Remember the first linenr with an illegal byte */
2035 if (conv_error == 0 && illegal_byte == 0)
2036 illegal_byte = readfile_linenr(linecnt, ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002037
2038 /* Drop, keep or replace the bad byte. */
2039 if (bad_char_behavior == BAD_DROP)
2040 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002041 mch_memmove(p, p + 1, todo - 1);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002042 --p;
2043 --size;
2044 }
2045 else if (bad_char_behavior != BAD_KEEP)
2046 *p = bad_char_behavior;
2047 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002048 else
2049 p += l - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002050 }
2051 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002052 if (p < ptr + size && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002053 {
2054 /* Detected a UTF-8 error. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002055rewind_retry:
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002056 /* Retry reading with another conversion. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002057# if defined(FEAT_EVAL) && defined(USE_ICONV)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002058 if (*p_ccv != NUL && iconv_fd != (iconv_t)-1)
2059 /* iconv() failed, try 'charconvert' */
2060 did_iconv = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002061 else
2062# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002063 /* use next item from 'fileencodings' */
2064 advance_fenc = TRUE;
2065 file_rewind = TRUE;
2066 goto retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002067 }
2068 }
2069#endif
2070
2071 /* count the number of characters (after conversion!) */
2072 filesize += size;
2073
2074 /*
2075 * when reading the first part of a file: guess EOL type
2076 */
2077 if (fileformat == EOL_UNKNOWN)
2078 {
2079 /* First try finding a NL, for Dos and Unix */
2080 if (try_dos || try_unix)
2081 {
2082 for (p = ptr; p < ptr + size; ++p)
2083 {
2084 if (*p == NL)
2085 {
2086 if (!try_unix
2087 || (try_dos && p > ptr && p[-1] == CAR))
2088 fileformat = EOL_DOS;
2089 else
2090 fileformat = EOL_UNIX;
2091 break;
2092 }
2093 }
2094
2095 /* Don't give in to EOL_UNIX if EOL_MAC is more likely */
2096 if (fileformat == EOL_UNIX && try_mac)
2097 {
2098 /* Need to reset the counters when retrying fenc. */
2099 try_mac = 1;
2100 try_unix = 1;
2101 for (; p >= ptr && *p != CAR; p--)
2102 ;
2103 if (p >= ptr)
2104 {
2105 for (p = ptr; p < ptr + size; ++p)
2106 {
2107 if (*p == NL)
2108 try_unix++;
2109 else if (*p == CAR)
2110 try_mac++;
2111 }
2112 if (try_mac > try_unix)
2113 fileformat = EOL_MAC;
2114 }
2115 }
2116 }
2117
2118 /* No NL found: may use Mac format */
2119 if (fileformat == EOL_UNKNOWN && try_mac)
2120 fileformat = EOL_MAC;
2121
2122 /* Still nothing found? Use first format in 'ffs' */
2123 if (fileformat == EOL_UNKNOWN)
2124 fileformat = default_fileformat();
2125
2126 /* if editing a new file: may set p_tx and p_ff */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002127 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002128 set_fileformat(fileformat, OPT_LOCAL);
2129 }
2130 }
2131
2132 /*
2133 * This loop is executed once for every character read.
2134 * Keep it fast!
2135 */
2136 if (fileformat == EOL_MAC)
2137 {
2138 --ptr;
2139 while (++ptr, --size >= 0)
2140 {
2141 /* catch most common case first */
2142 if ((c = *ptr) != NUL && c != CAR && c != NL)
2143 continue;
2144 if (c == NUL)
2145 *ptr = NL; /* NULs are replaced by newlines! */
2146 else if (c == NL)
2147 *ptr = CAR; /* NLs are replaced by CRs! */
2148 else
2149 {
2150 if (skip_count == 0)
2151 {
2152 *ptr = NUL; /* end of line */
2153 len = (colnr_T) (ptr - line_start + 1);
2154 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2155 {
2156 error = TRUE;
2157 break;
2158 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002159#ifdef FEAT_PERSISTENT_UNDO
2160 if (read_undo_file)
2161 sha256_update(&sha_ctx, line_start, len);
2162#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002163 ++lnum;
2164 if (--read_count == 0)
2165 {
2166 error = TRUE; /* break loop */
2167 line_start = ptr; /* nothing left to write */
2168 break;
2169 }
2170 }
2171 else
2172 --skip_count;
2173 line_start = ptr + 1;
2174 }
2175 }
2176 }
2177 else
2178 {
2179 --ptr;
2180 while (++ptr, --size >= 0)
2181 {
2182 if ((c = *ptr) != NUL && c != NL) /* catch most common case */
2183 continue;
2184 if (c == NUL)
2185 *ptr = NL; /* NULs are replaced by newlines! */
2186 else
2187 {
2188 if (skip_count == 0)
2189 {
2190 *ptr = NUL; /* end of line */
2191 len = (colnr_T)(ptr - line_start + 1);
2192 if (fileformat == EOL_DOS)
2193 {
2194 if (ptr[-1] == CAR) /* remove CR */
2195 {
2196 ptr[-1] = NUL;
2197 --len;
2198 }
2199 /*
2200 * Reading in Dos format, but no CR-LF found!
2201 * When 'fileformats' includes "unix", delete all
2202 * the lines read so far and start all over again.
2203 * Otherwise give an error message later.
2204 */
2205 else if (ff_error != EOL_DOS)
2206 {
2207 if ( try_unix
2208 && !read_stdin
2209 && (read_buffer
2210 || lseek(fd, (off_t)0L, SEEK_SET) == 0))
2211 {
2212 fileformat = EOL_UNIX;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002213 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002214 set_fileformat(EOL_UNIX, OPT_LOCAL);
2215 file_rewind = TRUE;
2216 keep_fileformat = TRUE;
2217 goto retry;
2218 }
2219 ff_error = EOL_DOS;
2220 }
2221 }
2222 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2223 {
2224 error = TRUE;
2225 break;
2226 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002227#ifdef FEAT_PERSISTENT_UNDO
2228 if (read_undo_file)
2229 sha256_update(&sha_ctx, line_start, len);
2230#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002231 ++lnum;
2232 if (--read_count == 0)
2233 {
2234 error = TRUE; /* break loop */
2235 line_start = ptr; /* nothing left to write */
2236 break;
2237 }
2238 }
2239 else
2240 --skip_count;
2241 line_start = ptr + 1;
2242 }
2243 }
2244 }
2245 linerest = (long)(ptr - line_start);
2246 ui_breakcheck();
2247 }
2248
2249failed:
2250 /* not an error, max. number of lines reached */
2251 if (error && read_count == 0)
2252 error = FALSE;
2253
2254 /*
2255 * If we get EOF in the middle of a line, note the fact and
2256 * complete the line ourselves.
2257 * In Dos format ignore a trailing CTRL-Z, unless 'binary' set.
2258 */
2259 if (!error
2260 && !got_int
2261 && linerest != 0
2262 && !(!curbuf->b_p_bin
2263 && fileformat == EOL_DOS
2264 && *line_start == Ctrl_Z
2265 && ptr == line_start + 1))
2266 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002267 /* remember for when writing */
2268 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002269 curbuf->b_p_eol = FALSE;
2270 *ptr = NUL;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002271 len = (colnr_T)(ptr - line_start + 1);
2272 if (ml_append(lnum, line_start, len, newfile) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002273 error = TRUE;
2274 else
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002275 {
2276#ifdef FEAT_PERSISTENT_UNDO
2277 if (read_undo_file)
2278 sha256_update(&sha_ctx, line_start, len);
2279#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002280 read_no_eol_lnum = ++lnum;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002281 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002282 }
2283
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002284 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002285 save_file_ff(curbuf); /* remember the current file format */
2286
2287#ifdef FEAT_CRYPT
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002288 if (cryptkey != NULL)
2289 {
2290 crypt_pop_state();
2291 if (cryptkey != curbuf->b_p_key)
2292 free_crypt_key(cryptkey);
2293 /* don't set cryptkey to NULL, it's used below as a flag that
2294 * encryption was used */
2295 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002296#endif
2297
2298#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002299 /* If editing a new file: set 'fenc' for the current buffer.
2300 * Also for ":read ++edit file". */
2301 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002302 set_string_option_direct((char_u *)"fenc", -1, fenc,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00002303 OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002304 if (fenc_alloced)
2305 vim_free(fenc);
2306# ifdef USE_ICONV
2307 if (iconv_fd != (iconv_t)-1)
2308 {
2309 iconv_close(iconv_fd);
2310 iconv_fd = (iconv_t)-1;
2311 }
2312# endif
2313#endif
2314
2315 if (!read_buffer && !read_stdin)
2316 close(fd); /* errors are ignored */
Bram Moolenaarf05da212009-11-17 16:13:15 +00002317#ifdef HAVE_FD_CLOEXEC
2318 else
2319 {
2320 int fdflags = fcntl(fd, F_GETFD);
2321 if (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0)
2322 fcntl(fd, F_SETFD, fdflags | FD_CLOEXEC);
2323 }
2324#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002325 vim_free(buffer);
2326
2327#ifdef HAVE_DUP
2328 if (read_stdin)
2329 {
2330 /* Use stderr for stdin, makes shell commands work. */
2331 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00002332 ignored = dup(2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002333 }
2334#endif
2335
2336#ifdef FEAT_MBYTE
2337 if (tmpname != NULL)
2338 {
2339 mch_remove(tmpname); /* delete converted file */
2340 vim_free(tmpname);
2341 }
2342#endif
2343 --no_wait_return; /* may wait for return now */
2344
2345 /*
2346 * In recovery mode everything but autocommands is skipped.
2347 */
2348 if (!recoverymode)
2349 {
2350 /* need to delete the last line, which comes from the empty buffer */
2351 if (newfile && wasempty && !(curbuf->b_ml.ml_flags & ML_EMPTY))
2352 {
2353#ifdef FEAT_NETBEANS_INTG
2354 netbeansFireChanges = 0;
2355#endif
2356 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
2357#ifdef FEAT_NETBEANS_INTG
2358 netbeansFireChanges = 1;
2359#endif
2360 --linecnt;
2361 }
2362 linecnt = curbuf->b_ml.ml_line_count - linecnt;
2363 if (filesize == 0)
2364 linecnt = 0;
2365 if (newfile || read_buffer)
Bram Moolenaar7263a772007-05-10 17:35:54 +00002366 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002367 redraw_curbuf_later(NOT_VALID);
Bram Moolenaar7263a772007-05-10 17:35:54 +00002368#ifdef FEAT_DIFF
2369 /* After reading the text into the buffer the diff info needs to
2370 * be updated. */
2371 diff_invalidate(curbuf);
2372#endif
2373#ifdef FEAT_FOLDING
2374 /* All folds in the window are invalid now. Mark them for update
2375 * before triggering autocommands. */
2376 foldUpdateAll(curwin);
2377#endif
2378 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002379 else if (linecnt) /* appended at least one line */
2380 appended_lines_mark(from, linecnt);
2381
Bram Moolenaar071d4272004-06-13 20:20:40 +00002382#ifndef ALWAYS_USE_GUI
2383 /*
2384 * If we were reading from the same terminal as where messages go,
2385 * the screen will have been messed up.
2386 * Switch on raw mode now and clear the screen.
2387 */
2388 if (read_stdin)
2389 {
2390 settmode(TMODE_RAW); /* set to raw mode */
2391 starttermcap();
2392 screenclear();
2393 }
2394#endif
2395
2396 if (got_int)
2397 {
2398 if (!(flags & READ_DUMMY))
2399 {
2400 filemess(curbuf, sfname, (char_u *)_(e_interr), 0);
2401 if (newfile)
2402 curbuf->b_p_ro = TRUE; /* must use "w!" now */
2403 }
2404 msg_scroll = msg_save;
2405#ifdef FEAT_VIMINFO
2406 check_marks_read();
2407#endif
2408 return OK; /* an interrupt isn't really an error */
2409 }
2410
2411 if (!filtering && !(flags & READ_DUMMY))
2412 {
2413 msg_add_fname(curbuf, sfname); /* fname in IObuff with quotes */
2414 c = FALSE;
2415
2416#ifdef UNIX
2417# ifdef S_ISFIFO
2418 if (S_ISFIFO(perm)) /* fifo or socket */
2419 {
2420 STRCAT(IObuff, _("[fifo/socket]"));
2421 c = TRUE;
2422 }
2423# else
2424# ifdef S_IFIFO
2425 if ((perm & S_IFMT) == S_IFIFO) /* fifo */
2426 {
2427 STRCAT(IObuff, _("[fifo]"));
2428 c = TRUE;
2429 }
2430# endif
2431# ifdef S_IFSOCK
2432 if ((perm & S_IFMT) == S_IFSOCK) /* or socket */
2433 {
2434 STRCAT(IObuff, _("[socket]"));
2435 c = TRUE;
2436 }
2437# endif
2438# endif
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002439# ifdef OPEN_CHR_FILES
2440 if (S_ISCHR(perm)) /* or character special */
2441 {
2442 STRCAT(IObuff, _("[character special]"));
2443 c = TRUE;
2444 }
2445# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002446#endif
2447 if (curbuf->b_p_ro)
2448 {
2449 STRCAT(IObuff, shortmess(SHM_RO) ? _("[RO]") : _("[readonly]"));
2450 c = TRUE;
2451 }
2452 if (read_no_eol_lnum)
2453 {
2454 msg_add_eol();
2455 c = TRUE;
2456 }
2457 if (ff_error == EOL_DOS)
2458 {
2459 STRCAT(IObuff, _("[CR missing]"));
2460 c = TRUE;
2461 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002462 if (split)
2463 {
2464 STRCAT(IObuff, _("[long lines split]"));
2465 c = TRUE;
2466 }
2467#ifdef FEAT_MBYTE
2468 if (notconverted)
2469 {
2470 STRCAT(IObuff, _("[NOT converted]"));
2471 c = TRUE;
2472 }
2473 else if (converted)
2474 {
2475 STRCAT(IObuff, _("[converted]"));
2476 c = TRUE;
2477 }
2478#endif
2479#ifdef FEAT_CRYPT
2480 if (cryptkey != NULL)
2481 {
2482 STRCAT(IObuff, _("[crypted]"));
2483 c = TRUE;
2484 }
2485#endif
2486#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002487 if (conv_error != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002488 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002489 sprintf((char *)IObuff + STRLEN(IObuff),
2490 _("[CONVERSION ERROR in line %ld]"), (long)conv_error);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002491 c = TRUE;
2492 }
2493 else if (illegal_byte > 0)
2494 {
2495 sprintf((char *)IObuff + STRLEN(IObuff),
2496 _("[ILLEGAL BYTE in line %ld]"), (long)illegal_byte);
2497 c = TRUE;
2498 }
2499 else
2500#endif
2501 if (error)
2502 {
2503 STRCAT(IObuff, _("[READ ERRORS]"));
2504 c = TRUE;
2505 }
2506 if (msg_add_fileformat(fileformat))
2507 c = TRUE;
2508#ifdef FEAT_CRYPT
2509 if (cryptkey != NULL)
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002510 msg_add_lines(c, (long)linecnt, filesize
Bram Moolenaar80794b12010-06-13 05:20:42 +02002511 - CRYPT_MAGIC_LEN
2512 - crypt_salt_len[use_crypt_method]
2513 - crypt_seed_len[use_crypt_method]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002514 else
2515#endif
2516 msg_add_lines(c, (long)linecnt, filesize);
2517
2518 vim_free(keep_msg);
2519 keep_msg = NULL;
2520 msg_scrolled_ign = TRUE;
2521#ifdef ALWAYS_USE_GUI
2522 /* Don't show the message when reading stdin, it would end up in a
2523 * message box (which might be shown when exiting!) */
2524 if (read_stdin || read_buffer)
2525 p = msg_may_trunc(FALSE, IObuff);
2526 else
2527#endif
2528 p = msg_trunc_attr(IObuff, FALSE, 0);
2529 if (read_stdin || read_buffer || restart_edit != 0
Bram Moolenaar1c7715d2005-10-03 22:02:18 +00002530 || (msg_scrolled != 0 && !need_wait_return))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002531 /* Need to repeat the message after redrawing when:
2532 * - When reading from stdin (the screen will be cleared next).
2533 * - When restart_edit is set (otherwise there will be a delay
2534 * before redrawing).
2535 * - When the screen was scrolled but there is no wait-return
2536 * prompt. */
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002537 set_keep_msg(p, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002538 msg_scrolled_ign = FALSE;
2539 }
2540
2541 /* with errors writing the file requires ":w!" */
2542 if (newfile && (error
2543#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002544 || conv_error != 0
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002545 || (illegal_byte > 0 && bad_char_behavior != BAD_KEEP)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002546#endif
2547 ))
2548 curbuf->b_p_ro = TRUE;
2549
2550 u_clearline(); /* cannot use "U" command after adding lines */
2551
2552 /*
2553 * In Ex mode: cursor at last new line.
2554 * Otherwise: cursor at first new line.
2555 */
2556 if (exmode_active)
2557 curwin->w_cursor.lnum = from + linecnt;
2558 else
2559 curwin->w_cursor.lnum = from + 1;
2560 check_cursor_lnum();
2561 beginline(BL_WHITE | BL_FIX); /* on first non-blank */
2562
2563 /*
2564 * Set '[ and '] marks to the newly read lines.
2565 */
2566 curbuf->b_op_start.lnum = from + 1;
2567 curbuf->b_op_start.col = 0;
2568 curbuf->b_op_end.lnum = from + linecnt;
2569 curbuf->b_op_end.col = 0;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002570
2571#ifdef WIN32
2572 /*
2573 * Work around a weird problem: When a file has two links (only
2574 * possible on NTFS) and we write through one link, then stat() it
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00002575 * through the other link, the timestamp information may be wrong.
Bram Moolenaar03f48552006-02-28 23:52:23 +00002576 * It's correct again after reading the file, thus reset the timestamp
2577 * here.
2578 */
2579 if (newfile && !read_stdin && !read_buffer
2580 && mch_stat((char *)fname, &st) >= 0)
2581 {
2582 buf_store_time(curbuf, &st, fname);
2583 curbuf->b_mtime_read = curbuf->b_mtime;
2584 }
2585#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002586 }
2587 msg_scroll = msg_save;
2588
2589#ifdef FEAT_VIMINFO
2590 /*
2591 * Get the marks before executing autocommands, so they can be used there.
2592 */
2593 check_marks_read();
2594#endif
2595
Bram Moolenaar071d4272004-06-13 20:20:40 +00002596 /*
2597 * Trick: We remember if the last line of the read didn't have
2598 * an eol for when writing it again. This is required for
2599 * ":autocmd FileReadPost *.gz set bin|'[,']!gunzip" to work.
2600 */
2601 write_no_eol_lnum = read_no_eol_lnum;
2602
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002603#ifdef FEAT_PERSISTENT_UNDO
2604 /*
2605 * When opening a new file locate undo info and read it.
2606 */
2607 if (read_undo_file)
2608 {
2609 char_u hash[UNDO_HASH_SIZE];
2610
2611 sha256_finish(&sha_ctx, hash);
Bram Moolenaar6ed8ed82010-05-30 20:40:11 +02002612 u_read_undo(NULL, hash, fname);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002613 }
2614#endif
2615
Bram Moolenaardf177f62005-02-22 08:39:57 +00002616#ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00002617 if (!read_stdin && !read_buffer)
2618 {
2619 int m = msg_scroll;
2620 int n = msg_scrolled;
2621
2622 /* Save the fileformat now, otherwise the buffer will be considered
2623 * modified if the format/encoding was automatically detected. */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002624 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002625 save_file_ff(curbuf);
2626
2627 /*
2628 * The output from the autocommands should not overwrite anything and
2629 * should not be overwritten: Set msg_scroll, restore its value if no
2630 * output was done.
2631 */
2632 msg_scroll = TRUE;
2633 if (filtering)
2634 apply_autocmds_exarg(EVENT_FILTERREADPOST, NULL, sfname,
2635 FALSE, curbuf, eap);
2636 else if (newfile)
2637 apply_autocmds_exarg(EVENT_BUFREADPOST, NULL, sfname,
2638 FALSE, curbuf, eap);
2639 else
2640 apply_autocmds_exarg(EVENT_FILEREADPOST, sfname, sfname,
2641 FALSE, NULL, eap);
2642 if (msg_scrolled == n)
2643 msg_scroll = m;
2644#ifdef FEAT_EVAL
2645 if (aborting()) /* autocmds may abort script processing */
2646 return FAIL;
2647#endif
2648 }
2649#endif
2650
2651 if (recoverymode && error)
2652 return FAIL;
2653 return OK;
2654}
2655
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002656#ifdef OPEN_CHR_FILES
2657/*
2658 * Returns TRUE if the file name argument is of the form "/dev/fd/\d\+",
2659 * which is the name of files used for process substitution output by
2660 * some shells on some operating systems, e.g., bash on SunOS.
2661 * Do not accept "/dev/fd/[012]", opening these may hang Vim.
2662 */
2663 static int
2664is_dev_fd_file(fname)
2665 char_u *fname;
2666{
2667 return (STRNCMP(fname, "/dev/fd/", 8) == 0
2668 && VIM_ISDIGIT(fname[8])
2669 && *skipdigits(fname + 9) == NUL
2670 && (fname[9] != NUL
2671 || (fname[8] != '0' && fname[8] != '1' && fname[8] != '2')));
2672}
2673#endif
2674
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002675#ifdef FEAT_MBYTE
2676
2677/*
2678 * From the current line count and characters read after that, estimate the
2679 * line number where we are now.
2680 * Used for error messages that include a line number.
2681 */
2682 static linenr_T
2683readfile_linenr(linecnt, p, endp)
2684 linenr_T linecnt; /* line count before reading more bytes */
2685 char_u *p; /* start of more bytes read */
2686 char_u *endp; /* end of more bytes read */
2687{
2688 char_u *s;
2689 linenr_T lnum;
2690
2691 lnum = curbuf->b_ml.ml_line_count - linecnt + 1;
2692 for (s = p; s < endp; ++s)
2693 if (*s == '\n')
2694 ++lnum;
2695 return lnum;
2696}
2697#endif
2698
Bram Moolenaar071d4272004-06-13 20:20:40 +00002699/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00002700 * Fill "*eap" to force the 'fileencoding', 'fileformat' and 'binary to be
2701 * equal to the buffer "buf". Used for calling readfile().
Bram Moolenaar071d4272004-06-13 20:20:40 +00002702 * Returns OK or FAIL.
2703 */
2704 int
2705prep_exarg(eap, buf)
2706 exarg_T *eap;
2707 buf_T *buf;
2708{
2709 eap->cmd = alloc((unsigned)(STRLEN(buf->b_p_ff)
2710#ifdef FEAT_MBYTE
2711 + STRLEN(buf->b_p_fenc)
2712#endif
2713 + 15));
2714 if (eap->cmd == NULL)
2715 return FAIL;
2716
2717#ifdef FEAT_MBYTE
2718 sprintf((char *)eap->cmd, "e ++ff=%s ++enc=%s", buf->b_p_ff, buf->b_p_fenc);
2719 eap->force_enc = 14 + (int)STRLEN(buf->b_p_ff);
Bram Moolenaar195d6352005-12-19 22:08:24 +00002720 eap->bad_char = buf->b_bad_char;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002721#else
2722 sprintf((char *)eap->cmd, "e ++ff=%s", buf->b_p_ff);
2723#endif
2724 eap->force_ff = 7;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002725
2726 eap->force_bin = buf->b_p_bin ? FORCE_BIN : FORCE_NOBIN;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002727 eap->read_edit = FALSE;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002728 eap->forceit = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002729 return OK;
2730}
2731
2732#ifdef FEAT_MBYTE
2733/*
2734 * Find next fileencoding to use from 'fileencodings'.
2735 * "pp" points to fenc_next. It's advanced to the next item.
2736 * When there are no more items, an empty string is returned and *pp is set to
2737 * NULL.
2738 * When *pp is not set to NULL, the result is in allocated memory.
2739 */
2740 static char_u *
2741next_fenc(pp)
2742 char_u **pp;
2743{
2744 char_u *p;
2745 char_u *r;
2746
2747 if (**pp == NUL)
2748 {
2749 *pp = NULL;
2750 return (char_u *)"";
2751 }
2752 p = vim_strchr(*pp, ',');
2753 if (p == NULL)
2754 {
2755 r = enc_canonize(*pp);
2756 *pp += STRLEN(*pp);
2757 }
2758 else
2759 {
2760 r = vim_strnsave(*pp, (int)(p - *pp));
2761 *pp = p + 1;
2762 if (r != NULL)
2763 {
2764 p = enc_canonize(r);
2765 vim_free(r);
2766 r = p;
2767 }
2768 }
2769 if (r == NULL) /* out of memory */
2770 {
2771 r = (char_u *)"";
2772 *pp = NULL;
2773 }
2774 return r;
2775}
2776
2777# ifdef FEAT_EVAL
2778/*
2779 * Convert a file with the 'charconvert' expression.
2780 * This closes the file which is to be read, converts it and opens the
2781 * resulting file for reading.
2782 * Returns name of the resulting converted file (the caller should delete it
2783 * after reading it).
2784 * Returns NULL if the conversion failed ("*fdp" is not set) .
2785 */
2786 static char_u *
2787readfile_charconvert(fname, fenc, fdp)
2788 char_u *fname; /* name of input file */
2789 char_u *fenc; /* converted from */
2790 int *fdp; /* in/out: file descriptor of file */
2791{
2792 char_u *tmpname;
2793 char_u *errmsg = NULL;
2794
2795 tmpname = vim_tempname('r');
2796 if (tmpname == NULL)
2797 errmsg = (char_u *)_("Can't find temp file for conversion");
2798 else
2799 {
2800 close(*fdp); /* close the input file, ignore errors */
2801 *fdp = -1;
2802 if (eval_charconvert(fenc, enc_utf8 ? (char_u *)"utf-8" : p_enc,
2803 fname, tmpname) == FAIL)
2804 errmsg = (char_u *)_("Conversion with 'charconvert' failed");
2805 if (errmsg == NULL && (*fdp = mch_open((char *)tmpname,
2806 O_RDONLY | O_EXTRA, 0)) < 0)
2807 errmsg = (char_u *)_("can't read output of 'charconvert'");
2808 }
2809
2810 if (errmsg != NULL)
2811 {
2812 /* Don't use emsg(), it breaks mappings, the retry with
2813 * another type of conversion might still work. */
2814 MSG(errmsg);
2815 if (tmpname != NULL)
2816 {
2817 mch_remove(tmpname); /* delete converted file */
2818 vim_free(tmpname);
2819 tmpname = NULL;
2820 }
2821 }
2822
2823 /* If the input file is closed, open it (caller should check for error). */
2824 if (*fdp < 0)
2825 *fdp = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
2826
2827 return tmpname;
2828}
2829# endif
2830
2831#endif
2832
2833#ifdef FEAT_VIMINFO
2834/*
2835 * Read marks for the current buffer from the viminfo file, when we support
2836 * buffer marks and the buffer has a name.
2837 */
2838 static void
2839check_marks_read()
2840{
2841 if (!curbuf->b_marks_read && get_viminfo_parameter('\'') > 0
2842 && curbuf->b_ffname != NULL)
Bram Moolenaard812df62008-11-09 12:46:09 +00002843 read_viminfo(NULL, VIF_WANT_MARKS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002844
2845 /* Always set b_marks_read; needed when 'viminfo' is changed to include
2846 * the ' parameter after opening a buffer. */
2847 curbuf->b_marks_read = TRUE;
2848}
2849#endif
2850
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002851#if defined(FEAT_CRYPT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002852/*
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002853 * Get the crypt method used for a file from "ptr[len]", the magic text at the
2854 * start of the file.
2855 * Returns -1 when no encryption used.
2856 */
2857 static int
2858get_crypt_method(ptr, len)
2859 char *ptr;
2860 int len;
2861{
2862 int i;
2863
2864 for (i = 0; i < (int)(sizeof(crypt_magic) / sizeof(crypt_magic[0])); i++)
2865 {
Bram Moolenaar80794b12010-06-13 05:20:42 +02002866 if (len < (CRYPT_MAGIC_LEN + crypt_salt_len[i] + crypt_seed_len[i]))
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002867 continue;
2868 if (memcmp(ptr, crypt_magic[i], CRYPT_MAGIC_LEN) == 0)
2869 return i;
2870 }
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002871
Bram Moolenaar442b4222010-05-24 21:34:22 +02002872 i = (int)STRLEN(crypt_magic_head);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002873 if (len >= i && memcmp(ptr, crypt_magic_head, i) == 0)
2874 EMSG(_("E821: File is encrypted with unknown method"));
2875
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002876 return -1;
2877}
2878
2879/*
2880 * Check for magic number used for encryption. Applies to the current buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002881 * If found, the magic number is removed from ptr[*sizep] and *sizep and
2882 * *filesizep are updated.
2883 * Return the (new) encryption key, NULL for no encryption.
2884 */
2885 static char_u *
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002886check_for_cryptkey(cryptkey, ptr, sizep, filesizep, newfile, fname, did_ask)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002887 char_u *cryptkey; /* previous encryption key or NULL */
2888 char_u *ptr; /* pointer to read bytes */
2889 long *sizep; /* length of read bytes */
Bram Moolenaar914703b2010-05-31 21:59:46 +02002890 off_t *filesizep; /* nr of bytes used from file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002891 int newfile; /* editing a new buffer */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002892 char_u *fname; /* file name to display */
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002893 int *did_ask; /* flag: whether already asked for key */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002894{
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002895 int method = get_crypt_method((char *)ptr, *sizep);
2896
2897 if (method >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002898 {
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002899 curbuf->b_p_cm = method;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002900 if (method > 0)
2901 (void)blowfish_self_test();
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002902 if (cryptkey == NULL && !*did_ask)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002903 {
2904 if (*curbuf->b_p_key)
2905 cryptkey = curbuf->b_p_key;
2906 else
2907 {
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002908 /* When newfile is TRUE, store the typed key in the 'key'
2909 * option and don't free it. bf needs hash of the key saved.
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002910 * Don't ask for the key again when first time Enter was hit.
2911 * Happens when retrying to detect encoding. */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002912 smsg((char_u *)_(need_key_msg), fname);
2913 msg_scroll = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002914 cryptkey = get_crypt_key(newfile, FALSE);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002915 *did_ask = TRUE;
2916
Bram Moolenaar071d4272004-06-13 20:20:40 +00002917 /* check if empty key entered */
2918 if (cryptkey != NULL && *cryptkey == NUL)
2919 {
2920 if (cryptkey != curbuf->b_p_key)
2921 vim_free(cryptkey);
2922 cryptkey = NULL;
2923 }
2924 }
2925 }
2926
2927 if (cryptkey != NULL)
2928 {
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002929 int seed_len = crypt_seed_len[method];
Bram Moolenaar80794b12010-06-13 05:20:42 +02002930 int salt_len = crypt_salt_len[method];
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002931
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002932 crypt_push_state();
2933 use_crypt_method = method;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002934 if (method == 0)
2935 crypt_init_keys(cryptkey);
2936 else
2937 {
Bram Moolenaar80794b12010-06-13 05:20:42 +02002938 bf_key_init(cryptkey, ptr + CRYPT_MAGIC_LEN, salt_len);
2939 bf_ofb_init(ptr + CRYPT_MAGIC_LEN + salt_len, seed_len);
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002940 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002941
2942 /* Remove magic number from the text */
Bram Moolenaar80794b12010-06-13 05:20:42 +02002943 *filesizep += CRYPT_MAGIC_LEN + salt_len + seed_len;
2944 *sizep -= CRYPT_MAGIC_LEN + salt_len + seed_len;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002945 mch_memmove(ptr, ptr + CRYPT_MAGIC_LEN + salt_len + seed_len,
2946 (size_t)*sizep);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002947 }
2948 }
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002949 /* When starting to edit a new file which does not have encryption, clear
2950 * the 'key' option, except when starting up (called with -x argument) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002951 else if (newfile && *curbuf->b_p_key && !starting)
2952 set_option_value((char_u *)"key", 0L, (char_u *)"", OPT_LOCAL);
2953
2954 return cryptkey;
2955}
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002956
2957/*
2958 * Check for magic number used for encryption. Applies to the current buffer.
2959 * If found and decryption is possible returns OK;
2960 */
2961 int
2962prepare_crypt_read(fp)
2963 FILE *fp;
2964{
2965 int method;
Bram Moolenaar80794b12010-06-13 05:20:42 +02002966 char_u buffer[CRYPT_MAGIC_LEN + CRYPT_SALT_LEN_MAX
2967 + CRYPT_SEED_LEN_MAX + 2];
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002968
2969 if (fread(buffer, CRYPT_MAGIC_LEN, 1, fp) != 1)
2970 return FAIL;
2971 method = get_crypt_method((char *)buffer,
Bram Moolenaar80794b12010-06-13 05:20:42 +02002972 CRYPT_MAGIC_LEN +
2973 CRYPT_SEED_LEN_MAX +
2974 CRYPT_SALT_LEN_MAX);
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002975 if (method < 0 || method != curbuf->b_p_cm)
2976 return FAIL;
2977
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002978 crypt_push_state();
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002979 if (method == 0)
2980 crypt_init_keys(curbuf->b_p_key);
2981 else
2982 {
Bram Moolenaar80794b12010-06-13 05:20:42 +02002983 int salt_len = crypt_salt_len[method];
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002984 int seed_len = crypt_seed_len[method];
2985
Bram Moolenaar80794b12010-06-13 05:20:42 +02002986 if (fread(buffer, salt_len + seed_len, 1, fp) != 1)
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002987 return FAIL;
Bram Moolenaar80794b12010-06-13 05:20:42 +02002988 bf_key_init(curbuf->b_p_key, buffer, salt_len);
2989 bf_ofb_init(buffer + salt_len, seed_len);
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002990 }
2991 return OK;
2992}
2993
2994/*
2995 * Prepare for writing encrypted bytes for buffer "buf".
2996 * Returns a pointer to an allocated header of length "*lenp".
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002997 * When out of memory returns NULL.
2998 * Otherwise calls crypt_push_state(), call crypt_pop_state() later.
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002999 */
3000 char_u *
3001prepare_crypt_write(buf, lenp)
3002 buf_T *buf;
3003 int *lenp;
3004{
3005 char_u *header;
3006 int seed_len = crypt_seed_len[buf->b_p_cm];
Bram Moolenaar80794b12010-06-13 05:20:42 +02003007 int salt_len = crypt_salt_len[buf->b_p_cm];
3008 char_u *salt;
3009 char_u *seed;
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003010
Bram Moolenaar80794b12010-06-13 05:20:42 +02003011 header = alloc_clear(CRYPT_MAGIC_LEN + CRYPT_SALT_LEN_MAX
3012 + CRYPT_SEED_LEN_MAX + 2);
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003013 if (header != NULL)
3014 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003015 crypt_push_state();
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003016 use_crypt_method = buf->b_p_cm; /* select pkzip or blowfish */
3017 vim_strncpy(header, (char_u *)crypt_magic[use_crypt_method],
3018 CRYPT_MAGIC_LEN);
3019 if (buf->b_p_cm == 0)
3020 crypt_init_keys(buf->b_p_key);
3021 else
3022 {
Bram Moolenaar80794b12010-06-13 05:20:42 +02003023 /* Using blowfish, add salt and seed. */
3024 salt = header + CRYPT_MAGIC_LEN;
3025 seed = salt + salt_len;
3026 sha2_seed(salt, salt_len, seed, seed_len);
3027 bf_key_init(buf->b_p_key, salt, salt_len);
3028 bf_ofb_init(seed, seed_len);
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003029 }
3030 }
Bram Moolenaar80794b12010-06-13 05:20:42 +02003031 *lenp = CRYPT_MAGIC_LEN + salt_len + seed_len;
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003032 return header;
3033}
3034
Bram Moolenaar80794b12010-06-13 05:20:42 +02003035#endif /* FEAT_CRYPT */
3036
Bram Moolenaar071d4272004-06-13 20:20:40 +00003037#ifdef UNIX
3038 static void
3039set_file_time(fname, atime, mtime)
3040 char_u *fname;
3041 time_t atime; /* access time */
3042 time_t mtime; /* modification time */
3043{
3044# if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
3045 struct utimbuf buf;
3046
3047 buf.actime = atime;
3048 buf.modtime = mtime;
3049 (void)utime((char *)fname, &buf);
3050# else
3051# if defined(HAVE_UTIMES)
3052 struct timeval tvp[2];
3053
3054 tvp[0].tv_sec = atime;
3055 tvp[0].tv_usec = 0;
3056 tvp[1].tv_sec = mtime;
3057 tvp[1].tv_usec = 0;
3058# ifdef NeXT
3059 (void)utimes((char *)fname, tvp);
3060# else
3061 (void)utimes((char *)fname, (const struct timeval *)&tvp);
3062# endif
3063# endif
3064# endif
3065}
3066#endif /* UNIX */
3067
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003068#if defined(VMS) && !defined(MIN)
3069/* Older DECC compiler for VAX doesn't define MIN() */
3070# define MIN(a, b) ((a) < (b) ? (a) : (b))
3071#endif
3072
Bram Moolenaar071d4272004-06-13 20:20:40 +00003073/*
Bram Moolenaar5386a122007-06-28 20:02:32 +00003074 * Return TRUE if a file appears to be read-only from the file permissions.
3075 */
3076 int
3077check_file_readonly(fname, perm)
3078 char_u *fname; /* full path to file */
3079 int perm; /* known permissions on file */
3080{
3081#ifndef USE_MCH_ACCESS
3082 int fd = 0;
3083#endif
3084
3085 return (
3086#ifdef USE_MCH_ACCESS
3087# ifdef UNIX
3088 (perm & 0222) == 0 ||
3089# endif
3090 mch_access((char *)fname, W_OK)
3091#else
3092 (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0
3093 ? TRUE : (close(fd), FALSE)
3094#endif
3095 );
3096}
3097
3098
3099/*
Bram Moolenaar292ad192005-12-11 21:29:51 +00003100 * buf_write() - write to file "fname" lines "start" through "end"
Bram Moolenaar071d4272004-06-13 20:20:40 +00003101 *
3102 * We do our own buffering here because fwrite() is so slow.
3103 *
Bram Moolenaar292ad192005-12-11 21:29:51 +00003104 * If "forceit" is true, we don't care for errors when attempting backups.
3105 * In case of an error everything possible is done to restore the original
Bram Moolenaare37d50a2008-08-06 17:06:04 +00003106 * file. But when "forceit" is TRUE, we risk losing it.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003107 *
3108 * When "reset_changed" is TRUE and "append" == FALSE and "start" == 1 and
3109 * "end" == curbuf->b_ml.ml_line_count, reset curbuf->b_changed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003110 *
3111 * This function must NOT use NameBuff (because it's called by autowrite()).
3112 *
3113 * return FAIL for failure, OK otherwise
3114 */
3115 int
3116buf_write(buf, fname, sfname, start, end, eap, append, forceit,
3117 reset_changed, filtering)
3118 buf_T *buf;
3119 char_u *fname;
3120 char_u *sfname;
3121 linenr_T start, end;
3122 exarg_T *eap; /* for forced 'ff' and 'fenc', can be
3123 NULL! */
Bram Moolenaar292ad192005-12-11 21:29:51 +00003124 int append; /* append to the file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003125 int forceit;
3126 int reset_changed;
3127 int filtering;
3128{
3129 int fd;
3130 char_u *backup = NULL;
3131 int backup_copy = FALSE; /* copy the original file? */
3132 int dobackup;
3133 char_u *ffname;
3134 char_u *wfname = NULL; /* name of file to write to */
3135 char_u *s;
3136 char_u *ptr;
3137 char_u c;
3138 int len;
3139 linenr_T lnum;
3140 long nchars;
3141 char_u *errmsg = NULL;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003142 int errmsg_allocated = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003143 char_u *errnum = NULL;
3144 char_u *buffer;
3145 char_u smallbuf[SMBUFSIZE];
3146 char_u *backup_ext;
3147 int bufsize;
3148 long perm; /* file permissions */
3149 int retval = OK;
3150 int newfile = FALSE; /* TRUE if file doesn't exist yet */
3151 int msg_save = msg_scroll;
3152 int overwriting; /* TRUE if writing over original */
3153 int no_eol = FALSE; /* no end-of-line written */
3154 int device = FALSE; /* writing to a device */
3155 struct stat st_old;
3156 int prev_got_int = got_int;
3157 int file_readonly = FALSE; /* overwritten file is read-only */
3158 static char *err_readonly = "is read-only (cannot override: \"W\" in 'cpoptions')";
3159#if defined(UNIX) || defined(__EMX__XX) /*XXX fix me sometime? */
3160 int made_writable = FALSE; /* 'w' bit has been set */
3161#endif
3162 /* writing everything */
3163 int whole = (start == 1 && end == buf->b_ml.ml_line_count);
3164#ifdef FEAT_AUTOCMD
3165 linenr_T old_line_count = buf->b_ml.ml_line_count;
3166#endif
3167 int attr;
3168 int fileformat;
3169 int write_bin;
3170 struct bw_info write_info; /* info for buf_write_bytes() */
3171#ifdef FEAT_MBYTE
3172 int converted = FALSE;
3173 int notconverted = FALSE;
3174 char_u *fenc; /* effective 'fileencoding' */
3175 char_u *fenc_tofree = NULL; /* allocated "fenc" */
3176#endif
3177#ifdef HAS_BW_FLAGS
3178 int wb_flags = 0;
3179#endif
3180#ifdef HAVE_ACL
3181 vim_acl_T acl = NULL; /* ACL copied from original file to
3182 backup or new file */
3183#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003184#ifdef FEAT_PERSISTENT_UNDO
3185 int write_undo_file = FALSE;
3186 context_sha256_T sha_ctx;
3187#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003188
3189 if (fname == NULL || *fname == NUL) /* safety check */
3190 return FAIL;
Bram Moolenaar70d60e92009-12-31 13:53:33 +00003191 if (buf->b_ml.ml_mfp == NULL)
3192 {
3193 /* This can happen during startup when there is a stray "w" in the
3194 * vimrc file. */
3195 EMSG(_(e_emptybuf));
3196 return FAIL;
3197 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003198
3199 /*
3200 * Disallow writing from .exrc and .vimrc in current directory for
3201 * security reasons.
3202 */
3203 if (check_secure())
3204 return FAIL;
3205
3206 /* Avoid a crash for a long name. */
3207 if (STRLEN(fname) >= MAXPATHL)
3208 {
3209 EMSG(_(e_longname));
3210 return FAIL;
3211 }
3212
3213#ifdef FEAT_MBYTE
3214 /* must init bw_conv_buf and bw_iconv_fd before jumping to "fail" */
3215 write_info.bw_conv_buf = NULL;
3216 write_info.bw_conv_error = FALSE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003217 write_info.bw_conv_error_lnum = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003218 write_info.bw_restlen = 0;
3219# ifdef USE_ICONV
3220 write_info.bw_iconv_fd = (iconv_t)-1;
3221# endif
3222#endif
3223
Bram Moolenaardf177f62005-02-22 08:39:57 +00003224 /* After writing a file changedtick changes but we don't want to display
3225 * the line. */
3226 ex_no_reprint = TRUE;
3227
Bram Moolenaar071d4272004-06-13 20:20:40 +00003228 /*
3229 * If there is no file name yet, use the one for the written file.
3230 * BF_NOTEDITED is set to reflect this (in case the write fails).
3231 * Don't do this when the write is for a filter command.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003232 * Don't do this when appending.
3233 * Only do this when 'cpoptions' contains the 'F' flag.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003234 */
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003235 if (buf->b_ffname == NULL
3236 && reset_changed
Bram Moolenaar071d4272004-06-13 20:20:40 +00003237 && whole
3238 && buf == curbuf
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00003239#ifdef FEAT_QUICKFIX
3240 && !bt_nofile(buf)
3241#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003242 && !filtering
Bram Moolenaar292ad192005-12-11 21:29:51 +00003243 && (!append || vim_strchr(p_cpo, CPO_FNAMEAPP) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003244 && vim_strchr(p_cpo, CPO_FNAMEW) != NULL)
3245 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003246 if (set_rw_fname(fname, sfname) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003247 return FAIL;
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003248 buf = curbuf; /* just in case autocmds made "buf" invalid */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003249 }
3250
3251 if (sfname == NULL)
3252 sfname = fname;
3253 /*
3254 * For Unix: Use the short file name whenever possible.
3255 * Avoids problems with networks and when directory names are changed.
3256 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
3257 * another directory, which we don't detect
3258 */
3259 ffname = fname; /* remember full fname */
3260#ifdef UNIX
3261 fname = sfname;
3262#endif
3263
3264 if (buf->b_ffname != NULL && fnamecmp(ffname, buf->b_ffname) == 0)
3265 overwriting = TRUE;
3266 else
3267 overwriting = FALSE;
3268
3269 if (exiting)
3270 settmode(TMODE_COOK); /* when exiting allow typahead now */
3271
3272 ++no_wait_return; /* don't wait for return yet */
3273
3274 /*
3275 * Set '[ and '] marks to the lines to be written.
3276 */
3277 buf->b_op_start.lnum = start;
3278 buf->b_op_start.col = 0;
3279 buf->b_op_end.lnum = end;
3280 buf->b_op_end.col = 0;
3281
3282#ifdef FEAT_AUTOCMD
3283 {
3284 aco_save_T aco;
3285 int buf_ffname = FALSE;
3286 int buf_sfname = FALSE;
3287 int buf_fname_f = FALSE;
3288 int buf_fname_s = FALSE;
3289 int did_cmd = FALSE;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003290 int nofile_err = FALSE;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003291 int empty_memline = (buf->b_ml.ml_mfp == NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003292
3293 /*
3294 * Apply PRE aucocommands.
3295 * Set curbuf to the buffer to be written.
3296 * Careful: The autocommands may call buf_write() recursively!
3297 */
3298 if (ffname == buf->b_ffname)
3299 buf_ffname = TRUE;
3300 if (sfname == buf->b_sfname)
3301 buf_sfname = TRUE;
3302 if (fname == buf->b_ffname)
3303 buf_fname_f = TRUE;
3304 if (fname == buf->b_sfname)
3305 buf_fname_s = TRUE;
3306
3307 /* set curwin/curbuf to buf and save a few things */
3308 aucmd_prepbuf(&aco, buf);
3309
3310 if (append)
3311 {
3312 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD,
3313 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003314 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003315#ifdef FEAT_QUICKFIX
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00003316 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003317 nofile_err = TRUE;
3318 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003319#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003320 apply_autocmds_exarg(EVENT_FILEAPPENDPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003321 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003322 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003323 }
3324 else if (filtering)
3325 {
3326 apply_autocmds_exarg(EVENT_FILTERWRITEPRE,
3327 NULL, sfname, FALSE, curbuf, eap);
3328 }
3329 else if (reset_changed && whole)
3330 {
3331 if (!(did_cmd = apply_autocmds_exarg(EVENT_BUFWRITECMD,
3332 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003333 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003334#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003335 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003336 nofile_err = TRUE;
3337 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003338#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003339 apply_autocmds_exarg(EVENT_BUFWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003340 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003341 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003342 }
3343 else
3344 {
3345 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD,
3346 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003347 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003348#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003349 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003350 nofile_err = TRUE;
3351 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003352#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003353 apply_autocmds_exarg(EVENT_FILEWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003354 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003355 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003356 }
3357
3358 /* restore curwin/curbuf and a few other things */
3359 aucmd_restbuf(&aco);
3360
3361 /*
3362 * In three situations we return here and don't write the file:
3363 * 1. the autocommands deleted or unloaded the buffer.
3364 * 2. The autocommands abort script processing.
3365 * 3. If one of the "Cmd" autocommands was executed.
3366 */
3367 if (!buf_valid(buf))
3368 buf = NULL;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003369 if (buf == NULL || (buf->b_ml.ml_mfp == NULL && !empty_memline)
Bram Moolenaar1e015462005-09-25 22:16:38 +00003370 || did_cmd || nofile_err
3371#ifdef FEAT_EVAL
3372 || aborting()
3373#endif
3374 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003375 {
3376 --no_wait_return;
3377 msg_scroll = msg_save;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003378 if (nofile_err)
3379 EMSG(_("E676: No matching autocommands for acwrite buffer"));
3380
Bram Moolenaar1e015462005-09-25 22:16:38 +00003381 if (nofile_err
3382#ifdef FEAT_EVAL
3383 || aborting()
3384#endif
3385 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003386 /* An aborting error, interrupt or exception in the
3387 * autocommands. */
3388 return FAIL;
3389 if (did_cmd)
3390 {
3391 if (buf == NULL)
3392 /* The buffer was deleted. We assume it was written
3393 * (can't retry anyway). */
3394 return OK;
3395 if (overwriting)
3396 {
3397 /* Assume the buffer was written, update the timestamp. */
3398 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00003399 if (append)
3400 buf->b_flags &= ~BF_NEW;
3401 else
3402 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003403 }
Bram Moolenaar292ad192005-12-11 21:29:51 +00003404 if (reset_changed && buf->b_changed && !append
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003405 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003406 /* Buffer still changed, the autocommands didn't work
3407 * properly. */
3408 return FAIL;
3409 return OK;
3410 }
3411#ifdef FEAT_EVAL
3412 if (!aborting())
3413#endif
3414 EMSG(_("E203: Autocommands deleted or unloaded buffer to be written"));
3415 return FAIL;
3416 }
3417
3418 /*
3419 * The autocommands may have changed the number of lines in the file.
3420 * When writing the whole file, adjust the end.
3421 * When writing part of the file, assume that the autocommands only
3422 * changed the number of lines that are to be written (tricky!).
3423 */
3424 if (buf->b_ml.ml_line_count != old_line_count)
3425 {
3426 if (whole) /* write all */
3427 end = buf->b_ml.ml_line_count;
3428 else if (buf->b_ml.ml_line_count > old_line_count) /* more lines */
3429 end += buf->b_ml.ml_line_count - old_line_count;
3430 else /* less lines */
3431 {
3432 end -= old_line_count - buf->b_ml.ml_line_count;
3433 if (end < start)
3434 {
3435 --no_wait_return;
3436 msg_scroll = msg_save;
3437 EMSG(_("E204: Autocommand changed number of lines in unexpected way"));
3438 return FAIL;
3439 }
3440 }
3441 }
3442
3443 /*
3444 * The autocommands may have changed the name of the buffer, which may
3445 * be kept in fname, ffname and sfname.
3446 */
3447 if (buf_ffname)
3448 ffname = buf->b_ffname;
3449 if (buf_sfname)
3450 sfname = buf->b_sfname;
3451 if (buf_fname_f)
3452 fname = buf->b_ffname;
3453 if (buf_fname_s)
3454 fname = buf->b_sfname;
3455 }
3456#endif
3457
3458#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003459 if (netbeans_active() && isNetbeansBuffer(buf))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003460 {
3461 if (whole)
3462 {
3463 /*
3464 * b_changed can be 0 after an undo, but we still need to write
3465 * the buffer to NetBeans.
3466 */
3467 if (buf->b_changed || isNetbeansModified(buf))
3468 {
Bram Moolenaar009b2592004-10-24 19:18:58 +00003469 --no_wait_return; /* may wait for return now */
3470 msg_scroll = msg_save;
3471 netbeans_save_buffer(buf); /* no error checking... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003472 return retval;
3473 }
3474 else
3475 {
3476 errnum = (char_u *)"E656: ";
Bram Moolenaared0e7452008-06-27 19:17:34 +00003477 errmsg = (char_u *)_("NetBeans disallows writes of unmodified buffers");
Bram Moolenaar071d4272004-06-13 20:20:40 +00003478 buffer = NULL;
3479 goto fail;
3480 }
3481 }
3482 else
3483 {
3484 errnum = (char_u *)"E657: ";
3485 errmsg = (char_u *)_("Partial writes disallowed for NetBeans buffers");
3486 buffer = NULL;
3487 goto fail;
3488 }
3489 }
3490#endif
3491
3492 if (shortmess(SHM_OVER) && !exiting)
3493 msg_scroll = FALSE; /* overwrite previous file message */
3494 else
3495 msg_scroll = TRUE; /* don't overwrite previous file message */
3496 if (!filtering)
3497 filemess(buf,
3498#ifndef UNIX
3499 sfname,
3500#else
3501 fname,
3502#endif
3503 (char_u *)"", 0); /* show that we are busy */
3504 msg_scroll = FALSE; /* always overwrite the file message now */
3505
3506 buffer = alloc(BUFSIZE);
3507 if (buffer == NULL) /* can't allocate big buffer, use small
3508 * one (to be able to write when out of
3509 * memory) */
3510 {
3511 buffer = smallbuf;
3512 bufsize = SMBUFSIZE;
3513 }
3514 else
3515 bufsize = BUFSIZE;
3516
3517 /*
3518 * Get information about original file (if there is one).
3519 */
3520#if defined(UNIX) && !defined(ARCHIE)
Bram Moolenaar6f192452007-11-08 19:49:02 +00003521 st_old.st_dev = 0;
3522 st_old.st_ino = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003523 perm = -1;
3524 if (mch_stat((char *)fname, &st_old) < 0)
3525 newfile = TRUE;
3526 else
3527 {
3528 perm = st_old.st_mode;
3529 if (!S_ISREG(st_old.st_mode)) /* not a file */
3530 {
3531 if (S_ISDIR(st_old.st_mode))
3532 {
3533 errnum = (char_u *)"E502: ";
3534 errmsg = (char_u *)_("is a directory");
3535 goto fail;
3536 }
3537 if (mch_nodetype(fname) != NODE_WRITABLE)
3538 {
3539 errnum = (char_u *)"E503: ";
3540 errmsg = (char_u *)_("is not a file or writable device");
3541 goto fail;
3542 }
3543 /* It's a device of some kind (or a fifo) which we can write to
3544 * but for which we can't make a backup. */
3545 device = TRUE;
3546 newfile = TRUE;
3547 perm = -1;
3548 }
3549 }
3550#else /* !UNIX */
3551 /*
3552 * Check for a writable device name.
3553 */
3554 c = mch_nodetype(fname);
3555 if (c == NODE_OTHER)
3556 {
3557 errnum = (char_u *)"E503: ";
3558 errmsg = (char_u *)_("is not a file or writable device");
3559 goto fail;
3560 }
3561 if (c == NODE_WRITABLE)
3562 {
Bram Moolenaar043545e2006-10-10 16:44:07 +00003563# if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3564 /* MS-Windows allows opening a device, but we will probably get stuck
3565 * trying to write to it. */
3566 if (!p_odev)
3567 {
3568 errnum = (char_u *)"E796: ";
3569 errmsg = (char_u *)_("writing to device disabled with 'opendevice' option");
3570 goto fail;
3571 }
3572# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003573 device = TRUE;
3574 newfile = TRUE;
3575 perm = -1;
3576 }
3577 else
3578 {
3579 perm = mch_getperm(fname);
3580 if (perm < 0)
3581 newfile = TRUE;
3582 else if (mch_isdir(fname))
3583 {
3584 errnum = (char_u *)"E502: ";
3585 errmsg = (char_u *)_("is a directory");
3586 goto fail;
3587 }
3588 if (overwriting)
3589 (void)mch_stat((char *)fname, &st_old);
3590 }
3591#endif /* !UNIX */
3592
3593 if (!device && !newfile)
3594 {
3595 /*
3596 * Check if the file is really writable (when renaming the file to
3597 * make a backup we won't discover it later).
3598 */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003599 file_readonly = check_file_readonly(fname, (int)perm);
3600
Bram Moolenaar071d4272004-06-13 20:20:40 +00003601 if (!forceit && file_readonly)
3602 {
3603 if (vim_strchr(p_cpo, CPO_FWRITE) != NULL)
3604 {
3605 errnum = (char_u *)"E504: ";
3606 errmsg = (char_u *)_(err_readonly);
3607 }
3608 else
3609 {
3610 errnum = (char_u *)"E505: ";
3611 errmsg = (char_u *)_("is read-only (add ! to override)");
3612 }
3613 goto fail;
3614 }
3615
3616 /*
3617 * Check if the timestamp hasn't changed since reading the file.
3618 */
3619 if (overwriting)
3620 {
3621 retval = check_mtime(buf, &st_old);
3622 if (retval == FAIL)
3623 goto fail;
3624 }
3625 }
3626
3627#ifdef HAVE_ACL
3628 /*
3629 * For systems that support ACL: get the ACL from the original file.
3630 */
3631 if (!newfile)
3632 acl = mch_get_acl(fname);
3633#endif
3634
3635 /*
3636 * If 'backupskip' is not empty, don't make a backup for some files.
3637 */
3638 dobackup = (p_wb || p_bk || *p_pm != NUL);
3639#ifdef FEAT_WILDIGN
3640 if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname))
3641 dobackup = FALSE;
3642#endif
3643
3644 /*
3645 * Save the value of got_int and reset it. We don't want a previous
3646 * interruption cancel writing, only hitting CTRL-C while writing should
3647 * abort it.
3648 */
3649 prev_got_int = got_int;
3650 got_int = FALSE;
3651
3652 /* Mark the buffer as 'being saved' to prevent changed buffer warnings */
3653 buf->b_saving = TRUE;
3654
3655 /*
3656 * If we are not appending or filtering, the file exists, and the
3657 * 'writebackup', 'backup' or 'patchmode' option is set, need a backup.
3658 * When 'patchmode' is set also make a backup when appending.
3659 *
3660 * Do not make any backup, if 'writebackup' and 'backup' are both switched
3661 * off. This helps when editing large files on almost-full disks.
3662 */
3663 if (!(append && *p_pm == NUL) && !filtering && perm >= 0 && dobackup)
3664 {
3665#if defined(UNIX) || defined(WIN32)
3666 struct stat st;
3667#endif
3668
3669 if ((bkc_flags & BKC_YES) || append) /* "yes" */
3670 backup_copy = TRUE;
3671#if defined(UNIX) || defined(WIN32)
3672 else if ((bkc_flags & BKC_AUTO)) /* "auto" */
3673 {
3674 int i;
3675
3676# ifdef UNIX
3677 /*
3678 * Don't rename the file when:
3679 * - it's a hard link
3680 * - it's a symbolic link
3681 * - we don't have write permission in the directory
3682 * - we can't set the owner/group of the new file
3683 */
3684 if (st_old.st_nlink > 1
3685 || mch_lstat((char *)fname, &st) < 0
3686 || st.st_dev != st_old.st_dev
Bram Moolenaara5792f52005-11-23 21:25:05 +00003687 || st.st_ino != st_old.st_ino
3688# ifndef HAVE_FCHOWN
3689 || st.st_uid != st_old.st_uid
3690 || st.st_gid != st_old.st_gid
3691# endif
3692 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003693 backup_copy = TRUE;
3694 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003695# else
3696# ifdef WIN32
3697 /* On NTFS file systems hard links are possible. */
3698 if (mch_is_linked(fname))
3699 backup_copy = TRUE;
3700 else
3701# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003702# endif
3703 {
3704 /*
3705 * Check if we can create a file and set the owner/group to
3706 * the ones from the original file.
3707 * First find a file name that doesn't exist yet (use some
3708 * arbitrary numbers).
3709 */
3710 STRCPY(IObuff, fname);
3711 for (i = 4913; ; i += 123)
3712 {
3713 sprintf((char *)gettail(IObuff), "%d", i);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003714 if (mch_lstat((char *)IObuff, &st) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003715 break;
3716 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00003717 fd = mch_open((char *)IObuff,
3718 O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003719 if (fd < 0) /* can't write in directory */
3720 backup_copy = TRUE;
3721 else
3722 {
3723# ifdef UNIX
Bram Moolenaara5792f52005-11-23 21:25:05 +00003724# ifdef HAVE_FCHOWN
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00003725 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003726# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003727 if (mch_stat((char *)IObuff, &st) < 0
3728 || st.st_uid != st_old.st_uid
3729 || st.st_gid != st_old.st_gid
Bram Moolenaar78a15312009-05-15 19:33:18 +00003730 || (long)st.st_mode != perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003731 backup_copy = TRUE;
3732# endif
Bram Moolenaar98358622005-11-28 22:58:23 +00003733 /* Close the file before removing it, on MS-Windows we
3734 * can't delete an open file. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003735 close(fd);
Bram Moolenaar98358622005-11-28 22:58:23 +00003736 mch_remove(IObuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003737 }
3738 }
3739 }
3740
3741# ifdef UNIX
3742 /*
3743 * Break symlinks and/or hardlinks if we've been asked to.
3744 */
3745 if ((bkc_flags & BKC_BREAKSYMLINK) || (bkc_flags & BKC_BREAKHARDLINK))
3746 {
3747 int lstat_res;
3748
3749 lstat_res = mch_lstat((char *)fname, &st);
3750
3751 /* Symlinks. */
3752 if ((bkc_flags & BKC_BREAKSYMLINK)
3753 && lstat_res == 0
3754 && st.st_ino != st_old.st_ino)
3755 backup_copy = FALSE;
3756
3757 /* Hardlinks. */
3758 if ((bkc_flags & BKC_BREAKHARDLINK)
3759 && st_old.st_nlink > 1
3760 && (lstat_res != 0 || st.st_ino == st_old.st_ino))
3761 backup_copy = FALSE;
3762 }
3763#endif
3764
3765#endif
3766
3767 /* make sure we have a valid backup extension to use */
3768 if (*p_bex == NUL)
3769 {
3770#ifdef RISCOS
3771 backup_ext = (char_u *)"/bak";
3772#else
3773 backup_ext = (char_u *)".bak";
3774#endif
3775 }
3776 else
3777 backup_ext = p_bex;
3778
3779 if (backup_copy
3780 && (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) >= 0)
3781 {
3782 int bfd;
3783 char_u *copybuf, *wp;
3784 int some_error = FALSE;
3785 struct stat st_new;
3786 char_u *dirp;
3787 char_u *rootname;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003788#if defined(UNIX) && !defined(SHORT_FNAME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003789 int did_set_shortname;
3790#endif
3791
3792 copybuf = alloc(BUFSIZE + 1);
3793 if (copybuf == NULL)
3794 {
3795 some_error = TRUE; /* out of memory */
3796 goto nobackup;
3797 }
3798
3799 /*
3800 * Try to make the backup in each directory in the 'bdir' option.
3801 *
3802 * Unix semantics has it, that we may have a writable file,
3803 * that cannot be recreated with a simple open(..., O_CREAT, ) e.g:
3804 * - the directory is not writable,
3805 * - the file may be a symbolic link,
3806 * - the file may belong to another user/group, etc.
3807 *
3808 * For these reasons, the existing writable file must be truncated
3809 * and reused. Creation of a backup COPY will be attempted.
3810 */
3811 dirp = p_bdir;
3812 while (*dirp)
3813 {
3814#ifdef UNIX
3815 st_new.st_ino = 0;
3816 st_new.st_dev = 0;
3817 st_new.st_gid = 0;
3818#endif
3819
3820 /*
3821 * Isolate one directory name, using an entry in 'bdir'.
3822 */
3823 (void)copy_option_part(&dirp, copybuf, BUFSIZE, ",");
3824 rootname = get_file_in_dir(fname, copybuf);
3825 if (rootname == NULL)
3826 {
3827 some_error = TRUE; /* out of memory */
3828 goto nobackup;
3829 }
3830
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003831#if defined(UNIX) && !defined(SHORT_FNAME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003832 did_set_shortname = FALSE;
3833#endif
3834
3835 /*
3836 * May try twice if 'shortname' not set.
3837 */
3838 for (;;)
3839 {
3840 /*
3841 * Make backup file name.
3842 */
3843 backup = buf_modname(
3844#ifdef SHORT_FNAME
3845 TRUE,
3846#else
3847 (buf->b_p_sn || buf->b_shortname),
3848#endif
3849 rootname, backup_ext, FALSE);
3850 if (backup == NULL)
3851 {
3852 vim_free(rootname);
3853 some_error = TRUE; /* out of memory */
3854 goto nobackup;
3855 }
3856
3857 /*
3858 * Check if backup file already exists.
3859 */
3860 if (mch_stat((char *)backup, &st_new) >= 0)
3861 {
3862#ifdef UNIX
3863 /*
3864 * Check if backup file is same as original file.
3865 * May happen when modname() gave the same file back.
3866 * E.g. silly link, or file name-length reached.
3867 * If we don't check here, we either ruin the file
3868 * when copying or erase it after writing. jw.
3869 */
3870 if (st_new.st_dev == st_old.st_dev
3871 && st_new.st_ino == st_old.st_ino)
3872 {
3873 vim_free(backup);
3874 backup = NULL; /* no backup file to delete */
3875# ifndef SHORT_FNAME
3876 /*
3877 * may try again with 'shortname' set
3878 */
3879 if (!(buf->b_shortname || buf->b_p_sn))
3880 {
3881 buf->b_shortname = TRUE;
3882 did_set_shortname = TRUE;
3883 continue;
3884 }
3885 /* setting shortname didn't help */
3886 if (did_set_shortname)
3887 buf->b_shortname = FALSE;
3888# endif
3889 break;
3890 }
3891#endif
3892
3893 /*
3894 * If we are not going to keep the backup file, don't
3895 * delete an existing one, try to use another name.
3896 * Change one character, just before the extension.
3897 */
3898 if (!p_bk)
3899 {
3900 wp = backup + STRLEN(backup) - 1
3901 - STRLEN(backup_ext);
3902 if (wp < backup) /* empty file name ??? */
3903 wp = backup;
3904 *wp = 'z';
3905 while (*wp > 'a'
3906 && mch_stat((char *)backup, &st_new) >= 0)
3907 --*wp;
3908 /* They all exist??? Must be something wrong. */
3909 if (*wp == 'a')
3910 {
3911 vim_free(backup);
3912 backup = NULL;
3913 }
3914 }
3915 }
3916 break;
3917 }
3918 vim_free(rootname);
3919
3920 /*
3921 * Try to create the backup file
3922 */
3923 if (backup != NULL)
3924 {
3925 /* remove old backup, if present */
3926 mch_remove(backup);
3927 /* Open with O_EXCL to avoid the file being created while
3928 * we were sleeping (symlink hacker attack?) */
3929 bfd = mch_open((char *)backup,
Bram Moolenaara5792f52005-11-23 21:25:05 +00003930 O_WRONLY|O_CREAT|O_EXTRA|O_EXCL|O_NOFOLLOW,
3931 perm & 0777);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003932 if (bfd < 0)
3933 {
3934 vim_free(backup);
3935 backup = NULL;
3936 }
3937 else
3938 {
3939 /* set file protection same as original file, but
3940 * strip s-bit */
3941 (void)mch_setperm(backup, perm & 0777);
3942
3943#ifdef UNIX
3944 /*
3945 * Try to set the group of the backup same as the
3946 * original file. If this fails, set the protection
3947 * bits for the group same as the protection bits for
3948 * others.
3949 */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003950 if (st_new.st_gid != st_old.st_gid
Bram Moolenaar071d4272004-06-13 20:20:40 +00003951# ifdef HAVE_FCHOWN /* sequent-ptx lacks fchown() */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003952 && fchown(bfd, (uid_t)-1, st_old.st_gid) != 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00003953# endif
3954 )
3955 mch_setperm(backup,
3956 (perm & 0707) | ((perm & 07) << 3));
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00003957# ifdef HAVE_SELINUX
3958 mch_copy_sec(fname, backup);
3959# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003960#endif
3961
3962 /*
3963 * copy the file.
3964 */
3965 write_info.bw_fd = bfd;
3966 write_info.bw_buf = copybuf;
3967#ifdef HAS_BW_FLAGS
3968 write_info.bw_flags = FIO_NOCONVERT;
3969#endif
3970 while ((write_info.bw_len = vim_read(fd, copybuf,
3971 BUFSIZE)) > 0)
3972 {
3973 if (buf_write_bytes(&write_info) == FAIL)
3974 {
3975 errmsg = (char_u *)_("E506: Can't write to backup file (add ! to override)");
3976 break;
3977 }
3978 ui_breakcheck();
3979 if (got_int)
3980 {
3981 errmsg = (char_u *)_(e_interr);
3982 break;
3983 }
3984 }
3985
3986 if (close(bfd) < 0 && errmsg == NULL)
3987 errmsg = (char_u *)_("E507: Close error for backup file (add ! to override)");
3988 if (write_info.bw_len < 0)
3989 errmsg = (char_u *)_("E508: Can't read file for backup (add ! to override)");
3990#ifdef UNIX
3991 set_file_time(backup, st_old.st_atime, st_old.st_mtime);
3992#endif
3993#ifdef HAVE_ACL
3994 mch_set_acl(backup, acl);
3995#endif
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00003996#ifdef HAVE_SELINUX
3997 mch_copy_sec(fname, backup);
3998#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003999 break;
4000 }
4001 }
4002 }
4003 nobackup:
4004 close(fd); /* ignore errors for closing read file */
4005 vim_free(copybuf);
4006
4007 if (backup == NULL && errmsg == NULL)
4008 errmsg = (char_u *)_("E509: Cannot create backup file (add ! to override)");
4009 /* ignore errors when forceit is TRUE */
4010 if ((some_error || errmsg != NULL) && !forceit)
4011 {
4012 retval = FAIL;
4013 goto fail;
4014 }
4015 errmsg = NULL;
4016 }
4017 else
4018 {
4019 char_u *dirp;
4020 char_u *p;
4021 char_u *rootname;
4022
4023 /*
4024 * Make a backup by renaming the original file.
4025 */
4026 /*
4027 * If 'cpoptions' includes the "W" flag, we don't want to
4028 * overwrite a read-only file. But rename may be possible
4029 * anyway, thus we need an extra check here.
4030 */
4031 if (file_readonly && vim_strchr(p_cpo, CPO_FWRITE) != NULL)
4032 {
4033 errnum = (char_u *)"E504: ";
4034 errmsg = (char_u *)_(err_readonly);
4035 goto fail;
4036 }
4037
4038 /*
4039 *
4040 * Form the backup file name - change path/fo.o.h to
4041 * path/fo.o.h.bak Try all directories in 'backupdir', first one
4042 * that works is used.
4043 */
4044 dirp = p_bdir;
4045 while (*dirp)
4046 {
4047 /*
4048 * Isolate one directory name and make the backup file name.
4049 */
4050 (void)copy_option_part(&dirp, IObuff, IOSIZE, ",");
4051 rootname = get_file_in_dir(fname, IObuff);
4052 if (rootname == NULL)
4053 backup = NULL;
4054 else
4055 {
4056 backup = buf_modname(
4057#ifdef SHORT_FNAME
4058 TRUE,
4059#else
4060 (buf->b_p_sn || buf->b_shortname),
4061#endif
4062 rootname, backup_ext, FALSE);
4063 vim_free(rootname);
4064 }
4065
4066 if (backup != NULL)
4067 {
4068 /*
4069 * If we are not going to keep the backup file, don't
4070 * delete an existing one, try to use another name.
4071 * Change one character, just before the extension.
4072 */
4073 if (!p_bk && mch_getperm(backup) >= 0)
4074 {
4075 p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext);
4076 if (p < backup) /* empty file name ??? */
4077 p = backup;
4078 *p = 'z';
4079 while (*p > 'a' && mch_getperm(backup) >= 0)
4080 --*p;
4081 /* They all exist??? Must be something wrong! */
4082 if (*p == 'a')
4083 {
4084 vim_free(backup);
4085 backup = NULL;
4086 }
4087 }
4088 }
4089 if (backup != NULL)
4090 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004091 /*
Bram Moolenaarbfd8fc02005-09-20 23:22:24 +00004092 * Delete any existing backup and move the current version
4093 * to the backup. For safety, we don't remove the backup
4094 * until the write has finished successfully. And if the
4095 * 'backup' option is set, leave it around.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004096 */
4097 /*
4098 * If the renaming of the original file to the backup file
4099 * works, quit here.
4100 */
4101 if (vim_rename(fname, backup) == 0)
4102 break;
4103
4104 vim_free(backup); /* don't do the rename below */
4105 backup = NULL;
4106 }
4107 }
4108 if (backup == NULL && !forceit)
4109 {
4110 errmsg = (char_u *)_("E510: Can't make backup file (add ! to override)");
4111 goto fail;
4112 }
4113 }
4114 }
4115
4116#if defined(UNIX) && !defined(ARCHIE)
4117 /* When using ":w!" and the file was read-only: make it writable */
4118 if (forceit && perm >= 0 && !(perm & 0200) && st_old.st_uid == getuid()
4119 && vim_strchr(p_cpo, CPO_FWRITE) == NULL)
4120 {
4121 perm |= 0200;
4122 (void)mch_setperm(fname, perm);
4123 made_writable = TRUE;
4124 }
4125#endif
4126
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004127 /* When using ":w!" and writing to the current file, 'readonly' makes no
Bram Moolenaar4399ef42005-02-12 14:29:27 +00004128 * sense, reset it, unless 'Z' appears in 'cpoptions'. */
4129 if (forceit && overwriting && vim_strchr(p_cpo, CPO_KEEPRO) == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004130 {
4131 buf->b_p_ro = FALSE;
4132#ifdef FEAT_TITLE
4133 need_maketitle = TRUE; /* set window title later */
4134#endif
4135#ifdef FEAT_WINDOWS
4136 status_redraw_all(); /* redraw status lines later */
4137#endif
4138 }
4139
4140 if (end > buf->b_ml.ml_line_count)
4141 end = buf->b_ml.ml_line_count;
4142 if (buf->b_ml.ml_flags & ML_EMPTY)
4143 start = end + 1;
4144
4145 /*
4146 * If the original file is being overwritten, there is a small chance that
4147 * we crash in the middle of writing. Therefore the file is preserved now.
4148 * This makes all block numbers positive so that recovery does not need
4149 * the original file.
4150 * Don't do this if there is a backup file and we are exiting.
4151 */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004152 if (reset_changed && !newfile && overwriting
Bram Moolenaar071d4272004-06-13 20:20:40 +00004153 && !(exiting && backup != NULL))
4154 {
4155 ml_preserve(buf, FALSE);
4156 if (got_int)
4157 {
4158 errmsg = (char_u *)_(e_interr);
4159 goto restore_backup;
4160 }
4161 }
4162
4163#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
4164 /*
4165 * Before risking to lose the original file verify if there's
4166 * a resource fork to preserve, and if cannot be done warn
4167 * the users. This happens when overwriting without backups.
4168 */
4169 if (backup == NULL && overwriting && !append)
4170 if (mch_has_resource_fork(fname))
4171 {
4172 errmsg = (char_u *)_("E460: The resource fork would be lost (add ! to override)");
4173 goto restore_backup;
4174 }
4175#endif
4176
4177#ifdef VMS
4178 vms_remove_version(fname); /* remove version */
4179#endif
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00004180 /* Default: write the file directly. May write to a temp file for
Bram Moolenaar071d4272004-06-13 20:20:40 +00004181 * multi-byte conversion. */
4182 wfname = fname;
4183
4184#ifdef FEAT_MBYTE
4185 /* Check for forced 'fileencoding' from "++opt=val" argument. */
4186 if (eap != NULL && eap->force_enc != 0)
4187 {
4188 fenc = eap->cmd + eap->force_enc;
4189 fenc = enc_canonize(fenc);
4190 fenc_tofree = fenc;
4191 }
4192 else
4193 fenc = buf->b_p_fenc;
4194
4195 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004196 * Check if the file needs to be converted.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004197 */
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004198 converted = need_conversion(fenc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004199
4200 /*
4201 * Check if UTF-8 to UCS-2/4 or Latin1 conversion needs to be done. Or
4202 * Latin1 to Unicode conversion. This is handled in buf_write_bytes().
4203 * Prepare the flags for it and allocate bw_conv_buf when needed.
4204 */
4205 if (converted && (enc_utf8 || STRCMP(p_enc, "latin1") == 0))
4206 {
4207 wb_flags = get_fio_flags(fenc);
4208 if (wb_flags & (FIO_UCS2 | FIO_UCS4 | FIO_UTF16 | FIO_UTF8))
4209 {
4210 /* Need to allocate a buffer to translate into. */
4211 if (wb_flags & (FIO_UCS2 | FIO_UTF16 | FIO_UTF8))
4212 write_info.bw_conv_buflen = bufsize * 2;
4213 else /* FIO_UCS4 */
4214 write_info.bw_conv_buflen = bufsize * 4;
4215 write_info.bw_conv_buf
4216 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4217 if (write_info.bw_conv_buf == NULL)
4218 end = 0;
4219 }
4220 }
4221
4222# ifdef WIN3264
4223 if (converted && wb_flags == 0 && (wb_flags = get_win_fio_flags(fenc)) != 0)
4224 {
4225 /* Convert UTF-8 -> UCS-2 and UCS-2 -> DBCS. Worst-case * 4: */
4226 write_info.bw_conv_buflen = bufsize * 4;
4227 write_info.bw_conv_buf
4228 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4229 if (write_info.bw_conv_buf == NULL)
4230 end = 0;
4231 }
4232# endif
4233
4234# ifdef MACOS_X
4235 if (converted && wb_flags == 0 && (wb_flags = get_mac_fio_flags(fenc)) != 0)
4236 {
4237 write_info.bw_conv_buflen = bufsize * 3;
4238 write_info.bw_conv_buf
4239 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4240 if (write_info.bw_conv_buf == NULL)
4241 end = 0;
4242 }
4243# endif
4244
4245# if defined(FEAT_EVAL) || defined(USE_ICONV)
4246 if (converted && wb_flags == 0)
4247 {
4248# ifdef USE_ICONV
4249 /*
4250 * Use iconv() conversion when conversion is needed and it's not done
4251 * internally.
4252 */
4253 write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc,
4254 enc_utf8 ? (char_u *)"utf-8" : p_enc);
4255 if (write_info.bw_iconv_fd != (iconv_t)-1)
4256 {
4257 /* We're going to use iconv(), allocate a buffer to convert in. */
4258 write_info.bw_conv_buflen = bufsize * ICONV_MULT;
4259 write_info.bw_conv_buf
4260 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4261 if (write_info.bw_conv_buf == NULL)
4262 end = 0;
4263 write_info.bw_first = TRUE;
4264 }
4265# ifdef FEAT_EVAL
4266 else
4267# endif
4268# endif
4269
4270# ifdef FEAT_EVAL
4271 /*
4272 * When the file needs to be converted with 'charconvert' after
4273 * writing, write to a temp file instead and let the conversion
4274 * overwrite the original file.
4275 */
4276 if (*p_ccv != NUL)
4277 {
4278 wfname = vim_tempname('w');
4279 if (wfname == NULL) /* Can't write without a tempfile! */
4280 {
4281 errmsg = (char_u *)_("E214: Can't find temp file for writing");
4282 goto restore_backup;
4283 }
4284 }
4285# endif
4286 }
4287# endif
4288 if (converted && wb_flags == 0
4289# ifdef USE_ICONV
4290 && write_info.bw_iconv_fd == (iconv_t)-1
4291# endif
4292# ifdef FEAT_EVAL
4293 && wfname == fname
4294# endif
4295 )
4296 {
4297 if (!forceit)
4298 {
4299 errmsg = (char_u *)_("E213: Cannot convert (add ! to write without conversion)");
4300 goto restore_backup;
4301 }
4302 notconverted = TRUE;
4303 }
4304#endif
4305
4306 /*
4307 * Open the file "wfname" for writing.
4308 * We may try to open the file twice: If we can't write to the
4309 * file and forceit is TRUE we delete the existing file and try to create
4310 * a new one. If this still fails we may have lost the original file!
4311 * (this may happen when the user reached his quotum for number of files).
4312 * Appending will fail if the file does not exist and forceit is FALSE.
4313 */
4314 while ((fd = mch_open((char *)wfname, O_WRONLY | O_EXTRA | (append
4315 ? (forceit ? (O_APPEND | O_CREAT) : O_APPEND)
4316 : (O_CREAT | O_TRUNC))
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00004317 , perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004318 {
4319 /*
4320 * A forced write will try to create a new file if the old one is
4321 * still readonly. This may also happen when the directory is
4322 * read-only. In that case the mch_remove() will fail.
4323 */
4324 if (errmsg == NULL)
4325 {
4326#ifdef UNIX
4327 struct stat st;
4328
4329 /* Don't delete the file when it's a hard or symbolic link. */
4330 if ((!newfile && st_old.st_nlink > 1)
4331 || (mch_lstat((char *)fname, &st) == 0
4332 && (st.st_dev != st_old.st_dev
4333 || st.st_ino != st_old.st_ino)))
4334 errmsg = (char_u *)_("E166: Can't open linked file for writing");
4335 else
4336#endif
4337 {
4338 errmsg = (char_u *)_("E212: Can't open file for writing");
4339 if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL
4340 && perm >= 0)
4341 {
4342#ifdef UNIX
4343 /* we write to the file, thus it should be marked
4344 writable after all */
4345 if (!(perm & 0200))
4346 made_writable = TRUE;
4347 perm |= 0200;
4348 if (st_old.st_uid != getuid() || st_old.st_gid != getgid())
4349 perm &= 0777;
4350#endif
4351 if (!append) /* don't remove when appending */
4352 mch_remove(wfname);
4353 continue;
4354 }
4355 }
4356 }
4357
4358restore_backup:
4359 {
4360 struct stat st;
4361
4362 /*
4363 * If we failed to open the file, we don't need a backup. Throw it
4364 * away. If we moved or removed the original file try to put the
4365 * backup in its place.
4366 */
4367 if (backup != NULL && wfname == fname)
4368 {
4369 if (backup_copy)
4370 {
4371 /*
4372 * There is a small chance that we removed the original,
4373 * try to move the copy in its place.
4374 * This may not work if the vim_rename() fails.
4375 * In that case we leave the copy around.
4376 */
4377 /* If file does not exist, put the copy in its place */
4378 if (mch_stat((char *)fname, &st) < 0)
4379 vim_rename(backup, fname);
4380 /* if original file does exist throw away the copy */
4381 if (mch_stat((char *)fname, &st) >= 0)
4382 mch_remove(backup);
4383 }
4384 else
4385 {
4386 /* try to put the original file back */
4387 vim_rename(backup, fname);
4388 }
4389 }
4390
4391 /* if original file no longer exists give an extra warning */
4392 if (!newfile && mch_stat((char *)fname, &st) < 0)
4393 end = 0;
4394 }
4395
4396#ifdef FEAT_MBYTE
4397 if (wfname != fname)
4398 vim_free(wfname);
4399#endif
4400 goto fail;
4401 }
4402 errmsg = NULL;
4403
4404#if defined(MACOS_CLASSIC) || defined(WIN3264)
4405 /* TODO: Is it need for MACOS_X? (Dany) */
4406 /*
4407 * On macintosh copy the original files attributes (i.e. the backup)
Bram Moolenaar7263a772007-05-10 17:35:54 +00004408 * This is done in order to preserve the resource fork and the
4409 * Finder attribute (label, comments, custom icons, file creator)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004410 */
4411 if (backup != NULL && overwriting && !append)
4412 {
4413 if (backup_copy)
4414 (void)mch_copy_file_attribute(wfname, backup);
4415 else
4416 (void)mch_copy_file_attribute(backup, wfname);
4417 }
4418
4419 if (!overwriting && !append)
4420 {
4421 if (buf->b_ffname != NULL)
4422 (void)mch_copy_file_attribute(buf->b_ffname, wfname);
Bram Moolenaar7263a772007-05-10 17:35:54 +00004423 /* Should copy resource fork */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004424 }
4425#endif
4426
4427 write_info.bw_fd = fd;
4428
4429#ifdef FEAT_CRYPT
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004430 if (*buf->b_p_key != NUL && !filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004431 {
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02004432 char_u *header;
4433 int header_len;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004434
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02004435 header = prepare_crypt_write(buf, &header_len);
4436 if (header == NULL)
4437 end = 0;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004438 else
4439 {
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02004440 /* Write magic number, so that Vim knows that this file is
4441 * encrypted when reading it again. This also undergoes utf-8 to
4442 * ucs-2/4 conversion when needed. */
4443 write_info.bw_buf = header;
4444 write_info.bw_len = header_len;
4445 write_info.bw_flags = FIO_NOCONVERT;
4446 if (buf_write_bytes(&write_info) == FAIL)
4447 end = 0;
4448 wb_flags |= FIO_ENCRYPTED;
4449 vim_free(header);
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004450 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004451 }
4452#endif
4453
4454 write_info.bw_buf = buffer;
4455 nchars = 0;
4456
4457 /* use "++bin", "++nobin" or 'binary' */
4458 if (eap != NULL && eap->force_bin != 0)
4459 write_bin = (eap->force_bin == FORCE_BIN);
4460 else
4461 write_bin = buf->b_p_bin;
4462
4463#ifdef FEAT_MBYTE
4464 /*
4465 * The BOM is written just after the encryption magic number.
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004466 * Skip it when appending and the file already existed, the BOM only makes
4467 * sense at the start of the file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004468 */
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004469 if (buf->b_p_bomb && !write_bin && (!append || perm < 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004470 {
4471 write_info.bw_len = make_bom(buffer, fenc);
4472 if (write_info.bw_len > 0)
4473 {
4474 /* don't convert, do encryption */
4475 write_info.bw_flags = FIO_NOCONVERT | wb_flags;
4476 if (buf_write_bytes(&write_info) == FAIL)
4477 end = 0;
4478 else
4479 nchars += write_info.bw_len;
4480 }
4481 }
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004482 write_info.bw_start_lnum = start;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004483#endif
4484
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004485#ifdef FEAT_PERSISTENT_UNDO
4486 write_undo_file = (buf->b_p_udf && overwriting && !append
4487 && !filtering && reset_changed);
4488 if (write_undo_file)
4489 /* Prepare for computing the hash value of the text. */
4490 sha256_start(&sha_ctx);
4491#endif
4492
Bram Moolenaar071d4272004-06-13 20:20:40 +00004493 write_info.bw_len = bufsize;
4494#ifdef HAS_BW_FLAGS
4495 write_info.bw_flags = wb_flags;
4496#endif
4497 fileformat = get_fileformat_force(buf, eap);
4498 s = buffer;
4499 len = 0;
4500 for (lnum = start; lnum <= end; ++lnum)
4501 {
4502 /*
4503 * The next while loop is done once for each character written.
4504 * Keep it fast!
4505 */
4506 ptr = ml_get_buf(buf, lnum, FALSE) - 1;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004507#ifdef FEAT_PERSISTENT_UNDO
4508 if (write_undo_file)
Bram Moolenaar442b4222010-05-24 21:34:22 +02004509 sha256_update(&sha_ctx, ptr + 1, (UINT32_T)(STRLEN(ptr + 1) + 1));
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004510#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004511 while ((c = *++ptr) != NUL)
4512 {
4513 if (c == NL)
4514 *s = NUL; /* replace newlines with NULs */
4515 else if (c == CAR && fileformat == EOL_MAC)
4516 *s = NL; /* Mac: replace CRs with NLs */
4517 else
4518 *s = c;
4519 ++s;
4520 if (++len != bufsize)
4521 continue;
4522 if (buf_write_bytes(&write_info) == FAIL)
4523 {
4524 end = 0; /* write error: break loop */
4525 break;
4526 }
4527 nchars += bufsize;
4528 s = buffer;
4529 len = 0;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004530#ifdef FEAT_MBYTE
4531 write_info.bw_start_lnum = lnum;
4532#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004533 }
4534 /* write failed or last line has no EOL: stop here */
4535 if (end == 0
4536 || (lnum == end
4537 && write_bin
4538 && (lnum == write_no_eol_lnum
4539 || (lnum == buf->b_ml.ml_line_count && !buf->b_p_eol))))
4540 {
4541 ++lnum; /* written the line, count it */
4542 no_eol = TRUE;
4543 break;
4544 }
4545 if (fileformat == EOL_UNIX)
4546 *s++ = NL;
4547 else
4548 {
4549 *s++ = CAR; /* EOL_MAC or EOL_DOS: write CR */
4550 if (fileformat == EOL_DOS) /* write CR-NL */
4551 {
4552 if (++len == bufsize)
4553 {
4554 if (buf_write_bytes(&write_info) == FAIL)
4555 {
4556 end = 0; /* write error: break loop */
4557 break;
4558 }
4559 nchars += bufsize;
4560 s = buffer;
4561 len = 0;
4562 }
4563 *s++ = NL;
4564 }
4565 }
4566 if (++len == bufsize && end)
4567 {
4568 if (buf_write_bytes(&write_info) == FAIL)
4569 {
4570 end = 0; /* write error: break loop */
4571 break;
4572 }
4573 nchars += bufsize;
4574 s = buffer;
4575 len = 0;
4576
4577 ui_breakcheck();
4578 if (got_int)
4579 {
4580 end = 0; /* Interrupted, break loop */
4581 break;
4582 }
4583 }
4584#ifdef VMS
4585 /*
4586 * On VMS there is a problem: newlines get added when writing blocks
4587 * at a time. Fix it by writing a line at a time.
4588 * This is much slower!
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004589 * Explanation: VAX/DECC RTL insists that records in some RMS
4590 * structures end with a newline (carriage return) character, and if
4591 * they don't it adds one.
4592 * With other RMS structures it works perfect without this fix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004593 */
Bram Moolenaarb52e2602007-10-29 21:38:54 +00004594 if (buf->b_fab_rfm == FAB$C_VFC
4595 || ((buf->b_fab_rat & (FAB$M_FTN | FAB$M_CR)) != 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004596 {
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004597 int b2write;
4598
4599 buf->b_fab_mrs = (buf->b_fab_mrs == 0
4600 ? MIN(4096, bufsize)
4601 : MIN(buf->b_fab_mrs, bufsize));
4602
4603 b2write = len;
4604 while (b2write > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004605 {
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004606 write_info.bw_len = MIN(b2write, buf->b_fab_mrs);
4607 if (buf_write_bytes(&write_info) == FAIL)
4608 {
4609 end = 0;
4610 break;
4611 }
4612 b2write -= MIN(b2write, buf->b_fab_mrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004613 }
4614 write_info.bw_len = bufsize;
4615 nchars += len;
4616 s = buffer;
4617 len = 0;
4618 }
4619#endif
4620 }
4621 if (len > 0 && end > 0)
4622 {
4623 write_info.bw_len = len;
4624 if (buf_write_bytes(&write_info) == FAIL)
4625 end = 0; /* write error */
4626 nchars += len;
4627 }
4628
4629#if defined(UNIX) && defined(HAVE_FSYNC)
4630 /* On many journalling file systems there is a bug that causes both the
4631 * original and the backup file to be lost when halting the system right
4632 * after writing the file. That's because only the meta-data is
4633 * journalled. Syncing the file slows down the system, but assures it has
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004634 * been written to disk and we don't lose it.
4635 * For a device do try the fsync() but don't complain if it does not work
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00004636 * (could be a pipe).
4637 * If the 'fsync' option is FALSE, don't fsync(). Useful for laptops. */
4638 if (p_fs && fsync(fd) != 0 && !device)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004639 {
4640 errmsg = (char_u *)_("E667: Fsync failed");
4641 end = 0;
4642 }
4643#endif
4644
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004645#ifdef HAVE_SELINUX
4646 /* Probably need to set the security context. */
4647 if (!backup_copy)
4648 mch_copy_sec(backup, wfname);
4649#endif
4650
Bram Moolenaara5792f52005-11-23 21:25:05 +00004651#ifdef UNIX
4652 /* When creating a new file, set its owner/group to that of the original
4653 * file. Get the new device and inode number. */
4654 if (backup != NULL && !backup_copy)
4655 {
4656# ifdef HAVE_FCHOWN
4657 struct stat st;
4658
4659 /* don't change the owner when it's already OK, some systems remove
4660 * permission or ACL stuff */
4661 if (mch_stat((char *)wfname, &st) < 0
4662 || st.st_uid != st_old.st_uid
4663 || st.st_gid != st_old.st_gid)
4664 {
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004665 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004666 if (perm >= 0) /* set permission again, may have changed */
4667 (void)mch_setperm(wfname, perm);
4668 }
4669# endif
4670 buf_setino(buf);
4671 }
Bram Moolenaarf1726cc2009-05-13 18:48:16 +00004672 else if (!buf->b_dev_valid)
Bram Moolenaar8fa04452005-12-23 22:13:51 +00004673 /* Set the inode when creating a new file. */
4674 buf_setino(buf);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004675#endif
4676
Bram Moolenaar071d4272004-06-13 20:20:40 +00004677 if (close(fd) != 0)
4678 {
4679 errmsg = (char_u *)_("E512: Close failed");
4680 end = 0;
4681 }
4682
4683#ifdef UNIX
4684 if (made_writable)
4685 perm &= ~0200; /* reset 'w' bit for security reasons */
4686#endif
4687 if (perm >= 0) /* set perm. of new file same as old file */
4688 (void)mch_setperm(wfname, perm);
4689#ifdef RISCOS
4690 if (!append && !filtering)
4691 /* Set the filetype after writing the file. */
4692 mch_set_filetype(wfname, buf->b_p_oft);
4693#endif
4694#ifdef HAVE_ACL
4695 /* Probably need to set the ACL before changing the user (can't set the
4696 * ACL on a file the user doesn't own). */
4697 if (!backup_copy)
4698 mch_set_acl(wfname, acl);
4699#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004700#ifdef FEAT_CRYPT
4701 if (wb_flags & FIO_ENCRYPTED)
4702 crypt_pop_state();
4703#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004704
Bram Moolenaar071d4272004-06-13 20:20:40 +00004705
4706#if defined(FEAT_MBYTE) && defined(FEAT_EVAL)
4707 if (wfname != fname)
4708 {
4709 /*
4710 * The file was written to a temp file, now it needs to be converted
4711 * with 'charconvert' to (overwrite) the output file.
4712 */
4713 if (end != 0)
4714 {
4715 if (eval_charconvert(enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc,
4716 wfname, fname) == FAIL)
4717 {
4718 write_info.bw_conv_error = TRUE;
4719 end = 0;
4720 }
4721 }
4722 mch_remove(wfname);
4723 vim_free(wfname);
4724 }
4725#endif
4726
4727 if (end == 0)
4728 {
4729 if (errmsg == NULL)
4730 {
4731#ifdef FEAT_MBYTE
4732 if (write_info.bw_conv_error)
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004733 {
4734 if (write_info.bw_conv_error_lnum == 0)
4735 errmsg = (char_u *)_("E513: write error, conversion failed (make 'fenc' empty to override)");
4736 else
4737 {
4738 errmsg_allocated = TRUE;
4739 errmsg = alloc(300);
4740 vim_snprintf((char *)errmsg, 300, _("E513: write error, conversion failed in line %ld (make 'fenc' empty to override)"),
4741 (long)write_info.bw_conv_error_lnum);
4742 }
4743 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004744 else
4745#endif
4746 if (got_int)
4747 errmsg = (char_u *)_(e_interr);
4748 else
4749 errmsg = (char_u *)_("E514: write error (file system full?)");
4750 }
4751
4752 /*
4753 * If we have a backup file, try to put it in place of the new file,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004754 * because the new file is probably corrupt. This avoids losing the
Bram Moolenaar071d4272004-06-13 20:20:40 +00004755 * original file when trying to make a backup when writing the file a
4756 * second time.
4757 * When "backup_copy" is set we need to copy the backup over the new
4758 * file. Otherwise rename the backup file.
4759 * If this is OK, don't give the extra warning message.
4760 */
4761 if (backup != NULL)
4762 {
4763 if (backup_copy)
4764 {
4765 /* This may take a while, if we were interrupted let the user
4766 * know we got the message. */
4767 if (got_int)
4768 {
4769 MSG(_(e_interr));
4770 out_flush();
4771 }
4772 if ((fd = mch_open((char *)backup, O_RDONLY | O_EXTRA, 0)) >= 0)
4773 {
4774 if ((write_info.bw_fd = mch_open((char *)fname,
Bram Moolenaar9be038d2005-03-08 22:34:32 +00004775 O_WRONLY | O_CREAT | O_TRUNC | O_EXTRA,
4776 perm & 0777)) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004777 {
4778 /* copy the file. */
4779 write_info.bw_buf = smallbuf;
4780#ifdef HAS_BW_FLAGS
4781 write_info.bw_flags = FIO_NOCONVERT;
4782#endif
4783 while ((write_info.bw_len = vim_read(fd, smallbuf,
4784 SMBUFSIZE)) > 0)
4785 if (buf_write_bytes(&write_info) == FAIL)
4786 break;
4787
4788 if (close(write_info.bw_fd) >= 0
4789 && write_info.bw_len == 0)
4790 end = 1; /* success */
4791 }
4792 close(fd); /* ignore errors for closing read file */
4793 }
4794 }
4795 else
4796 {
4797 if (vim_rename(backup, fname) == 0)
4798 end = 1;
4799 }
4800 }
4801 goto fail;
4802 }
4803
4804 lnum -= start; /* compute number of written lines */
4805 --no_wait_return; /* may wait for return now */
4806
4807#if !(defined(UNIX) || defined(VMS))
4808 fname = sfname; /* use shortname now, for the messages */
4809#endif
4810 if (!filtering)
4811 {
4812 msg_add_fname(buf, fname); /* put fname in IObuff with quotes */
4813 c = FALSE;
4814#ifdef FEAT_MBYTE
4815 if (write_info.bw_conv_error)
4816 {
4817 STRCAT(IObuff, _(" CONVERSION ERROR"));
4818 c = TRUE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004819 if (write_info.bw_conv_error_lnum != 0)
Bram Moolenaara800b422010-06-27 01:15:55 +02004820 vim_snprintf_add((char *)IObuff, IOSIZE, _(" in line %ld;"),
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004821 (long)write_info.bw_conv_error_lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004822 }
4823 else if (notconverted)
4824 {
4825 STRCAT(IObuff, _("[NOT converted]"));
4826 c = TRUE;
4827 }
4828 else if (converted)
4829 {
4830 STRCAT(IObuff, _("[converted]"));
4831 c = TRUE;
4832 }
4833#endif
4834 if (device)
4835 {
4836 STRCAT(IObuff, _("[Device]"));
4837 c = TRUE;
4838 }
4839 else if (newfile)
4840 {
4841 STRCAT(IObuff, shortmess(SHM_NEW) ? _("[New]") : _("[New File]"));
4842 c = TRUE;
4843 }
4844 if (no_eol)
4845 {
4846 msg_add_eol();
4847 c = TRUE;
4848 }
4849 /* may add [unix/dos/mac] */
4850 if (msg_add_fileformat(fileformat))
4851 c = TRUE;
4852#ifdef FEAT_CRYPT
4853 if (wb_flags & FIO_ENCRYPTED)
4854 {
4855 STRCAT(IObuff, _("[crypted]"));
4856 c = TRUE;
4857 }
4858#endif
4859 msg_add_lines(c, (long)lnum, nchars); /* add line/char count */
4860 if (!shortmess(SHM_WRITE))
4861 {
4862 if (append)
4863 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended"));
4864 else
4865 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written"));
4866 }
4867
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00004868 set_keep_msg(msg_trunc_attr(IObuff, FALSE, 0), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004869 }
4870
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004871 /* When written everything correctly: reset 'modified'. Unless not
4872 * writing to the original file and '+' is not in 'cpoptions'. */
Bram Moolenaar292ad192005-12-11 21:29:51 +00004873 if (reset_changed && whole && !append
Bram Moolenaar071d4272004-06-13 20:20:40 +00004874#ifdef FEAT_MBYTE
4875 && !write_info.bw_conv_error
4876#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004877 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL)
4878 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004879 {
4880 unchanged(buf, TRUE);
4881 u_unchanged(buf);
4882 }
4883
4884 /*
4885 * If written to the current file, update the timestamp of the swap file
4886 * and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
4887 */
4888 if (overwriting)
4889 {
4890 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00004891 if (append)
4892 buf->b_flags &= ~BF_NEW;
4893 else
4894 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004895 }
4896
4897 /*
4898 * If we kept a backup until now, and we are in patch mode, then we make
4899 * the backup file our 'original' file.
4900 */
4901 if (*p_pm && dobackup)
4902 {
4903 char *org = (char *)buf_modname(
4904#ifdef SHORT_FNAME
4905 TRUE,
4906#else
4907 (buf->b_p_sn || buf->b_shortname),
4908#endif
4909 fname, p_pm, FALSE);
4910
4911 if (backup != NULL)
4912 {
4913 struct stat st;
4914
4915 /*
4916 * If the original file does not exist yet
4917 * the current backup file becomes the original file
4918 */
4919 if (org == NULL)
4920 EMSG(_("E205: Patchmode: can't save original file"));
4921 else if (mch_stat(org, &st) < 0)
4922 {
4923 vim_rename(backup, (char_u *)org);
4924 vim_free(backup); /* don't delete the file */
4925 backup = NULL;
4926#ifdef UNIX
4927 set_file_time((char_u *)org, st_old.st_atime, st_old.st_mtime);
4928#endif
4929 }
4930 }
4931 /*
4932 * If there is no backup file, remember that a (new) file was
4933 * created.
4934 */
4935 else
4936 {
4937 int empty_fd;
4938
4939 if (org == NULL
Bram Moolenaara5792f52005-11-23 21:25:05 +00004940 || (empty_fd = mch_open(org,
4941 O_CREAT | O_EXTRA | O_EXCL | O_NOFOLLOW,
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00004942 perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004943 EMSG(_("E206: patchmode: can't touch empty original file"));
4944 else
4945 close(empty_fd);
4946 }
4947 if (org != NULL)
4948 {
4949 mch_setperm((char_u *)org, mch_getperm(fname) & 0777);
4950 vim_free(org);
4951 }
4952 }
4953
4954 /*
4955 * Remove the backup unless 'backup' option is set
4956 */
4957 if (!p_bk && backup != NULL && mch_remove(backup) != 0)
4958 EMSG(_("E207: Can't delete backup file"));
4959
4960#ifdef FEAT_SUN_WORKSHOP
4961 if (usingSunWorkShop)
4962 workshop_file_saved((char *) ffname);
4963#endif
4964
4965 goto nofail;
4966
4967 /*
4968 * Finish up. We get here either after failure or success.
4969 */
4970fail:
4971 --no_wait_return; /* may wait for return now */
4972nofail:
4973
4974 /* Done saving, we accept changed buffer warnings again */
4975 buf->b_saving = FALSE;
4976
4977 vim_free(backup);
4978 if (buffer != smallbuf)
4979 vim_free(buffer);
4980#ifdef FEAT_MBYTE
4981 vim_free(fenc_tofree);
4982 vim_free(write_info.bw_conv_buf);
4983# ifdef USE_ICONV
4984 if (write_info.bw_iconv_fd != (iconv_t)-1)
4985 {
4986 iconv_close(write_info.bw_iconv_fd);
4987 write_info.bw_iconv_fd = (iconv_t)-1;
4988 }
4989# endif
4990#endif
4991#ifdef HAVE_ACL
4992 mch_free_acl(acl);
4993#endif
4994
4995 if (errmsg != NULL)
4996 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00004997 int numlen = errnum != NULL ? (int)STRLEN(errnum) : 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004998
4999 attr = hl_attr(HLF_E); /* set highlight for error messages */
5000 msg_add_fname(buf,
5001#ifndef UNIX
5002 sfname
5003#else
5004 fname
5005#endif
5006 ); /* put file name in IObuff with quotes */
5007 if (STRLEN(IObuff) + STRLEN(errmsg) + numlen >= IOSIZE)
5008 IObuff[IOSIZE - STRLEN(errmsg) - numlen - 1] = NUL;
5009 /* If the error message has the form "is ...", put the error number in
5010 * front of the file name. */
5011 if (errnum != NULL)
5012 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00005013 STRMOVE(IObuff + numlen, IObuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005014 mch_memmove(IObuff, errnum, (size_t)numlen);
5015 }
5016 STRCAT(IObuff, errmsg);
5017 emsg(IObuff);
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005018 if (errmsg_allocated)
5019 vim_free(errmsg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005020
5021 retval = FAIL;
5022 if (end == 0)
5023 {
5024 MSG_PUTS_ATTR(_("\nWARNING: Original file may be lost or damaged\n"),
5025 attr | MSG_HIST);
5026 MSG_PUTS_ATTR(_("don't quit the editor until the file is successfully written!"),
5027 attr | MSG_HIST);
5028
5029 /* Update the timestamp to avoid an "overwrite changed file"
5030 * prompt when writing again. */
5031 if (mch_stat((char *)fname, &st_old) >= 0)
5032 {
5033 buf_store_time(buf, &st_old, fname);
5034 buf->b_mtime_read = buf->b_mtime;
5035 }
5036 }
5037 }
5038 msg_scroll = msg_save;
5039
Bram Moolenaar55debbe2010-05-23 23:34:36 +02005040#ifdef FEAT_PERSISTENT_UNDO
5041 /*
5042 * When writing the whole file and 'undofile' is set, also write the undo
5043 * file.
5044 */
5045 if (retval == OK && write_undo_file)
5046 {
5047 char_u hash[UNDO_HASH_SIZE];
5048
5049 sha256_finish(&sha_ctx, hash);
5050 u_write_undo(NULL, FALSE, buf, hash);
5051 }
5052#endif
5053
Bram Moolenaar071d4272004-06-13 20:20:40 +00005054#ifdef FEAT_AUTOCMD
5055#ifdef FEAT_EVAL
5056 if (!should_abort(retval))
5057#else
5058 if (!got_int)
5059#endif
5060 {
5061 aco_save_T aco;
5062
5063 write_no_eol_lnum = 0; /* in case it was set by the previous read */
5064
5065 /*
5066 * Apply POST autocommands.
5067 * Careful: The autocommands may call buf_write() recursively!
5068 */
5069 aucmd_prepbuf(&aco, buf);
5070
5071 if (append)
5072 apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname,
5073 FALSE, curbuf, eap);
5074 else if (filtering)
5075 apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname,
5076 FALSE, curbuf, eap);
5077 else if (reset_changed && whole)
5078 apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname,
5079 FALSE, curbuf, eap);
5080 else
5081 apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname,
5082 FALSE, curbuf, eap);
5083
5084 /* restore curwin/curbuf and a few other things */
5085 aucmd_restbuf(&aco);
5086
5087#ifdef FEAT_EVAL
5088 if (aborting()) /* autocmds may abort script processing */
5089 retval = FALSE;
5090#endif
5091 }
5092#endif
5093
5094 got_int |= prev_got_int;
5095
5096#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
5097 /* Update machine specific information. */
5098 mch_post_buffer_write(buf);
5099#endif
5100 return retval;
5101}
5102
5103/*
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005104 * Set the name of the current buffer. Use when the buffer doesn't have a
5105 * name and a ":r" or ":w" command with a file name is used.
5106 */
5107 static int
5108set_rw_fname(fname, sfname)
5109 char_u *fname;
5110 char_u *sfname;
5111{
5112#ifdef FEAT_AUTOCMD
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005113 buf_T *buf = curbuf;
5114
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005115 /* It's like the unnamed buffer is deleted.... */
5116 if (curbuf->b_p_bl)
5117 apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
5118 apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf);
5119# ifdef FEAT_EVAL
5120 if (aborting()) /* autocmds may abort script processing */
5121 return FAIL;
5122# endif
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005123 if (curbuf != buf)
5124 {
5125 /* We are in another buffer now, don't do the renaming. */
5126 EMSG(_(e_auchangedbuf));
5127 return FAIL;
5128 }
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005129#endif
5130
5131 if (setfname(curbuf, fname, sfname, FALSE) == OK)
5132 curbuf->b_flags |= BF_NOTEDITED;
5133
5134#ifdef FEAT_AUTOCMD
5135 /* ....and a new named one is created */
5136 apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, curbuf);
5137 if (curbuf->b_p_bl)
5138 apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf);
5139# ifdef FEAT_EVAL
5140 if (aborting()) /* autocmds may abort script processing */
5141 return FAIL;
5142# endif
5143
5144 /* Do filetype detection now if 'filetype' is empty. */
5145 if (*curbuf->b_p_ft == NUL)
5146 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005147 if (au_has_group((char_u *)"filetypedetect"))
Bram Moolenaar70836c82006-02-20 21:28:49 +00005148 (void)do_doautocmd((char_u *)"filetypedetect BufRead", FALSE);
Bram Moolenaara3227e22006-03-08 21:32:40 +00005149 do_modelines(0);
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005150 }
5151#endif
5152
5153 return OK;
5154}
5155
5156/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00005157 * Put file name into IObuff with quotes.
5158 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005159 void
Bram Moolenaar071d4272004-06-13 20:20:40 +00005160msg_add_fname(buf, fname)
5161 buf_T *buf;
5162 char_u *fname;
5163{
5164 if (fname == NULL)
5165 fname = (char_u *)"-stdin-";
5166 home_replace(buf, fname, IObuff + 1, IOSIZE - 4, TRUE);
5167 IObuff[0] = '"';
5168 STRCAT(IObuff, "\" ");
5169}
5170
5171/*
5172 * Append message for text mode to IObuff.
5173 * Return TRUE if something appended.
5174 */
5175 static int
5176msg_add_fileformat(eol_type)
5177 int eol_type;
5178{
5179#ifndef USE_CRNL
5180 if (eol_type == EOL_DOS)
5181 {
5182 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[dos]") : _("[dos format]"));
5183 return TRUE;
5184 }
5185#endif
5186#ifndef USE_CR
5187 if (eol_type == EOL_MAC)
5188 {
5189 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[mac]") : _("[mac format]"));
5190 return TRUE;
5191 }
5192#endif
5193#if defined(USE_CRNL) || defined(USE_CR)
5194 if (eol_type == EOL_UNIX)
5195 {
5196 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[unix]") : _("[unix format]"));
5197 return TRUE;
5198 }
5199#endif
5200 return FALSE;
5201}
5202
5203/*
5204 * Append line and character count to IObuff.
5205 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005206 void
Bram Moolenaar071d4272004-06-13 20:20:40 +00005207msg_add_lines(insert_space, lnum, nchars)
5208 int insert_space;
5209 long lnum;
Bram Moolenaar914703b2010-05-31 21:59:46 +02005210 off_t nchars;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005211{
5212 char_u *p;
5213
5214 p = IObuff + STRLEN(IObuff);
5215
5216 if (insert_space)
5217 *p++ = ' ';
5218 if (shortmess(SHM_LINES))
Bram Moolenaar914703b2010-05-31 21:59:46 +02005219 sprintf((char *)p,
5220#ifdef LONG_LONG_OFF_T
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005221 "%ldL, %lldC", lnum, nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005222#else
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005223 /* Explicit typecast avoids warning on Mac OS X 10.6 */
5224 "%ldL, %ldC", lnum, (long)nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005225#endif
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005226 );
Bram Moolenaar071d4272004-06-13 20:20:40 +00005227 else
5228 {
5229 if (lnum == 1)
5230 STRCPY(p, _("1 line, "));
5231 else
5232 sprintf((char *)p, _("%ld lines, "), lnum);
5233 p += STRLEN(p);
5234 if (nchars == 1)
5235 STRCPY(p, _("1 character"));
5236 else
Bram Moolenaar914703b2010-05-31 21:59:46 +02005237 sprintf((char *)p,
5238#ifdef LONG_LONG_OFF_T
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005239 _("%lld characters"), nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005240#else
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005241 /* Explicit typecast avoids warning on Mac OS X 10.6 */
5242 _("%ld characters"), (long)nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005243#endif
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005244 );
Bram Moolenaar071d4272004-06-13 20:20:40 +00005245 }
5246}
5247
5248/*
5249 * Append message for missing line separator to IObuff.
5250 */
5251 static void
5252msg_add_eol()
5253{
5254 STRCAT(IObuff, shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]"));
5255}
5256
5257/*
5258 * Check modification time of file, before writing to it.
5259 * The size isn't checked, because using a tool like "gzip" takes care of
5260 * using the same timestamp but can't set the size.
5261 */
5262 static int
5263check_mtime(buf, st)
5264 buf_T *buf;
5265 struct stat *st;
5266{
5267 if (buf->b_mtime_read != 0
5268 && time_differs((long)st->st_mtime, buf->b_mtime_read))
5269 {
5270 msg_scroll = TRUE; /* don't overwrite messages here */
5271 msg_silent = 0; /* must give this prompt */
5272 /* don't use emsg() here, don't want to flush the buffers */
5273 MSG_ATTR(_("WARNING: The file has been changed since reading it!!!"),
5274 hl_attr(HLF_E));
5275 if (ask_yesno((char_u *)_("Do you really want to write to it"),
5276 TRUE) == 'n')
5277 return FAIL;
5278 msg_scroll = FALSE; /* always overwrite the file message now */
5279 }
5280 return OK;
5281}
5282
5283 static int
5284time_differs(t1, t2)
5285 long t1, t2;
5286{
5287#if defined(__linux__) || defined(MSDOS) || defined(MSWIN)
5288 /* On a FAT filesystem, esp. under Linux, there are only 5 bits to store
5289 * the seconds. Since the roundoff is done when flushing the inode, the
5290 * time may change unexpectedly by one second!!! */
5291 return (t1 - t2 > 1 || t2 - t1 > 1);
5292#else
5293 return (t1 != t2);
5294#endif
5295}
5296
5297/*
5298 * Call write() to write a number of bytes to the file.
5299 * Also handles encryption and 'encoding' conversion.
5300 *
5301 * Return FAIL for failure, OK otherwise.
5302 */
5303 static int
5304buf_write_bytes(ip)
5305 struct bw_info *ip;
5306{
5307 int wlen;
5308 char_u *buf = ip->bw_buf; /* data to write */
5309 int len = ip->bw_len; /* length of data */
5310#ifdef HAS_BW_FLAGS
5311 int flags = ip->bw_flags; /* extra flags */
5312#endif
5313
5314#ifdef FEAT_MBYTE
5315 /*
5316 * Skip conversion when writing the crypt magic number or the BOM.
5317 */
5318 if (!(flags & FIO_NOCONVERT))
5319 {
5320 char_u *p;
5321 unsigned c;
5322 int n;
5323
5324 if (flags & FIO_UTF8)
5325 {
5326 /*
5327 * Convert latin1 in the buffer to UTF-8 in the file.
5328 */
5329 p = ip->bw_conv_buf; /* translate to buffer */
5330 for (wlen = 0; wlen < len; ++wlen)
5331 p += utf_char2bytes(buf[wlen], p);
5332 buf = ip->bw_conv_buf;
5333 len = (int)(p - ip->bw_conv_buf);
5334 }
5335 else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1))
5336 {
5337 /*
5338 * Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
5339 * Latin1 chars in the file.
5340 */
5341 if (flags & FIO_LATIN1)
5342 p = buf; /* translate in-place (can only get shorter) */
5343 else
5344 p = ip->bw_conv_buf; /* translate to buffer */
5345 for (wlen = 0; wlen < len; wlen += n)
5346 {
5347 if (wlen == 0 && ip->bw_restlen != 0)
5348 {
5349 int l;
5350
5351 /* Use remainder of previous call. Append the start of
5352 * buf[] to get a full sequence. Might still be too
5353 * short! */
5354 l = CONV_RESTLEN - ip->bw_restlen;
5355 if (l > len)
5356 l = len;
5357 mch_memmove(ip->bw_rest + ip->bw_restlen, buf, (size_t)l);
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005358 n = utf_ptr2len_len(ip->bw_rest, ip->bw_restlen + l);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005359 if (n > ip->bw_restlen + len)
5360 {
5361 /* We have an incomplete byte sequence at the end to
5362 * be written. We can't convert it without the
5363 * remaining bytes. Keep them for the next call. */
5364 if (ip->bw_restlen + len > CONV_RESTLEN)
5365 return FAIL;
5366 ip->bw_restlen += len;
5367 break;
5368 }
5369 if (n > 1)
5370 c = utf_ptr2char(ip->bw_rest);
5371 else
5372 c = ip->bw_rest[0];
5373 if (n >= ip->bw_restlen)
5374 {
5375 n -= ip->bw_restlen;
5376 ip->bw_restlen = 0;
5377 }
5378 else
5379 {
5380 ip->bw_restlen -= n;
5381 mch_memmove(ip->bw_rest, ip->bw_rest + n,
5382 (size_t)ip->bw_restlen);
5383 n = 0;
5384 }
5385 }
5386 else
5387 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005388 n = utf_ptr2len_len(buf + wlen, len - wlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005389 if (n > len - wlen)
5390 {
5391 /* We have an incomplete byte sequence at the end to
5392 * be written. We can't convert it without the
5393 * remaining bytes. Keep them for the next call. */
5394 if (len - wlen > CONV_RESTLEN)
5395 return FAIL;
5396 ip->bw_restlen = len - wlen;
5397 mch_memmove(ip->bw_rest, buf + wlen,
5398 (size_t)ip->bw_restlen);
5399 break;
5400 }
5401 if (n > 1)
5402 c = utf_ptr2char(buf + wlen);
5403 else
5404 c = buf[wlen];
5405 }
5406
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005407 if (ucs2bytes(c, &p, flags) && !ip->bw_conv_error)
5408 {
5409 ip->bw_conv_error = TRUE;
5410 ip->bw_conv_error_lnum = ip->bw_start_lnum;
5411 }
5412 if (c == NL)
5413 ++ip->bw_start_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005414 }
5415 if (flags & FIO_LATIN1)
5416 len = (int)(p - buf);
5417 else
5418 {
5419 buf = ip->bw_conv_buf;
5420 len = (int)(p - ip->bw_conv_buf);
5421 }
5422 }
5423
5424# ifdef WIN3264
5425 else if (flags & FIO_CODEPAGE)
5426 {
5427 /*
5428 * Convert UTF-8 or codepage to UCS-2 and then to MS-Windows
5429 * codepage.
5430 */
5431 char_u *from;
5432 size_t fromlen;
5433 char_u *to;
5434 int u8c;
5435 BOOL bad = FALSE;
5436 int needed;
5437
5438 if (ip->bw_restlen > 0)
5439 {
5440 /* Need to concatenate the remainder of the previous call and
5441 * the bytes of the current call. Use the end of the
5442 * conversion buffer for this. */
5443 fromlen = len + ip->bw_restlen;
5444 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5445 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5446 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5447 }
5448 else
5449 {
5450 from = buf;
5451 fromlen = len;
5452 }
5453
5454 to = ip->bw_conv_buf;
5455 if (enc_utf8)
5456 {
5457 /* Convert from UTF-8 to UCS-2, to the start of the buffer.
5458 * The buffer has been allocated to be big enough. */
5459 while (fromlen > 0)
5460 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005461 n = (int)utf_ptr2len_len(from, (int)fromlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005462 if (n > (int)fromlen) /* incomplete byte sequence */
5463 break;
5464 u8c = utf_ptr2char(from);
5465 *to++ = (u8c & 0xff);
5466 *to++ = (u8c >> 8);
5467 fromlen -= n;
5468 from += n;
5469 }
5470
5471 /* Copy remainder to ip->bw_rest[] to be used for the next
5472 * call. */
5473 if (fromlen > CONV_RESTLEN)
5474 {
5475 /* weird overlong sequence */
5476 ip->bw_conv_error = TRUE;
5477 return FAIL;
5478 }
5479 mch_memmove(ip->bw_rest, from, fromlen);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005480 ip->bw_restlen = (int)fromlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005481 }
5482 else
5483 {
5484 /* Convert from enc_codepage to UCS-2, to the start of the
5485 * buffer. The buffer has been allocated to be big enough. */
5486 ip->bw_restlen = 0;
5487 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005488 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005489 NULL, 0);
5490 if (needed == 0)
5491 {
5492 /* When conversion fails there may be a trailing byte. */
5493 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005494 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen - 1,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005495 NULL, 0);
5496 if (needed == 0)
5497 {
5498 /* Conversion doesn't work. */
5499 ip->bw_conv_error = TRUE;
5500 return FAIL;
5501 }
5502 /* Save the trailing byte for the next call. */
5503 ip->bw_rest[0] = from[fromlen - 1];
5504 ip->bw_restlen = 1;
5505 }
5506 needed = MultiByteToWideChar(enc_codepage, MB_ERR_INVALID_CHARS,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005507 (LPCSTR)from, (int)(fromlen - ip->bw_restlen),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005508 (LPWSTR)to, needed);
5509 if (needed == 0)
5510 {
5511 /* Safety check: Conversion doesn't work. */
5512 ip->bw_conv_error = TRUE;
5513 return FAIL;
5514 }
5515 to += needed * 2;
5516 }
5517
5518 fromlen = to - ip->bw_conv_buf;
5519 buf = to;
5520# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5521 if (FIO_GET_CP(flags) == CP_UTF8)
5522 {
5523 /* Convert from UCS-2 to UTF-8, using the remainder of the
5524 * conversion buffer. Fails when out of space. */
5525 for (from = ip->bw_conv_buf; fromlen > 1; fromlen -= 2)
5526 {
5527 u8c = *from++;
5528 u8c += (*from++ << 8);
5529 to += utf_char2bytes(u8c, to);
5530 if (to + 6 >= ip->bw_conv_buf + ip->bw_conv_buflen)
5531 {
5532 ip->bw_conv_error = TRUE;
5533 return FAIL;
5534 }
5535 }
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005536 len = (int)(to - buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005537 }
5538 else
5539#endif
5540 {
5541 /* Convert from UCS-2 to the codepage, using the remainder of
5542 * the conversion buffer. If the conversion uses the default
5543 * character "0", the data doesn't fit in this encoding, so
5544 * fail. */
5545 len = WideCharToMultiByte(FIO_GET_CP(flags), 0,
5546 (LPCWSTR)ip->bw_conv_buf, (int)fromlen / sizeof(WCHAR),
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005547 (LPSTR)to, (int)(ip->bw_conv_buflen - fromlen), 0,
5548 &bad);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005549 if (bad)
5550 {
5551 ip->bw_conv_error = TRUE;
5552 return FAIL;
5553 }
5554 }
5555 }
5556# endif
5557
Bram Moolenaar56718732006-03-15 22:53:57 +00005558# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00005559 else if (flags & FIO_MACROMAN)
5560 {
5561 /*
5562 * Convert UTF-8 or latin1 to Apple MacRoman.
5563 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005564 char_u *from;
5565 size_t fromlen;
5566
5567 if (ip->bw_restlen > 0)
5568 {
5569 /* Need to concatenate the remainder of the previous call and
5570 * the bytes of the current call. Use the end of the
5571 * conversion buffer for this. */
5572 fromlen = len + ip->bw_restlen;
5573 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5574 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5575 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5576 }
5577 else
5578 {
5579 from = buf;
5580 fromlen = len;
5581 }
5582
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00005583 if (enc2macroman(from, fromlen,
5584 ip->bw_conv_buf, &len, ip->bw_conv_buflen,
5585 ip->bw_rest, &ip->bw_restlen) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005586 {
5587 ip->bw_conv_error = TRUE;
5588 return FAIL;
5589 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005590 buf = ip->bw_conv_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005591 }
5592# endif
5593
5594# ifdef USE_ICONV
5595 if (ip->bw_iconv_fd != (iconv_t)-1)
5596 {
5597 const char *from;
5598 size_t fromlen;
5599 char *to;
5600 size_t tolen;
5601
5602 /* Convert with iconv(). */
5603 if (ip->bw_restlen > 0)
5604 {
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005605 char *fp;
5606
Bram Moolenaar071d4272004-06-13 20:20:40 +00005607 /* Need to concatenate the remainder of the previous call and
5608 * the bytes of the current call. Use the end of the
5609 * conversion buffer for this. */
5610 fromlen = len + ip->bw_restlen;
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005611 fp = (char *)ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5612 mch_memmove(fp, ip->bw_rest, (size_t)ip->bw_restlen);
5613 mch_memmove(fp + ip->bw_restlen, buf, (size_t)len);
5614 from = fp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005615 tolen = ip->bw_conv_buflen - fromlen;
5616 }
5617 else
5618 {
5619 from = (const char *)buf;
5620 fromlen = len;
5621 tolen = ip->bw_conv_buflen;
5622 }
5623 to = (char *)ip->bw_conv_buf;
5624
5625 if (ip->bw_first)
5626 {
5627 size_t save_len = tolen;
5628
5629 /* output the initial shift state sequence */
5630 (void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen);
5631
5632 /* There is a bug in iconv() on Linux (which appears to be
5633 * wide-spread) which sets "to" to NULL and messes up "tolen".
5634 */
5635 if (to == NULL)
5636 {
5637 to = (char *)ip->bw_conv_buf;
5638 tolen = save_len;
5639 }
5640 ip->bw_first = FALSE;
5641 }
5642
5643 /*
5644 * If iconv() has an error or there is not enough room, fail.
5645 */
5646 if ((iconv(ip->bw_iconv_fd, (void *)&from, &fromlen, &to, &tolen)
5647 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
5648 || fromlen > CONV_RESTLEN)
5649 {
5650 ip->bw_conv_error = TRUE;
5651 return FAIL;
5652 }
5653
5654 /* copy remainder to ip->bw_rest[] to be used for the next call. */
5655 if (fromlen > 0)
5656 mch_memmove(ip->bw_rest, (void *)from, fromlen);
5657 ip->bw_restlen = (int)fromlen;
5658
5659 buf = ip->bw_conv_buf;
5660 len = (int)((char_u *)to - ip->bw_conv_buf);
5661 }
5662# endif
5663 }
5664#endif /* FEAT_MBYTE */
5665
5666#ifdef FEAT_CRYPT
5667 if (flags & FIO_ENCRYPTED) /* encrypt the data */
Bram Moolenaar04c9baf2010-06-01 23:37:39 +02005668 crypt_encode(buf, len, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005669#endif
5670
5671 /* Repeat the write(), it may be interrupted by a signal. */
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005672 while (len > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005673 {
5674 wlen = vim_write(ip->bw_fd, buf, len);
5675 if (wlen <= 0) /* error! */
5676 return FAIL;
5677 len -= wlen;
5678 buf += wlen;
5679 }
5680 return OK;
5681}
5682
5683#ifdef FEAT_MBYTE
5684/*
5685 * Convert a Unicode character to bytes.
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005686 * Return TRUE for an error, FALSE when it's OK.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005687 */
5688 static int
5689ucs2bytes(c, pp, flags)
5690 unsigned c; /* in: character */
5691 char_u **pp; /* in/out: pointer to result */
5692 int flags; /* FIO_ flags */
5693{
5694 char_u *p = *pp;
5695 int error = FALSE;
5696 int cc;
5697
5698
5699 if (flags & FIO_UCS4)
5700 {
5701 if (flags & FIO_ENDIAN_L)
5702 {
5703 *p++ = c;
5704 *p++ = (c >> 8);
5705 *p++ = (c >> 16);
5706 *p++ = (c >> 24);
5707 }
5708 else
5709 {
5710 *p++ = (c >> 24);
5711 *p++ = (c >> 16);
5712 *p++ = (c >> 8);
5713 *p++ = c;
5714 }
5715 }
5716 else if (flags & (FIO_UCS2 | FIO_UTF16))
5717 {
5718 if (c >= 0x10000)
5719 {
5720 if (flags & FIO_UTF16)
5721 {
5722 /* Make two words, ten bits of the character in each. First
5723 * word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff */
5724 c -= 0x10000;
5725 if (c >= 0x100000)
5726 error = TRUE;
5727 cc = ((c >> 10) & 0x3ff) + 0xd800;
5728 if (flags & FIO_ENDIAN_L)
5729 {
5730 *p++ = cc;
5731 *p++ = ((unsigned)cc >> 8);
5732 }
5733 else
5734 {
5735 *p++ = ((unsigned)cc >> 8);
5736 *p++ = cc;
5737 }
5738 c = (c & 0x3ff) + 0xdc00;
5739 }
5740 else
5741 error = TRUE;
5742 }
5743 if (flags & FIO_ENDIAN_L)
5744 {
5745 *p++ = c;
5746 *p++ = (c >> 8);
5747 }
5748 else
5749 {
5750 *p++ = (c >> 8);
5751 *p++ = c;
5752 }
5753 }
5754 else /* Latin1 */
5755 {
5756 if (c >= 0x100)
5757 {
5758 error = TRUE;
5759 *p++ = 0xBF;
5760 }
5761 else
5762 *p++ = c;
5763 }
5764
5765 *pp = p;
5766 return error;
5767}
5768
5769/*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005770 * Return TRUE if file encoding "fenc" requires conversion from or to
5771 * 'encoding'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005772 */
5773 static int
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005774need_conversion(fenc)
5775 char_u *fenc;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005776{
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005777 int same_encoding;
5778 int enc_flags;
5779 int fenc_flags;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005780
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005781 if (*fenc == NUL || STRCMP(p_enc, fenc) == 0)
Bram Moolenaar442b4222010-05-24 21:34:22 +02005782 {
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005783 same_encoding = TRUE;
Bram Moolenaar442b4222010-05-24 21:34:22 +02005784 fenc_flags = 0;
5785 }
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005786 else
5787 {
5788 /* Ignore difference between "ansi" and "latin1", "ucs-4" and
5789 * "ucs-4be", etc. */
5790 enc_flags = get_fio_flags(p_enc);
5791 fenc_flags = get_fio_flags(fenc);
5792 same_encoding = (enc_flags != 0 && fenc_flags == enc_flags);
5793 }
5794 if (same_encoding)
5795 {
5796 /* Specified encoding matches with 'encoding'. This requires
5797 * conversion when 'encoding' is Unicode but not UTF-8. */
5798 return enc_unicode != 0;
5799 }
5800
5801 /* Encodings differ. However, conversion is not needed when 'enc' is any
5802 * Unicode encoding and the file is UTF-8. */
5803 return !(enc_utf8 && fenc_flags == FIO_UTF8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005804}
5805
5806/*
5807 * Check "ptr" for a unicode encoding and return the FIO_ flags needed for the
5808 * internal conversion.
5809 * if "ptr" is an empty string, use 'encoding'.
5810 */
5811 static int
5812get_fio_flags(ptr)
5813 char_u *ptr;
5814{
5815 int prop;
5816
5817 if (*ptr == NUL)
5818 ptr = p_enc;
5819
5820 prop = enc_canon_props(ptr);
5821 if (prop & ENC_UNICODE)
5822 {
5823 if (prop & ENC_2BYTE)
5824 {
5825 if (prop & ENC_ENDIAN_L)
5826 return FIO_UCS2 | FIO_ENDIAN_L;
5827 return FIO_UCS2;
5828 }
5829 if (prop & ENC_4BYTE)
5830 {
5831 if (prop & ENC_ENDIAN_L)
5832 return FIO_UCS4 | FIO_ENDIAN_L;
5833 return FIO_UCS4;
5834 }
5835 if (prop & ENC_2WORD)
5836 {
5837 if (prop & ENC_ENDIAN_L)
5838 return FIO_UTF16 | FIO_ENDIAN_L;
5839 return FIO_UTF16;
5840 }
5841 return FIO_UTF8;
5842 }
5843 if (prop & ENC_LATIN1)
5844 return FIO_LATIN1;
5845 /* must be ENC_DBCS, requires iconv() */
5846 return 0;
5847}
5848
5849#ifdef WIN3264
5850/*
5851 * Check "ptr" for a MS-Windows codepage name and return the FIO_ flags needed
5852 * for the conversion MS-Windows can do for us. Also accept "utf-8".
5853 * Used for conversion between 'encoding' and 'fileencoding'.
5854 */
5855 static int
5856get_win_fio_flags(ptr)
5857 char_u *ptr;
5858{
5859 int cp;
5860
5861 /* Cannot do this when 'encoding' is not utf-8 and not a codepage. */
5862 if (!enc_utf8 && enc_codepage <= 0)
5863 return 0;
5864
5865 cp = encname2codepage(ptr);
5866 if (cp == 0)
5867 {
5868# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5869 if (STRCMP(ptr, "utf-8") == 0)
5870 cp = CP_UTF8;
5871 else
5872# endif
5873 return 0;
5874 }
5875 return FIO_PUT_CP(cp) | FIO_CODEPAGE;
5876}
5877#endif
5878
5879#ifdef MACOS_X
5880/*
5881 * Check "ptr" for a Carbon supported encoding and return the FIO_ flags
5882 * needed for the internal conversion to/from utf-8 or latin1.
5883 */
5884 static int
5885get_mac_fio_flags(ptr)
5886 char_u *ptr;
5887{
5888 if ((enc_utf8 || STRCMP(p_enc, "latin1") == 0)
5889 && (enc_canon_props(ptr) & ENC_MACROMAN))
5890 return FIO_MACROMAN;
5891 return 0;
5892}
5893#endif
5894
5895/*
5896 * Check for a Unicode BOM (Byte Order Mark) at the start of p[size].
5897 * "size" must be at least 2.
5898 * Return the name of the encoding and set "*lenp" to the length.
5899 * Returns NULL when no BOM found.
5900 */
5901 static char_u *
5902check_for_bom(p, size, lenp, flags)
5903 char_u *p;
5904 long size;
5905 int *lenp;
5906 int flags;
5907{
5908 char *name = NULL;
5909 int len = 2;
5910
5911 if (p[0] == 0xef && p[1] == 0xbb && size >= 3 && p[2] == 0xbf
Bram Moolenaaree0f5a62008-07-24 20:09:16 +00005912 && (flags == FIO_ALL || flags == FIO_UTF8 || flags == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005913 {
5914 name = "utf-8"; /* EF BB BF */
5915 len = 3;
5916 }
5917 else if (p[0] == 0xff && p[1] == 0xfe)
5918 {
5919 if (size >= 4 && p[2] == 0 && p[3] == 0
5920 && (flags == FIO_ALL || flags == (FIO_UCS4 | FIO_ENDIAN_L)))
5921 {
5922 name = "ucs-4le"; /* FF FE 00 00 */
5923 len = 4;
5924 }
Bram Moolenaar223a1892008-11-11 20:57:11 +00005925 else if (flags == (FIO_UCS2 | FIO_ENDIAN_L))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005926 name = "ucs-2le"; /* FF FE */
Bram Moolenaar223a1892008-11-11 20:57:11 +00005927 else if (flags == FIO_ALL || flags == (FIO_UTF16 | FIO_ENDIAN_L))
5928 /* utf-16le is preferred, it also works for ucs-2le text */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005929 name = "utf-16le"; /* FF FE */
5930 }
5931 else if (p[0] == 0xfe && p[1] == 0xff
5932 && (flags == FIO_ALL || flags == FIO_UCS2 || flags == FIO_UTF16))
5933 {
Bram Moolenaarffd82c52008-02-20 17:15:26 +00005934 /* Default to utf-16, it works also for ucs-2 text. */
5935 if (flags == FIO_UCS2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005936 name = "ucs-2"; /* FE FF */
Bram Moolenaarffd82c52008-02-20 17:15:26 +00005937 else
5938 name = "utf-16"; /* FE FF */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005939 }
5940 else if (size >= 4 && p[0] == 0 && p[1] == 0 && p[2] == 0xfe
5941 && p[3] == 0xff && (flags == FIO_ALL || flags == FIO_UCS4))
5942 {
5943 name = "ucs-4"; /* 00 00 FE FF */
5944 len = 4;
5945 }
5946
5947 *lenp = len;
5948 return (char_u *)name;
5949}
5950
5951/*
5952 * Generate a BOM in "buf[4]" for encoding "name".
5953 * Return the length of the BOM (zero when no BOM).
5954 */
5955 static int
5956make_bom(buf, name)
5957 char_u *buf;
5958 char_u *name;
5959{
5960 int flags;
5961 char_u *p;
5962
5963 flags = get_fio_flags(name);
5964
5965 /* Can't put a BOM in a non-Unicode file. */
5966 if (flags == FIO_LATIN1 || flags == 0)
5967 return 0;
5968
5969 if (flags == FIO_UTF8) /* UTF-8 */
5970 {
5971 buf[0] = 0xef;
5972 buf[1] = 0xbb;
5973 buf[2] = 0xbf;
5974 return 3;
5975 }
5976 p = buf;
5977 (void)ucs2bytes(0xfeff, &p, flags);
5978 return (int)(p - buf);
5979}
5980#endif
5981
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00005982#if defined(FEAT_VIMINFO) || defined(FEAT_BROWSE) || \
Bram Moolenaara0174af2008-01-02 20:08:25 +00005983 defined(FEAT_QUICKFIX) || defined(FEAT_AUTOCMD) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005984/*
5985 * Try to find a shortname by comparing the fullname with the current
5986 * directory.
Bram Moolenaard089d9b2007-09-30 12:02:55 +00005987 * Returns "full_path" or pointer into "full_path" if shortened.
5988 */
5989 char_u *
5990shorten_fname1(full_path)
5991 char_u *full_path;
5992{
5993 char_u dirname[MAXPATHL];
5994 char_u *p = full_path;
5995
5996 if (mch_dirname(dirname, MAXPATHL) == OK)
5997 {
5998 p = shorten_fname(full_path, dirname);
5999 if (p == NULL || *p == NUL)
6000 p = full_path;
6001 }
6002 return p;
6003}
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00006004#endif
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006005
6006/*
6007 * Try to find a shortname by comparing the fullname with the current
6008 * directory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006009 * Returns NULL if not shorter name possible, pointer into "full_path"
6010 * otherwise.
6011 */
6012 char_u *
6013shorten_fname(full_path, dir_name)
6014 char_u *full_path;
6015 char_u *dir_name;
6016{
6017 int len;
6018 char_u *p;
6019
6020 if (full_path == NULL)
6021 return NULL;
6022 len = (int)STRLEN(dir_name);
6023 if (fnamencmp(dir_name, full_path, len) == 0)
6024 {
6025 p = full_path + len;
6026#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
6027 /*
6028 * MSDOS: when a file is in the root directory, dir_name will end in a
6029 * slash, since C: by itself does not define a specific dir. In this
6030 * case p may already be correct. <negri>
6031 */
6032 if (!((len > 2) && (*(p - 2) == ':')))
6033#endif
6034 {
6035 if (vim_ispathsep(*p))
6036 ++p;
6037#ifndef VMS /* the path separator is always part of the path */
6038 else
6039 p = NULL;
6040#endif
6041 }
6042 }
6043#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
6044 /*
6045 * When using a file in the current drive, remove the drive name:
6046 * "A:\dir\file" -> "\dir\file". This helps when moving a session file on
6047 * a floppy from "A:\dir" to "B:\dir".
6048 */
6049 else if (len > 3
6050 && TOUPPER_LOC(full_path[0]) == TOUPPER_LOC(dir_name[0])
6051 && full_path[1] == ':'
6052 && vim_ispathsep(full_path[2]))
6053 p = full_path + 2;
6054#endif
6055 else
6056 p = NULL;
6057 return p;
6058}
6059
6060/*
6061 * Shorten filenames for all buffers.
6062 * When "force" is TRUE: Use full path from now on for files currently being
6063 * edited, both for file name and swap file name. Try to shorten the file
6064 * names a bit, if safe to do so.
6065 * When "force" is FALSE: Only try to shorten absolute file names.
6066 * For buffers that have buftype "nofile" or "scratch": never change the file
6067 * name.
6068 */
6069 void
6070shorten_fnames(force)
6071 int force;
6072{
6073 char_u dirname[MAXPATHL];
6074 buf_T *buf;
6075 char_u *p;
6076
6077 mch_dirname(dirname, MAXPATHL);
6078 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
6079 {
6080 if (buf->b_fname != NULL
6081#ifdef FEAT_QUICKFIX
6082 && !bt_nofile(buf)
6083#endif
6084 && !path_with_url(buf->b_fname)
6085 && (force
6086 || buf->b_sfname == NULL
6087 || mch_isFullName(buf->b_sfname)))
6088 {
6089 vim_free(buf->b_sfname);
6090 buf->b_sfname = NULL;
6091 p = shorten_fname(buf->b_ffname, dirname);
6092 if (p != NULL)
6093 {
6094 buf->b_sfname = vim_strsave(p);
6095 buf->b_fname = buf->b_sfname;
6096 }
6097 if (p == NULL || buf->b_fname == NULL)
6098 buf->b_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006099 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00006100
6101 /* Always make the swap file name a full path, a "nofile" buffer may
6102 * also have a swap file. */
6103 mf_fullname(buf->b_ml.ml_mfp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006104 }
6105#ifdef FEAT_WINDOWS
6106 status_redraw_all();
Bram Moolenaar49d7bf12006-02-17 21:45:41 +00006107 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006108#endif
6109}
6110
6111#if (defined(FEAT_DND) && defined(FEAT_GUI_GTK)) \
6112 || defined(FEAT_GUI_MSWIN) \
6113 || defined(FEAT_GUI_MAC) \
6114 || defined(PROTO)
6115/*
6116 * Shorten all filenames in "fnames[count]" by current directory.
6117 */
6118 void
6119shorten_filenames(fnames, count)
6120 char_u **fnames;
6121 int count;
6122{
6123 int i;
6124 char_u dirname[MAXPATHL];
6125 char_u *p;
6126
6127 if (fnames == NULL || count < 1)
6128 return;
6129 mch_dirname(dirname, sizeof(dirname));
6130 for (i = 0; i < count; ++i)
6131 {
6132 if ((p = shorten_fname(fnames[i], dirname)) != NULL)
6133 {
6134 /* shorten_fname() returns pointer in given "fnames[i]". If free
6135 * "fnames[i]" first, "p" becomes invalid. So we need to copy
6136 * "p" first then free fnames[i]. */
6137 p = vim_strsave(p);
6138 vim_free(fnames[i]);
6139 fnames[i] = p;
6140 }
6141 }
6142}
6143#endif
6144
6145/*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006146 * add extension to file name - change path/fo.o.h to path/fo.o.h.ext or
Bram Moolenaar071d4272004-06-13 20:20:40 +00006147 * fo_o_h.ext for MSDOS or when shortname option set.
6148 *
6149 * Assumed that fname is a valid name found in the filesystem we assure that
6150 * the return value is a different name and ends in 'ext'.
6151 * "ext" MUST be at most 4 characters long if it starts with a dot, 3
6152 * characters otherwise.
6153 * Space for the returned name is allocated, must be freed later.
6154 * Returns NULL when out of memory.
6155 */
6156 char_u *
6157modname(fname, ext, prepend_dot)
6158 char_u *fname, *ext;
6159 int prepend_dot; /* may prepend a '.' to file name */
6160{
6161 return buf_modname(
6162#ifdef SHORT_FNAME
6163 TRUE,
6164#else
6165 (curbuf->b_p_sn || curbuf->b_shortname),
6166#endif
6167 fname, ext, prepend_dot);
6168}
6169
6170 char_u *
6171buf_modname(shortname, fname, ext, prepend_dot)
6172 int shortname; /* use 8.3 file name */
6173 char_u *fname, *ext;
6174 int prepend_dot; /* may prepend a '.' to file name */
6175{
6176 char_u *retval;
6177 char_u *s;
6178 char_u *e;
6179 char_u *ptr;
6180 int fnamelen, extlen;
6181
6182 extlen = (int)STRLEN(ext);
6183
6184 /*
6185 * If there is no file name we must get the name of the current directory
6186 * (we need the full path in case :cd is used).
6187 */
6188 if (fname == NULL || *fname == NUL)
6189 {
6190 retval = alloc((unsigned)(MAXPATHL + extlen + 3));
6191 if (retval == NULL)
6192 return NULL;
6193 if (mch_dirname(retval, MAXPATHL) == FAIL ||
6194 (fnamelen = (int)STRLEN(retval)) == 0)
6195 {
6196 vim_free(retval);
6197 return NULL;
6198 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006199 if (!after_pathsep(retval, retval + fnamelen))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006200 {
6201 retval[fnamelen++] = PATHSEP;
6202 retval[fnamelen] = NUL;
6203 }
6204#ifndef SHORT_FNAME
6205 prepend_dot = FALSE; /* nothing to prepend a dot to */
6206#endif
6207 }
6208 else
6209 {
6210 fnamelen = (int)STRLEN(fname);
6211 retval = alloc((unsigned)(fnamelen + extlen + 3));
6212 if (retval == NULL)
6213 return NULL;
6214 STRCPY(retval, fname);
6215#ifdef VMS
6216 vms_remove_version(retval); /* we do not need versions here */
6217#endif
6218 }
6219
6220 /*
6221 * search backwards until we hit a '/', '\' or ':' replacing all '.'
6222 * by '_' for MSDOS or when shortname option set and ext starts with a dot.
6223 * Then truncate what is after the '/', '\' or ':' to 8 characters for
6224 * MSDOS and 26 characters for AMIGA, a lot more for UNIX.
6225 */
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006226 for (ptr = retval + fnamelen; ptr > retval; mb_ptr_back(retval, ptr))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006227 {
6228#ifndef RISCOS
6229 if (*ext == '.'
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006230# ifdef USE_LONG_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00006231 && (!USE_LONG_FNAME || shortname)
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006232# else
6233# ifndef SHORT_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00006234 && shortname
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006235# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006236# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006237 )
6238 if (*ptr == '.') /* replace '.' by '_' */
6239 *ptr = '_';
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006240#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006241 if (vim_ispathsep(*ptr))
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006242 {
6243 ++ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006244 break;
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006245 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006246 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006247
6248 /* the file name has at most BASENAMELEN characters. */
6249#ifndef SHORT_FNAME
6250 if (STRLEN(ptr) > (unsigned)BASENAMELEN)
6251 ptr[BASENAMELEN] = '\0';
6252#endif
6253
6254 s = ptr + STRLEN(ptr);
6255
6256 /*
6257 * For 8.3 file names we may have to reduce the length.
6258 */
6259#ifdef USE_LONG_FNAME
6260 if (!USE_LONG_FNAME || shortname)
6261#else
6262# ifndef SHORT_FNAME
6263 if (shortname)
6264# endif
6265#endif
6266 {
6267 /*
6268 * If there is no file name, or the file name ends in '/', and the
6269 * extension starts with '.', put a '_' before the dot, because just
6270 * ".ext" is invalid.
6271 */
6272 if (fname == NULL || *fname == NUL
6273 || vim_ispathsep(fname[STRLEN(fname) - 1]))
6274 {
6275#ifdef RISCOS
6276 if (*ext == '/')
6277#else
6278 if (*ext == '.')
6279#endif
6280 *s++ = '_';
6281 }
6282 /*
6283 * If the extension starts with '.', truncate the base name at 8
6284 * characters
6285 */
6286#ifdef RISCOS
6287 /* We normally use '/', but swap files are '_' */
6288 else if (*ext == '/' || *ext == '_')
6289#else
6290 else if (*ext == '.')
6291#endif
6292 {
Bram Moolenaar78a15312009-05-15 19:33:18 +00006293 if ((size_t)(s - ptr) > (size_t)8)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006294 {
6295 s = ptr + 8;
6296 *s = '\0';
6297 }
6298 }
6299 /*
6300 * If the extension doesn't start with '.', and the file name
6301 * doesn't have an extension yet, append a '.'
6302 */
6303#ifdef RISCOS
6304 else if ((e = vim_strchr(ptr, '/')) == NULL)
6305 *s++ = '/';
6306#else
6307 else if ((e = vim_strchr(ptr, '.')) == NULL)
6308 *s++ = '.';
6309#endif
6310 /*
6311 * If the extension doesn't start with '.', and there already is an
Bram Moolenaar7263a772007-05-10 17:35:54 +00006312 * extension, it may need to be truncated
Bram Moolenaar071d4272004-06-13 20:20:40 +00006313 */
6314 else if ((int)STRLEN(e) + extlen > 4)
6315 s = e + 4 - extlen;
6316 }
6317#if defined(OS2) || defined(USE_LONG_FNAME) || defined(WIN3264)
6318 /*
6319 * If there is no file name, and the extension starts with '.', put a
6320 * '_' before the dot, because just ".ext" may be invalid if it's on a
6321 * FAT partition, and on HPFS it doesn't matter.
6322 */
6323 else if ((fname == NULL || *fname == NUL) && *ext == '.')
6324 *s++ = '_';
6325#endif
6326
6327 /*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006328 * Append the extension.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006329 * ext can start with '.' and cannot exceed 3 more characters.
6330 */
6331 STRCPY(s, ext);
6332
6333#ifndef SHORT_FNAME
6334 /*
6335 * Prepend the dot.
6336 */
6337 if (prepend_dot && !shortname && *(e = gettail(retval)) !=
6338#ifdef RISCOS
6339 '/'
6340#else
6341 '.'
6342#endif
6343#ifdef USE_LONG_FNAME
6344 && USE_LONG_FNAME
6345#endif
6346 )
6347 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006348 STRMOVE(e + 1, e);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006349#ifdef RISCOS
6350 *e = '/';
6351#else
6352 *e = '.';
6353#endif
6354 }
6355#endif
6356
6357 /*
6358 * Check that, after appending the extension, the file name is really
6359 * different.
6360 */
6361 if (fname != NULL && STRCMP(fname, retval) == 0)
6362 {
6363 /* we search for a character that can be replaced by '_' */
6364 while (--s >= ptr)
6365 {
6366 if (*s != '_')
6367 {
6368 *s = '_';
6369 break;
6370 }
6371 }
6372 if (s < ptr) /* fname was "________.<ext>", how tricky! */
6373 *ptr = 'v';
6374 }
6375 return retval;
6376}
6377
6378/*
6379 * Like fgets(), but if the file line is too long, it is truncated and the
6380 * rest of the line is thrown away. Returns TRUE for end-of-file.
6381 */
6382 int
6383vim_fgets(buf, size, fp)
6384 char_u *buf;
6385 int size;
6386 FILE *fp;
6387{
6388 char *eof;
6389#define FGETS_SIZE 200
6390 char tbuf[FGETS_SIZE];
6391
6392 buf[size - 2] = NUL;
6393#ifdef USE_CR
6394 eof = fgets_cr((char *)buf, size, fp);
6395#else
6396 eof = fgets((char *)buf, size, fp);
6397#endif
6398 if (buf[size - 2] != NUL && buf[size - 2] != '\n')
6399 {
6400 buf[size - 1] = NUL; /* Truncate the line */
6401
6402 /* Now throw away the rest of the line: */
6403 do
6404 {
6405 tbuf[FGETS_SIZE - 2] = NUL;
6406#ifdef USE_CR
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006407 ignoredp = fgets_cr((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006408#else
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006409 ignoredp = fgets((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006410#endif
6411 } while (tbuf[FGETS_SIZE - 2] != NUL && tbuf[FGETS_SIZE - 2] != '\n');
6412 }
6413 return (eof == NULL);
6414}
6415
6416#if defined(USE_CR) || defined(PROTO)
6417/*
6418 * Like vim_fgets(), but accept any line terminator: CR, CR-LF or LF.
6419 * Returns TRUE for end-of-file.
6420 * Only used for the Mac, because it's much slower than vim_fgets().
6421 */
6422 int
6423tag_fgets(buf, size, fp)
6424 char_u *buf;
6425 int size;
6426 FILE *fp;
6427{
6428 int i = 0;
6429 int c;
6430 int eof = FALSE;
6431
6432 for (;;)
6433 {
6434 c = fgetc(fp);
6435 if (c == EOF)
6436 {
6437 eof = TRUE;
6438 break;
6439 }
6440 if (c == '\r')
6441 {
6442 /* Always store a NL for end-of-line. */
6443 if (i < size - 1)
6444 buf[i++] = '\n';
6445 c = fgetc(fp);
6446 if (c != '\n') /* Macintosh format: single CR. */
6447 ungetc(c, fp);
6448 break;
6449 }
6450 if (i < size - 1)
6451 buf[i++] = c;
6452 if (c == '\n')
6453 break;
6454 }
6455 buf[i] = NUL;
6456 return eof;
6457}
6458#endif
6459
6460/*
6461 * rename() only works if both files are on the same file system, this
6462 * function will (attempts to?) copy the file across if rename fails -- webb
6463 * Return -1 for failure, 0 for success.
6464 */
6465 int
6466vim_rename(from, to)
6467 char_u *from;
6468 char_u *to;
6469{
6470 int fd_in;
6471 int fd_out;
6472 int n;
6473 char *errmsg = NULL;
6474 char *buffer;
6475#ifdef AMIGA
6476 BPTR flock;
6477#endif
6478 struct stat st;
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006479 long perm;
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006480#ifdef HAVE_ACL
6481 vim_acl_T acl; /* ACL from original file */
6482#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006483#if defined(UNIX) || defined(CASE_INSENSITIVE_FILENAME)
6484 int use_tmp_file = FALSE;
6485#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006486
6487 /*
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006488 * When the names are identical, there is nothing to do. When they refer
6489 * to the same file (ignoring case and slash/backslash differences) but
6490 * the file name differs we need to go through a temp file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006491 */
6492 if (fnamecmp(from, to) == 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006493 {
6494#ifdef CASE_INSENSITIVE_FILENAME
6495 if (STRCMP(gettail(from), gettail(to)) != 0)
6496 use_tmp_file = TRUE;
6497 else
6498#endif
6499 return 0;
6500 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006501
6502 /*
6503 * Fail if the "from" file doesn't exist. Avoids that "to" is deleted.
6504 */
6505 if (mch_stat((char *)from, &st) < 0)
6506 return -1;
6507
Bram Moolenaar3576da72008-12-30 15:15:57 +00006508#ifdef UNIX
6509 {
6510 struct stat st_to;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006511
6512 /* It's possible for the source and destination to be the same file.
6513 * This happens when "from" and "to" differ in case and are on a FAT32
6514 * filesystem. In that case go through a temp file name. */
6515 if (mch_stat((char *)to, &st_to) >= 0
6516 && st.st_dev == st_to.st_dev
6517 && st.st_ino == st_to.st_ino)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006518 use_tmp_file = TRUE;
6519 }
6520#endif
6521
6522#if defined(UNIX) || defined(CASE_INSENSITIVE_FILENAME)
6523 if (use_tmp_file)
6524 {
6525 char tempname[MAXPATHL + 1];
6526
6527 /*
6528 * Find a name that doesn't exist and is in the same directory.
6529 * Rename "from" to "tempname" and then rename "tempname" to "to".
6530 */
6531 if (STRLEN(from) >= MAXPATHL - 5)
6532 return -1;
6533 STRCPY(tempname, from);
6534 for (n = 123; n < 99999; ++n)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006535 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006536 sprintf((char *)gettail((char_u *)tempname), "%d", n);
6537 if (mch_stat(tempname, &st) < 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006538 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006539 if (mch_rename((char *)from, tempname) == 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006540 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006541 if (mch_rename(tempname, (char *)to) == 0)
6542 return 0;
6543 /* Strange, the second step failed. Try moving the
6544 * file back and return failure. */
6545 mch_rename(tempname, (char *)from);
Bram Moolenaar3576da72008-12-30 15:15:57 +00006546 return -1;
6547 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006548 /* If it fails for one temp name it will most likely fail
6549 * for any temp name, give up. */
6550 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006551 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006552 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006553 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006554 }
6555#endif
6556
Bram Moolenaar071d4272004-06-13 20:20:40 +00006557 /*
6558 * Delete the "to" file, this is required on some systems to make the
6559 * mch_rename() work, on other systems it makes sure that we don't have
6560 * two files when the mch_rename() fails.
6561 */
6562
6563#ifdef AMIGA
6564 /*
6565 * With MSDOS-compatible filesystems (crossdos, messydos) it is possible
6566 * that the name of the "to" file is the same as the "from" file, even
Bram Moolenaar7263a772007-05-10 17:35:54 +00006567 * though the names are different. To avoid the chance of accidentally
Bram Moolenaar071d4272004-06-13 20:20:40 +00006568 * deleting the "from" file (horror!) we lock it during the remove.
6569 *
6570 * When used for making a backup before writing the file: This should not
6571 * happen with ":w", because startscript() should detect this problem and
6572 * set buf->b_shortname, causing modname() to return a correct ".bak" file
6573 * name. This problem does exist with ":w filename", but then the
6574 * original file will be somewhere else so the backup isn't really
6575 * important. If autoscripting is off the rename may fail.
6576 */
6577 flock = Lock((UBYTE *)from, (long)ACCESS_READ);
6578#endif
6579 mch_remove(to);
6580#ifdef AMIGA
6581 if (flock)
6582 UnLock(flock);
6583#endif
6584
6585 /*
6586 * First try a normal rename, return if it works.
6587 */
6588 if (mch_rename((char *)from, (char *)to) == 0)
6589 return 0;
6590
6591 /*
6592 * Rename() failed, try copying the file.
6593 */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006594 perm = mch_getperm(from);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006595#ifdef HAVE_ACL
6596 /* For systems that support ACL: get the ACL from the original file. */
6597 acl = mch_get_acl(from);
6598#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006599 fd_in = mch_open((char *)from, O_RDONLY|O_EXTRA, 0);
6600 if (fd_in == -1)
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006601 {
6602#ifdef HAVE_ACL
6603 mch_free_acl(acl);
6604#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006605 return -1;
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006606 }
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006607
6608 /* Create the new file with same permissions as the original. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00006609 fd_out = mch_open((char *)to,
6610 O_CREAT|O_EXCL|O_WRONLY|O_EXTRA|O_NOFOLLOW, (int)perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006611 if (fd_out == -1)
6612 {
6613 close(fd_in);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006614#ifdef HAVE_ACL
6615 mch_free_acl(acl);
6616#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006617 return -1;
6618 }
6619
6620 buffer = (char *)alloc(BUFSIZE);
6621 if (buffer == NULL)
6622 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006623 close(fd_out);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006624 close(fd_in);
6625#ifdef HAVE_ACL
6626 mch_free_acl(acl);
6627#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006628 return -1;
6629 }
6630
6631 while ((n = vim_read(fd_in, buffer, BUFSIZE)) > 0)
6632 if (vim_write(fd_out, buffer, n) != n)
6633 {
6634 errmsg = _("E208: Error writing to \"%s\"");
6635 break;
6636 }
6637
6638 vim_free(buffer);
6639 close(fd_in);
6640 if (close(fd_out) < 0)
6641 errmsg = _("E209: Error closing \"%s\"");
6642 if (n < 0)
6643 {
6644 errmsg = _("E210: Error reading \"%s\"");
6645 to = from;
6646 }
Bram Moolenaar7263a772007-05-10 17:35:54 +00006647#ifndef UNIX /* for Unix mch_open() already set the permission */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006648 mch_setperm(to, perm);
Bram Moolenaarc6039d82005-12-02 00:44:04 +00006649#endif
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006650#ifdef HAVE_ACL
6651 mch_set_acl(to, acl);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006652 mch_free_acl(acl);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006653#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006654 if (errmsg != NULL)
6655 {
6656 EMSG2(errmsg, to);
6657 return -1;
6658 }
6659 mch_remove(from);
6660 return 0;
6661}
6662
6663static int already_warned = FALSE;
6664
6665/*
6666 * Check if any not hidden buffer has been changed.
6667 * Postpone the check if there are characters in the stuff buffer, a global
6668 * command is being executed, a mapping is being executed or an autocommand is
6669 * busy.
6670 * Returns TRUE if some message was written (screen should be redrawn and
6671 * cursor positioned).
6672 */
6673 int
6674check_timestamps(focus)
6675 int focus; /* called for GUI focus event */
6676{
6677 buf_T *buf;
6678 int didit = 0;
6679 int n;
6680
6681 /* Don't check timestamps while system() or another low-level function may
6682 * cause us to lose and gain focus. */
6683 if (no_check_timestamps > 0)
6684 return FALSE;
6685
6686 /* Avoid doing a check twice. The OK/Reload dialog can cause a focus
6687 * event and we would keep on checking if the file is steadily growing.
6688 * Do check again after typing something. */
6689 if (focus && did_check_timestamps)
6690 {
6691 need_check_timestamps = TRUE;
6692 return FALSE;
6693 }
6694
6695 if (!stuff_empty() || global_busy || !typebuf_typed()
6696#ifdef FEAT_AUTOCMD
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006697 || autocmd_busy || curbuf_lock > 0 || allbuf_lock > 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00006698#endif
6699 )
6700 need_check_timestamps = TRUE; /* check later */
6701 else
6702 {
6703 ++no_wait_return;
6704 did_check_timestamps = TRUE;
6705 already_warned = FALSE;
6706 for (buf = firstbuf; buf != NULL; )
6707 {
6708 /* Only check buffers in a window. */
6709 if (buf->b_nwindows > 0)
6710 {
6711 n = buf_check_timestamp(buf, focus);
6712 if (didit < n)
6713 didit = n;
6714 if (n > 0 && !buf_valid(buf))
6715 {
6716 /* Autocommands have removed the buffer, start at the
6717 * first one again. */
6718 buf = firstbuf;
6719 continue;
6720 }
6721 }
6722 buf = buf->b_next;
6723 }
6724 --no_wait_return;
6725 need_check_timestamps = FALSE;
6726 if (need_wait_return && didit == 2)
6727 {
6728 /* make sure msg isn't overwritten */
6729 msg_puts((char_u *)"\n");
6730 out_flush();
6731 }
6732 }
6733 return didit;
6734}
6735
6736/*
6737 * Move all the lines from buffer "frombuf" to buffer "tobuf".
6738 * Return OK or FAIL. When FAIL "tobuf" is incomplete and/or "frombuf" is not
6739 * empty.
6740 */
6741 static int
6742move_lines(frombuf, tobuf)
6743 buf_T *frombuf;
6744 buf_T *tobuf;
6745{
6746 buf_T *tbuf = curbuf;
6747 int retval = OK;
6748 linenr_T lnum;
6749 char_u *p;
6750
6751 /* Copy the lines in "frombuf" to "tobuf". */
6752 curbuf = tobuf;
6753 for (lnum = 1; lnum <= frombuf->b_ml.ml_line_count; ++lnum)
6754 {
6755 p = vim_strsave(ml_get_buf(frombuf, lnum, FALSE));
6756 if (p == NULL || ml_append(lnum - 1, p, 0, FALSE) == FAIL)
6757 {
6758 vim_free(p);
6759 retval = FAIL;
6760 break;
6761 }
6762 vim_free(p);
6763 }
6764
6765 /* Delete all the lines in "frombuf". */
6766 if (retval != FAIL)
6767 {
6768 curbuf = frombuf;
Bram Moolenaar9460b9d2007-01-09 14:37:01 +00006769 for (lnum = curbuf->b_ml.ml_line_count; lnum > 0; --lnum)
6770 if (ml_delete(lnum, FALSE) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006771 {
6772 /* Oops! We could try putting back the saved lines, but that
6773 * might fail again... */
6774 retval = FAIL;
6775 break;
6776 }
6777 }
6778
6779 curbuf = tbuf;
6780 return retval;
6781}
6782
6783/*
6784 * Check if buffer "buf" has been changed.
6785 * Also check if the file for a new buffer unexpectedly appeared.
6786 * return 1 if a changed buffer was found.
6787 * return 2 if a message has been displayed.
6788 * return 0 otherwise.
6789 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006790 int
6791buf_check_timestamp(buf, focus)
6792 buf_T *buf;
Bram Moolenaar78a15312009-05-15 19:33:18 +00006793 int focus UNUSED; /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006794{
6795 struct stat st;
6796 int stat_res;
6797 int retval = 0;
6798 char_u *path;
6799 char_u *tbuf;
6800 char *mesg = NULL;
Bram Moolenaar44ecf652005-03-07 23:09:59 +00006801 char *mesg2 = "";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006802 int helpmesg = FALSE;
6803 int reload = FALSE;
6804#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6805 int can_reload = FALSE;
6806#endif
Bram Moolenaar914703b2010-05-31 21:59:46 +02006807 off_t orig_size = buf->b_orig_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006808 int orig_mode = buf->b_orig_mode;
6809#ifdef FEAT_GUI
6810 int save_mouse_correct = need_mouse_correct;
6811#endif
6812#ifdef FEAT_AUTOCMD
6813 static int busy = FALSE;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006814 int n;
6815 char_u *s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006816#endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006817 char *reason;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006818
6819 /* If there is no file name, the buffer is not loaded, 'buftype' is
6820 * set, we are in the middle of a save or being called recursively: ignore
6821 * this buffer. */
6822 if (buf->b_ffname == NULL
6823 || buf->b_ml.ml_mfp == NULL
6824#if defined(FEAT_QUICKFIX)
6825 || *buf->b_p_bt != NUL
6826#endif
6827 || buf->b_saving
6828#ifdef FEAT_AUTOCMD
6829 || busy
6830#endif
Bram Moolenaar009b2592004-10-24 19:18:58 +00006831#ifdef FEAT_NETBEANS_INTG
6832 || isNetbeansBuffer(buf)
6833#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006834 )
6835 return 0;
6836
6837 if ( !(buf->b_flags & BF_NOTEDITED)
6838 && buf->b_mtime != 0
6839 && ((stat_res = mch_stat((char *)buf->b_ffname, &st)) < 0
6840 || time_differs((long)st.st_mtime, buf->b_mtime)
6841#ifdef HAVE_ST_MODE
6842 || (int)st.st_mode != buf->b_orig_mode
6843#else
6844 || mch_getperm(buf->b_ffname) != buf->b_orig_mode
6845#endif
6846 ))
6847 {
6848 retval = 1;
6849
Bram Moolenaar316059c2006-01-14 21:18:42 +00006850 /* set b_mtime to stop further warnings (e.g., when executing
6851 * FileChangedShell autocmd) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006852 if (stat_res < 0)
6853 {
6854 buf->b_mtime = 0;
6855 buf->b_orig_size = 0;
6856 buf->b_orig_mode = 0;
6857 }
6858 else
6859 buf_store_time(buf, &st, buf->b_ffname);
6860
6861 /* Don't do anything for a directory. Might contain the file
6862 * explorer. */
6863 if (mch_isdir(buf->b_fname))
6864 ;
6865
6866 /*
6867 * If 'autoread' is set, the buffer has no changes and the file still
6868 * exists, reload the buffer. Use the buffer-local option value if it
6869 * was set, the global option value otherwise.
6870 */
6871 else if ((buf->b_p_ar >= 0 ? buf->b_p_ar : p_ar)
6872 && !bufIsChanged(buf) && stat_res >= 0)
6873 reload = TRUE;
6874 else
6875 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006876 if (stat_res < 0)
6877 reason = "deleted";
6878 else if (bufIsChanged(buf))
6879 reason = "conflict";
6880 else if (orig_size != buf->b_orig_size || buf_contents_changed(buf))
6881 reason = "changed";
6882 else if (orig_mode != buf->b_orig_mode)
6883 reason = "mode";
6884 else
6885 reason = "time";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006886
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006887#ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006888 /*
6889 * Only give the warning if there are no FileChangedShell
6890 * autocommands.
6891 * Avoid being called recursively by setting "busy".
6892 */
6893 busy = TRUE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00006894# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006895 set_vim_var_string(VV_FCS_REASON, (char_u *)reason, -1);
6896 set_vim_var_string(VV_FCS_CHOICE, (char_u *)"", -1);
Bram Moolenaar1e015462005-09-25 22:16:38 +00006897# endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006898 ++allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006899 n = apply_autocmds(EVENT_FILECHANGEDSHELL,
6900 buf->b_fname, buf->b_fname, FALSE, buf);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006901 --allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006902 busy = FALSE;
6903 if (n)
6904 {
6905 if (!buf_valid(buf))
6906 EMSG(_("E246: FileChangedShell autocommand deleted buffer"));
Bram Moolenaar1e015462005-09-25 22:16:38 +00006907# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006908 s = get_vim_var_str(VV_FCS_CHOICE);
6909 if (STRCMP(s, "reload") == 0 && *reason != 'd')
6910 reload = TRUE;
6911 else if (STRCMP(s, "ask") == 0)
6912 n = FALSE;
6913 else
Bram Moolenaar1e015462005-09-25 22:16:38 +00006914# endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006915 return 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006916 }
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006917 if (!n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006918#endif
6919 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006920 if (*reason == 'd')
6921 mesg = _("E211: File \"%s\" no longer available");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006922 else
6923 {
6924 helpmesg = TRUE;
6925#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6926 can_reload = TRUE;
6927#endif
6928 /*
6929 * Check if the file contents really changed to avoid
6930 * giving a warning when only the timestamp was set (e.g.,
6931 * checked out of CVS). Always warn when the buffer was
6932 * changed.
6933 */
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006934 if (reason[2] == 'n')
6935 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006936 mesg = _("W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006937 mesg2 = _("See \":help W12\" for more info.");
6938 }
6939 else if (reason[1] == 'h')
6940 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006941 mesg = _("W11: Warning: File \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006942 mesg2 = _("See \":help W11\" for more info.");
6943 }
6944 else if (*reason == 'm')
6945 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006946 mesg = _("W16: Warning: Mode of file \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006947 mesg2 = _("See \":help W16\" for more info.");
6948 }
Bram Moolenaar85388b52009-06-24 09:58:32 +00006949 else
6950 /* Only timestamp changed, store it to avoid a warning
6951 * in check_mtime() later. */
6952 buf->b_mtime_read = buf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006953 }
6954 }
6955 }
6956
6957 }
6958 else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W)
6959 && vim_fexists(buf->b_ffname))
6960 {
6961 retval = 1;
6962 mesg = _("W13: Warning: File \"%s\" has been created after editing started");
6963 buf->b_flags |= BF_NEW_W;
6964#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6965 can_reload = TRUE;
6966#endif
6967 }
6968
6969 if (mesg != NULL)
6970 {
6971 path = home_replace_save(buf, buf->b_fname);
6972 if (path != NULL)
6973 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006974 if (!helpmesg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006975 mesg2 = "";
6976 tbuf = alloc((unsigned)(STRLEN(path) + STRLEN(mesg)
6977 + STRLEN(mesg2) + 2));
6978 sprintf((char *)tbuf, mesg, path);
Bram Moolenaar496c5262009-03-18 14:42:00 +00006979#ifdef FEAT_EVAL
6980 /* Set warningmsg here, before the unimportant and output-specific
6981 * mesg2 has been appended. */
6982 set_vim_var_string(VV_WARNINGMSG, tbuf, -1);
6983#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006984#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6985 if (can_reload)
6986 {
6987 if (*mesg2 != NUL)
6988 {
6989 STRCAT(tbuf, "\n");
6990 STRCAT(tbuf, mesg2);
6991 }
6992 if (do_dialog(VIM_WARNING, (char_u *)_("Warning"), tbuf,
6993 (char_u *)_("&OK\n&Load File"), 1, NULL) == 2)
6994 reload = TRUE;
6995 }
6996 else
6997#endif
6998 if (State > NORMAL_BUSY || (State & CMDLINE) || already_warned)
6999 {
7000 if (*mesg2 != NUL)
7001 {
7002 STRCAT(tbuf, "; ");
7003 STRCAT(tbuf, mesg2);
7004 }
7005 EMSG(tbuf);
7006 retval = 2;
7007 }
7008 else
7009 {
Bram Moolenaared203462004-06-16 11:19:22 +00007010# ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00007011 if (!autocmd_busy)
Bram Moolenaared203462004-06-16 11:19:22 +00007012# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007013 {
7014 msg_start();
7015 msg_puts_attr(tbuf, hl_attr(HLF_E) + MSG_HIST);
7016 if (*mesg2 != NUL)
7017 msg_puts_attr((char_u *)mesg2,
7018 hl_attr(HLF_W) + MSG_HIST);
7019 msg_clr_eos();
7020 (void)msg_end();
7021 if (emsg_silent == 0)
7022 {
7023 out_flush();
Bram Moolenaared203462004-06-16 11:19:22 +00007024# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00007025 if (!focus)
Bram Moolenaared203462004-06-16 11:19:22 +00007026# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007027 /* give the user some time to think about it */
7028 ui_delay(1000L, TRUE);
7029
7030 /* don't redraw and erase the message */
7031 redraw_cmdline = FALSE;
7032 }
7033 }
7034 already_warned = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007035 }
7036
7037 vim_free(path);
7038 vim_free(tbuf);
7039 }
7040 }
7041
7042 if (reload)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007043 /* Reload the buffer. */
Bram Moolenaar316059c2006-01-14 21:18:42 +00007044 buf_reload(buf, orig_mode);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007045
Bram Moolenaar56718732006-03-15 22:53:57 +00007046#ifdef FEAT_AUTOCMD
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00007047 /* Trigger FileChangedShell when the file was changed in any way. */
7048 if (buf_valid(buf) && retval != 0)
Bram Moolenaar56718732006-03-15 22:53:57 +00007049 (void)apply_autocmds(EVENT_FILECHANGEDSHELLPOST,
7050 buf->b_fname, buf->b_fname, FALSE, buf);
7051#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007052#ifdef FEAT_GUI
7053 /* restore this in case an autocommand has set it; it would break
7054 * 'mousefocus' */
7055 need_mouse_correct = save_mouse_correct;
7056#endif
7057
7058 return retval;
7059}
7060
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007061/*
7062 * Reload a buffer that is already loaded.
7063 * Used when the file was changed outside of Vim.
Bram Moolenaar316059c2006-01-14 21:18:42 +00007064 * "orig_mode" is buf->b_orig_mode before the need for reloading was detected.
7065 * buf->b_orig_mode may have been reset already.
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007066 */
7067 void
Bram Moolenaar316059c2006-01-14 21:18:42 +00007068buf_reload(buf, orig_mode)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007069 buf_T *buf;
Bram Moolenaar316059c2006-01-14 21:18:42 +00007070 int orig_mode;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007071{
7072 exarg_T ea;
7073 pos_T old_cursor;
7074 linenr_T old_topline;
7075 int old_ro = buf->b_p_ro;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007076 buf_T *savebuf;
7077 int saved = OK;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007078 aco_save_T aco;
7079
7080 /* set curwin/curbuf for "buf" and save some things */
7081 aucmd_prepbuf(&aco, buf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007082
7083 /* We only want to read the text from the file, not reset the syntax
7084 * highlighting, clear marks, diff status, etc. Force the fileformat
7085 * and encoding to be the same. */
7086 if (prep_exarg(&ea, buf) == OK)
7087 {
7088 old_cursor = curwin->w_cursor;
7089 old_topline = curwin->w_topline;
7090
7091 /*
7092 * To behave like when a new file is edited (matters for
7093 * BufReadPost autocommands) we first need to delete the current
7094 * buffer contents. But if reading the file fails we should keep
7095 * the old contents. Can't use memory only, the file might be
7096 * too big. Use a hidden buffer to move the buffer contents to.
7097 */
7098 if (bufempty())
7099 savebuf = NULL;
7100 else
7101 {
7102 /* Allocate a buffer without putting it in the buffer list. */
7103 savebuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007104 if (savebuf != NULL && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007105 {
7106 /* Open the memline. */
7107 curbuf = savebuf;
7108 curwin->w_buffer = savebuf;
Bram Moolenaar4770d092006-01-12 23:22:24 +00007109 saved = ml_open(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007110 curbuf = buf;
7111 curwin->w_buffer = buf;
7112 }
Bram Moolenaar8424a622006-04-19 21:23:36 +00007113 if (savebuf == NULL || saved == FAIL || buf != curbuf
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007114 || move_lines(buf, savebuf) == FAIL)
7115 {
7116 EMSG2(_("E462: Could not prepare for reloading \"%s\""),
7117 buf->b_fname);
7118 saved = FAIL;
7119 }
7120 }
7121
7122 if (saved == OK)
7123 {
7124 curbuf->b_flags |= BF_CHECK_RO; /* check for RO again */
7125#ifdef FEAT_AUTOCMD
7126 keep_filetype = TRUE; /* don't detect 'filetype' */
7127#endif
7128 if (readfile(buf->b_ffname, buf->b_fname, (linenr_T)0,
7129 (linenr_T)0,
7130 (linenr_T)MAXLNUM, &ea, READ_NEW) == FAIL)
7131 {
7132#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
7133 if (!aborting())
7134#endif
7135 EMSG2(_("E321: Could not reload \"%s\""), buf->b_fname);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007136 if (savebuf != NULL && buf_valid(savebuf) && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007137 {
7138 /* Put the text back from the save buffer. First
7139 * delete any lines that readfile() added. */
7140 while (!bufempty())
Bram Moolenaar8424a622006-04-19 21:23:36 +00007141 if (ml_delete(buf->b_ml.ml_line_count, FALSE) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007142 break;
7143 (void)move_lines(savebuf, buf);
7144 }
7145 }
Bram Moolenaar8424a622006-04-19 21:23:36 +00007146 else if (buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007147 {
7148 /* Mark the buffer as unmodified and free undo info. */
7149 unchanged(buf, TRUE);
7150 u_blockfree(buf);
7151 u_clearall(buf);
7152 }
7153 }
7154 vim_free(ea.cmd);
7155
Bram Moolenaar8424a622006-04-19 21:23:36 +00007156 if (savebuf != NULL && buf_valid(savebuf))
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007157 wipe_buffer(savebuf, FALSE);
7158
7159#ifdef FEAT_DIFF
7160 /* Invalidate diff info if necessary. */
Bram Moolenaar8424a622006-04-19 21:23:36 +00007161 diff_invalidate(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007162#endif
7163
7164 /* Restore the topline and cursor position and check it (lines may
7165 * have been removed). */
7166 if (old_topline > curbuf->b_ml.ml_line_count)
7167 curwin->w_topline = curbuf->b_ml.ml_line_count;
7168 else
7169 curwin->w_topline = old_topline;
7170 curwin->w_cursor = old_cursor;
7171 check_cursor();
7172 update_topline();
7173#ifdef FEAT_AUTOCMD
7174 keep_filetype = FALSE;
7175#endif
7176#ifdef FEAT_FOLDING
7177 {
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007178 win_T *wp;
7179 tabpage_T *tp;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007180
7181 /* Update folds unless they are defined manually. */
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007182 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007183 if (wp->w_buffer == curwin->w_buffer
7184 && !foldmethodIsManual(wp))
7185 foldUpdateAll(wp);
7186 }
7187#endif
7188 /* If the mode didn't change and 'readonly' was set, keep the old
7189 * value; the user probably used the ":view" command. But don't
7190 * reset it, might have had a read error. */
7191 if (orig_mode == curbuf->b_orig_mode)
7192 curbuf->b_p_ro |= old_ro;
7193 }
7194
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007195 /* restore curwin/curbuf and a few other things */
7196 aucmd_restbuf(&aco);
7197 /* Careful: autocommands may have made "buf" invalid! */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007198}
7199
Bram Moolenaar071d4272004-06-13 20:20:40 +00007200 void
7201buf_store_time(buf, st, fname)
7202 buf_T *buf;
7203 struct stat *st;
Bram Moolenaar78a15312009-05-15 19:33:18 +00007204 char_u *fname UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007205{
7206 buf->b_mtime = (long)st->st_mtime;
Bram Moolenaar914703b2010-05-31 21:59:46 +02007207 buf->b_orig_size = st->st_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007208#ifdef HAVE_ST_MODE
7209 buf->b_orig_mode = (int)st->st_mode;
7210#else
7211 buf->b_orig_mode = mch_getperm(fname);
7212#endif
7213}
7214
7215/*
7216 * Adjust the line with missing eol, used for the next write.
7217 * Used for do_filter(), when the input lines for the filter are deleted.
7218 */
7219 void
7220write_lnum_adjust(offset)
7221 linenr_T offset;
7222{
Bram Moolenaardf177f62005-02-22 08:39:57 +00007223 if (write_no_eol_lnum != 0) /* only if there is a missing eol */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007224 write_no_eol_lnum += offset;
7225}
7226
7227#if defined(TEMPDIRNAMES) || defined(PROTO)
7228static long temp_count = 0; /* Temp filename counter. */
7229
7230/*
7231 * Delete the temp directory and all files it contains.
7232 */
7233 void
7234vim_deltempdir()
7235{
7236 char_u **files;
7237 int file_count;
7238 int i;
7239
7240 if (vim_tempdir != NULL)
7241 {
7242 sprintf((char *)NameBuff, "%s*", vim_tempdir);
7243 if (gen_expand_wildcards(1, &NameBuff, &file_count, &files,
7244 EW_DIR|EW_FILE|EW_SILENT) == OK)
7245 {
7246 for (i = 0; i < file_count; ++i)
7247 mch_remove(files[i]);
7248 FreeWild(file_count, files);
7249 }
7250 gettail(NameBuff)[-1] = NUL;
7251 (void)mch_rmdir(NameBuff);
7252
7253 vim_free(vim_tempdir);
7254 vim_tempdir = NULL;
7255 }
7256}
7257#endif
7258
Bram Moolenaar4592dee2009-11-18 19:11:58 +00007259#ifdef TEMPDIRNAMES
Bram Moolenaar071d4272004-06-13 20:20:40 +00007260/*
Bram Moolenaareaf03392009-11-17 11:08:52 +00007261 * Directory "tempdir" was created. Expand this name to a full path and put
7262 * it in "vim_tempdir". This avoids that using ":cd" would confuse us.
7263 * "tempdir" must be no longer than MAXPATHL.
7264 */
7265 static void
7266vim_settempdir(tempdir)
7267 char_u *tempdir;
7268{
7269 char_u *buf;
7270
7271 buf = alloc((unsigned)MAXPATHL + 2);
7272 if (buf != NULL)
7273 {
7274 if (vim_FullName(tempdir, buf, MAXPATHL, FALSE) == FAIL)
7275 STRCPY(buf, tempdir);
7276# ifdef __EMX__
7277 if (vim_strchr(buf, '/') != NULL)
7278 STRCAT(buf, "/");
7279 else
7280# endif
7281 add_pathsep(buf);
7282 vim_tempdir = vim_strsave(buf);
7283 vim_free(buf);
7284 }
7285}
Bram Moolenaar4592dee2009-11-18 19:11:58 +00007286#endif
Bram Moolenaareaf03392009-11-17 11:08:52 +00007287
7288/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007289 * vim_tempname(): Return a unique name that can be used for a temp file.
7290 *
7291 * The temp file is NOT created.
7292 *
7293 * The returned pointer is to allocated memory.
7294 * The returned pointer is NULL if no valid name was found.
7295 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007296 char_u *
7297vim_tempname(extra_char)
Bram Moolenaar78a15312009-05-15 19:33:18 +00007298 int extra_char UNUSED; /* char to use in the name instead of '?' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007299{
7300#ifdef USE_TMPNAM
7301 char_u itmp[L_tmpnam]; /* use tmpnam() */
7302#else
7303 char_u itmp[TEMPNAMELEN];
7304#endif
7305
7306#ifdef TEMPDIRNAMES
7307 static char *(tempdirs[]) = {TEMPDIRNAMES};
7308 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007309# ifndef EEXIST
7310 struct stat st;
7311# endif
7312
7313 /*
7314 * This will create a directory for private use by this instance of Vim.
7315 * This is done once, and the same directory is used for all temp files.
7316 * This method avoids security problems because of symlink attacks et al.
7317 * It's also a bit faster, because we only need to check for an existing
7318 * file when creating the directory and not for each temp file.
7319 */
7320 if (vim_tempdir == NULL)
7321 {
7322 /*
7323 * Try the entries in TEMPDIRNAMES to create the temp directory.
7324 */
Bram Moolenaar78a15312009-05-15 19:33:18 +00007325 for (i = 0; i < (int)(sizeof(tempdirs) / sizeof(char *)); ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007326 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007327# ifndef HAVE_MKDTEMP
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007328 size_t itmplen;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007329 long nr;
7330 long off;
7331# endif
7332
Bram Moolenaar071d4272004-06-13 20:20:40 +00007333 /* expand $TMP, leave room for "/v1100000/999999999" */
7334 expand_env((char_u *)tempdirs[i], itmp, TEMPNAMELEN - 20);
7335 if (mch_isdir(itmp)) /* directory exists */
7336 {
7337# ifdef __EMX__
7338 /* If $TMP contains a forward slash (perhaps using bash or
7339 * tcsh), don't add a backslash, use a forward slash!
7340 * Adding 2 backslashes didn't work. */
7341 if (vim_strchr(itmp, '/') != NULL)
7342 STRCAT(itmp, "/");
7343 else
7344# endif
7345 add_pathsep(itmp);
7346
Bram Moolenaareaf03392009-11-17 11:08:52 +00007347# ifdef HAVE_MKDTEMP
7348 /* Leave room for filename */
7349 STRCAT(itmp, "vXXXXXX");
7350 if (mkdtemp((char *)itmp) != NULL)
7351 vim_settempdir(itmp);
7352# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007353 /* Get an arbitrary number of up to 6 digits. When it's
7354 * unlikely that it already exists it will be faster,
7355 * otherwise it doesn't matter. The use of mkdir() avoids any
7356 * security problems because of the predictable number. */
7357 nr = (mch_get_pid() + (long)time(NULL)) % 1000000L;
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007358 itmplen = STRLEN(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007359
7360 /* Try up to 10000 different values until we find a name that
7361 * doesn't exist. */
7362 for (off = 0; off < 10000L; ++off)
7363 {
7364 int r;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007365# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007366 mode_t umask_save;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007367# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007368
Bram Moolenaareaf03392009-11-17 11:08:52 +00007369 sprintf((char *)itmp + itmplen, "v%ld", nr + off);
7370# ifndef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007371 /* If mkdir() does not set errno to EEXIST, check for
7372 * existing file here. There is a race condition then,
7373 * although it's fail-safe. */
7374 if (mch_stat((char *)itmp, &st) >= 0)
7375 continue;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007376# endif
7377# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007378 /* Make sure the umask doesn't remove the executable bit.
7379 * "repl" has been reported to use "177". */
7380 umask_save = umask(077);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007381# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007382 r = vim_mkdir(itmp, 0700);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007383# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007384 (void)umask(umask_save);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007385# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007386 if (r == 0)
7387 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007388 vim_settempdir(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007389 break;
7390 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007391# ifdef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007392 /* If the mkdir() didn't fail because the file/dir exists,
7393 * we probably can't create any dir here, try another
7394 * place. */
7395 if (errno != EEXIST)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007396# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007397 break;
7398 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007399# endif /* HAVE_MKDTEMP */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007400 if (vim_tempdir != NULL)
7401 break;
7402 }
7403 }
7404 }
7405
7406 if (vim_tempdir != NULL)
7407 {
7408 /* There is no need to check if the file exists, because we own the
7409 * directory and nobody else creates a file in it. */
7410 sprintf((char *)itmp, "%s%ld", vim_tempdir, temp_count++);
7411 return vim_strsave(itmp);
7412 }
7413
7414 return NULL;
7415
7416#else /* TEMPDIRNAMES */
7417
7418# ifdef WIN3264
7419 char szTempFile[_MAX_PATH + 1];
7420 char buf4[4];
7421 char_u *retval;
7422 char_u *p;
7423
7424 STRCPY(itmp, "");
7425 if (GetTempPath(_MAX_PATH, szTempFile) == 0)
7426 szTempFile[0] = NUL; /* GetTempPath() failed, use current dir */
7427 strcpy(buf4, "VIM");
7428 buf4[2] = extra_char; /* make it "VIa", "VIb", etc. */
7429 if (GetTempFileName(szTempFile, buf4, 0, itmp) == 0)
7430 return NULL;
7431 /* GetTempFileName() will create the file, we don't want that */
7432 (void)DeleteFile(itmp);
7433
7434 /* Backslashes in a temp file name cause problems when filtering with
7435 * "sh". NOTE: This also checks 'shellcmdflag' to help those people who
7436 * didn't set 'shellslash'. */
7437 retval = vim_strsave(itmp);
7438 if (*p_shcf == '-' || p_ssl)
7439 for (p = retval; *p; ++p)
7440 if (*p == '\\')
7441 *p = '/';
7442 return retval;
7443
7444# else /* WIN3264 */
7445
7446# ifdef USE_TMPNAM
7447 /* tmpnam() will make its own name */
7448 if (*tmpnam((char *)itmp) == NUL)
7449 return NULL;
7450# else
7451 char_u *p;
7452
7453# ifdef VMS_TEMPNAM
7454 /* mktemp() is not working on VMS. It seems to be
7455 * a do-nothing function. Therefore we use tempnam().
7456 */
7457 sprintf((char *)itmp, "VIM%c", extra_char);
7458 p = (char_u *)tempnam("tmp:", (char *)itmp);
7459 if (p != NULL)
7460 {
7461 /* VMS will use '.LOG' if we don't explicitly specify an extension,
7462 * and VIM will then be unable to find the file later */
7463 STRCPY(itmp, p);
7464 STRCAT(itmp, ".txt");
7465 free(p);
7466 }
7467 else
7468 return NULL;
7469# else
7470 STRCPY(itmp, TEMPNAME);
7471 if ((p = vim_strchr(itmp, '?')) != NULL)
7472 *p = extra_char;
7473 if (mktemp((char *)itmp) == NULL)
7474 return NULL;
7475# endif
7476# endif
7477
7478 return vim_strsave(itmp);
7479# endif /* WIN3264 */
7480#endif /* TEMPDIRNAMES */
7481}
7482
7483#if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
7484/*
7485 * Convert all backslashes in fname to forward slashes in-place.
7486 */
7487 void
7488forward_slash(fname)
7489 char_u *fname;
7490{
7491 char_u *p;
7492
7493 for (p = fname; *p != NUL; ++p)
7494# ifdef FEAT_MBYTE
7495 /* The Big5 encoding can have '\' in the trail byte. */
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00007496 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007497 ++p;
7498 else
7499# endif
7500 if (*p == '\\')
7501 *p = '/';
7502}
7503#endif
7504
7505
7506/*
7507 * Code for automatic commands.
7508 *
7509 * Only included when "FEAT_AUTOCMD" has been defined.
7510 */
7511
7512#if defined(FEAT_AUTOCMD) || defined(PROTO)
7513
7514/*
7515 * The autocommands are stored in a list for each event.
7516 * Autocommands for the same pattern, that are consecutive, are joined
7517 * together, to avoid having to match the pattern too often.
7518 * The result is an array of Autopat lists, which point to AutoCmd lists:
7519 *
7520 * first_autopat[0] --> Autopat.next --> Autopat.next --> NULL
7521 * Autopat.cmds Autopat.cmds
7522 * | |
7523 * V V
7524 * AutoCmd.next AutoCmd.next
7525 * | |
7526 * V V
7527 * AutoCmd.next NULL
7528 * |
7529 * V
7530 * NULL
7531 *
7532 * first_autopat[1] --> Autopat.next --> NULL
7533 * Autopat.cmds
7534 * |
7535 * V
7536 * AutoCmd.next
7537 * |
7538 * V
7539 * NULL
7540 * etc.
7541 *
7542 * The order of AutoCmds is important, this is the order in which they were
7543 * defined and will have to be executed.
7544 */
7545typedef struct AutoCmd
7546{
7547 char_u *cmd; /* The command to be executed (NULL
7548 when command has been removed) */
7549 char nested; /* If autocommands nest here */
7550 char last; /* last command in list */
7551#ifdef FEAT_EVAL
7552 scid_T scriptID; /* script ID where defined */
7553#endif
7554 struct AutoCmd *next; /* Next AutoCmd in list */
7555} AutoCmd;
7556
7557typedef struct AutoPat
7558{
7559 int group; /* group ID */
7560 char_u *pat; /* pattern as typed (NULL when pattern
7561 has been removed) */
7562 int patlen; /* strlen() of pat */
Bram Moolenaar748bf032005-02-02 23:04:36 +00007563 regprog_T *reg_prog; /* compiled regprog for pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007564 char allow_dirs; /* Pattern may match whole path */
7565 char last; /* last pattern for apply_autocmds() */
7566 AutoCmd *cmds; /* list of commands to do */
7567 struct AutoPat *next; /* next AutoPat in AutoPat list */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007568 int buflocal_nr; /* !=0 for buffer-local AutoPat */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007569} AutoPat;
7570
7571static struct event_name
7572{
7573 char *name; /* event name */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007574 event_T event; /* event number */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007575} event_names[] =
7576{
7577 {"BufAdd", EVENT_BUFADD},
7578 {"BufCreate", EVENT_BUFADD},
7579 {"BufDelete", EVENT_BUFDELETE},
7580 {"BufEnter", EVENT_BUFENTER},
7581 {"BufFilePost", EVENT_BUFFILEPOST},
7582 {"BufFilePre", EVENT_BUFFILEPRE},
7583 {"BufHidden", EVENT_BUFHIDDEN},
7584 {"BufLeave", EVENT_BUFLEAVE},
7585 {"BufNew", EVENT_BUFNEW},
7586 {"BufNewFile", EVENT_BUFNEWFILE},
7587 {"BufRead", EVENT_BUFREADPOST},
7588 {"BufReadCmd", EVENT_BUFREADCMD},
7589 {"BufReadPost", EVENT_BUFREADPOST},
7590 {"BufReadPre", EVENT_BUFREADPRE},
7591 {"BufUnload", EVENT_BUFUNLOAD},
7592 {"BufWinEnter", EVENT_BUFWINENTER},
7593 {"BufWinLeave", EVENT_BUFWINLEAVE},
7594 {"BufWipeout", EVENT_BUFWIPEOUT},
7595 {"BufWrite", EVENT_BUFWRITEPRE},
7596 {"BufWritePost", EVENT_BUFWRITEPOST},
7597 {"BufWritePre", EVENT_BUFWRITEPRE},
7598 {"BufWriteCmd", EVENT_BUFWRITECMD},
7599 {"CmdwinEnter", EVENT_CMDWINENTER},
7600 {"CmdwinLeave", EVENT_CMDWINLEAVE},
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007601 {"ColorScheme", EVENT_COLORSCHEME},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007602 {"CursorHold", EVENT_CURSORHOLD},
7603 {"CursorHoldI", EVENT_CURSORHOLDI},
7604 {"CursorMoved", EVENT_CURSORMOVED},
7605 {"CursorMovedI", EVENT_CURSORMOVEDI},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007606 {"EncodingChanged", EVENT_ENCODINGCHANGED},
7607 {"FileEncoding", EVENT_ENCODINGCHANGED},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007608 {"FileAppendPost", EVENT_FILEAPPENDPOST},
7609 {"FileAppendPre", EVENT_FILEAPPENDPRE},
7610 {"FileAppendCmd", EVENT_FILEAPPENDCMD},
7611 {"FileChangedShell",EVENT_FILECHANGEDSHELL},
Bram Moolenaar56718732006-03-15 22:53:57 +00007612 {"FileChangedShellPost",EVENT_FILECHANGEDSHELLPOST},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007613 {"FileChangedRO", EVENT_FILECHANGEDRO},
7614 {"FileReadPost", EVENT_FILEREADPOST},
7615 {"FileReadPre", EVENT_FILEREADPRE},
7616 {"FileReadCmd", EVENT_FILEREADCMD},
7617 {"FileType", EVENT_FILETYPE},
7618 {"FileWritePost", EVENT_FILEWRITEPOST},
7619 {"FileWritePre", EVENT_FILEWRITEPRE},
7620 {"FileWriteCmd", EVENT_FILEWRITECMD},
7621 {"FilterReadPost", EVENT_FILTERREADPOST},
7622 {"FilterReadPre", EVENT_FILTERREADPRE},
7623 {"FilterWritePost", EVENT_FILTERWRITEPOST},
7624 {"FilterWritePre", EVENT_FILTERWRITEPRE},
7625 {"FocusGained", EVENT_FOCUSGAINED},
7626 {"FocusLost", EVENT_FOCUSLOST},
7627 {"FuncUndefined", EVENT_FUNCUNDEFINED},
7628 {"GUIEnter", EVENT_GUIENTER},
Bram Moolenaar265e5072006-08-29 16:13:22 +00007629 {"GUIFailed", EVENT_GUIFAILED},
Bram Moolenaar843ee412004-06-30 16:16:41 +00007630 {"InsertChange", EVENT_INSERTCHANGE},
7631 {"InsertEnter", EVENT_INSERTENTER},
7632 {"InsertLeave", EVENT_INSERTLEAVE},
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00007633 {"MenuPopup", EVENT_MENUPOPUP},
Bram Moolenaar7c626922005-02-07 22:01:03 +00007634 {"QuickFixCmdPost", EVENT_QUICKFIXCMDPOST},
7635 {"QuickFixCmdPre", EVENT_QUICKFIXCMDPRE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007636 {"RemoteReply", EVENT_REMOTEREPLY},
Bram Moolenaar9372a112005-12-06 19:59:18 +00007637 {"SessionLoadPost", EVENT_SESSIONLOADPOST},
Bram Moolenaar5c4bab02006-03-10 21:37:46 +00007638 {"ShellCmdPost", EVENT_SHELLCMDPOST},
7639 {"ShellFilterPost", EVENT_SHELLFILTERPOST},
Bram Moolenaara2031822006-03-07 22:29:51 +00007640 {"SourcePre", EVENT_SOURCEPRE},
Bram Moolenaar8dd1aa52007-01-16 20:33:19 +00007641 {"SourceCmd", EVENT_SOURCECMD},
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00007642 {"SpellFileMissing",EVENT_SPELLFILEMISSING},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007643 {"StdinReadPost", EVENT_STDINREADPOST},
7644 {"StdinReadPre", EVENT_STDINREADPRE},
Bram Moolenaarb815dac2005-12-07 20:59:24 +00007645 {"SwapExists", EVENT_SWAPEXISTS},
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00007646 {"Syntax", EVENT_SYNTAX},
Bram Moolenaar70836c82006-02-20 21:28:49 +00007647 {"TabEnter", EVENT_TABENTER},
7648 {"TabLeave", EVENT_TABLEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007649 {"TermChanged", EVENT_TERMCHANGED},
7650 {"TermResponse", EVENT_TERMRESPONSE},
7651 {"User", EVENT_USER},
7652 {"VimEnter", EVENT_VIMENTER},
7653 {"VimLeave", EVENT_VIMLEAVE},
7654 {"VimLeavePre", EVENT_VIMLEAVEPRE},
7655 {"WinEnter", EVENT_WINENTER},
7656 {"WinLeave", EVENT_WINLEAVE},
Bram Moolenaar56718732006-03-15 22:53:57 +00007657 {"VimResized", EVENT_VIMRESIZED},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007658 {NULL, (event_T)0}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007659};
7660
7661static AutoPat *first_autopat[NUM_EVENTS] =
7662{
7663 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7664 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7665 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7666 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00007667 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7668 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007669};
7670
7671/*
7672 * struct used to keep status while executing autocommands for an event.
7673 */
7674typedef struct AutoPatCmd
7675{
7676 AutoPat *curpat; /* next AutoPat to examine */
7677 AutoCmd *nextcmd; /* next AutoCmd to execute */
7678 int group; /* group being used */
7679 char_u *fname; /* fname to match with */
7680 char_u *sfname; /* sfname to match with */
7681 char_u *tail; /* tail of fname */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007682 event_T event; /* current event */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007683 int arg_bufnr; /* initially equal to <abuf>, set to zero when
7684 buf is deleted */
7685 struct AutoPatCmd *next; /* chain of active apc-s for auto-invalidation*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00007686} AutoPatCmd;
7687
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007688static AutoPatCmd *active_apc_list = NULL; /* stack of active autocommands */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007689
Bram Moolenaar071d4272004-06-13 20:20:40 +00007690/*
7691 * augroups stores a list of autocmd group names.
7692 */
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007693static garray_T augroups = {0, 0, sizeof(char_u *), 10, NULL};
Bram Moolenaar071d4272004-06-13 20:20:40 +00007694#define AUGROUP_NAME(i) (((char_u **)augroups.ga_data)[i])
7695
7696/*
7697 * The ID of the current group. Group 0 is the default one.
7698 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007699static int current_augroup = AUGROUP_DEFAULT;
7700
7701static int au_need_clean = FALSE; /* need to delete marked patterns */
7702
Bram Moolenaar754b5602006-02-09 23:53:20 +00007703static void show_autocmd __ARGS((AutoPat *ap, event_T event));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007704static void au_remove_pat __ARGS((AutoPat *ap));
7705static void au_remove_cmds __ARGS((AutoPat *ap));
7706static void au_cleanup __ARGS((void));
7707static int au_new_group __ARGS((char_u *name));
7708static void au_del_group __ARGS((char_u *name));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007709static event_T event_name2nr __ARGS((char_u *start, char_u **end));
7710static char_u *event_nr2name __ARGS((event_T event));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007711static char_u *find_end_event __ARGS((char_u *arg, int have_group));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007712static int event_ignored __ARGS((event_T event));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007713static int au_get_grouparg __ARGS((char_u **argp));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007714static 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 +00007715static char_u *getnextac __ARGS((int c, void *cookie, int indent));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007716static 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 +00007717static void auto_next_pat __ARGS((AutoPatCmd *apc, int stop_at_last));
7718
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007719
Bram Moolenaar754b5602006-02-09 23:53:20 +00007720static event_T last_event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007721static int last_group;
Bram Moolenaar78ab3312007-09-29 12:16:41 +00007722static int autocmd_blocked = 0; /* block all autocmds */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007723
7724/*
7725 * Show the autocommands for one AutoPat.
7726 */
7727 static void
7728show_autocmd(ap, event)
7729 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007730 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007731{
7732 AutoCmd *ac;
7733
7734 /* Check for "got_int" (here and at various places below), which is set
7735 * when "q" has been hit for the "--more--" prompt */
7736 if (got_int)
7737 return;
7738 if (ap->pat == NULL) /* pattern has been removed */
7739 return;
7740
7741 msg_putchar('\n');
7742 if (got_int)
7743 return;
7744 if (event != last_event || ap->group != last_group)
7745 {
7746 if (ap->group != AUGROUP_DEFAULT)
7747 {
7748 if (AUGROUP_NAME(ap->group) == NULL)
7749 msg_puts_attr((char_u *)_("--Deleted--"), hl_attr(HLF_E));
7750 else
7751 msg_puts_attr(AUGROUP_NAME(ap->group), hl_attr(HLF_T));
7752 msg_puts((char_u *)" ");
7753 }
7754 msg_puts_attr(event_nr2name(event), hl_attr(HLF_T));
7755 last_event = event;
7756 last_group = ap->group;
7757 msg_putchar('\n');
7758 if (got_int)
7759 return;
7760 }
7761 msg_col = 4;
7762 msg_outtrans(ap->pat);
7763
7764 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7765 {
7766 if (ac->cmd != NULL) /* skip removed commands */
7767 {
7768 if (msg_col >= 14)
7769 msg_putchar('\n');
7770 msg_col = 14;
7771 if (got_int)
7772 return;
7773 msg_outtrans(ac->cmd);
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00007774#ifdef FEAT_EVAL
7775 if (p_verbose > 0)
7776 last_set_msg(ac->scriptID);
7777#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007778 if (got_int)
7779 return;
7780 if (ac->next != NULL)
7781 {
7782 msg_putchar('\n');
7783 if (got_int)
7784 return;
7785 }
7786 }
7787 }
7788}
7789
7790/*
7791 * Mark an autocommand pattern for deletion.
7792 */
7793 static void
7794au_remove_pat(ap)
7795 AutoPat *ap;
7796{
7797 vim_free(ap->pat);
7798 ap->pat = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007799 ap->buflocal_nr = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007800 au_need_clean = TRUE;
7801}
7802
7803/*
7804 * Mark all commands for a pattern for deletion.
7805 */
7806 static void
7807au_remove_cmds(ap)
7808 AutoPat *ap;
7809{
7810 AutoCmd *ac;
7811
7812 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7813 {
7814 vim_free(ac->cmd);
7815 ac->cmd = NULL;
7816 }
7817 au_need_clean = TRUE;
7818}
7819
7820/*
7821 * Cleanup autocommands and patterns that have been deleted.
7822 * This is only done when not executing autocommands.
7823 */
7824 static void
7825au_cleanup()
7826{
7827 AutoPat *ap, **prev_ap;
7828 AutoCmd *ac, **prev_ac;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007829 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007830
7831 if (autocmd_busy || !au_need_clean)
7832 return;
7833
7834 /* loop over all events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007835 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7836 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007837 {
7838 /* loop over all autocommand patterns */
7839 prev_ap = &(first_autopat[(int)event]);
7840 for (ap = *prev_ap; ap != NULL; ap = *prev_ap)
7841 {
7842 /* loop over all commands for this pattern */
7843 prev_ac = &(ap->cmds);
7844 for (ac = *prev_ac; ac != NULL; ac = *prev_ac)
7845 {
7846 /* remove the command if the pattern is to be deleted or when
7847 * the command has been marked for deletion */
7848 if (ap->pat == NULL || ac->cmd == NULL)
7849 {
7850 *prev_ac = ac->next;
7851 vim_free(ac->cmd);
7852 vim_free(ac);
7853 }
7854 else
7855 prev_ac = &(ac->next);
7856 }
7857
7858 /* remove the pattern if it has been marked for deletion */
7859 if (ap->pat == NULL)
7860 {
7861 *prev_ap = ap->next;
Bram Moolenaar748bf032005-02-02 23:04:36 +00007862 vim_free(ap->reg_prog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007863 vim_free(ap);
7864 }
7865 else
7866 prev_ap = &(ap->next);
7867 }
7868 }
7869
7870 au_need_clean = FALSE;
7871}
7872
7873/*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007874 * Called when buffer is freed, to remove/invalidate related buffer-local
7875 * autocmds.
7876 */
7877 void
7878aubuflocal_remove(buf)
7879 buf_T *buf;
7880{
7881 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007882 event_T event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007883 AutoPatCmd *apc;
7884
7885 /* invalidate currently executing autocommands */
7886 for (apc = active_apc_list; apc; apc = apc->next)
7887 if (buf->b_fnum == apc->arg_bufnr)
7888 apc->arg_bufnr = 0;
7889
7890 /* invalidate buflocals looping through events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007891 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7892 event = (event_T)((int)event + 1))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007893 /* loop over all autocommand patterns */
7894 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
7895 if (ap->buflocal_nr == buf->b_fnum)
7896 {
7897 au_remove_pat(ap);
7898 if (p_verbose >= 6)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007899 {
7900 verbose_enter();
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007901 smsg((char_u *)
7902 _("auto-removing autocommand: %s <buffer=%d>"),
7903 event_nr2name(event), buf->b_fnum);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007904 verbose_leave();
7905 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007906 }
7907 au_cleanup();
7908}
7909
7910/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007911 * Add an autocmd group name.
7912 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
7913 */
7914 static int
7915au_new_group(name)
7916 char_u *name;
7917{
7918 int i;
7919
7920 i = au_find_group(name);
7921 if (i == AUGROUP_ERROR) /* the group doesn't exist yet, add it */
7922 {
7923 /* First try using a free entry. */
7924 for (i = 0; i < augroups.ga_len; ++i)
7925 if (AUGROUP_NAME(i) == NULL)
7926 break;
7927 if (i == augroups.ga_len && ga_grow(&augroups, 1) == FAIL)
7928 return AUGROUP_ERROR;
7929
7930 AUGROUP_NAME(i) = vim_strsave(name);
7931 if (AUGROUP_NAME(i) == NULL)
7932 return AUGROUP_ERROR;
7933 if (i == augroups.ga_len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007934 ++augroups.ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007935 }
7936
7937 return i;
7938}
7939
7940 static void
7941au_del_group(name)
7942 char_u *name;
7943{
7944 int i;
7945
7946 i = au_find_group(name);
7947 if (i == AUGROUP_ERROR) /* the group doesn't exist */
7948 EMSG2(_("E367: No such group: \"%s\""), name);
7949 else
7950 {
7951 vim_free(AUGROUP_NAME(i));
7952 AUGROUP_NAME(i) = NULL;
7953 }
7954}
7955
7956/*
7957 * Find the ID of an autocmd group name.
7958 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
7959 */
7960 static int
7961au_find_group(name)
7962 char_u *name;
7963{
7964 int i;
7965
7966 for (i = 0; i < augroups.ga_len; ++i)
7967 if (AUGROUP_NAME(i) != NULL && STRCMP(AUGROUP_NAME(i), name) == 0)
7968 return i;
7969 return AUGROUP_ERROR;
7970}
7971
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00007972/*
7973 * Return TRUE if augroup "name" exists.
7974 */
7975 int
7976au_has_group(name)
7977 char_u *name;
7978{
7979 return au_find_group(name) != AUGROUP_ERROR;
7980}
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00007981
Bram Moolenaar071d4272004-06-13 20:20:40 +00007982/*
7983 * ":augroup {name}".
7984 */
7985 void
7986do_augroup(arg, del_group)
7987 char_u *arg;
7988 int del_group;
7989{
7990 int i;
7991
7992 if (del_group)
7993 {
7994 if (*arg == NUL)
7995 EMSG(_(e_argreq));
7996 else
7997 au_del_group(arg);
7998 }
7999 else if (STRICMP(arg, "end") == 0) /* ":aug end": back to group 0 */
8000 current_augroup = AUGROUP_DEFAULT;
8001 else if (*arg) /* ":aug xxx": switch to group xxx */
8002 {
8003 i = au_new_group(arg);
8004 if (i != AUGROUP_ERROR)
8005 current_augroup = i;
8006 }
8007 else /* ":aug": list the group names */
8008 {
8009 msg_start();
8010 for (i = 0; i < augroups.ga_len; ++i)
8011 {
8012 if (AUGROUP_NAME(i) != NULL)
8013 {
8014 msg_puts(AUGROUP_NAME(i));
8015 msg_puts((char_u *)" ");
8016 }
8017 }
8018 msg_clr_eos();
8019 msg_end();
8020 }
8021}
8022
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008023#if defined(EXITFREE) || defined(PROTO)
8024 void
8025free_all_autocmds()
8026{
8027 for (current_augroup = -1; current_augroup < augroups.ga_len;
8028 ++current_augroup)
8029 do_autocmd((char_u *)"", TRUE);
8030 ga_clear_strings(&augroups);
8031}
8032#endif
8033
Bram Moolenaar071d4272004-06-13 20:20:40 +00008034/*
8035 * Return the event number for event name "start".
8036 * Return NUM_EVENTS if the event name was not found.
8037 * Return a pointer to the next event name in "end".
8038 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008039 static event_T
Bram Moolenaar071d4272004-06-13 20:20:40 +00008040event_name2nr(start, end)
8041 char_u *start;
8042 char_u **end;
8043{
8044 char_u *p;
8045 int i;
8046 int len;
8047
8048 /* the event name ends with end of line, a blank or a comma */
8049 for (p = start; *p && !vim_iswhite(*p) && *p != ','; ++p)
8050 ;
8051 for (i = 0; event_names[i].name != NULL; ++i)
8052 {
8053 len = (int)STRLEN(event_names[i].name);
8054 if (len == p - start && STRNICMP(event_names[i].name, start, len) == 0)
8055 break;
8056 }
8057 if (*p == ',')
8058 ++p;
8059 *end = p;
8060 if (event_names[i].name == NULL)
8061 return NUM_EVENTS;
8062 return event_names[i].event;
8063}
8064
8065/*
8066 * Return the name for event "event".
8067 */
8068 static char_u *
8069event_nr2name(event)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008070 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008071{
8072 int i;
8073
8074 for (i = 0; event_names[i].name != NULL; ++i)
8075 if (event_names[i].event == event)
8076 return (char_u *)event_names[i].name;
8077 return (char_u *)"Unknown";
8078}
8079
8080/*
8081 * Scan over the events. "*" stands for all events.
8082 */
8083 static char_u *
8084find_end_event(arg, have_group)
8085 char_u *arg;
8086 int have_group; /* TRUE when group name was found */
8087{
8088 char_u *pat;
8089 char_u *p;
8090
8091 if (*arg == '*')
8092 {
8093 if (arg[1] && !vim_iswhite(arg[1]))
8094 {
8095 EMSG2(_("E215: Illegal character after *: %s"), arg);
8096 return NULL;
8097 }
8098 pat = arg + 1;
8099 }
8100 else
8101 {
8102 for (pat = arg; *pat && !vim_iswhite(*pat); pat = p)
8103 {
8104 if ((int)event_name2nr(pat, &p) >= (int)NUM_EVENTS)
8105 {
8106 if (have_group)
8107 EMSG2(_("E216: No such event: %s"), pat);
8108 else
8109 EMSG2(_("E216: No such group or event: %s"), pat);
8110 return NULL;
8111 }
8112 }
8113 }
8114 return pat;
8115}
8116
8117/*
8118 * Return TRUE if "event" is included in 'eventignore'.
8119 */
8120 static int
8121event_ignored(event)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008122 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008123{
8124 char_u *p = p_ei;
8125
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008126 while (*p != NUL)
8127 {
8128 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8129 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008130 if (event_name2nr(p, &p) == event)
8131 return TRUE;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008132 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008133
8134 return FALSE;
8135}
8136
8137/*
8138 * Return OK when the contents of p_ei is valid, FAIL otherwise.
8139 */
8140 int
8141check_ei()
8142{
8143 char_u *p = p_ei;
8144
Bram Moolenaar071d4272004-06-13 20:20:40 +00008145 while (*p)
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008146 {
8147 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8148 {
8149 p += 3;
8150 if (*p == ',')
8151 ++p;
8152 }
8153 else if (event_name2nr(p, &p) == NUM_EVENTS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008154 return FAIL;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008155 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008156
8157 return OK;
8158}
8159
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008160# if defined(FEAT_SYN_HL) || defined(PROTO)
8161
8162/*
8163 * Add "what" to 'eventignore' to skip loading syntax highlighting for every
8164 * buffer loaded into the window. "what" must start with a comma.
8165 * Returns the old value of 'eventignore' in allocated memory.
8166 */
8167 char_u *
8168au_event_disable(what)
8169 char *what;
8170{
8171 char_u *new_ei;
8172 char_u *save_ei;
8173
8174 save_ei = vim_strsave(p_ei);
8175 if (save_ei != NULL)
8176 {
Bram Moolenaara5792f52005-11-23 21:25:05 +00008177 new_ei = vim_strnsave(p_ei, (int)(STRLEN(p_ei) + STRLEN(what)));
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008178 if (new_ei != NULL)
8179 {
Bram Moolenaar8cac9fd2010-03-02 12:48:05 +01008180 if (*what == ',' && *p_ei == NUL)
8181 STRCPY(new_ei, what + 1);
8182 else
8183 STRCAT(new_ei, what);
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008184 set_string_option_direct((char_u *)"ei", -1, new_ei,
8185 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008186 vim_free(new_ei);
8187 }
8188 }
8189 return save_ei;
8190}
8191
8192 void
8193au_event_restore(old_ei)
8194 char_u *old_ei;
8195{
8196 if (old_ei != NULL)
8197 {
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008198 set_string_option_direct((char_u *)"ei", -1, old_ei,
8199 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008200 vim_free(old_ei);
8201 }
8202}
8203# endif /* FEAT_SYN_HL */
8204
Bram Moolenaar071d4272004-06-13 20:20:40 +00008205/*
8206 * do_autocmd() -- implements the :autocmd command. Can be used in the
8207 * following ways:
8208 *
8209 * :autocmd <event> <pat> <cmd> Add <cmd> to the list of commands that
8210 * will be automatically executed for <event>
8211 * when editing a file matching <pat>, in
8212 * the current group.
8213 * :autocmd <event> <pat> Show the auto-commands associated with
8214 * <event> and <pat>.
8215 * :autocmd <event> Show the auto-commands associated with
8216 * <event>.
8217 * :autocmd Show all auto-commands.
8218 * :autocmd! <event> <pat> <cmd> Remove all auto-commands associated with
8219 * <event> and <pat>, and add the command
8220 * <cmd>, for the current group.
8221 * :autocmd! <event> <pat> Remove all auto-commands associated with
8222 * <event> and <pat> for the current group.
8223 * :autocmd! <event> Remove all auto-commands associated with
8224 * <event> for the current group.
8225 * :autocmd! Remove ALL auto-commands for the current
8226 * group.
8227 *
8228 * Multiple events and patterns may be given separated by commas. Here are
8229 * some examples:
8230 * :autocmd bufread,bufenter *.c,*.h set tw=0 smartindent noic
8231 * :autocmd bufleave * set tw=79 nosmartindent ic infercase
8232 *
8233 * :autocmd * *.c show all autocommands for *.c files.
Bram Moolenaard35f9712005-12-18 22:02:33 +00008234 *
8235 * Mostly a {group} argument can optionally appear before <event>.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008236 */
8237 void
8238do_autocmd(arg, forceit)
8239 char_u *arg;
8240 int forceit;
8241{
8242 char_u *pat;
8243 char_u *envpat = NULL;
8244 char_u *cmd;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008245 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008246 int need_free = FALSE;
8247 int nested = FALSE;
8248 int group;
8249
8250 /*
8251 * Check for a legal group name. If not, use AUGROUP_ALL.
8252 */
8253 group = au_get_grouparg(&arg);
8254 if (arg == NULL) /* out of memory */
8255 return;
8256
8257 /*
8258 * Scan over the events.
8259 * If we find an illegal name, return here, don't do anything.
8260 */
8261 pat = find_end_event(arg, group != AUGROUP_ALL);
8262 if (pat == NULL)
8263 return;
8264
8265 /*
8266 * Scan over the pattern. Put a NUL at the end.
8267 */
8268 pat = skipwhite(pat);
8269 cmd = pat;
8270 while (*cmd && (!vim_iswhite(*cmd) || cmd[-1] == '\\'))
8271 cmd++;
8272 if (*cmd)
8273 *cmd++ = NUL;
8274
8275 /* Expand environment variables in the pattern. Set 'shellslash', we want
8276 * forward slashes here. */
8277 if (vim_strchr(pat, '$') != NULL || vim_strchr(pat, '~') != NULL)
8278 {
8279#ifdef BACKSLASH_IN_FILENAME
8280 int p_ssl_save = p_ssl;
8281
8282 p_ssl = TRUE;
8283#endif
8284 envpat = expand_env_save(pat);
8285#ifdef BACKSLASH_IN_FILENAME
8286 p_ssl = p_ssl_save;
8287#endif
8288 if (envpat != NULL)
8289 pat = envpat;
8290 }
8291
8292 /*
8293 * Check for "nested" flag.
8294 */
8295 cmd = skipwhite(cmd);
8296 if (*cmd != NUL && STRNCMP(cmd, "nested", 6) == 0 && vim_iswhite(cmd[6]))
8297 {
8298 nested = TRUE;
8299 cmd = skipwhite(cmd + 6);
8300 }
8301
8302 /*
8303 * Find the start of the commands.
8304 * Expand <sfile> in it.
8305 */
8306 if (*cmd != NUL)
8307 {
8308 cmd = expand_sfile(cmd);
8309 if (cmd == NULL) /* some error */
8310 return;
8311 need_free = TRUE;
8312 }
8313
8314 /*
8315 * Print header when showing autocommands.
8316 */
8317 if (!forceit && *cmd == NUL)
8318 {
8319 /* Highlight title */
8320 MSG_PUTS_TITLE(_("\n--- Auto-Commands ---"));
8321 }
8322
8323 /*
8324 * Loop over the events.
8325 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008326 last_event = (event_T)-1; /* for listing the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008327 last_group = AUGROUP_ERROR; /* for listing the group name */
8328 if (*arg == '*' || *arg == NUL)
8329 {
Bram Moolenaar754b5602006-02-09 23:53:20 +00008330 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8331 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008332 if (do_autocmd_event(event, pat,
8333 nested, cmd, forceit, group) == FAIL)
8334 break;
8335 }
8336 else
8337 {
8338 while (*arg && !vim_iswhite(*arg))
8339 if (do_autocmd_event(event_name2nr(arg, &arg), pat,
8340 nested, cmd, forceit, group) == FAIL)
8341 break;
8342 }
8343
8344 if (need_free)
8345 vim_free(cmd);
8346 vim_free(envpat);
8347}
8348
8349/*
8350 * Find the group ID in a ":autocmd" or ":doautocmd" argument.
8351 * The "argp" argument is advanced to the following argument.
8352 *
8353 * Returns the group ID, AUGROUP_ERROR for error (out of memory).
8354 */
8355 static int
8356au_get_grouparg(argp)
8357 char_u **argp;
8358{
8359 char_u *group_name;
8360 char_u *p;
8361 char_u *arg = *argp;
8362 int group = AUGROUP_ALL;
8363
8364 p = skiptowhite(arg);
8365 if (p > arg)
8366 {
8367 group_name = vim_strnsave(arg, (int)(p - arg));
8368 if (group_name == NULL) /* out of memory */
8369 return AUGROUP_ERROR;
8370 group = au_find_group(group_name);
8371 if (group == AUGROUP_ERROR)
8372 group = AUGROUP_ALL; /* no match, use all groups */
8373 else
8374 *argp = skipwhite(p); /* match, skip over group name */
8375 vim_free(group_name);
8376 }
8377 return group;
8378}
8379
8380/*
8381 * do_autocmd() for one event.
8382 * If *pat == NUL do for all patterns.
8383 * If *cmd == NUL show entries.
8384 * If forceit == TRUE delete entries.
8385 * If group is not AUGROUP_ALL, only use this group.
8386 */
8387 static int
8388do_autocmd_event(event, pat, nested, cmd, forceit, group)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008389 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008390 char_u *pat;
8391 int nested;
8392 char_u *cmd;
8393 int forceit;
8394 int group;
8395{
8396 AutoPat *ap;
8397 AutoPat **prev_ap;
8398 AutoCmd *ac;
8399 AutoCmd **prev_ac;
8400 int brace_level;
8401 char_u *endpat;
8402 int findgroup;
8403 int allgroups;
8404 int patlen;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00008405 int is_buflocal;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008406 int buflocal_nr;
8407 char_u buflocal_pat[25]; /* for "<buffer=X>" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008408
8409 if (group == AUGROUP_ALL)
8410 findgroup = current_augroup;
8411 else
8412 findgroup = group;
8413 allgroups = (group == AUGROUP_ALL && !forceit && *cmd == NUL);
8414
8415 /*
8416 * Show or delete all patterns for an event.
8417 */
8418 if (*pat == NUL)
8419 {
8420 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8421 {
8422 if (forceit) /* delete the AutoPat, if it's in the current group */
8423 {
8424 if (ap->group == findgroup)
8425 au_remove_pat(ap);
8426 }
8427 else if (group == AUGROUP_ALL || ap->group == group)
8428 show_autocmd(ap, event);
8429 }
8430 }
8431
8432 /*
8433 * Loop through all the specified patterns.
8434 */
8435 for ( ; *pat; pat = (*endpat == ',' ? endpat + 1 : endpat))
8436 {
8437 /*
8438 * Find end of the pattern.
8439 * Watch out for a comma in braces, like "*.\{obj,o\}".
8440 */
8441 brace_level = 0;
8442 for (endpat = pat; *endpat && (*endpat != ',' || brace_level
8443 || endpat[-1] == '\\'); ++endpat)
8444 {
8445 if (*endpat == '{')
8446 brace_level++;
8447 else if (*endpat == '}')
8448 brace_level--;
8449 }
8450 if (pat == endpat) /* ignore single comma */
8451 continue;
8452 patlen = (int)(endpat - pat);
8453
8454 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008455 * detect special <buflocal[=X]> buffer-local patterns
8456 */
8457 is_buflocal = FALSE;
8458 buflocal_nr = 0;
8459
8460 if (patlen >= 7 && STRNCMP(pat, "<buffer", 7) == 0
8461 && pat[patlen - 1] == '>')
8462 {
8463 /* Error will be printed only for addition. printing and removing
8464 * will proceed silently. */
8465 is_buflocal = TRUE;
8466 if (patlen == 8)
8467 buflocal_nr = curbuf->b_fnum;
8468 else if (patlen > 9 && pat[7] == '=')
8469 {
8470 /* <buffer=abuf> */
8471 if (patlen == 13 && STRNICMP(pat, "<buffer=abuf>", 13))
8472 buflocal_nr = autocmd_bufnr;
8473 /* <buffer=123> */
8474 else if (skipdigits(pat + 8) == pat + patlen - 1)
8475 buflocal_nr = atoi((char *)pat + 8);
8476 }
8477 }
8478
8479 if (is_buflocal)
8480 {
8481 /* normalize pat into standard "<buffer>#N" form */
8482 sprintf((char *)buflocal_pat, "<buffer=%d>", buflocal_nr);
8483 pat = buflocal_pat; /* can modify pat and patlen */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008484 patlen = (int)STRLEN(buflocal_pat); /* but not endpat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008485 }
8486
8487 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008488 * Find AutoPat entries with this pattern.
8489 */
8490 prev_ap = &first_autopat[(int)event];
8491 while ((ap = *prev_ap) != NULL)
8492 {
8493 if (ap->pat != NULL)
8494 {
8495 /* Accept a pattern when:
8496 * - a group was specified and it's that group, or a group was
8497 * not specified and it's the current group, or a group was
8498 * not specified and we are listing
8499 * - the length of the pattern matches
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008500 * - the pattern matches.
8501 * For <buffer[=X]>, this condition works because we normalize
8502 * all buffer-local patterns.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008503 */
8504 if ((allgroups || ap->group == findgroup)
8505 && ap->patlen == patlen
8506 && STRNCMP(pat, ap->pat, patlen) == 0)
8507 {
8508 /*
8509 * Remove existing autocommands.
8510 * If adding any new autocmd's for this AutoPat, don't
8511 * delete the pattern from the autopat list, append to
8512 * this list.
8513 */
8514 if (forceit)
8515 {
8516 if (*cmd != NUL && ap->next == NULL)
8517 {
8518 au_remove_cmds(ap);
8519 break;
8520 }
8521 au_remove_pat(ap);
8522 }
8523
8524 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008525 * Show autocmd's for this autopat, or buflocals <buffer=X>
Bram Moolenaar071d4272004-06-13 20:20:40 +00008526 */
8527 else if (*cmd == NUL)
8528 show_autocmd(ap, event);
8529
8530 /*
8531 * Add autocmd to this autopat, if it's the last one.
8532 */
8533 else if (ap->next == NULL)
8534 break;
8535 }
8536 }
8537 prev_ap = &ap->next;
8538 }
8539
8540 /*
8541 * Add a new command.
8542 */
8543 if (*cmd != NUL)
8544 {
8545 /*
8546 * If the pattern we want to add a command to does appear at the
8547 * end of the list (or not is not in the list at all), add the
8548 * pattern at the end of the list.
8549 */
8550 if (ap == NULL)
8551 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008552 /* refuse to add buffer-local ap if buffer number is invalid */
8553 if (is_buflocal && (buflocal_nr == 0
8554 || buflist_findnr(buflocal_nr) == NULL))
8555 {
8556 EMSGN(_("E680: <buffer=%d>: invalid buffer number "),
8557 buflocal_nr);
8558 return FAIL;
8559 }
8560
Bram Moolenaar071d4272004-06-13 20:20:40 +00008561 ap = (AutoPat *)alloc((unsigned)sizeof(AutoPat));
8562 if (ap == NULL)
8563 return FAIL;
8564 ap->pat = vim_strnsave(pat, patlen);
8565 ap->patlen = patlen;
8566 if (ap->pat == NULL)
8567 {
8568 vim_free(ap);
8569 return FAIL;
8570 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008571
8572 if (is_buflocal)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008573 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008574 ap->buflocal_nr = buflocal_nr;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008575 ap->reg_prog = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008576 }
8577 else
8578 {
Bram Moolenaar748bf032005-02-02 23:04:36 +00008579 char_u *reg_pat;
8580
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008581 ap->buflocal_nr = 0;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008582 reg_pat = file_pat_to_reg_pat(pat, endpat,
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008583 &ap->allow_dirs, TRUE);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008584 if (reg_pat != NULL)
8585 ap->reg_prog = vim_regcomp(reg_pat, RE_MAGIC);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008586 vim_free(reg_pat);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008587 if (reg_pat == NULL || ap->reg_prog == NULL)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008588 {
8589 vim_free(ap->pat);
8590 vim_free(ap);
8591 return FAIL;
8592 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008593 }
8594 ap->cmds = NULL;
8595 *prev_ap = ap;
8596 ap->next = NULL;
8597 if (group == AUGROUP_ALL)
8598 ap->group = current_augroup;
8599 else
8600 ap->group = group;
8601 }
8602
8603 /*
8604 * Add the autocmd at the end of the AutoCmd list.
8605 */
8606 prev_ac = &(ap->cmds);
8607 while ((ac = *prev_ac) != NULL)
8608 prev_ac = &ac->next;
8609 ac = (AutoCmd *)alloc((unsigned)sizeof(AutoCmd));
8610 if (ac == NULL)
8611 return FAIL;
8612 ac->cmd = vim_strsave(cmd);
8613#ifdef FEAT_EVAL
8614 ac->scriptID = current_SID;
8615#endif
8616 if (ac->cmd == NULL)
8617 {
8618 vim_free(ac);
8619 return FAIL;
8620 }
8621 ac->next = NULL;
8622 *prev_ac = ac;
8623 ac->nested = nested;
8624 }
8625 }
8626
8627 au_cleanup(); /* may really delete removed patterns/commands now */
8628 return OK;
8629}
8630
8631/*
8632 * Implementation of ":doautocmd [group] event [fname]".
8633 * Return OK for success, FAIL for failure;
8634 */
8635 int
8636do_doautocmd(arg, do_msg)
8637 char_u *arg;
8638 int do_msg; /* give message for no matching autocmds? */
8639{
8640 char_u *fname;
8641 int nothing_done = TRUE;
8642 int group;
8643
8644 /*
8645 * Check for a legal group name. If not, use AUGROUP_ALL.
8646 */
8647 group = au_get_grouparg(&arg);
8648 if (arg == NULL) /* out of memory */
8649 return FAIL;
8650
8651 if (*arg == '*')
8652 {
8653 EMSG(_("E217: Can't execute autocommands for ALL events"));
8654 return FAIL;
8655 }
8656
8657 /*
8658 * Scan over the events.
8659 * If we find an illegal name, return here, don't do anything.
8660 */
8661 fname = find_end_event(arg, group != AUGROUP_ALL);
8662 if (fname == NULL)
8663 return FAIL;
8664
8665 fname = skipwhite(fname);
8666
8667 /*
8668 * Loop over the events.
8669 */
8670 while (*arg && !vim_iswhite(*arg))
8671 if (apply_autocmds_group(event_name2nr(arg, &arg),
8672 fname, NULL, TRUE, group, curbuf, NULL))
8673 nothing_done = FALSE;
8674
8675 if (nothing_done && do_msg)
8676 MSG(_("No matching autocommands"));
8677
8678#ifdef FEAT_EVAL
8679 return aborting() ? FAIL : OK;
8680#else
8681 return OK;
8682#endif
8683}
8684
8685/*
8686 * ":doautoall": execute autocommands for each loaded buffer.
8687 */
8688 void
8689ex_doautoall(eap)
8690 exarg_T *eap;
8691{
8692 int retval;
8693 aco_save_T aco;
8694 buf_T *buf;
8695
8696 /*
8697 * This is a bit tricky: For some commands curwin->w_buffer needs to be
8698 * equal to curbuf, but for some buffers there may not be a window.
8699 * So we change the buffer for the current window for a moment. This
8700 * gives problems when the autocommands make changes to the list of
8701 * buffers or windows...
8702 */
8703 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8704 {
Bram Moolenaar3a847972008-07-08 09:36:58 +00008705 if (buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008706 {
8707 /* find a window for this buffer and save some values */
8708 aucmd_prepbuf(&aco, buf);
8709
8710 /* execute the autocommands for this buffer */
8711 retval = do_doautocmd(eap->arg, FALSE);
Bram Moolenaareeefcc72007-05-01 21:21:21 +00008712
8713 /* Execute the modeline settings, but don't set window-local
8714 * options if we are using the current window for another buffer. */
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008715 do_modelines(curwin == aucmd_win ? OPT_NOWIN : 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008716
8717 /* restore the current window */
8718 aucmd_restbuf(&aco);
8719
8720 /* stop if there is some error or buffer was deleted */
8721 if (retval == FAIL || !buf_valid(buf))
8722 break;
8723 }
8724 }
8725
8726 check_cursor(); /* just in case lines got deleted */
8727}
8728
8729/*
8730 * Prepare for executing autocommands for (hidden) buffer "buf".
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008731 * Search for a visible window containing the current buffer. If there isn't
8732 * one then use "aucmd_win".
Bram Moolenaar071d4272004-06-13 20:20:40 +00008733 * Set "curbuf" and "curwin" to match "buf".
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00008734 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008735 */
8736 void
8737aucmd_prepbuf(aco, buf)
8738 aco_save_T *aco; /* structure to save values in */
8739 buf_T *buf; /* new curbuf */
8740{
8741 win_T *win;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008742#ifdef FEAT_WINDOWS
8743 int save_ea;
8744#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008745
8746 /* Find a window that is for the new buffer */
8747 if (buf == curbuf) /* be quick when buf is curbuf */
8748 win = curwin;
8749 else
8750#ifdef FEAT_WINDOWS
8751 for (win = firstwin; win != NULL; win = win->w_next)
8752 if (win->w_buffer == buf)
8753 break;
8754#else
8755 win = NULL;
8756#endif
8757
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008758 /* Allocate "aucmd_win" when needed. If this fails (out of memory) fall
8759 * back to using the current window. */
8760 if (win == NULL && aucmd_win == NULL)
8761 {
8762 win_alloc_aucmd_win();
8763 if (aucmd_win == NULL)
8764 win = curwin;
8765 }
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008766 if (win == NULL && aucmd_win_used)
8767 /* Strange recursive autocommand, fall back to using the current
8768 * window. Expect a few side effects... */
8769 win = curwin;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008770
8771 aco->save_curwin = curwin;
8772 aco->save_curbuf = curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008773 if (win != NULL)
8774 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008775 /* There is a window for "buf" in the current tab page, make it the
8776 * curwin. This is preferred, it has the least side effects (esp. if
8777 * "buf" is curbuf). */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008778 aco->use_aucmd_win = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008779 curwin = win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008780 }
8781 else
8782 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008783 /* There is no window for "buf", use "aucmd_win". To minimize the side
8784 * effects, insert it in a the current tab page.
8785 * Anything related to a window (e.g., setting folds) may have
8786 * unexpected results. */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008787 aco->use_aucmd_win = TRUE;
8788 aucmd_win_used = TRUE;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008789 aucmd_win->w_buffer = buf;
Bram Moolenaarcdddaa42010-06-07 23:07:44 +02008790 aucmd_win->w_s = &buf->b_s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008791 ++buf->b_nwindows;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008792 win_init_empty(aucmd_win); /* set cursor and topline to safe values */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008793 vim_free(aucmd_win->w_localdir);
8794 aucmd_win->w_localdir = NULL;
8795
8796 /* Make sure w_localdir and globaldir are NULL to avoid a chdir() in
8797 * win_enter_ext(). */
8798 aucmd_win->w_localdir = NULL;
8799 aco->globaldir = globaldir;
8800 globaldir = NULL;
8801
Bram Moolenaar071d4272004-06-13 20:20:40 +00008802
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008803#ifdef FEAT_WINDOWS
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008804 /* Split the current window, put the aucmd_win in the upper half.
8805 * We don't want the BufEnter or WinEnter autocommands. */
8806 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008807 make_snapshot(SNAP_AUCMD_IDX);
8808 save_ea = p_ea;
8809 p_ea = FALSE;
8810 (void)win_split_ins(0, WSP_TOP, aucmd_win, 0);
8811 (void)win_comp_pos(); /* recompute window positions */
8812 p_ea = save_ea;
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008813 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008814#endif
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008815 curwin = aucmd_win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008816 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008817 curbuf = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008818 aco->new_curwin = curwin;
8819 aco->new_curbuf = curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008820}
8821
8822/*
8823 * Cleanup after executing autocommands for a (hidden) buffer.
8824 * Restore the window as it was (if possible).
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00008825 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008826 */
8827 void
8828aucmd_restbuf(aco)
8829 aco_save_T *aco; /* structure holding saved values */
8830{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008831#ifdef FEAT_WINDOWS
8832 int dummy;
8833#endif
8834
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008835 if (aco->use_aucmd_win)
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008836 {
8837 --curbuf->b_nwindows;
8838#ifdef FEAT_WINDOWS
8839 /* Find "aucmd_win", it can't be closed, but it may be in another tab
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008840 * page. Do not trigger autocommands here. */
8841 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008842 if (curwin != aucmd_win)
8843 {
8844 tabpage_T *tp;
8845 win_T *wp;
8846
8847 FOR_ALL_TAB_WINDOWS(tp, wp)
8848 {
8849 if (wp == aucmd_win)
8850 {
8851 if (tp != curtab)
8852 goto_tabpage_tp(tp);
8853 win_goto(aucmd_win);
8854 break;
8855 }
8856 }
8857 }
8858
8859 /* Remove the window and frame from the tree of frames. */
8860 (void)winframe_remove(curwin, &dummy, NULL);
8861 win_remove(curwin, NULL);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008862 aucmd_win_used = FALSE;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008863 last_status(FALSE); /* may need to remove last status line */
8864 restore_snapshot(SNAP_AUCMD_IDX, FALSE);
8865 (void)win_comp_pos(); /* recompute window positions */
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008866 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008867
8868 if (win_valid(aco->save_curwin))
8869 curwin = aco->save_curwin;
8870 else
8871 /* Hmm, original window disappeared. Just use the first one. */
8872 curwin = firstwin;
8873# ifdef FEAT_EVAL
8874 vars_clear(&aucmd_win->w_vars.dv_hashtab); /* free all w: variables */
Bram Moolenaar50daf402009-11-17 13:57:22 +00008875 hash_init(&aucmd_win->w_vars.dv_hashtab); /* re-use the hashtab */
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008876# endif
8877#else
8878 curwin = aco->save_curwin;
8879#endif
8880 curbuf = curwin->w_buffer;
8881
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008882 vim_free(globaldir);
8883 globaldir = aco->globaldir;
8884
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008885 /* the buffer contents may have changed */
8886 check_cursor();
8887 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
8888 {
8889 curwin->w_topline = curbuf->b_ml.ml_line_count;
8890#ifdef FEAT_DIFF
8891 curwin->w_topfill = 0;
8892#endif
8893 }
8894#if defined(FEAT_GUI)
8895 /* Hide the scrollbars from the aucmd_win and update. */
8896 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_LEFT], FALSE);
8897 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_RIGHT], FALSE);
8898 gui_may_update_scrollbars();
8899#endif
8900 }
8901 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00008902 {
8903 /* restore curwin */
8904#ifdef FEAT_WINDOWS
8905 if (win_valid(aco->save_curwin))
8906#endif
8907 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008908 /* Restore the buffer which was previously edited by curwin, if
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008909 * it was changed, we are still the same window and the buffer is
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008910 * valid. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008911 if (curwin == aco->new_curwin
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008912 && curbuf != aco->new_curbuf
8913 && buf_valid(aco->new_curbuf)
8914 && aco->new_curbuf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008915 {
8916 --curbuf->b_nwindows;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008917 curbuf = aco->new_curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008918 curwin->w_buffer = curbuf;
8919 ++curbuf->b_nwindows;
8920 }
8921
8922 curwin = aco->save_curwin;
8923 curbuf = curwin->w_buffer;
8924 }
8925 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008926}
8927
8928static int autocmd_nested = FALSE;
8929
8930/*
8931 * Execute autocommands for "event" and file name "fname".
8932 * Return TRUE if some commands were executed.
8933 */
8934 int
8935apply_autocmds(event, fname, fname_io, force, buf)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008936 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008937 char_u *fname; /* NULL or empty means use actual file name */
8938 char_u *fname_io; /* fname to use for <afile> on cmdline */
8939 int force; /* when TRUE, ignore autocmd_busy */
8940 buf_T *buf; /* buffer for <abuf> */
8941{
8942 return apply_autocmds_group(event, fname, fname_io, force,
8943 AUGROUP_ALL, buf, NULL);
8944}
8945
8946/*
8947 * Like apply_autocmds(), but with extra "eap" argument. This takes care of
8948 * setting v:filearg.
8949 */
8950 static int
8951apply_autocmds_exarg(event, fname, fname_io, force, buf, eap)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008952 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008953 char_u *fname;
8954 char_u *fname_io;
8955 int force;
8956 buf_T *buf;
8957 exarg_T *eap;
8958{
8959 return apply_autocmds_group(event, fname, fname_io, force,
8960 AUGROUP_ALL, buf, eap);
8961}
8962
8963/*
8964 * Like apply_autocmds(), but handles the caller's retval. If the script
8965 * processing is being aborted or if retval is FAIL when inside a try
8966 * conditional, no autocommands are executed. If otherwise the autocommands
8967 * cause the script to be aborted, retval is set to FAIL.
8968 */
8969 int
8970apply_autocmds_retval(event, fname, fname_io, force, buf, retval)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008971 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008972 char_u *fname; /* NULL or empty means use actual file name */
8973 char_u *fname_io; /* fname to use for <afile> on cmdline */
8974 int force; /* when TRUE, ignore autocmd_busy */
8975 buf_T *buf; /* buffer for <abuf> */
8976 int *retval; /* pointer to caller's retval */
8977{
8978 int did_cmd;
8979
Bram Moolenaar1e015462005-09-25 22:16:38 +00008980#ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00008981 if (should_abort(*retval))
8982 return FALSE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00008983#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008984
8985 did_cmd = apply_autocmds_group(event, fname, fname_io, force,
8986 AUGROUP_ALL, buf, NULL);
Bram Moolenaar1e015462005-09-25 22:16:38 +00008987 if (did_cmd
8988#ifdef FEAT_EVAL
8989 && aborting()
8990#endif
8991 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00008992 *retval = FAIL;
8993 return did_cmd;
8994}
8995
Bram Moolenaard35f9712005-12-18 22:02:33 +00008996/*
8997 * Return TRUE when there is a CursorHold autocommand defined.
8998 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008999 int
9000has_cursorhold()
9001{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009002 return (first_autopat[(int)(get_real_state() == NORMAL_BUSY
9003 ? EVENT_CURSORHOLD : EVENT_CURSORHOLDI)] != NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009004}
Bram Moolenaard35f9712005-12-18 22:02:33 +00009005
9006/*
9007 * Return TRUE if the CursorHold event can be triggered.
9008 */
9009 int
9010trigger_cursorhold()
9011{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009012 int state;
9013
Bram Moolenaard29a9ee2006-09-14 09:07:34 +00009014 if (!did_cursorhold && has_cursorhold() && !Recording
9015#ifdef FEAT_INS_EXPAND
9016 && !ins_compl_active()
9017#endif
9018 )
Bram Moolenaar754b5602006-02-09 23:53:20 +00009019 {
9020 state = get_real_state();
9021 if (state == NORMAL_BUSY || (state & INSERT) != 0)
9022 return TRUE;
9023 }
9024 return FALSE;
Bram Moolenaard35f9712005-12-18 22:02:33 +00009025}
Bram Moolenaar754b5602006-02-09 23:53:20 +00009026
9027/*
9028 * Return TRUE when there is a CursorMoved autocommand defined.
9029 */
9030 int
9031has_cursormoved()
9032{
9033 return (first_autopat[(int)EVENT_CURSORMOVED] != NULL);
9034}
9035
9036/*
9037 * Return TRUE when there is a CursorMovedI autocommand defined.
9038 */
9039 int
9040has_cursormovedI()
9041{
9042 return (first_autopat[(int)EVENT_CURSORMOVEDI] != NULL);
9043}
Bram Moolenaar071d4272004-06-13 20:20:40 +00009044
9045 static int
9046apply_autocmds_group(event, fname, fname_io, force, group, buf, eap)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009047 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009048 char_u *fname; /* NULL or empty means use actual file name */
9049 char_u *fname_io; /* fname to use for <afile> on cmdline, NULL means
9050 use fname */
9051 int force; /* when TRUE, ignore autocmd_busy */
9052 int group; /* group ID, or AUGROUP_ALL */
9053 buf_T *buf; /* buffer for <abuf> */
9054 exarg_T *eap; /* command arguments */
9055{
9056 char_u *sfname = NULL; /* short file name */
9057 char_u *tail;
9058 int save_changed;
9059 buf_T *old_curbuf;
9060 int retval = FALSE;
9061 char_u *save_sourcing_name;
9062 linenr_T save_sourcing_lnum;
9063 char_u *save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009064 int save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009065 int save_autocmd_bufnr;
9066 char_u *save_autocmd_match;
9067 int save_autocmd_busy;
9068 int save_autocmd_nested;
9069 static int nesting = 0;
9070 AutoPatCmd patcmd;
9071 AutoPat *ap;
9072#ifdef FEAT_EVAL
9073 scid_T save_current_SID;
9074 void *save_funccalp;
9075 char_u *save_cmdarg;
9076 long save_cmdbang;
9077#endif
9078 static int filechangeshell_busy = FALSE;
Bram Moolenaar05159a02005-02-26 23:04:13 +00009079#ifdef FEAT_PROFILE
9080 proftime_T wait_time;
9081#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009082
9083 /*
9084 * Quickly return if there are no autocommands for this event or
9085 * autocommands are blocked.
9086 */
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009087 if (first_autopat[(int)event] == NULL || autocmd_blocked > 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009088 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009089
9090 /*
9091 * When autocommands are busy, new autocommands are only executed when
9092 * explicitly enabled with the "nested" flag.
9093 */
9094 if (autocmd_busy && !(force || autocmd_nested))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009095 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009096
9097#ifdef FEAT_EVAL
9098 /*
Bram Moolenaar7263a772007-05-10 17:35:54 +00009099 * Quickly return when immediately aborting on error, or when an interrupt
Bram Moolenaar071d4272004-06-13 20:20:40 +00009100 * occurred or an exception was thrown but not caught.
9101 */
9102 if (aborting())
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009103 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009104#endif
9105
9106 /*
9107 * FileChangedShell never nests, because it can create an endless loop.
9108 */
Bram Moolenaar56718732006-03-15 22:53:57 +00009109 if (filechangeshell_busy && (event == EVENT_FILECHANGEDSHELL
9110 || event == EVENT_FILECHANGEDSHELLPOST))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009111 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009112
9113 /*
9114 * Ignore events in 'eventignore'.
9115 */
9116 if (event_ignored(event))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009117 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009118
9119 /*
9120 * Allow nesting of autocommands, but restrict the depth, because it's
9121 * possible to create an endless loop.
9122 */
9123 if (nesting == 10)
9124 {
9125 EMSG(_("E218: autocommand nesting too deep"));
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009126 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009127 }
9128
9129 /*
9130 * Check if these autocommands are disabled. Used when doing ":all" or
9131 * ":ball".
9132 */
9133 if ( (autocmd_no_enter
9134 && (event == EVENT_WINENTER || event == EVENT_BUFENTER))
9135 || (autocmd_no_leave
9136 && (event == EVENT_WINLEAVE || event == EVENT_BUFLEAVE)))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009137 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009138
9139 /*
9140 * Save the autocmd_* variables and info about the current buffer.
9141 */
9142 save_autocmd_fname = autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009143 save_autocmd_fname_full = autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009144 save_autocmd_bufnr = autocmd_bufnr;
9145 save_autocmd_match = autocmd_match;
9146 save_autocmd_busy = autocmd_busy;
9147 save_autocmd_nested = autocmd_nested;
9148 save_changed = curbuf->b_changed;
9149 old_curbuf = curbuf;
9150
9151 /*
9152 * Set the file name to be used for <afile>.
Bram Moolenaara0174af2008-01-02 20:08:25 +00009153 * Make a copy to avoid that changing a buffer name or directory makes it
9154 * invalid.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009155 */
9156 if (fname_io == NULL)
9157 {
9158 if (fname != NULL && *fname != NUL)
9159 autocmd_fname = fname;
9160 else if (buf != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009161 autocmd_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009162 else
9163 autocmd_fname = NULL;
9164 }
9165 else
9166 autocmd_fname = fname_io;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009167 if (autocmd_fname != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009168 autocmd_fname = vim_strsave(autocmd_fname);
9169 autocmd_fname_full = FALSE; /* call FullName_save() later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009170
9171 /*
9172 * Set the buffer number to be used for <abuf>.
9173 */
9174 if (buf == NULL)
9175 autocmd_bufnr = 0;
9176 else
9177 autocmd_bufnr = buf->b_fnum;
9178
9179 /*
9180 * When the file name is NULL or empty, use the file name of buffer "buf".
9181 * Always use the full path of the file name to match with, in case
9182 * "allow_dirs" is set.
9183 */
9184 if (fname == NULL || *fname == NUL)
9185 {
9186 if (buf == NULL)
9187 fname = NULL;
9188 else
9189 {
9190#ifdef FEAT_SYN_HL
9191 if (event == EVENT_SYNTAX)
9192 fname = buf->b_p_syn;
9193 else
9194#endif
9195 if (event == EVENT_FILETYPE)
9196 fname = buf->b_p_ft;
9197 else
9198 {
9199 if (buf->b_sfname != NULL)
9200 sfname = vim_strsave(buf->b_sfname);
9201 fname = buf->b_ffname;
9202 }
9203 }
9204 if (fname == NULL)
9205 fname = (char_u *)"";
9206 fname = vim_strsave(fname); /* make a copy, so we can change it */
9207 }
9208 else
9209 {
9210 sfname = vim_strsave(fname);
Bram Moolenaar5135d462009-04-29 16:03:38 +00009211 /* Don't try expanding FileType, Syntax, FuncUndefined, WindowID or
9212 * QuickFixCmd* */
Bram Moolenaar7c626922005-02-07 22:01:03 +00009213 if (event == EVENT_FILETYPE
9214 || event == EVENT_SYNTAX
Bram Moolenaar5135d462009-04-29 16:03:38 +00009215 || event == EVENT_FUNCUNDEFINED
Bram Moolenaar7c626922005-02-07 22:01:03 +00009216 || event == EVENT_REMOTEREPLY
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00009217 || event == EVENT_SPELLFILEMISSING
Bram Moolenaar7c626922005-02-07 22:01:03 +00009218 || event == EVENT_QUICKFIXCMDPRE
9219 || event == EVENT_QUICKFIXCMDPOST)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009220 fname = vim_strsave(fname);
9221 else
9222 fname = FullName_save(fname, FALSE);
9223 }
9224 if (fname == NULL) /* out of memory */
9225 {
9226 vim_free(sfname);
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009227 retval = FALSE;
9228 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009229 }
9230
9231#ifdef BACKSLASH_IN_FILENAME
9232 /*
9233 * Replace all backslashes with forward slashes. This makes the
9234 * autocommand patterns portable between Unix and MS-DOS.
9235 */
9236 if (sfname != NULL)
9237 forward_slash(sfname);
9238 forward_slash(fname);
9239#endif
9240
9241#ifdef VMS
9242 /* remove version for correct match */
9243 if (sfname != NULL)
9244 vms_remove_version(sfname);
9245 vms_remove_version(fname);
9246#endif
9247
9248 /*
9249 * Set the name to be used for <amatch>.
9250 */
9251 autocmd_match = fname;
9252
9253
9254 /* Don't redraw while doing auto commands. */
9255 ++RedrawingDisabled;
9256 save_sourcing_name = sourcing_name;
9257 sourcing_name = NULL; /* don't free this one */
9258 save_sourcing_lnum = sourcing_lnum;
9259 sourcing_lnum = 0; /* no line number here */
9260
9261#ifdef FEAT_EVAL
9262 save_current_SID = current_SID;
9263
Bram Moolenaar05159a02005-02-26 23:04:13 +00009264# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009265 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009266 prof_child_enter(&wait_time); /* doesn't count for the caller itself */
9267# endif
9268
Bram Moolenaar071d4272004-06-13 20:20:40 +00009269 /* Don't use local function variables, if called from a function */
9270 save_funccalp = save_funccal();
9271#endif
9272
9273 /*
9274 * When starting to execute autocommands, save the search patterns.
9275 */
9276 if (!autocmd_busy)
9277 {
9278 save_search_patterns();
9279 saveRedobuff();
9280 did_filetype = keep_filetype;
9281 }
9282
9283 /*
9284 * Note that we are applying autocmds. Some commands need to know.
9285 */
9286 autocmd_busy = TRUE;
9287 filechangeshell_busy = (event == EVENT_FILECHANGEDSHELL);
9288 ++nesting; /* see matching decrement below */
9289
9290 /* Remember that FileType was triggered. Used for did_filetype(). */
9291 if (event == EVENT_FILETYPE)
9292 did_filetype = TRUE;
9293
9294 tail = gettail(fname);
9295
9296 /* Find first autocommand that matches */
9297 patcmd.curpat = first_autopat[(int)event];
9298 patcmd.nextcmd = NULL;
9299 patcmd.group = group;
9300 patcmd.fname = fname;
9301 patcmd.sfname = sfname;
9302 patcmd.tail = tail;
9303 patcmd.event = event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009304 patcmd.arg_bufnr = autocmd_bufnr;
9305 patcmd.next = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009306 auto_next_pat(&patcmd, FALSE);
9307
9308 /* found one, start executing the autocommands */
9309 if (patcmd.curpat != NULL)
9310 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009311 /* add to active_apc_list */
9312 patcmd.next = active_apc_list;
9313 active_apc_list = &patcmd;
9314
Bram Moolenaar071d4272004-06-13 20:20:40 +00009315#ifdef FEAT_EVAL
9316 /* set v:cmdarg (only when there is a matching pattern) */
9317 save_cmdbang = get_vim_var_nr(VV_CMDBANG);
9318 if (eap != NULL)
9319 {
9320 save_cmdarg = set_cmdarg(eap, NULL);
9321 set_vim_var_nr(VV_CMDBANG, (long)eap->forceit);
9322 }
9323 else
9324 save_cmdarg = NULL; /* avoid gcc warning */
9325#endif
9326 retval = TRUE;
9327 /* mark the last pattern, to avoid an endless loop when more patterns
9328 * are added when executing autocommands */
9329 for (ap = patcmd.curpat; ap->next != NULL; ap = ap->next)
9330 ap->last = FALSE;
9331 ap->last = TRUE;
9332 check_lnums(TRUE); /* make sure cursor and topline are valid */
9333 do_cmdline(NULL, getnextac, (void *)&patcmd,
9334 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
9335#ifdef FEAT_EVAL
9336 if (eap != NULL)
9337 {
9338 (void)set_cmdarg(NULL, save_cmdarg);
9339 set_vim_var_nr(VV_CMDBANG, save_cmdbang);
9340 }
9341#endif
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009342 /* delete from active_apc_list */
9343 if (active_apc_list == &patcmd) /* just in case */
9344 active_apc_list = patcmd.next;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009345 }
9346
9347 --RedrawingDisabled;
9348 autocmd_busy = save_autocmd_busy;
9349 filechangeshell_busy = FALSE;
9350 autocmd_nested = save_autocmd_nested;
9351 vim_free(sourcing_name);
9352 sourcing_name = save_sourcing_name;
9353 sourcing_lnum = save_sourcing_lnum;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009354 vim_free(autocmd_fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009355 autocmd_fname = save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009356 autocmd_fname_full = save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009357 autocmd_bufnr = save_autocmd_bufnr;
9358 autocmd_match = save_autocmd_match;
9359#ifdef FEAT_EVAL
9360 current_SID = save_current_SID;
9361 restore_funccal(save_funccalp);
Bram Moolenaar05159a02005-02-26 23:04:13 +00009362# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009363 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009364 prof_child_exit(&wait_time);
9365# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009366#endif
9367 vim_free(fname);
9368 vim_free(sfname);
9369 --nesting; /* see matching increment above */
9370
9371 /*
9372 * When stopping to execute autocommands, restore the search patterns and
9373 * the redo buffer.
9374 */
9375 if (!autocmd_busy)
9376 {
9377 restore_search_patterns();
9378 restoreRedobuff();
9379 did_filetype = FALSE;
9380 }
9381
9382 /*
9383 * Some events don't set or reset the Changed flag.
9384 * Check if still in the same buffer!
9385 */
9386 if (curbuf == old_curbuf
9387 && (event == EVENT_BUFREADPOST
9388 || event == EVENT_BUFWRITEPOST
9389 || event == EVENT_FILEAPPENDPOST
9390 || event == EVENT_VIMLEAVE
9391 || event == EVENT_VIMLEAVEPRE))
9392 {
9393#ifdef FEAT_TITLE
9394 if (curbuf->b_changed != save_changed)
9395 need_maketitle = TRUE;
9396#endif
9397 curbuf->b_changed = save_changed;
9398 }
9399
9400 au_cleanup(); /* may really delete removed patterns/commands now */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009401
9402BYPASS_AU:
9403 /* When wiping out a buffer make sure all its buffer-local autocommands
9404 * are deleted. */
9405 if (event == EVENT_BUFWIPEOUT && buf != NULL)
9406 aubuflocal_remove(buf);
9407
Bram Moolenaar071d4272004-06-13 20:20:40 +00009408 return retval;
9409}
9410
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009411# ifdef FEAT_EVAL
9412static char_u *old_termresponse = NULL;
9413# endif
9414
9415/*
9416 * Block triggering autocommands until unblock_autocmd() is called.
9417 * Can be used recursively, so long as it's symmetric.
9418 */
9419 void
9420block_autocmds()
9421{
9422# ifdef FEAT_EVAL
9423 /* Remember the value of v:termresponse. */
9424 if (autocmd_blocked == 0)
9425 old_termresponse = get_vim_var_str(VV_TERMRESPONSE);
9426# endif
9427 ++autocmd_blocked;
9428}
9429
9430 void
9431unblock_autocmds()
9432{
9433 --autocmd_blocked;
9434
9435# ifdef FEAT_EVAL
9436 /* When v:termresponse was set while autocommands were blocked, trigger
9437 * the autocommands now. Esp. useful when executing a shell command
9438 * during startup (vimdiff). */
9439 if (autocmd_blocked == 0
9440 && get_vim_var_str(VV_TERMRESPONSE) != old_termresponse)
9441 apply_autocmds(EVENT_TERMRESPONSE, NULL, NULL, FALSE, curbuf);
9442# endif
9443}
9444
Bram Moolenaar071d4272004-06-13 20:20:40 +00009445/*
9446 * Find next autocommand pattern that matches.
9447 */
9448 static void
9449auto_next_pat(apc, stop_at_last)
9450 AutoPatCmd *apc;
9451 int stop_at_last; /* stop when 'last' flag is set */
9452{
9453 AutoPat *ap;
9454 AutoCmd *cp;
9455 char_u *name;
9456 char *s;
9457
9458 vim_free(sourcing_name);
9459 sourcing_name = NULL;
9460
9461 for (ap = apc->curpat; ap != NULL && !got_int; ap = ap->next)
9462 {
9463 apc->curpat = NULL;
9464
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009465 /* Only use a pattern when it has not been removed, has commands and
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009466 * the group matches. For buffer-local autocommands only check the
9467 * buffer number. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009468 if (ap->pat != NULL && ap->cmds != NULL
9469 && (apc->group == AUGROUP_ALL || apc->group == ap->group))
9470 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009471 /* execution-condition */
9472 if (ap->buflocal_nr == 0
Bram Moolenaar748bf032005-02-02 23:04:36 +00009473 ? (match_file_pat(NULL, ap->reg_prog, apc->fname,
9474 apc->sfname, apc->tail, ap->allow_dirs))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009475 : ap->buflocal_nr == apc->arg_bufnr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009476 {
9477 name = event_nr2name(apc->event);
9478 s = _("%s Auto commands for \"%s\"");
9479 sourcing_name = alloc((unsigned)(STRLEN(s)
9480 + STRLEN(name) + ap->patlen + 1));
9481 if (sourcing_name != NULL)
9482 {
9483 sprintf((char *)sourcing_name, s,
9484 (char *)name, (char *)ap->pat);
9485 if (p_verbose >= 8)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009486 {
9487 verbose_enter();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009488 smsg((char_u *)_("Executing %s"), sourcing_name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009489 verbose_leave();
9490 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009491 }
9492
9493 apc->curpat = ap;
9494 apc->nextcmd = ap->cmds;
9495 /* mark last command */
9496 for (cp = ap->cmds; cp->next != NULL; cp = cp->next)
9497 cp->last = FALSE;
9498 cp->last = TRUE;
9499 }
9500 line_breakcheck();
9501 if (apc->curpat != NULL) /* found a match */
9502 break;
9503 }
9504 if (stop_at_last && ap->last)
9505 break;
9506 }
9507}
9508
9509/*
9510 * Get next autocommand command.
9511 * Called by do_cmdline() to get the next line for ":if".
9512 * Returns allocated string, or NULL for end of autocommands.
9513 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009514 static char_u *
9515getnextac(c, cookie, indent)
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009516 int c UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009517 void *cookie;
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009518 int indent UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009519{
9520 AutoPatCmd *acp = (AutoPatCmd *)cookie;
9521 char_u *retval;
9522 AutoCmd *ac;
9523
9524 /* Can be called again after returning the last line. */
9525 if (acp->curpat == NULL)
9526 return NULL;
9527
9528 /* repeat until we find an autocommand to execute */
9529 for (;;)
9530 {
9531 /* skip removed commands */
9532 while (acp->nextcmd != NULL && acp->nextcmd->cmd == NULL)
9533 if (acp->nextcmd->last)
9534 acp->nextcmd = NULL;
9535 else
9536 acp->nextcmd = acp->nextcmd->next;
9537
9538 if (acp->nextcmd != NULL)
9539 break;
9540
9541 /* at end of commands, find next pattern that matches */
9542 if (acp->curpat->last)
9543 acp->curpat = NULL;
9544 else
9545 acp->curpat = acp->curpat->next;
9546 if (acp->curpat != NULL)
9547 auto_next_pat(acp, TRUE);
9548 if (acp->curpat == NULL)
9549 return NULL;
9550 }
9551
9552 ac = acp->nextcmd;
9553
9554 if (p_verbose >= 9)
9555 {
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009556 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009557 smsg((char_u *)_("autocommand %s"), ac->cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009558 msg_puts((char_u *)"\n"); /* don't overwrite this either */
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009559 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009560 }
9561 retval = vim_strsave(ac->cmd);
9562 autocmd_nested = ac->nested;
9563#ifdef FEAT_EVAL
9564 current_SID = ac->scriptID;
9565#endif
9566 if (ac->last)
9567 acp->nextcmd = NULL;
9568 else
9569 acp->nextcmd = ac->next;
9570 return retval;
9571}
9572
9573/*
9574 * Return TRUE if there is a matching autocommand for "fname".
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009575 * To account for buffer-local autocommands, function needs to know
9576 * in which buffer the file will be opened.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009577 */
9578 int
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009579has_autocmd(event, sfname, buf)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009580 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009581 char_u *sfname;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009582 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009583{
9584 AutoPat *ap;
9585 char_u *fname;
9586 char_u *tail = gettail(sfname);
9587 int retval = FALSE;
9588
9589 fname = FullName_save(sfname, FALSE);
9590 if (fname == NULL)
9591 return FALSE;
9592
9593#ifdef BACKSLASH_IN_FILENAME
9594 /*
9595 * Replace all backslashes with forward slashes. This makes the
9596 * autocommand patterns portable between Unix and MS-DOS.
9597 */
9598 sfname = vim_strsave(sfname);
9599 if (sfname != NULL)
9600 forward_slash(sfname);
9601 forward_slash(fname);
9602#endif
9603
9604 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
9605 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009606 && (ap->buflocal_nr == 0
Bram Moolenaar748bf032005-02-02 23:04:36 +00009607 ? match_file_pat(NULL, ap->reg_prog,
9608 fname, sfname, tail, ap->allow_dirs)
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009609 : buf != NULL && ap->buflocal_nr == buf->b_fnum
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009610 ))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009611 {
9612 retval = TRUE;
9613 break;
9614 }
9615
9616 vim_free(fname);
9617#ifdef BACKSLASH_IN_FILENAME
9618 vim_free(sfname);
9619#endif
9620
9621 return retval;
9622}
9623
9624#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
9625/*
9626 * Function given to ExpandGeneric() to obtain the list of autocommand group
9627 * names.
9628 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009629 char_u *
9630get_augroup_name(xp, idx)
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009631 expand_T *xp UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009632 int idx;
9633{
9634 if (idx == augroups.ga_len) /* add "END" add the end */
9635 return (char_u *)"END";
9636 if (idx >= augroups.ga_len) /* end of list */
9637 return NULL;
9638 if (AUGROUP_NAME(idx) == NULL) /* skip deleted entries */
9639 return (char_u *)"";
9640 return AUGROUP_NAME(idx); /* return a name */
9641}
9642
9643static int include_groups = FALSE;
9644
9645 char_u *
9646set_context_in_autocmd(xp, arg, doautocmd)
9647 expand_T *xp;
9648 char_u *arg;
Bram Moolenaard812df62008-11-09 12:46:09 +00009649 int doautocmd; /* TRUE for :doauto*, FALSE for :autocmd */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009650{
9651 char_u *p;
9652 int group;
9653
9654 /* check for a group name, skip it if present */
9655 include_groups = FALSE;
9656 p = arg;
9657 group = au_get_grouparg(&arg);
9658 if (group == AUGROUP_ERROR)
9659 return NULL;
9660 /* If there only is a group name that's what we expand. */
9661 if (*arg == NUL && group != AUGROUP_ALL && !vim_iswhite(arg[-1]))
9662 {
9663 arg = p;
9664 group = AUGROUP_ALL;
9665 }
9666
9667 /* skip over event name */
9668 for (p = arg; *p != NUL && !vim_iswhite(*p); ++p)
9669 if (*p == ',')
9670 arg = p + 1;
9671 if (*p == NUL)
9672 {
9673 if (group == AUGROUP_ALL)
9674 include_groups = TRUE;
9675 xp->xp_context = EXPAND_EVENTS; /* expand event name */
9676 xp->xp_pattern = arg;
9677 return NULL;
9678 }
9679
9680 /* skip over pattern */
9681 arg = skipwhite(p);
9682 while (*arg && (!vim_iswhite(*arg) || arg[-1] == '\\'))
9683 arg++;
9684 if (*arg)
9685 return arg; /* expand (next) command */
9686
9687 if (doautocmd)
9688 xp->xp_context = EXPAND_FILES; /* expand file names */
9689 else
9690 xp->xp_context = EXPAND_NOTHING; /* pattern is not expanded */
9691 return NULL;
9692}
9693
9694/*
9695 * Function given to ExpandGeneric() to obtain the list of event names.
9696 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009697 char_u *
9698get_event_name(xp, idx)
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009699 expand_T *xp UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009700 int idx;
9701{
9702 if (idx < augroups.ga_len) /* First list group names, if wanted */
9703 {
9704 if (!include_groups || AUGROUP_NAME(idx) == NULL)
9705 return (char_u *)""; /* skip deleted entries */
9706 return AUGROUP_NAME(idx); /* return a name */
9707 }
9708 return (char_u *)event_names[idx - augroups.ga_len].name;
9709}
9710
9711#endif /* FEAT_CMDL_COMPL */
9712
9713/*
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009714 * Return TRUE if autocmd is supported.
9715 */
9716 int
9717autocmd_supported(name)
9718 char_u *name;
9719{
9720 char_u *p;
9721
9722 return (event_name2nr(name, &p) != NUM_EVENTS);
9723}
9724
9725/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00009726 * Return TRUE if an autocommand is defined for a group, event and
9727 * pattern: The group can be omitted to accept any group. "event" and "pattern"
9728 * can be NULL to accept any event and pattern. "pattern" can be NULL to accept
9729 * any pattern. Buffer-local patterns <buffer> or <buffer=N> are accepted.
9730 * Used for:
9731 * exists("#Group") or
9732 * exists("#Group#Event") or
9733 * exists("#Group#Event#pat") or
9734 * exists("#Event") or
9735 * exists("#Event#pat")
Bram Moolenaar071d4272004-06-13 20:20:40 +00009736 */
9737 int
Bram Moolenaar195d6352005-12-19 22:08:24 +00009738au_exists(arg)
9739 char_u *arg;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009740{
Bram Moolenaar195d6352005-12-19 22:08:24 +00009741 char_u *arg_save;
9742 char_u *pattern = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009743 char_u *event_name;
9744 char_u *p;
Bram Moolenaar754b5602006-02-09 23:53:20 +00009745 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009746 AutoPat *ap;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009747 buf_T *buflocal_buf = NULL;
Bram Moolenaar195d6352005-12-19 22:08:24 +00009748 int group;
9749 int retval = FALSE;
9750
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009751 /* Make a copy so that we can change the '#' chars to a NUL. */
Bram Moolenaar195d6352005-12-19 22:08:24 +00009752 arg_save = vim_strsave(arg);
9753 if (arg_save == NULL)
9754 return FALSE;
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009755 p = vim_strchr(arg_save, '#');
Bram Moolenaar195d6352005-12-19 22:08:24 +00009756 if (p != NULL)
9757 *p++ = NUL;
9758
9759 /* First, look for an autocmd group name */
9760 group = au_find_group(arg_save);
9761 if (group == AUGROUP_ERROR)
9762 {
9763 /* Didn't match a group name, assume the first argument is an event. */
9764 group = AUGROUP_ALL;
9765 event_name = arg_save;
9766 }
9767 else
9768 {
9769 if (p == NULL)
9770 {
9771 /* "Group": group name is present and it's recognized */
9772 retval = TRUE;
9773 goto theend;
9774 }
9775
9776 /* Must be "Group#Event" or "Group#Event#pat". */
9777 event_name = p;
9778 p = vim_strchr(event_name, '#');
9779 if (p != NULL)
9780 *p++ = NUL; /* "Group#Event#pat" */
9781 }
9782
9783 pattern = p; /* "pattern" is NULL when there is no pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009784
9785 /* find the index (enum) for the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009786 event = event_name2nr(event_name, &p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009787
9788 /* return FALSE if the event name is not recognized */
Bram Moolenaar195d6352005-12-19 22:08:24 +00009789 if (event == NUM_EVENTS)
9790 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009791
9792 /* Find the first autocommand for this event.
9793 * If there isn't any, return FALSE;
9794 * If there is one and no pattern given, return TRUE; */
9795 ap = first_autopat[(int)event];
9796 if (ap == NULL)
Bram Moolenaar195d6352005-12-19 22:08:24 +00009797 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009798
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009799 /* if pattern is "<buffer>", special handling is needed which uses curbuf */
9800 /* for pattern "<buffer=N>, fnamecmp() will work fine */
Bram Moolenaar5b7880d2009-09-11 15:24:31 +00009801 if (pattern != NULL && STRICMP(pattern, "<buffer>") == 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009802 buflocal_buf = curbuf;
9803
Bram Moolenaar071d4272004-06-13 20:20:40 +00009804 /* Check if there is an autocommand with the given pattern. */
9805 for ( ; ap != NULL; ap = ap->next)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009806 /* only use a pattern when it has not been removed and has commands. */
9807 /* For buffer-local autocommands, fnamecmp() works fine. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009808 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaar195d6352005-12-19 22:08:24 +00009809 && (group == AUGROUP_ALL || ap->group == group)
Bram Moolenaar5b7880d2009-09-11 15:24:31 +00009810 && (pattern == NULL
9811 || (buflocal_buf == NULL
9812 ? fnamecmp(ap->pat, pattern) == 0
9813 : ap->buflocal_nr == buflocal_buf->b_fnum)))
Bram Moolenaar195d6352005-12-19 22:08:24 +00009814 {
9815 retval = TRUE;
9816 break;
9817 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009818
Bram Moolenaar195d6352005-12-19 22:08:24 +00009819theend:
9820 vim_free(arg_save);
9821 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009822}
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009823
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009824#else /* FEAT_AUTOCMD */
9825
9826/*
9827 * Prepare for executing commands for (hidden) buffer "buf".
9828 * This is the non-autocommand version, it simply saves "curbuf" and sets
9829 * "curbuf" and "curwin" to match "buf".
9830 */
9831 void
9832aucmd_prepbuf(aco, buf)
9833 aco_save_T *aco; /* structure to save values in */
9834 buf_T *buf; /* new curbuf */
9835{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009836 aco->save_curbuf = curbuf;
9837 --curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009838 curbuf = buf;
9839 curwin->w_buffer = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009840 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009841}
9842
9843/*
9844 * Restore after executing commands for a (hidden) buffer.
9845 * This is the non-autocommand version.
9846 */
9847 void
9848aucmd_restbuf(aco)
9849 aco_save_T *aco; /* structure holding saved values */
9850{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009851 --curbuf->b_nwindows;
9852 curbuf = aco->save_curbuf;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009853 curwin->w_buffer = curbuf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009854 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009855}
9856
Bram Moolenaar071d4272004-06-13 20:20:40 +00009857#endif /* FEAT_AUTOCMD */
9858
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009859
Bram Moolenaar071d4272004-06-13 20:20:40 +00009860#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN) || defined(PROTO)
9861/*
Bram Moolenaar748bf032005-02-02 23:04:36 +00009862 * Try matching a filename with a "pattern" ("prog" is NULL), or use the
9863 * precompiled regprog "prog" ("pattern" is NULL). That avoids calling
9864 * vim_regcomp() often.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009865 * Used for autocommands and 'wildignore'.
9866 * Returns TRUE if there is a match, FALSE otherwise.
9867 */
9868 int
Bram Moolenaar748bf032005-02-02 23:04:36 +00009869match_file_pat(pattern, prog, fname, sfname, tail, allow_dirs)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009870 char_u *pattern; /* pattern to match with */
Bram Moolenaar748bf032005-02-02 23:04:36 +00009871 regprog_T *prog; /* pre-compiled regprog or NULL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009872 char_u *fname; /* full path of file name */
9873 char_u *sfname; /* short file name or NULL */
9874 char_u *tail; /* tail of path */
9875 int allow_dirs; /* allow matching with dir */
9876{
9877 regmatch_T regmatch;
9878 int result = FALSE;
9879#ifdef FEAT_OSFILETYPE
9880 int no_pattern = FALSE; /* TRUE if check is filetype only */
9881 char_u *type_start;
9882 char_u c;
9883 int match = FALSE;
9884#endif
9885
9886#ifdef CASE_INSENSITIVE_FILENAME
9887 regmatch.rm_ic = TRUE; /* Always ignore case */
9888#else
9889 regmatch.rm_ic = FALSE; /* Don't ever ignore case */
9890#endif
9891#ifdef FEAT_OSFILETYPE
9892 if (*pattern == '<')
9893 {
9894 /* There is a filetype condition specified with this pattern.
9895 * Check the filetype matches first. If not, don't bother with the
9896 * pattern (set regprog to NULL).
9897 * Always use magic for the regexp.
9898 */
9899
9900 for (type_start = pattern + 1; (c = *pattern); pattern++)
9901 {
9902 if ((c == ';' || c == '>') && match == FALSE)
9903 {
9904 *pattern = NUL; /* Terminate the string */
9905 match = mch_check_filetype(fname, type_start);
9906 *pattern = c; /* Restore the terminator */
9907 type_start = pattern + 1;
9908 }
9909 if (c == '>')
9910 break;
9911 }
9912
9913 /* (c should never be NUL, but check anyway) */
9914 if (match == FALSE || c == NUL)
9915 regmatch.regprog = NULL; /* Doesn't match - don't check pat. */
9916 else if (*pattern == NUL)
9917 {
9918 regmatch.regprog = NULL; /* Vim will try to free regprog later */
9919 no_pattern = TRUE; /* Always matches - don't check pat. */
9920 }
9921 else
9922 regmatch.regprog = vim_regcomp(pattern + 1, RE_MAGIC);
9923 }
9924 else
9925#endif
Bram Moolenaar748bf032005-02-02 23:04:36 +00009926 {
9927 if (prog != NULL)
9928 regmatch.regprog = prog;
9929 else
9930 regmatch.regprog = vim_regcomp(pattern, RE_MAGIC);
9931 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009932
9933 /*
9934 * Try for a match with the pattern with:
9935 * 1. the full file name, when the pattern has a '/'.
9936 * 2. the short file name, when the pattern has a '/'.
9937 * 3. the tail of the file name, when the pattern has no '/'.
9938 */
9939 if (
9940#ifdef FEAT_OSFILETYPE
9941 /* If the check is for a filetype only and we don't care
9942 * about the path then skip all the regexp stuff.
9943 */
9944 no_pattern ||
9945#endif
9946 (regmatch.regprog != NULL
9947 && ((allow_dirs
9948 && (vim_regexec(&regmatch, fname, (colnr_T)0)
9949 || (sfname != NULL
9950 && vim_regexec(&regmatch, sfname, (colnr_T)0))))
9951 || (!allow_dirs && vim_regexec(&regmatch, tail, (colnr_T)0)))))
9952 result = TRUE;
9953
Bram Moolenaar748bf032005-02-02 23:04:36 +00009954 if (prog == NULL)
9955 vim_free(regmatch.regprog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009956 return result;
9957}
9958#endif
9959
9960#if defined(FEAT_WILDIGN) || defined(PROTO)
9961/*
9962 * Return TRUE if a file matches with a pattern in "list".
9963 * "list" is a comma-separated list of patterns, like 'wildignore'.
9964 * "sfname" is the short file name or NULL, "ffname" the long file name.
9965 */
9966 int
9967match_file_list(list, sfname, ffname)
9968 char_u *list;
9969 char_u *sfname;
9970 char_u *ffname;
9971{
9972 char_u buf[100];
9973 char_u *tail;
9974 char_u *regpat;
9975 char allow_dirs;
9976 int match;
9977 char_u *p;
9978
9979 tail = gettail(sfname);
9980
9981 /* try all patterns in 'wildignore' */
9982 p = list;
9983 while (*p)
9984 {
9985 copy_option_part(&p, buf, 100, ",");
9986 regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, FALSE);
9987 if (regpat == NULL)
9988 break;
Bram Moolenaar748bf032005-02-02 23:04:36 +00009989 match = match_file_pat(regpat, NULL, ffname, sfname,
9990 tail, (int)allow_dirs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009991 vim_free(regpat);
9992 if (match)
9993 return TRUE;
9994 }
9995 return FALSE;
9996}
9997#endif
9998
9999/*
10000 * Convert the given pattern "pat" which has shell style wildcards in it, into
10001 * a regular expression, and return the result in allocated memory. If there
10002 * is a directory path separator to be matched, then TRUE is put in
10003 * allow_dirs, otherwise FALSE is put there -- webb.
10004 * Handle backslashes before special characters, like "\*" and "\ ".
10005 *
10006 * If FEAT_OSFILETYPE defined then pass initial <type> through unchanged. Eg:
10007 * '<html>myfile' becomes '<html>^myfile$' -- leonard.
10008 *
10009 * Returns NULL when out of memory.
10010 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010011 char_u *
10012file_pat_to_reg_pat(pat, pat_end, allow_dirs, no_bslash)
10013 char_u *pat;
10014 char_u *pat_end; /* first char after pattern or NULL */
10015 char *allow_dirs; /* Result passed back out in here */
Bram Moolenaar78a15312009-05-15 19:33:18 +000010016 int no_bslash UNUSED; /* Don't use a backward slash as pathsep */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010017{
10018 int size;
10019 char_u *endp;
10020 char_u *reg_pat;
10021 char_u *p;
10022 int i;
10023 int nested = 0;
10024 int add_dollar = TRUE;
10025#ifdef FEAT_OSFILETYPE
10026 int check_length = 0;
10027#endif
10028
10029 if (allow_dirs != NULL)
10030 *allow_dirs = FALSE;
10031 if (pat_end == NULL)
10032 pat_end = pat + STRLEN(pat);
10033
10034#ifdef FEAT_OSFILETYPE
10035 /* Find out how much of the string is the filetype check */
10036 if (*pat == '<')
10037 {
10038 /* Count chars until the next '>' */
10039 for (p = pat + 1; p < pat_end && *p != '>'; p++)
10040 ;
10041 if (p < pat_end)
10042 {
10043 /* Pattern is of the form <.*>.* */
10044 check_length = p - pat + 1;
10045 if (p + 1 >= pat_end)
10046 {
10047 /* The 'pattern' is a filetype check ONLY */
10048 reg_pat = (char_u *)alloc(check_length + 1);
10049 if (reg_pat != NULL)
10050 {
10051 mch_memmove(reg_pat, pat, (size_t)check_length);
10052 reg_pat[check_length] = NUL;
10053 }
10054 return reg_pat;
10055 }
10056 }
10057 /* else: there was no closing '>' - assume it was a normal pattern */
10058
10059 }
10060 pat += check_length;
10061 size = 2 + check_length;
10062#else
10063 size = 2; /* '^' at start, '$' at end */
10064#endif
10065
10066 for (p = pat; p < pat_end; p++)
10067 {
10068 switch (*p)
10069 {
10070 case '*':
10071 case '.':
10072 case ',':
10073 case '{':
10074 case '}':
10075 case '~':
10076 size += 2; /* extra backslash */
10077 break;
10078#ifdef BACKSLASH_IN_FILENAME
10079 case '\\':
10080 case '/':
10081 size += 4; /* could become "[\/]" */
10082 break;
10083#endif
10084 default:
10085 size++;
10086# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010087 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010088 {
10089 ++p;
10090 ++size;
10091 }
10092# endif
10093 break;
10094 }
10095 }
10096 reg_pat = alloc(size + 1);
10097 if (reg_pat == NULL)
10098 return NULL;
10099
10100#ifdef FEAT_OSFILETYPE
10101 /* Copy the type check in to the start. */
10102 if (check_length)
10103 mch_memmove(reg_pat, pat - check_length, (size_t)check_length);
10104 i = check_length;
10105#else
10106 i = 0;
10107#endif
10108
10109 if (pat[0] == '*')
10110 while (pat[0] == '*' && pat < pat_end - 1)
10111 pat++;
10112 else
10113 reg_pat[i++] = '^';
10114 endp = pat_end - 1;
10115 if (*endp == '*')
10116 {
10117 while (endp - pat > 0 && *endp == '*')
10118 endp--;
10119 add_dollar = FALSE;
10120 }
10121 for (p = pat; *p && nested >= 0 && p <= endp; p++)
10122 {
10123 switch (*p)
10124 {
10125 case '*':
10126 reg_pat[i++] = '.';
10127 reg_pat[i++] = '*';
Bram Moolenaar02743632005-07-25 20:42:36 +000010128 while (p[1] == '*') /* "**" matches like "*" */
10129 ++p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010130 break;
10131 case '.':
10132#ifdef RISCOS
10133 if (allow_dirs != NULL)
10134 *allow_dirs = TRUE;
10135 /* FALLTHROUGH */
10136#endif
10137 case '~':
10138 reg_pat[i++] = '\\';
10139 reg_pat[i++] = *p;
10140 break;
10141 case '?':
10142#ifdef RISCOS
10143 case '#':
10144#endif
10145 reg_pat[i++] = '.';
10146 break;
10147 case '\\':
10148 if (p[1] == NUL)
10149 break;
10150#ifdef BACKSLASH_IN_FILENAME
10151 if (!no_bslash)
10152 {
10153 /* translate:
10154 * "\x" to "\\x" e.g., "dir\file"
10155 * "\*" to "\\.*" e.g., "dir\*.c"
10156 * "\?" to "\\." e.g., "dir\??.c"
10157 * "\+" to "\+" e.g., "fileX\+.c"
10158 */
10159 if ((vim_isfilec(p[1]) || p[1] == '*' || p[1] == '?')
10160 && p[1] != '+')
10161 {
10162 reg_pat[i++] = '[';
10163 reg_pat[i++] = '\\';
10164 reg_pat[i++] = '/';
10165 reg_pat[i++] = ']';
10166 if (allow_dirs != NULL)
10167 *allow_dirs = TRUE;
10168 break;
10169 }
10170 }
10171#endif
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010172 /* Undo escaping from ExpandEscape():
10173 * foo\?bar -> foo?bar
10174 * foo\%bar -> foo%bar
10175 * foo\,bar -> foo,bar
10176 * foo\ bar -> foo bar
10177 * Don't unescape \, * and others that are also special in a
10178 * regexp. */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010179 if (*++p == '?'
10180#ifdef BACKSLASH_IN_FILENAME
10181 && no_bslash
10182#endif
10183 )
10184 reg_pat[i++] = '?';
10185 else
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010186 if (*p == ',' || *p == '%' || *p == '#' || *p == ' ')
10187 reg_pat[i++] = *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010188 else
10189 {
10190 if (allow_dirs != NULL && vim_ispathsep(*p)
10191#ifdef BACKSLASH_IN_FILENAME
10192 && (!no_bslash || *p != '\\')
10193#endif
10194 )
10195 *allow_dirs = TRUE;
10196 reg_pat[i++] = '\\';
10197 reg_pat[i++] = *p;
10198 }
10199 break;
10200#ifdef BACKSLASH_IN_FILENAME
10201 case '/':
10202 reg_pat[i++] = '[';
10203 reg_pat[i++] = '\\';
10204 reg_pat[i++] = '/';
10205 reg_pat[i++] = ']';
10206 if (allow_dirs != NULL)
10207 *allow_dirs = TRUE;
10208 break;
10209#endif
10210 case '{':
10211 reg_pat[i++] = '\\';
10212 reg_pat[i++] = '(';
10213 nested++;
10214 break;
10215 case '}':
10216 reg_pat[i++] = '\\';
10217 reg_pat[i++] = ')';
10218 --nested;
10219 break;
10220 case ',':
10221 if (nested)
10222 {
10223 reg_pat[i++] = '\\';
10224 reg_pat[i++] = '|';
10225 }
10226 else
10227 reg_pat[i++] = ',';
10228 break;
10229 default:
10230# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010231 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010232 reg_pat[i++] = *p++;
10233 else
10234# endif
10235 if (allow_dirs != NULL && vim_ispathsep(*p))
10236 *allow_dirs = TRUE;
10237 reg_pat[i++] = *p;
10238 break;
10239 }
10240 }
10241 if (add_dollar)
10242 reg_pat[i++] = '$';
10243 reg_pat[i] = NUL;
10244 if (nested != 0)
10245 {
10246 if (nested < 0)
10247 EMSG(_("E219: Missing {."));
10248 else
10249 EMSG(_("E220: Missing }."));
10250 vim_free(reg_pat);
10251 reg_pat = NULL;
10252 }
10253 return reg_pat;
10254}