blob: b0994616758395c5a5c510b5aeddaa0d8760c12a [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)
4820 {
Bram Moolenaarc0662022009-09-11 13:04:24 +00004821 size_t l = STRLEN(IObuff);
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004822 vim_snprintf((char *)IObuff + l, IOSIZE - l, _(" in line %ld;"),
4823 (long)write_info.bw_conv_error_lnum);
4824 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004825 }
4826 else if (notconverted)
4827 {
4828 STRCAT(IObuff, _("[NOT converted]"));
4829 c = TRUE;
4830 }
4831 else if (converted)
4832 {
4833 STRCAT(IObuff, _("[converted]"));
4834 c = TRUE;
4835 }
4836#endif
4837 if (device)
4838 {
4839 STRCAT(IObuff, _("[Device]"));
4840 c = TRUE;
4841 }
4842 else if (newfile)
4843 {
4844 STRCAT(IObuff, shortmess(SHM_NEW) ? _("[New]") : _("[New File]"));
4845 c = TRUE;
4846 }
4847 if (no_eol)
4848 {
4849 msg_add_eol();
4850 c = TRUE;
4851 }
4852 /* may add [unix/dos/mac] */
4853 if (msg_add_fileformat(fileformat))
4854 c = TRUE;
4855#ifdef FEAT_CRYPT
4856 if (wb_flags & FIO_ENCRYPTED)
4857 {
4858 STRCAT(IObuff, _("[crypted]"));
4859 c = TRUE;
4860 }
4861#endif
4862 msg_add_lines(c, (long)lnum, nchars); /* add line/char count */
4863 if (!shortmess(SHM_WRITE))
4864 {
4865 if (append)
4866 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended"));
4867 else
4868 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written"));
4869 }
4870
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00004871 set_keep_msg(msg_trunc_attr(IObuff, FALSE, 0), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004872 }
4873
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004874 /* When written everything correctly: reset 'modified'. Unless not
4875 * writing to the original file and '+' is not in 'cpoptions'. */
Bram Moolenaar292ad192005-12-11 21:29:51 +00004876 if (reset_changed && whole && !append
Bram Moolenaar071d4272004-06-13 20:20:40 +00004877#ifdef FEAT_MBYTE
4878 && !write_info.bw_conv_error
4879#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004880 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL)
4881 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004882 {
4883 unchanged(buf, TRUE);
4884 u_unchanged(buf);
4885 }
4886
4887 /*
4888 * If written to the current file, update the timestamp of the swap file
4889 * and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
4890 */
4891 if (overwriting)
4892 {
4893 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00004894 if (append)
4895 buf->b_flags &= ~BF_NEW;
4896 else
4897 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004898 }
4899
4900 /*
4901 * If we kept a backup until now, and we are in patch mode, then we make
4902 * the backup file our 'original' file.
4903 */
4904 if (*p_pm && dobackup)
4905 {
4906 char *org = (char *)buf_modname(
4907#ifdef SHORT_FNAME
4908 TRUE,
4909#else
4910 (buf->b_p_sn || buf->b_shortname),
4911#endif
4912 fname, p_pm, FALSE);
4913
4914 if (backup != NULL)
4915 {
4916 struct stat st;
4917
4918 /*
4919 * If the original file does not exist yet
4920 * the current backup file becomes the original file
4921 */
4922 if (org == NULL)
4923 EMSG(_("E205: Patchmode: can't save original file"));
4924 else if (mch_stat(org, &st) < 0)
4925 {
4926 vim_rename(backup, (char_u *)org);
4927 vim_free(backup); /* don't delete the file */
4928 backup = NULL;
4929#ifdef UNIX
4930 set_file_time((char_u *)org, st_old.st_atime, st_old.st_mtime);
4931#endif
4932 }
4933 }
4934 /*
4935 * If there is no backup file, remember that a (new) file was
4936 * created.
4937 */
4938 else
4939 {
4940 int empty_fd;
4941
4942 if (org == NULL
Bram Moolenaara5792f52005-11-23 21:25:05 +00004943 || (empty_fd = mch_open(org,
4944 O_CREAT | O_EXTRA | O_EXCL | O_NOFOLLOW,
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00004945 perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004946 EMSG(_("E206: patchmode: can't touch empty original file"));
4947 else
4948 close(empty_fd);
4949 }
4950 if (org != NULL)
4951 {
4952 mch_setperm((char_u *)org, mch_getperm(fname) & 0777);
4953 vim_free(org);
4954 }
4955 }
4956
4957 /*
4958 * Remove the backup unless 'backup' option is set
4959 */
4960 if (!p_bk && backup != NULL && mch_remove(backup) != 0)
4961 EMSG(_("E207: Can't delete backup file"));
4962
4963#ifdef FEAT_SUN_WORKSHOP
4964 if (usingSunWorkShop)
4965 workshop_file_saved((char *) ffname);
4966#endif
4967
4968 goto nofail;
4969
4970 /*
4971 * Finish up. We get here either after failure or success.
4972 */
4973fail:
4974 --no_wait_return; /* may wait for return now */
4975nofail:
4976
4977 /* Done saving, we accept changed buffer warnings again */
4978 buf->b_saving = FALSE;
4979
4980 vim_free(backup);
4981 if (buffer != smallbuf)
4982 vim_free(buffer);
4983#ifdef FEAT_MBYTE
4984 vim_free(fenc_tofree);
4985 vim_free(write_info.bw_conv_buf);
4986# ifdef USE_ICONV
4987 if (write_info.bw_iconv_fd != (iconv_t)-1)
4988 {
4989 iconv_close(write_info.bw_iconv_fd);
4990 write_info.bw_iconv_fd = (iconv_t)-1;
4991 }
4992# endif
4993#endif
4994#ifdef HAVE_ACL
4995 mch_free_acl(acl);
4996#endif
4997
4998 if (errmsg != NULL)
4999 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005000 int numlen = errnum != NULL ? (int)STRLEN(errnum) : 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005001
5002 attr = hl_attr(HLF_E); /* set highlight for error messages */
5003 msg_add_fname(buf,
5004#ifndef UNIX
5005 sfname
5006#else
5007 fname
5008#endif
5009 ); /* put file name in IObuff with quotes */
5010 if (STRLEN(IObuff) + STRLEN(errmsg) + numlen >= IOSIZE)
5011 IObuff[IOSIZE - STRLEN(errmsg) - numlen - 1] = NUL;
5012 /* If the error message has the form "is ...", put the error number in
5013 * front of the file name. */
5014 if (errnum != NULL)
5015 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00005016 STRMOVE(IObuff + numlen, IObuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005017 mch_memmove(IObuff, errnum, (size_t)numlen);
5018 }
5019 STRCAT(IObuff, errmsg);
5020 emsg(IObuff);
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005021 if (errmsg_allocated)
5022 vim_free(errmsg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005023
5024 retval = FAIL;
5025 if (end == 0)
5026 {
5027 MSG_PUTS_ATTR(_("\nWARNING: Original file may be lost or damaged\n"),
5028 attr | MSG_HIST);
5029 MSG_PUTS_ATTR(_("don't quit the editor until the file is successfully written!"),
5030 attr | MSG_HIST);
5031
5032 /* Update the timestamp to avoid an "overwrite changed file"
5033 * prompt when writing again. */
5034 if (mch_stat((char *)fname, &st_old) >= 0)
5035 {
5036 buf_store_time(buf, &st_old, fname);
5037 buf->b_mtime_read = buf->b_mtime;
5038 }
5039 }
5040 }
5041 msg_scroll = msg_save;
5042
Bram Moolenaar55debbe2010-05-23 23:34:36 +02005043#ifdef FEAT_PERSISTENT_UNDO
5044 /*
5045 * When writing the whole file and 'undofile' is set, also write the undo
5046 * file.
5047 */
5048 if (retval == OK && write_undo_file)
5049 {
5050 char_u hash[UNDO_HASH_SIZE];
5051
5052 sha256_finish(&sha_ctx, hash);
5053 u_write_undo(NULL, FALSE, buf, hash);
5054 }
5055#endif
5056
Bram Moolenaar071d4272004-06-13 20:20:40 +00005057#ifdef FEAT_AUTOCMD
5058#ifdef FEAT_EVAL
5059 if (!should_abort(retval))
5060#else
5061 if (!got_int)
5062#endif
5063 {
5064 aco_save_T aco;
5065
5066 write_no_eol_lnum = 0; /* in case it was set by the previous read */
5067
5068 /*
5069 * Apply POST autocommands.
5070 * Careful: The autocommands may call buf_write() recursively!
5071 */
5072 aucmd_prepbuf(&aco, buf);
5073
5074 if (append)
5075 apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname,
5076 FALSE, curbuf, eap);
5077 else if (filtering)
5078 apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname,
5079 FALSE, curbuf, eap);
5080 else if (reset_changed && whole)
5081 apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname,
5082 FALSE, curbuf, eap);
5083 else
5084 apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname,
5085 FALSE, curbuf, eap);
5086
5087 /* restore curwin/curbuf and a few other things */
5088 aucmd_restbuf(&aco);
5089
5090#ifdef FEAT_EVAL
5091 if (aborting()) /* autocmds may abort script processing */
5092 retval = FALSE;
5093#endif
5094 }
5095#endif
5096
5097 got_int |= prev_got_int;
5098
5099#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
5100 /* Update machine specific information. */
5101 mch_post_buffer_write(buf);
5102#endif
5103 return retval;
5104}
5105
5106/*
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005107 * Set the name of the current buffer. Use when the buffer doesn't have a
5108 * name and a ":r" or ":w" command with a file name is used.
5109 */
5110 static int
5111set_rw_fname(fname, sfname)
5112 char_u *fname;
5113 char_u *sfname;
5114{
5115#ifdef FEAT_AUTOCMD
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005116 buf_T *buf = curbuf;
5117
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005118 /* It's like the unnamed buffer is deleted.... */
5119 if (curbuf->b_p_bl)
5120 apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
5121 apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf);
5122# ifdef FEAT_EVAL
5123 if (aborting()) /* autocmds may abort script processing */
5124 return FAIL;
5125# endif
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005126 if (curbuf != buf)
5127 {
5128 /* We are in another buffer now, don't do the renaming. */
5129 EMSG(_(e_auchangedbuf));
5130 return FAIL;
5131 }
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005132#endif
5133
5134 if (setfname(curbuf, fname, sfname, FALSE) == OK)
5135 curbuf->b_flags |= BF_NOTEDITED;
5136
5137#ifdef FEAT_AUTOCMD
5138 /* ....and a new named one is created */
5139 apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, curbuf);
5140 if (curbuf->b_p_bl)
5141 apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf);
5142# ifdef FEAT_EVAL
5143 if (aborting()) /* autocmds may abort script processing */
5144 return FAIL;
5145# endif
5146
5147 /* Do filetype detection now if 'filetype' is empty. */
5148 if (*curbuf->b_p_ft == NUL)
5149 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005150 if (au_has_group((char_u *)"filetypedetect"))
Bram Moolenaar70836c82006-02-20 21:28:49 +00005151 (void)do_doautocmd((char_u *)"filetypedetect BufRead", FALSE);
Bram Moolenaara3227e22006-03-08 21:32:40 +00005152 do_modelines(0);
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005153 }
5154#endif
5155
5156 return OK;
5157}
5158
5159/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00005160 * Put file name into IObuff with quotes.
5161 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005162 void
Bram Moolenaar071d4272004-06-13 20:20:40 +00005163msg_add_fname(buf, fname)
5164 buf_T *buf;
5165 char_u *fname;
5166{
5167 if (fname == NULL)
5168 fname = (char_u *)"-stdin-";
5169 home_replace(buf, fname, IObuff + 1, IOSIZE - 4, TRUE);
5170 IObuff[0] = '"';
5171 STRCAT(IObuff, "\" ");
5172}
5173
5174/*
5175 * Append message for text mode to IObuff.
5176 * Return TRUE if something appended.
5177 */
5178 static int
5179msg_add_fileformat(eol_type)
5180 int eol_type;
5181{
5182#ifndef USE_CRNL
5183 if (eol_type == EOL_DOS)
5184 {
5185 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[dos]") : _("[dos format]"));
5186 return TRUE;
5187 }
5188#endif
5189#ifndef USE_CR
5190 if (eol_type == EOL_MAC)
5191 {
5192 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[mac]") : _("[mac format]"));
5193 return TRUE;
5194 }
5195#endif
5196#if defined(USE_CRNL) || defined(USE_CR)
5197 if (eol_type == EOL_UNIX)
5198 {
5199 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[unix]") : _("[unix format]"));
5200 return TRUE;
5201 }
5202#endif
5203 return FALSE;
5204}
5205
5206/*
5207 * Append line and character count to IObuff.
5208 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005209 void
Bram Moolenaar071d4272004-06-13 20:20:40 +00005210msg_add_lines(insert_space, lnum, nchars)
5211 int insert_space;
5212 long lnum;
Bram Moolenaar914703b2010-05-31 21:59:46 +02005213 off_t nchars;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005214{
5215 char_u *p;
5216
5217 p = IObuff + STRLEN(IObuff);
5218
5219 if (insert_space)
5220 *p++ = ' ';
5221 if (shortmess(SHM_LINES))
Bram Moolenaar914703b2010-05-31 21:59:46 +02005222 sprintf((char *)p,
5223#ifdef LONG_LONG_OFF_T
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005224 "%ldL, %lldC", lnum, nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005225#else
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005226 /* Explicit typecast avoids warning on Mac OS X 10.6 */
5227 "%ldL, %ldC", lnum, (long)nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005228#endif
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005229 );
Bram Moolenaar071d4272004-06-13 20:20:40 +00005230 else
5231 {
5232 if (lnum == 1)
5233 STRCPY(p, _("1 line, "));
5234 else
5235 sprintf((char *)p, _("%ld lines, "), lnum);
5236 p += STRLEN(p);
5237 if (nchars == 1)
5238 STRCPY(p, _("1 character"));
5239 else
Bram Moolenaar914703b2010-05-31 21:59:46 +02005240 sprintf((char *)p,
5241#ifdef LONG_LONG_OFF_T
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005242 _("%lld characters"), nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005243#else
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005244 /* Explicit typecast avoids warning on Mac OS X 10.6 */
5245 _("%ld characters"), (long)nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005246#endif
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005247 );
Bram Moolenaar071d4272004-06-13 20:20:40 +00005248 }
5249}
5250
5251/*
5252 * Append message for missing line separator to IObuff.
5253 */
5254 static void
5255msg_add_eol()
5256{
5257 STRCAT(IObuff, shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]"));
5258}
5259
5260/*
5261 * Check modification time of file, before writing to it.
5262 * The size isn't checked, because using a tool like "gzip" takes care of
5263 * using the same timestamp but can't set the size.
5264 */
5265 static int
5266check_mtime(buf, st)
5267 buf_T *buf;
5268 struct stat *st;
5269{
5270 if (buf->b_mtime_read != 0
5271 && time_differs((long)st->st_mtime, buf->b_mtime_read))
5272 {
5273 msg_scroll = TRUE; /* don't overwrite messages here */
5274 msg_silent = 0; /* must give this prompt */
5275 /* don't use emsg() here, don't want to flush the buffers */
5276 MSG_ATTR(_("WARNING: The file has been changed since reading it!!!"),
5277 hl_attr(HLF_E));
5278 if (ask_yesno((char_u *)_("Do you really want to write to it"),
5279 TRUE) == 'n')
5280 return FAIL;
5281 msg_scroll = FALSE; /* always overwrite the file message now */
5282 }
5283 return OK;
5284}
5285
5286 static int
5287time_differs(t1, t2)
5288 long t1, t2;
5289{
5290#if defined(__linux__) || defined(MSDOS) || defined(MSWIN)
5291 /* On a FAT filesystem, esp. under Linux, there are only 5 bits to store
5292 * the seconds. Since the roundoff is done when flushing the inode, the
5293 * time may change unexpectedly by one second!!! */
5294 return (t1 - t2 > 1 || t2 - t1 > 1);
5295#else
5296 return (t1 != t2);
5297#endif
5298}
5299
5300/*
5301 * Call write() to write a number of bytes to the file.
5302 * Also handles encryption and 'encoding' conversion.
5303 *
5304 * Return FAIL for failure, OK otherwise.
5305 */
5306 static int
5307buf_write_bytes(ip)
5308 struct bw_info *ip;
5309{
5310 int wlen;
5311 char_u *buf = ip->bw_buf; /* data to write */
5312 int len = ip->bw_len; /* length of data */
5313#ifdef HAS_BW_FLAGS
5314 int flags = ip->bw_flags; /* extra flags */
5315#endif
5316
5317#ifdef FEAT_MBYTE
5318 /*
5319 * Skip conversion when writing the crypt magic number or the BOM.
5320 */
5321 if (!(flags & FIO_NOCONVERT))
5322 {
5323 char_u *p;
5324 unsigned c;
5325 int n;
5326
5327 if (flags & FIO_UTF8)
5328 {
5329 /*
5330 * Convert latin1 in the buffer to UTF-8 in the file.
5331 */
5332 p = ip->bw_conv_buf; /* translate to buffer */
5333 for (wlen = 0; wlen < len; ++wlen)
5334 p += utf_char2bytes(buf[wlen], p);
5335 buf = ip->bw_conv_buf;
5336 len = (int)(p - ip->bw_conv_buf);
5337 }
5338 else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1))
5339 {
5340 /*
5341 * Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
5342 * Latin1 chars in the file.
5343 */
5344 if (flags & FIO_LATIN1)
5345 p = buf; /* translate in-place (can only get shorter) */
5346 else
5347 p = ip->bw_conv_buf; /* translate to buffer */
5348 for (wlen = 0; wlen < len; wlen += n)
5349 {
5350 if (wlen == 0 && ip->bw_restlen != 0)
5351 {
5352 int l;
5353
5354 /* Use remainder of previous call. Append the start of
5355 * buf[] to get a full sequence. Might still be too
5356 * short! */
5357 l = CONV_RESTLEN - ip->bw_restlen;
5358 if (l > len)
5359 l = len;
5360 mch_memmove(ip->bw_rest + ip->bw_restlen, buf, (size_t)l);
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005361 n = utf_ptr2len_len(ip->bw_rest, ip->bw_restlen + l);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005362 if (n > ip->bw_restlen + len)
5363 {
5364 /* We have an incomplete byte sequence at the end to
5365 * be written. We can't convert it without the
5366 * remaining bytes. Keep them for the next call. */
5367 if (ip->bw_restlen + len > CONV_RESTLEN)
5368 return FAIL;
5369 ip->bw_restlen += len;
5370 break;
5371 }
5372 if (n > 1)
5373 c = utf_ptr2char(ip->bw_rest);
5374 else
5375 c = ip->bw_rest[0];
5376 if (n >= ip->bw_restlen)
5377 {
5378 n -= ip->bw_restlen;
5379 ip->bw_restlen = 0;
5380 }
5381 else
5382 {
5383 ip->bw_restlen -= n;
5384 mch_memmove(ip->bw_rest, ip->bw_rest + n,
5385 (size_t)ip->bw_restlen);
5386 n = 0;
5387 }
5388 }
5389 else
5390 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005391 n = utf_ptr2len_len(buf + wlen, len - wlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005392 if (n > len - wlen)
5393 {
5394 /* We have an incomplete byte sequence at the end to
5395 * be written. We can't convert it without the
5396 * remaining bytes. Keep them for the next call. */
5397 if (len - wlen > CONV_RESTLEN)
5398 return FAIL;
5399 ip->bw_restlen = len - wlen;
5400 mch_memmove(ip->bw_rest, buf + wlen,
5401 (size_t)ip->bw_restlen);
5402 break;
5403 }
5404 if (n > 1)
5405 c = utf_ptr2char(buf + wlen);
5406 else
5407 c = buf[wlen];
5408 }
5409
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005410 if (ucs2bytes(c, &p, flags) && !ip->bw_conv_error)
5411 {
5412 ip->bw_conv_error = TRUE;
5413 ip->bw_conv_error_lnum = ip->bw_start_lnum;
5414 }
5415 if (c == NL)
5416 ++ip->bw_start_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005417 }
5418 if (flags & FIO_LATIN1)
5419 len = (int)(p - buf);
5420 else
5421 {
5422 buf = ip->bw_conv_buf;
5423 len = (int)(p - ip->bw_conv_buf);
5424 }
5425 }
5426
5427# ifdef WIN3264
5428 else if (flags & FIO_CODEPAGE)
5429 {
5430 /*
5431 * Convert UTF-8 or codepage to UCS-2 and then to MS-Windows
5432 * codepage.
5433 */
5434 char_u *from;
5435 size_t fromlen;
5436 char_u *to;
5437 int u8c;
5438 BOOL bad = FALSE;
5439 int needed;
5440
5441 if (ip->bw_restlen > 0)
5442 {
5443 /* Need to concatenate the remainder of the previous call and
5444 * the bytes of the current call. Use the end of the
5445 * conversion buffer for this. */
5446 fromlen = len + ip->bw_restlen;
5447 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5448 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5449 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5450 }
5451 else
5452 {
5453 from = buf;
5454 fromlen = len;
5455 }
5456
5457 to = ip->bw_conv_buf;
5458 if (enc_utf8)
5459 {
5460 /* Convert from UTF-8 to UCS-2, to the start of the buffer.
5461 * The buffer has been allocated to be big enough. */
5462 while (fromlen > 0)
5463 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005464 n = (int)utf_ptr2len_len(from, (int)fromlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005465 if (n > (int)fromlen) /* incomplete byte sequence */
5466 break;
5467 u8c = utf_ptr2char(from);
5468 *to++ = (u8c & 0xff);
5469 *to++ = (u8c >> 8);
5470 fromlen -= n;
5471 from += n;
5472 }
5473
5474 /* Copy remainder to ip->bw_rest[] to be used for the next
5475 * call. */
5476 if (fromlen > CONV_RESTLEN)
5477 {
5478 /* weird overlong sequence */
5479 ip->bw_conv_error = TRUE;
5480 return FAIL;
5481 }
5482 mch_memmove(ip->bw_rest, from, fromlen);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005483 ip->bw_restlen = (int)fromlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005484 }
5485 else
5486 {
5487 /* Convert from enc_codepage to UCS-2, to the start of the
5488 * buffer. The buffer has been allocated to be big enough. */
5489 ip->bw_restlen = 0;
5490 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005491 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005492 NULL, 0);
5493 if (needed == 0)
5494 {
5495 /* When conversion fails there may be a trailing byte. */
5496 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005497 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen - 1,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005498 NULL, 0);
5499 if (needed == 0)
5500 {
5501 /* Conversion doesn't work. */
5502 ip->bw_conv_error = TRUE;
5503 return FAIL;
5504 }
5505 /* Save the trailing byte for the next call. */
5506 ip->bw_rest[0] = from[fromlen - 1];
5507 ip->bw_restlen = 1;
5508 }
5509 needed = MultiByteToWideChar(enc_codepage, MB_ERR_INVALID_CHARS,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005510 (LPCSTR)from, (int)(fromlen - ip->bw_restlen),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005511 (LPWSTR)to, needed);
5512 if (needed == 0)
5513 {
5514 /* Safety check: Conversion doesn't work. */
5515 ip->bw_conv_error = TRUE;
5516 return FAIL;
5517 }
5518 to += needed * 2;
5519 }
5520
5521 fromlen = to - ip->bw_conv_buf;
5522 buf = to;
5523# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5524 if (FIO_GET_CP(flags) == CP_UTF8)
5525 {
5526 /* Convert from UCS-2 to UTF-8, using the remainder of the
5527 * conversion buffer. Fails when out of space. */
5528 for (from = ip->bw_conv_buf; fromlen > 1; fromlen -= 2)
5529 {
5530 u8c = *from++;
5531 u8c += (*from++ << 8);
5532 to += utf_char2bytes(u8c, to);
5533 if (to + 6 >= ip->bw_conv_buf + ip->bw_conv_buflen)
5534 {
5535 ip->bw_conv_error = TRUE;
5536 return FAIL;
5537 }
5538 }
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005539 len = (int)(to - buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005540 }
5541 else
5542#endif
5543 {
5544 /* Convert from UCS-2 to the codepage, using the remainder of
5545 * the conversion buffer. If the conversion uses the default
5546 * character "0", the data doesn't fit in this encoding, so
5547 * fail. */
5548 len = WideCharToMultiByte(FIO_GET_CP(flags), 0,
5549 (LPCWSTR)ip->bw_conv_buf, (int)fromlen / sizeof(WCHAR),
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005550 (LPSTR)to, (int)(ip->bw_conv_buflen - fromlen), 0,
5551 &bad);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005552 if (bad)
5553 {
5554 ip->bw_conv_error = TRUE;
5555 return FAIL;
5556 }
5557 }
5558 }
5559# endif
5560
Bram Moolenaar56718732006-03-15 22:53:57 +00005561# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00005562 else if (flags & FIO_MACROMAN)
5563 {
5564 /*
5565 * Convert UTF-8 or latin1 to Apple MacRoman.
5566 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005567 char_u *from;
5568 size_t fromlen;
5569
5570 if (ip->bw_restlen > 0)
5571 {
5572 /* Need to concatenate the remainder of the previous call and
5573 * the bytes of the current call. Use the end of the
5574 * conversion buffer for this. */
5575 fromlen = len + ip->bw_restlen;
5576 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5577 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5578 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5579 }
5580 else
5581 {
5582 from = buf;
5583 fromlen = len;
5584 }
5585
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00005586 if (enc2macroman(from, fromlen,
5587 ip->bw_conv_buf, &len, ip->bw_conv_buflen,
5588 ip->bw_rest, &ip->bw_restlen) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005589 {
5590 ip->bw_conv_error = TRUE;
5591 return FAIL;
5592 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005593 buf = ip->bw_conv_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005594 }
5595# endif
5596
5597# ifdef USE_ICONV
5598 if (ip->bw_iconv_fd != (iconv_t)-1)
5599 {
5600 const char *from;
5601 size_t fromlen;
5602 char *to;
5603 size_t tolen;
5604
5605 /* Convert with iconv(). */
5606 if (ip->bw_restlen > 0)
5607 {
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005608 char *fp;
5609
Bram Moolenaar071d4272004-06-13 20:20:40 +00005610 /* Need to concatenate the remainder of the previous call and
5611 * the bytes of the current call. Use the end of the
5612 * conversion buffer for this. */
5613 fromlen = len + ip->bw_restlen;
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005614 fp = (char *)ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5615 mch_memmove(fp, ip->bw_rest, (size_t)ip->bw_restlen);
5616 mch_memmove(fp + ip->bw_restlen, buf, (size_t)len);
5617 from = fp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005618 tolen = ip->bw_conv_buflen - fromlen;
5619 }
5620 else
5621 {
5622 from = (const char *)buf;
5623 fromlen = len;
5624 tolen = ip->bw_conv_buflen;
5625 }
5626 to = (char *)ip->bw_conv_buf;
5627
5628 if (ip->bw_first)
5629 {
5630 size_t save_len = tolen;
5631
5632 /* output the initial shift state sequence */
5633 (void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen);
5634
5635 /* There is a bug in iconv() on Linux (which appears to be
5636 * wide-spread) which sets "to" to NULL and messes up "tolen".
5637 */
5638 if (to == NULL)
5639 {
5640 to = (char *)ip->bw_conv_buf;
5641 tolen = save_len;
5642 }
5643 ip->bw_first = FALSE;
5644 }
5645
5646 /*
5647 * If iconv() has an error or there is not enough room, fail.
5648 */
5649 if ((iconv(ip->bw_iconv_fd, (void *)&from, &fromlen, &to, &tolen)
5650 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
5651 || fromlen > CONV_RESTLEN)
5652 {
5653 ip->bw_conv_error = TRUE;
5654 return FAIL;
5655 }
5656
5657 /* copy remainder to ip->bw_rest[] to be used for the next call. */
5658 if (fromlen > 0)
5659 mch_memmove(ip->bw_rest, (void *)from, fromlen);
5660 ip->bw_restlen = (int)fromlen;
5661
5662 buf = ip->bw_conv_buf;
5663 len = (int)((char_u *)to - ip->bw_conv_buf);
5664 }
5665# endif
5666 }
5667#endif /* FEAT_MBYTE */
5668
5669#ifdef FEAT_CRYPT
5670 if (flags & FIO_ENCRYPTED) /* encrypt the data */
Bram Moolenaar04c9baf2010-06-01 23:37:39 +02005671 crypt_encode(buf, len, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005672#endif
5673
5674 /* Repeat the write(), it may be interrupted by a signal. */
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005675 while (len > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005676 {
5677 wlen = vim_write(ip->bw_fd, buf, len);
5678 if (wlen <= 0) /* error! */
5679 return FAIL;
5680 len -= wlen;
5681 buf += wlen;
5682 }
5683 return OK;
5684}
5685
5686#ifdef FEAT_MBYTE
5687/*
5688 * Convert a Unicode character to bytes.
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005689 * Return TRUE for an error, FALSE when it's OK.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005690 */
5691 static int
5692ucs2bytes(c, pp, flags)
5693 unsigned c; /* in: character */
5694 char_u **pp; /* in/out: pointer to result */
5695 int flags; /* FIO_ flags */
5696{
5697 char_u *p = *pp;
5698 int error = FALSE;
5699 int cc;
5700
5701
5702 if (flags & FIO_UCS4)
5703 {
5704 if (flags & FIO_ENDIAN_L)
5705 {
5706 *p++ = c;
5707 *p++ = (c >> 8);
5708 *p++ = (c >> 16);
5709 *p++ = (c >> 24);
5710 }
5711 else
5712 {
5713 *p++ = (c >> 24);
5714 *p++ = (c >> 16);
5715 *p++ = (c >> 8);
5716 *p++ = c;
5717 }
5718 }
5719 else if (flags & (FIO_UCS2 | FIO_UTF16))
5720 {
5721 if (c >= 0x10000)
5722 {
5723 if (flags & FIO_UTF16)
5724 {
5725 /* Make two words, ten bits of the character in each. First
5726 * word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff */
5727 c -= 0x10000;
5728 if (c >= 0x100000)
5729 error = TRUE;
5730 cc = ((c >> 10) & 0x3ff) + 0xd800;
5731 if (flags & FIO_ENDIAN_L)
5732 {
5733 *p++ = cc;
5734 *p++ = ((unsigned)cc >> 8);
5735 }
5736 else
5737 {
5738 *p++ = ((unsigned)cc >> 8);
5739 *p++ = cc;
5740 }
5741 c = (c & 0x3ff) + 0xdc00;
5742 }
5743 else
5744 error = TRUE;
5745 }
5746 if (flags & FIO_ENDIAN_L)
5747 {
5748 *p++ = c;
5749 *p++ = (c >> 8);
5750 }
5751 else
5752 {
5753 *p++ = (c >> 8);
5754 *p++ = c;
5755 }
5756 }
5757 else /* Latin1 */
5758 {
5759 if (c >= 0x100)
5760 {
5761 error = TRUE;
5762 *p++ = 0xBF;
5763 }
5764 else
5765 *p++ = c;
5766 }
5767
5768 *pp = p;
5769 return error;
5770}
5771
5772/*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005773 * Return TRUE if file encoding "fenc" requires conversion from or to
5774 * 'encoding'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005775 */
5776 static int
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005777need_conversion(fenc)
5778 char_u *fenc;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005779{
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005780 int same_encoding;
5781 int enc_flags;
5782 int fenc_flags;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005783
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005784 if (*fenc == NUL || STRCMP(p_enc, fenc) == 0)
Bram Moolenaar442b4222010-05-24 21:34:22 +02005785 {
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005786 same_encoding = TRUE;
Bram Moolenaar442b4222010-05-24 21:34:22 +02005787 fenc_flags = 0;
5788 }
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005789 else
5790 {
5791 /* Ignore difference between "ansi" and "latin1", "ucs-4" and
5792 * "ucs-4be", etc. */
5793 enc_flags = get_fio_flags(p_enc);
5794 fenc_flags = get_fio_flags(fenc);
5795 same_encoding = (enc_flags != 0 && fenc_flags == enc_flags);
5796 }
5797 if (same_encoding)
5798 {
5799 /* Specified encoding matches with 'encoding'. This requires
5800 * conversion when 'encoding' is Unicode but not UTF-8. */
5801 return enc_unicode != 0;
5802 }
5803
5804 /* Encodings differ. However, conversion is not needed when 'enc' is any
5805 * Unicode encoding and the file is UTF-8. */
5806 return !(enc_utf8 && fenc_flags == FIO_UTF8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005807}
5808
5809/*
5810 * Check "ptr" for a unicode encoding and return the FIO_ flags needed for the
5811 * internal conversion.
5812 * if "ptr" is an empty string, use 'encoding'.
5813 */
5814 static int
5815get_fio_flags(ptr)
5816 char_u *ptr;
5817{
5818 int prop;
5819
5820 if (*ptr == NUL)
5821 ptr = p_enc;
5822
5823 prop = enc_canon_props(ptr);
5824 if (prop & ENC_UNICODE)
5825 {
5826 if (prop & ENC_2BYTE)
5827 {
5828 if (prop & ENC_ENDIAN_L)
5829 return FIO_UCS2 | FIO_ENDIAN_L;
5830 return FIO_UCS2;
5831 }
5832 if (prop & ENC_4BYTE)
5833 {
5834 if (prop & ENC_ENDIAN_L)
5835 return FIO_UCS4 | FIO_ENDIAN_L;
5836 return FIO_UCS4;
5837 }
5838 if (prop & ENC_2WORD)
5839 {
5840 if (prop & ENC_ENDIAN_L)
5841 return FIO_UTF16 | FIO_ENDIAN_L;
5842 return FIO_UTF16;
5843 }
5844 return FIO_UTF8;
5845 }
5846 if (prop & ENC_LATIN1)
5847 return FIO_LATIN1;
5848 /* must be ENC_DBCS, requires iconv() */
5849 return 0;
5850}
5851
5852#ifdef WIN3264
5853/*
5854 * Check "ptr" for a MS-Windows codepage name and return the FIO_ flags needed
5855 * for the conversion MS-Windows can do for us. Also accept "utf-8".
5856 * Used for conversion between 'encoding' and 'fileencoding'.
5857 */
5858 static int
5859get_win_fio_flags(ptr)
5860 char_u *ptr;
5861{
5862 int cp;
5863
5864 /* Cannot do this when 'encoding' is not utf-8 and not a codepage. */
5865 if (!enc_utf8 && enc_codepage <= 0)
5866 return 0;
5867
5868 cp = encname2codepage(ptr);
5869 if (cp == 0)
5870 {
5871# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5872 if (STRCMP(ptr, "utf-8") == 0)
5873 cp = CP_UTF8;
5874 else
5875# endif
5876 return 0;
5877 }
5878 return FIO_PUT_CP(cp) | FIO_CODEPAGE;
5879}
5880#endif
5881
5882#ifdef MACOS_X
5883/*
5884 * Check "ptr" for a Carbon supported encoding and return the FIO_ flags
5885 * needed for the internal conversion to/from utf-8 or latin1.
5886 */
5887 static int
5888get_mac_fio_flags(ptr)
5889 char_u *ptr;
5890{
5891 if ((enc_utf8 || STRCMP(p_enc, "latin1") == 0)
5892 && (enc_canon_props(ptr) & ENC_MACROMAN))
5893 return FIO_MACROMAN;
5894 return 0;
5895}
5896#endif
5897
5898/*
5899 * Check for a Unicode BOM (Byte Order Mark) at the start of p[size].
5900 * "size" must be at least 2.
5901 * Return the name of the encoding and set "*lenp" to the length.
5902 * Returns NULL when no BOM found.
5903 */
5904 static char_u *
5905check_for_bom(p, size, lenp, flags)
5906 char_u *p;
5907 long size;
5908 int *lenp;
5909 int flags;
5910{
5911 char *name = NULL;
5912 int len = 2;
5913
5914 if (p[0] == 0xef && p[1] == 0xbb && size >= 3 && p[2] == 0xbf
Bram Moolenaaree0f5a62008-07-24 20:09:16 +00005915 && (flags == FIO_ALL || flags == FIO_UTF8 || flags == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005916 {
5917 name = "utf-8"; /* EF BB BF */
5918 len = 3;
5919 }
5920 else if (p[0] == 0xff && p[1] == 0xfe)
5921 {
5922 if (size >= 4 && p[2] == 0 && p[3] == 0
5923 && (flags == FIO_ALL || flags == (FIO_UCS4 | FIO_ENDIAN_L)))
5924 {
5925 name = "ucs-4le"; /* FF FE 00 00 */
5926 len = 4;
5927 }
Bram Moolenaar223a1892008-11-11 20:57:11 +00005928 else if (flags == (FIO_UCS2 | FIO_ENDIAN_L))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005929 name = "ucs-2le"; /* FF FE */
Bram Moolenaar223a1892008-11-11 20:57:11 +00005930 else if (flags == FIO_ALL || flags == (FIO_UTF16 | FIO_ENDIAN_L))
5931 /* utf-16le is preferred, it also works for ucs-2le text */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005932 name = "utf-16le"; /* FF FE */
5933 }
5934 else if (p[0] == 0xfe && p[1] == 0xff
5935 && (flags == FIO_ALL || flags == FIO_UCS2 || flags == FIO_UTF16))
5936 {
Bram Moolenaarffd82c52008-02-20 17:15:26 +00005937 /* Default to utf-16, it works also for ucs-2 text. */
5938 if (flags == FIO_UCS2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005939 name = "ucs-2"; /* FE FF */
Bram Moolenaarffd82c52008-02-20 17:15:26 +00005940 else
5941 name = "utf-16"; /* FE FF */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005942 }
5943 else if (size >= 4 && p[0] == 0 && p[1] == 0 && p[2] == 0xfe
5944 && p[3] == 0xff && (flags == FIO_ALL || flags == FIO_UCS4))
5945 {
5946 name = "ucs-4"; /* 00 00 FE FF */
5947 len = 4;
5948 }
5949
5950 *lenp = len;
5951 return (char_u *)name;
5952}
5953
5954/*
5955 * Generate a BOM in "buf[4]" for encoding "name".
5956 * Return the length of the BOM (zero when no BOM).
5957 */
5958 static int
5959make_bom(buf, name)
5960 char_u *buf;
5961 char_u *name;
5962{
5963 int flags;
5964 char_u *p;
5965
5966 flags = get_fio_flags(name);
5967
5968 /* Can't put a BOM in a non-Unicode file. */
5969 if (flags == FIO_LATIN1 || flags == 0)
5970 return 0;
5971
5972 if (flags == FIO_UTF8) /* UTF-8 */
5973 {
5974 buf[0] = 0xef;
5975 buf[1] = 0xbb;
5976 buf[2] = 0xbf;
5977 return 3;
5978 }
5979 p = buf;
5980 (void)ucs2bytes(0xfeff, &p, flags);
5981 return (int)(p - buf);
5982}
5983#endif
5984
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00005985#if defined(FEAT_VIMINFO) || defined(FEAT_BROWSE) || \
Bram Moolenaara0174af2008-01-02 20:08:25 +00005986 defined(FEAT_QUICKFIX) || defined(FEAT_AUTOCMD) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005987/*
5988 * Try to find a shortname by comparing the fullname with the current
5989 * directory.
Bram Moolenaard089d9b2007-09-30 12:02:55 +00005990 * Returns "full_path" or pointer into "full_path" if shortened.
5991 */
5992 char_u *
5993shorten_fname1(full_path)
5994 char_u *full_path;
5995{
5996 char_u dirname[MAXPATHL];
5997 char_u *p = full_path;
5998
5999 if (mch_dirname(dirname, MAXPATHL) == OK)
6000 {
6001 p = shorten_fname(full_path, dirname);
6002 if (p == NULL || *p == NUL)
6003 p = full_path;
6004 }
6005 return p;
6006}
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00006007#endif
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006008
6009/*
6010 * Try to find a shortname by comparing the fullname with the current
6011 * directory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006012 * Returns NULL if not shorter name possible, pointer into "full_path"
6013 * otherwise.
6014 */
6015 char_u *
6016shorten_fname(full_path, dir_name)
6017 char_u *full_path;
6018 char_u *dir_name;
6019{
6020 int len;
6021 char_u *p;
6022
6023 if (full_path == NULL)
6024 return NULL;
6025 len = (int)STRLEN(dir_name);
6026 if (fnamencmp(dir_name, full_path, len) == 0)
6027 {
6028 p = full_path + len;
6029#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
6030 /*
6031 * MSDOS: when a file is in the root directory, dir_name will end in a
6032 * slash, since C: by itself does not define a specific dir. In this
6033 * case p may already be correct. <negri>
6034 */
6035 if (!((len > 2) && (*(p - 2) == ':')))
6036#endif
6037 {
6038 if (vim_ispathsep(*p))
6039 ++p;
6040#ifndef VMS /* the path separator is always part of the path */
6041 else
6042 p = NULL;
6043#endif
6044 }
6045 }
6046#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
6047 /*
6048 * When using a file in the current drive, remove the drive name:
6049 * "A:\dir\file" -> "\dir\file". This helps when moving a session file on
6050 * a floppy from "A:\dir" to "B:\dir".
6051 */
6052 else if (len > 3
6053 && TOUPPER_LOC(full_path[0]) == TOUPPER_LOC(dir_name[0])
6054 && full_path[1] == ':'
6055 && vim_ispathsep(full_path[2]))
6056 p = full_path + 2;
6057#endif
6058 else
6059 p = NULL;
6060 return p;
6061}
6062
6063/*
6064 * Shorten filenames for all buffers.
6065 * When "force" is TRUE: Use full path from now on for files currently being
6066 * edited, both for file name and swap file name. Try to shorten the file
6067 * names a bit, if safe to do so.
6068 * When "force" is FALSE: Only try to shorten absolute file names.
6069 * For buffers that have buftype "nofile" or "scratch": never change the file
6070 * name.
6071 */
6072 void
6073shorten_fnames(force)
6074 int force;
6075{
6076 char_u dirname[MAXPATHL];
6077 buf_T *buf;
6078 char_u *p;
6079
6080 mch_dirname(dirname, MAXPATHL);
6081 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
6082 {
6083 if (buf->b_fname != NULL
6084#ifdef FEAT_QUICKFIX
6085 && !bt_nofile(buf)
6086#endif
6087 && !path_with_url(buf->b_fname)
6088 && (force
6089 || buf->b_sfname == NULL
6090 || mch_isFullName(buf->b_sfname)))
6091 {
6092 vim_free(buf->b_sfname);
6093 buf->b_sfname = NULL;
6094 p = shorten_fname(buf->b_ffname, dirname);
6095 if (p != NULL)
6096 {
6097 buf->b_sfname = vim_strsave(p);
6098 buf->b_fname = buf->b_sfname;
6099 }
6100 if (p == NULL || buf->b_fname == NULL)
6101 buf->b_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006102 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00006103
6104 /* Always make the swap file name a full path, a "nofile" buffer may
6105 * also have a swap file. */
6106 mf_fullname(buf->b_ml.ml_mfp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006107 }
6108#ifdef FEAT_WINDOWS
6109 status_redraw_all();
Bram Moolenaar49d7bf12006-02-17 21:45:41 +00006110 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006111#endif
6112}
6113
6114#if (defined(FEAT_DND) && defined(FEAT_GUI_GTK)) \
6115 || defined(FEAT_GUI_MSWIN) \
6116 || defined(FEAT_GUI_MAC) \
6117 || defined(PROTO)
6118/*
6119 * Shorten all filenames in "fnames[count]" by current directory.
6120 */
6121 void
6122shorten_filenames(fnames, count)
6123 char_u **fnames;
6124 int count;
6125{
6126 int i;
6127 char_u dirname[MAXPATHL];
6128 char_u *p;
6129
6130 if (fnames == NULL || count < 1)
6131 return;
6132 mch_dirname(dirname, sizeof(dirname));
6133 for (i = 0; i < count; ++i)
6134 {
6135 if ((p = shorten_fname(fnames[i], dirname)) != NULL)
6136 {
6137 /* shorten_fname() returns pointer in given "fnames[i]". If free
6138 * "fnames[i]" first, "p" becomes invalid. So we need to copy
6139 * "p" first then free fnames[i]. */
6140 p = vim_strsave(p);
6141 vim_free(fnames[i]);
6142 fnames[i] = p;
6143 }
6144 }
6145}
6146#endif
6147
6148/*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006149 * add extension to file name - change path/fo.o.h to path/fo.o.h.ext or
Bram Moolenaar071d4272004-06-13 20:20:40 +00006150 * fo_o_h.ext for MSDOS or when shortname option set.
6151 *
6152 * Assumed that fname is a valid name found in the filesystem we assure that
6153 * the return value is a different name and ends in 'ext'.
6154 * "ext" MUST be at most 4 characters long if it starts with a dot, 3
6155 * characters otherwise.
6156 * Space for the returned name is allocated, must be freed later.
6157 * Returns NULL when out of memory.
6158 */
6159 char_u *
6160modname(fname, ext, prepend_dot)
6161 char_u *fname, *ext;
6162 int prepend_dot; /* may prepend a '.' to file name */
6163{
6164 return buf_modname(
6165#ifdef SHORT_FNAME
6166 TRUE,
6167#else
6168 (curbuf->b_p_sn || curbuf->b_shortname),
6169#endif
6170 fname, ext, prepend_dot);
6171}
6172
6173 char_u *
6174buf_modname(shortname, fname, ext, prepend_dot)
6175 int shortname; /* use 8.3 file name */
6176 char_u *fname, *ext;
6177 int prepend_dot; /* may prepend a '.' to file name */
6178{
6179 char_u *retval;
6180 char_u *s;
6181 char_u *e;
6182 char_u *ptr;
6183 int fnamelen, extlen;
6184
6185 extlen = (int)STRLEN(ext);
6186
6187 /*
6188 * If there is no file name we must get the name of the current directory
6189 * (we need the full path in case :cd is used).
6190 */
6191 if (fname == NULL || *fname == NUL)
6192 {
6193 retval = alloc((unsigned)(MAXPATHL + extlen + 3));
6194 if (retval == NULL)
6195 return NULL;
6196 if (mch_dirname(retval, MAXPATHL) == FAIL ||
6197 (fnamelen = (int)STRLEN(retval)) == 0)
6198 {
6199 vim_free(retval);
6200 return NULL;
6201 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006202 if (!after_pathsep(retval, retval + fnamelen))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006203 {
6204 retval[fnamelen++] = PATHSEP;
6205 retval[fnamelen] = NUL;
6206 }
6207#ifndef SHORT_FNAME
6208 prepend_dot = FALSE; /* nothing to prepend a dot to */
6209#endif
6210 }
6211 else
6212 {
6213 fnamelen = (int)STRLEN(fname);
6214 retval = alloc((unsigned)(fnamelen + extlen + 3));
6215 if (retval == NULL)
6216 return NULL;
6217 STRCPY(retval, fname);
6218#ifdef VMS
6219 vms_remove_version(retval); /* we do not need versions here */
6220#endif
6221 }
6222
6223 /*
6224 * search backwards until we hit a '/', '\' or ':' replacing all '.'
6225 * by '_' for MSDOS or when shortname option set and ext starts with a dot.
6226 * Then truncate what is after the '/', '\' or ':' to 8 characters for
6227 * MSDOS and 26 characters for AMIGA, a lot more for UNIX.
6228 */
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006229 for (ptr = retval + fnamelen; ptr > retval; mb_ptr_back(retval, ptr))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006230 {
6231#ifndef RISCOS
6232 if (*ext == '.'
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006233# ifdef USE_LONG_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00006234 && (!USE_LONG_FNAME || shortname)
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006235# else
6236# ifndef SHORT_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00006237 && shortname
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006238# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006239# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006240 )
6241 if (*ptr == '.') /* replace '.' by '_' */
6242 *ptr = '_';
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006243#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006244 if (vim_ispathsep(*ptr))
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006245 {
6246 ++ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006247 break;
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006248 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006249 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006250
6251 /* the file name has at most BASENAMELEN characters. */
6252#ifndef SHORT_FNAME
6253 if (STRLEN(ptr) > (unsigned)BASENAMELEN)
6254 ptr[BASENAMELEN] = '\0';
6255#endif
6256
6257 s = ptr + STRLEN(ptr);
6258
6259 /*
6260 * For 8.3 file names we may have to reduce the length.
6261 */
6262#ifdef USE_LONG_FNAME
6263 if (!USE_LONG_FNAME || shortname)
6264#else
6265# ifndef SHORT_FNAME
6266 if (shortname)
6267# endif
6268#endif
6269 {
6270 /*
6271 * If there is no file name, or the file name ends in '/', and the
6272 * extension starts with '.', put a '_' before the dot, because just
6273 * ".ext" is invalid.
6274 */
6275 if (fname == NULL || *fname == NUL
6276 || vim_ispathsep(fname[STRLEN(fname) - 1]))
6277 {
6278#ifdef RISCOS
6279 if (*ext == '/')
6280#else
6281 if (*ext == '.')
6282#endif
6283 *s++ = '_';
6284 }
6285 /*
6286 * If the extension starts with '.', truncate the base name at 8
6287 * characters
6288 */
6289#ifdef RISCOS
6290 /* We normally use '/', but swap files are '_' */
6291 else if (*ext == '/' || *ext == '_')
6292#else
6293 else if (*ext == '.')
6294#endif
6295 {
Bram Moolenaar78a15312009-05-15 19:33:18 +00006296 if ((size_t)(s - ptr) > (size_t)8)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006297 {
6298 s = ptr + 8;
6299 *s = '\0';
6300 }
6301 }
6302 /*
6303 * If the extension doesn't start with '.', and the file name
6304 * doesn't have an extension yet, append a '.'
6305 */
6306#ifdef RISCOS
6307 else if ((e = vim_strchr(ptr, '/')) == NULL)
6308 *s++ = '/';
6309#else
6310 else if ((e = vim_strchr(ptr, '.')) == NULL)
6311 *s++ = '.';
6312#endif
6313 /*
6314 * If the extension doesn't start with '.', and there already is an
Bram Moolenaar7263a772007-05-10 17:35:54 +00006315 * extension, it may need to be truncated
Bram Moolenaar071d4272004-06-13 20:20:40 +00006316 */
6317 else if ((int)STRLEN(e) + extlen > 4)
6318 s = e + 4 - extlen;
6319 }
6320#if defined(OS2) || defined(USE_LONG_FNAME) || defined(WIN3264)
6321 /*
6322 * If there is no file name, and the extension starts with '.', put a
6323 * '_' before the dot, because just ".ext" may be invalid if it's on a
6324 * FAT partition, and on HPFS it doesn't matter.
6325 */
6326 else if ((fname == NULL || *fname == NUL) && *ext == '.')
6327 *s++ = '_';
6328#endif
6329
6330 /*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006331 * Append the extension.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006332 * ext can start with '.' and cannot exceed 3 more characters.
6333 */
6334 STRCPY(s, ext);
6335
6336#ifndef SHORT_FNAME
6337 /*
6338 * Prepend the dot.
6339 */
6340 if (prepend_dot && !shortname && *(e = gettail(retval)) !=
6341#ifdef RISCOS
6342 '/'
6343#else
6344 '.'
6345#endif
6346#ifdef USE_LONG_FNAME
6347 && USE_LONG_FNAME
6348#endif
6349 )
6350 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006351 STRMOVE(e + 1, e);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006352#ifdef RISCOS
6353 *e = '/';
6354#else
6355 *e = '.';
6356#endif
6357 }
6358#endif
6359
6360 /*
6361 * Check that, after appending the extension, the file name is really
6362 * different.
6363 */
6364 if (fname != NULL && STRCMP(fname, retval) == 0)
6365 {
6366 /* we search for a character that can be replaced by '_' */
6367 while (--s >= ptr)
6368 {
6369 if (*s != '_')
6370 {
6371 *s = '_';
6372 break;
6373 }
6374 }
6375 if (s < ptr) /* fname was "________.<ext>", how tricky! */
6376 *ptr = 'v';
6377 }
6378 return retval;
6379}
6380
6381/*
6382 * Like fgets(), but if the file line is too long, it is truncated and the
6383 * rest of the line is thrown away. Returns TRUE for end-of-file.
6384 */
6385 int
6386vim_fgets(buf, size, fp)
6387 char_u *buf;
6388 int size;
6389 FILE *fp;
6390{
6391 char *eof;
6392#define FGETS_SIZE 200
6393 char tbuf[FGETS_SIZE];
6394
6395 buf[size - 2] = NUL;
6396#ifdef USE_CR
6397 eof = fgets_cr((char *)buf, size, fp);
6398#else
6399 eof = fgets((char *)buf, size, fp);
6400#endif
6401 if (buf[size - 2] != NUL && buf[size - 2] != '\n')
6402 {
6403 buf[size - 1] = NUL; /* Truncate the line */
6404
6405 /* Now throw away the rest of the line: */
6406 do
6407 {
6408 tbuf[FGETS_SIZE - 2] = NUL;
6409#ifdef USE_CR
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006410 ignoredp = fgets_cr((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006411#else
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006412 ignoredp = fgets((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006413#endif
6414 } while (tbuf[FGETS_SIZE - 2] != NUL && tbuf[FGETS_SIZE - 2] != '\n');
6415 }
6416 return (eof == NULL);
6417}
6418
6419#if defined(USE_CR) || defined(PROTO)
6420/*
6421 * Like vim_fgets(), but accept any line terminator: CR, CR-LF or LF.
6422 * Returns TRUE for end-of-file.
6423 * Only used for the Mac, because it's much slower than vim_fgets().
6424 */
6425 int
6426tag_fgets(buf, size, fp)
6427 char_u *buf;
6428 int size;
6429 FILE *fp;
6430{
6431 int i = 0;
6432 int c;
6433 int eof = FALSE;
6434
6435 for (;;)
6436 {
6437 c = fgetc(fp);
6438 if (c == EOF)
6439 {
6440 eof = TRUE;
6441 break;
6442 }
6443 if (c == '\r')
6444 {
6445 /* Always store a NL for end-of-line. */
6446 if (i < size - 1)
6447 buf[i++] = '\n';
6448 c = fgetc(fp);
6449 if (c != '\n') /* Macintosh format: single CR. */
6450 ungetc(c, fp);
6451 break;
6452 }
6453 if (i < size - 1)
6454 buf[i++] = c;
6455 if (c == '\n')
6456 break;
6457 }
6458 buf[i] = NUL;
6459 return eof;
6460}
6461#endif
6462
6463/*
6464 * rename() only works if both files are on the same file system, this
6465 * function will (attempts to?) copy the file across if rename fails -- webb
6466 * Return -1 for failure, 0 for success.
6467 */
6468 int
6469vim_rename(from, to)
6470 char_u *from;
6471 char_u *to;
6472{
6473 int fd_in;
6474 int fd_out;
6475 int n;
6476 char *errmsg = NULL;
6477 char *buffer;
6478#ifdef AMIGA
6479 BPTR flock;
6480#endif
6481 struct stat st;
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006482 long perm;
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006483#ifdef HAVE_ACL
6484 vim_acl_T acl; /* ACL from original file */
6485#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006486#if defined(UNIX) || defined(CASE_INSENSITIVE_FILENAME)
6487 int use_tmp_file = FALSE;
6488#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006489
6490 /*
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006491 * When the names are identical, there is nothing to do. When they refer
6492 * to the same file (ignoring case and slash/backslash differences) but
6493 * the file name differs we need to go through a temp file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006494 */
6495 if (fnamecmp(from, to) == 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006496 {
6497#ifdef CASE_INSENSITIVE_FILENAME
6498 if (STRCMP(gettail(from), gettail(to)) != 0)
6499 use_tmp_file = TRUE;
6500 else
6501#endif
6502 return 0;
6503 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006504
6505 /*
6506 * Fail if the "from" file doesn't exist. Avoids that "to" is deleted.
6507 */
6508 if (mch_stat((char *)from, &st) < 0)
6509 return -1;
6510
Bram Moolenaar3576da72008-12-30 15:15:57 +00006511#ifdef UNIX
6512 {
6513 struct stat st_to;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006514
6515 /* It's possible for the source and destination to be the same file.
6516 * This happens when "from" and "to" differ in case and are on a FAT32
6517 * filesystem. In that case go through a temp file name. */
6518 if (mch_stat((char *)to, &st_to) >= 0
6519 && st.st_dev == st_to.st_dev
6520 && st.st_ino == st_to.st_ino)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006521 use_tmp_file = TRUE;
6522 }
6523#endif
6524
6525#if defined(UNIX) || defined(CASE_INSENSITIVE_FILENAME)
6526 if (use_tmp_file)
6527 {
6528 char tempname[MAXPATHL + 1];
6529
6530 /*
6531 * Find a name that doesn't exist and is in the same directory.
6532 * Rename "from" to "tempname" and then rename "tempname" to "to".
6533 */
6534 if (STRLEN(from) >= MAXPATHL - 5)
6535 return -1;
6536 STRCPY(tempname, from);
6537 for (n = 123; n < 99999; ++n)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006538 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006539 sprintf((char *)gettail((char_u *)tempname), "%d", n);
6540 if (mch_stat(tempname, &st) < 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006541 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006542 if (mch_rename((char *)from, tempname) == 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006543 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006544 if (mch_rename(tempname, (char *)to) == 0)
6545 return 0;
6546 /* Strange, the second step failed. Try moving the
6547 * file back and return failure. */
6548 mch_rename(tempname, (char *)from);
Bram Moolenaar3576da72008-12-30 15:15:57 +00006549 return -1;
6550 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006551 /* If it fails for one temp name it will most likely fail
6552 * for any temp name, give up. */
6553 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006554 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006555 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006556 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006557 }
6558#endif
6559
Bram Moolenaar071d4272004-06-13 20:20:40 +00006560 /*
6561 * Delete the "to" file, this is required on some systems to make the
6562 * mch_rename() work, on other systems it makes sure that we don't have
6563 * two files when the mch_rename() fails.
6564 */
6565
6566#ifdef AMIGA
6567 /*
6568 * With MSDOS-compatible filesystems (crossdos, messydos) it is possible
6569 * that the name of the "to" file is the same as the "from" file, even
Bram Moolenaar7263a772007-05-10 17:35:54 +00006570 * though the names are different. To avoid the chance of accidentally
Bram Moolenaar071d4272004-06-13 20:20:40 +00006571 * deleting the "from" file (horror!) we lock it during the remove.
6572 *
6573 * When used for making a backup before writing the file: This should not
6574 * happen with ":w", because startscript() should detect this problem and
6575 * set buf->b_shortname, causing modname() to return a correct ".bak" file
6576 * name. This problem does exist with ":w filename", but then the
6577 * original file will be somewhere else so the backup isn't really
6578 * important. If autoscripting is off the rename may fail.
6579 */
6580 flock = Lock((UBYTE *)from, (long)ACCESS_READ);
6581#endif
6582 mch_remove(to);
6583#ifdef AMIGA
6584 if (flock)
6585 UnLock(flock);
6586#endif
6587
6588 /*
6589 * First try a normal rename, return if it works.
6590 */
6591 if (mch_rename((char *)from, (char *)to) == 0)
6592 return 0;
6593
6594 /*
6595 * Rename() failed, try copying the file.
6596 */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006597 perm = mch_getperm(from);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006598#ifdef HAVE_ACL
6599 /* For systems that support ACL: get the ACL from the original file. */
6600 acl = mch_get_acl(from);
6601#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006602 fd_in = mch_open((char *)from, O_RDONLY|O_EXTRA, 0);
6603 if (fd_in == -1)
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006604 {
6605#ifdef HAVE_ACL
6606 mch_free_acl(acl);
6607#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006608 return -1;
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006609 }
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006610
6611 /* Create the new file with same permissions as the original. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00006612 fd_out = mch_open((char *)to,
6613 O_CREAT|O_EXCL|O_WRONLY|O_EXTRA|O_NOFOLLOW, (int)perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006614 if (fd_out == -1)
6615 {
6616 close(fd_in);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006617#ifdef HAVE_ACL
6618 mch_free_acl(acl);
6619#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006620 return -1;
6621 }
6622
6623 buffer = (char *)alloc(BUFSIZE);
6624 if (buffer == NULL)
6625 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006626 close(fd_out);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006627 close(fd_in);
6628#ifdef HAVE_ACL
6629 mch_free_acl(acl);
6630#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006631 return -1;
6632 }
6633
6634 while ((n = vim_read(fd_in, buffer, BUFSIZE)) > 0)
6635 if (vim_write(fd_out, buffer, n) != n)
6636 {
6637 errmsg = _("E208: Error writing to \"%s\"");
6638 break;
6639 }
6640
6641 vim_free(buffer);
6642 close(fd_in);
6643 if (close(fd_out) < 0)
6644 errmsg = _("E209: Error closing \"%s\"");
6645 if (n < 0)
6646 {
6647 errmsg = _("E210: Error reading \"%s\"");
6648 to = from;
6649 }
Bram Moolenaar7263a772007-05-10 17:35:54 +00006650#ifndef UNIX /* for Unix mch_open() already set the permission */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006651 mch_setperm(to, perm);
Bram Moolenaarc6039d82005-12-02 00:44:04 +00006652#endif
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006653#ifdef HAVE_ACL
6654 mch_set_acl(to, acl);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006655 mch_free_acl(acl);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006656#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006657 if (errmsg != NULL)
6658 {
6659 EMSG2(errmsg, to);
6660 return -1;
6661 }
6662 mch_remove(from);
6663 return 0;
6664}
6665
6666static int already_warned = FALSE;
6667
6668/*
6669 * Check if any not hidden buffer has been changed.
6670 * Postpone the check if there are characters in the stuff buffer, a global
6671 * command is being executed, a mapping is being executed or an autocommand is
6672 * busy.
6673 * Returns TRUE if some message was written (screen should be redrawn and
6674 * cursor positioned).
6675 */
6676 int
6677check_timestamps(focus)
6678 int focus; /* called for GUI focus event */
6679{
6680 buf_T *buf;
6681 int didit = 0;
6682 int n;
6683
6684 /* Don't check timestamps while system() or another low-level function may
6685 * cause us to lose and gain focus. */
6686 if (no_check_timestamps > 0)
6687 return FALSE;
6688
6689 /* Avoid doing a check twice. The OK/Reload dialog can cause a focus
6690 * event and we would keep on checking if the file is steadily growing.
6691 * Do check again after typing something. */
6692 if (focus && did_check_timestamps)
6693 {
6694 need_check_timestamps = TRUE;
6695 return FALSE;
6696 }
6697
6698 if (!stuff_empty() || global_busy || !typebuf_typed()
6699#ifdef FEAT_AUTOCMD
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006700 || autocmd_busy || curbuf_lock > 0 || allbuf_lock > 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00006701#endif
6702 )
6703 need_check_timestamps = TRUE; /* check later */
6704 else
6705 {
6706 ++no_wait_return;
6707 did_check_timestamps = TRUE;
6708 already_warned = FALSE;
6709 for (buf = firstbuf; buf != NULL; )
6710 {
6711 /* Only check buffers in a window. */
6712 if (buf->b_nwindows > 0)
6713 {
6714 n = buf_check_timestamp(buf, focus);
6715 if (didit < n)
6716 didit = n;
6717 if (n > 0 && !buf_valid(buf))
6718 {
6719 /* Autocommands have removed the buffer, start at the
6720 * first one again. */
6721 buf = firstbuf;
6722 continue;
6723 }
6724 }
6725 buf = buf->b_next;
6726 }
6727 --no_wait_return;
6728 need_check_timestamps = FALSE;
6729 if (need_wait_return && didit == 2)
6730 {
6731 /* make sure msg isn't overwritten */
6732 msg_puts((char_u *)"\n");
6733 out_flush();
6734 }
6735 }
6736 return didit;
6737}
6738
6739/*
6740 * Move all the lines from buffer "frombuf" to buffer "tobuf".
6741 * Return OK or FAIL. When FAIL "tobuf" is incomplete and/or "frombuf" is not
6742 * empty.
6743 */
6744 static int
6745move_lines(frombuf, tobuf)
6746 buf_T *frombuf;
6747 buf_T *tobuf;
6748{
6749 buf_T *tbuf = curbuf;
6750 int retval = OK;
6751 linenr_T lnum;
6752 char_u *p;
6753
6754 /* Copy the lines in "frombuf" to "tobuf". */
6755 curbuf = tobuf;
6756 for (lnum = 1; lnum <= frombuf->b_ml.ml_line_count; ++lnum)
6757 {
6758 p = vim_strsave(ml_get_buf(frombuf, lnum, FALSE));
6759 if (p == NULL || ml_append(lnum - 1, p, 0, FALSE) == FAIL)
6760 {
6761 vim_free(p);
6762 retval = FAIL;
6763 break;
6764 }
6765 vim_free(p);
6766 }
6767
6768 /* Delete all the lines in "frombuf". */
6769 if (retval != FAIL)
6770 {
6771 curbuf = frombuf;
Bram Moolenaar9460b9d2007-01-09 14:37:01 +00006772 for (lnum = curbuf->b_ml.ml_line_count; lnum > 0; --lnum)
6773 if (ml_delete(lnum, FALSE) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006774 {
6775 /* Oops! We could try putting back the saved lines, but that
6776 * might fail again... */
6777 retval = FAIL;
6778 break;
6779 }
6780 }
6781
6782 curbuf = tbuf;
6783 return retval;
6784}
6785
6786/*
6787 * Check if buffer "buf" has been changed.
6788 * Also check if the file for a new buffer unexpectedly appeared.
6789 * return 1 if a changed buffer was found.
6790 * return 2 if a message has been displayed.
6791 * return 0 otherwise.
6792 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006793 int
6794buf_check_timestamp(buf, focus)
6795 buf_T *buf;
Bram Moolenaar78a15312009-05-15 19:33:18 +00006796 int focus UNUSED; /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006797{
6798 struct stat st;
6799 int stat_res;
6800 int retval = 0;
6801 char_u *path;
6802 char_u *tbuf;
6803 char *mesg = NULL;
Bram Moolenaar44ecf652005-03-07 23:09:59 +00006804 char *mesg2 = "";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006805 int helpmesg = FALSE;
6806 int reload = FALSE;
6807#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6808 int can_reload = FALSE;
6809#endif
Bram Moolenaar914703b2010-05-31 21:59:46 +02006810 off_t orig_size = buf->b_orig_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006811 int orig_mode = buf->b_orig_mode;
6812#ifdef FEAT_GUI
6813 int save_mouse_correct = need_mouse_correct;
6814#endif
6815#ifdef FEAT_AUTOCMD
6816 static int busy = FALSE;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006817 int n;
6818 char_u *s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006819#endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006820 char *reason;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006821
6822 /* If there is no file name, the buffer is not loaded, 'buftype' is
6823 * set, we are in the middle of a save or being called recursively: ignore
6824 * this buffer. */
6825 if (buf->b_ffname == NULL
6826 || buf->b_ml.ml_mfp == NULL
6827#if defined(FEAT_QUICKFIX)
6828 || *buf->b_p_bt != NUL
6829#endif
6830 || buf->b_saving
6831#ifdef FEAT_AUTOCMD
6832 || busy
6833#endif
Bram Moolenaar009b2592004-10-24 19:18:58 +00006834#ifdef FEAT_NETBEANS_INTG
6835 || isNetbeansBuffer(buf)
6836#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006837 )
6838 return 0;
6839
6840 if ( !(buf->b_flags & BF_NOTEDITED)
6841 && buf->b_mtime != 0
6842 && ((stat_res = mch_stat((char *)buf->b_ffname, &st)) < 0
6843 || time_differs((long)st.st_mtime, buf->b_mtime)
6844#ifdef HAVE_ST_MODE
6845 || (int)st.st_mode != buf->b_orig_mode
6846#else
6847 || mch_getperm(buf->b_ffname) != buf->b_orig_mode
6848#endif
6849 ))
6850 {
6851 retval = 1;
6852
Bram Moolenaar316059c2006-01-14 21:18:42 +00006853 /* set b_mtime to stop further warnings (e.g., when executing
6854 * FileChangedShell autocmd) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006855 if (stat_res < 0)
6856 {
6857 buf->b_mtime = 0;
6858 buf->b_orig_size = 0;
6859 buf->b_orig_mode = 0;
6860 }
6861 else
6862 buf_store_time(buf, &st, buf->b_ffname);
6863
6864 /* Don't do anything for a directory. Might contain the file
6865 * explorer. */
6866 if (mch_isdir(buf->b_fname))
6867 ;
6868
6869 /*
6870 * If 'autoread' is set, the buffer has no changes and the file still
6871 * exists, reload the buffer. Use the buffer-local option value if it
6872 * was set, the global option value otherwise.
6873 */
6874 else if ((buf->b_p_ar >= 0 ? buf->b_p_ar : p_ar)
6875 && !bufIsChanged(buf) && stat_res >= 0)
6876 reload = TRUE;
6877 else
6878 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006879 if (stat_res < 0)
6880 reason = "deleted";
6881 else if (bufIsChanged(buf))
6882 reason = "conflict";
6883 else if (orig_size != buf->b_orig_size || buf_contents_changed(buf))
6884 reason = "changed";
6885 else if (orig_mode != buf->b_orig_mode)
6886 reason = "mode";
6887 else
6888 reason = "time";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006889
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006890#ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006891 /*
6892 * Only give the warning if there are no FileChangedShell
6893 * autocommands.
6894 * Avoid being called recursively by setting "busy".
6895 */
6896 busy = TRUE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00006897# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006898 set_vim_var_string(VV_FCS_REASON, (char_u *)reason, -1);
6899 set_vim_var_string(VV_FCS_CHOICE, (char_u *)"", -1);
Bram Moolenaar1e015462005-09-25 22:16:38 +00006900# endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006901 ++allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006902 n = apply_autocmds(EVENT_FILECHANGEDSHELL,
6903 buf->b_fname, buf->b_fname, FALSE, buf);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006904 --allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006905 busy = FALSE;
6906 if (n)
6907 {
6908 if (!buf_valid(buf))
6909 EMSG(_("E246: FileChangedShell autocommand deleted buffer"));
Bram Moolenaar1e015462005-09-25 22:16:38 +00006910# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006911 s = get_vim_var_str(VV_FCS_CHOICE);
6912 if (STRCMP(s, "reload") == 0 && *reason != 'd')
6913 reload = TRUE;
6914 else if (STRCMP(s, "ask") == 0)
6915 n = FALSE;
6916 else
Bram Moolenaar1e015462005-09-25 22:16:38 +00006917# endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006918 return 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006919 }
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006920 if (!n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006921#endif
6922 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006923 if (*reason == 'd')
6924 mesg = _("E211: File \"%s\" no longer available");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006925 else
6926 {
6927 helpmesg = TRUE;
6928#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6929 can_reload = TRUE;
6930#endif
6931 /*
6932 * Check if the file contents really changed to avoid
6933 * giving a warning when only the timestamp was set (e.g.,
6934 * checked out of CVS). Always warn when the buffer was
6935 * changed.
6936 */
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006937 if (reason[2] == 'n')
6938 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006939 mesg = _("W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006940 mesg2 = _("See \":help W12\" for more info.");
6941 }
6942 else if (reason[1] == 'h')
6943 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006944 mesg = _("W11: Warning: File \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006945 mesg2 = _("See \":help W11\" for more info.");
6946 }
6947 else if (*reason == 'm')
6948 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006949 mesg = _("W16: Warning: Mode of file \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006950 mesg2 = _("See \":help W16\" for more info.");
6951 }
Bram Moolenaar85388b52009-06-24 09:58:32 +00006952 else
6953 /* Only timestamp changed, store it to avoid a warning
6954 * in check_mtime() later. */
6955 buf->b_mtime_read = buf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006956 }
6957 }
6958 }
6959
6960 }
6961 else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W)
6962 && vim_fexists(buf->b_ffname))
6963 {
6964 retval = 1;
6965 mesg = _("W13: Warning: File \"%s\" has been created after editing started");
6966 buf->b_flags |= BF_NEW_W;
6967#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6968 can_reload = TRUE;
6969#endif
6970 }
6971
6972 if (mesg != NULL)
6973 {
6974 path = home_replace_save(buf, buf->b_fname);
6975 if (path != NULL)
6976 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006977 if (!helpmesg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006978 mesg2 = "";
6979 tbuf = alloc((unsigned)(STRLEN(path) + STRLEN(mesg)
6980 + STRLEN(mesg2) + 2));
6981 sprintf((char *)tbuf, mesg, path);
Bram Moolenaar496c5262009-03-18 14:42:00 +00006982#ifdef FEAT_EVAL
6983 /* Set warningmsg here, before the unimportant and output-specific
6984 * mesg2 has been appended. */
6985 set_vim_var_string(VV_WARNINGMSG, tbuf, -1);
6986#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006987#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6988 if (can_reload)
6989 {
6990 if (*mesg2 != NUL)
6991 {
6992 STRCAT(tbuf, "\n");
6993 STRCAT(tbuf, mesg2);
6994 }
6995 if (do_dialog(VIM_WARNING, (char_u *)_("Warning"), tbuf,
6996 (char_u *)_("&OK\n&Load File"), 1, NULL) == 2)
6997 reload = TRUE;
6998 }
6999 else
7000#endif
7001 if (State > NORMAL_BUSY || (State & CMDLINE) || already_warned)
7002 {
7003 if (*mesg2 != NUL)
7004 {
7005 STRCAT(tbuf, "; ");
7006 STRCAT(tbuf, mesg2);
7007 }
7008 EMSG(tbuf);
7009 retval = 2;
7010 }
7011 else
7012 {
Bram Moolenaared203462004-06-16 11:19:22 +00007013# ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00007014 if (!autocmd_busy)
Bram Moolenaared203462004-06-16 11:19:22 +00007015# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007016 {
7017 msg_start();
7018 msg_puts_attr(tbuf, hl_attr(HLF_E) + MSG_HIST);
7019 if (*mesg2 != NUL)
7020 msg_puts_attr((char_u *)mesg2,
7021 hl_attr(HLF_W) + MSG_HIST);
7022 msg_clr_eos();
7023 (void)msg_end();
7024 if (emsg_silent == 0)
7025 {
7026 out_flush();
Bram Moolenaared203462004-06-16 11:19:22 +00007027# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00007028 if (!focus)
Bram Moolenaared203462004-06-16 11:19:22 +00007029# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007030 /* give the user some time to think about it */
7031 ui_delay(1000L, TRUE);
7032
7033 /* don't redraw and erase the message */
7034 redraw_cmdline = FALSE;
7035 }
7036 }
7037 already_warned = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007038 }
7039
7040 vim_free(path);
7041 vim_free(tbuf);
7042 }
7043 }
7044
7045 if (reload)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007046 /* Reload the buffer. */
Bram Moolenaar316059c2006-01-14 21:18:42 +00007047 buf_reload(buf, orig_mode);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007048
Bram Moolenaar56718732006-03-15 22:53:57 +00007049#ifdef FEAT_AUTOCMD
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00007050 /* Trigger FileChangedShell when the file was changed in any way. */
7051 if (buf_valid(buf) && retval != 0)
Bram Moolenaar56718732006-03-15 22:53:57 +00007052 (void)apply_autocmds(EVENT_FILECHANGEDSHELLPOST,
7053 buf->b_fname, buf->b_fname, FALSE, buf);
7054#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007055#ifdef FEAT_GUI
7056 /* restore this in case an autocommand has set it; it would break
7057 * 'mousefocus' */
7058 need_mouse_correct = save_mouse_correct;
7059#endif
7060
7061 return retval;
7062}
7063
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007064/*
7065 * Reload a buffer that is already loaded.
7066 * Used when the file was changed outside of Vim.
Bram Moolenaar316059c2006-01-14 21:18:42 +00007067 * "orig_mode" is buf->b_orig_mode before the need for reloading was detected.
7068 * buf->b_orig_mode may have been reset already.
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007069 */
7070 void
Bram Moolenaar316059c2006-01-14 21:18:42 +00007071buf_reload(buf, orig_mode)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007072 buf_T *buf;
Bram Moolenaar316059c2006-01-14 21:18:42 +00007073 int orig_mode;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007074{
7075 exarg_T ea;
7076 pos_T old_cursor;
7077 linenr_T old_topline;
7078 int old_ro = buf->b_p_ro;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007079 buf_T *savebuf;
7080 int saved = OK;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007081 aco_save_T aco;
7082
7083 /* set curwin/curbuf for "buf" and save some things */
7084 aucmd_prepbuf(&aco, buf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007085
7086 /* We only want to read the text from the file, not reset the syntax
7087 * highlighting, clear marks, diff status, etc. Force the fileformat
7088 * and encoding to be the same. */
7089 if (prep_exarg(&ea, buf) == OK)
7090 {
7091 old_cursor = curwin->w_cursor;
7092 old_topline = curwin->w_topline;
7093
7094 /*
7095 * To behave like when a new file is edited (matters for
7096 * BufReadPost autocommands) we first need to delete the current
7097 * buffer contents. But if reading the file fails we should keep
7098 * the old contents. Can't use memory only, the file might be
7099 * too big. Use a hidden buffer to move the buffer contents to.
7100 */
7101 if (bufempty())
7102 savebuf = NULL;
7103 else
7104 {
7105 /* Allocate a buffer without putting it in the buffer list. */
7106 savebuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007107 if (savebuf != NULL && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007108 {
7109 /* Open the memline. */
7110 curbuf = savebuf;
7111 curwin->w_buffer = savebuf;
Bram Moolenaar4770d092006-01-12 23:22:24 +00007112 saved = ml_open(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007113 curbuf = buf;
7114 curwin->w_buffer = buf;
7115 }
Bram Moolenaar8424a622006-04-19 21:23:36 +00007116 if (savebuf == NULL || saved == FAIL || buf != curbuf
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007117 || move_lines(buf, savebuf) == FAIL)
7118 {
7119 EMSG2(_("E462: Could not prepare for reloading \"%s\""),
7120 buf->b_fname);
7121 saved = FAIL;
7122 }
7123 }
7124
7125 if (saved == OK)
7126 {
7127 curbuf->b_flags |= BF_CHECK_RO; /* check for RO again */
7128#ifdef FEAT_AUTOCMD
7129 keep_filetype = TRUE; /* don't detect 'filetype' */
7130#endif
7131 if (readfile(buf->b_ffname, buf->b_fname, (linenr_T)0,
7132 (linenr_T)0,
7133 (linenr_T)MAXLNUM, &ea, READ_NEW) == FAIL)
7134 {
7135#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
7136 if (!aborting())
7137#endif
7138 EMSG2(_("E321: Could not reload \"%s\""), buf->b_fname);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007139 if (savebuf != NULL && buf_valid(savebuf) && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007140 {
7141 /* Put the text back from the save buffer. First
7142 * delete any lines that readfile() added. */
7143 while (!bufempty())
Bram Moolenaar8424a622006-04-19 21:23:36 +00007144 if (ml_delete(buf->b_ml.ml_line_count, FALSE) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007145 break;
7146 (void)move_lines(savebuf, buf);
7147 }
7148 }
Bram Moolenaar8424a622006-04-19 21:23:36 +00007149 else if (buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007150 {
7151 /* Mark the buffer as unmodified and free undo info. */
7152 unchanged(buf, TRUE);
7153 u_blockfree(buf);
7154 u_clearall(buf);
7155 }
7156 }
7157 vim_free(ea.cmd);
7158
Bram Moolenaar8424a622006-04-19 21:23:36 +00007159 if (savebuf != NULL && buf_valid(savebuf))
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007160 wipe_buffer(savebuf, FALSE);
7161
7162#ifdef FEAT_DIFF
7163 /* Invalidate diff info if necessary. */
Bram Moolenaar8424a622006-04-19 21:23:36 +00007164 diff_invalidate(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007165#endif
7166
7167 /* Restore the topline and cursor position and check it (lines may
7168 * have been removed). */
7169 if (old_topline > curbuf->b_ml.ml_line_count)
7170 curwin->w_topline = curbuf->b_ml.ml_line_count;
7171 else
7172 curwin->w_topline = old_topline;
7173 curwin->w_cursor = old_cursor;
7174 check_cursor();
7175 update_topline();
7176#ifdef FEAT_AUTOCMD
7177 keep_filetype = FALSE;
7178#endif
7179#ifdef FEAT_FOLDING
7180 {
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007181 win_T *wp;
7182 tabpage_T *tp;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007183
7184 /* Update folds unless they are defined manually. */
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007185 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007186 if (wp->w_buffer == curwin->w_buffer
7187 && !foldmethodIsManual(wp))
7188 foldUpdateAll(wp);
7189 }
7190#endif
7191 /* If the mode didn't change and 'readonly' was set, keep the old
7192 * value; the user probably used the ":view" command. But don't
7193 * reset it, might have had a read error. */
7194 if (orig_mode == curbuf->b_orig_mode)
7195 curbuf->b_p_ro |= old_ro;
7196 }
7197
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007198 /* restore curwin/curbuf and a few other things */
7199 aucmd_restbuf(&aco);
7200 /* Careful: autocommands may have made "buf" invalid! */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007201}
7202
Bram Moolenaar071d4272004-06-13 20:20:40 +00007203 void
7204buf_store_time(buf, st, fname)
7205 buf_T *buf;
7206 struct stat *st;
Bram Moolenaar78a15312009-05-15 19:33:18 +00007207 char_u *fname UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007208{
7209 buf->b_mtime = (long)st->st_mtime;
Bram Moolenaar914703b2010-05-31 21:59:46 +02007210 buf->b_orig_size = st->st_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007211#ifdef HAVE_ST_MODE
7212 buf->b_orig_mode = (int)st->st_mode;
7213#else
7214 buf->b_orig_mode = mch_getperm(fname);
7215#endif
7216}
7217
7218/*
7219 * Adjust the line with missing eol, used for the next write.
7220 * Used for do_filter(), when the input lines for the filter are deleted.
7221 */
7222 void
7223write_lnum_adjust(offset)
7224 linenr_T offset;
7225{
Bram Moolenaardf177f62005-02-22 08:39:57 +00007226 if (write_no_eol_lnum != 0) /* only if there is a missing eol */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007227 write_no_eol_lnum += offset;
7228}
7229
7230#if defined(TEMPDIRNAMES) || defined(PROTO)
7231static long temp_count = 0; /* Temp filename counter. */
7232
7233/*
7234 * Delete the temp directory and all files it contains.
7235 */
7236 void
7237vim_deltempdir()
7238{
7239 char_u **files;
7240 int file_count;
7241 int i;
7242
7243 if (vim_tempdir != NULL)
7244 {
7245 sprintf((char *)NameBuff, "%s*", vim_tempdir);
7246 if (gen_expand_wildcards(1, &NameBuff, &file_count, &files,
7247 EW_DIR|EW_FILE|EW_SILENT) == OK)
7248 {
7249 for (i = 0; i < file_count; ++i)
7250 mch_remove(files[i]);
7251 FreeWild(file_count, files);
7252 }
7253 gettail(NameBuff)[-1] = NUL;
7254 (void)mch_rmdir(NameBuff);
7255
7256 vim_free(vim_tempdir);
7257 vim_tempdir = NULL;
7258 }
7259}
7260#endif
7261
Bram Moolenaar4592dee2009-11-18 19:11:58 +00007262#ifdef TEMPDIRNAMES
Bram Moolenaar071d4272004-06-13 20:20:40 +00007263/*
Bram Moolenaareaf03392009-11-17 11:08:52 +00007264 * Directory "tempdir" was created. Expand this name to a full path and put
7265 * it in "vim_tempdir". This avoids that using ":cd" would confuse us.
7266 * "tempdir" must be no longer than MAXPATHL.
7267 */
7268 static void
7269vim_settempdir(tempdir)
7270 char_u *tempdir;
7271{
7272 char_u *buf;
7273
7274 buf = alloc((unsigned)MAXPATHL + 2);
7275 if (buf != NULL)
7276 {
7277 if (vim_FullName(tempdir, buf, MAXPATHL, FALSE) == FAIL)
7278 STRCPY(buf, tempdir);
7279# ifdef __EMX__
7280 if (vim_strchr(buf, '/') != NULL)
7281 STRCAT(buf, "/");
7282 else
7283# endif
7284 add_pathsep(buf);
7285 vim_tempdir = vim_strsave(buf);
7286 vim_free(buf);
7287 }
7288}
Bram Moolenaar4592dee2009-11-18 19:11:58 +00007289#endif
Bram Moolenaareaf03392009-11-17 11:08:52 +00007290
7291/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007292 * vim_tempname(): Return a unique name that can be used for a temp file.
7293 *
7294 * The temp file is NOT created.
7295 *
7296 * The returned pointer is to allocated memory.
7297 * The returned pointer is NULL if no valid name was found.
7298 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007299 char_u *
7300vim_tempname(extra_char)
Bram Moolenaar78a15312009-05-15 19:33:18 +00007301 int extra_char UNUSED; /* char to use in the name instead of '?' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007302{
7303#ifdef USE_TMPNAM
7304 char_u itmp[L_tmpnam]; /* use tmpnam() */
7305#else
7306 char_u itmp[TEMPNAMELEN];
7307#endif
7308
7309#ifdef TEMPDIRNAMES
7310 static char *(tempdirs[]) = {TEMPDIRNAMES};
7311 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007312# ifndef EEXIST
7313 struct stat st;
7314# endif
7315
7316 /*
7317 * This will create a directory for private use by this instance of Vim.
7318 * This is done once, and the same directory is used for all temp files.
7319 * This method avoids security problems because of symlink attacks et al.
7320 * It's also a bit faster, because we only need to check for an existing
7321 * file when creating the directory and not for each temp file.
7322 */
7323 if (vim_tempdir == NULL)
7324 {
7325 /*
7326 * Try the entries in TEMPDIRNAMES to create the temp directory.
7327 */
Bram Moolenaar78a15312009-05-15 19:33:18 +00007328 for (i = 0; i < (int)(sizeof(tempdirs) / sizeof(char *)); ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007329 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007330# ifndef HAVE_MKDTEMP
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007331 size_t itmplen;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007332 long nr;
7333 long off;
7334# endif
7335
Bram Moolenaar071d4272004-06-13 20:20:40 +00007336 /* expand $TMP, leave room for "/v1100000/999999999" */
7337 expand_env((char_u *)tempdirs[i], itmp, TEMPNAMELEN - 20);
7338 if (mch_isdir(itmp)) /* directory exists */
7339 {
7340# ifdef __EMX__
7341 /* If $TMP contains a forward slash (perhaps using bash or
7342 * tcsh), don't add a backslash, use a forward slash!
7343 * Adding 2 backslashes didn't work. */
7344 if (vim_strchr(itmp, '/') != NULL)
7345 STRCAT(itmp, "/");
7346 else
7347# endif
7348 add_pathsep(itmp);
7349
Bram Moolenaareaf03392009-11-17 11:08:52 +00007350# ifdef HAVE_MKDTEMP
7351 /* Leave room for filename */
7352 STRCAT(itmp, "vXXXXXX");
7353 if (mkdtemp((char *)itmp) != NULL)
7354 vim_settempdir(itmp);
7355# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007356 /* Get an arbitrary number of up to 6 digits. When it's
7357 * unlikely that it already exists it will be faster,
7358 * otherwise it doesn't matter. The use of mkdir() avoids any
7359 * security problems because of the predictable number. */
7360 nr = (mch_get_pid() + (long)time(NULL)) % 1000000L;
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007361 itmplen = STRLEN(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007362
7363 /* Try up to 10000 different values until we find a name that
7364 * doesn't exist. */
7365 for (off = 0; off < 10000L; ++off)
7366 {
7367 int r;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007368# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007369 mode_t umask_save;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007370# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007371
Bram Moolenaareaf03392009-11-17 11:08:52 +00007372 sprintf((char *)itmp + itmplen, "v%ld", nr + off);
7373# ifndef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007374 /* If mkdir() does not set errno to EEXIST, check for
7375 * existing file here. There is a race condition then,
7376 * although it's fail-safe. */
7377 if (mch_stat((char *)itmp, &st) >= 0)
7378 continue;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007379# endif
7380# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007381 /* Make sure the umask doesn't remove the executable bit.
7382 * "repl" has been reported to use "177". */
7383 umask_save = umask(077);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007384# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007385 r = vim_mkdir(itmp, 0700);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007386# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007387 (void)umask(umask_save);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007388# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007389 if (r == 0)
7390 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007391 vim_settempdir(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007392 break;
7393 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007394# ifdef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007395 /* If the mkdir() didn't fail because the file/dir exists,
7396 * we probably can't create any dir here, try another
7397 * place. */
7398 if (errno != EEXIST)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007399# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007400 break;
7401 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007402# endif /* HAVE_MKDTEMP */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007403 if (vim_tempdir != NULL)
7404 break;
7405 }
7406 }
7407 }
7408
7409 if (vim_tempdir != NULL)
7410 {
7411 /* There is no need to check if the file exists, because we own the
7412 * directory and nobody else creates a file in it. */
7413 sprintf((char *)itmp, "%s%ld", vim_tempdir, temp_count++);
7414 return vim_strsave(itmp);
7415 }
7416
7417 return NULL;
7418
7419#else /* TEMPDIRNAMES */
7420
7421# ifdef WIN3264
7422 char szTempFile[_MAX_PATH + 1];
7423 char buf4[4];
7424 char_u *retval;
7425 char_u *p;
7426
7427 STRCPY(itmp, "");
7428 if (GetTempPath(_MAX_PATH, szTempFile) == 0)
7429 szTempFile[0] = NUL; /* GetTempPath() failed, use current dir */
7430 strcpy(buf4, "VIM");
7431 buf4[2] = extra_char; /* make it "VIa", "VIb", etc. */
7432 if (GetTempFileName(szTempFile, buf4, 0, itmp) == 0)
7433 return NULL;
7434 /* GetTempFileName() will create the file, we don't want that */
7435 (void)DeleteFile(itmp);
7436
7437 /* Backslashes in a temp file name cause problems when filtering with
7438 * "sh". NOTE: This also checks 'shellcmdflag' to help those people who
7439 * didn't set 'shellslash'. */
7440 retval = vim_strsave(itmp);
7441 if (*p_shcf == '-' || p_ssl)
7442 for (p = retval; *p; ++p)
7443 if (*p == '\\')
7444 *p = '/';
7445 return retval;
7446
7447# else /* WIN3264 */
7448
7449# ifdef USE_TMPNAM
7450 /* tmpnam() will make its own name */
7451 if (*tmpnam((char *)itmp) == NUL)
7452 return NULL;
7453# else
7454 char_u *p;
7455
7456# ifdef VMS_TEMPNAM
7457 /* mktemp() is not working on VMS. It seems to be
7458 * a do-nothing function. Therefore we use tempnam().
7459 */
7460 sprintf((char *)itmp, "VIM%c", extra_char);
7461 p = (char_u *)tempnam("tmp:", (char *)itmp);
7462 if (p != NULL)
7463 {
7464 /* VMS will use '.LOG' if we don't explicitly specify an extension,
7465 * and VIM will then be unable to find the file later */
7466 STRCPY(itmp, p);
7467 STRCAT(itmp, ".txt");
7468 free(p);
7469 }
7470 else
7471 return NULL;
7472# else
7473 STRCPY(itmp, TEMPNAME);
7474 if ((p = vim_strchr(itmp, '?')) != NULL)
7475 *p = extra_char;
7476 if (mktemp((char *)itmp) == NULL)
7477 return NULL;
7478# endif
7479# endif
7480
7481 return vim_strsave(itmp);
7482# endif /* WIN3264 */
7483#endif /* TEMPDIRNAMES */
7484}
7485
7486#if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
7487/*
7488 * Convert all backslashes in fname to forward slashes in-place.
7489 */
7490 void
7491forward_slash(fname)
7492 char_u *fname;
7493{
7494 char_u *p;
7495
7496 for (p = fname; *p != NUL; ++p)
7497# ifdef FEAT_MBYTE
7498 /* The Big5 encoding can have '\' in the trail byte. */
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00007499 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007500 ++p;
7501 else
7502# endif
7503 if (*p == '\\')
7504 *p = '/';
7505}
7506#endif
7507
7508
7509/*
7510 * Code for automatic commands.
7511 *
7512 * Only included when "FEAT_AUTOCMD" has been defined.
7513 */
7514
7515#if defined(FEAT_AUTOCMD) || defined(PROTO)
7516
7517/*
7518 * The autocommands are stored in a list for each event.
7519 * Autocommands for the same pattern, that are consecutive, are joined
7520 * together, to avoid having to match the pattern too often.
7521 * The result is an array of Autopat lists, which point to AutoCmd lists:
7522 *
7523 * first_autopat[0] --> Autopat.next --> Autopat.next --> NULL
7524 * Autopat.cmds Autopat.cmds
7525 * | |
7526 * V V
7527 * AutoCmd.next AutoCmd.next
7528 * | |
7529 * V V
7530 * AutoCmd.next NULL
7531 * |
7532 * V
7533 * NULL
7534 *
7535 * first_autopat[1] --> Autopat.next --> NULL
7536 * Autopat.cmds
7537 * |
7538 * V
7539 * AutoCmd.next
7540 * |
7541 * V
7542 * NULL
7543 * etc.
7544 *
7545 * The order of AutoCmds is important, this is the order in which they were
7546 * defined and will have to be executed.
7547 */
7548typedef struct AutoCmd
7549{
7550 char_u *cmd; /* The command to be executed (NULL
7551 when command has been removed) */
7552 char nested; /* If autocommands nest here */
7553 char last; /* last command in list */
7554#ifdef FEAT_EVAL
7555 scid_T scriptID; /* script ID where defined */
7556#endif
7557 struct AutoCmd *next; /* Next AutoCmd in list */
7558} AutoCmd;
7559
7560typedef struct AutoPat
7561{
7562 int group; /* group ID */
7563 char_u *pat; /* pattern as typed (NULL when pattern
7564 has been removed) */
7565 int patlen; /* strlen() of pat */
Bram Moolenaar748bf032005-02-02 23:04:36 +00007566 regprog_T *reg_prog; /* compiled regprog for pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007567 char allow_dirs; /* Pattern may match whole path */
7568 char last; /* last pattern for apply_autocmds() */
7569 AutoCmd *cmds; /* list of commands to do */
7570 struct AutoPat *next; /* next AutoPat in AutoPat list */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007571 int buflocal_nr; /* !=0 for buffer-local AutoPat */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007572} AutoPat;
7573
7574static struct event_name
7575{
7576 char *name; /* event name */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007577 event_T event; /* event number */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007578} event_names[] =
7579{
7580 {"BufAdd", EVENT_BUFADD},
7581 {"BufCreate", EVENT_BUFADD},
7582 {"BufDelete", EVENT_BUFDELETE},
7583 {"BufEnter", EVENT_BUFENTER},
7584 {"BufFilePost", EVENT_BUFFILEPOST},
7585 {"BufFilePre", EVENT_BUFFILEPRE},
7586 {"BufHidden", EVENT_BUFHIDDEN},
7587 {"BufLeave", EVENT_BUFLEAVE},
7588 {"BufNew", EVENT_BUFNEW},
7589 {"BufNewFile", EVENT_BUFNEWFILE},
7590 {"BufRead", EVENT_BUFREADPOST},
7591 {"BufReadCmd", EVENT_BUFREADCMD},
7592 {"BufReadPost", EVENT_BUFREADPOST},
7593 {"BufReadPre", EVENT_BUFREADPRE},
7594 {"BufUnload", EVENT_BUFUNLOAD},
7595 {"BufWinEnter", EVENT_BUFWINENTER},
7596 {"BufWinLeave", EVENT_BUFWINLEAVE},
7597 {"BufWipeout", EVENT_BUFWIPEOUT},
7598 {"BufWrite", EVENT_BUFWRITEPRE},
7599 {"BufWritePost", EVENT_BUFWRITEPOST},
7600 {"BufWritePre", EVENT_BUFWRITEPRE},
7601 {"BufWriteCmd", EVENT_BUFWRITECMD},
7602 {"CmdwinEnter", EVENT_CMDWINENTER},
7603 {"CmdwinLeave", EVENT_CMDWINLEAVE},
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007604 {"ColorScheme", EVENT_COLORSCHEME},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007605 {"CursorHold", EVENT_CURSORHOLD},
7606 {"CursorHoldI", EVENT_CURSORHOLDI},
7607 {"CursorMoved", EVENT_CURSORMOVED},
7608 {"CursorMovedI", EVENT_CURSORMOVEDI},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007609 {"EncodingChanged", EVENT_ENCODINGCHANGED},
7610 {"FileEncoding", EVENT_ENCODINGCHANGED},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007611 {"FileAppendPost", EVENT_FILEAPPENDPOST},
7612 {"FileAppendPre", EVENT_FILEAPPENDPRE},
7613 {"FileAppendCmd", EVENT_FILEAPPENDCMD},
7614 {"FileChangedShell",EVENT_FILECHANGEDSHELL},
Bram Moolenaar56718732006-03-15 22:53:57 +00007615 {"FileChangedShellPost",EVENT_FILECHANGEDSHELLPOST},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007616 {"FileChangedRO", EVENT_FILECHANGEDRO},
7617 {"FileReadPost", EVENT_FILEREADPOST},
7618 {"FileReadPre", EVENT_FILEREADPRE},
7619 {"FileReadCmd", EVENT_FILEREADCMD},
7620 {"FileType", EVENT_FILETYPE},
7621 {"FileWritePost", EVENT_FILEWRITEPOST},
7622 {"FileWritePre", EVENT_FILEWRITEPRE},
7623 {"FileWriteCmd", EVENT_FILEWRITECMD},
7624 {"FilterReadPost", EVENT_FILTERREADPOST},
7625 {"FilterReadPre", EVENT_FILTERREADPRE},
7626 {"FilterWritePost", EVENT_FILTERWRITEPOST},
7627 {"FilterWritePre", EVENT_FILTERWRITEPRE},
7628 {"FocusGained", EVENT_FOCUSGAINED},
7629 {"FocusLost", EVENT_FOCUSLOST},
7630 {"FuncUndefined", EVENT_FUNCUNDEFINED},
7631 {"GUIEnter", EVENT_GUIENTER},
Bram Moolenaar265e5072006-08-29 16:13:22 +00007632 {"GUIFailed", EVENT_GUIFAILED},
Bram Moolenaar843ee412004-06-30 16:16:41 +00007633 {"InsertChange", EVENT_INSERTCHANGE},
7634 {"InsertEnter", EVENT_INSERTENTER},
7635 {"InsertLeave", EVENT_INSERTLEAVE},
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00007636 {"MenuPopup", EVENT_MENUPOPUP},
Bram Moolenaar7c626922005-02-07 22:01:03 +00007637 {"QuickFixCmdPost", EVENT_QUICKFIXCMDPOST},
7638 {"QuickFixCmdPre", EVENT_QUICKFIXCMDPRE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007639 {"RemoteReply", EVENT_REMOTEREPLY},
Bram Moolenaar9372a112005-12-06 19:59:18 +00007640 {"SessionLoadPost", EVENT_SESSIONLOADPOST},
Bram Moolenaar5c4bab02006-03-10 21:37:46 +00007641 {"ShellCmdPost", EVENT_SHELLCMDPOST},
7642 {"ShellFilterPost", EVENT_SHELLFILTERPOST},
Bram Moolenaara2031822006-03-07 22:29:51 +00007643 {"SourcePre", EVENT_SOURCEPRE},
Bram Moolenaar8dd1aa52007-01-16 20:33:19 +00007644 {"SourceCmd", EVENT_SOURCECMD},
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00007645 {"SpellFileMissing",EVENT_SPELLFILEMISSING},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007646 {"StdinReadPost", EVENT_STDINREADPOST},
7647 {"StdinReadPre", EVENT_STDINREADPRE},
Bram Moolenaarb815dac2005-12-07 20:59:24 +00007648 {"SwapExists", EVENT_SWAPEXISTS},
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00007649 {"Syntax", EVENT_SYNTAX},
Bram Moolenaar70836c82006-02-20 21:28:49 +00007650 {"TabEnter", EVENT_TABENTER},
7651 {"TabLeave", EVENT_TABLEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007652 {"TermChanged", EVENT_TERMCHANGED},
7653 {"TermResponse", EVENT_TERMRESPONSE},
7654 {"User", EVENT_USER},
7655 {"VimEnter", EVENT_VIMENTER},
7656 {"VimLeave", EVENT_VIMLEAVE},
7657 {"VimLeavePre", EVENT_VIMLEAVEPRE},
7658 {"WinEnter", EVENT_WINENTER},
7659 {"WinLeave", EVENT_WINLEAVE},
Bram Moolenaar56718732006-03-15 22:53:57 +00007660 {"VimResized", EVENT_VIMRESIZED},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007661 {NULL, (event_T)0}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007662};
7663
7664static AutoPat *first_autopat[NUM_EVENTS] =
7665{
7666 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7667 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7668 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7669 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00007670 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7671 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007672};
7673
7674/*
7675 * struct used to keep status while executing autocommands for an event.
7676 */
7677typedef struct AutoPatCmd
7678{
7679 AutoPat *curpat; /* next AutoPat to examine */
7680 AutoCmd *nextcmd; /* next AutoCmd to execute */
7681 int group; /* group being used */
7682 char_u *fname; /* fname to match with */
7683 char_u *sfname; /* sfname to match with */
7684 char_u *tail; /* tail of fname */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007685 event_T event; /* current event */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007686 int arg_bufnr; /* initially equal to <abuf>, set to zero when
7687 buf is deleted */
7688 struct AutoPatCmd *next; /* chain of active apc-s for auto-invalidation*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00007689} AutoPatCmd;
7690
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007691static AutoPatCmd *active_apc_list = NULL; /* stack of active autocommands */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007692
Bram Moolenaar071d4272004-06-13 20:20:40 +00007693/*
7694 * augroups stores a list of autocmd group names.
7695 */
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007696static garray_T augroups = {0, 0, sizeof(char_u *), 10, NULL};
Bram Moolenaar071d4272004-06-13 20:20:40 +00007697#define AUGROUP_NAME(i) (((char_u **)augroups.ga_data)[i])
7698
7699/*
7700 * The ID of the current group. Group 0 is the default one.
7701 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007702static int current_augroup = AUGROUP_DEFAULT;
7703
7704static int au_need_clean = FALSE; /* need to delete marked patterns */
7705
Bram Moolenaar754b5602006-02-09 23:53:20 +00007706static void show_autocmd __ARGS((AutoPat *ap, event_T event));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007707static void au_remove_pat __ARGS((AutoPat *ap));
7708static void au_remove_cmds __ARGS((AutoPat *ap));
7709static void au_cleanup __ARGS((void));
7710static int au_new_group __ARGS((char_u *name));
7711static void au_del_group __ARGS((char_u *name));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007712static event_T event_name2nr __ARGS((char_u *start, char_u **end));
7713static char_u *event_nr2name __ARGS((event_T event));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007714static char_u *find_end_event __ARGS((char_u *arg, int have_group));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007715static int event_ignored __ARGS((event_T event));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007716static int au_get_grouparg __ARGS((char_u **argp));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007717static 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 +00007718static char_u *getnextac __ARGS((int c, void *cookie, int indent));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007719static 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 +00007720static void auto_next_pat __ARGS((AutoPatCmd *apc, int stop_at_last));
7721
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007722
Bram Moolenaar754b5602006-02-09 23:53:20 +00007723static event_T last_event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007724static int last_group;
Bram Moolenaar78ab3312007-09-29 12:16:41 +00007725static int autocmd_blocked = 0; /* block all autocmds */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007726
7727/*
7728 * Show the autocommands for one AutoPat.
7729 */
7730 static void
7731show_autocmd(ap, event)
7732 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007733 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007734{
7735 AutoCmd *ac;
7736
7737 /* Check for "got_int" (here and at various places below), which is set
7738 * when "q" has been hit for the "--more--" prompt */
7739 if (got_int)
7740 return;
7741 if (ap->pat == NULL) /* pattern has been removed */
7742 return;
7743
7744 msg_putchar('\n');
7745 if (got_int)
7746 return;
7747 if (event != last_event || ap->group != last_group)
7748 {
7749 if (ap->group != AUGROUP_DEFAULT)
7750 {
7751 if (AUGROUP_NAME(ap->group) == NULL)
7752 msg_puts_attr((char_u *)_("--Deleted--"), hl_attr(HLF_E));
7753 else
7754 msg_puts_attr(AUGROUP_NAME(ap->group), hl_attr(HLF_T));
7755 msg_puts((char_u *)" ");
7756 }
7757 msg_puts_attr(event_nr2name(event), hl_attr(HLF_T));
7758 last_event = event;
7759 last_group = ap->group;
7760 msg_putchar('\n');
7761 if (got_int)
7762 return;
7763 }
7764 msg_col = 4;
7765 msg_outtrans(ap->pat);
7766
7767 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7768 {
7769 if (ac->cmd != NULL) /* skip removed commands */
7770 {
7771 if (msg_col >= 14)
7772 msg_putchar('\n');
7773 msg_col = 14;
7774 if (got_int)
7775 return;
7776 msg_outtrans(ac->cmd);
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00007777#ifdef FEAT_EVAL
7778 if (p_verbose > 0)
7779 last_set_msg(ac->scriptID);
7780#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007781 if (got_int)
7782 return;
7783 if (ac->next != NULL)
7784 {
7785 msg_putchar('\n');
7786 if (got_int)
7787 return;
7788 }
7789 }
7790 }
7791}
7792
7793/*
7794 * Mark an autocommand pattern for deletion.
7795 */
7796 static void
7797au_remove_pat(ap)
7798 AutoPat *ap;
7799{
7800 vim_free(ap->pat);
7801 ap->pat = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007802 ap->buflocal_nr = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007803 au_need_clean = TRUE;
7804}
7805
7806/*
7807 * Mark all commands for a pattern for deletion.
7808 */
7809 static void
7810au_remove_cmds(ap)
7811 AutoPat *ap;
7812{
7813 AutoCmd *ac;
7814
7815 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7816 {
7817 vim_free(ac->cmd);
7818 ac->cmd = NULL;
7819 }
7820 au_need_clean = TRUE;
7821}
7822
7823/*
7824 * Cleanup autocommands and patterns that have been deleted.
7825 * This is only done when not executing autocommands.
7826 */
7827 static void
7828au_cleanup()
7829{
7830 AutoPat *ap, **prev_ap;
7831 AutoCmd *ac, **prev_ac;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007832 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007833
7834 if (autocmd_busy || !au_need_clean)
7835 return;
7836
7837 /* loop over all events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007838 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7839 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007840 {
7841 /* loop over all autocommand patterns */
7842 prev_ap = &(first_autopat[(int)event]);
7843 for (ap = *prev_ap; ap != NULL; ap = *prev_ap)
7844 {
7845 /* loop over all commands for this pattern */
7846 prev_ac = &(ap->cmds);
7847 for (ac = *prev_ac; ac != NULL; ac = *prev_ac)
7848 {
7849 /* remove the command if the pattern is to be deleted or when
7850 * the command has been marked for deletion */
7851 if (ap->pat == NULL || ac->cmd == NULL)
7852 {
7853 *prev_ac = ac->next;
7854 vim_free(ac->cmd);
7855 vim_free(ac);
7856 }
7857 else
7858 prev_ac = &(ac->next);
7859 }
7860
7861 /* remove the pattern if it has been marked for deletion */
7862 if (ap->pat == NULL)
7863 {
7864 *prev_ap = ap->next;
Bram Moolenaar748bf032005-02-02 23:04:36 +00007865 vim_free(ap->reg_prog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007866 vim_free(ap);
7867 }
7868 else
7869 prev_ap = &(ap->next);
7870 }
7871 }
7872
7873 au_need_clean = FALSE;
7874}
7875
7876/*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007877 * Called when buffer is freed, to remove/invalidate related buffer-local
7878 * autocmds.
7879 */
7880 void
7881aubuflocal_remove(buf)
7882 buf_T *buf;
7883{
7884 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007885 event_T event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007886 AutoPatCmd *apc;
7887
7888 /* invalidate currently executing autocommands */
7889 for (apc = active_apc_list; apc; apc = apc->next)
7890 if (buf->b_fnum == apc->arg_bufnr)
7891 apc->arg_bufnr = 0;
7892
7893 /* invalidate buflocals looping through events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007894 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7895 event = (event_T)((int)event + 1))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007896 /* loop over all autocommand patterns */
7897 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
7898 if (ap->buflocal_nr == buf->b_fnum)
7899 {
7900 au_remove_pat(ap);
7901 if (p_verbose >= 6)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007902 {
7903 verbose_enter();
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007904 smsg((char_u *)
7905 _("auto-removing autocommand: %s <buffer=%d>"),
7906 event_nr2name(event), buf->b_fnum);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007907 verbose_leave();
7908 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007909 }
7910 au_cleanup();
7911}
7912
7913/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007914 * Add an autocmd group name.
7915 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
7916 */
7917 static int
7918au_new_group(name)
7919 char_u *name;
7920{
7921 int i;
7922
7923 i = au_find_group(name);
7924 if (i == AUGROUP_ERROR) /* the group doesn't exist yet, add it */
7925 {
7926 /* First try using a free entry. */
7927 for (i = 0; i < augroups.ga_len; ++i)
7928 if (AUGROUP_NAME(i) == NULL)
7929 break;
7930 if (i == augroups.ga_len && ga_grow(&augroups, 1) == FAIL)
7931 return AUGROUP_ERROR;
7932
7933 AUGROUP_NAME(i) = vim_strsave(name);
7934 if (AUGROUP_NAME(i) == NULL)
7935 return AUGROUP_ERROR;
7936 if (i == augroups.ga_len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007937 ++augroups.ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007938 }
7939
7940 return i;
7941}
7942
7943 static void
7944au_del_group(name)
7945 char_u *name;
7946{
7947 int i;
7948
7949 i = au_find_group(name);
7950 if (i == AUGROUP_ERROR) /* the group doesn't exist */
7951 EMSG2(_("E367: No such group: \"%s\""), name);
7952 else
7953 {
7954 vim_free(AUGROUP_NAME(i));
7955 AUGROUP_NAME(i) = NULL;
7956 }
7957}
7958
7959/*
7960 * Find the ID of an autocmd group name.
7961 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
7962 */
7963 static int
7964au_find_group(name)
7965 char_u *name;
7966{
7967 int i;
7968
7969 for (i = 0; i < augroups.ga_len; ++i)
7970 if (AUGROUP_NAME(i) != NULL && STRCMP(AUGROUP_NAME(i), name) == 0)
7971 return i;
7972 return AUGROUP_ERROR;
7973}
7974
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00007975/*
7976 * Return TRUE if augroup "name" exists.
7977 */
7978 int
7979au_has_group(name)
7980 char_u *name;
7981{
7982 return au_find_group(name) != AUGROUP_ERROR;
7983}
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00007984
Bram Moolenaar071d4272004-06-13 20:20:40 +00007985/*
7986 * ":augroup {name}".
7987 */
7988 void
7989do_augroup(arg, del_group)
7990 char_u *arg;
7991 int del_group;
7992{
7993 int i;
7994
7995 if (del_group)
7996 {
7997 if (*arg == NUL)
7998 EMSG(_(e_argreq));
7999 else
8000 au_del_group(arg);
8001 }
8002 else if (STRICMP(arg, "end") == 0) /* ":aug end": back to group 0 */
8003 current_augroup = AUGROUP_DEFAULT;
8004 else if (*arg) /* ":aug xxx": switch to group xxx */
8005 {
8006 i = au_new_group(arg);
8007 if (i != AUGROUP_ERROR)
8008 current_augroup = i;
8009 }
8010 else /* ":aug": list the group names */
8011 {
8012 msg_start();
8013 for (i = 0; i < augroups.ga_len; ++i)
8014 {
8015 if (AUGROUP_NAME(i) != NULL)
8016 {
8017 msg_puts(AUGROUP_NAME(i));
8018 msg_puts((char_u *)" ");
8019 }
8020 }
8021 msg_clr_eos();
8022 msg_end();
8023 }
8024}
8025
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008026#if defined(EXITFREE) || defined(PROTO)
8027 void
8028free_all_autocmds()
8029{
8030 for (current_augroup = -1; current_augroup < augroups.ga_len;
8031 ++current_augroup)
8032 do_autocmd((char_u *)"", TRUE);
8033 ga_clear_strings(&augroups);
8034}
8035#endif
8036
Bram Moolenaar071d4272004-06-13 20:20:40 +00008037/*
8038 * Return the event number for event name "start".
8039 * Return NUM_EVENTS if the event name was not found.
8040 * Return a pointer to the next event name in "end".
8041 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008042 static event_T
Bram Moolenaar071d4272004-06-13 20:20:40 +00008043event_name2nr(start, end)
8044 char_u *start;
8045 char_u **end;
8046{
8047 char_u *p;
8048 int i;
8049 int len;
8050
8051 /* the event name ends with end of line, a blank or a comma */
8052 for (p = start; *p && !vim_iswhite(*p) && *p != ','; ++p)
8053 ;
8054 for (i = 0; event_names[i].name != NULL; ++i)
8055 {
8056 len = (int)STRLEN(event_names[i].name);
8057 if (len == p - start && STRNICMP(event_names[i].name, start, len) == 0)
8058 break;
8059 }
8060 if (*p == ',')
8061 ++p;
8062 *end = p;
8063 if (event_names[i].name == NULL)
8064 return NUM_EVENTS;
8065 return event_names[i].event;
8066}
8067
8068/*
8069 * Return the name for event "event".
8070 */
8071 static char_u *
8072event_nr2name(event)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008073 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008074{
8075 int i;
8076
8077 for (i = 0; event_names[i].name != NULL; ++i)
8078 if (event_names[i].event == event)
8079 return (char_u *)event_names[i].name;
8080 return (char_u *)"Unknown";
8081}
8082
8083/*
8084 * Scan over the events. "*" stands for all events.
8085 */
8086 static char_u *
8087find_end_event(arg, have_group)
8088 char_u *arg;
8089 int have_group; /* TRUE when group name was found */
8090{
8091 char_u *pat;
8092 char_u *p;
8093
8094 if (*arg == '*')
8095 {
8096 if (arg[1] && !vim_iswhite(arg[1]))
8097 {
8098 EMSG2(_("E215: Illegal character after *: %s"), arg);
8099 return NULL;
8100 }
8101 pat = arg + 1;
8102 }
8103 else
8104 {
8105 for (pat = arg; *pat && !vim_iswhite(*pat); pat = p)
8106 {
8107 if ((int)event_name2nr(pat, &p) >= (int)NUM_EVENTS)
8108 {
8109 if (have_group)
8110 EMSG2(_("E216: No such event: %s"), pat);
8111 else
8112 EMSG2(_("E216: No such group or event: %s"), pat);
8113 return NULL;
8114 }
8115 }
8116 }
8117 return pat;
8118}
8119
8120/*
8121 * Return TRUE if "event" is included in 'eventignore'.
8122 */
8123 static int
8124event_ignored(event)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008125 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008126{
8127 char_u *p = p_ei;
8128
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008129 while (*p != NUL)
8130 {
8131 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8132 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008133 if (event_name2nr(p, &p) == event)
8134 return TRUE;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008135 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008136
8137 return FALSE;
8138}
8139
8140/*
8141 * Return OK when the contents of p_ei is valid, FAIL otherwise.
8142 */
8143 int
8144check_ei()
8145{
8146 char_u *p = p_ei;
8147
Bram Moolenaar071d4272004-06-13 20:20:40 +00008148 while (*p)
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008149 {
8150 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8151 {
8152 p += 3;
8153 if (*p == ',')
8154 ++p;
8155 }
8156 else if (event_name2nr(p, &p) == NUM_EVENTS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008157 return FAIL;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008158 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008159
8160 return OK;
8161}
8162
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008163# if defined(FEAT_SYN_HL) || defined(PROTO)
8164
8165/*
8166 * Add "what" to 'eventignore' to skip loading syntax highlighting for every
8167 * buffer loaded into the window. "what" must start with a comma.
8168 * Returns the old value of 'eventignore' in allocated memory.
8169 */
8170 char_u *
8171au_event_disable(what)
8172 char *what;
8173{
8174 char_u *new_ei;
8175 char_u *save_ei;
8176
8177 save_ei = vim_strsave(p_ei);
8178 if (save_ei != NULL)
8179 {
Bram Moolenaara5792f52005-11-23 21:25:05 +00008180 new_ei = vim_strnsave(p_ei, (int)(STRLEN(p_ei) + STRLEN(what)));
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008181 if (new_ei != NULL)
8182 {
Bram Moolenaar8cac9fd2010-03-02 12:48:05 +01008183 if (*what == ',' && *p_ei == NUL)
8184 STRCPY(new_ei, what + 1);
8185 else
8186 STRCAT(new_ei, what);
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008187 set_string_option_direct((char_u *)"ei", -1, new_ei,
8188 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008189 vim_free(new_ei);
8190 }
8191 }
8192 return save_ei;
8193}
8194
8195 void
8196au_event_restore(old_ei)
8197 char_u *old_ei;
8198{
8199 if (old_ei != NULL)
8200 {
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008201 set_string_option_direct((char_u *)"ei", -1, old_ei,
8202 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008203 vim_free(old_ei);
8204 }
8205}
8206# endif /* FEAT_SYN_HL */
8207
Bram Moolenaar071d4272004-06-13 20:20:40 +00008208/*
8209 * do_autocmd() -- implements the :autocmd command. Can be used in the
8210 * following ways:
8211 *
8212 * :autocmd <event> <pat> <cmd> Add <cmd> to the list of commands that
8213 * will be automatically executed for <event>
8214 * when editing a file matching <pat>, in
8215 * the current group.
8216 * :autocmd <event> <pat> Show the auto-commands associated with
8217 * <event> and <pat>.
8218 * :autocmd <event> Show the auto-commands associated with
8219 * <event>.
8220 * :autocmd Show all auto-commands.
8221 * :autocmd! <event> <pat> <cmd> Remove all auto-commands associated with
8222 * <event> and <pat>, and add the command
8223 * <cmd>, for the current group.
8224 * :autocmd! <event> <pat> Remove all auto-commands associated with
8225 * <event> and <pat> for the current group.
8226 * :autocmd! <event> Remove all auto-commands associated with
8227 * <event> for the current group.
8228 * :autocmd! Remove ALL auto-commands for the current
8229 * group.
8230 *
8231 * Multiple events and patterns may be given separated by commas. Here are
8232 * some examples:
8233 * :autocmd bufread,bufenter *.c,*.h set tw=0 smartindent noic
8234 * :autocmd bufleave * set tw=79 nosmartindent ic infercase
8235 *
8236 * :autocmd * *.c show all autocommands for *.c files.
Bram Moolenaard35f9712005-12-18 22:02:33 +00008237 *
8238 * Mostly a {group} argument can optionally appear before <event>.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008239 */
8240 void
8241do_autocmd(arg, forceit)
8242 char_u *arg;
8243 int forceit;
8244{
8245 char_u *pat;
8246 char_u *envpat = NULL;
8247 char_u *cmd;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008248 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008249 int need_free = FALSE;
8250 int nested = FALSE;
8251 int group;
8252
8253 /*
8254 * Check for a legal group name. If not, use AUGROUP_ALL.
8255 */
8256 group = au_get_grouparg(&arg);
8257 if (arg == NULL) /* out of memory */
8258 return;
8259
8260 /*
8261 * Scan over the events.
8262 * If we find an illegal name, return here, don't do anything.
8263 */
8264 pat = find_end_event(arg, group != AUGROUP_ALL);
8265 if (pat == NULL)
8266 return;
8267
8268 /*
8269 * Scan over the pattern. Put a NUL at the end.
8270 */
8271 pat = skipwhite(pat);
8272 cmd = pat;
8273 while (*cmd && (!vim_iswhite(*cmd) || cmd[-1] == '\\'))
8274 cmd++;
8275 if (*cmd)
8276 *cmd++ = NUL;
8277
8278 /* Expand environment variables in the pattern. Set 'shellslash', we want
8279 * forward slashes here. */
8280 if (vim_strchr(pat, '$') != NULL || vim_strchr(pat, '~') != NULL)
8281 {
8282#ifdef BACKSLASH_IN_FILENAME
8283 int p_ssl_save = p_ssl;
8284
8285 p_ssl = TRUE;
8286#endif
8287 envpat = expand_env_save(pat);
8288#ifdef BACKSLASH_IN_FILENAME
8289 p_ssl = p_ssl_save;
8290#endif
8291 if (envpat != NULL)
8292 pat = envpat;
8293 }
8294
8295 /*
8296 * Check for "nested" flag.
8297 */
8298 cmd = skipwhite(cmd);
8299 if (*cmd != NUL && STRNCMP(cmd, "nested", 6) == 0 && vim_iswhite(cmd[6]))
8300 {
8301 nested = TRUE;
8302 cmd = skipwhite(cmd + 6);
8303 }
8304
8305 /*
8306 * Find the start of the commands.
8307 * Expand <sfile> in it.
8308 */
8309 if (*cmd != NUL)
8310 {
8311 cmd = expand_sfile(cmd);
8312 if (cmd == NULL) /* some error */
8313 return;
8314 need_free = TRUE;
8315 }
8316
8317 /*
8318 * Print header when showing autocommands.
8319 */
8320 if (!forceit && *cmd == NUL)
8321 {
8322 /* Highlight title */
8323 MSG_PUTS_TITLE(_("\n--- Auto-Commands ---"));
8324 }
8325
8326 /*
8327 * Loop over the events.
8328 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008329 last_event = (event_T)-1; /* for listing the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008330 last_group = AUGROUP_ERROR; /* for listing the group name */
8331 if (*arg == '*' || *arg == NUL)
8332 {
Bram Moolenaar754b5602006-02-09 23:53:20 +00008333 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8334 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008335 if (do_autocmd_event(event, pat,
8336 nested, cmd, forceit, group) == FAIL)
8337 break;
8338 }
8339 else
8340 {
8341 while (*arg && !vim_iswhite(*arg))
8342 if (do_autocmd_event(event_name2nr(arg, &arg), pat,
8343 nested, cmd, forceit, group) == FAIL)
8344 break;
8345 }
8346
8347 if (need_free)
8348 vim_free(cmd);
8349 vim_free(envpat);
8350}
8351
8352/*
8353 * Find the group ID in a ":autocmd" or ":doautocmd" argument.
8354 * The "argp" argument is advanced to the following argument.
8355 *
8356 * Returns the group ID, AUGROUP_ERROR for error (out of memory).
8357 */
8358 static int
8359au_get_grouparg(argp)
8360 char_u **argp;
8361{
8362 char_u *group_name;
8363 char_u *p;
8364 char_u *arg = *argp;
8365 int group = AUGROUP_ALL;
8366
8367 p = skiptowhite(arg);
8368 if (p > arg)
8369 {
8370 group_name = vim_strnsave(arg, (int)(p - arg));
8371 if (group_name == NULL) /* out of memory */
8372 return AUGROUP_ERROR;
8373 group = au_find_group(group_name);
8374 if (group == AUGROUP_ERROR)
8375 group = AUGROUP_ALL; /* no match, use all groups */
8376 else
8377 *argp = skipwhite(p); /* match, skip over group name */
8378 vim_free(group_name);
8379 }
8380 return group;
8381}
8382
8383/*
8384 * do_autocmd() for one event.
8385 * If *pat == NUL do for all patterns.
8386 * If *cmd == NUL show entries.
8387 * If forceit == TRUE delete entries.
8388 * If group is not AUGROUP_ALL, only use this group.
8389 */
8390 static int
8391do_autocmd_event(event, pat, nested, cmd, forceit, group)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008392 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008393 char_u *pat;
8394 int nested;
8395 char_u *cmd;
8396 int forceit;
8397 int group;
8398{
8399 AutoPat *ap;
8400 AutoPat **prev_ap;
8401 AutoCmd *ac;
8402 AutoCmd **prev_ac;
8403 int brace_level;
8404 char_u *endpat;
8405 int findgroup;
8406 int allgroups;
8407 int patlen;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00008408 int is_buflocal;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008409 int buflocal_nr;
8410 char_u buflocal_pat[25]; /* for "<buffer=X>" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008411
8412 if (group == AUGROUP_ALL)
8413 findgroup = current_augroup;
8414 else
8415 findgroup = group;
8416 allgroups = (group == AUGROUP_ALL && !forceit && *cmd == NUL);
8417
8418 /*
8419 * Show or delete all patterns for an event.
8420 */
8421 if (*pat == NUL)
8422 {
8423 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8424 {
8425 if (forceit) /* delete the AutoPat, if it's in the current group */
8426 {
8427 if (ap->group == findgroup)
8428 au_remove_pat(ap);
8429 }
8430 else if (group == AUGROUP_ALL || ap->group == group)
8431 show_autocmd(ap, event);
8432 }
8433 }
8434
8435 /*
8436 * Loop through all the specified patterns.
8437 */
8438 for ( ; *pat; pat = (*endpat == ',' ? endpat + 1 : endpat))
8439 {
8440 /*
8441 * Find end of the pattern.
8442 * Watch out for a comma in braces, like "*.\{obj,o\}".
8443 */
8444 brace_level = 0;
8445 for (endpat = pat; *endpat && (*endpat != ',' || brace_level
8446 || endpat[-1] == '\\'); ++endpat)
8447 {
8448 if (*endpat == '{')
8449 brace_level++;
8450 else if (*endpat == '}')
8451 brace_level--;
8452 }
8453 if (pat == endpat) /* ignore single comma */
8454 continue;
8455 patlen = (int)(endpat - pat);
8456
8457 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008458 * detect special <buflocal[=X]> buffer-local patterns
8459 */
8460 is_buflocal = FALSE;
8461 buflocal_nr = 0;
8462
8463 if (patlen >= 7 && STRNCMP(pat, "<buffer", 7) == 0
8464 && pat[patlen - 1] == '>')
8465 {
8466 /* Error will be printed only for addition. printing and removing
8467 * will proceed silently. */
8468 is_buflocal = TRUE;
8469 if (patlen == 8)
8470 buflocal_nr = curbuf->b_fnum;
8471 else if (patlen > 9 && pat[7] == '=')
8472 {
8473 /* <buffer=abuf> */
8474 if (patlen == 13 && STRNICMP(pat, "<buffer=abuf>", 13))
8475 buflocal_nr = autocmd_bufnr;
8476 /* <buffer=123> */
8477 else if (skipdigits(pat + 8) == pat + patlen - 1)
8478 buflocal_nr = atoi((char *)pat + 8);
8479 }
8480 }
8481
8482 if (is_buflocal)
8483 {
8484 /* normalize pat into standard "<buffer>#N" form */
8485 sprintf((char *)buflocal_pat, "<buffer=%d>", buflocal_nr);
8486 pat = buflocal_pat; /* can modify pat and patlen */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008487 patlen = (int)STRLEN(buflocal_pat); /* but not endpat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008488 }
8489
8490 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008491 * Find AutoPat entries with this pattern.
8492 */
8493 prev_ap = &first_autopat[(int)event];
8494 while ((ap = *prev_ap) != NULL)
8495 {
8496 if (ap->pat != NULL)
8497 {
8498 /* Accept a pattern when:
8499 * - a group was specified and it's that group, or a group was
8500 * not specified and it's the current group, or a group was
8501 * not specified and we are listing
8502 * - the length of the pattern matches
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008503 * - the pattern matches.
8504 * For <buffer[=X]>, this condition works because we normalize
8505 * all buffer-local patterns.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008506 */
8507 if ((allgroups || ap->group == findgroup)
8508 && ap->patlen == patlen
8509 && STRNCMP(pat, ap->pat, patlen) == 0)
8510 {
8511 /*
8512 * Remove existing autocommands.
8513 * If adding any new autocmd's for this AutoPat, don't
8514 * delete the pattern from the autopat list, append to
8515 * this list.
8516 */
8517 if (forceit)
8518 {
8519 if (*cmd != NUL && ap->next == NULL)
8520 {
8521 au_remove_cmds(ap);
8522 break;
8523 }
8524 au_remove_pat(ap);
8525 }
8526
8527 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008528 * Show autocmd's for this autopat, or buflocals <buffer=X>
Bram Moolenaar071d4272004-06-13 20:20:40 +00008529 */
8530 else if (*cmd == NUL)
8531 show_autocmd(ap, event);
8532
8533 /*
8534 * Add autocmd to this autopat, if it's the last one.
8535 */
8536 else if (ap->next == NULL)
8537 break;
8538 }
8539 }
8540 prev_ap = &ap->next;
8541 }
8542
8543 /*
8544 * Add a new command.
8545 */
8546 if (*cmd != NUL)
8547 {
8548 /*
8549 * If the pattern we want to add a command to does appear at the
8550 * end of the list (or not is not in the list at all), add the
8551 * pattern at the end of the list.
8552 */
8553 if (ap == NULL)
8554 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008555 /* refuse to add buffer-local ap if buffer number is invalid */
8556 if (is_buflocal && (buflocal_nr == 0
8557 || buflist_findnr(buflocal_nr) == NULL))
8558 {
8559 EMSGN(_("E680: <buffer=%d>: invalid buffer number "),
8560 buflocal_nr);
8561 return FAIL;
8562 }
8563
Bram Moolenaar071d4272004-06-13 20:20:40 +00008564 ap = (AutoPat *)alloc((unsigned)sizeof(AutoPat));
8565 if (ap == NULL)
8566 return FAIL;
8567 ap->pat = vim_strnsave(pat, patlen);
8568 ap->patlen = patlen;
8569 if (ap->pat == NULL)
8570 {
8571 vim_free(ap);
8572 return FAIL;
8573 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008574
8575 if (is_buflocal)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008576 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008577 ap->buflocal_nr = buflocal_nr;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008578 ap->reg_prog = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008579 }
8580 else
8581 {
Bram Moolenaar748bf032005-02-02 23:04:36 +00008582 char_u *reg_pat;
8583
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008584 ap->buflocal_nr = 0;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008585 reg_pat = file_pat_to_reg_pat(pat, endpat,
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008586 &ap->allow_dirs, TRUE);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008587 if (reg_pat != NULL)
8588 ap->reg_prog = vim_regcomp(reg_pat, RE_MAGIC);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008589 vim_free(reg_pat);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008590 if (reg_pat == NULL || ap->reg_prog == NULL)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008591 {
8592 vim_free(ap->pat);
8593 vim_free(ap);
8594 return FAIL;
8595 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008596 }
8597 ap->cmds = NULL;
8598 *prev_ap = ap;
8599 ap->next = NULL;
8600 if (group == AUGROUP_ALL)
8601 ap->group = current_augroup;
8602 else
8603 ap->group = group;
8604 }
8605
8606 /*
8607 * Add the autocmd at the end of the AutoCmd list.
8608 */
8609 prev_ac = &(ap->cmds);
8610 while ((ac = *prev_ac) != NULL)
8611 prev_ac = &ac->next;
8612 ac = (AutoCmd *)alloc((unsigned)sizeof(AutoCmd));
8613 if (ac == NULL)
8614 return FAIL;
8615 ac->cmd = vim_strsave(cmd);
8616#ifdef FEAT_EVAL
8617 ac->scriptID = current_SID;
8618#endif
8619 if (ac->cmd == NULL)
8620 {
8621 vim_free(ac);
8622 return FAIL;
8623 }
8624 ac->next = NULL;
8625 *prev_ac = ac;
8626 ac->nested = nested;
8627 }
8628 }
8629
8630 au_cleanup(); /* may really delete removed patterns/commands now */
8631 return OK;
8632}
8633
8634/*
8635 * Implementation of ":doautocmd [group] event [fname]".
8636 * Return OK for success, FAIL for failure;
8637 */
8638 int
8639do_doautocmd(arg, do_msg)
8640 char_u *arg;
8641 int do_msg; /* give message for no matching autocmds? */
8642{
8643 char_u *fname;
8644 int nothing_done = TRUE;
8645 int group;
8646
8647 /*
8648 * Check for a legal group name. If not, use AUGROUP_ALL.
8649 */
8650 group = au_get_grouparg(&arg);
8651 if (arg == NULL) /* out of memory */
8652 return FAIL;
8653
8654 if (*arg == '*')
8655 {
8656 EMSG(_("E217: Can't execute autocommands for ALL events"));
8657 return FAIL;
8658 }
8659
8660 /*
8661 * Scan over the events.
8662 * If we find an illegal name, return here, don't do anything.
8663 */
8664 fname = find_end_event(arg, group != AUGROUP_ALL);
8665 if (fname == NULL)
8666 return FAIL;
8667
8668 fname = skipwhite(fname);
8669
8670 /*
8671 * Loop over the events.
8672 */
8673 while (*arg && !vim_iswhite(*arg))
8674 if (apply_autocmds_group(event_name2nr(arg, &arg),
8675 fname, NULL, TRUE, group, curbuf, NULL))
8676 nothing_done = FALSE;
8677
8678 if (nothing_done && do_msg)
8679 MSG(_("No matching autocommands"));
8680
8681#ifdef FEAT_EVAL
8682 return aborting() ? FAIL : OK;
8683#else
8684 return OK;
8685#endif
8686}
8687
8688/*
8689 * ":doautoall": execute autocommands for each loaded buffer.
8690 */
8691 void
8692ex_doautoall(eap)
8693 exarg_T *eap;
8694{
8695 int retval;
8696 aco_save_T aco;
8697 buf_T *buf;
8698
8699 /*
8700 * This is a bit tricky: For some commands curwin->w_buffer needs to be
8701 * equal to curbuf, but for some buffers there may not be a window.
8702 * So we change the buffer for the current window for a moment. This
8703 * gives problems when the autocommands make changes to the list of
8704 * buffers or windows...
8705 */
8706 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8707 {
Bram Moolenaar3a847972008-07-08 09:36:58 +00008708 if (buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008709 {
8710 /* find a window for this buffer and save some values */
8711 aucmd_prepbuf(&aco, buf);
8712
8713 /* execute the autocommands for this buffer */
8714 retval = do_doautocmd(eap->arg, FALSE);
Bram Moolenaareeefcc72007-05-01 21:21:21 +00008715
8716 /* Execute the modeline settings, but don't set window-local
8717 * options if we are using the current window for another buffer. */
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008718 do_modelines(curwin == aucmd_win ? OPT_NOWIN : 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008719
8720 /* restore the current window */
8721 aucmd_restbuf(&aco);
8722
8723 /* stop if there is some error or buffer was deleted */
8724 if (retval == FAIL || !buf_valid(buf))
8725 break;
8726 }
8727 }
8728
8729 check_cursor(); /* just in case lines got deleted */
8730}
8731
8732/*
8733 * Prepare for executing autocommands for (hidden) buffer "buf".
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008734 * Search for a visible window containing the current buffer. If there isn't
8735 * one then use "aucmd_win".
Bram Moolenaar071d4272004-06-13 20:20:40 +00008736 * Set "curbuf" and "curwin" to match "buf".
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00008737 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008738 */
8739 void
8740aucmd_prepbuf(aco, buf)
8741 aco_save_T *aco; /* structure to save values in */
8742 buf_T *buf; /* new curbuf */
8743{
8744 win_T *win;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008745#ifdef FEAT_WINDOWS
8746 int save_ea;
8747#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008748
8749 /* Find a window that is for the new buffer */
8750 if (buf == curbuf) /* be quick when buf is curbuf */
8751 win = curwin;
8752 else
8753#ifdef FEAT_WINDOWS
8754 for (win = firstwin; win != NULL; win = win->w_next)
8755 if (win->w_buffer == buf)
8756 break;
8757#else
8758 win = NULL;
8759#endif
8760
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008761 /* Allocate "aucmd_win" when needed. If this fails (out of memory) fall
8762 * back to using the current window. */
8763 if (win == NULL && aucmd_win == NULL)
8764 {
8765 win_alloc_aucmd_win();
8766 if (aucmd_win == NULL)
8767 win = curwin;
8768 }
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008769 if (win == NULL && aucmd_win_used)
8770 /* Strange recursive autocommand, fall back to using the current
8771 * window. Expect a few side effects... */
8772 win = curwin;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008773
8774 aco->save_curwin = curwin;
8775 aco->save_curbuf = curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008776 if (win != NULL)
8777 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008778 /* There is a window for "buf" in the current tab page, make it the
8779 * curwin. This is preferred, it has the least side effects (esp. if
8780 * "buf" is curbuf). */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008781 aco->use_aucmd_win = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008782 curwin = win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008783 }
8784 else
8785 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008786 /* There is no window for "buf", use "aucmd_win". To minimize the side
8787 * effects, insert it in a the current tab page.
8788 * Anything related to a window (e.g., setting folds) may have
8789 * unexpected results. */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008790 aco->use_aucmd_win = TRUE;
8791 aucmd_win_used = TRUE;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008792 aucmd_win->w_buffer = buf;
Bram Moolenaarcdddaa42010-06-07 23:07:44 +02008793 aucmd_win->w_s = &buf->b_s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008794 ++buf->b_nwindows;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008795 win_init_empty(aucmd_win); /* set cursor and topline to safe values */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008796 vim_free(aucmd_win->w_localdir);
8797 aucmd_win->w_localdir = NULL;
8798
8799 /* Make sure w_localdir and globaldir are NULL to avoid a chdir() in
8800 * win_enter_ext(). */
8801 aucmd_win->w_localdir = NULL;
8802 aco->globaldir = globaldir;
8803 globaldir = NULL;
8804
Bram Moolenaar071d4272004-06-13 20:20:40 +00008805
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008806#ifdef FEAT_WINDOWS
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008807 /* Split the current window, put the aucmd_win in the upper half.
8808 * We don't want the BufEnter or WinEnter autocommands. */
8809 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008810 make_snapshot(SNAP_AUCMD_IDX);
8811 save_ea = p_ea;
8812 p_ea = FALSE;
8813 (void)win_split_ins(0, WSP_TOP, aucmd_win, 0);
8814 (void)win_comp_pos(); /* recompute window positions */
8815 p_ea = save_ea;
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008816 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008817#endif
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008818 curwin = aucmd_win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008819 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008820 curbuf = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008821 aco->new_curwin = curwin;
8822 aco->new_curbuf = curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008823}
8824
8825/*
8826 * Cleanup after executing autocommands for a (hidden) buffer.
8827 * Restore the window as it was (if possible).
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00008828 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008829 */
8830 void
8831aucmd_restbuf(aco)
8832 aco_save_T *aco; /* structure holding saved values */
8833{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008834#ifdef FEAT_WINDOWS
8835 int dummy;
8836#endif
8837
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008838 if (aco->use_aucmd_win)
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008839 {
8840 --curbuf->b_nwindows;
8841#ifdef FEAT_WINDOWS
8842 /* Find "aucmd_win", it can't be closed, but it may be in another tab
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008843 * page. Do not trigger autocommands here. */
8844 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008845 if (curwin != aucmd_win)
8846 {
8847 tabpage_T *tp;
8848 win_T *wp;
8849
8850 FOR_ALL_TAB_WINDOWS(tp, wp)
8851 {
8852 if (wp == aucmd_win)
8853 {
8854 if (tp != curtab)
8855 goto_tabpage_tp(tp);
8856 win_goto(aucmd_win);
8857 break;
8858 }
8859 }
8860 }
8861
8862 /* Remove the window and frame from the tree of frames. */
8863 (void)winframe_remove(curwin, &dummy, NULL);
8864 win_remove(curwin, NULL);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008865 aucmd_win_used = FALSE;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008866 last_status(FALSE); /* may need to remove last status line */
8867 restore_snapshot(SNAP_AUCMD_IDX, FALSE);
8868 (void)win_comp_pos(); /* recompute window positions */
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008869 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008870
8871 if (win_valid(aco->save_curwin))
8872 curwin = aco->save_curwin;
8873 else
8874 /* Hmm, original window disappeared. Just use the first one. */
8875 curwin = firstwin;
8876# ifdef FEAT_EVAL
8877 vars_clear(&aucmd_win->w_vars.dv_hashtab); /* free all w: variables */
Bram Moolenaar50daf402009-11-17 13:57:22 +00008878 hash_init(&aucmd_win->w_vars.dv_hashtab); /* re-use the hashtab */
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008879# endif
8880#else
8881 curwin = aco->save_curwin;
8882#endif
8883 curbuf = curwin->w_buffer;
8884
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008885 vim_free(globaldir);
8886 globaldir = aco->globaldir;
8887
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008888 /* the buffer contents may have changed */
8889 check_cursor();
8890 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
8891 {
8892 curwin->w_topline = curbuf->b_ml.ml_line_count;
8893#ifdef FEAT_DIFF
8894 curwin->w_topfill = 0;
8895#endif
8896 }
8897#if defined(FEAT_GUI)
8898 /* Hide the scrollbars from the aucmd_win and update. */
8899 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_LEFT], FALSE);
8900 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_RIGHT], FALSE);
8901 gui_may_update_scrollbars();
8902#endif
8903 }
8904 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00008905 {
8906 /* restore curwin */
8907#ifdef FEAT_WINDOWS
8908 if (win_valid(aco->save_curwin))
8909#endif
8910 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008911 /* Restore the buffer which was previously edited by curwin, if
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008912 * it was changed, we are still the same window and the buffer is
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008913 * valid. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008914 if (curwin == aco->new_curwin
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008915 && curbuf != aco->new_curbuf
8916 && buf_valid(aco->new_curbuf)
8917 && aco->new_curbuf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008918 {
8919 --curbuf->b_nwindows;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008920 curbuf = aco->new_curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008921 curwin->w_buffer = curbuf;
8922 ++curbuf->b_nwindows;
8923 }
8924
8925 curwin = aco->save_curwin;
8926 curbuf = curwin->w_buffer;
8927 }
8928 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008929}
8930
8931static int autocmd_nested = FALSE;
8932
8933/*
8934 * Execute autocommands for "event" and file name "fname".
8935 * Return TRUE if some commands were executed.
8936 */
8937 int
8938apply_autocmds(event, fname, fname_io, force, buf)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008939 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008940 char_u *fname; /* NULL or empty means use actual file name */
8941 char_u *fname_io; /* fname to use for <afile> on cmdline */
8942 int force; /* when TRUE, ignore autocmd_busy */
8943 buf_T *buf; /* buffer for <abuf> */
8944{
8945 return apply_autocmds_group(event, fname, fname_io, force,
8946 AUGROUP_ALL, buf, NULL);
8947}
8948
8949/*
8950 * Like apply_autocmds(), but with extra "eap" argument. This takes care of
8951 * setting v:filearg.
8952 */
8953 static int
8954apply_autocmds_exarg(event, fname, fname_io, force, buf, eap)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008955 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008956 char_u *fname;
8957 char_u *fname_io;
8958 int force;
8959 buf_T *buf;
8960 exarg_T *eap;
8961{
8962 return apply_autocmds_group(event, fname, fname_io, force,
8963 AUGROUP_ALL, buf, eap);
8964}
8965
8966/*
8967 * Like apply_autocmds(), but handles the caller's retval. If the script
8968 * processing is being aborted or if retval is FAIL when inside a try
8969 * conditional, no autocommands are executed. If otherwise the autocommands
8970 * cause the script to be aborted, retval is set to FAIL.
8971 */
8972 int
8973apply_autocmds_retval(event, fname, fname_io, force, buf, retval)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008974 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008975 char_u *fname; /* NULL or empty means use actual file name */
8976 char_u *fname_io; /* fname to use for <afile> on cmdline */
8977 int force; /* when TRUE, ignore autocmd_busy */
8978 buf_T *buf; /* buffer for <abuf> */
8979 int *retval; /* pointer to caller's retval */
8980{
8981 int did_cmd;
8982
Bram Moolenaar1e015462005-09-25 22:16:38 +00008983#ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00008984 if (should_abort(*retval))
8985 return FALSE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00008986#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008987
8988 did_cmd = apply_autocmds_group(event, fname, fname_io, force,
8989 AUGROUP_ALL, buf, NULL);
Bram Moolenaar1e015462005-09-25 22:16:38 +00008990 if (did_cmd
8991#ifdef FEAT_EVAL
8992 && aborting()
8993#endif
8994 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00008995 *retval = FAIL;
8996 return did_cmd;
8997}
8998
Bram Moolenaard35f9712005-12-18 22:02:33 +00008999/*
9000 * Return TRUE when there is a CursorHold autocommand defined.
9001 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009002 int
9003has_cursorhold()
9004{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009005 return (first_autopat[(int)(get_real_state() == NORMAL_BUSY
9006 ? EVENT_CURSORHOLD : EVENT_CURSORHOLDI)] != NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009007}
Bram Moolenaard35f9712005-12-18 22:02:33 +00009008
9009/*
9010 * Return TRUE if the CursorHold event can be triggered.
9011 */
9012 int
9013trigger_cursorhold()
9014{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009015 int state;
9016
Bram Moolenaard29a9ee2006-09-14 09:07:34 +00009017 if (!did_cursorhold && has_cursorhold() && !Recording
9018#ifdef FEAT_INS_EXPAND
9019 && !ins_compl_active()
9020#endif
9021 )
Bram Moolenaar754b5602006-02-09 23:53:20 +00009022 {
9023 state = get_real_state();
9024 if (state == NORMAL_BUSY || (state & INSERT) != 0)
9025 return TRUE;
9026 }
9027 return FALSE;
Bram Moolenaard35f9712005-12-18 22:02:33 +00009028}
Bram Moolenaar754b5602006-02-09 23:53:20 +00009029
9030/*
9031 * Return TRUE when there is a CursorMoved autocommand defined.
9032 */
9033 int
9034has_cursormoved()
9035{
9036 return (first_autopat[(int)EVENT_CURSORMOVED] != NULL);
9037}
9038
9039/*
9040 * Return TRUE when there is a CursorMovedI autocommand defined.
9041 */
9042 int
9043has_cursormovedI()
9044{
9045 return (first_autopat[(int)EVENT_CURSORMOVEDI] != NULL);
9046}
Bram Moolenaar071d4272004-06-13 20:20:40 +00009047
9048 static int
9049apply_autocmds_group(event, fname, fname_io, force, group, buf, eap)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009050 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009051 char_u *fname; /* NULL or empty means use actual file name */
9052 char_u *fname_io; /* fname to use for <afile> on cmdline, NULL means
9053 use fname */
9054 int force; /* when TRUE, ignore autocmd_busy */
9055 int group; /* group ID, or AUGROUP_ALL */
9056 buf_T *buf; /* buffer for <abuf> */
9057 exarg_T *eap; /* command arguments */
9058{
9059 char_u *sfname = NULL; /* short file name */
9060 char_u *tail;
9061 int save_changed;
9062 buf_T *old_curbuf;
9063 int retval = FALSE;
9064 char_u *save_sourcing_name;
9065 linenr_T save_sourcing_lnum;
9066 char_u *save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009067 int save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009068 int save_autocmd_bufnr;
9069 char_u *save_autocmd_match;
9070 int save_autocmd_busy;
9071 int save_autocmd_nested;
9072 static int nesting = 0;
9073 AutoPatCmd patcmd;
9074 AutoPat *ap;
9075#ifdef FEAT_EVAL
9076 scid_T save_current_SID;
9077 void *save_funccalp;
9078 char_u *save_cmdarg;
9079 long save_cmdbang;
9080#endif
9081 static int filechangeshell_busy = FALSE;
Bram Moolenaar05159a02005-02-26 23:04:13 +00009082#ifdef FEAT_PROFILE
9083 proftime_T wait_time;
9084#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009085
9086 /*
9087 * Quickly return if there are no autocommands for this event or
9088 * autocommands are blocked.
9089 */
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009090 if (first_autopat[(int)event] == NULL || autocmd_blocked > 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009091 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009092
9093 /*
9094 * When autocommands are busy, new autocommands are only executed when
9095 * explicitly enabled with the "nested" flag.
9096 */
9097 if (autocmd_busy && !(force || autocmd_nested))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009098 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009099
9100#ifdef FEAT_EVAL
9101 /*
Bram Moolenaar7263a772007-05-10 17:35:54 +00009102 * Quickly return when immediately aborting on error, or when an interrupt
Bram Moolenaar071d4272004-06-13 20:20:40 +00009103 * occurred or an exception was thrown but not caught.
9104 */
9105 if (aborting())
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009106 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009107#endif
9108
9109 /*
9110 * FileChangedShell never nests, because it can create an endless loop.
9111 */
Bram Moolenaar56718732006-03-15 22:53:57 +00009112 if (filechangeshell_busy && (event == EVENT_FILECHANGEDSHELL
9113 || event == EVENT_FILECHANGEDSHELLPOST))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009114 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009115
9116 /*
9117 * Ignore events in 'eventignore'.
9118 */
9119 if (event_ignored(event))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009120 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009121
9122 /*
9123 * Allow nesting of autocommands, but restrict the depth, because it's
9124 * possible to create an endless loop.
9125 */
9126 if (nesting == 10)
9127 {
9128 EMSG(_("E218: autocommand nesting too deep"));
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009129 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009130 }
9131
9132 /*
9133 * Check if these autocommands are disabled. Used when doing ":all" or
9134 * ":ball".
9135 */
9136 if ( (autocmd_no_enter
9137 && (event == EVENT_WINENTER || event == EVENT_BUFENTER))
9138 || (autocmd_no_leave
9139 && (event == EVENT_WINLEAVE || event == EVENT_BUFLEAVE)))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009140 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009141
9142 /*
9143 * Save the autocmd_* variables and info about the current buffer.
9144 */
9145 save_autocmd_fname = autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009146 save_autocmd_fname_full = autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009147 save_autocmd_bufnr = autocmd_bufnr;
9148 save_autocmd_match = autocmd_match;
9149 save_autocmd_busy = autocmd_busy;
9150 save_autocmd_nested = autocmd_nested;
9151 save_changed = curbuf->b_changed;
9152 old_curbuf = curbuf;
9153
9154 /*
9155 * Set the file name to be used for <afile>.
Bram Moolenaara0174af2008-01-02 20:08:25 +00009156 * Make a copy to avoid that changing a buffer name or directory makes it
9157 * invalid.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009158 */
9159 if (fname_io == NULL)
9160 {
9161 if (fname != NULL && *fname != NUL)
9162 autocmd_fname = fname;
9163 else if (buf != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009164 autocmd_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009165 else
9166 autocmd_fname = NULL;
9167 }
9168 else
9169 autocmd_fname = fname_io;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009170 if (autocmd_fname != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009171 autocmd_fname = vim_strsave(autocmd_fname);
9172 autocmd_fname_full = FALSE; /* call FullName_save() later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009173
9174 /*
9175 * Set the buffer number to be used for <abuf>.
9176 */
9177 if (buf == NULL)
9178 autocmd_bufnr = 0;
9179 else
9180 autocmd_bufnr = buf->b_fnum;
9181
9182 /*
9183 * When the file name is NULL or empty, use the file name of buffer "buf".
9184 * Always use the full path of the file name to match with, in case
9185 * "allow_dirs" is set.
9186 */
9187 if (fname == NULL || *fname == NUL)
9188 {
9189 if (buf == NULL)
9190 fname = NULL;
9191 else
9192 {
9193#ifdef FEAT_SYN_HL
9194 if (event == EVENT_SYNTAX)
9195 fname = buf->b_p_syn;
9196 else
9197#endif
9198 if (event == EVENT_FILETYPE)
9199 fname = buf->b_p_ft;
9200 else
9201 {
9202 if (buf->b_sfname != NULL)
9203 sfname = vim_strsave(buf->b_sfname);
9204 fname = buf->b_ffname;
9205 }
9206 }
9207 if (fname == NULL)
9208 fname = (char_u *)"";
9209 fname = vim_strsave(fname); /* make a copy, so we can change it */
9210 }
9211 else
9212 {
9213 sfname = vim_strsave(fname);
Bram Moolenaar5135d462009-04-29 16:03:38 +00009214 /* Don't try expanding FileType, Syntax, FuncUndefined, WindowID or
9215 * QuickFixCmd* */
Bram Moolenaar7c626922005-02-07 22:01:03 +00009216 if (event == EVENT_FILETYPE
9217 || event == EVENT_SYNTAX
Bram Moolenaar5135d462009-04-29 16:03:38 +00009218 || event == EVENT_FUNCUNDEFINED
Bram Moolenaar7c626922005-02-07 22:01:03 +00009219 || event == EVENT_REMOTEREPLY
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00009220 || event == EVENT_SPELLFILEMISSING
Bram Moolenaar7c626922005-02-07 22:01:03 +00009221 || event == EVENT_QUICKFIXCMDPRE
9222 || event == EVENT_QUICKFIXCMDPOST)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009223 fname = vim_strsave(fname);
9224 else
9225 fname = FullName_save(fname, FALSE);
9226 }
9227 if (fname == NULL) /* out of memory */
9228 {
9229 vim_free(sfname);
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009230 retval = FALSE;
9231 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009232 }
9233
9234#ifdef BACKSLASH_IN_FILENAME
9235 /*
9236 * Replace all backslashes with forward slashes. This makes the
9237 * autocommand patterns portable between Unix and MS-DOS.
9238 */
9239 if (sfname != NULL)
9240 forward_slash(sfname);
9241 forward_slash(fname);
9242#endif
9243
9244#ifdef VMS
9245 /* remove version for correct match */
9246 if (sfname != NULL)
9247 vms_remove_version(sfname);
9248 vms_remove_version(fname);
9249#endif
9250
9251 /*
9252 * Set the name to be used for <amatch>.
9253 */
9254 autocmd_match = fname;
9255
9256
9257 /* Don't redraw while doing auto commands. */
9258 ++RedrawingDisabled;
9259 save_sourcing_name = sourcing_name;
9260 sourcing_name = NULL; /* don't free this one */
9261 save_sourcing_lnum = sourcing_lnum;
9262 sourcing_lnum = 0; /* no line number here */
9263
9264#ifdef FEAT_EVAL
9265 save_current_SID = current_SID;
9266
Bram Moolenaar05159a02005-02-26 23:04:13 +00009267# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009268 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009269 prof_child_enter(&wait_time); /* doesn't count for the caller itself */
9270# endif
9271
Bram Moolenaar071d4272004-06-13 20:20:40 +00009272 /* Don't use local function variables, if called from a function */
9273 save_funccalp = save_funccal();
9274#endif
9275
9276 /*
9277 * When starting to execute autocommands, save the search patterns.
9278 */
9279 if (!autocmd_busy)
9280 {
9281 save_search_patterns();
9282 saveRedobuff();
9283 did_filetype = keep_filetype;
9284 }
9285
9286 /*
9287 * Note that we are applying autocmds. Some commands need to know.
9288 */
9289 autocmd_busy = TRUE;
9290 filechangeshell_busy = (event == EVENT_FILECHANGEDSHELL);
9291 ++nesting; /* see matching decrement below */
9292
9293 /* Remember that FileType was triggered. Used for did_filetype(). */
9294 if (event == EVENT_FILETYPE)
9295 did_filetype = TRUE;
9296
9297 tail = gettail(fname);
9298
9299 /* Find first autocommand that matches */
9300 patcmd.curpat = first_autopat[(int)event];
9301 patcmd.nextcmd = NULL;
9302 patcmd.group = group;
9303 patcmd.fname = fname;
9304 patcmd.sfname = sfname;
9305 patcmd.tail = tail;
9306 patcmd.event = event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009307 patcmd.arg_bufnr = autocmd_bufnr;
9308 patcmd.next = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009309 auto_next_pat(&patcmd, FALSE);
9310
9311 /* found one, start executing the autocommands */
9312 if (patcmd.curpat != NULL)
9313 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009314 /* add to active_apc_list */
9315 patcmd.next = active_apc_list;
9316 active_apc_list = &patcmd;
9317
Bram Moolenaar071d4272004-06-13 20:20:40 +00009318#ifdef FEAT_EVAL
9319 /* set v:cmdarg (only when there is a matching pattern) */
9320 save_cmdbang = get_vim_var_nr(VV_CMDBANG);
9321 if (eap != NULL)
9322 {
9323 save_cmdarg = set_cmdarg(eap, NULL);
9324 set_vim_var_nr(VV_CMDBANG, (long)eap->forceit);
9325 }
9326 else
9327 save_cmdarg = NULL; /* avoid gcc warning */
9328#endif
9329 retval = TRUE;
9330 /* mark the last pattern, to avoid an endless loop when more patterns
9331 * are added when executing autocommands */
9332 for (ap = patcmd.curpat; ap->next != NULL; ap = ap->next)
9333 ap->last = FALSE;
9334 ap->last = TRUE;
9335 check_lnums(TRUE); /* make sure cursor and topline are valid */
9336 do_cmdline(NULL, getnextac, (void *)&patcmd,
9337 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
9338#ifdef FEAT_EVAL
9339 if (eap != NULL)
9340 {
9341 (void)set_cmdarg(NULL, save_cmdarg);
9342 set_vim_var_nr(VV_CMDBANG, save_cmdbang);
9343 }
9344#endif
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009345 /* delete from active_apc_list */
9346 if (active_apc_list == &patcmd) /* just in case */
9347 active_apc_list = patcmd.next;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009348 }
9349
9350 --RedrawingDisabled;
9351 autocmd_busy = save_autocmd_busy;
9352 filechangeshell_busy = FALSE;
9353 autocmd_nested = save_autocmd_nested;
9354 vim_free(sourcing_name);
9355 sourcing_name = save_sourcing_name;
9356 sourcing_lnum = save_sourcing_lnum;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009357 vim_free(autocmd_fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009358 autocmd_fname = save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009359 autocmd_fname_full = save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009360 autocmd_bufnr = save_autocmd_bufnr;
9361 autocmd_match = save_autocmd_match;
9362#ifdef FEAT_EVAL
9363 current_SID = save_current_SID;
9364 restore_funccal(save_funccalp);
Bram Moolenaar05159a02005-02-26 23:04:13 +00009365# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009366 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009367 prof_child_exit(&wait_time);
9368# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009369#endif
9370 vim_free(fname);
9371 vim_free(sfname);
9372 --nesting; /* see matching increment above */
9373
9374 /*
9375 * When stopping to execute autocommands, restore the search patterns and
9376 * the redo buffer.
9377 */
9378 if (!autocmd_busy)
9379 {
9380 restore_search_patterns();
9381 restoreRedobuff();
9382 did_filetype = FALSE;
9383 }
9384
9385 /*
9386 * Some events don't set or reset the Changed flag.
9387 * Check if still in the same buffer!
9388 */
9389 if (curbuf == old_curbuf
9390 && (event == EVENT_BUFREADPOST
9391 || event == EVENT_BUFWRITEPOST
9392 || event == EVENT_FILEAPPENDPOST
9393 || event == EVENT_VIMLEAVE
9394 || event == EVENT_VIMLEAVEPRE))
9395 {
9396#ifdef FEAT_TITLE
9397 if (curbuf->b_changed != save_changed)
9398 need_maketitle = TRUE;
9399#endif
9400 curbuf->b_changed = save_changed;
9401 }
9402
9403 au_cleanup(); /* may really delete removed patterns/commands now */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009404
9405BYPASS_AU:
9406 /* When wiping out a buffer make sure all its buffer-local autocommands
9407 * are deleted. */
9408 if (event == EVENT_BUFWIPEOUT && buf != NULL)
9409 aubuflocal_remove(buf);
9410
Bram Moolenaar071d4272004-06-13 20:20:40 +00009411 return retval;
9412}
9413
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009414# ifdef FEAT_EVAL
9415static char_u *old_termresponse = NULL;
9416# endif
9417
9418/*
9419 * Block triggering autocommands until unblock_autocmd() is called.
9420 * Can be used recursively, so long as it's symmetric.
9421 */
9422 void
9423block_autocmds()
9424{
9425# ifdef FEAT_EVAL
9426 /* Remember the value of v:termresponse. */
9427 if (autocmd_blocked == 0)
9428 old_termresponse = get_vim_var_str(VV_TERMRESPONSE);
9429# endif
9430 ++autocmd_blocked;
9431}
9432
9433 void
9434unblock_autocmds()
9435{
9436 --autocmd_blocked;
9437
9438# ifdef FEAT_EVAL
9439 /* When v:termresponse was set while autocommands were blocked, trigger
9440 * the autocommands now. Esp. useful when executing a shell command
9441 * during startup (vimdiff). */
9442 if (autocmd_blocked == 0
9443 && get_vim_var_str(VV_TERMRESPONSE) != old_termresponse)
9444 apply_autocmds(EVENT_TERMRESPONSE, NULL, NULL, FALSE, curbuf);
9445# endif
9446}
9447
Bram Moolenaar071d4272004-06-13 20:20:40 +00009448/*
9449 * Find next autocommand pattern that matches.
9450 */
9451 static void
9452auto_next_pat(apc, stop_at_last)
9453 AutoPatCmd *apc;
9454 int stop_at_last; /* stop when 'last' flag is set */
9455{
9456 AutoPat *ap;
9457 AutoCmd *cp;
9458 char_u *name;
9459 char *s;
9460
9461 vim_free(sourcing_name);
9462 sourcing_name = NULL;
9463
9464 for (ap = apc->curpat; ap != NULL && !got_int; ap = ap->next)
9465 {
9466 apc->curpat = NULL;
9467
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009468 /* Only use a pattern when it has not been removed, has commands and
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009469 * the group matches. For buffer-local autocommands only check the
9470 * buffer number. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009471 if (ap->pat != NULL && ap->cmds != NULL
9472 && (apc->group == AUGROUP_ALL || apc->group == ap->group))
9473 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009474 /* execution-condition */
9475 if (ap->buflocal_nr == 0
Bram Moolenaar748bf032005-02-02 23:04:36 +00009476 ? (match_file_pat(NULL, ap->reg_prog, apc->fname,
9477 apc->sfname, apc->tail, ap->allow_dirs))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009478 : ap->buflocal_nr == apc->arg_bufnr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009479 {
9480 name = event_nr2name(apc->event);
9481 s = _("%s Auto commands for \"%s\"");
9482 sourcing_name = alloc((unsigned)(STRLEN(s)
9483 + STRLEN(name) + ap->patlen + 1));
9484 if (sourcing_name != NULL)
9485 {
9486 sprintf((char *)sourcing_name, s,
9487 (char *)name, (char *)ap->pat);
9488 if (p_verbose >= 8)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009489 {
9490 verbose_enter();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009491 smsg((char_u *)_("Executing %s"), sourcing_name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009492 verbose_leave();
9493 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009494 }
9495
9496 apc->curpat = ap;
9497 apc->nextcmd = ap->cmds;
9498 /* mark last command */
9499 for (cp = ap->cmds; cp->next != NULL; cp = cp->next)
9500 cp->last = FALSE;
9501 cp->last = TRUE;
9502 }
9503 line_breakcheck();
9504 if (apc->curpat != NULL) /* found a match */
9505 break;
9506 }
9507 if (stop_at_last && ap->last)
9508 break;
9509 }
9510}
9511
9512/*
9513 * Get next autocommand command.
9514 * Called by do_cmdline() to get the next line for ":if".
9515 * Returns allocated string, or NULL for end of autocommands.
9516 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009517 static char_u *
9518getnextac(c, cookie, indent)
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009519 int c UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009520 void *cookie;
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009521 int indent UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009522{
9523 AutoPatCmd *acp = (AutoPatCmd *)cookie;
9524 char_u *retval;
9525 AutoCmd *ac;
9526
9527 /* Can be called again after returning the last line. */
9528 if (acp->curpat == NULL)
9529 return NULL;
9530
9531 /* repeat until we find an autocommand to execute */
9532 for (;;)
9533 {
9534 /* skip removed commands */
9535 while (acp->nextcmd != NULL && acp->nextcmd->cmd == NULL)
9536 if (acp->nextcmd->last)
9537 acp->nextcmd = NULL;
9538 else
9539 acp->nextcmd = acp->nextcmd->next;
9540
9541 if (acp->nextcmd != NULL)
9542 break;
9543
9544 /* at end of commands, find next pattern that matches */
9545 if (acp->curpat->last)
9546 acp->curpat = NULL;
9547 else
9548 acp->curpat = acp->curpat->next;
9549 if (acp->curpat != NULL)
9550 auto_next_pat(acp, TRUE);
9551 if (acp->curpat == NULL)
9552 return NULL;
9553 }
9554
9555 ac = acp->nextcmd;
9556
9557 if (p_verbose >= 9)
9558 {
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009559 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009560 smsg((char_u *)_("autocommand %s"), ac->cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009561 msg_puts((char_u *)"\n"); /* don't overwrite this either */
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009562 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009563 }
9564 retval = vim_strsave(ac->cmd);
9565 autocmd_nested = ac->nested;
9566#ifdef FEAT_EVAL
9567 current_SID = ac->scriptID;
9568#endif
9569 if (ac->last)
9570 acp->nextcmd = NULL;
9571 else
9572 acp->nextcmd = ac->next;
9573 return retval;
9574}
9575
9576/*
9577 * Return TRUE if there is a matching autocommand for "fname".
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009578 * To account for buffer-local autocommands, function needs to know
9579 * in which buffer the file will be opened.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009580 */
9581 int
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009582has_autocmd(event, sfname, buf)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009583 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009584 char_u *sfname;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009585 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009586{
9587 AutoPat *ap;
9588 char_u *fname;
9589 char_u *tail = gettail(sfname);
9590 int retval = FALSE;
9591
9592 fname = FullName_save(sfname, FALSE);
9593 if (fname == NULL)
9594 return FALSE;
9595
9596#ifdef BACKSLASH_IN_FILENAME
9597 /*
9598 * Replace all backslashes with forward slashes. This makes the
9599 * autocommand patterns portable between Unix and MS-DOS.
9600 */
9601 sfname = vim_strsave(sfname);
9602 if (sfname != NULL)
9603 forward_slash(sfname);
9604 forward_slash(fname);
9605#endif
9606
9607 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
9608 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009609 && (ap->buflocal_nr == 0
Bram Moolenaar748bf032005-02-02 23:04:36 +00009610 ? match_file_pat(NULL, ap->reg_prog,
9611 fname, sfname, tail, ap->allow_dirs)
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009612 : buf != NULL && ap->buflocal_nr == buf->b_fnum
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009613 ))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009614 {
9615 retval = TRUE;
9616 break;
9617 }
9618
9619 vim_free(fname);
9620#ifdef BACKSLASH_IN_FILENAME
9621 vim_free(sfname);
9622#endif
9623
9624 return retval;
9625}
9626
9627#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
9628/*
9629 * Function given to ExpandGeneric() to obtain the list of autocommand group
9630 * names.
9631 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009632 char_u *
9633get_augroup_name(xp, idx)
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009634 expand_T *xp UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009635 int idx;
9636{
9637 if (idx == augroups.ga_len) /* add "END" add the end */
9638 return (char_u *)"END";
9639 if (idx >= augroups.ga_len) /* end of list */
9640 return NULL;
9641 if (AUGROUP_NAME(idx) == NULL) /* skip deleted entries */
9642 return (char_u *)"";
9643 return AUGROUP_NAME(idx); /* return a name */
9644}
9645
9646static int include_groups = FALSE;
9647
9648 char_u *
9649set_context_in_autocmd(xp, arg, doautocmd)
9650 expand_T *xp;
9651 char_u *arg;
Bram Moolenaard812df62008-11-09 12:46:09 +00009652 int doautocmd; /* TRUE for :doauto*, FALSE for :autocmd */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009653{
9654 char_u *p;
9655 int group;
9656
9657 /* check for a group name, skip it if present */
9658 include_groups = FALSE;
9659 p = arg;
9660 group = au_get_grouparg(&arg);
9661 if (group == AUGROUP_ERROR)
9662 return NULL;
9663 /* If there only is a group name that's what we expand. */
9664 if (*arg == NUL && group != AUGROUP_ALL && !vim_iswhite(arg[-1]))
9665 {
9666 arg = p;
9667 group = AUGROUP_ALL;
9668 }
9669
9670 /* skip over event name */
9671 for (p = arg; *p != NUL && !vim_iswhite(*p); ++p)
9672 if (*p == ',')
9673 arg = p + 1;
9674 if (*p == NUL)
9675 {
9676 if (group == AUGROUP_ALL)
9677 include_groups = TRUE;
9678 xp->xp_context = EXPAND_EVENTS; /* expand event name */
9679 xp->xp_pattern = arg;
9680 return NULL;
9681 }
9682
9683 /* skip over pattern */
9684 arg = skipwhite(p);
9685 while (*arg && (!vim_iswhite(*arg) || arg[-1] == '\\'))
9686 arg++;
9687 if (*arg)
9688 return arg; /* expand (next) command */
9689
9690 if (doautocmd)
9691 xp->xp_context = EXPAND_FILES; /* expand file names */
9692 else
9693 xp->xp_context = EXPAND_NOTHING; /* pattern is not expanded */
9694 return NULL;
9695}
9696
9697/*
9698 * Function given to ExpandGeneric() to obtain the list of event names.
9699 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009700 char_u *
9701get_event_name(xp, idx)
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009702 expand_T *xp UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009703 int idx;
9704{
9705 if (idx < augroups.ga_len) /* First list group names, if wanted */
9706 {
9707 if (!include_groups || AUGROUP_NAME(idx) == NULL)
9708 return (char_u *)""; /* skip deleted entries */
9709 return AUGROUP_NAME(idx); /* return a name */
9710 }
9711 return (char_u *)event_names[idx - augroups.ga_len].name;
9712}
9713
9714#endif /* FEAT_CMDL_COMPL */
9715
9716/*
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009717 * Return TRUE if autocmd is supported.
9718 */
9719 int
9720autocmd_supported(name)
9721 char_u *name;
9722{
9723 char_u *p;
9724
9725 return (event_name2nr(name, &p) != NUM_EVENTS);
9726}
9727
9728/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00009729 * Return TRUE if an autocommand is defined for a group, event and
9730 * pattern: The group can be omitted to accept any group. "event" and "pattern"
9731 * can be NULL to accept any event and pattern. "pattern" can be NULL to accept
9732 * any pattern. Buffer-local patterns <buffer> or <buffer=N> are accepted.
9733 * Used for:
9734 * exists("#Group") or
9735 * exists("#Group#Event") or
9736 * exists("#Group#Event#pat") or
9737 * exists("#Event") or
9738 * exists("#Event#pat")
Bram Moolenaar071d4272004-06-13 20:20:40 +00009739 */
9740 int
Bram Moolenaar195d6352005-12-19 22:08:24 +00009741au_exists(arg)
9742 char_u *arg;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009743{
Bram Moolenaar195d6352005-12-19 22:08:24 +00009744 char_u *arg_save;
9745 char_u *pattern = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009746 char_u *event_name;
9747 char_u *p;
Bram Moolenaar754b5602006-02-09 23:53:20 +00009748 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009749 AutoPat *ap;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009750 buf_T *buflocal_buf = NULL;
Bram Moolenaar195d6352005-12-19 22:08:24 +00009751 int group;
9752 int retval = FALSE;
9753
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009754 /* Make a copy so that we can change the '#' chars to a NUL. */
Bram Moolenaar195d6352005-12-19 22:08:24 +00009755 arg_save = vim_strsave(arg);
9756 if (arg_save == NULL)
9757 return FALSE;
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009758 p = vim_strchr(arg_save, '#');
Bram Moolenaar195d6352005-12-19 22:08:24 +00009759 if (p != NULL)
9760 *p++ = NUL;
9761
9762 /* First, look for an autocmd group name */
9763 group = au_find_group(arg_save);
9764 if (group == AUGROUP_ERROR)
9765 {
9766 /* Didn't match a group name, assume the first argument is an event. */
9767 group = AUGROUP_ALL;
9768 event_name = arg_save;
9769 }
9770 else
9771 {
9772 if (p == NULL)
9773 {
9774 /* "Group": group name is present and it's recognized */
9775 retval = TRUE;
9776 goto theend;
9777 }
9778
9779 /* Must be "Group#Event" or "Group#Event#pat". */
9780 event_name = p;
9781 p = vim_strchr(event_name, '#');
9782 if (p != NULL)
9783 *p++ = NUL; /* "Group#Event#pat" */
9784 }
9785
9786 pattern = p; /* "pattern" is NULL when there is no pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009787
9788 /* find the index (enum) for the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009789 event = event_name2nr(event_name, &p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009790
9791 /* return FALSE if the event name is not recognized */
Bram Moolenaar195d6352005-12-19 22:08:24 +00009792 if (event == NUM_EVENTS)
9793 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009794
9795 /* Find the first autocommand for this event.
9796 * If there isn't any, return FALSE;
9797 * If there is one and no pattern given, return TRUE; */
9798 ap = first_autopat[(int)event];
9799 if (ap == NULL)
Bram Moolenaar195d6352005-12-19 22:08:24 +00009800 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009801
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009802 /* if pattern is "<buffer>", special handling is needed which uses curbuf */
9803 /* for pattern "<buffer=N>, fnamecmp() will work fine */
Bram Moolenaar5b7880d2009-09-11 15:24:31 +00009804 if (pattern != NULL && STRICMP(pattern, "<buffer>") == 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009805 buflocal_buf = curbuf;
9806
Bram Moolenaar071d4272004-06-13 20:20:40 +00009807 /* Check if there is an autocommand with the given pattern. */
9808 for ( ; ap != NULL; ap = ap->next)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009809 /* only use a pattern when it has not been removed and has commands. */
9810 /* For buffer-local autocommands, fnamecmp() works fine. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009811 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaar195d6352005-12-19 22:08:24 +00009812 && (group == AUGROUP_ALL || ap->group == group)
Bram Moolenaar5b7880d2009-09-11 15:24:31 +00009813 && (pattern == NULL
9814 || (buflocal_buf == NULL
9815 ? fnamecmp(ap->pat, pattern) == 0
9816 : ap->buflocal_nr == buflocal_buf->b_fnum)))
Bram Moolenaar195d6352005-12-19 22:08:24 +00009817 {
9818 retval = TRUE;
9819 break;
9820 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009821
Bram Moolenaar195d6352005-12-19 22:08:24 +00009822theend:
9823 vim_free(arg_save);
9824 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009825}
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009826
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009827#else /* FEAT_AUTOCMD */
9828
9829/*
9830 * Prepare for executing commands for (hidden) buffer "buf".
9831 * This is the non-autocommand version, it simply saves "curbuf" and sets
9832 * "curbuf" and "curwin" to match "buf".
9833 */
9834 void
9835aucmd_prepbuf(aco, buf)
9836 aco_save_T *aco; /* structure to save values in */
9837 buf_T *buf; /* new curbuf */
9838{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009839 aco->save_curbuf = curbuf;
9840 --curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009841 curbuf = buf;
9842 curwin->w_buffer = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009843 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009844}
9845
9846/*
9847 * Restore after executing commands for a (hidden) buffer.
9848 * This is the non-autocommand version.
9849 */
9850 void
9851aucmd_restbuf(aco)
9852 aco_save_T *aco; /* structure holding saved values */
9853{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009854 --curbuf->b_nwindows;
9855 curbuf = aco->save_curbuf;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009856 curwin->w_buffer = curbuf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009857 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009858}
9859
Bram Moolenaar071d4272004-06-13 20:20:40 +00009860#endif /* FEAT_AUTOCMD */
9861
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009862
Bram Moolenaar071d4272004-06-13 20:20:40 +00009863#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN) || defined(PROTO)
9864/*
Bram Moolenaar748bf032005-02-02 23:04:36 +00009865 * Try matching a filename with a "pattern" ("prog" is NULL), or use the
9866 * precompiled regprog "prog" ("pattern" is NULL). That avoids calling
9867 * vim_regcomp() often.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009868 * Used for autocommands and 'wildignore'.
9869 * Returns TRUE if there is a match, FALSE otherwise.
9870 */
9871 int
Bram Moolenaar748bf032005-02-02 23:04:36 +00009872match_file_pat(pattern, prog, fname, sfname, tail, allow_dirs)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009873 char_u *pattern; /* pattern to match with */
Bram Moolenaar748bf032005-02-02 23:04:36 +00009874 regprog_T *prog; /* pre-compiled regprog or NULL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009875 char_u *fname; /* full path of file name */
9876 char_u *sfname; /* short file name or NULL */
9877 char_u *tail; /* tail of path */
9878 int allow_dirs; /* allow matching with dir */
9879{
9880 regmatch_T regmatch;
9881 int result = FALSE;
9882#ifdef FEAT_OSFILETYPE
9883 int no_pattern = FALSE; /* TRUE if check is filetype only */
9884 char_u *type_start;
9885 char_u c;
9886 int match = FALSE;
9887#endif
9888
9889#ifdef CASE_INSENSITIVE_FILENAME
9890 regmatch.rm_ic = TRUE; /* Always ignore case */
9891#else
9892 regmatch.rm_ic = FALSE; /* Don't ever ignore case */
9893#endif
9894#ifdef FEAT_OSFILETYPE
9895 if (*pattern == '<')
9896 {
9897 /* There is a filetype condition specified with this pattern.
9898 * Check the filetype matches first. If not, don't bother with the
9899 * pattern (set regprog to NULL).
9900 * Always use magic for the regexp.
9901 */
9902
9903 for (type_start = pattern + 1; (c = *pattern); pattern++)
9904 {
9905 if ((c == ';' || c == '>') && match == FALSE)
9906 {
9907 *pattern = NUL; /* Terminate the string */
9908 match = mch_check_filetype(fname, type_start);
9909 *pattern = c; /* Restore the terminator */
9910 type_start = pattern + 1;
9911 }
9912 if (c == '>')
9913 break;
9914 }
9915
9916 /* (c should never be NUL, but check anyway) */
9917 if (match == FALSE || c == NUL)
9918 regmatch.regprog = NULL; /* Doesn't match - don't check pat. */
9919 else if (*pattern == NUL)
9920 {
9921 regmatch.regprog = NULL; /* Vim will try to free regprog later */
9922 no_pattern = TRUE; /* Always matches - don't check pat. */
9923 }
9924 else
9925 regmatch.regprog = vim_regcomp(pattern + 1, RE_MAGIC);
9926 }
9927 else
9928#endif
Bram Moolenaar748bf032005-02-02 23:04:36 +00009929 {
9930 if (prog != NULL)
9931 regmatch.regprog = prog;
9932 else
9933 regmatch.regprog = vim_regcomp(pattern, RE_MAGIC);
9934 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009935
9936 /*
9937 * Try for a match with the pattern with:
9938 * 1. the full file name, when the pattern has a '/'.
9939 * 2. the short file name, when the pattern has a '/'.
9940 * 3. the tail of the file name, when the pattern has no '/'.
9941 */
9942 if (
9943#ifdef FEAT_OSFILETYPE
9944 /* If the check is for a filetype only and we don't care
9945 * about the path then skip all the regexp stuff.
9946 */
9947 no_pattern ||
9948#endif
9949 (regmatch.regprog != NULL
9950 && ((allow_dirs
9951 && (vim_regexec(&regmatch, fname, (colnr_T)0)
9952 || (sfname != NULL
9953 && vim_regexec(&regmatch, sfname, (colnr_T)0))))
9954 || (!allow_dirs && vim_regexec(&regmatch, tail, (colnr_T)0)))))
9955 result = TRUE;
9956
Bram Moolenaar748bf032005-02-02 23:04:36 +00009957 if (prog == NULL)
9958 vim_free(regmatch.regprog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009959 return result;
9960}
9961#endif
9962
9963#if defined(FEAT_WILDIGN) || defined(PROTO)
9964/*
9965 * Return TRUE if a file matches with a pattern in "list".
9966 * "list" is a comma-separated list of patterns, like 'wildignore'.
9967 * "sfname" is the short file name or NULL, "ffname" the long file name.
9968 */
9969 int
9970match_file_list(list, sfname, ffname)
9971 char_u *list;
9972 char_u *sfname;
9973 char_u *ffname;
9974{
9975 char_u buf[100];
9976 char_u *tail;
9977 char_u *regpat;
9978 char allow_dirs;
9979 int match;
9980 char_u *p;
9981
9982 tail = gettail(sfname);
9983
9984 /* try all patterns in 'wildignore' */
9985 p = list;
9986 while (*p)
9987 {
9988 copy_option_part(&p, buf, 100, ",");
9989 regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, FALSE);
9990 if (regpat == NULL)
9991 break;
Bram Moolenaar748bf032005-02-02 23:04:36 +00009992 match = match_file_pat(regpat, NULL, ffname, sfname,
9993 tail, (int)allow_dirs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009994 vim_free(regpat);
9995 if (match)
9996 return TRUE;
9997 }
9998 return FALSE;
9999}
10000#endif
10001
10002/*
10003 * Convert the given pattern "pat" which has shell style wildcards in it, into
10004 * a regular expression, and return the result in allocated memory. If there
10005 * is a directory path separator to be matched, then TRUE is put in
10006 * allow_dirs, otherwise FALSE is put there -- webb.
10007 * Handle backslashes before special characters, like "\*" and "\ ".
10008 *
10009 * If FEAT_OSFILETYPE defined then pass initial <type> through unchanged. Eg:
10010 * '<html>myfile' becomes '<html>^myfile$' -- leonard.
10011 *
10012 * Returns NULL when out of memory.
10013 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010014 char_u *
10015file_pat_to_reg_pat(pat, pat_end, allow_dirs, no_bslash)
10016 char_u *pat;
10017 char_u *pat_end; /* first char after pattern or NULL */
10018 char *allow_dirs; /* Result passed back out in here */
Bram Moolenaar78a15312009-05-15 19:33:18 +000010019 int no_bslash UNUSED; /* Don't use a backward slash as pathsep */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010020{
10021 int size;
10022 char_u *endp;
10023 char_u *reg_pat;
10024 char_u *p;
10025 int i;
10026 int nested = 0;
10027 int add_dollar = TRUE;
10028#ifdef FEAT_OSFILETYPE
10029 int check_length = 0;
10030#endif
10031
10032 if (allow_dirs != NULL)
10033 *allow_dirs = FALSE;
10034 if (pat_end == NULL)
10035 pat_end = pat + STRLEN(pat);
10036
10037#ifdef FEAT_OSFILETYPE
10038 /* Find out how much of the string is the filetype check */
10039 if (*pat == '<')
10040 {
10041 /* Count chars until the next '>' */
10042 for (p = pat + 1; p < pat_end && *p != '>'; p++)
10043 ;
10044 if (p < pat_end)
10045 {
10046 /* Pattern is of the form <.*>.* */
10047 check_length = p - pat + 1;
10048 if (p + 1 >= pat_end)
10049 {
10050 /* The 'pattern' is a filetype check ONLY */
10051 reg_pat = (char_u *)alloc(check_length + 1);
10052 if (reg_pat != NULL)
10053 {
10054 mch_memmove(reg_pat, pat, (size_t)check_length);
10055 reg_pat[check_length] = NUL;
10056 }
10057 return reg_pat;
10058 }
10059 }
10060 /* else: there was no closing '>' - assume it was a normal pattern */
10061
10062 }
10063 pat += check_length;
10064 size = 2 + check_length;
10065#else
10066 size = 2; /* '^' at start, '$' at end */
10067#endif
10068
10069 for (p = pat; p < pat_end; p++)
10070 {
10071 switch (*p)
10072 {
10073 case '*':
10074 case '.':
10075 case ',':
10076 case '{':
10077 case '}':
10078 case '~':
10079 size += 2; /* extra backslash */
10080 break;
10081#ifdef BACKSLASH_IN_FILENAME
10082 case '\\':
10083 case '/':
10084 size += 4; /* could become "[\/]" */
10085 break;
10086#endif
10087 default:
10088 size++;
10089# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010090 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010091 {
10092 ++p;
10093 ++size;
10094 }
10095# endif
10096 break;
10097 }
10098 }
10099 reg_pat = alloc(size + 1);
10100 if (reg_pat == NULL)
10101 return NULL;
10102
10103#ifdef FEAT_OSFILETYPE
10104 /* Copy the type check in to the start. */
10105 if (check_length)
10106 mch_memmove(reg_pat, pat - check_length, (size_t)check_length);
10107 i = check_length;
10108#else
10109 i = 0;
10110#endif
10111
10112 if (pat[0] == '*')
10113 while (pat[0] == '*' && pat < pat_end - 1)
10114 pat++;
10115 else
10116 reg_pat[i++] = '^';
10117 endp = pat_end - 1;
10118 if (*endp == '*')
10119 {
10120 while (endp - pat > 0 && *endp == '*')
10121 endp--;
10122 add_dollar = FALSE;
10123 }
10124 for (p = pat; *p && nested >= 0 && p <= endp; p++)
10125 {
10126 switch (*p)
10127 {
10128 case '*':
10129 reg_pat[i++] = '.';
10130 reg_pat[i++] = '*';
Bram Moolenaar02743632005-07-25 20:42:36 +000010131 while (p[1] == '*') /* "**" matches like "*" */
10132 ++p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010133 break;
10134 case '.':
10135#ifdef RISCOS
10136 if (allow_dirs != NULL)
10137 *allow_dirs = TRUE;
10138 /* FALLTHROUGH */
10139#endif
10140 case '~':
10141 reg_pat[i++] = '\\';
10142 reg_pat[i++] = *p;
10143 break;
10144 case '?':
10145#ifdef RISCOS
10146 case '#':
10147#endif
10148 reg_pat[i++] = '.';
10149 break;
10150 case '\\':
10151 if (p[1] == NUL)
10152 break;
10153#ifdef BACKSLASH_IN_FILENAME
10154 if (!no_bslash)
10155 {
10156 /* translate:
10157 * "\x" to "\\x" e.g., "dir\file"
10158 * "\*" to "\\.*" e.g., "dir\*.c"
10159 * "\?" to "\\." e.g., "dir\??.c"
10160 * "\+" to "\+" e.g., "fileX\+.c"
10161 */
10162 if ((vim_isfilec(p[1]) || p[1] == '*' || p[1] == '?')
10163 && p[1] != '+')
10164 {
10165 reg_pat[i++] = '[';
10166 reg_pat[i++] = '\\';
10167 reg_pat[i++] = '/';
10168 reg_pat[i++] = ']';
10169 if (allow_dirs != NULL)
10170 *allow_dirs = TRUE;
10171 break;
10172 }
10173 }
10174#endif
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010175 /* Undo escaping from ExpandEscape():
10176 * foo\?bar -> foo?bar
10177 * foo\%bar -> foo%bar
10178 * foo\,bar -> foo,bar
10179 * foo\ bar -> foo bar
10180 * Don't unescape \, * and others that are also special in a
10181 * regexp. */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010182 if (*++p == '?'
10183#ifdef BACKSLASH_IN_FILENAME
10184 && no_bslash
10185#endif
10186 )
10187 reg_pat[i++] = '?';
10188 else
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010189 if (*p == ',' || *p == '%' || *p == '#' || *p == ' ')
10190 reg_pat[i++] = *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010191 else
10192 {
10193 if (allow_dirs != NULL && vim_ispathsep(*p)
10194#ifdef BACKSLASH_IN_FILENAME
10195 && (!no_bslash || *p != '\\')
10196#endif
10197 )
10198 *allow_dirs = TRUE;
10199 reg_pat[i++] = '\\';
10200 reg_pat[i++] = *p;
10201 }
10202 break;
10203#ifdef BACKSLASH_IN_FILENAME
10204 case '/':
10205 reg_pat[i++] = '[';
10206 reg_pat[i++] = '\\';
10207 reg_pat[i++] = '/';
10208 reg_pat[i++] = ']';
10209 if (allow_dirs != NULL)
10210 *allow_dirs = TRUE;
10211 break;
10212#endif
10213 case '{':
10214 reg_pat[i++] = '\\';
10215 reg_pat[i++] = '(';
10216 nested++;
10217 break;
10218 case '}':
10219 reg_pat[i++] = '\\';
10220 reg_pat[i++] = ')';
10221 --nested;
10222 break;
10223 case ',':
10224 if (nested)
10225 {
10226 reg_pat[i++] = '\\';
10227 reg_pat[i++] = '|';
10228 }
10229 else
10230 reg_pat[i++] = ',';
10231 break;
10232 default:
10233# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010234 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010235 reg_pat[i++] = *p++;
10236 else
10237# endif
10238 if (allow_dirs != NULL && vim_ispathsep(*p))
10239 *allow_dirs = TRUE;
10240 reg_pat[i++] = *p;
10241 break;
10242 }
10243 }
10244 if (add_dollar)
10245 reg_pat[i++] = '$';
10246 reg_pat[i] = NUL;
10247 if (nested != 0)
10248 {
10249 if (nested < 0)
10250 EMSG(_("E219: Missing {."));
10251 else
10252 EMSG(_("E220: Missing }."));
10253 vim_free(reg_pat);
10254 reg_pat = NULL;
10255 }
10256 return reg_pat;
10257}