blob: 2881cbc88bcdd0ebf0e9b23f2befe61ff362f6a6 [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 Moolenaar49771f42010-07-20 17:32:38 +020066static int crypt_method_from_magic __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)
Bram Moolenaar59f931e2010-07-24 20:27:03 +0200222 * READ_KEEP_UNDO don't clear undo info or read it from a file
Bram Moolenaar071d4272004-06-13 20:20:40 +0000223 *
224 * return FAIL for failure, OK otherwise
225 */
226 int
227readfile(fname, sfname, from, lines_to_skip, lines_to_read, eap, flags)
228 char_u *fname;
229 char_u *sfname;
230 linenr_T from;
231 linenr_T lines_to_skip;
232 linenr_T lines_to_read;
233 exarg_T *eap; /* can be NULL! */
234 int flags;
235{
236 int fd = 0;
237 int newfile = (flags & READ_NEW);
238 int check_readonly;
239 int filtering = (flags & READ_FILTER);
240 int read_stdin = (flags & READ_STDIN);
241 int read_buffer = (flags & READ_BUFFER);
Bram Moolenaar690ffc02008-01-04 15:31:21 +0000242 int set_options = newfile || read_buffer
243 || (eap != NULL && eap->read_edit);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000244 linenr_T read_buf_lnum = 1; /* next line to read from curbuf */
245 colnr_T read_buf_col = 0; /* next char to read from this line */
246 char_u c;
247 linenr_T lnum = from;
248 char_u *ptr = NULL; /* pointer into read buffer */
249 char_u *buffer = NULL; /* read buffer */
250 char_u *new_buffer = NULL; /* init to shut up gcc */
251 char_u *line_start = NULL; /* init to shut up gcc */
252 int wasempty; /* buffer was empty before reading */
253 colnr_T len;
254 long size = 0;
255 char_u *p;
Bram Moolenaar914703b2010-05-31 21:59:46 +0200256 off_t filesize = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000257 int skip_read = FALSE;
258#ifdef FEAT_CRYPT
259 char_u *cryptkey = NULL;
Bram Moolenaarf50a2532010-05-21 15:36:08 +0200260 int did_ask_for_key = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000261#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +0200262#ifdef FEAT_PERSISTENT_UNDO
263 context_sha256_T sha_ctx;
264 int read_undo_file = FALSE;
265#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000266 int split = 0; /* number of split lines */
267#define UNKNOWN 0x0fffffff /* file size is unknown */
268 linenr_T linecnt;
269 int error = FALSE; /* errors encountered */
270 int ff_error = EOL_UNKNOWN; /* file format with errors */
271 long linerest = 0; /* remaining chars in line */
272#ifdef UNIX
273 int perm = 0;
274 int swap_mode = -1; /* protection bits for swap file */
275#else
276 int perm;
277#endif
278 int fileformat = 0; /* end-of-line format */
279 int keep_fileformat = FALSE;
280 struct stat st;
281 int file_readonly;
282 linenr_T skip_count = 0;
283 linenr_T read_count = 0;
284 int msg_save = msg_scroll;
285 linenr_T read_no_eol_lnum = 0; /* non-zero lnum when last line of
286 * last read was missing the eol */
287 int try_mac = (vim_strchr(p_ffs, 'm') != NULL);
288 int try_dos = (vim_strchr(p_ffs, 'd') != NULL);
289 int try_unix = (vim_strchr(p_ffs, 'x') != NULL);
290 int file_rewind = FALSE;
291#ifdef FEAT_MBYTE
292 int can_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000293 linenr_T conv_error = 0; /* line nr with conversion error */
294 linenr_T illegal_byte = 0; /* line nr with illegal byte */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000295 int keep_dest_enc = FALSE; /* don't retry when char doesn't fit
296 in destination encoding */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000297 int bad_char_behavior = BAD_REPLACE;
298 /* BAD_KEEP, BAD_DROP or character to
299 * replace with */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000300 char_u *tmpname = NULL; /* name of 'charconvert' output file */
301 int fio_flags = 0;
302 char_u *fenc; /* fileencoding to use */
303 int fenc_alloced; /* fenc_next is in allocated memory */
304 char_u *fenc_next = NULL; /* next item in 'fencs' or NULL */
305 int advance_fenc = FALSE;
306 long real_size = 0;
307# ifdef USE_ICONV
308 iconv_t iconv_fd = (iconv_t)-1; /* descriptor for iconv() or -1 */
309# ifdef FEAT_EVAL
310 int did_iconv = FALSE; /* TRUE when iconv() failed and trying
311 'charconvert' next */
312# endif
313# endif
314 int converted = FALSE; /* TRUE if conversion done */
315 int notconverted = FALSE; /* TRUE if conversion wanted but it
316 wasn't possible */
317 char_u conv_rest[CONV_RESTLEN];
318 int conv_restlen = 0; /* nr of bytes in conv_rest[] */
319#endif
320
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000321#ifdef FEAT_AUTOCMD
322 /* Remember the initial values of curbuf, curbuf->b_ffname and
323 * curbuf->b_fname to detect whether they are altered as a result of
324 * executing nasty autocommands. Also check if "fname" and "sfname"
325 * point to one of these values. */
326 buf_T *old_curbuf = curbuf;
327 char_u *old_b_ffname = curbuf->b_ffname;
328 char_u *old_b_fname = curbuf->b_fname;
329 int using_b_ffname = (fname == curbuf->b_ffname)
330 || (sfname == curbuf->b_ffname);
331 int using_b_fname = (fname == curbuf->b_fname)
332 || (sfname == curbuf->b_fname);
333#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000334 write_no_eol_lnum = 0; /* in case it was set by the previous read */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000335
336 /*
337 * If there is no file name yet, use the one for the read file.
338 * BF_NOTEDITED is set to reflect this.
339 * Don't do this for a read from a filter.
340 * Only do this when 'cpoptions' contains the 'f' flag.
341 */
342 if (curbuf->b_ffname == NULL
343 && !filtering
344 && fname != NULL
345 && vim_strchr(p_cpo, CPO_FNAMER) != NULL
346 && !(flags & READ_DUMMY))
347 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000348 if (set_rw_fname(fname, sfname) == FAIL)
349 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000350 }
351
Bram Moolenaardf177f62005-02-22 08:39:57 +0000352 /* After reading a file the cursor line changes but we don't want to
353 * display the line. */
354 ex_no_reprint = TRUE;
355
Bram Moolenaar55b7cf82006-09-09 12:52:42 +0000356 /* don't display the file info for another buffer now */
357 need_fileinfo = FALSE;
358
Bram Moolenaar071d4272004-06-13 20:20:40 +0000359 /*
360 * For Unix: Use the short file name whenever possible.
361 * Avoids problems with networks and when directory names are changed.
362 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
363 * another directory, which we don't detect.
364 */
365 if (sfname == NULL)
366 sfname = fname;
367#if defined(UNIX) || defined(__EMX__)
368 fname = sfname;
369#endif
370
371#ifdef FEAT_AUTOCMD
372 /*
373 * The BufReadCmd and FileReadCmd events intercept the reading process by
374 * executing the associated commands instead.
375 */
376 if (!filtering && !read_stdin && !read_buffer)
377 {
378 pos_T pos;
379
380 pos = curbuf->b_op_start;
381
382 /* Set '[ mark to the line above where the lines go (line 1 if zero). */
383 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
384 curbuf->b_op_start.col = 0;
385
386 if (newfile)
387 {
388 if (apply_autocmds_exarg(EVENT_BUFREADCMD, NULL, sfname,
389 FALSE, curbuf, eap))
390#ifdef FEAT_EVAL
391 return aborting() ? FAIL : OK;
392#else
393 return OK;
394#endif
395 }
396 else if (apply_autocmds_exarg(EVENT_FILEREADCMD, sfname, sfname,
397 FALSE, NULL, eap))
398#ifdef FEAT_EVAL
399 return aborting() ? FAIL : OK;
400#else
401 return OK;
402#endif
403
404 curbuf->b_op_start = pos;
405 }
406#endif
407
408 if ((shortmess(SHM_OVER) || curbuf->b_help) && p_verbose == 0)
409 msg_scroll = FALSE; /* overwrite previous file message */
410 else
411 msg_scroll = TRUE; /* don't overwrite previous file message */
412
413 /*
414 * If the name ends in a path separator, we can't open it. Check here,
415 * because reading the file may actually work, but then creating the swap
416 * file may destroy it! Reported on MS-DOS and Win 95.
417 * If the name is too long we might crash further on, quit here.
418 */
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000419 if (fname != NULL && *fname != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000420 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000421 p = fname + STRLEN(fname);
422 if (after_pathsep(fname, p) || STRLEN(fname) >= MAXPATHL)
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000423 {
424 filemess(curbuf, fname, (char_u *)_("Illegal file name"), 0);
425 msg_end();
426 msg_scroll = msg_save;
427 return FAIL;
428 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000429 }
430
431#ifdef UNIX
432 /*
433 * On Unix it is possible to read a directory, so we have to
434 * check for it before the mch_open().
435 */
436 if (!read_stdin && !read_buffer)
437 {
438 perm = mch_getperm(fname);
439 if (perm >= 0 && !S_ISREG(perm) /* not a regular file ... */
440# ifdef S_ISFIFO
441 && !S_ISFIFO(perm) /* ... or fifo */
442# endif
443# ifdef S_ISSOCK
444 && !S_ISSOCK(perm) /* ... or socket */
445# endif
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +0000446# ifdef OPEN_CHR_FILES
447 && !(S_ISCHR(perm) && is_dev_fd_file(fname))
448 /* ... or a character special file named /dev/fd/<n> */
449# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000450 )
451 {
452 if (S_ISDIR(perm))
453 filemess(curbuf, fname, (char_u *)_("is a directory"), 0);
454 else
455 filemess(curbuf, fname, (char_u *)_("is not a file"), 0);
456 msg_end();
457 msg_scroll = msg_save;
458 return FAIL;
459 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000460
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000461# if defined(MSDOS) || defined(MSWIN) || defined(OS2)
462 /*
463 * MS-Windows allows opening a device, but we will probably get stuck
464 * trying to read it.
465 */
466 if (!p_odev && mch_nodetype(fname) == NODE_WRITABLE)
467 {
Bram Moolenaar5386a122007-06-28 20:02:32 +0000468 filemess(curbuf, fname, (char_u *)_("is a device (disabled with 'opendevice' option)"), 0);
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000469 msg_end();
470 msg_scroll = msg_save;
471 return FAIL;
472 }
473# endif
Bram Moolenaar043545e2006-10-10 16:44:07 +0000474 }
475#endif
476
Bram Moolenaar071d4272004-06-13 20:20:40 +0000477 /* set default 'fileformat' */
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000478 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000479 {
480 if (eap != NULL && eap->force_ff != 0)
481 set_fileformat(get_fileformat_force(curbuf, eap), OPT_LOCAL);
482 else if (*p_ffs != NUL)
483 set_fileformat(default_fileformat(), OPT_LOCAL);
484 }
485
486 /* set or reset 'binary' */
487 if (eap != NULL && eap->force_bin != 0)
488 {
489 int oldval = curbuf->b_p_bin;
490
491 curbuf->b_p_bin = (eap->force_bin == FORCE_BIN);
492 set_options_bin(oldval, curbuf->b_p_bin, OPT_LOCAL);
493 }
494
495 /*
496 * When opening a new file we take the readonly flag from the file.
497 * Default is r/w, can be set to r/o below.
498 * Don't reset it when in readonly mode
499 * Only set/reset b_p_ro when BF_CHECK_RO is set.
500 */
501 check_readonly = (newfile && (curbuf->b_flags & BF_CHECK_RO));
Bram Moolenaar4399ef42005-02-12 14:29:27 +0000502 if (check_readonly && !readonlymode)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000503 curbuf->b_p_ro = FALSE;
504
505 if (newfile && !read_stdin && !read_buffer)
506 {
507 /* Remember time of file.
508 * For RISCOS, also remember the filetype.
509 */
510 if (mch_stat((char *)fname, &st) >= 0)
511 {
512 buf_store_time(curbuf, &st, fname);
513 curbuf->b_mtime_read = curbuf->b_mtime;
514
515#if defined(RISCOS) && defined(FEAT_OSFILETYPE)
516 /* Read the filetype into the buffer local filetype option. */
517 mch_read_filetype(fname);
518#endif
519#ifdef UNIX
520 /*
521 * Use the protection bits of the original file for the swap file.
522 * This makes it possible for others to read the name of the
523 * edited file from the swapfile, but only if they can read the
524 * edited file.
525 * Remove the "write" and "execute" bits for group and others
526 * (they must not write the swapfile).
527 * Add the "read" and "write" bits for the user, otherwise we may
528 * not be able to write to the file ourselves.
529 * Setting the bits is done below, after creating the swap file.
530 */
531 swap_mode = (st.st_mode & 0644) | 0600;
532#endif
533#ifdef FEAT_CW_EDITOR
534 /* Get the FSSpec on MacOS
535 * TODO: Update it properly when the buffer name changes
536 */
537 (void)GetFSSpecFromPath(curbuf->b_ffname, &curbuf->b_FSSpec);
538#endif
539#ifdef VMS
540 curbuf->b_fab_rfm = st.st_fab_rfm;
Bram Moolenaard4755bb2004-09-02 19:12:26 +0000541 curbuf->b_fab_rat = st.st_fab_rat;
542 curbuf->b_fab_mrs = st.st_fab_mrs;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000543#endif
544 }
545 else
546 {
547 curbuf->b_mtime = 0;
548 curbuf->b_mtime_read = 0;
549 curbuf->b_orig_size = 0;
550 curbuf->b_orig_mode = 0;
551 }
552
553 /* Reset the "new file" flag. It will be set again below when the
554 * file doesn't exist. */
555 curbuf->b_flags &= ~(BF_NEW | BF_NEW_W);
556 }
557
558/*
559 * for UNIX: check readonly with perm and mch_access()
560 * for RISCOS: same as Unix, otherwise file gets re-datestamped!
561 * for MSDOS and Amiga: check readonly by trying to open the file for writing
562 */
563 file_readonly = FALSE;
564 if (read_stdin)
565 {
566#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
567 /* Force binary I/O on stdin to avoid CR-LF -> LF conversion. */
568 setmode(0, O_BINARY);
569#endif
570 }
571 else if (!read_buffer)
572 {
573#ifdef USE_MCH_ACCESS
574 if (
575# ifdef UNIX
576 !(perm & 0222) ||
577# endif
578 mch_access((char *)fname, W_OK))
579 file_readonly = TRUE;
580 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
581#else
582 if (!newfile
583 || readonlymode
584 || (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0)
585 {
586 file_readonly = TRUE;
587 /* try to open ro */
588 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
589 }
590#endif
591 }
592
593 if (fd < 0) /* cannot open at all */
594 {
595#ifndef UNIX
596 int isdir_f;
597#endif
598 msg_scroll = msg_save;
599#ifndef UNIX
600 /*
601 * On MSDOS and Amiga we can't open a directory, check here.
602 */
603 isdir_f = (mch_isdir(fname));
604 perm = mch_getperm(fname); /* check if the file exists */
605 if (isdir_f)
606 {
607 filemess(curbuf, sfname, (char_u *)_("is a directory"), 0);
608 curbuf->b_p_ro = TRUE; /* must use "w!" now */
609 }
610 else
611#endif
612 if (newfile)
613 {
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200614 if (perm < 0
615#ifdef ENOENT
616 && errno == ENOENT
617#endif
618 )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000619 {
620 /*
621 * Set the 'new-file' flag, so that when the file has
622 * been created by someone else, a ":w" will complain.
623 */
624 curbuf->b_flags |= BF_NEW;
625
626 /* Create a swap file now, so that other Vims are warned
627 * that we are editing this file. Don't do this for a
628 * "nofile" or "nowrite" buffer type. */
629#ifdef FEAT_QUICKFIX
630 if (!bt_dontwrite(curbuf))
631#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000632 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000633 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000634#ifdef FEAT_AUTOCMD
635 /* SwapExists autocommand may mess things up */
636 if (curbuf != old_curbuf
637 || (using_b_ffname
638 && (old_b_ffname != curbuf->b_ffname))
639 || (using_b_fname
640 && (old_b_fname != curbuf->b_fname)))
641 {
642 EMSG(_(e_auchangedbuf));
643 return FAIL;
644 }
645#endif
646 }
Bram Moolenaar5b962cf2005-12-12 21:58:40 +0000647 if (dir_of_file_exists(fname))
648 filemess(curbuf, sfname, (char_u *)_("[New File]"), 0);
649 else
650 filemess(curbuf, sfname,
651 (char_u *)_("[New DIRECTORY]"), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000652#ifdef FEAT_VIMINFO
653 /* Even though this is a new file, it might have been
654 * edited before and deleted. Get the old marks. */
655 check_marks_read();
656#endif
657#ifdef FEAT_MBYTE
658 if (eap != NULL && eap->force_enc != 0)
659 {
660 /* set forced 'fileencoding' */
661 fenc = enc_canonize(eap->cmd + eap->force_enc);
662 if (fenc != NULL)
663 set_string_option_direct((char_u *)"fenc", -1,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +0000664 fenc, OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000665 vim_free(fenc);
666 }
667#endif
668#ifdef FEAT_AUTOCMD
669 apply_autocmds_exarg(EVENT_BUFNEWFILE, sfname, sfname,
670 FALSE, curbuf, eap);
671#endif
672 /* remember the current fileformat */
673 save_file_ff(curbuf);
674
675#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
676 if (aborting()) /* autocmds may abort script processing */
677 return FAIL;
678#endif
679 return OK; /* a new file is not an error */
680 }
681 else
682 {
Bram Moolenaar202795b2005-10-11 20:29:39 +0000683 filemess(curbuf, sfname, (char_u *)(
684# ifdef EFBIG
685 (errno == EFBIG) ? _("[File too big]") :
686# endif
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200687# ifdef EOVERFLOW
688 (errno == EOVERFLOW) ? _("[File too big]") :
689# endif
Bram Moolenaar202795b2005-10-11 20:29:39 +0000690 _("[Permission Denied]")), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000691 curbuf->b_p_ro = TRUE; /* must use "w!" now */
692 }
693 }
694
695 return FAIL;
696 }
697
698 /*
699 * Only set the 'ro' flag for readonly files the first time they are
700 * loaded. Help files always get readonly mode
701 */
702 if ((check_readonly && file_readonly) || curbuf->b_help)
703 curbuf->b_p_ro = TRUE;
704
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000705 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000706 {
Bram Moolenaar690ffc02008-01-04 15:31:21 +0000707 /* Don't change 'eol' if reading from buffer as it will already be
708 * correctly set when reading stdin. */
709 if (!read_buffer)
710 {
711 curbuf->b_p_eol = TRUE;
712 curbuf->b_start_eol = TRUE;
713 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000714#ifdef FEAT_MBYTE
715 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000716 curbuf->b_start_bomb = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000717#endif
718 }
719
720 /* Create a swap file now, so that other Vims are warned that we are
721 * editing this file.
722 * Don't do this for a "nofile" or "nowrite" buffer type. */
723#ifdef FEAT_QUICKFIX
724 if (!bt_dontwrite(curbuf))
725#endif
726 {
727 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000728#ifdef FEAT_AUTOCMD
729 if (!read_stdin && (curbuf != old_curbuf
730 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
731 || (using_b_fname && (old_b_fname != curbuf->b_fname))))
732 {
733 EMSG(_(e_auchangedbuf));
734 if (!read_buffer)
735 close(fd);
736 return FAIL;
737 }
738#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000739#ifdef UNIX
740 /* Set swap file protection bits after creating it. */
Bram Moolenaarf061e0b2009-06-24 15:32:01 +0000741 if (swap_mode > 0 && curbuf->b_ml.ml_mfp != NULL
742 && curbuf->b_ml.ml_mfp->mf_fname != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000743 (void)mch_setperm(curbuf->b_ml.ml_mfp->mf_fname, (long)swap_mode);
744#endif
745 }
746
Bram Moolenaarb815dac2005-12-07 20:59:24 +0000747#if defined(HAS_SWAP_EXISTS_ACTION)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000748 /* If "Quit" selected at ATTENTION dialog, don't load the file */
749 if (swap_exists_action == SEA_QUIT)
750 {
751 if (!read_buffer && !read_stdin)
752 close(fd);
753 return FAIL;
754 }
755#endif
756
757 ++no_wait_return; /* don't wait for return yet */
758
759 /*
760 * Set '[ mark to the line above where the lines go (line 1 if zero).
761 */
762 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
763 curbuf->b_op_start.col = 0;
764
765#ifdef FEAT_AUTOCMD
766 if (!read_buffer)
767 {
768 int m = msg_scroll;
769 int n = msg_scrolled;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000770
771 /*
772 * The file must be closed again, the autocommands may want to change
773 * the file before reading it.
774 */
775 if (!read_stdin)
776 close(fd); /* ignore errors */
777
778 /*
779 * The output from the autocommands should not overwrite anything and
780 * should not be overwritten: Set msg_scroll, restore its value if no
781 * output was done.
782 */
783 msg_scroll = TRUE;
784 if (filtering)
785 apply_autocmds_exarg(EVENT_FILTERREADPRE, NULL, sfname,
786 FALSE, curbuf, eap);
787 else if (read_stdin)
788 apply_autocmds_exarg(EVENT_STDINREADPRE, NULL, sfname,
789 FALSE, curbuf, eap);
790 else if (newfile)
791 apply_autocmds_exarg(EVENT_BUFREADPRE, NULL, sfname,
792 FALSE, curbuf, eap);
793 else
794 apply_autocmds_exarg(EVENT_FILEREADPRE, sfname, sfname,
795 FALSE, NULL, eap);
796 if (msg_scrolled == n)
797 msg_scroll = m;
798
799#ifdef FEAT_EVAL
800 if (aborting()) /* autocmds may abort script processing */
801 {
802 --no_wait_return;
803 msg_scroll = msg_save;
804 curbuf->b_p_ro = TRUE; /* must use "w!" now */
805 return FAIL;
806 }
807#endif
808 /*
809 * Don't allow the autocommands to change the current buffer.
810 * Try to re-open the file.
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000811 *
812 * Don't allow the autocommands to change the buffer name either
813 * (cd for example) if it invalidates fname or sfname.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000814 */
815 if (!read_stdin && (curbuf != old_curbuf
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000816 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
817 || (using_b_fname && (old_b_fname != curbuf->b_fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000818 || (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) < 0))
819 {
820 --no_wait_return;
821 msg_scroll = msg_save;
822 if (fd < 0)
823 EMSG(_("E200: *ReadPre autocommands made the file unreadable"));
824 else
825 EMSG(_("E201: *ReadPre autocommands must not change current buffer"));
826 curbuf->b_p_ro = TRUE; /* must use "w!" now */
827 return FAIL;
828 }
829 }
830#endif /* FEAT_AUTOCMD */
831
832 /* Autocommands may add lines to the file, need to check if it is empty */
833 wasempty = (curbuf->b_ml.ml_flags & ML_EMPTY);
834
835 if (!recoverymode && !filtering && !(flags & READ_DUMMY))
836 {
837 /*
838 * Show the user that we are busy reading the input. Sometimes this
839 * may take a while. When reading from stdin another program may
840 * still be running, don't move the cursor to the last line, unless
841 * always using the GUI.
842 */
843 if (read_stdin)
844 {
845#ifndef ALWAYS_USE_GUI
846 mch_msg(_("Vim: Reading from stdin...\n"));
847#endif
848#ifdef FEAT_GUI
849 /* Also write a message in the GUI window, if there is one. */
850 if (gui.in_use && !gui.dying && !gui.starting)
851 {
852 p = (char_u *)_("Reading from stdin...");
853 gui_write(p, (int)STRLEN(p));
854 }
855#endif
856 }
857 else if (!read_buffer)
858 filemess(curbuf, sfname, (char_u *)"", 0);
859 }
860
861 msg_scroll = FALSE; /* overwrite the file message */
862
863 /*
864 * Set linecnt now, before the "retry" caused by a wrong guess for
865 * fileformat, and after the autocommands, which may change them.
866 */
867 linecnt = curbuf->b_ml.ml_line_count;
868
869#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000870 /* "++bad=" argument. */
871 if (eap != NULL && eap->bad_char != 0)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000872 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000873 bad_char_behavior = eap->bad_char;
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000874 if (set_options)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000875 curbuf->b_bad_char = eap->bad_char;
876 }
877 else
878 curbuf->b_bad_char = 0;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000879
Bram Moolenaar071d4272004-06-13 20:20:40 +0000880 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000881 * Decide which 'encoding' to use or use first.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000882 */
883 if (eap != NULL && eap->force_enc != 0)
884 {
885 fenc = enc_canonize(eap->cmd + eap->force_enc);
886 fenc_alloced = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000887 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000888 }
889 else if (curbuf->b_p_bin)
890 {
891 fenc = (char_u *)""; /* binary: don't convert */
892 fenc_alloced = FALSE;
893 }
894 else if (curbuf->b_help)
895 {
896 char_u firstline[80];
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000897 int fc;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000898
899 /* Help files are either utf-8 or latin1. Try utf-8 first, if this
900 * fails it must be latin1.
901 * Always do this when 'encoding' is "utf-8". Otherwise only do
902 * this when needed to avoid [converted] remarks all the time.
903 * It is needed when the first line contains non-ASCII characters.
904 * That is only in *.??x files. */
905 fenc = (char_u *)"latin1";
906 c = enc_utf8;
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000907 if (!c && !read_stdin)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000908 {
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000909 fc = fname[STRLEN(fname) - 1];
910 if (TOLOWER_ASC(fc) == 'x')
911 {
912 /* Read the first line (and a bit more). Immediately rewind to
913 * the start of the file. If the read() fails "len" is -1. */
914 len = vim_read(fd, firstline, 80);
915 lseek(fd, (off_t)0L, SEEK_SET);
916 for (p = firstline; p < firstline + len; ++p)
917 if (*p >= 0x80)
918 {
919 c = TRUE;
920 break;
921 }
922 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000923 }
924
925 if (c)
926 {
927 fenc_next = fenc;
928 fenc = (char_u *)"utf-8";
929
930 /* When the file is utf-8 but a character doesn't fit in
931 * 'encoding' don't retry. In help text editing utf-8 bytes
932 * doesn't make sense. */
Bram Moolenaarf193fff2006-04-27 00:02:13 +0000933 if (!enc_utf8)
934 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000935 }
936 fenc_alloced = FALSE;
937 }
938 else if (*p_fencs == NUL)
939 {
940 fenc = curbuf->b_p_fenc; /* use format from buffer */
941 fenc_alloced = FALSE;
942 }
943 else
944 {
945 fenc_next = p_fencs; /* try items in 'fileencodings' */
946 fenc = next_fenc(&fenc_next);
947 fenc_alloced = TRUE;
948 }
949#endif
950
951 /*
952 * Jump back here to retry reading the file in different ways.
953 * Reasons to retry:
954 * - encoding conversion failed: try another one from "fenc_next"
955 * - BOM detected and fenc was set, need to setup conversion
956 * - "fileformat" check failed: try another
957 *
958 * Variables set for special retry actions:
959 * "file_rewind" Rewind the file to start reading it again.
960 * "advance_fenc" Advance "fenc" using "fenc_next".
961 * "skip_read" Re-use already read bytes (BOM detected).
962 * "did_iconv" iconv() conversion failed, try 'charconvert'.
963 * "keep_fileformat" Don't reset "fileformat".
964 *
965 * Other status indicators:
966 * "tmpname" When != NULL did conversion with 'charconvert'.
967 * Output file has to be deleted afterwards.
968 * "iconv_fd" When != -1 did conversion with iconv().
969 */
970retry:
971
972 if (file_rewind)
973 {
974 if (read_buffer)
975 {
976 read_buf_lnum = 1;
977 read_buf_col = 0;
978 }
979 else if (read_stdin || lseek(fd, (off_t)0L, SEEK_SET) != 0)
980 {
981 /* Can't rewind the file, give up. */
982 error = TRUE;
983 goto failed;
984 }
985 /* Delete the previously read lines. */
986 while (lnum > from)
987 ml_delete(lnum--, FALSE);
988 file_rewind = FALSE;
989#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000990 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000991 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000992 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000993 curbuf->b_start_bomb = FALSE;
994 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000995 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000996#endif
997 }
998
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200999#ifdef FEAT_CRYPT
1000 if (cryptkey != NULL)
1001 /* Need to reset the state, but keep the key, don't want to ask for it
1002 * again. */
1003 crypt_pop_state();
1004#endif
1005
Bram Moolenaar071d4272004-06-13 20:20:40 +00001006 /*
1007 * When retrying with another "fenc" and the first time "fileformat"
1008 * will be reset.
1009 */
1010 if (keep_fileformat)
1011 keep_fileformat = FALSE;
1012 else
1013 {
1014 if (eap != NULL && eap->force_ff != 0)
Bram Moolenaar1c860362008-11-12 15:05:21 +00001015 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001016 fileformat = get_fileformat_force(curbuf, eap);
Bram Moolenaar1c860362008-11-12 15:05:21 +00001017 try_unix = try_dos = try_mac = FALSE;
1018 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001019 else if (curbuf->b_p_bin)
1020 fileformat = EOL_UNIX; /* binary: use Unix format */
1021 else if (*p_ffs == NUL)
1022 fileformat = get_fileformat(curbuf);/* use format from buffer */
1023 else
1024 fileformat = EOL_UNKNOWN; /* detect from file */
1025 }
1026
1027#ifdef FEAT_MBYTE
1028# ifdef USE_ICONV
1029 if (iconv_fd != (iconv_t)-1)
1030 {
1031 /* aborted conversion with iconv(), close the descriptor */
1032 iconv_close(iconv_fd);
1033 iconv_fd = (iconv_t)-1;
1034 }
1035# endif
1036
1037 if (advance_fenc)
1038 {
1039 /*
1040 * Try the next entry in 'fileencodings'.
1041 */
1042 advance_fenc = FALSE;
1043
1044 if (eap != NULL && eap->force_enc != 0)
1045 {
1046 /* Conversion given with "++cc=" wasn't possible, read
1047 * without conversion. */
1048 notconverted = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001049 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001050 if (fenc_alloced)
1051 vim_free(fenc);
1052 fenc = (char_u *)"";
1053 fenc_alloced = FALSE;
1054 }
1055 else
1056 {
1057 if (fenc_alloced)
1058 vim_free(fenc);
1059 if (fenc_next != NULL)
1060 {
1061 fenc = next_fenc(&fenc_next);
1062 fenc_alloced = (fenc_next != NULL);
1063 }
1064 else
1065 {
1066 fenc = (char_u *)"";
1067 fenc_alloced = FALSE;
1068 }
1069 }
1070 if (tmpname != NULL)
1071 {
1072 mch_remove(tmpname); /* delete converted file */
1073 vim_free(tmpname);
1074 tmpname = NULL;
1075 }
1076 }
1077
1078 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001079 * Conversion may be required when the encoding of the file is different
1080 * from 'encoding' or 'encoding' is UTF-16, UCS-2 or UCS-4.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001081 */
1082 fio_flags = 0;
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001083 converted = need_conversion(fenc);
1084 if (converted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001085 {
1086
1087 /* "ucs-bom" means we need to check the first bytes of the file
1088 * for a BOM. */
1089 if (STRCMP(fenc, ENC_UCSBOM) == 0)
1090 fio_flags = FIO_UCSBOM;
1091
1092 /*
1093 * Check if UCS-2/4 or Latin1 to UTF-8 conversion needs to be
1094 * done. This is handled below after read(). Prepare the
1095 * fio_flags to avoid having to parse the string each time.
1096 * Also check for Unicode to Latin1 conversion, because iconv()
1097 * appears not to handle this correctly. This works just like
1098 * conversion to UTF-8 except how the resulting character is put in
1099 * the buffer.
1100 */
1101 else if (enc_utf8 || STRCMP(p_enc, "latin1") == 0)
1102 fio_flags = get_fio_flags(fenc);
1103
1104# ifdef WIN3264
1105 /*
1106 * Conversion from an MS-Windows codepage to UTF-8 or another codepage
1107 * is handled with MultiByteToWideChar().
1108 */
1109 if (fio_flags == 0)
1110 fio_flags = get_win_fio_flags(fenc);
1111# endif
1112
1113# ifdef MACOS_X
1114 /* Conversion from Apple MacRoman to latin1 or UTF-8 */
1115 if (fio_flags == 0)
1116 fio_flags = get_mac_fio_flags(fenc);
1117# endif
1118
1119# ifdef USE_ICONV
1120 /*
1121 * Try using iconv() if we can't convert internally.
1122 */
1123 if (fio_flags == 0
1124# ifdef FEAT_EVAL
1125 && !did_iconv
1126# endif
1127 )
1128 iconv_fd = (iconv_t)my_iconv_open(
1129 enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc);
1130# endif
1131
1132# ifdef FEAT_EVAL
1133 /*
1134 * Use the 'charconvert' expression when conversion is required
1135 * and we can't do it internally or with iconv().
1136 */
1137 if (fio_flags == 0 && !read_stdin && !read_buffer && *p_ccv != NUL
1138# ifdef USE_ICONV
1139 && iconv_fd == (iconv_t)-1
1140# endif
1141 )
1142 {
1143# ifdef USE_ICONV
1144 did_iconv = FALSE;
1145# endif
1146 /* Skip conversion when it's already done (retry for wrong
1147 * "fileformat"). */
1148 if (tmpname == NULL)
1149 {
1150 tmpname = readfile_charconvert(fname, fenc, &fd);
1151 if (tmpname == NULL)
1152 {
1153 /* Conversion failed. Try another one. */
1154 advance_fenc = TRUE;
1155 if (fd < 0)
1156 {
1157 /* Re-opening the original file failed! */
1158 EMSG(_("E202: Conversion made file unreadable!"));
1159 error = TRUE;
1160 goto failed;
1161 }
1162 goto retry;
1163 }
1164 }
1165 }
1166 else
1167# endif
1168 {
1169 if (fio_flags == 0
1170# ifdef USE_ICONV
1171 && iconv_fd == (iconv_t)-1
1172# endif
1173 )
1174 {
1175 /* Conversion wanted but we can't.
1176 * Try the next conversion in 'fileencodings' */
1177 advance_fenc = TRUE;
1178 goto retry;
1179 }
1180 }
1181 }
1182
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001183 /* Set "can_retry" when it's possible to rewind the file and try with
Bram Moolenaar071d4272004-06-13 20:20:40 +00001184 * another "fenc" value. It's FALSE when no other "fenc" to try, reading
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001185 * stdin or fixed at a specific encoding. */
1186 can_retry = (*fenc != NUL && !read_stdin && !keep_dest_enc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001187#endif
1188
1189 if (!skip_read)
1190 {
1191 linerest = 0;
1192 filesize = 0;
1193 skip_count = lines_to_skip;
1194 read_count = lines_to_read;
1195#ifdef FEAT_MBYTE
1196 conv_restlen = 0;
1197#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001198#ifdef FEAT_PERSISTENT_UNDO
Bram Moolenaar59f931e2010-07-24 20:27:03 +02001199 read_undo_file = (newfile && (flags & READ_KEEP_UNDO) == 0
1200 && curbuf->b_ffname != NULL
1201 && curbuf->b_p_udf
1202 && !filtering
1203 && !read_stdin
1204 && !read_buffer);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001205 if (read_undo_file)
1206 sha256_start(&sha_ctx);
1207#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001208 }
1209
1210 while (!error && !got_int)
1211 {
1212 /*
1213 * We allocate as much space for the file as we can get, plus
1214 * space for the old line plus room for one terminating NUL.
1215 * The amount is limited by the fact that read() only can read
1216 * upto max_unsigned characters (and other things).
1217 */
1218#if SIZEOF_INT <= 2
1219 if (linerest >= 0x7ff0)
1220 {
1221 ++split;
1222 *ptr = NL; /* split line by inserting a NL */
1223 size = 1;
1224 }
1225 else
1226#endif
1227 {
1228 if (!skip_read)
1229 {
1230#if SIZEOF_INT > 2
Bram Moolenaar311d9822007-02-27 15:48:28 +00001231# if defined(SSIZE_MAX) && (SSIZE_MAX < 0x10000L)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001232 size = SSIZE_MAX; /* use max I/O size, 52K */
1233# else
1234 size = 0x10000L; /* use buffer >= 64K */
1235# endif
1236#else
1237 size = 0x7ff0L - linerest; /* limit buffer to 32K */
1238#endif
1239
Bram Moolenaarc1e37902006-04-18 21:55:01 +00001240 for ( ; size >= 10; size = (long)((long_u)size >> 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001241 {
1242 if ((new_buffer = lalloc((long_u)(size + linerest + 1),
1243 FALSE)) != NULL)
1244 break;
1245 }
1246 if (new_buffer == NULL)
1247 {
1248 do_outofmem_msg((long_u)(size * 2 + linerest + 1));
1249 error = TRUE;
1250 break;
1251 }
1252 if (linerest) /* copy characters from the previous buffer */
1253 mch_memmove(new_buffer, ptr - linerest, (size_t)linerest);
1254 vim_free(buffer);
1255 buffer = new_buffer;
1256 ptr = buffer + linerest;
1257 line_start = buffer;
1258
1259#ifdef FEAT_MBYTE
1260 /* May need room to translate into.
1261 * For iconv() we don't really know the required space, use a
1262 * factor ICONV_MULT.
1263 * latin1 to utf-8: 1 byte becomes up to 2 bytes
1264 * utf-16 to utf-8: 2 bytes become up to 3 bytes, 4 bytes
1265 * become up to 4 bytes, size must be multiple of 2
1266 * ucs-2 to utf-8: 2 bytes become up to 3 bytes, size must be
1267 * multiple of 2
1268 * ucs-4 to utf-8: 4 bytes become up to 6 bytes, size must be
1269 * multiple of 4 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001270 real_size = (int)size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001271# ifdef USE_ICONV
1272 if (iconv_fd != (iconv_t)-1)
1273 size = size / ICONV_MULT;
1274 else
1275# endif
1276 if (fio_flags & FIO_LATIN1)
1277 size = size / 2;
1278 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1279 size = (size * 2 / 3) & ~1;
1280 else if (fio_flags & FIO_UCS4)
1281 size = (size * 2 / 3) & ~3;
1282 else if (fio_flags == FIO_UCSBOM)
1283 size = size / ICONV_MULT; /* worst case */
1284# ifdef WIN3264
1285 else if (fio_flags & FIO_CODEPAGE)
1286 size = size / ICONV_MULT; /* also worst case */
1287# endif
1288# ifdef MACOS_X
1289 else if (fio_flags & FIO_MACROMAN)
1290 size = size / ICONV_MULT; /* also worst case */
1291# endif
1292#endif
1293
1294#ifdef FEAT_MBYTE
1295 if (conv_restlen > 0)
1296 {
1297 /* Insert unconverted bytes from previous line. */
1298 mch_memmove(ptr, conv_rest, conv_restlen);
1299 ptr += conv_restlen;
1300 size -= conv_restlen;
1301 }
1302#endif
1303
1304 if (read_buffer)
1305 {
1306 /*
1307 * Read bytes from curbuf. Used for converting text read
1308 * from stdin.
1309 */
1310 if (read_buf_lnum > from)
1311 size = 0;
1312 else
1313 {
1314 int n, ni;
1315 long tlen;
1316
1317 tlen = 0;
1318 for (;;)
1319 {
1320 p = ml_get(read_buf_lnum) + read_buf_col;
1321 n = (int)STRLEN(p);
1322 if ((int)tlen + n + 1 > size)
1323 {
1324 /* Filled up to "size", append partial line.
1325 * Change NL to NUL to reverse the effect done
1326 * below. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001327 n = (int)(size - tlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001328 for (ni = 0; ni < n; ++ni)
1329 {
1330 if (p[ni] == NL)
1331 ptr[tlen++] = NUL;
1332 else
1333 ptr[tlen++] = p[ni];
1334 }
1335 read_buf_col += n;
1336 break;
1337 }
1338 else
1339 {
1340 /* Append whole line and new-line. Change NL
1341 * to NUL to reverse the effect done below. */
1342 for (ni = 0; ni < n; ++ni)
1343 {
1344 if (p[ni] == NL)
1345 ptr[tlen++] = NUL;
1346 else
1347 ptr[tlen++] = p[ni];
1348 }
1349 ptr[tlen++] = NL;
1350 read_buf_col = 0;
1351 if (++read_buf_lnum > from)
1352 {
1353 /* When the last line didn't have an
1354 * end-of-line don't add it now either. */
1355 if (!curbuf->b_p_eol)
1356 --tlen;
1357 size = tlen;
1358 break;
1359 }
1360 }
1361 }
1362 }
1363 }
1364 else
1365 {
1366 /*
1367 * Read bytes from the file.
1368 */
1369 size = vim_read(fd, ptr, size);
1370 }
1371
1372 if (size <= 0)
1373 {
1374 if (size < 0) /* read error */
1375 error = TRUE;
1376#ifdef FEAT_MBYTE
1377 else if (conv_restlen > 0)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001378 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001379 /*
1380 * Reached end-of-file but some trailing bytes could
1381 * not be converted. Truncated file?
1382 */
1383
1384 /* When we did a conversion report an error. */
1385 if (fio_flags != 0
1386# ifdef USE_ICONV
1387 || iconv_fd != (iconv_t)-1
1388# endif
1389 )
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001390 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001391 if (conv_error == 0)
1392 conv_error = curbuf->b_ml.ml_line_count
1393 - linecnt + 1;
1394 }
1395 /* Remember the first linenr with an illegal byte */
1396 else if (illegal_byte == 0)
1397 illegal_byte = curbuf->b_ml.ml_line_count
1398 - linecnt + 1;
1399 if (bad_char_behavior == BAD_DROP)
1400 {
1401 *(ptr - conv_restlen) = NUL;
1402 conv_restlen = 0;
1403 }
1404 else
1405 {
1406 /* Replace the trailing bytes with the replacement
1407 * character if we were converting; if we weren't,
1408 * leave the UTF8 checking code to do it, as it
1409 * works slightly differently. */
1410 if (bad_char_behavior != BAD_KEEP && (fio_flags != 0
1411# ifdef USE_ICONV
1412 || iconv_fd != (iconv_t)-1
1413# endif
1414 ))
1415 {
1416 while (conv_restlen > 0)
1417 {
1418 *(--ptr) = bad_char_behavior;
1419 --conv_restlen;
1420 }
1421 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001422 fio_flags = 0; /* don't convert this */
Bram Moolenaarb21e5842006-04-16 18:30:08 +00001423# ifdef USE_ICONV
1424 if (iconv_fd != (iconv_t)-1)
1425 {
1426 iconv_close(iconv_fd);
1427 iconv_fd = (iconv_t)-1;
1428 }
1429# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001430 }
1431 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001432#endif
1433 }
1434
1435#ifdef FEAT_CRYPT
1436 /*
1437 * At start of file: Check for magic number of encryption.
1438 */
1439 if (filesize == 0)
1440 cryptkey = check_for_cryptkey(cryptkey, ptr, &size,
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001441 &filesize, newfile, sfname,
1442 &did_ask_for_key);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001443 /*
1444 * Decrypt the read bytes.
1445 */
1446 if (cryptkey != NULL && size > 0)
Bram Moolenaar04c9baf2010-06-01 23:37:39 +02001447 crypt_decode(ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001448#endif
1449 }
1450 skip_read = FALSE;
1451
1452#ifdef FEAT_MBYTE
1453 /*
1454 * At start of file (or after crypt magic number): Check for BOM.
1455 * Also check for a BOM for other Unicode encodings, but not after
1456 * converting with 'charconvert' or when a BOM has already been
1457 * found.
1458 */
1459 if ((filesize == 0
1460# ifdef FEAT_CRYPT
Bram Moolenaar40e6a712010-05-16 22:32:54 +02001461 || (filesize == (CRYPT_MAGIC_LEN
Bram Moolenaar80794b12010-06-13 05:20:42 +02001462 + crypt_salt_len[use_crypt_method]
Bram Moolenaar40e6a712010-05-16 22:32:54 +02001463 + crypt_seed_len[use_crypt_method])
1464 && cryptkey != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001465# endif
1466 )
1467 && (fio_flags == FIO_UCSBOM
1468 || (!curbuf->b_p_bomb
1469 && tmpname == NULL
1470 && (*fenc == 'u' || (*fenc == NUL && enc_utf8)))))
1471 {
1472 char_u *ccname;
1473 int blen;
1474
1475 /* no BOM detection in a short file or in binary mode */
1476 if (size < 2 || curbuf->b_p_bin)
1477 ccname = NULL;
1478 else
1479 ccname = check_for_bom(ptr, size, &blen,
1480 fio_flags == FIO_UCSBOM ? FIO_ALL : get_fio_flags(fenc));
1481 if (ccname != NULL)
1482 {
1483 /* Remove BOM from the text */
1484 filesize += blen;
1485 size -= blen;
1486 mch_memmove(ptr, ptr + blen, (size_t)size);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00001487 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001488 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001489 curbuf->b_p_bomb = TRUE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001490 curbuf->b_start_bomb = TRUE;
1491 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001492 }
1493
1494 if (fio_flags == FIO_UCSBOM)
1495 {
1496 if (ccname == NULL)
1497 {
1498 /* No BOM detected: retry with next encoding. */
1499 advance_fenc = TRUE;
1500 }
1501 else
1502 {
1503 /* BOM detected: set "fenc" and jump back */
1504 if (fenc_alloced)
1505 vim_free(fenc);
1506 fenc = ccname;
1507 fenc_alloced = FALSE;
1508 }
1509 /* retry reading without getting new bytes or rewinding */
1510 skip_read = TRUE;
1511 goto retry;
1512 }
1513 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001514
1515 /* Include not converted bytes. */
1516 ptr -= conv_restlen;
1517 size += conv_restlen;
1518 conv_restlen = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001519#endif
1520 /*
1521 * Break here for a read error or end-of-file.
1522 */
1523 if (size <= 0)
1524 break;
1525
1526#ifdef FEAT_MBYTE
1527
Bram Moolenaar071d4272004-06-13 20:20:40 +00001528# ifdef USE_ICONV
1529 if (iconv_fd != (iconv_t)-1)
1530 {
1531 /*
1532 * Attempt conversion of the read bytes to 'encoding' using
1533 * iconv().
1534 */
1535 const char *fromp;
1536 char *top;
1537 size_t from_size;
1538 size_t to_size;
1539
1540 fromp = (char *)ptr;
1541 from_size = size;
1542 ptr += size;
1543 top = (char *)ptr;
1544 to_size = real_size - size;
1545
1546 /*
1547 * If there is conversion error or not enough room try using
Bram Moolenaar19a09a12005-03-04 23:39:37 +00001548 * another conversion. Except for when there is no
1549 * alternative (help files).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001550 */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001551 while ((iconv(iconv_fd, (void *)&fromp, &from_size,
1552 &top, &to_size)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001553 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
1554 || from_size > CONV_RESTLEN)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001555 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001556 if (can_retry)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001557 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001558 if (conv_error == 0)
1559 conv_error = readfile_linenr(linecnt,
1560 ptr, (char_u *)top);
Bram Moolenaar42eeac32005-06-29 22:40:58 +00001561
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001562 /* Deal with a bad byte and continue with the next. */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001563 ++fromp;
1564 --from_size;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001565 if (bad_char_behavior == BAD_KEEP)
1566 {
1567 *top++ = *(fromp - 1);
1568 --to_size;
1569 }
1570 else if (bad_char_behavior != BAD_DROP)
1571 {
1572 *top++ = bad_char_behavior;
1573 --to_size;
1574 }
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001575 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001576
1577 if (from_size > 0)
1578 {
1579 /* Some remaining characters, keep them for the next
1580 * round. */
1581 mch_memmove(conv_rest, (char_u *)fromp, from_size);
1582 conv_restlen = (int)from_size;
1583 }
1584
1585 /* move the linerest to before the converted characters */
1586 line_start = ptr - linerest;
1587 mch_memmove(line_start, buffer, (size_t)linerest);
1588 size = (long)((char_u *)top - ptr);
1589 }
1590# endif
1591
1592# ifdef WIN3264
1593 if (fio_flags & FIO_CODEPAGE)
1594 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001595 char_u *src, *dst;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001596 WCHAR ucs2buf[3];
1597 int ucs2len;
1598 int codepage = FIO_GET_CP(fio_flags);
1599 int bytelen;
1600 int found_bad;
1601 char replstr[2];
1602
Bram Moolenaar071d4272004-06-13 20:20:40 +00001603 /*
1604 * Conversion from an MS-Windows codepage or UTF-8 to UTF-8 or
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001605 * a codepage, using standard MS-Windows functions. This
1606 * requires two steps:
1607 * 1. convert from 'fileencoding' to ucs-2
1608 * 2. convert from ucs-2 to 'encoding'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001609 *
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001610 * Because there may be illegal bytes AND an incomplete byte
1611 * sequence at the end, we may have to do the conversion one
1612 * character at a time to get it right.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001613 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001614
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001615 /* Replacement string for WideCharToMultiByte(). */
1616 if (bad_char_behavior > 0)
1617 replstr[0] = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001618 else
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001619 replstr[0] = '?';
1620 replstr[1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001621
1622 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001623 * Move the bytes to the end of the buffer, so that we have
1624 * room to put the result at the start.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001625 */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001626 src = ptr + real_size - size;
1627 mch_memmove(src, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001628
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001629 /*
1630 * Do the conversion.
1631 */
1632 dst = ptr;
1633 size = size;
1634 while (size > 0)
1635 {
1636 found_bad = FALSE;
1637
1638# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
1639 if (codepage == CP_UTF8)
1640 {
1641 /* Handle CP_UTF8 input ourselves to be able to handle
1642 * trailing bytes properly.
1643 * Get one UTF-8 character from src. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001644 bytelen = (int)utf_ptr2len_len(src, size);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001645 if (bytelen > size)
1646 {
1647 /* Only got some bytes of a character. Normally
1648 * it's put in "conv_rest", but if it's too long
1649 * deal with it as if they were illegal bytes. */
1650 if (bytelen <= CONV_RESTLEN)
1651 break;
1652
1653 /* weird overlong byte sequence */
1654 bytelen = size;
1655 found_bad = TRUE;
1656 }
1657 else
1658 {
Bram Moolenaarc01140a2006-03-24 22:21:52 +00001659 int u8c = utf_ptr2char(src);
1660
Bram Moolenaar86e01082005-12-29 22:45:34 +00001661 if (u8c > 0xffff || (*src >= 0x80 && bytelen == 1))
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001662 found_bad = TRUE;
1663 ucs2buf[0] = u8c;
1664 ucs2len = 1;
1665 }
1666 }
1667 else
1668# endif
1669 {
1670 /* We don't know how long the byte sequence is, try
1671 * from one to three bytes. */
1672 for (bytelen = 1; bytelen <= size && bytelen <= 3;
1673 ++bytelen)
1674 {
1675 ucs2len = MultiByteToWideChar(codepage,
1676 MB_ERR_INVALID_CHARS,
1677 (LPCSTR)src, bytelen,
1678 ucs2buf, 3);
1679 if (ucs2len > 0)
1680 break;
1681 }
1682 if (ucs2len == 0)
1683 {
1684 /* If we have only one byte then it's probably an
1685 * incomplete byte sequence. Otherwise discard
1686 * one byte as a bad character. */
1687 if (size == 1)
1688 break;
1689 found_bad = TRUE;
1690 bytelen = 1;
1691 }
1692 }
1693
1694 if (!found_bad)
1695 {
1696 int i;
1697
1698 /* Convert "ucs2buf[ucs2len]" to 'enc' in "dst". */
1699 if (enc_utf8)
1700 {
1701 /* From UCS-2 to UTF-8. Cannot fail. */
1702 for (i = 0; i < ucs2len; ++i)
1703 dst += utf_char2bytes(ucs2buf[i], dst);
1704 }
1705 else
1706 {
1707 BOOL bad = FALSE;
1708 int dstlen;
1709
1710 /* From UCS-2 to "enc_codepage". If the
1711 * conversion uses the default character "?",
1712 * the data doesn't fit in this encoding. */
1713 dstlen = WideCharToMultiByte(enc_codepage, 0,
1714 (LPCWSTR)ucs2buf, ucs2len,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001715 (LPSTR)dst, (int)(src - dst),
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001716 replstr, &bad);
1717 if (bad)
1718 found_bad = TRUE;
1719 else
1720 dst += dstlen;
1721 }
1722 }
1723
1724 if (found_bad)
1725 {
1726 /* Deal with bytes we can't convert. */
1727 if (can_retry)
1728 goto rewind_retry;
1729 if (conv_error == 0)
1730 conv_error = readfile_linenr(linecnt, ptr, dst);
1731 if (bad_char_behavior != BAD_DROP)
1732 {
1733 if (bad_char_behavior == BAD_KEEP)
1734 {
1735 mch_memmove(dst, src, bytelen);
1736 dst += bytelen;
1737 }
1738 else
1739 *dst++ = bad_char_behavior;
1740 }
1741 }
1742
1743 src += bytelen;
1744 size -= bytelen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001745 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001746
1747 if (size > 0)
1748 {
1749 /* An incomplete byte sequence remaining. */
1750 mch_memmove(conv_rest, src, size);
1751 conv_restlen = size;
1752 }
1753
1754 /* The new size is equal to how much "dst" was advanced. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001755 size = (long)(dst - ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001756 }
1757 else
1758# endif
Bram Moolenaar56718732006-03-15 22:53:57 +00001759# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001760 if (fio_flags & FIO_MACROMAN)
1761 {
1762 /*
1763 * Conversion from Apple MacRoman char encoding to UTF-8 or
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001764 * latin1. This is in os_mac_conv.c.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001765 */
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001766 if (macroman2enc(ptr, &size, real_size) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001767 goto rewind_retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001768 }
1769 else
1770# endif
1771 if (fio_flags != 0)
1772 {
1773 int u8c;
1774 char_u *dest;
1775 char_u *tail = NULL;
1776
1777 /*
1778 * "enc_utf8" set: Convert Unicode or Latin1 to UTF-8.
1779 * "enc_utf8" not set: Convert Unicode to Latin1.
1780 * Go from end to start through the buffer, because the number
1781 * of bytes may increase.
1782 * "dest" points to after where the UTF-8 bytes go, "p" points
1783 * to after the next character to convert.
1784 */
1785 dest = ptr + real_size;
1786 if (fio_flags == FIO_LATIN1 || fio_flags == FIO_UTF8)
1787 {
1788 p = ptr + size;
1789 if (fio_flags == FIO_UTF8)
1790 {
1791 /* Check for a trailing incomplete UTF-8 sequence */
1792 tail = ptr + size - 1;
1793 while (tail > ptr && (*tail & 0xc0) == 0x80)
1794 --tail;
1795 if (tail + utf_byte2len(*tail) <= ptr + size)
1796 tail = NULL;
1797 else
1798 p = tail;
1799 }
1800 }
1801 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1802 {
1803 /* Check for a trailing byte */
1804 p = ptr + (size & ~1);
1805 if (size & 1)
1806 tail = p;
1807 if ((fio_flags & FIO_UTF16) && p > ptr)
1808 {
1809 /* Check for a trailing leading word */
1810 if (fio_flags & FIO_ENDIAN_L)
1811 {
1812 u8c = (*--p << 8);
1813 u8c += *--p;
1814 }
1815 else
1816 {
1817 u8c = *--p;
1818 u8c += (*--p << 8);
1819 }
1820 if (u8c >= 0xd800 && u8c <= 0xdbff)
1821 tail = p;
1822 else
1823 p += 2;
1824 }
1825 }
1826 else /* FIO_UCS4 */
1827 {
1828 /* Check for trailing 1, 2 or 3 bytes */
1829 p = ptr + (size & ~3);
1830 if (size & 3)
1831 tail = p;
1832 }
1833
1834 /* If there is a trailing incomplete sequence move it to
1835 * conv_rest[]. */
1836 if (tail != NULL)
1837 {
1838 conv_restlen = (int)((ptr + size) - tail);
1839 mch_memmove(conv_rest, (char_u *)tail, conv_restlen);
1840 size -= conv_restlen;
1841 }
1842
1843
1844 while (p > ptr)
1845 {
1846 if (fio_flags & FIO_LATIN1)
1847 u8c = *--p;
1848 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1849 {
1850 if (fio_flags & FIO_ENDIAN_L)
1851 {
1852 u8c = (*--p << 8);
1853 u8c += *--p;
1854 }
1855 else
1856 {
1857 u8c = *--p;
1858 u8c += (*--p << 8);
1859 }
1860 if ((fio_flags & FIO_UTF16)
1861 && u8c >= 0xdc00 && u8c <= 0xdfff)
1862 {
1863 int u16c;
1864
1865 if (p == ptr)
1866 {
1867 /* Missing leading word. */
1868 if (can_retry)
1869 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001870 if (conv_error == 0)
1871 conv_error = readfile_linenr(linecnt,
1872 ptr, p);
1873 if (bad_char_behavior == BAD_DROP)
1874 continue;
1875 if (bad_char_behavior != BAD_KEEP)
1876 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001877 }
1878
1879 /* found second word of double-word, get the first
1880 * word and compute the resulting character */
1881 if (fio_flags & FIO_ENDIAN_L)
1882 {
1883 u16c = (*--p << 8);
1884 u16c += *--p;
1885 }
1886 else
1887 {
1888 u16c = *--p;
1889 u16c += (*--p << 8);
1890 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001891 u8c = 0x10000 + ((u16c & 0x3ff) << 10)
1892 + (u8c & 0x3ff);
1893
Bram Moolenaar071d4272004-06-13 20:20:40 +00001894 /* Check if the word is indeed a leading word. */
1895 if (u16c < 0xd800 || u16c > 0xdbff)
1896 {
1897 if (can_retry)
1898 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001899 if (conv_error == 0)
1900 conv_error = readfile_linenr(linecnt,
1901 ptr, p);
1902 if (bad_char_behavior == BAD_DROP)
1903 continue;
1904 if (bad_char_behavior != BAD_KEEP)
1905 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001906 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001907 }
1908 }
1909 else if (fio_flags & FIO_UCS4)
1910 {
1911 if (fio_flags & FIO_ENDIAN_L)
1912 {
1913 u8c = (*--p << 24);
1914 u8c += (*--p << 16);
1915 u8c += (*--p << 8);
1916 u8c += *--p;
1917 }
1918 else /* big endian */
1919 {
1920 u8c = *--p;
1921 u8c += (*--p << 8);
1922 u8c += (*--p << 16);
1923 u8c += (*--p << 24);
1924 }
1925 }
1926 else /* UTF-8 */
1927 {
1928 if (*--p < 0x80)
1929 u8c = *p;
1930 else
1931 {
1932 len = utf_head_off(ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001933 p -= len;
1934 u8c = utf_ptr2char(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001935 if (len == 0)
1936 {
1937 /* Not a valid UTF-8 character, retry with
1938 * another fenc when possible, otherwise just
1939 * report the error. */
1940 if (can_retry)
1941 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001942 if (conv_error == 0)
1943 conv_error = readfile_linenr(linecnt,
1944 ptr, p);
1945 if (bad_char_behavior == BAD_DROP)
1946 continue;
1947 if (bad_char_behavior != BAD_KEEP)
1948 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001949 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001950 }
1951 }
1952 if (enc_utf8) /* produce UTF-8 */
1953 {
1954 dest -= utf_char2len(u8c);
1955 (void)utf_char2bytes(u8c, dest);
1956 }
1957 else /* produce Latin1 */
1958 {
1959 --dest;
1960 if (u8c >= 0x100)
1961 {
1962 /* character doesn't fit in latin1, retry with
1963 * another fenc when possible, otherwise just
1964 * report the error. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001965 if (can_retry)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001966 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001967 if (conv_error == 0)
1968 conv_error = readfile_linenr(linecnt, ptr, p);
1969 if (bad_char_behavior == BAD_DROP)
1970 ++dest;
1971 else if (bad_char_behavior == BAD_KEEP)
1972 *dest = u8c;
1973 else if (eap != NULL && eap->bad_char != 0)
1974 *dest = bad_char_behavior;
1975 else
1976 *dest = 0xBF;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001977 }
1978 else
1979 *dest = u8c;
1980 }
1981 }
1982
1983 /* move the linerest to before the converted characters */
1984 line_start = dest - linerest;
1985 mch_memmove(line_start, buffer, (size_t)linerest);
1986 size = (long)((ptr + real_size) - dest);
1987 ptr = dest;
1988 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001989 else if (enc_utf8 && !curbuf->b_p_bin)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001990 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001991 int incomplete_tail = FALSE;
1992
1993 /* Reading UTF-8: Check if the bytes are valid UTF-8. */
1994 for (p = ptr; ; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001995 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001996 int todo = (int)((ptr + size) - p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001997 int l;
1998
1999 if (todo <= 0)
2000 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002001 if (*p >= 0x80)
2002 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002003 /* A length of 1 means it's an illegal byte. Accept
2004 * an incomplete character at the end though, the next
2005 * read() will get the next bytes, we'll check it
2006 * then. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002007 l = utf_ptr2len_len(p, todo);
Bram Moolenaarf453d352008-06-04 17:37:34 +00002008 if (l > todo && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002009 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002010 /* Avoid retrying with a different encoding when
2011 * a truncated file is more likely, or attempting
2012 * to read the rest of an incomplete sequence when
2013 * we have already done so. */
2014 if (p > ptr || filesize > 0)
2015 incomplete_tail = TRUE;
2016 /* Incomplete byte sequence, move it to conv_rest[]
2017 * and try to read the rest of it, unless we've
2018 * already done so. */
2019 if (p > ptr)
2020 {
2021 conv_restlen = todo;
2022 mch_memmove(conv_rest, p, conv_restlen);
2023 size -= conv_restlen;
2024 break;
2025 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002026 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002027 if (l == 1 || l > todo)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002028 {
2029 /* Illegal byte. If we can try another encoding
Bram Moolenaarf453d352008-06-04 17:37:34 +00002030 * do that, unless at EOF where a truncated
2031 * file is more likely than a conversion error. */
2032 if (can_retry && !incomplete_tail)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002033 break;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002034# ifdef USE_ICONV
2035 /* When we did a conversion report an error. */
2036 if (iconv_fd != (iconv_t)-1 && conv_error == 0)
2037 conv_error = readfile_linenr(linecnt, ptr, p);
2038# endif
Bram Moolenaarf453d352008-06-04 17:37:34 +00002039 /* Remember the first linenr with an illegal byte */
2040 if (conv_error == 0 && illegal_byte == 0)
2041 illegal_byte = readfile_linenr(linecnt, ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002042
2043 /* Drop, keep or replace the bad byte. */
2044 if (bad_char_behavior == BAD_DROP)
2045 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002046 mch_memmove(p, p + 1, todo - 1);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002047 --p;
2048 --size;
2049 }
2050 else if (bad_char_behavior != BAD_KEEP)
2051 *p = bad_char_behavior;
2052 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002053 else
2054 p += l - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002055 }
2056 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002057 if (p < ptr + size && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002058 {
2059 /* Detected a UTF-8 error. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002060rewind_retry:
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002061 /* Retry reading with another conversion. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002062# if defined(FEAT_EVAL) && defined(USE_ICONV)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002063 if (*p_ccv != NUL && iconv_fd != (iconv_t)-1)
2064 /* iconv() failed, try 'charconvert' */
2065 did_iconv = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002066 else
2067# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002068 /* use next item from 'fileencodings' */
2069 advance_fenc = TRUE;
2070 file_rewind = TRUE;
2071 goto retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002072 }
2073 }
2074#endif
2075
2076 /* count the number of characters (after conversion!) */
2077 filesize += size;
2078
2079 /*
2080 * when reading the first part of a file: guess EOL type
2081 */
2082 if (fileformat == EOL_UNKNOWN)
2083 {
2084 /* First try finding a NL, for Dos and Unix */
2085 if (try_dos || try_unix)
2086 {
2087 for (p = ptr; p < ptr + size; ++p)
2088 {
2089 if (*p == NL)
2090 {
2091 if (!try_unix
2092 || (try_dos && p > ptr && p[-1] == CAR))
2093 fileformat = EOL_DOS;
2094 else
2095 fileformat = EOL_UNIX;
2096 break;
2097 }
2098 }
2099
2100 /* Don't give in to EOL_UNIX if EOL_MAC is more likely */
2101 if (fileformat == EOL_UNIX && try_mac)
2102 {
2103 /* Need to reset the counters when retrying fenc. */
2104 try_mac = 1;
2105 try_unix = 1;
2106 for (; p >= ptr && *p != CAR; p--)
2107 ;
2108 if (p >= ptr)
2109 {
2110 for (p = ptr; p < ptr + size; ++p)
2111 {
2112 if (*p == NL)
2113 try_unix++;
2114 else if (*p == CAR)
2115 try_mac++;
2116 }
2117 if (try_mac > try_unix)
2118 fileformat = EOL_MAC;
2119 }
2120 }
2121 }
2122
2123 /* No NL found: may use Mac format */
2124 if (fileformat == EOL_UNKNOWN && try_mac)
2125 fileformat = EOL_MAC;
2126
2127 /* Still nothing found? Use first format in 'ffs' */
2128 if (fileformat == EOL_UNKNOWN)
2129 fileformat = default_fileformat();
2130
2131 /* if editing a new file: may set p_tx and p_ff */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002132 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002133 set_fileformat(fileformat, OPT_LOCAL);
2134 }
2135 }
2136
2137 /*
2138 * This loop is executed once for every character read.
2139 * Keep it fast!
2140 */
2141 if (fileformat == EOL_MAC)
2142 {
2143 --ptr;
2144 while (++ptr, --size >= 0)
2145 {
2146 /* catch most common case first */
2147 if ((c = *ptr) != NUL && c != CAR && c != NL)
2148 continue;
2149 if (c == NUL)
2150 *ptr = NL; /* NULs are replaced by newlines! */
2151 else if (c == NL)
2152 *ptr = CAR; /* NLs are replaced by CRs! */
2153 else
2154 {
2155 if (skip_count == 0)
2156 {
2157 *ptr = NUL; /* end of line */
2158 len = (colnr_T) (ptr - line_start + 1);
2159 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2160 {
2161 error = TRUE;
2162 break;
2163 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002164#ifdef FEAT_PERSISTENT_UNDO
2165 if (read_undo_file)
2166 sha256_update(&sha_ctx, line_start, len);
2167#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002168 ++lnum;
2169 if (--read_count == 0)
2170 {
2171 error = TRUE; /* break loop */
2172 line_start = ptr; /* nothing left to write */
2173 break;
2174 }
2175 }
2176 else
2177 --skip_count;
2178 line_start = ptr + 1;
2179 }
2180 }
2181 }
2182 else
2183 {
2184 --ptr;
2185 while (++ptr, --size >= 0)
2186 {
2187 if ((c = *ptr) != NUL && c != NL) /* catch most common case */
2188 continue;
2189 if (c == NUL)
2190 *ptr = NL; /* NULs are replaced by newlines! */
2191 else
2192 {
2193 if (skip_count == 0)
2194 {
2195 *ptr = NUL; /* end of line */
2196 len = (colnr_T)(ptr - line_start + 1);
2197 if (fileformat == EOL_DOS)
2198 {
2199 if (ptr[-1] == CAR) /* remove CR */
2200 {
2201 ptr[-1] = NUL;
2202 --len;
2203 }
2204 /*
2205 * Reading in Dos format, but no CR-LF found!
2206 * When 'fileformats' includes "unix", delete all
2207 * the lines read so far and start all over again.
2208 * Otherwise give an error message later.
2209 */
2210 else if (ff_error != EOL_DOS)
2211 {
2212 if ( try_unix
2213 && !read_stdin
2214 && (read_buffer
2215 || lseek(fd, (off_t)0L, SEEK_SET) == 0))
2216 {
2217 fileformat = EOL_UNIX;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002218 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002219 set_fileformat(EOL_UNIX, OPT_LOCAL);
2220 file_rewind = TRUE;
2221 keep_fileformat = TRUE;
2222 goto retry;
2223 }
2224 ff_error = EOL_DOS;
2225 }
2226 }
2227 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2228 {
2229 error = TRUE;
2230 break;
2231 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002232#ifdef FEAT_PERSISTENT_UNDO
2233 if (read_undo_file)
2234 sha256_update(&sha_ctx, line_start, len);
2235#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002236 ++lnum;
2237 if (--read_count == 0)
2238 {
2239 error = TRUE; /* break loop */
2240 line_start = ptr; /* nothing left to write */
2241 break;
2242 }
2243 }
2244 else
2245 --skip_count;
2246 line_start = ptr + 1;
2247 }
2248 }
2249 }
2250 linerest = (long)(ptr - line_start);
2251 ui_breakcheck();
2252 }
2253
2254failed:
2255 /* not an error, max. number of lines reached */
2256 if (error && read_count == 0)
2257 error = FALSE;
2258
2259 /*
2260 * If we get EOF in the middle of a line, note the fact and
2261 * complete the line ourselves.
2262 * In Dos format ignore a trailing CTRL-Z, unless 'binary' set.
2263 */
2264 if (!error
2265 && !got_int
2266 && linerest != 0
2267 && !(!curbuf->b_p_bin
2268 && fileformat == EOL_DOS
2269 && *line_start == Ctrl_Z
2270 && ptr == line_start + 1))
2271 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002272 /* remember for when writing */
2273 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002274 curbuf->b_p_eol = FALSE;
2275 *ptr = NUL;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002276 len = (colnr_T)(ptr - line_start + 1);
2277 if (ml_append(lnum, line_start, len, newfile) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002278 error = TRUE;
2279 else
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002280 {
2281#ifdef FEAT_PERSISTENT_UNDO
2282 if (read_undo_file)
2283 sha256_update(&sha_ctx, line_start, len);
2284#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002285 read_no_eol_lnum = ++lnum;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002286 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002287 }
2288
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002289 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002290 save_file_ff(curbuf); /* remember the current file format */
2291
2292#ifdef FEAT_CRYPT
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002293 if (cryptkey != NULL)
2294 {
2295 crypt_pop_state();
2296 if (cryptkey != curbuf->b_p_key)
2297 free_crypt_key(cryptkey);
2298 /* don't set cryptkey to NULL, it's used below as a flag that
2299 * encryption was used */
2300 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002301#endif
2302
2303#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002304 /* If editing a new file: set 'fenc' for the current buffer.
2305 * Also for ":read ++edit file". */
2306 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002307 set_string_option_direct((char_u *)"fenc", -1, fenc,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00002308 OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002309 if (fenc_alloced)
2310 vim_free(fenc);
2311# ifdef USE_ICONV
2312 if (iconv_fd != (iconv_t)-1)
2313 {
2314 iconv_close(iconv_fd);
2315 iconv_fd = (iconv_t)-1;
2316 }
2317# endif
2318#endif
2319
2320 if (!read_buffer && !read_stdin)
2321 close(fd); /* errors are ignored */
Bram Moolenaarf05da212009-11-17 16:13:15 +00002322#ifdef HAVE_FD_CLOEXEC
2323 else
2324 {
2325 int fdflags = fcntl(fd, F_GETFD);
2326 if (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0)
2327 fcntl(fd, F_SETFD, fdflags | FD_CLOEXEC);
2328 }
2329#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002330 vim_free(buffer);
2331
2332#ifdef HAVE_DUP
2333 if (read_stdin)
2334 {
2335 /* Use stderr for stdin, makes shell commands work. */
2336 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00002337 ignored = dup(2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002338 }
2339#endif
2340
2341#ifdef FEAT_MBYTE
2342 if (tmpname != NULL)
2343 {
2344 mch_remove(tmpname); /* delete converted file */
2345 vim_free(tmpname);
2346 }
2347#endif
2348 --no_wait_return; /* may wait for return now */
2349
2350 /*
2351 * In recovery mode everything but autocommands is skipped.
2352 */
2353 if (!recoverymode)
2354 {
2355 /* need to delete the last line, which comes from the empty buffer */
2356 if (newfile && wasempty && !(curbuf->b_ml.ml_flags & ML_EMPTY))
2357 {
2358#ifdef FEAT_NETBEANS_INTG
2359 netbeansFireChanges = 0;
2360#endif
2361 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
2362#ifdef FEAT_NETBEANS_INTG
2363 netbeansFireChanges = 1;
2364#endif
2365 --linecnt;
2366 }
2367 linecnt = curbuf->b_ml.ml_line_count - linecnt;
2368 if (filesize == 0)
2369 linecnt = 0;
2370 if (newfile || read_buffer)
Bram Moolenaar7263a772007-05-10 17:35:54 +00002371 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002372 redraw_curbuf_later(NOT_VALID);
Bram Moolenaar7263a772007-05-10 17:35:54 +00002373#ifdef FEAT_DIFF
2374 /* After reading the text into the buffer the diff info needs to
2375 * be updated. */
2376 diff_invalidate(curbuf);
2377#endif
2378#ifdef FEAT_FOLDING
2379 /* All folds in the window are invalid now. Mark them for update
2380 * before triggering autocommands. */
2381 foldUpdateAll(curwin);
2382#endif
2383 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002384 else if (linecnt) /* appended at least one line */
2385 appended_lines_mark(from, linecnt);
2386
Bram Moolenaar071d4272004-06-13 20:20:40 +00002387#ifndef ALWAYS_USE_GUI
2388 /*
2389 * If we were reading from the same terminal as where messages go,
2390 * the screen will have been messed up.
2391 * Switch on raw mode now and clear the screen.
2392 */
2393 if (read_stdin)
2394 {
2395 settmode(TMODE_RAW); /* set to raw mode */
2396 starttermcap();
2397 screenclear();
2398 }
2399#endif
2400
2401 if (got_int)
2402 {
2403 if (!(flags & READ_DUMMY))
2404 {
2405 filemess(curbuf, sfname, (char_u *)_(e_interr), 0);
2406 if (newfile)
2407 curbuf->b_p_ro = TRUE; /* must use "w!" now */
2408 }
2409 msg_scroll = msg_save;
2410#ifdef FEAT_VIMINFO
2411 check_marks_read();
2412#endif
2413 return OK; /* an interrupt isn't really an error */
2414 }
2415
2416 if (!filtering && !(flags & READ_DUMMY))
2417 {
2418 msg_add_fname(curbuf, sfname); /* fname in IObuff with quotes */
2419 c = FALSE;
2420
2421#ifdef UNIX
2422# ifdef S_ISFIFO
2423 if (S_ISFIFO(perm)) /* fifo or socket */
2424 {
2425 STRCAT(IObuff, _("[fifo/socket]"));
2426 c = TRUE;
2427 }
2428# else
2429# ifdef S_IFIFO
2430 if ((perm & S_IFMT) == S_IFIFO) /* fifo */
2431 {
2432 STRCAT(IObuff, _("[fifo]"));
2433 c = TRUE;
2434 }
2435# endif
2436# ifdef S_IFSOCK
2437 if ((perm & S_IFMT) == S_IFSOCK) /* or socket */
2438 {
2439 STRCAT(IObuff, _("[socket]"));
2440 c = TRUE;
2441 }
2442# endif
2443# endif
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002444# ifdef OPEN_CHR_FILES
2445 if (S_ISCHR(perm)) /* or character special */
2446 {
2447 STRCAT(IObuff, _("[character special]"));
2448 c = TRUE;
2449 }
2450# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002451#endif
2452 if (curbuf->b_p_ro)
2453 {
2454 STRCAT(IObuff, shortmess(SHM_RO) ? _("[RO]") : _("[readonly]"));
2455 c = TRUE;
2456 }
2457 if (read_no_eol_lnum)
2458 {
2459 msg_add_eol();
2460 c = TRUE;
2461 }
2462 if (ff_error == EOL_DOS)
2463 {
2464 STRCAT(IObuff, _("[CR missing]"));
2465 c = TRUE;
2466 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002467 if (split)
2468 {
2469 STRCAT(IObuff, _("[long lines split]"));
2470 c = TRUE;
2471 }
2472#ifdef FEAT_MBYTE
2473 if (notconverted)
2474 {
2475 STRCAT(IObuff, _("[NOT converted]"));
2476 c = TRUE;
2477 }
2478 else if (converted)
2479 {
2480 STRCAT(IObuff, _("[converted]"));
2481 c = TRUE;
2482 }
2483#endif
2484#ifdef FEAT_CRYPT
2485 if (cryptkey != NULL)
2486 {
2487 STRCAT(IObuff, _("[crypted]"));
2488 c = TRUE;
2489 }
2490#endif
2491#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002492 if (conv_error != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002493 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002494 sprintf((char *)IObuff + STRLEN(IObuff),
2495 _("[CONVERSION ERROR in line %ld]"), (long)conv_error);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002496 c = TRUE;
2497 }
2498 else if (illegal_byte > 0)
2499 {
2500 sprintf((char *)IObuff + STRLEN(IObuff),
2501 _("[ILLEGAL BYTE in line %ld]"), (long)illegal_byte);
2502 c = TRUE;
2503 }
2504 else
2505#endif
2506 if (error)
2507 {
2508 STRCAT(IObuff, _("[READ ERRORS]"));
2509 c = TRUE;
2510 }
2511 if (msg_add_fileformat(fileformat))
2512 c = TRUE;
2513#ifdef FEAT_CRYPT
2514 if (cryptkey != NULL)
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002515 msg_add_lines(c, (long)linecnt, filesize
Bram Moolenaar80794b12010-06-13 05:20:42 +02002516 - CRYPT_MAGIC_LEN
2517 - crypt_salt_len[use_crypt_method]
2518 - crypt_seed_len[use_crypt_method]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002519 else
2520#endif
2521 msg_add_lines(c, (long)linecnt, filesize);
2522
2523 vim_free(keep_msg);
2524 keep_msg = NULL;
2525 msg_scrolled_ign = TRUE;
2526#ifdef ALWAYS_USE_GUI
2527 /* Don't show the message when reading stdin, it would end up in a
2528 * message box (which might be shown when exiting!) */
2529 if (read_stdin || read_buffer)
2530 p = msg_may_trunc(FALSE, IObuff);
2531 else
2532#endif
2533 p = msg_trunc_attr(IObuff, FALSE, 0);
2534 if (read_stdin || read_buffer || restart_edit != 0
Bram Moolenaar1c7715d2005-10-03 22:02:18 +00002535 || (msg_scrolled != 0 && !need_wait_return))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002536 /* Need to repeat the message after redrawing when:
2537 * - When reading from stdin (the screen will be cleared next).
2538 * - When restart_edit is set (otherwise there will be a delay
2539 * before redrawing).
2540 * - When the screen was scrolled but there is no wait-return
2541 * prompt. */
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002542 set_keep_msg(p, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002543 msg_scrolled_ign = FALSE;
2544 }
2545
2546 /* with errors writing the file requires ":w!" */
2547 if (newfile && (error
2548#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002549 || conv_error != 0
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002550 || (illegal_byte > 0 && bad_char_behavior != BAD_KEEP)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002551#endif
2552 ))
2553 curbuf->b_p_ro = TRUE;
2554
2555 u_clearline(); /* cannot use "U" command after adding lines */
2556
2557 /*
2558 * In Ex mode: cursor at last new line.
2559 * Otherwise: cursor at first new line.
2560 */
2561 if (exmode_active)
2562 curwin->w_cursor.lnum = from + linecnt;
2563 else
2564 curwin->w_cursor.lnum = from + 1;
2565 check_cursor_lnum();
2566 beginline(BL_WHITE | BL_FIX); /* on first non-blank */
2567
2568 /*
2569 * Set '[ and '] marks to the newly read lines.
2570 */
2571 curbuf->b_op_start.lnum = from + 1;
2572 curbuf->b_op_start.col = 0;
2573 curbuf->b_op_end.lnum = from + linecnt;
2574 curbuf->b_op_end.col = 0;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002575
2576#ifdef WIN32
2577 /*
2578 * Work around a weird problem: When a file has two links (only
2579 * possible on NTFS) and we write through one link, then stat() it
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00002580 * through the other link, the timestamp information may be wrong.
Bram Moolenaar03f48552006-02-28 23:52:23 +00002581 * It's correct again after reading the file, thus reset the timestamp
2582 * here.
2583 */
2584 if (newfile && !read_stdin && !read_buffer
2585 && mch_stat((char *)fname, &st) >= 0)
2586 {
2587 buf_store_time(curbuf, &st, fname);
2588 curbuf->b_mtime_read = curbuf->b_mtime;
2589 }
2590#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002591 }
2592 msg_scroll = msg_save;
2593
2594#ifdef FEAT_VIMINFO
2595 /*
2596 * Get the marks before executing autocommands, so they can be used there.
2597 */
2598 check_marks_read();
2599#endif
2600
Bram Moolenaar071d4272004-06-13 20:20:40 +00002601 /*
2602 * Trick: We remember if the last line of the read didn't have
2603 * an eol for when writing it again. This is required for
2604 * ":autocmd FileReadPost *.gz set bin|'[,']!gunzip" to work.
2605 */
2606 write_no_eol_lnum = read_no_eol_lnum;
2607
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02002608 /* When reloading a buffer put the cursor at the first line that is
2609 * different. */
2610 if (flags & READ_KEEP_UNDO)
2611 u_find_first_changed();
2612
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002613#ifdef FEAT_PERSISTENT_UNDO
2614 /*
2615 * When opening a new file locate undo info and read it.
2616 */
2617 if (read_undo_file)
2618 {
2619 char_u hash[UNDO_HASH_SIZE];
2620
2621 sha256_finish(&sha_ctx, hash);
Bram Moolenaar6ed8ed82010-05-30 20:40:11 +02002622 u_read_undo(NULL, hash, fname);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002623 }
2624#endif
2625
Bram Moolenaardf177f62005-02-22 08:39:57 +00002626#ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00002627 if (!read_stdin && !read_buffer)
2628 {
2629 int m = msg_scroll;
2630 int n = msg_scrolled;
2631
2632 /* Save the fileformat now, otherwise the buffer will be considered
2633 * modified if the format/encoding was automatically detected. */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002634 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002635 save_file_ff(curbuf);
2636
2637 /*
2638 * The output from the autocommands should not overwrite anything and
2639 * should not be overwritten: Set msg_scroll, restore its value if no
2640 * output was done.
2641 */
2642 msg_scroll = TRUE;
2643 if (filtering)
2644 apply_autocmds_exarg(EVENT_FILTERREADPOST, NULL, sfname,
2645 FALSE, curbuf, eap);
2646 else if (newfile)
2647 apply_autocmds_exarg(EVENT_BUFREADPOST, NULL, sfname,
2648 FALSE, curbuf, eap);
2649 else
2650 apply_autocmds_exarg(EVENT_FILEREADPOST, sfname, sfname,
2651 FALSE, NULL, eap);
2652 if (msg_scrolled == n)
2653 msg_scroll = m;
2654#ifdef FEAT_EVAL
2655 if (aborting()) /* autocmds may abort script processing */
2656 return FAIL;
2657#endif
2658 }
2659#endif
2660
2661 if (recoverymode && error)
2662 return FAIL;
2663 return OK;
2664}
2665
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002666#ifdef OPEN_CHR_FILES
2667/*
2668 * Returns TRUE if the file name argument is of the form "/dev/fd/\d\+",
2669 * which is the name of files used for process substitution output by
2670 * some shells on some operating systems, e.g., bash on SunOS.
2671 * Do not accept "/dev/fd/[012]", opening these may hang Vim.
2672 */
2673 static int
2674is_dev_fd_file(fname)
2675 char_u *fname;
2676{
2677 return (STRNCMP(fname, "/dev/fd/", 8) == 0
2678 && VIM_ISDIGIT(fname[8])
2679 && *skipdigits(fname + 9) == NUL
2680 && (fname[9] != NUL
2681 || (fname[8] != '0' && fname[8] != '1' && fname[8] != '2')));
2682}
2683#endif
2684
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002685#ifdef FEAT_MBYTE
2686
2687/*
2688 * From the current line count and characters read after that, estimate the
2689 * line number where we are now.
2690 * Used for error messages that include a line number.
2691 */
2692 static linenr_T
2693readfile_linenr(linecnt, p, endp)
2694 linenr_T linecnt; /* line count before reading more bytes */
2695 char_u *p; /* start of more bytes read */
2696 char_u *endp; /* end of more bytes read */
2697{
2698 char_u *s;
2699 linenr_T lnum;
2700
2701 lnum = curbuf->b_ml.ml_line_count - linecnt + 1;
2702 for (s = p; s < endp; ++s)
2703 if (*s == '\n')
2704 ++lnum;
2705 return lnum;
2706}
2707#endif
2708
Bram Moolenaar071d4272004-06-13 20:20:40 +00002709/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00002710 * Fill "*eap" to force the 'fileencoding', 'fileformat' and 'binary to be
2711 * equal to the buffer "buf". Used for calling readfile().
Bram Moolenaar071d4272004-06-13 20:20:40 +00002712 * Returns OK or FAIL.
2713 */
2714 int
2715prep_exarg(eap, buf)
2716 exarg_T *eap;
2717 buf_T *buf;
2718{
2719 eap->cmd = alloc((unsigned)(STRLEN(buf->b_p_ff)
2720#ifdef FEAT_MBYTE
2721 + STRLEN(buf->b_p_fenc)
2722#endif
2723 + 15));
2724 if (eap->cmd == NULL)
2725 return FAIL;
2726
2727#ifdef FEAT_MBYTE
2728 sprintf((char *)eap->cmd, "e ++ff=%s ++enc=%s", buf->b_p_ff, buf->b_p_fenc);
2729 eap->force_enc = 14 + (int)STRLEN(buf->b_p_ff);
Bram Moolenaar195d6352005-12-19 22:08:24 +00002730 eap->bad_char = buf->b_bad_char;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002731#else
2732 sprintf((char *)eap->cmd, "e ++ff=%s", buf->b_p_ff);
2733#endif
2734 eap->force_ff = 7;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002735
2736 eap->force_bin = buf->b_p_bin ? FORCE_BIN : FORCE_NOBIN;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002737 eap->read_edit = FALSE;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002738 eap->forceit = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002739 return OK;
2740}
2741
2742#ifdef FEAT_MBYTE
2743/*
2744 * Find next fileencoding to use from 'fileencodings'.
2745 * "pp" points to fenc_next. It's advanced to the next item.
2746 * When there are no more items, an empty string is returned and *pp is set to
2747 * NULL.
2748 * When *pp is not set to NULL, the result is in allocated memory.
2749 */
2750 static char_u *
2751next_fenc(pp)
2752 char_u **pp;
2753{
2754 char_u *p;
2755 char_u *r;
2756
2757 if (**pp == NUL)
2758 {
2759 *pp = NULL;
2760 return (char_u *)"";
2761 }
2762 p = vim_strchr(*pp, ',');
2763 if (p == NULL)
2764 {
2765 r = enc_canonize(*pp);
2766 *pp += STRLEN(*pp);
2767 }
2768 else
2769 {
2770 r = vim_strnsave(*pp, (int)(p - *pp));
2771 *pp = p + 1;
2772 if (r != NULL)
2773 {
2774 p = enc_canonize(r);
2775 vim_free(r);
2776 r = p;
2777 }
2778 }
2779 if (r == NULL) /* out of memory */
2780 {
2781 r = (char_u *)"";
2782 *pp = NULL;
2783 }
2784 return r;
2785}
2786
2787# ifdef FEAT_EVAL
2788/*
2789 * Convert a file with the 'charconvert' expression.
2790 * This closes the file which is to be read, converts it and opens the
2791 * resulting file for reading.
2792 * Returns name of the resulting converted file (the caller should delete it
2793 * after reading it).
2794 * Returns NULL if the conversion failed ("*fdp" is not set) .
2795 */
2796 static char_u *
2797readfile_charconvert(fname, fenc, fdp)
2798 char_u *fname; /* name of input file */
2799 char_u *fenc; /* converted from */
2800 int *fdp; /* in/out: file descriptor of file */
2801{
2802 char_u *tmpname;
2803 char_u *errmsg = NULL;
2804
2805 tmpname = vim_tempname('r');
2806 if (tmpname == NULL)
2807 errmsg = (char_u *)_("Can't find temp file for conversion");
2808 else
2809 {
2810 close(*fdp); /* close the input file, ignore errors */
2811 *fdp = -1;
2812 if (eval_charconvert(fenc, enc_utf8 ? (char_u *)"utf-8" : p_enc,
2813 fname, tmpname) == FAIL)
2814 errmsg = (char_u *)_("Conversion with 'charconvert' failed");
2815 if (errmsg == NULL && (*fdp = mch_open((char *)tmpname,
2816 O_RDONLY | O_EXTRA, 0)) < 0)
2817 errmsg = (char_u *)_("can't read output of 'charconvert'");
2818 }
2819
2820 if (errmsg != NULL)
2821 {
2822 /* Don't use emsg(), it breaks mappings, the retry with
2823 * another type of conversion might still work. */
2824 MSG(errmsg);
2825 if (tmpname != NULL)
2826 {
2827 mch_remove(tmpname); /* delete converted file */
2828 vim_free(tmpname);
2829 tmpname = NULL;
2830 }
2831 }
2832
2833 /* If the input file is closed, open it (caller should check for error). */
2834 if (*fdp < 0)
2835 *fdp = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
2836
2837 return tmpname;
2838}
2839# endif
2840
2841#endif
2842
2843#ifdef FEAT_VIMINFO
2844/*
2845 * Read marks for the current buffer from the viminfo file, when we support
2846 * buffer marks and the buffer has a name.
2847 */
2848 static void
2849check_marks_read()
2850{
2851 if (!curbuf->b_marks_read && get_viminfo_parameter('\'') > 0
2852 && curbuf->b_ffname != NULL)
Bram Moolenaard812df62008-11-09 12:46:09 +00002853 read_viminfo(NULL, VIF_WANT_MARKS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002854
2855 /* Always set b_marks_read; needed when 'viminfo' is changed to include
2856 * the ' parameter after opening a buffer. */
2857 curbuf->b_marks_read = TRUE;
2858}
2859#endif
2860
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002861#if defined(FEAT_CRYPT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002862/*
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002863 * Get the crypt method used for a file from "ptr[len]", the magic text at the
2864 * start of the file.
2865 * Returns -1 when no encryption used.
2866 */
2867 static int
Bram Moolenaar49771f42010-07-20 17:32:38 +02002868crypt_method_from_magic(ptr, len)
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002869 char *ptr;
2870 int len;
2871{
2872 int i;
2873
2874 for (i = 0; i < (int)(sizeof(crypt_magic) / sizeof(crypt_magic[0])); i++)
2875 {
Bram Moolenaar80794b12010-06-13 05:20:42 +02002876 if (len < (CRYPT_MAGIC_LEN + crypt_salt_len[i] + crypt_seed_len[i]))
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002877 continue;
2878 if (memcmp(ptr, crypt_magic[i], CRYPT_MAGIC_LEN) == 0)
2879 return i;
2880 }
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002881
Bram Moolenaar442b4222010-05-24 21:34:22 +02002882 i = (int)STRLEN(crypt_magic_head);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002883 if (len >= i && memcmp(ptr, crypt_magic_head, i) == 0)
2884 EMSG(_("E821: File is encrypted with unknown method"));
2885
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002886 return -1;
2887}
2888
2889/*
2890 * Check for magic number used for encryption. Applies to the current buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002891 * If found, the magic number is removed from ptr[*sizep] and *sizep and
2892 * *filesizep are updated.
2893 * Return the (new) encryption key, NULL for no encryption.
2894 */
2895 static char_u *
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002896check_for_cryptkey(cryptkey, ptr, sizep, filesizep, newfile, fname, did_ask)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002897 char_u *cryptkey; /* previous encryption key or NULL */
2898 char_u *ptr; /* pointer to read bytes */
2899 long *sizep; /* length of read bytes */
Bram Moolenaar914703b2010-05-31 21:59:46 +02002900 off_t *filesizep; /* nr of bytes used from file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002901 int newfile; /* editing a new buffer */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002902 char_u *fname; /* file name to display */
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002903 int *did_ask; /* flag: whether already asked for key */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002904{
Bram Moolenaar49771f42010-07-20 17:32:38 +02002905 int method = crypt_method_from_magic((char *)ptr, *sizep);
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002906
2907 if (method >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002908 {
Bram Moolenaar49771f42010-07-20 17:32:38 +02002909 set_crypt_method(curbuf, method);
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002910 if (method > 0)
2911 (void)blowfish_self_test();
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002912 if (cryptkey == NULL && !*did_ask)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002913 {
2914 if (*curbuf->b_p_key)
2915 cryptkey = curbuf->b_p_key;
2916 else
2917 {
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002918 /* When newfile is TRUE, store the typed key in the 'key'
2919 * option and don't free it. bf needs hash of the key saved.
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002920 * Don't ask for the key again when first time Enter was hit.
2921 * Happens when retrying to detect encoding. */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002922 smsg((char_u *)_(need_key_msg), fname);
2923 msg_scroll = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002924 cryptkey = get_crypt_key(newfile, FALSE);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002925 *did_ask = TRUE;
2926
Bram Moolenaar071d4272004-06-13 20:20:40 +00002927 /* check if empty key entered */
2928 if (cryptkey != NULL && *cryptkey == NUL)
2929 {
2930 if (cryptkey != curbuf->b_p_key)
2931 vim_free(cryptkey);
2932 cryptkey = NULL;
2933 }
2934 }
2935 }
2936
2937 if (cryptkey != NULL)
2938 {
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002939 int seed_len = crypt_seed_len[method];
Bram Moolenaar80794b12010-06-13 05:20:42 +02002940 int salt_len = crypt_salt_len[method];
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002941
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002942 crypt_push_state();
2943 use_crypt_method = method;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002944 if (method == 0)
2945 crypt_init_keys(cryptkey);
2946 else
2947 {
Bram Moolenaar80794b12010-06-13 05:20:42 +02002948 bf_key_init(cryptkey, ptr + CRYPT_MAGIC_LEN, salt_len);
2949 bf_ofb_init(ptr + CRYPT_MAGIC_LEN + salt_len, seed_len);
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002950 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002951
2952 /* Remove magic number from the text */
Bram Moolenaar80794b12010-06-13 05:20:42 +02002953 *filesizep += CRYPT_MAGIC_LEN + salt_len + seed_len;
2954 *sizep -= CRYPT_MAGIC_LEN + salt_len + seed_len;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002955 mch_memmove(ptr, ptr + CRYPT_MAGIC_LEN + salt_len + seed_len,
2956 (size_t)*sizep);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002957 }
2958 }
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002959 /* When starting to edit a new file which does not have encryption, clear
2960 * the 'key' option, except when starting up (called with -x argument) */
Bram Moolenaarfa0ff9a2010-07-25 16:05:19 +02002961 else if (newfile && *curbuf->b_p_key != NUL && !starting)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002962 set_option_value((char_u *)"key", 0L, (char_u *)"", OPT_LOCAL);
2963
2964 return cryptkey;
2965}
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002966
2967/*
2968 * Check for magic number used for encryption. Applies to the current buffer.
2969 * If found and decryption is possible returns OK;
2970 */
2971 int
2972prepare_crypt_read(fp)
2973 FILE *fp;
2974{
2975 int method;
Bram Moolenaar80794b12010-06-13 05:20:42 +02002976 char_u buffer[CRYPT_MAGIC_LEN + CRYPT_SALT_LEN_MAX
2977 + CRYPT_SEED_LEN_MAX + 2];
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002978
2979 if (fread(buffer, CRYPT_MAGIC_LEN, 1, fp) != 1)
2980 return FAIL;
Bram Moolenaar49771f42010-07-20 17:32:38 +02002981 method = crypt_method_from_magic((char *)buffer,
Bram Moolenaar80794b12010-06-13 05:20:42 +02002982 CRYPT_MAGIC_LEN +
Bram Moolenaarcc448b32010-07-14 16:52:17 +02002983 CRYPT_SEED_LEN_MAX +
2984 CRYPT_SALT_LEN_MAX);
Bram Moolenaar49771f42010-07-20 17:32:38 +02002985 if (method < 0 || method != get_crypt_method(curbuf))
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002986 return FAIL;
2987
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002988 crypt_push_state();
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002989 if (method == 0)
2990 crypt_init_keys(curbuf->b_p_key);
2991 else
2992 {
Bram Moolenaar80794b12010-06-13 05:20:42 +02002993 int salt_len = crypt_salt_len[method];
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002994 int seed_len = crypt_seed_len[method];
2995
Bram Moolenaar80794b12010-06-13 05:20:42 +02002996 if (fread(buffer, salt_len + seed_len, 1, fp) != 1)
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002997 return FAIL;
Bram Moolenaar80794b12010-06-13 05:20:42 +02002998 bf_key_init(curbuf->b_p_key, buffer, salt_len);
2999 bf_ofb_init(buffer + salt_len, seed_len);
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003000 }
3001 return OK;
3002}
3003
3004/*
3005 * Prepare for writing encrypted bytes for buffer "buf".
3006 * Returns a pointer to an allocated header of length "*lenp".
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003007 * When out of memory returns NULL.
3008 * Otherwise calls crypt_push_state(), call crypt_pop_state() later.
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003009 */
3010 char_u *
3011prepare_crypt_write(buf, lenp)
3012 buf_T *buf;
3013 int *lenp;
3014{
3015 char_u *header;
Bram Moolenaar49771f42010-07-20 17:32:38 +02003016 int seed_len = crypt_seed_len[get_crypt_method(buf)];
3017 int salt_len = crypt_salt_len[get_crypt_method(buf)];
Bram Moolenaar80794b12010-06-13 05:20:42 +02003018 char_u *salt;
3019 char_u *seed;
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003020
Bram Moolenaar80794b12010-06-13 05:20:42 +02003021 header = alloc_clear(CRYPT_MAGIC_LEN + CRYPT_SALT_LEN_MAX
3022 + CRYPT_SEED_LEN_MAX + 2);
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003023 if (header != NULL)
3024 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003025 crypt_push_state();
Bram Moolenaar49771f42010-07-20 17:32:38 +02003026 use_crypt_method = get_crypt_method(buf); /* select zip or blowfish */
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003027 vim_strncpy(header, (char_u *)crypt_magic[use_crypt_method],
3028 CRYPT_MAGIC_LEN);
Bram Moolenaar49771f42010-07-20 17:32:38 +02003029 if (use_crypt_method == 0)
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003030 crypt_init_keys(buf->b_p_key);
3031 else
3032 {
Bram Moolenaar80794b12010-06-13 05:20:42 +02003033 /* Using blowfish, add salt and seed. */
3034 salt = header + CRYPT_MAGIC_LEN;
3035 seed = salt + salt_len;
3036 sha2_seed(salt, salt_len, seed, seed_len);
3037 bf_key_init(buf->b_p_key, salt, salt_len);
3038 bf_ofb_init(seed, seed_len);
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003039 }
3040 }
Bram Moolenaar80794b12010-06-13 05:20:42 +02003041 *lenp = CRYPT_MAGIC_LEN + salt_len + seed_len;
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003042 return header;
3043}
3044
Bram Moolenaar80794b12010-06-13 05:20:42 +02003045#endif /* FEAT_CRYPT */
3046
Bram Moolenaar071d4272004-06-13 20:20:40 +00003047#ifdef UNIX
3048 static void
3049set_file_time(fname, atime, mtime)
3050 char_u *fname;
3051 time_t atime; /* access time */
3052 time_t mtime; /* modification time */
3053{
3054# if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
3055 struct utimbuf buf;
3056
3057 buf.actime = atime;
3058 buf.modtime = mtime;
3059 (void)utime((char *)fname, &buf);
3060# else
3061# if defined(HAVE_UTIMES)
3062 struct timeval tvp[2];
3063
3064 tvp[0].tv_sec = atime;
3065 tvp[0].tv_usec = 0;
3066 tvp[1].tv_sec = mtime;
3067 tvp[1].tv_usec = 0;
3068# ifdef NeXT
3069 (void)utimes((char *)fname, tvp);
3070# else
3071 (void)utimes((char *)fname, (const struct timeval *)&tvp);
3072# endif
3073# endif
3074# endif
3075}
3076#endif /* UNIX */
3077
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003078#if defined(VMS) && !defined(MIN)
3079/* Older DECC compiler for VAX doesn't define MIN() */
3080# define MIN(a, b) ((a) < (b) ? (a) : (b))
3081#endif
3082
Bram Moolenaar071d4272004-06-13 20:20:40 +00003083/*
Bram Moolenaar5386a122007-06-28 20:02:32 +00003084 * Return TRUE if a file appears to be read-only from the file permissions.
3085 */
3086 int
3087check_file_readonly(fname, perm)
3088 char_u *fname; /* full path to file */
3089 int perm; /* known permissions on file */
3090{
3091#ifndef USE_MCH_ACCESS
3092 int fd = 0;
3093#endif
3094
3095 return (
3096#ifdef USE_MCH_ACCESS
3097# ifdef UNIX
3098 (perm & 0222) == 0 ||
3099# endif
3100 mch_access((char *)fname, W_OK)
3101#else
3102 (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0
3103 ? TRUE : (close(fd), FALSE)
3104#endif
3105 );
3106}
3107
3108
3109/*
Bram Moolenaar292ad192005-12-11 21:29:51 +00003110 * buf_write() - write to file "fname" lines "start" through "end"
Bram Moolenaar071d4272004-06-13 20:20:40 +00003111 *
3112 * We do our own buffering here because fwrite() is so slow.
3113 *
Bram Moolenaar292ad192005-12-11 21:29:51 +00003114 * If "forceit" is true, we don't care for errors when attempting backups.
3115 * In case of an error everything possible is done to restore the original
Bram Moolenaare37d50a2008-08-06 17:06:04 +00003116 * file. But when "forceit" is TRUE, we risk losing it.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003117 *
3118 * When "reset_changed" is TRUE and "append" == FALSE and "start" == 1 and
3119 * "end" == curbuf->b_ml.ml_line_count, reset curbuf->b_changed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003120 *
3121 * This function must NOT use NameBuff (because it's called by autowrite()).
3122 *
3123 * return FAIL for failure, OK otherwise
3124 */
3125 int
3126buf_write(buf, fname, sfname, start, end, eap, append, forceit,
3127 reset_changed, filtering)
3128 buf_T *buf;
3129 char_u *fname;
3130 char_u *sfname;
3131 linenr_T start, end;
3132 exarg_T *eap; /* for forced 'ff' and 'fenc', can be
3133 NULL! */
Bram Moolenaar292ad192005-12-11 21:29:51 +00003134 int append; /* append to the file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003135 int forceit;
3136 int reset_changed;
3137 int filtering;
3138{
3139 int fd;
3140 char_u *backup = NULL;
3141 int backup_copy = FALSE; /* copy the original file? */
3142 int dobackup;
3143 char_u *ffname;
3144 char_u *wfname = NULL; /* name of file to write to */
3145 char_u *s;
3146 char_u *ptr;
3147 char_u c;
3148 int len;
3149 linenr_T lnum;
3150 long nchars;
3151 char_u *errmsg = NULL;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003152 int errmsg_allocated = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003153 char_u *errnum = NULL;
3154 char_u *buffer;
3155 char_u smallbuf[SMBUFSIZE];
3156 char_u *backup_ext;
3157 int bufsize;
3158 long perm; /* file permissions */
3159 int retval = OK;
3160 int newfile = FALSE; /* TRUE if file doesn't exist yet */
3161 int msg_save = msg_scroll;
3162 int overwriting; /* TRUE if writing over original */
3163 int no_eol = FALSE; /* no end-of-line written */
3164 int device = FALSE; /* writing to a device */
3165 struct stat st_old;
3166 int prev_got_int = got_int;
3167 int file_readonly = FALSE; /* overwritten file is read-only */
3168 static char *err_readonly = "is read-only (cannot override: \"W\" in 'cpoptions')";
3169#if defined(UNIX) || defined(__EMX__XX) /*XXX fix me sometime? */
3170 int made_writable = FALSE; /* 'w' bit has been set */
3171#endif
3172 /* writing everything */
3173 int whole = (start == 1 && end == buf->b_ml.ml_line_count);
3174#ifdef FEAT_AUTOCMD
3175 linenr_T old_line_count = buf->b_ml.ml_line_count;
3176#endif
3177 int attr;
3178 int fileformat;
3179 int write_bin;
3180 struct bw_info write_info; /* info for buf_write_bytes() */
3181#ifdef FEAT_MBYTE
3182 int converted = FALSE;
3183 int notconverted = FALSE;
3184 char_u *fenc; /* effective 'fileencoding' */
3185 char_u *fenc_tofree = NULL; /* allocated "fenc" */
3186#endif
3187#ifdef HAS_BW_FLAGS
3188 int wb_flags = 0;
3189#endif
3190#ifdef HAVE_ACL
3191 vim_acl_T acl = NULL; /* ACL copied from original file to
3192 backup or new file */
3193#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003194#ifdef FEAT_PERSISTENT_UNDO
3195 int write_undo_file = FALSE;
3196 context_sha256_T sha_ctx;
3197#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003198
3199 if (fname == NULL || *fname == NUL) /* safety check */
3200 return FAIL;
Bram Moolenaar70d60e92009-12-31 13:53:33 +00003201 if (buf->b_ml.ml_mfp == NULL)
3202 {
3203 /* This can happen during startup when there is a stray "w" in the
3204 * vimrc file. */
3205 EMSG(_(e_emptybuf));
3206 return FAIL;
3207 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003208
3209 /*
3210 * Disallow writing from .exrc and .vimrc in current directory for
3211 * security reasons.
3212 */
3213 if (check_secure())
3214 return FAIL;
3215
3216 /* Avoid a crash for a long name. */
3217 if (STRLEN(fname) >= MAXPATHL)
3218 {
3219 EMSG(_(e_longname));
3220 return FAIL;
3221 }
3222
3223#ifdef FEAT_MBYTE
3224 /* must init bw_conv_buf and bw_iconv_fd before jumping to "fail" */
3225 write_info.bw_conv_buf = NULL;
3226 write_info.bw_conv_error = FALSE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003227 write_info.bw_conv_error_lnum = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003228 write_info.bw_restlen = 0;
3229# ifdef USE_ICONV
3230 write_info.bw_iconv_fd = (iconv_t)-1;
3231# endif
3232#endif
3233
Bram Moolenaardf177f62005-02-22 08:39:57 +00003234 /* After writing a file changedtick changes but we don't want to display
3235 * the line. */
3236 ex_no_reprint = TRUE;
3237
Bram Moolenaar071d4272004-06-13 20:20:40 +00003238 /*
3239 * If there is no file name yet, use the one for the written file.
3240 * BF_NOTEDITED is set to reflect this (in case the write fails).
3241 * Don't do this when the write is for a filter command.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003242 * Don't do this when appending.
3243 * Only do this when 'cpoptions' contains the 'F' flag.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003244 */
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003245 if (buf->b_ffname == NULL
3246 && reset_changed
Bram Moolenaar071d4272004-06-13 20:20:40 +00003247 && whole
3248 && buf == curbuf
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00003249#ifdef FEAT_QUICKFIX
3250 && !bt_nofile(buf)
3251#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003252 && !filtering
Bram Moolenaar292ad192005-12-11 21:29:51 +00003253 && (!append || vim_strchr(p_cpo, CPO_FNAMEAPP) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003254 && vim_strchr(p_cpo, CPO_FNAMEW) != NULL)
3255 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003256 if (set_rw_fname(fname, sfname) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003257 return FAIL;
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003258 buf = curbuf; /* just in case autocmds made "buf" invalid */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003259 }
3260
3261 if (sfname == NULL)
3262 sfname = fname;
3263 /*
3264 * For Unix: Use the short file name whenever possible.
3265 * Avoids problems with networks and when directory names are changed.
3266 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
3267 * another directory, which we don't detect
3268 */
3269 ffname = fname; /* remember full fname */
3270#ifdef UNIX
3271 fname = sfname;
3272#endif
3273
3274 if (buf->b_ffname != NULL && fnamecmp(ffname, buf->b_ffname) == 0)
3275 overwriting = TRUE;
3276 else
3277 overwriting = FALSE;
3278
3279 if (exiting)
3280 settmode(TMODE_COOK); /* when exiting allow typahead now */
3281
3282 ++no_wait_return; /* don't wait for return yet */
3283
3284 /*
3285 * Set '[ and '] marks to the lines to be written.
3286 */
3287 buf->b_op_start.lnum = start;
3288 buf->b_op_start.col = 0;
3289 buf->b_op_end.lnum = end;
3290 buf->b_op_end.col = 0;
3291
3292#ifdef FEAT_AUTOCMD
3293 {
3294 aco_save_T aco;
3295 int buf_ffname = FALSE;
3296 int buf_sfname = FALSE;
3297 int buf_fname_f = FALSE;
3298 int buf_fname_s = FALSE;
3299 int did_cmd = FALSE;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003300 int nofile_err = FALSE;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003301 int empty_memline = (buf->b_ml.ml_mfp == NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003302
3303 /*
3304 * Apply PRE aucocommands.
3305 * Set curbuf to the buffer to be written.
3306 * Careful: The autocommands may call buf_write() recursively!
3307 */
3308 if (ffname == buf->b_ffname)
3309 buf_ffname = TRUE;
3310 if (sfname == buf->b_sfname)
3311 buf_sfname = TRUE;
3312 if (fname == buf->b_ffname)
3313 buf_fname_f = TRUE;
3314 if (fname == buf->b_sfname)
3315 buf_fname_s = TRUE;
3316
3317 /* set curwin/curbuf to buf and save a few things */
3318 aucmd_prepbuf(&aco, buf);
3319
3320 if (append)
3321 {
3322 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD,
3323 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003324 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003325#ifdef FEAT_QUICKFIX
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00003326 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003327 nofile_err = TRUE;
3328 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003329#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003330 apply_autocmds_exarg(EVENT_FILEAPPENDPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003331 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003332 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003333 }
3334 else if (filtering)
3335 {
3336 apply_autocmds_exarg(EVENT_FILTERWRITEPRE,
3337 NULL, sfname, FALSE, curbuf, eap);
3338 }
3339 else if (reset_changed && whole)
3340 {
3341 if (!(did_cmd = apply_autocmds_exarg(EVENT_BUFWRITECMD,
3342 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003343 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003344#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003345 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003346 nofile_err = TRUE;
3347 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003348#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003349 apply_autocmds_exarg(EVENT_BUFWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003350 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003351 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003352 }
3353 else
3354 {
3355 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD,
3356 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003357 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003358#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003359 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003360 nofile_err = TRUE;
3361 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003362#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003363 apply_autocmds_exarg(EVENT_FILEWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003364 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003365 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003366 }
3367
3368 /* restore curwin/curbuf and a few other things */
3369 aucmd_restbuf(&aco);
3370
3371 /*
3372 * In three situations we return here and don't write the file:
3373 * 1. the autocommands deleted or unloaded the buffer.
3374 * 2. The autocommands abort script processing.
3375 * 3. If one of the "Cmd" autocommands was executed.
3376 */
3377 if (!buf_valid(buf))
3378 buf = NULL;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003379 if (buf == NULL || (buf->b_ml.ml_mfp == NULL && !empty_memline)
Bram Moolenaar1e015462005-09-25 22:16:38 +00003380 || did_cmd || nofile_err
3381#ifdef FEAT_EVAL
3382 || aborting()
3383#endif
3384 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003385 {
3386 --no_wait_return;
3387 msg_scroll = msg_save;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003388 if (nofile_err)
3389 EMSG(_("E676: No matching autocommands for acwrite buffer"));
3390
Bram Moolenaar1e015462005-09-25 22:16:38 +00003391 if (nofile_err
3392#ifdef FEAT_EVAL
3393 || aborting()
3394#endif
3395 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003396 /* An aborting error, interrupt or exception in the
3397 * autocommands. */
3398 return FAIL;
3399 if (did_cmd)
3400 {
3401 if (buf == NULL)
3402 /* The buffer was deleted. We assume it was written
3403 * (can't retry anyway). */
3404 return OK;
3405 if (overwriting)
3406 {
3407 /* Assume the buffer was written, update the timestamp. */
3408 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00003409 if (append)
3410 buf->b_flags &= ~BF_NEW;
3411 else
3412 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003413 }
Bram Moolenaar292ad192005-12-11 21:29:51 +00003414 if (reset_changed && buf->b_changed && !append
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003415 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003416 /* Buffer still changed, the autocommands didn't work
3417 * properly. */
3418 return FAIL;
3419 return OK;
3420 }
3421#ifdef FEAT_EVAL
3422 if (!aborting())
3423#endif
3424 EMSG(_("E203: Autocommands deleted or unloaded buffer to be written"));
3425 return FAIL;
3426 }
3427
3428 /*
3429 * The autocommands may have changed the number of lines in the file.
3430 * When writing the whole file, adjust the end.
3431 * When writing part of the file, assume that the autocommands only
3432 * changed the number of lines that are to be written (tricky!).
3433 */
3434 if (buf->b_ml.ml_line_count != old_line_count)
3435 {
3436 if (whole) /* write all */
3437 end = buf->b_ml.ml_line_count;
3438 else if (buf->b_ml.ml_line_count > old_line_count) /* more lines */
3439 end += buf->b_ml.ml_line_count - old_line_count;
3440 else /* less lines */
3441 {
3442 end -= old_line_count - buf->b_ml.ml_line_count;
3443 if (end < start)
3444 {
3445 --no_wait_return;
3446 msg_scroll = msg_save;
3447 EMSG(_("E204: Autocommand changed number of lines in unexpected way"));
3448 return FAIL;
3449 }
3450 }
3451 }
3452
3453 /*
3454 * The autocommands may have changed the name of the buffer, which may
3455 * be kept in fname, ffname and sfname.
3456 */
3457 if (buf_ffname)
3458 ffname = buf->b_ffname;
3459 if (buf_sfname)
3460 sfname = buf->b_sfname;
3461 if (buf_fname_f)
3462 fname = buf->b_ffname;
3463 if (buf_fname_s)
3464 fname = buf->b_sfname;
3465 }
3466#endif
3467
3468#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003469 if (netbeans_active() && isNetbeansBuffer(buf))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003470 {
3471 if (whole)
3472 {
3473 /*
3474 * b_changed can be 0 after an undo, but we still need to write
3475 * the buffer to NetBeans.
3476 */
3477 if (buf->b_changed || isNetbeansModified(buf))
3478 {
Bram Moolenaar009b2592004-10-24 19:18:58 +00003479 --no_wait_return; /* may wait for return now */
3480 msg_scroll = msg_save;
3481 netbeans_save_buffer(buf); /* no error checking... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003482 return retval;
3483 }
3484 else
3485 {
3486 errnum = (char_u *)"E656: ";
Bram Moolenaared0e7452008-06-27 19:17:34 +00003487 errmsg = (char_u *)_("NetBeans disallows writes of unmodified buffers");
Bram Moolenaar071d4272004-06-13 20:20:40 +00003488 buffer = NULL;
3489 goto fail;
3490 }
3491 }
3492 else
3493 {
3494 errnum = (char_u *)"E657: ";
3495 errmsg = (char_u *)_("Partial writes disallowed for NetBeans buffers");
3496 buffer = NULL;
3497 goto fail;
3498 }
3499 }
3500#endif
3501
3502 if (shortmess(SHM_OVER) && !exiting)
3503 msg_scroll = FALSE; /* overwrite previous file message */
3504 else
3505 msg_scroll = TRUE; /* don't overwrite previous file message */
3506 if (!filtering)
3507 filemess(buf,
3508#ifndef UNIX
3509 sfname,
3510#else
3511 fname,
3512#endif
3513 (char_u *)"", 0); /* show that we are busy */
3514 msg_scroll = FALSE; /* always overwrite the file message now */
3515
3516 buffer = alloc(BUFSIZE);
3517 if (buffer == NULL) /* can't allocate big buffer, use small
3518 * one (to be able to write when out of
3519 * memory) */
3520 {
3521 buffer = smallbuf;
3522 bufsize = SMBUFSIZE;
3523 }
3524 else
3525 bufsize = BUFSIZE;
3526
3527 /*
3528 * Get information about original file (if there is one).
3529 */
3530#if defined(UNIX) && !defined(ARCHIE)
Bram Moolenaar6f192452007-11-08 19:49:02 +00003531 st_old.st_dev = 0;
3532 st_old.st_ino = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003533 perm = -1;
3534 if (mch_stat((char *)fname, &st_old) < 0)
3535 newfile = TRUE;
3536 else
3537 {
3538 perm = st_old.st_mode;
3539 if (!S_ISREG(st_old.st_mode)) /* not a file */
3540 {
3541 if (S_ISDIR(st_old.st_mode))
3542 {
3543 errnum = (char_u *)"E502: ";
3544 errmsg = (char_u *)_("is a directory");
3545 goto fail;
3546 }
3547 if (mch_nodetype(fname) != NODE_WRITABLE)
3548 {
3549 errnum = (char_u *)"E503: ";
3550 errmsg = (char_u *)_("is not a file or writable device");
3551 goto fail;
3552 }
3553 /* It's a device of some kind (or a fifo) which we can write to
3554 * but for which we can't make a backup. */
3555 device = TRUE;
3556 newfile = TRUE;
3557 perm = -1;
3558 }
3559 }
3560#else /* !UNIX */
3561 /*
3562 * Check for a writable device name.
3563 */
3564 c = mch_nodetype(fname);
3565 if (c == NODE_OTHER)
3566 {
3567 errnum = (char_u *)"E503: ";
3568 errmsg = (char_u *)_("is not a file or writable device");
3569 goto fail;
3570 }
3571 if (c == NODE_WRITABLE)
3572 {
Bram Moolenaar043545e2006-10-10 16:44:07 +00003573# if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3574 /* MS-Windows allows opening a device, but we will probably get stuck
3575 * trying to write to it. */
3576 if (!p_odev)
3577 {
3578 errnum = (char_u *)"E796: ";
3579 errmsg = (char_u *)_("writing to device disabled with 'opendevice' option");
3580 goto fail;
3581 }
3582# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003583 device = TRUE;
3584 newfile = TRUE;
3585 perm = -1;
3586 }
3587 else
3588 {
3589 perm = mch_getperm(fname);
3590 if (perm < 0)
3591 newfile = TRUE;
3592 else if (mch_isdir(fname))
3593 {
3594 errnum = (char_u *)"E502: ";
3595 errmsg = (char_u *)_("is a directory");
3596 goto fail;
3597 }
3598 if (overwriting)
3599 (void)mch_stat((char *)fname, &st_old);
3600 }
3601#endif /* !UNIX */
3602
3603 if (!device && !newfile)
3604 {
3605 /*
3606 * Check if the file is really writable (when renaming the file to
3607 * make a backup we won't discover it later).
3608 */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003609 file_readonly = check_file_readonly(fname, (int)perm);
3610
Bram Moolenaar071d4272004-06-13 20:20:40 +00003611 if (!forceit && file_readonly)
3612 {
3613 if (vim_strchr(p_cpo, CPO_FWRITE) != NULL)
3614 {
3615 errnum = (char_u *)"E504: ";
3616 errmsg = (char_u *)_(err_readonly);
3617 }
3618 else
3619 {
3620 errnum = (char_u *)"E505: ";
3621 errmsg = (char_u *)_("is read-only (add ! to override)");
3622 }
3623 goto fail;
3624 }
3625
3626 /*
3627 * Check if the timestamp hasn't changed since reading the file.
3628 */
3629 if (overwriting)
3630 {
3631 retval = check_mtime(buf, &st_old);
3632 if (retval == FAIL)
3633 goto fail;
3634 }
3635 }
3636
3637#ifdef HAVE_ACL
3638 /*
3639 * For systems that support ACL: get the ACL from the original file.
3640 */
3641 if (!newfile)
3642 acl = mch_get_acl(fname);
3643#endif
3644
3645 /*
3646 * If 'backupskip' is not empty, don't make a backup for some files.
3647 */
3648 dobackup = (p_wb || p_bk || *p_pm != NUL);
3649#ifdef FEAT_WILDIGN
3650 if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname))
3651 dobackup = FALSE;
3652#endif
3653
3654 /*
3655 * Save the value of got_int and reset it. We don't want a previous
3656 * interruption cancel writing, only hitting CTRL-C while writing should
3657 * abort it.
3658 */
3659 prev_got_int = got_int;
3660 got_int = FALSE;
3661
3662 /* Mark the buffer as 'being saved' to prevent changed buffer warnings */
3663 buf->b_saving = TRUE;
3664
3665 /*
3666 * If we are not appending or filtering, the file exists, and the
3667 * 'writebackup', 'backup' or 'patchmode' option is set, need a backup.
3668 * When 'patchmode' is set also make a backup when appending.
3669 *
3670 * Do not make any backup, if 'writebackup' and 'backup' are both switched
3671 * off. This helps when editing large files on almost-full disks.
3672 */
3673 if (!(append && *p_pm == NUL) && !filtering && perm >= 0 && dobackup)
3674 {
3675#if defined(UNIX) || defined(WIN32)
3676 struct stat st;
3677#endif
3678
3679 if ((bkc_flags & BKC_YES) || append) /* "yes" */
3680 backup_copy = TRUE;
3681#if defined(UNIX) || defined(WIN32)
3682 else if ((bkc_flags & BKC_AUTO)) /* "auto" */
3683 {
3684 int i;
3685
3686# ifdef UNIX
3687 /*
3688 * Don't rename the file when:
3689 * - it's a hard link
3690 * - it's a symbolic link
3691 * - we don't have write permission in the directory
3692 * - we can't set the owner/group of the new file
3693 */
3694 if (st_old.st_nlink > 1
3695 || mch_lstat((char *)fname, &st) < 0
3696 || st.st_dev != st_old.st_dev
Bram Moolenaara5792f52005-11-23 21:25:05 +00003697 || st.st_ino != st_old.st_ino
3698# ifndef HAVE_FCHOWN
3699 || st.st_uid != st_old.st_uid
3700 || st.st_gid != st_old.st_gid
3701# endif
3702 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003703 backup_copy = TRUE;
3704 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003705# else
3706# ifdef WIN32
3707 /* On NTFS file systems hard links are possible. */
3708 if (mch_is_linked(fname))
3709 backup_copy = TRUE;
3710 else
3711# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003712# endif
3713 {
3714 /*
3715 * Check if we can create a file and set the owner/group to
3716 * the ones from the original file.
3717 * First find a file name that doesn't exist yet (use some
3718 * arbitrary numbers).
3719 */
3720 STRCPY(IObuff, fname);
3721 for (i = 4913; ; i += 123)
3722 {
3723 sprintf((char *)gettail(IObuff), "%d", i);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003724 if (mch_lstat((char *)IObuff, &st) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003725 break;
3726 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00003727 fd = mch_open((char *)IObuff,
3728 O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003729 if (fd < 0) /* can't write in directory */
3730 backup_copy = TRUE;
3731 else
3732 {
3733# ifdef UNIX
Bram Moolenaara5792f52005-11-23 21:25:05 +00003734# ifdef HAVE_FCHOWN
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00003735 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003736# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003737 if (mch_stat((char *)IObuff, &st) < 0
3738 || st.st_uid != st_old.st_uid
3739 || st.st_gid != st_old.st_gid
Bram Moolenaar78a15312009-05-15 19:33:18 +00003740 || (long)st.st_mode != perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003741 backup_copy = TRUE;
3742# endif
Bram Moolenaar98358622005-11-28 22:58:23 +00003743 /* Close the file before removing it, on MS-Windows we
3744 * can't delete an open file. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003745 close(fd);
Bram Moolenaar98358622005-11-28 22:58:23 +00003746 mch_remove(IObuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003747 }
3748 }
3749 }
3750
3751# ifdef UNIX
3752 /*
3753 * Break symlinks and/or hardlinks if we've been asked to.
3754 */
3755 if ((bkc_flags & BKC_BREAKSYMLINK) || (bkc_flags & BKC_BREAKHARDLINK))
3756 {
3757 int lstat_res;
3758
3759 lstat_res = mch_lstat((char *)fname, &st);
3760
3761 /* Symlinks. */
3762 if ((bkc_flags & BKC_BREAKSYMLINK)
3763 && lstat_res == 0
3764 && st.st_ino != st_old.st_ino)
3765 backup_copy = FALSE;
3766
3767 /* Hardlinks. */
3768 if ((bkc_flags & BKC_BREAKHARDLINK)
3769 && st_old.st_nlink > 1
3770 && (lstat_res != 0 || st.st_ino == st_old.st_ino))
3771 backup_copy = FALSE;
3772 }
3773#endif
3774
3775#endif
3776
3777 /* make sure we have a valid backup extension to use */
3778 if (*p_bex == NUL)
3779 {
3780#ifdef RISCOS
3781 backup_ext = (char_u *)"/bak";
3782#else
3783 backup_ext = (char_u *)".bak";
3784#endif
3785 }
3786 else
3787 backup_ext = p_bex;
3788
3789 if (backup_copy
3790 && (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) >= 0)
3791 {
3792 int bfd;
3793 char_u *copybuf, *wp;
3794 int some_error = FALSE;
3795 struct stat st_new;
3796 char_u *dirp;
3797 char_u *rootname;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003798#if defined(UNIX) && !defined(SHORT_FNAME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003799 int did_set_shortname;
3800#endif
3801
3802 copybuf = alloc(BUFSIZE + 1);
3803 if (copybuf == NULL)
3804 {
3805 some_error = TRUE; /* out of memory */
3806 goto nobackup;
3807 }
3808
3809 /*
3810 * Try to make the backup in each directory in the 'bdir' option.
3811 *
3812 * Unix semantics has it, that we may have a writable file,
3813 * that cannot be recreated with a simple open(..., O_CREAT, ) e.g:
3814 * - the directory is not writable,
3815 * - the file may be a symbolic link,
3816 * - the file may belong to another user/group, etc.
3817 *
3818 * For these reasons, the existing writable file must be truncated
3819 * and reused. Creation of a backup COPY will be attempted.
3820 */
3821 dirp = p_bdir;
3822 while (*dirp)
3823 {
3824#ifdef UNIX
3825 st_new.st_ino = 0;
3826 st_new.st_dev = 0;
3827 st_new.st_gid = 0;
3828#endif
3829
3830 /*
3831 * Isolate one directory name, using an entry in 'bdir'.
3832 */
3833 (void)copy_option_part(&dirp, copybuf, BUFSIZE, ",");
3834 rootname = get_file_in_dir(fname, copybuf);
3835 if (rootname == NULL)
3836 {
3837 some_error = TRUE; /* out of memory */
3838 goto nobackup;
3839 }
3840
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003841#if defined(UNIX) && !defined(SHORT_FNAME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003842 did_set_shortname = FALSE;
3843#endif
3844
3845 /*
3846 * May try twice if 'shortname' not set.
3847 */
3848 for (;;)
3849 {
3850 /*
3851 * Make backup file name.
3852 */
3853 backup = buf_modname(
3854#ifdef SHORT_FNAME
3855 TRUE,
3856#else
3857 (buf->b_p_sn || buf->b_shortname),
3858#endif
3859 rootname, backup_ext, FALSE);
3860 if (backup == NULL)
3861 {
3862 vim_free(rootname);
3863 some_error = TRUE; /* out of memory */
3864 goto nobackup;
3865 }
3866
3867 /*
3868 * Check if backup file already exists.
3869 */
3870 if (mch_stat((char *)backup, &st_new) >= 0)
3871 {
3872#ifdef UNIX
3873 /*
3874 * Check if backup file is same as original file.
3875 * May happen when modname() gave the same file back.
3876 * E.g. silly link, or file name-length reached.
3877 * If we don't check here, we either ruin the file
3878 * when copying or erase it after writing. jw.
3879 */
3880 if (st_new.st_dev == st_old.st_dev
3881 && st_new.st_ino == st_old.st_ino)
3882 {
3883 vim_free(backup);
3884 backup = NULL; /* no backup file to delete */
3885# ifndef SHORT_FNAME
3886 /*
3887 * may try again with 'shortname' set
3888 */
3889 if (!(buf->b_shortname || buf->b_p_sn))
3890 {
3891 buf->b_shortname = TRUE;
3892 did_set_shortname = TRUE;
3893 continue;
3894 }
3895 /* setting shortname didn't help */
3896 if (did_set_shortname)
3897 buf->b_shortname = FALSE;
3898# endif
3899 break;
3900 }
3901#endif
3902
3903 /*
3904 * If we are not going to keep the backup file, don't
3905 * delete an existing one, try to use another name.
3906 * Change one character, just before the extension.
3907 */
3908 if (!p_bk)
3909 {
3910 wp = backup + STRLEN(backup) - 1
3911 - STRLEN(backup_ext);
3912 if (wp < backup) /* empty file name ??? */
3913 wp = backup;
3914 *wp = 'z';
3915 while (*wp > 'a'
3916 && mch_stat((char *)backup, &st_new) >= 0)
3917 --*wp;
3918 /* They all exist??? Must be something wrong. */
3919 if (*wp == 'a')
3920 {
3921 vim_free(backup);
3922 backup = NULL;
3923 }
3924 }
3925 }
3926 break;
3927 }
3928 vim_free(rootname);
3929
3930 /*
3931 * Try to create the backup file
3932 */
3933 if (backup != NULL)
3934 {
3935 /* remove old backup, if present */
3936 mch_remove(backup);
3937 /* Open with O_EXCL to avoid the file being created while
3938 * we were sleeping (symlink hacker attack?) */
3939 bfd = mch_open((char *)backup,
Bram Moolenaara5792f52005-11-23 21:25:05 +00003940 O_WRONLY|O_CREAT|O_EXTRA|O_EXCL|O_NOFOLLOW,
3941 perm & 0777);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003942 if (bfd < 0)
3943 {
3944 vim_free(backup);
3945 backup = NULL;
3946 }
3947 else
3948 {
3949 /* set file protection same as original file, but
3950 * strip s-bit */
3951 (void)mch_setperm(backup, perm & 0777);
3952
3953#ifdef UNIX
3954 /*
3955 * Try to set the group of the backup same as the
3956 * original file. If this fails, set the protection
3957 * bits for the group same as the protection bits for
3958 * others.
3959 */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003960 if (st_new.st_gid != st_old.st_gid
Bram Moolenaar071d4272004-06-13 20:20:40 +00003961# ifdef HAVE_FCHOWN /* sequent-ptx lacks fchown() */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003962 && fchown(bfd, (uid_t)-1, st_old.st_gid) != 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00003963# endif
3964 )
3965 mch_setperm(backup,
3966 (perm & 0707) | ((perm & 07) << 3));
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00003967# ifdef HAVE_SELINUX
3968 mch_copy_sec(fname, backup);
3969# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003970#endif
3971
3972 /*
3973 * copy the file.
3974 */
3975 write_info.bw_fd = bfd;
3976 write_info.bw_buf = copybuf;
3977#ifdef HAS_BW_FLAGS
3978 write_info.bw_flags = FIO_NOCONVERT;
3979#endif
3980 while ((write_info.bw_len = vim_read(fd, copybuf,
3981 BUFSIZE)) > 0)
3982 {
3983 if (buf_write_bytes(&write_info) == FAIL)
3984 {
3985 errmsg = (char_u *)_("E506: Can't write to backup file (add ! to override)");
3986 break;
3987 }
3988 ui_breakcheck();
3989 if (got_int)
3990 {
3991 errmsg = (char_u *)_(e_interr);
3992 break;
3993 }
3994 }
3995
3996 if (close(bfd) < 0 && errmsg == NULL)
3997 errmsg = (char_u *)_("E507: Close error for backup file (add ! to override)");
3998 if (write_info.bw_len < 0)
3999 errmsg = (char_u *)_("E508: Can't read file for backup (add ! to override)");
4000#ifdef UNIX
4001 set_file_time(backup, st_old.st_atime, st_old.st_mtime);
4002#endif
4003#ifdef HAVE_ACL
4004 mch_set_acl(backup, acl);
4005#endif
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004006#ifdef HAVE_SELINUX
4007 mch_copy_sec(fname, backup);
4008#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004009 break;
4010 }
4011 }
4012 }
4013 nobackup:
4014 close(fd); /* ignore errors for closing read file */
4015 vim_free(copybuf);
4016
4017 if (backup == NULL && errmsg == NULL)
4018 errmsg = (char_u *)_("E509: Cannot create backup file (add ! to override)");
4019 /* ignore errors when forceit is TRUE */
4020 if ((some_error || errmsg != NULL) && !forceit)
4021 {
4022 retval = FAIL;
4023 goto fail;
4024 }
4025 errmsg = NULL;
4026 }
4027 else
4028 {
4029 char_u *dirp;
4030 char_u *p;
4031 char_u *rootname;
4032
4033 /*
4034 * Make a backup by renaming the original file.
4035 */
4036 /*
4037 * If 'cpoptions' includes the "W" flag, we don't want to
4038 * overwrite a read-only file. But rename may be possible
4039 * anyway, thus we need an extra check here.
4040 */
4041 if (file_readonly && vim_strchr(p_cpo, CPO_FWRITE) != NULL)
4042 {
4043 errnum = (char_u *)"E504: ";
4044 errmsg = (char_u *)_(err_readonly);
4045 goto fail;
4046 }
4047
4048 /*
4049 *
4050 * Form the backup file name - change path/fo.o.h to
4051 * path/fo.o.h.bak Try all directories in 'backupdir', first one
4052 * that works is used.
4053 */
4054 dirp = p_bdir;
4055 while (*dirp)
4056 {
4057 /*
4058 * Isolate one directory name and make the backup file name.
4059 */
4060 (void)copy_option_part(&dirp, IObuff, IOSIZE, ",");
4061 rootname = get_file_in_dir(fname, IObuff);
4062 if (rootname == NULL)
4063 backup = NULL;
4064 else
4065 {
4066 backup = buf_modname(
4067#ifdef SHORT_FNAME
4068 TRUE,
4069#else
4070 (buf->b_p_sn || buf->b_shortname),
4071#endif
4072 rootname, backup_ext, FALSE);
4073 vim_free(rootname);
4074 }
4075
4076 if (backup != NULL)
4077 {
4078 /*
4079 * If we are not going to keep the backup file, don't
4080 * delete an existing one, try to use another name.
4081 * Change one character, just before the extension.
4082 */
4083 if (!p_bk && mch_getperm(backup) >= 0)
4084 {
4085 p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext);
4086 if (p < backup) /* empty file name ??? */
4087 p = backup;
4088 *p = 'z';
4089 while (*p > 'a' && mch_getperm(backup) >= 0)
4090 --*p;
4091 /* They all exist??? Must be something wrong! */
4092 if (*p == 'a')
4093 {
4094 vim_free(backup);
4095 backup = NULL;
4096 }
4097 }
4098 }
4099 if (backup != NULL)
4100 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004101 /*
Bram Moolenaarbfd8fc02005-09-20 23:22:24 +00004102 * Delete any existing backup and move the current version
4103 * to the backup. For safety, we don't remove the backup
4104 * until the write has finished successfully. And if the
4105 * 'backup' option is set, leave it around.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004106 */
4107 /*
4108 * If the renaming of the original file to the backup file
4109 * works, quit here.
4110 */
4111 if (vim_rename(fname, backup) == 0)
4112 break;
4113
4114 vim_free(backup); /* don't do the rename below */
4115 backup = NULL;
4116 }
4117 }
4118 if (backup == NULL && !forceit)
4119 {
4120 errmsg = (char_u *)_("E510: Can't make backup file (add ! to override)");
4121 goto fail;
4122 }
4123 }
4124 }
4125
4126#if defined(UNIX) && !defined(ARCHIE)
4127 /* When using ":w!" and the file was read-only: make it writable */
4128 if (forceit && perm >= 0 && !(perm & 0200) && st_old.st_uid == getuid()
4129 && vim_strchr(p_cpo, CPO_FWRITE) == NULL)
4130 {
4131 perm |= 0200;
4132 (void)mch_setperm(fname, perm);
4133 made_writable = TRUE;
4134 }
4135#endif
4136
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004137 /* When using ":w!" and writing to the current file, 'readonly' makes no
Bram Moolenaar4399ef42005-02-12 14:29:27 +00004138 * sense, reset it, unless 'Z' appears in 'cpoptions'. */
4139 if (forceit && overwriting && vim_strchr(p_cpo, CPO_KEEPRO) == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004140 {
4141 buf->b_p_ro = FALSE;
4142#ifdef FEAT_TITLE
4143 need_maketitle = TRUE; /* set window title later */
4144#endif
4145#ifdef FEAT_WINDOWS
4146 status_redraw_all(); /* redraw status lines later */
4147#endif
4148 }
4149
4150 if (end > buf->b_ml.ml_line_count)
4151 end = buf->b_ml.ml_line_count;
4152 if (buf->b_ml.ml_flags & ML_EMPTY)
4153 start = end + 1;
4154
4155 /*
4156 * If the original file is being overwritten, there is a small chance that
4157 * we crash in the middle of writing. Therefore the file is preserved now.
4158 * This makes all block numbers positive so that recovery does not need
4159 * the original file.
4160 * Don't do this if there is a backup file and we are exiting.
4161 */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004162 if (reset_changed && !newfile && overwriting
Bram Moolenaar071d4272004-06-13 20:20:40 +00004163 && !(exiting && backup != NULL))
4164 {
4165 ml_preserve(buf, FALSE);
4166 if (got_int)
4167 {
4168 errmsg = (char_u *)_(e_interr);
4169 goto restore_backup;
4170 }
4171 }
4172
4173#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
4174 /*
4175 * Before risking to lose the original file verify if there's
4176 * a resource fork to preserve, and if cannot be done warn
4177 * the users. This happens when overwriting without backups.
4178 */
4179 if (backup == NULL && overwriting && !append)
4180 if (mch_has_resource_fork(fname))
4181 {
4182 errmsg = (char_u *)_("E460: The resource fork would be lost (add ! to override)");
4183 goto restore_backup;
4184 }
4185#endif
4186
4187#ifdef VMS
4188 vms_remove_version(fname); /* remove version */
4189#endif
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00004190 /* Default: write the file directly. May write to a temp file for
Bram Moolenaar071d4272004-06-13 20:20:40 +00004191 * multi-byte conversion. */
4192 wfname = fname;
4193
4194#ifdef FEAT_MBYTE
4195 /* Check for forced 'fileencoding' from "++opt=val" argument. */
4196 if (eap != NULL && eap->force_enc != 0)
4197 {
4198 fenc = eap->cmd + eap->force_enc;
4199 fenc = enc_canonize(fenc);
4200 fenc_tofree = fenc;
4201 }
4202 else
4203 fenc = buf->b_p_fenc;
4204
4205 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004206 * Check if the file needs to be converted.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004207 */
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004208 converted = need_conversion(fenc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004209
4210 /*
4211 * Check if UTF-8 to UCS-2/4 or Latin1 conversion needs to be done. Or
4212 * Latin1 to Unicode conversion. This is handled in buf_write_bytes().
4213 * Prepare the flags for it and allocate bw_conv_buf when needed.
4214 */
4215 if (converted && (enc_utf8 || STRCMP(p_enc, "latin1") == 0))
4216 {
4217 wb_flags = get_fio_flags(fenc);
4218 if (wb_flags & (FIO_UCS2 | FIO_UCS4 | FIO_UTF16 | FIO_UTF8))
4219 {
4220 /* Need to allocate a buffer to translate into. */
4221 if (wb_flags & (FIO_UCS2 | FIO_UTF16 | FIO_UTF8))
4222 write_info.bw_conv_buflen = bufsize * 2;
4223 else /* FIO_UCS4 */
4224 write_info.bw_conv_buflen = bufsize * 4;
4225 write_info.bw_conv_buf
4226 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4227 if (write_info.bw_conv_buf == NULL)
4228 end = 0;
4229 }
4230 }
4231
4232# ifdef WIN3264
4233 if (converted && wb_flags == 0 && (wb_flags = get_win_fio_flags(fenc)) != 0)
4234 {
4235 /* Convert UTF-8 -> UCS-2 and UCS-2 -> DBCS. Worst-case * 4: */
4236 write_info.bw_conv_buflen = bufsize * 4;
4237 write_info.bw_conv_buf
4238 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4239 if (write_info.bw_conv_buf == NULL)
4240 end = 0;
4241 }
4242# endif
4243
4244# ifdef MACOS_X
4245 if (converted && wb_flags == 0 && (wb_flags = get_mac_fio_flags(fenc)) != 0)
4246 {
4247 write_info.bw_conv_buflen = bufsize * 3;
4248 write_info.bw_conv_buf
4249 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4250 if (write_info.bw_conv_buf == NULL)
4251 end = 0;
4252 }
4253# endif
4254
4255# if defined(FEAT_EVAL) || defined(USE_ICONV)
4256 if (converted && wb_flags == 0)
4257 {
4258# ifdef USE_ICONV
4259 /*
4260 * Use iconv() conversion when conversion is needed and it's not done
4261 * internally.
4262 */
4263 write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc,
4264 enc_utf8 ? (char_u *)"utf-8" : p_enc);
4265 if (write_info.bw_iconv_fd != (iconv_t)-1)
4266 {
4267 /* We're going to use iconv(), allocate a buffer to convert in. */
4268 write_info.bw_conv_buflen = bufsize * ICONV_MULT;
4269 write_info.bw_conv_buf
4270 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4271 if (write_info.bw_conv_buf == NULL)
4272 end = 0;
4273 write_info.bw_first = TRUE;
4274 }
4275# ifdef FEAT_EVAL
4276 else
4277# endif
4278# endif
4279
4280# ifdef FEAT_EVAL
4281 /*
4282 * When the file needs to be converted with 'charconvert' after
4283 * writing, write to a temp file instead and let the conversion
4284 * overwrite the original file.
4285 */
4286 if (*p_ccv != NUL)
4287 {
4288 wfname = vim_tempname('w');
4289 if (wfname == NULL) /* Can't write without a tempfile! */
4290 {
4291 errmsg = (char_u *)_("E214: Can't find temp file for writing");
4292 goto restore_backup;
4293 }
4294 }
4295# endif
4296 }
4297# endif
4298 if (converted && wb_flags == 0
4299# ifdef USE_ICONV
4300 && write_info.bw_iconv_fd == (iconv_t)-1
4301# endif
4302# ifdef FEAT_EVAL
4303 && wfname == fname
4304# endif
4305 )
4306 {
4307 if (!forceit)
4308 {
4309 errmsg = (char_u *)_("E213: Cannot convert (add ! to write without conversion)");
4310 goto restore_backup;
4311 }
4312 notconverted = TRUE;
4313 }
4314#endif
4315
4316 /*
4317 * Open the file "wfname" for writing.
4318 * We may try to open the file twice: If we can't write to the
4319 * file and forceit is TRUE we delete the existing file and try to create
4320 * a new one. If this still fails we may have lost the original file!
4321 * (this may happen when the user reached his quotum for number of files).
4322 * Appending will fail if the file does not exist and forceit is FALSE.
4323 */
4324 while ((fd = mch_open((char *)wfname, O_WRONLY | O_EXTRA | (append
4325 ? (forceit ? (O_APPEND | O_CREAT) : O_APPEND)
4326 : (O_CREAT | O_TRUNC))
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00004327 , perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004328 {
4329 /*
4330 * A forced write will try to create a new file if the old one is
4331 * still readonly. This may also happen when the directory is
4332 * read-only. In that case the mch_remove() will fail.
4333 */
4334 if (errmsg == NULL)
4335 {
4336#ifdef UNIX
4337 struct stat st;
4338
4339 /* Don't delete the file when it's a hard or symbolic link. */
4340 if ((!newfile && st_old.st_nlink > 1)
4341 || (mch_lstat((char *)fname, &st) == 0
4342 && (st.st_dev != st_old.st_dev
4343 || st.st_ino != st_old.st_ino)))
4344 errmsg = (char_u *)_("E166: Can't open linked file for writing");
4345 else
4346#endif
4347 {
4348 errmsg = (char_u *)_("E212: Can't open file for writing");
4349 if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL
4350 && perm >= 0)
4351 {
4352#ifdef UNIX
4353 /* we write to the file, thus it should be marked
4354 writable after all */
4355 if (!(perm & 0200))
4356 made_writable = TRUE;
4357 perm |= 0200;
4358 if (st_old.st_uid != getuid() || st_old.st_gid != getgid())
4359 perm &= 0777;
4360#endif
4361 if (!append) /* don't remove when appending */
4362 mch_remove(wfname);
4363 continue;
4364 }
4365 }
4366 }
4367
4368restore_backup:
4369 {
4370 struct stat st;
4371
4372 /*
4373 * If we failed to open the file, we don't need a backup. Throw it
4374 * away. If we moved or removed the original file try to put the
4375 * backup in its place.
4376 */
4377 if (backup != NULL && wfname == fname)
4378 {
4379 if (backup_copy)
4380 {
4381 /*
4382 * There is a small chance that we removed the original,
4383 * try to move the copy in its place.
4384 * This may not work if the vim_rename() fails.
4385 * In that case we leave the copy around.
4386 */
4387 /* If file does not exist, put the copy in its place */
4388 if (mch_stat((char *)fname, &st) < 0)
4389 vim_rename(backup, fname);
4390 /* if original file does exist throw away the copy */
4391 if (mch_stat((char *)fname, &st) >= 0)
4392 mch_remove(backup);
4393 }
4394 else
4395 {
4396 /* try to put the original file back */
4397 vim_rename(backup, fname);
4398 }
4399 }
4400
4401 /* if original file no longer exists give an extra warning */
4402 if (!newfile && mch_stat((char *)fname, &st) < 0)
4403 end = 0;
4404 }
4405
4406#ifdef FEAT_MBYTE
4407 if (wfname != fname)
4408 vim_free(wfname);
4409#endif
4410 goto fail;
4411 }
4412 errmsg = NULL;
4413
4414#if defined(MACOS_CLASSIC) || defined(WIN3264)
4415 /* TODO: Is it need for MACOS_X? (Dany) */
4416 /*
4417 * On macintosh copy the original files attributes (i.e. the backup)
Bram Moolenaar7263a772007-05-10 17:35:54 +00004418 * This is done in order to preserve the resource fork and the
4419 * Finder attribute (label, comments, custom icons, file creator)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004420 */
4421 if (backup != NULL && overwriting && !append)
4422 {
4423 if (backup_copy)
4424 (void)mch_copy_file_attribute(wfname, backup);
4425 else
4426 (void)mch_copy_file_attribute(backup, wfname);
4427 }
4428
4429 if (!overwriting && !append)
4430 {
4431 if (buf->b_ffname != NULL)
4432 (void)mch_copy_file_attribute(buf->b_ffname, wfname);
Bram Moolenaar7263a772007-05-10 17:35:54 +00004433 /* Should copy resource fork */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004434 }
4435#endif
4436
4437 write_info.bw_fd = fd;
4438
4439#ifdef FEAT_CRYPT
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004440 if (*buf->b_p_key != NUL && !filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004441 {
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02004442 char_u *header;
4443 int header_len;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004444
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02004445 header = prepare_crypt_write(buf, &header_len);
4446 if (header == NULL)
4447 end = 0;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004448 else
4449 {
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02004450 /* Write magic number, so that Vim knows that this file is
4451 * encrypted when reading it again. This also undergoes utf-8 to
4452 * ucs-2/4 conversion when needed. */
4453 write_info.bw_buf = header;
4454 write_info.bw_len = header_len;
4455 write_info.bw_flags = FIO_NOCONVERT;
4456 if (buf_write_bytes(&write_info) == FAIL)
4457 end = 0;
4458 wb_flags |= FIO_ENCRYPTED;
4459 vim_free(header);
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004460 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004461 }
4462#endif
4463
4464 write_info.bw_buf = buffer;
4465 nchars = 0;
4466
4467 /* use "++bin", "++nobin" or 'binary' */
4468 if (eap != NULL && eap->force_bin != 0)
4469 write_bin = (eap->force_bin == FORCE_BIN);
4470 else
4471 write_bin = buf->b_p_bin;
4472
4473#ifdef FEAT_MBYTE
4474 /*
4475 * The BOM is written just after the encryption magic number.
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004476 * Skip it when appending and the file already existed, the BOM only makes
4477 * sense at the start of the file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004478 */
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004479 if (buf->b_p_bomb && !write_bin && (!append || perm < 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004480 {
4481 write_info.bw_len = make_bom(buffer, fenc);
4482 if (write_info.bw_len > 0)
4483 {
4484 /* don't convert, do encryption */
4485 write_info.bw_flags = FIO_NOCONVERT | wb_flags;
4486 if (buf_write_bytes(&write_info) == FAIL)
4487 end = 0;
4488 else
4489 nchars += write_info.bw_len;
4490 }
4491 }
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004492 write_info.bw_start_lnum = start;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004493#endif
4494
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004495#ifdef FEAT_PERSISTENT_UNDO
4496 write_undo_file = (buf->b_p_udf && overwriting && !append
4497 && !filtering && reset_changed);
4498 if (write_undo_file)
4499 /* Prepare for computing the hash value of the text. */
4500 sha256_start(&sha_ctx);
4501#endif
4502
Bram Moolenaar071d4272004-06-13 20:20:40 +00004503 write_info.bw_len = bufsize;
4504#ifdef HAS_BW_FLAGS
4505 write_info.bw_flags = wb_flags;
4506#endif
4507 fileformat = get_fileformat_force(buf, eap);
4508 s = buffer;
4509 len = 0;
4510 for (lnum = start; lnum <= end; ++lnum)
4511 {
4512 /*
4513 * The next while loop is done once for each character written.
4514 * Keep it fast!
4515 */
4516 ptr = ml_get_buf(buf, lnum, FALSE) - 1;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004517#ifdef FEAT_PERSISTENT_UNDO
4518 if (write_undo_file)
Bram Moolenaar442b4222010-05-24 21:34:22 +02004519 sha256_update(&sha_ctx, ptr + 1, (UINT32_T)(STRLEN(ptr + 1) + 1));
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004520#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004521 while ((c = *++ptr) != NUL)
4522 {
4523 if (c == NL)
4524 *s = NUL; /* replace newlines with NULs */
4525 else if (c == CAR && fileformat == EOL_MAC)
4526 *s = NL; /* Mac: replace CRs with NLs */
4527 else
4528 *s = c;
4529 ++s;
4530 if (++len != bufsize)
4531 continue;
4532 if (buf_write_bytes(&write_info) == FAIL)
4533 {
4534 end = 0; /* write error: break loop */
4535 break;
4536 }
4537 nchars += bufsize;
4538 s = buffer;
4539 len = 0;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004540#ifdef FEAT_MBYTE
4541 write_info.bw_start_lnum = lnum;
4542#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004543 }
4544 /* write failed or last line has no EOL: stop here */
4545 if (end == 0
4546 || (lnum == end
4547 && write_bin
4548 && (lnum == write_no_eol_lnum
4549 || (lnum == buf->b_ml.ml_line_count && !buf->b_p_eol))))
4550 {
4551 ++lnum; /* written the line, count it */
4552 no_eol = TRUE;
4553 break;
4554 }
4555 if (fileformat == EOL_UNIX)
4556 *s++ = NL;
4557 else
4558 {
4559 *s++ = CAR; /* EOL_MAC or EOL_DOS: write CR */
4560 if (fileformat == EOL_DOS) /* write CR-NL */
4561 {
4562 if (++len == bufsize)
4563 {
4564 if (buf_write_bytes(&write_info) == FAIL)
4565 {
4566 end = 0; /* write error: break loop */
4567 break;
4568 }
4569 nchars += bufsize;
4570 s = buffer;
4571 len = 0;
4572 }
4573 *s++ = NL;
4574 }
4575 }
4576 if (++len == bufsize && end)
4577 {
4578 if (buf_write_bytes(&write_info) == FAIL)
4579 {
4580 end = 0; /* write error: break loop */
4581 break;
4582 }
4583 nchars += bufsize;
4584 s = buffer;
4585 len = 0;
4586
4587 ui_breakcheck();
4588 if (got_int)
4589 {
4590 end = 0; /* Interrupted, break loop */
4591 break;
4592 }
4593 }
4594#ifdef VMS
4595 /*
4596 * On VMS there is a problem: newlines get added when writing blocks
4597 * at a time. Fix it by writing a line at a time.
4598 * This is much slower!
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004599 * Explanation: VAX/DECC RTL insists that records in some RMS
4600 * structures end with a newline (carriage return) character, and if
4601 * they don't it adds one.
4602 * With other RMS structures it works perfect without this fix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004603 */
Bram Moolenaarb52e2602007-10-29 21:38:54 +00004604 if (buf->b_fab_rfm == FAB$C_VFC
4605 || ((buf->b_fab_rat & (FAB$M_FTN | FAB$M_CR)) != 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004606 {
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004607 int b2write;
4608
4609 buf->b_fab_mrs = (buf->b_fab_mrs == 0
4610 ? MIN(4096, bufsize)
4611 : MIN(buf->b_fab_mrs, bufsize));
4612
4613 b2write = len;
4614 while (b2write > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004615 {
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004616 write_info.bw_len = MIN(b2write, buf->b_fab_mrs);
4617 if (buf_write_bytes(&write_info) == FAIL)
4618 {
4619 end = 0;
4620 break;
4621 }
4622 b2write -= MIN(b2write, buf->b_fab_mrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004623 }
4624 write_info.bw_len = bufsize;
4625 nchars += len;
4626 s = buffer;
4627 len = 0;
4628 }
4629#endif
4630 }
4631 if (len > 0 && end > 0)
4632 {
4633 write_info.bw_len = len;
4634 if (buf_write_bytes(&write_info) == FAIL)
4635 end = 0; /* write error */
4636 nchars += len;
4637 }
4638
4639#if defined(UNIX) && defined(HAVE_FSYNC)
4640 /* On many journalling file systems there is a bug that causes both the
4641 * original and the backup file to be lost when halting the system right
4642 * after writing the file. That's because only the meta-data is
4643 * journalled. Syncing the file slows down the system, but assures it has
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004644 * been written to disk and we don't lose it.
4645 * For a device do try the fsync() but don't complain if it does not work
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00004646 * (could be a pipe).
4647 * If the 'fsync' option is FALSE, don't fsync(). Useful for laptops. */
4648 if (p_fs && fsync(fd) != 0 && !device)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004649 {
4650 errmsg = (char_u *)_("E667: Fsync failed");
4651 end = 0;
4652 }
4653#endif
4654
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004655#ifdef HAVE_SELINUX
4656 /* Probably need to set the security context. */
4657 if (!backup_copy)
4658 mch_copy_sec(backup, wfname);
4659#endif
4660
Bram Moolenaara5792f52005-11-23 21:25:05 +00004661#ifdef UNIX
4662 /* When creating a new file, set its owner/group to that of the original
4663 * file. Get the new device and inode number. */
4664 if (backup != NULL && !backup_copy)
4665 {
4666# ifdef HAVE_FCHOWN
4667 struct stat st;
4668
4669 /* don't change the owner when it's already OK, some systems remove
4670 * permission or ACL stuff */
4671 if (mch_stat((char *)wfname, &st) < 0
4672 || st.st_uid != st_old.st_uid
4673 || st.st_gid != st_old.st_gid)
4674 {
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004675 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004676 if (perm >= 0) /* set permission again, may have changed */
4677 (void)mch_setperm(wfname, perm);
4678 }
4679# endif
4680 buf_setino(buf);
4681 }
Bram Moolenaarf1726cc2009-05-13 18:48:16 +00004682 else if (!buf->b_dev_valid)
Bram Moolenaar8fa04452005-12-23 22:13:51 +00004683 /* Set the inode when creating a new file. */
4684 buf_setino(buf);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004685#endif
4686
Bram Moolenaar071d4272004-06-13 20:20:40 +00004687 if (close(fd) != 0)
4688 {
4689 errmsg = (char_u *)_("E512: Close failed");
4690 end = 0;
4691 }
4692
4693#ifdef UNIX
4694 if (made_writable)
4695 perm &= ~0200; /* reset 'w' bit for security reasons */
4696#endif
4697 if (perm >= 0) /* set perm. of new file same as old file */
4698 (void)mch_setperm(wfname, perm);
4699#ifdef RISCOS
4700 if (!append && !filtering)
4701 /* Set the filetype after writing the file. */
4702 mch_set_filetype(wfname, buf->b_p_oft);
4703#endif
4704#ifdef HAVE_ACL
4705 /* Probably need to set the ACL before changing the user (can't set the
4706 * ACL on a file the user doesn't own). */
4707 if (!backup_copy)
4708 mch_set_acl(wfname, acl);
4709#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004710#ifdef FEAT_CRYPT
4711 if (wb_flags & FIO_ENCRYPTED)
4712 crypt_pop_state();
4713#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004714
Bram Moolenaar071d4272004-06-13 20:20:40 +00004715
4716#if defined(FEAT_MBYTE) && defined(FEAT_EVAL)
4717 if (wfname != fname)
4718 {
4719 /*
4720 * The file was written to a temp file, now it needs to be converted
4721 * with 'charconvert' to (overwrite) the output file.
4722 */
4723 if (end != 0)
4724 {
4725 if (eval_charconvert(enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc,
4726 wfname, fname) == FAIL)
4727 {
4728 write_info.bw_conv_error = TRUE;
4729 end = 0;
4730 }
4731 }
4732 mch_remove(wfname);
4733 vim_free(wfname);
4734 }
4735#endif
4736
4737 if (end == 0)
4738 {
4739 if (errmsg == NULL)
4740 {
4741#ifdef FEAT_MBYTE
4742 if (write_info.bw_conv_error)
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004743 {
4744 if (write_info.bw_conv_error_lnum == 0)
4745 errmsg = (char_u *)_("E513: write error, conversion failed (make 'fenc' empty to override)");
4746 else
4747 {
4748 errmsg_allocated = TRUE;
4749 errmsg = alloc(300);
4750 vim_snprintf((char *)errmsg, 300, _("E513: write error, conversion failed in line %ld (make 'fenc' empty to override)"),
4751 (long)write_info.bw_conv_error_lnum);
4752 }
4753 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004754 else
4755#endif
4756 if (got_int)
4757 errmsg = (char_u *)_(e_interr);
4758 else
4759 errmsg = (char_u *)_("E514: write error (file system full?)");
4760 }
4761
4762 /*
4763 * If we have a backup file, try to put it in place of the new file,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004764 * because the new file is probably corrupt. This avoids losing the
Bram Moolenaar071d4272004-06-13 20:20:40 +00004765 * original file when trying to make a backup when writing the file a
4766 * second time.
4767 * When "backup_copy" is set we need to copy the backup over the new
4768 * file. Otherwise rename the backup file.
4769 * If this is OK, don't give the extra warning message.
4770 */
4771 if (backup != NULL)
4772 {
4773 if (backup_copy)
4774 {
4775 /* This may take a while, if we were interrupted let the user
4776 * know we got the message. */
4777 if (got_int)
4778 {
4779 MSG(_(e_interr));
4780 out_flush();
4781 }
4782 if ((fd = mch_open((char *)backup, O_RDONLY | O_EXTRA, 0)) >= 0)
4783 {
4784 if ((write_info.bw_fd = mch_open((char *)fname,
Bram Moolenaar9be038d2005-03-08 22:34:32 +00004785 O_WRONLY | O_CREAT | O_TRUNC | O_EXTRA,
4786 perm & 0777)) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004787 {
4788 /* copy the file. */
4789 write_info.bw_buf = smallbuf;
4790#ifdef HAS_BW_FLAGS
4791 write_info.bw_flags = FIO_NOCONVERT;
4792#endif
4793 while ((write_info.bw_len = vim_read(fd, smallbuf,
4794 SMBUFSIZE)) > 0)
4795 if (buf_write_bytes(&write_info) == FAIL)
4796 break;
4797
4798 if (close(write_info.bw_fd) >= 0
4799 && write_info.bw_len == 0)
4800 end = 1; /* success */
4801 }
4802 close(fd); /* ignore errors for closing read file */
4803 }
4804 }
4805 else
4806 {
4807 if (vim_rename(backup, fname) == 0)
4808 end = 1;
4809 }
4810 }
4811 goto fail;
4812 }
4813
4814 lnum -= start; /* compute number of written lines */
4815 --no_wait_return; /* may wait for return now */
4816
4817#if !(defined(UNIX) || defined(VMS))
4818 fname = sfname; /* use shortname now, for the messages */
4819#endif
4820 if (!filtering)
4821 {
4822 msg_add_fname(buf, fname); /* put fname in IObuff with quotes */
4823 c = FALSE;
4824#ifdef FEAT_MBYTE
4825 if (write_info.bw_conv_error)
4826 {
4827 STRCAT(IObuff, _(" CONVERSION ERROR"));
4828 c = TRUE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004829 if (write_info.bw_conv_error_lnum != 0)
Bram Moolenaara800b422010-06-27 01:15:55 +02004830 vim_snprintf_add((char *)IObuff, IOSIZE, _(" in line %ld;"),
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004831 (long)write_info.bw_conv_error_lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004832 }
4833 else if (notconverted)
4834 {
4835 STRCAT(IObuff, _("[NOT converted]"));
4836 c = TRUE;
4837 }
4838 else if (converted)
4839 {
4840 STRCAT(IObuff, _("[converted]"));
4841 c = TRUE;
4842 }
4843#endif
4844 if (device)
4845 {
4846 STRCAT(IObuff, _("[Device]"));
4847 c = TRUE;
4848 }
4849 else if (newfile)
4850 {
4851 STRCAT(IObuff, shortmess(SHM_NEW) ? _("[New]") : _("[New File]"));
4852 c = TRUE;
4853 }
4854 if (no_eol)
4855 {
4856 msg_add_eol();
4857 c = TRUE;
4858 }
4859 /* may add [unix/dos/mac] */
4860 if (msg_add_fileformat(fileformat))
4861 c = TRUE;
4862#ifdef FEAT_CRYPT
4863 if (wb_flags & FIO_ENCRYPTED)
4864 {
4865 STRCAT(IObuff, _("[crypted]"));
4866 c = TRUE;
4867 }
4868#endif
4869 msg_add_lines(c, (long)lnum, nchars); /* add line/char count */
4870 if (!shortmess(SHM_WRITE))
4871 {
4872 if (append)
4873 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended"));
4874 else
4875 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written"));
4876 }
4877
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00004878 set_keep_msg(msg_trunc_attr(IObuff, FALSE, 0), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004879 }
4880
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004881 /* When written everything correctly: reset 'modified'. Unless not
4882 * writing to the original file and '+' is not in 'cpoptions'. */
Bram Moolenaar292ad192005-12-11 21:29:51 +00004883 if (reset_changed && whole && !append
Bram Moolenaar071d4272004-06-13 20:20:40 +00004884#ifdef FEAT_MBYTE
4885 && !write_info.bw_conv_error
4886#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004887 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL)
4888 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004889 {
4890 unchanged(buf, TRUE);
4891 u_unchanged(buf);
Bram Moolenaar730cde92010-06-27 05:18:54 +02004892 u_update_save_nr(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004893 }
4894
4895 /*
4896 * If written to the current file, update the timestamp of the swap file
4897 * and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
4898 */
4899 if (overwriting)
4900 {
4901 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00004902 if (append)
4903 buf->b_flags &= ~BF_NEW;
4904 else
4905 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004906 }
4907
4908 /*
4909 * If we kept a backup until now, and we are in patch mode, then we make
4910 * the backup file our 'original' file.
4911 */
4912 if (*p_pm && dobackup)
4913 {
4914 char *org = (char *)buf_modname(
4915#ifdef SHORT_FNAME
4916 TRUE,
4917#else
4918 (buf->b_p_sn || buf->b_shortname),
4919#endif
4920 fname, p_pm, FALSE);
4921
4922 if (backup != NULL)
4923 {
4924 struct stat st;
4925
4926 /*
4927 * If the original file does not exist yet
4928 * the current backup file becomes the original file
4929 */
4930 if (org == NULL)
4931 EMSG(_("E205: Patchmode: can't save original file"));
4932 else if (mch_stat(org, &st) < 0)
4933 {
4934 vim_rename(backup, (char_u *)org);
4935 vim_free(backup); /* don't delete the file */
4936 backup = NULL;
4937#ifdef UNIX
4938 set_file_time((char_u *)org, st_old.st_atime, st_old.st_mtime);
4939#endif
4940 }
4941 }
4942 /*
4943 * If there is no backup file, remember that a (new) file was
4944 * created.
4945 */
4946 else
4947 {
4948 int empty_fd;
4949
4950 if (org == NULL
Bram Moolenaara5792f52005-11-23 21:25:05 +00004951 || (empty_fd = mch_open(org,
4952 O_CREAT | O_EXTRA | O_EXCL | O_NOFOLLOW,
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00004953 perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004954 EMSG(_("E206: patchmode: can't touch empty original file"));
4955 else
4956 close(empty_fd);
4957 }
4958 if (org != NULL)
4959 {
4960 mch_setperm((char_u *)org, mch_getperm(fname) & 0777);
4961 vim_free(org);
4962 }
4963 }
4964
4965 /*
4966 * Remove the backup unless 'backup' option is set
4967 */
4968 if (!p_bk && backup != NULL && mch_remove(backup) != 0)
4969 EMSG(_("E207: Can't delete backup file"));
4970
4971#ifdef FEAT_SUN_WORKSHOP
4972 if (usingSunWorkShop)
4973 workshop_file_saved((char *) ffname);
4974#endif
4975
4976 goto nofail;
4977
4978 /*
4979 * Finish up. We get here either after failure or success.
4980 */
4981fail:
4982 --no_wait_return; /* may wait for return now */
4983nofail:
4984
4985 /* Done saving, we accept changed buffer warnings again */
4986 buf->b_saving = FALSE;
4987
4988 vim_free(backup);
4989 if (buffer != smallbuf)
4990 vim_free(buffer);
4991#ifdef FEAT_MBYTE
4992 vim_free(fenc_tofree);
4993 vim_free(write_info.bw_conv_buf);
4994# ifdef USE_ICONV
4995 if (write_info.bw_iconv_fd != (iconv_t)-1)
4996 {
4997 iconv_close(write_info.bw_iconv_fd);
4998 write_info.bw_iconv_fd = (iconv_t)-1;
4999 }
5000# endif
5001#endif
5002#ifdef HAVE_ACL
5003 mch_free_acl(acl);
5004#endif
5005
5006 if (errmsg != NULL)
5007 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005008 int numlen = errnum != NULL ? (int)STRLEN(errnum) : 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005009
5010 attr = hl_attr(HLF_E); /* set highlight for error messages */
5011 msg_add_fname(buf,
5012#ifndef UNIX
5013 sfname
5014#else
5015 fname
5016#endif
5017 ); /* put file name in IObuff with quotes */
5018 if (STRLEN(IObuff) + STRLEN(errmsg) + numlen >= IOSIZE)
5019 IObuff[IOSIZE - STRLEN(errmsg) - numlen - 1] = NUL;
5020 /* If the error message has the form "is ...", put the error number in
5021 * front of the file name. */
5022 if (errnum != NULL)
5023 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00005024 STRMOVE(IObuff + numlen, IObuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005025 mch_memmove(IObuff, errnum, (size_t)numlen);
5026 }
5027 STRCAT(IObuff, errmsg);
5028 emsg(IObuff);
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005029 if (errmsg_allocated)
5030 vim_free(errmsg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005031
5032 retval = FAIL;
5033 if (end == 0)
5034 {
5035 MSG_PUTS_ATTR(_("\nWARNING: Original file may be lost or damaged\n"),
5036 attr | MSG_HIST);
5037 MSG_PUTS_ATTR(_("don't quit the editor until the file is successfully written!"),
5038 attr | MSG_HIST);
5039
5040 /* Update the timestamp to avoid an "overwrite changed file"
5041 * prompt when writing again. */
5042 if (mch_stat((char *)fname, &st_old) >= 0)
5043 {
5044 buf_store_time(buf, &st_old, fname);
5045 buf->b_mtime_read = buf->b_mtime;
5046 }
5047 }
5048 }
5049 msg_scroll = msg_save;
5050
Bram Moolenaar55debbe2010-05-23 23:34:36 +02005051#ifdef FEAT_PERSISTENT_UNDO
5052 /*
5053 * When writing the whole file and 'undofile' is set, also write the undo
5054 * file.
5055 */
5056 if (retval == OK && write_undo_file)
5057 {
5058 char_u hash[UNDO_HASH_SIZE];
5059
5060 sha256_finish(&sha_ctx, hash);
5061 u_write_undo(NULL, FALSE, buf, hash);
5062 }
5063#endif
5064
Bram Moolenaar071d4272004-06-13 20:20:40 +00005065#ifdef FEAT_AUTOCMD
5066#ifdef FEAT_EVAL
5067 if (!should_abort(retval))
5068#else
5069 if (!got_int)
5070#endif
5071 {
5072 aco_save_T aco;
5073
5074 write_no_eol_lnum = 0; /* in case it was set by the previous read */
5075
5076 /*
5077 * Apply POST autocommands.
5078 * Careful: The autocommands may call buf_write() recursively!
5079 */
5080 aucmd_prepbuf(&aco, buf);
5081
5082 if (append)
5083 apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname,
5084 FALSE, curbuf, eap);
5085 else if (filtering)
5086 apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname,
5087 FALSE, curbuf, eap);
5088 else if (reset_changed && whole)
5089 apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname,
5090 FALSE, curbuf, eap);
5091 else
5092 apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname,
5093 FALSE, curbuf, eap);
5094
5095 /* restore curwin/curbuf and a few other things */
5096 aucmd_restbuf(&aco);
5097
5098#ifdef FEAT_EVAL
5099 if (aborting()) /* autocmds may abort script processing */
5100 retval = FALSE;
5101#endif
5102 }
5103#endif
5104
5105 got_int |= prev_got_int;
5106
5107#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
5108 /* Update machine specific information. */
5109 mch_post_buffer_write(buf);
5110#endif
5111 return retval;
5112}
5113
5114/*
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005115 * Set the name of the current buffer. Use when the buffer doesn't have a
5116 * name and a ":r" or ":w" command with a file name is used.
5117 */
5118 static int
5119set_rw_fname(fname, sfname)
5120 char_u *fname;
5121 char_u *sfname;
5122{
5123#ifdef FEAT_AUTOCMD
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005124 buf_T *buf = curbuf;
5125
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005126 /* It's like the unnamed buffer is deleted.... */
5127 if (curbuf->b_p_bl)
5128 apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
5129 apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf);
5130# ifdef FEAT_EVAL
5131 if (aborting()) /* autocmds may abort script processing */
5132 return FAIL;
5133# endif
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005134 if (curbuf != buf)
5135 {
5136 /* We are in another buffer now, don't do the renaming. */
5137 EMSG(_(e_auchangedbuf));
5138 return FAIL;
5139 }
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005140#endif
5141
5142 if (setfname(curbuf, fname, sfname, FALSE) == OK)
5143 curbuf->b_flags |= BF_NOTEDITED;
5144
5145#ifdef FEAT_AUTOCMD
5146 /* ....and a new named one is created */
5147 apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, curbuf);
5148 if (curbuf->b_p_bl)
5149 apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf);
5150# ifdef FEAT_EVAL
5151 if (aborting()) /* autocmds may abort script processing */
5152 return FAIL;
5153# endif
5154
5155 /* Do filetype detection now if 'filetype' is empty. */
5156 if (*curbuf->b_p_ft == NUL)
5157 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005158 if (au_has_group((char_u *)"filetypedetect"))
Bram Moolenaar70836c82006-02-20 21:28:49 +00005159 (void)do_doautocmd((char_u *)"filetypedetect BufRead", FALSE);
Bram Moolenaara3227e22006-03-08 21:32:40 +00005160 do_modelines(0);
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005161 }
5162#endif
5163
5164 return OK;
5165}
5166
5167/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00005168 * Put file name into IObuff with quotes.
5169 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005170 void
Bram Moolenaar071d4272004-06-13 20:20:40 +00005171msg_add_fname(buf, fname)
5172 buf_T *buf;
5173 char_u *fname;
5174{
5175 if (fname == NULL)
5176 fname = (char_u *)"-stdin-";
5177 home_replace(buf, fname, IObuff + 1, IOSIZE - 4, TRUE);
5178 IObuff[0] = '"';
5179 STRCAT(IObuff, "\" ");
5180}
5181
5182/*
5183 * Append message for text mode to IObuff.
5184 * Return TRUE if something appended.
5185 */
5186 static int
5187msg_add_fileformat(eol_type)
5188 int eol_type;
5189{
5190#ifndef USE_CRNL
5191 if (eol_type == EOL_DOS)
5192 {
5193 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[dos]") : _("[dos format]"));
5194 return TRUE;
5195 }
5196#endif
5197#ifndef USE_CR
5198 if (eol_type == EOL_MAC)
5199 {
5200 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[mac]") : _("[mac format]"));
5201 return TRUE;
5202 }
5203#endif
5204#if defined(USE_CRNL) || defined(USE_CR)
5205 if (eol_type == EOL_UNIX)
5206 {
5207 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[unix]") : _("[unix format]"));
5208 return TRUE;
5209 }
5210#endif
5211 return FALSE;
5212}
5213
5214/*
5215 * Append line and character count to IObuff.
5216 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005217 void
Bram Moolenaar071d4272004-06-13 20:20:40 +00005218msg_add_lines(insert_space, lnum, nchars)
5219 int insert_space;
5220 long lnum;
Bram Moolenaar914703b2010-05-31 21:59:46 +02005221 off_t nchars;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005222{
5223 char_u *p;
5224
5225 p = IObuff + STRLEN(IObuff);
5226
5227 if (insert_space)
5228 *p++ = ' ';
5229 if (shortmess(SHM_LINES))
Bram Moolenaar914703b2010-05-31 21:59:46 +02005230 sprintf((char *)p,
5231#ifdef LONG_LONG_OFF_T
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005232 "%ldL, %lldC", lnum, nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005233#else
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005234 /* Explicit typecast avoids warning on Mac OS X 10.6 */
5235 "%ldL, %ldC", lnum, (long)nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005236#endif
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005237 );
Bram Moolenaar071d4272004-06-13 20:20:40 +00005238 else
5239 {
5240 if (lnum == 1)
5241 STRCPY(p, _("1 line, "));
5242 else
5243 sprintf((char *)p, _("%ld lines, "), lnum);
5244 p += STRLEN(p);
5245 if (nchars == 1)
5246 STRCPY(p, _("1 character"));
5247 else
Bram Moolenaar914703b2010-05-31 21:59:46 +02005248 sprintf((char *)p,
5249#ifdef LONG_LONG_OFF_T
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005250 _("%lld characters"), nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005251#else
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005252 /* Explicit typecast avoids warning on Mac OS X 10.6 */
5253 _("%ld characters"), (long)nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005254#endif
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005255 );
Bram Moolenaar071d4272004-06-13 20:20:40 +00005256 }
5257}
5258
5259/*
5260 * Append message for missing line separator to IObuff.
5261 */
5262 static void
5263msg_add_eol()
5264{
5265 STRCAT(IObuff, shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]"));
5266}
5267
5268/*
5269 * Check modification time of file, before writing to it.
5270 * The size isn't checked, because using a tool like "gzip" takes care of
5271 * using the same timestamp but can't set the size.
5272 */
5273 static int
5274check_mtime(buf, st)
5275 buf_T *buf;
5276 struct stat *st;
5277{
5278 if (buf->b_mtime_read != 0
5279 && time_differs((long)st->st_mtime, buf->b_mtime_read))
5280 {
5281 msg_scroll = TRUE; /* don't overwrite messages here */
5282 msg_silent = 0; /* must give this prompt */
5283 /* don't use emsg() here, don't want to flush the buffers */
5284 MSG_ATTR(_("WARNING: The file has been changed since reading it!!!"),
5285 hl_attr(HLF_E));
5286 if (ask_yesno((char_u *)_("Do you really want to write to it"),
5287 TRUE) == 'n')
5288 return FAIL;
5289 msg_scroll = FALSE; /* always overwrite the file message now */
5290 }
5291 return OK;
5292}
5293
5294 static int
5295time_differs(t1, t2)
5296 long t1, t2;
5297{
5298#if defined(__linux__) || defined(MSDOS) || defined(MSWIN)
5299 /* On a FAT filesystem, esp. under Linux, there are only 5 bits to store
5300 * the seconds. Since the roundoff is done when flushing the inode, the
5301 * time may change unexpectedly by one second!!! */
5302 return (t1 - t2 > 1 || t2 - t1 > 1);
5303#else
5304 return (t1 != t2);
5305#endif
5306}
5307
5308/*
5309 * Call write() to write a number of bytes to the file.
5310 * Also handles encryption and 'encoding' conversion.
5311 *
5312 * Return FAIL for failure, OK otherwise.
5313 */
5314 static int
5315buf_write_bytes(ip)
5316 struct bw_info *ip;
5317{
5318 int wlen;
5319 char_u *buf = ip->bw_buf; /* data to write */
5320 int len = ip->bw_len; /* length of data */
5321#ifdef HAS_BW_FLAGS
5322 int flags = ip->bw_flags; /* extra flags */
5323#endif
5324
5325#ifdef FEAT_MBYTE
5326 /*
5327 * Skip conversion when writing the crypt magic number or the BOM.
5328 */
5329 if (!(flags & FIO_NOCONVERT))
5330 {
5331 char_u *p;
5332 unsigned c;
5333 int n;
5334
5335 if (flags & FIO_UTF8)
5336 {
5337 /*
5338 * Convert latin1 in the buffer to UTF-8 in the file.
5339 */
5340 p = ip->bw_conv_buf; /* translate to buffer */
5341 for (wlen = 0; wlen < len; ++wlen)
5342 p += utf_char2bytes(buf[wlen], p);
5343 buf = ip->bw_conv_buf;
5344 len = (int)(p - ip->bw_conv_buf);
5345 }
5346 else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1))
5347 {
5348 /*
5349 * Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
5350 * Latin1 chars in the file.
5351 */
5352 if (flags & FIO_LATIN1)
5353 p = buf; /* translate in-place (can only get shorter) */
5354 else
5355 p = ip->bw_conv_buf; /* translate to buffer */
5356 for (wlen = 0; wlen < len; wlen += n)
5357 {
5358 if (wlen == 0 && ip->bw_restlen != 0)
5359 {
5360 int l;
5361
5362 /* Use remainder of previous call. Append the start of
5363 * buf[] to get a full sequence. Might still be too
5364 * short! */
5365 l = CONV_RESTLEN - ip->bw_restlen;
5366 if (l > len)
5367 l = len;
5368 mch_memmove(ip->bw_rest + ip->bw_restlen, buf, (size_t)l);
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005369 n = utf_ptr2len_len(ip->bw_rest, ip->bw_restlen + l);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005370 if (n > ip->bw_restlen + len)
5371 {
5372 /* We have an incomplete byte sequence at the end to
5373 * be written. We can't convert it without the
5374 * remaining bytes. Keep them for the next call. */
5375 if (ip->bw_restlen + len > CONV_RESTLEN)
5376 return FAIL;
5377 ip->bw_restlen += len;
5378 break;
5379 }
5380 if (n > 1)
5381 c = utf_ptr2char(ip->bw_rest);
5382 else
5383 c = ip->bw_rest[0];
5384 if (n >= ip->bw_restlen)
5385 {
5386 n -= ip->bw_restlen;
5387 ip->bw_restlen = 0;
5388 }
5389 else
5390 {
5391 ip->bw_restlen -= n;
5392 mch_memmove(ip->bw_rest, ip->bw_rest + n,
5393 (size_t)ip->bw_restlen);
5394 n = 0;
5395 }
5396 }
5397 else
5398 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005399 n = utf_ptr2len_len(buf + wlen, len - wlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005400 if (n > len - wlen)
5401 {
5402 /* We have an incomplete byte sequence at the end to
5403 * be written. We can't convert it without the
5404 * remaining bytes. Keep them for the next call. */
5405 if (len - wlen > CONV_RESTLEN)
5406 return FAIL;
5407 ip->bw_restlen = len - wlen;
5408 mch_memmove(ip->bw_rest, buf + wlen,
5409 (size_t)ip->bw_restlen);
5410 break;
5411 }
5412 if (n > 1)
5413 c = utf_ptr2char(buf + wlen);
5414 else
5415 c = buf[wlen];
5416 }
5417
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005418 if (ucs2bytes(c, &p, flags) && !ip->bw_conv_error)
5419 {
5420 ip->bw_conv_error = TRUE;
5421 ip->bw_conv_error_lnum = ip->bw_start_lnum;
5422 }
5423 if (c == NL)
5424 ++ip->bw_start_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005425 }
5426 if (flags & FIO_LATIN1)
5427 len = (int)(p - buf);
5428 else
5429 {
5430 buf = ip->bw_conv_buf;
5431 len = (int)(p - ip->bw_conv_buf);
5432 }
5433 }
5434
5435# ifdef WIN3264
5436 else if (flags & FIO_CODEPAGE)
5437 {
5438 /*
5439 * Convert UTF-8 or codepage to UCS-2 and then to MS-Windows
5440 * codepage.
5441 */
5442 char_u *from;
5443 size_t fromlen;
5444 char_u *to;
5445 int u8c;
5446 BOOL bad = FALSE;
5447 int needed;
5448
5449 if (ip->bw_restlen > 0)
5450 {
5451 /* Need to concatenate the remainder of the previous call and
5452 * the bytes of the current call. Use the end of the
5453 * conversion buffer for this. */
5454 fromlen = len + ip->bw_restlen;
5455 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5456 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5457 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5458 }
5459 else
5460 {
5461 from = buf;
5462 fromlen = len;
5463 }
5464
5465 to = ip->bw_conv_buf;
5466 if (enc_utf8)
5467 {
5468 /* Convert from UTF-8 to UCS-2, to the start of the buffer.
5469 * The buffer has been allocated to be big enough. */
5470 while (fromlen > 0)
5471 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005472 n = (int)utf_ptr2len_len(from, (int)fromlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005473 if (n > (int)fromlen) /* incomplete byte sequence */
5474 break;
5475 u8c = utf_ptr2char(from);
5476 *to++ = (u8c & 0xff);
5477 *to++ = (u8c >> 8);
5478 fromlen -= n;
5479 from += n;
5480 }
5481
5482 /* Copy remainder to ip->bw_rest[] to be used for the next
5483 * call. */
5484 if (fromlen > CONV_RESTLEN)
5485 {
5486 /* weird overlong sequence */
5487 ip->bw_conv_error = TRUE;
5488 return FAIL;
5489 }
5490 mch_memmove(ip->bw_rest, from, fromlen);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005491 ip->bw_restlen = (int)fromlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005492 }
5493 else
5494 {
5495 /* Convert from enc_codepage to UCS-2, to the start of the
5496 * buffer. The buffer has been allocated to be big enough. */
5497 ip->bw_restlen = 0;
5498 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005499 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005500 NULL, 0);
5501 if (needed == 0)
5502 {
5503 /* When conversion fails there may be a trailing byte. */
5504 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005505 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen - 1,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005506 NULL, 0);
5507 if (needed == 0)
5508 {
5509 /* Conversion doesn't work. */
5510 ip->bw_conv_error = TRUE;
5511 return FAIL;
5512 }
5513 /* Save the trailing byte for the next call. */
5514 ip->bw_rest[0] = from[fromlen - 1];
5515 ip->bw_restlen = 1;
5516 }
5517 needed = MultiByteToWideChar(enc_codepage, MB_ERR_INVALID_CHARS,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005518 (LPCSTR)from, (int)(fromlen - ip->bw_restlen),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005519 (LPWSTR)to, needed);
5520 if (needed == 0)
5521 {
5522 /* Safety check: Conversion doesn't work. */
5523 ip->bw_conv_error = TRUE;
5524 return FAIL;
5525 }
5526 to += needed * 2;
5527 }
5528
5529 fromlen = to - ip->bw_conv_buf;
5530 buf = to;
5531# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5532 if (FIO_GET_CP(flags) == CP_UTF8)
5533 {
5534 /* Convert from UCS-2 to UTF-8, using the remainder of the
5535 * conversion buffer. Fails when out of space. */
5536 for (from = ip->bw_conv_buf; fromlen > 1; fromlen -= 2)
5537 {
5538 u8c = *from++;
5539 u8c += (*from++ << 8);
5540 to += utf_char2bytes(u8c, to);
5541 if (to + 6 >= ip->bw_conv_buf + ip->bw_conv_buflen)
5542 {
5543 ip->bw_conv_error = TRUE;
5544 return FAIL;
5545 }
5546 }
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005547 len = (int)(to - buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005548 }
5549 else
5550#endif
5551 {
5552 /* Convert from UCS-2 to the codepage, using the remainder of
5553 * the conversion buffer. If the conversion uses the default
5554 * character "0", the data doesn't fit in this encoding, so
5555 * fail. */
5556 len = WideCharToMultiByte(FIO_GET_CP(flags), 0,
5557 (LPCWSTR)ip->bw_conv_buf, (int)fromlen / sizeof(WCHAR),
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005558 (LPSTR)to, (int)(ip->bw_conv_buflen - fromlen), 0,
5559 &bad);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005560 if (bad)
5561 {
5562 ip->bw_conv_error = TRUE;
5563 return FAIL;
5564 }
5565 }
5566 }
5567# endif
5568
Bram Moolenaar56718732006-03-15 22:53:57 +00005569# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00005570 else if (flags & FIO_MACROMAN)
5571 {
5572 /*
5573 * Convert UTF-8 or latin1 to Apple MacRoman.
5574 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005575 char_u *from;
5576 size_t fromlen;
5577
5578 if (ip->bw_restlen > 0)
5579 {
5580 /* Need to concatenate the remainder of the previous call and
5581 * the bytes of the current call. Use the end of the
5582 * conversion buffer for this. */
5583 fromlen = len + ip->bw_restlen;
5584 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5585 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5586 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5587 }
5588 else
5589 {
5590 from = buf;
5591 fromlen = len;
5592 }
5593
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00005594 if (enc2macroman(from, fromlen,
5595 ip->bw_conv_buf, &len, ip->bw_conv_buflen,
5596 ip->bw_rest, &ip->bw_restlen) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005597 {
5598 ip->bw_conv_error = TRUE;
5599 return FAIL;
5600 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005601 buf = ip->bw_conv_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005602 }
5603# endif
5604
5605# ifdef USE_ICONV
5606 if (ip->bw_iconv_fd != (iconv_t)-1)
5607 {
5608 const char *from;
5609 size_t fromlen;
5610 char *to;
5611 size_t tolen;
5612
5613 /* Convert with iconv(). */
5614 if (ip->bw_restlen > 0)
5615 {
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005616 char *fp;
5617
Bram Moolenaar071d4272004-06-13 20:20:40 +00005618 /* Need to concatenate the remainder of the previous call and
5619 * the bytes of the current call. Use the end of the
5620 * conversion buffer for this. */
5621 fromlen = len + ip->bw_restlen;
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005622 fp = (char *)ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5623 mch_memmove(fp, ip->bw_rest, (size_t)ip->bw_restlen);
5624 mch_memmove(fp + ip->bw_restlen, buf, (size_t)len);
5625 from = fp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005626 tolen = ip->bw_conv_buflen - fromlen;
5627 }
5628 else
5629 {
5630 from = (const char *)buf;
5631 fromlen = len;
5632 tolen = ip->bw_conv_buflen;
5633 }
5634 to = (char *)ip->bw_conv_buf;
5635
5636 if (ip->bw_first)
5637 {
5638 size_t save_len = tolen;
5639
5640 /* output the initial shift state sequence */
5641 (void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen);
5642
5643 /* There is a bug in iconv() on Linux (which appears to be
5644 * wide-spread) which sets "to" to NULL and messes up "tolen".
5645 */
5646 if (to == NULL)
5647 {
5648 to = (char *)ip->bw_conv_buf;
5649 tolen = save_len;
5650 }
5651 ip->bw_first = FALSE;
5652 }
5653
5654 /*
5655 * If iconv() has an error or there is not enough room, fail.
5656 */
5657 if ((iconv(ip->bw_iconv_fd, (void *)&from, &fromlen, &to, &tolen)
5658 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
5659 || fromlen > CONV_RESTLEN)
5660 {
5661 ip->bw_conv_error = TRUE;
5662 return FAIL;
5663 }
5664
5665 /* copy remainder to ip->bw_rest[] to be used for the next call. */
5666 if (fromlen > 0)
5667 mch_memmove(ip->bw_rest, (void *)from, fromlen);
5668 ip->bw_restlen = (int)fromlen;
5669
5670 buf = ip->bw_conv_buf;
5671 len = (int)((char_u *)to - ip->bw_conv_buf);
5672 }
5673# endif
5674 }
5675#endif /* FEAT_MBYTE */
5676
5677#ifdef FEAT_CRYPT
5678 if (flags & FIO_ENCRYPTED) /* encrypt the data */
Bram Moolenaar04c9baf2010-06-01 23:37:39 +02005679 crypt_encode(buf, len, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005680#endif
5681
5682 /* Repeat the write(), it may be interrupted by a signal. */
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005683 while (len > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005684 {
5685 wlen = vim_write(ip->bw_fd, buf, len);
5686 if (wlen <= 0) /* error! */
5687 return FAIL;
5688 len -= wlen;
5689 buf += wlen;
5690 }
5691 return OK;
5692}
5693
5694#ifdef FEAT_MBYTE
5695/*
5696 * Convert a Unicode character to bytes.
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005697 * Return TRUE for an error, FALSE when it's OK.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005698 */
5699 static int
5700ucs2bytes(c, pp, flags)
5701 unsigned c; /* in: character */
5702 char_u **pp; /* in/out: pointer to result */
5703 int flags; /* FIO_ flags */
5704{
5705 char_u *p = *pp;
5706 int error = FALSE;
5707 int cc;
5708
5709
5710 if (flags & FIO_UCS4)
5711 {
5712 if (flags & FIO_ENDIAN_L)
5713 {
5714 *p++ = c;
5715 *p++ = (c >> 8);
5716 *p++ = (c >> 16);
5717 *p++ = (c >> 24);
5718 }
5719 else
5720 {
5721 *p++ = (c >> 24);
5722 *p++ = (c >> 16);
5723 *p++ = (c >> 8);
5724 *p++ = c;
5725 }
5726 }
5727 else if (flags & (FIO_UCS2 | FIO_UTF16))
5728 {
5729 if (c >= 0x10000)
5730 {
5731 if (flags & FIO_UTF16)
5732 {
5733 /* Make two words, ten bits of the character in each. First
5734 * word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff */
5735 c -= 0x10000;
5736 if (c >= 0x100000)
5737 error = TRUE;
5738 cc = ((c >> 10) & 0x3ff) + 0xd800;
5739 if (flags & FIO_ENDIAN_L)
5740 {
5741 *p++ = cc;
5742 *p++ = ((unsigned)cc >> 8);
5743 }
5744 else
5745 {
5746 *p++ = ((unsigned)cc >> 8);
5747 *p++ = cc;
5748 }
5749 c = (c & 0x3ff) + 0xdc00;
5750 }
5751 else
5752 error = TRUE;
5753 }
5754 if (flags & FIO_ENDIAN_L)
5755 {
5756 *p++ = c;
5757 *p++ = (c >> 8);
5758 }
5759 else
5760 {
5761 *p++ = (c >> 8);
5762 *p++ = c;
5763 }
5764 }
5765 else /* Latin1 */
5766 {
5767 if (c >= 0x100)
5768 {
5769 error = TRUE;
5770 *p++ = 0xBF;
5771 }
5772 else
5773 *p++ = c;
5774 }
5775
5776 *pp = p;
5777 return error;
5778}
5779
5780/*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005781 * Return TRUE if file encoding "fenc" requires conversion from or to
5782 * 'encoding'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005783 */
5784 static int
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005785need_conversion(fenc)
5786 char_u *fenc;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005787{
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005788 int same_encoding;
5789 int enc_flags;
5790 int fenc_flags;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005791
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005792 if (*fenc == NUL || STRCMP(p_enc, fenc) == 0)
Bram Moolenaar442b4222010-05-24 21:34:22 +02005793 {
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005794 same_encoding = TRUE;
Bram Moolenaar442b4222010-05-24 21:34:22 +02005795 fenc_flags = 0;
5796 }
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005797 else
5798 {
5799 /* Ignore difference between "ansi" and "latin1", "ucs-4" and
5800 * "ucs-4be", etc. */
5801 enc_flags = get_fio_flags(p_enc);
5802 fenc_flags = get_fio_flags(fenc);
5803 same_encoding = (enc_flags != 0 && fenc_flags == enc_flags);
5804 }
5805 if (same_encoding)
5806 {
5807 /* Specified encoding matches with 'encoding'. This requires
5808 * conversion when 'encoding' is Unicode but not UTF-8. */
5809 return enc_unicode != 0;
5810 }
5811
5812 /* Encodings differ. However, conversion is not needed when 'enc' is any
5813 * Unicode encoding and the file is UTF-8. */
5814 return !(enc_utf8 && fenc_flags == FIO_UTF8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005815}
5816
5817/*
5818 * Check "ptr" for a unicode encoding and return the FIO_ flags needed for the
5819 * internal conversion.
5820 * if "ptr" is an empty string, use 'encoding'.
5821 */
5822 static int
5823get_fio_flags(ptr)
5824 char_u *ptr;
5825{
5826 int prop;
5827
5828 if (*ptr == NUL)
5829 ptr = p_enc;
5830
5831 prop = enc_canon_props(ptr);
5832 if (prop & ENC_UNICODE)
5833 {
5834 if (prop & ENC_2BYTE)
5835 {
5836 if (prop & ENC_ENDIAN_L)
5837 return FIO_UCS2 | FIO_ENDIAN_L;
5838 return FIO_UCS2;
5839 }
5840 if (prop & ENC_4BYTE)
5841 {
5842 if (prop & ENC_ENDIAN_L)
5843 return FIO_UCS4 | FIO_ENDIAN_L;
5844 return FIO_UCS4;
5845 }
5846 if (prop & ENC_2WORD)
5847 {
5848 if (prop & ENC_ENDIAN_L)
5849 return FIO_UTF16 | FIO_ENDIAN_L;
5850 return FIO_UTF16;
5851 }
5852 return FIO_UTF8;
5853 }
5854 if (prop & ENC_LATIN1)
5855 return FIO_LATIN1;
5856 /* must be ENC_DBCS, requires iconv() */
5857 return 0;
5858}
5859
5860#ifdef WIN3264
5861/*
5862 * Check "ptr" for a MS-Windows codepage name and return the FIO_ flags needed
5863 * for the conversion MS-Windows can do for us. Also accept "utf-8".
5864 * Used for conversion between 'encoding' and 'fileencoding'.
5865 */
5866 static int
5867get_win_fio_flags(ptr)
5868 char_u *ptr;
5869{
5870 int cp;
5871
5872 /* Cannot do this when 'encoding' is not utf-8 and not a codepage. */
5873 if (!enc_utf8 && enc_codepage <= 0)
5874 return 0;
5875
5876 cp = encname2codepage(ptr);
5877 if (cp == 0)
5878 {
5879# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5880 if (STRCMP(ptr, "utf-8") == 0)
5881 cp = CP_UTF8;
5882 else
5883# endif
5884 return 0;
5885 }
5886 return FIO_PUT_CP(cp) | FIO_CODEPAGE;
5887}
5888#endif
5889
5890#ifdef MACOS_X
5891/*
5892 * Check "ptr" for a Carbon supported encoding and return the FIO_ flags
5893 * needed for the internal conversion to/from utf-8 or latin1.
5894 */
5895 static int
5896get_mac_fio_flags(ptr)
5897 char_u *ptr;
5898{
5899 if ((enc_utf8 || STRCMP(p_enc, "latin1") == 0)
5900 && (enc_canon_props(ptr) & ENC_MACROMAN))
5901 return FIO_MACROMAN;
5902 return 0;
5903}
5904#endif
5905
5906/*
5907 * Check for a Unicode BOM (Byte Order Mark) at the start of p[size].
5908 * "size" must be at least 2.
5909 * Return the name of the encoding and set "*lenp" to the length.
5910 * Returns NULL when no BOM found.
5911 */
5912 static char_u *
5913check_for_bom(p, size, lenp, flags)
5914 char_u *p;
5915 long size;
5916 int *lenp;
5917 int flags;
5918{
5919 char *name = NULL;
5920 int len = 2;
5921
5922 if (p[0] == 0xef && p[1] == 0xbb && size >= 3 && p[2] == 0xbf
Bram Moolenaaree0f5a62008-07-24 20:09:16 +00005923 && (flags == FIO_ALL || flags == FIO_UTF8 || flags == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005924 {
5925 name = "utf-8"; /* EF BB BF */
5926 len = 3;
5927 }
5928 else if (p[0] == 0xff && p[1] == 0xfe)
5929 {
5930 if (size >= 4 && p[2] == 0 && p[3] == 0
5931 && (flags == FIO_ALL || flags == (FIO_UCS4 | FIO_ENDIAN_L)))
5932 {
5933 name = "ucs-4le"; /* FF FE 00 00 */
5934 len = 4;
5935 }
Bram Moolenaar223a1892008-11-11 20:57:11 +00005936 else if (flags == (FIO_UCS2 | FIO_ENDIAN_L))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005937 name = "ucs-2le"; /* FF FE */
Bram Moolenaar223a1892008-11-11 20:57:11 +00005938 else if (flags == FIO_ALL || flags == (FIO_UTF16 | FIO_ENDIAN_L))
5939 /* utf-16le is preferred, it also works for ucs-2le text */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005940 name = "utf-16le"; /* FF FE */
5941 }
5942 else if (p[0] == 0xfe && p[1] == 0xff
5943 && (flags == FIO_ALL || flags == FIO_UCS2 || flags == FIO_UTF16))
5944 {
Bram Moolenaarffd82c52008-02-20 17:15:26 +00005945 /* Default to utf-16, it works also for ucs-2 text. */
5946 if (flags == FIO_UCS2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005947 name = "ucs-2"; /* FE FF */
Bram Moolenaarffd82c52008-02-20 17:15:26 +00005948 else
5949 name = "utf-16"; /* FE FF */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005950 }
5951 else if (size >= 4 && p[0] == 0 && p[1] == 0 && p[2] == 0xfe
5952 && p[3] == 0xff && (flags == FIO_ALL || flags == FIO_UCS4))
5953 {
5954 name = "ucs-4"; /* 00 00 FE FF */
5955 len = 4;
5956 }
5957
5958 *lenp = len;
5959 return (char_u *)name;
5960}
5961
5962/*
5963 * Generate a BOM in "buf[4]" for encoding "name".
5964 * Return the length of the BOM (zero when no BOM).
5965 */
5966 static int
5967make_bom(buf, name)
5968 char_u *buf;
5969 char_u *name;
5970{
5971 int flags;
5972 char_u *p;
5973
5974 flags = get_fio_flags(name);
5975
5976 /* Can't put a BOM in a non-Unicode file. */
5977 if (flags == FIO_LATIN1 || flags == 0)
5978 return 0;
5979
5980 if (flags == FIO_UTF8) /* UTF-8 */
5981 {
5982 buf[0] = 0xef;
5983 buf[1] = 0xbb;
5984 buf[2] = 0xbf;
5985 return 3;
5986 }
5987 p = buf;
5988 (void)ucs2bytes(0xfeff, &p, flags);
5989 return (int)(p - buf);
5990}
5991#endif
5992
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00005993#if defined(FEAT_VIMINFO) || defined(FEAT_BROWSE) || \
Bram Moolenaara0174af2008-01-02 20:08:25 +00005994 defined(FEAT_QUICKFIX) || defined(FEAT_AUTOCMD) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005995/*
5996 * Try to find a shortname by comparing the fullname with the current
5997 * directory.
Bram Moolenaard089d9b2007-09-30 12:02:55 +00005998 * Returns "full_path" or pointer into "full_path" if shortened.
5999 */
6000 char_u *
6001shorten_fname1(full_path)
6002 char_u *full_path;
6003{
6004 char_u dirname[MAXPATHL];
6005 char_u *p = full_path;
6006
6007 if (mch_dirname(dirname, MAXPATHL) == OK)
6008 {
6009 p = shorten_fname(full_path, dirname);
6010 if (p == NULL || *p == NUL)
6011 p = full_path;
6012 }
6013 return p;
6014}
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00006015#endif
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006016
6017/*
6018 * Try to find a shortname by comparing the fullname with the current
6019 * directory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006020 * Returns NULL if not shorter name possible, pointer into "full_path"
6021 * otherwise.
6022 */
6023 char_u *
6024shorten_fname(full_path, dir_name)
6025 char_u *full_path;
6026 char_u *dir_name;
6027{
6028 int len;
6029 char_u *p;
6030
6031 if (full_path == NULL)
6032 return NULL;
6033 len = (int)STRLEN(dir_name);
6034 if (fnamencmp(dir_name, full_path, len) == 0)
6035 {
6036 p = full_path + len;
6037#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
6038 /*
6039 * MSDOS: when a file is in the root directory, dir_name will end in a
6040 * slash, since C: by itself does not define a specific dir. In this
6041 * case p may already be correct. <negri>
6042 */
6043 if (!((len > 2) && (*(p - 2) == ':')))
6044#endif
6045 {
6046 if (vim_ispathsep(*p))
6047 ++p;
6048#ifndef VMS /* the path separator is always part of the path */
6049 else
6050 p = NULL;
6051#endif
6052 }
6053 }
6054#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
6055 /*
6056 * When using a file in the current drive, remove the drive name:
6057 * "A:\dir\file" -> "\dir\file". This helps when moving a session file on
6058 * a floppy from "A:\dir" to "B:\dir".
6059 */
6060 else if (len > 3
6061 && TOUPPER_LOC(full_path[0]) == TOUPPER_LOC(dir_name[0])
6062 && full_path[1] == ':'
6063 && vim_ispathsep(full_path[2]))
6064 p = full_path + 2;
6065#endif
6066 else
6067 p = NULL;
6068 return p;
6069}
6070
6071/*
6072 * Shorten filenames for all buffers.
6073 * When "force" is TRUE: Use full path from now on for files currently being
6074 * edited, both for file name and swap file name. Try to shorten the file
6075 * names a bit, if safe to do so.
6076 * When "force" is FALSE: Only try to shorten absolute file names.
6077 * For buffers that have buftype "nofile" or "scratch": never change the file
6078 * name.
6079 */
6080 void
6081shorten_fnames(force)
6082 int force;
6083{
6084 char_u dirname[MAXPATHL];
6085 buf_T *buf;
6086 char_u *p;
6087
6088 mch_dirname(dirname, MAXPATHL);
6089 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
6090 {
6091 if (buf->b_fname != NULL
6092#ifdef FEAT_QUICKFIX
6093 && !bt_nofile(buf)
6094#endif
6095 && !path_with_url(buf->b_fname)
6096 && (force
6097 || buf->b_sfname == NULL
6098 || mch_isFullName(buf->b_sfname)))
6099 {
6100 vim_free(buf->b_sfname);
6101 buf->b_sfname = NULL;
6102 p = shorten_fname(buf->b_ffname, dirname);
6103 if (p != NULL)
6104 {
6105 buf->b_sfname = vim_strsave(p);
6106 buf->b_fname = buf->b_sfname;
6107 }
6108 if (p == NULL || buf->b_fname == NULL)
6109 buf->b_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006110 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00006111
6112 /* Always make the swap file name a full path, a "nofile" buffer may
6113 * also have a swap file. */
6114 mf_fullname(buf->b_ml.ml_mfp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006115 }
6116#ifdef FEAT_WINDOWS
6117 status_redraw_all();
Bram Moolenaar49d7bf12006-02-17 21:45:41 +00006118 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006119#endif
6120}
6121
6122#if (defined(FEAT_DND) && defined(FEAT_GUI_GTK)) \
6123 || defined(FEAT_GUI_MSWIN) \
6124 || defined(FEAT_GUI_MAC) \
6125 || defined(PROTO)
6126/*
6127 * Shorten all filenames in "fnames[count]" by current directory.
6128 */
6129 void
6130shorten_filenames(fnames, count)
6131 char_u **fnames;
6132 int count;
6133{
6134 int i;
6135 char_u dirname[MAXPATHL];
6136 char_u *p;
6137
6138 if (fnames == NULL || count < 1)
6139 return;
6140 mch_dirname(dirname, sizeof(dirname));
6141 for (i = 0; i < count; ++i)
6142 {
6143 if ((p = shorten_fname(fnames[i], dirname)) != NULL)
6144 {
6145 /* shorten_fname() returns pointer in given "fnames[i]". If free
6146 * "fnames[i]" first, "p" becomes invalid. So we need to copy
6147 * "p" first then free fnames[i]. */
6148 p = vim_strsave(p);
6149 vim_free(fnames[i]);
6150 fnames[i] = p;
6151 }
6152 }
6153}
6154#endif
6155
6156/*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006157 * add extension to file name - change path/fo.o.h to path/fo.o.h.ext or
Bram Moolenaar071d4272004-06-13 20:20:40 +00006158 * fo_o_h.ext for MSDOS or when shortname option set.
6159 *
6160 * Assumed that fname is a valid name found in the filesystem we assure that
6161 * the return value is a different name and ends in 'ext'.
6162 * "ext" MUST be at most 4 characters long if it starts with a dot, 3
6163 * characters otherwise.
6164 * Space for the returned name is allocated, must be freed later.
6165 * Returns NULL when out of memory.
6166 */
6167 char_u *
6168modname(fname, ext, prepend_dot)
6169 char_u *fname, *ext;
6170 int prepend_dot; /* may prepend a '.' to file name */
6171{
6172 return buf_modname(
6173#ifdef SHORT_FNAME
6174 TRUE,
6175#else
6176 (curbuf->b_p_sn || curbuf->b_shortname),
6177#endif
6178 fname, ext, prepend_dot);
6179}
6180
6181 char_u *
6182buf_modname(shortname, fname, ext, prepend_dot)
6183 int shortname; /* use 8.3 file name */
6184 char_u *fname, *ext;
6185 int prepend_dot; /* may prepend a '.' to file name */
6186{
6187 char_u *retval;
6188 char_u *s;
6189 char_u *e;
6190 char_u *ptr;
6191 int fnamelen, extlen;
6192
6193 extlen = (int)STRLEN(ext);
6194
6195 /*
6196 * If there is no file name we must get the name of the current directory
6197 * (we need the full path in case :cd is used).
6198 */
6199 if (fname == NULL || *fname == NUL)
6200 {
6201 retval = alloc((unsigned)(MAXPATHL + extlen + 3));
6202 if (retval == NULL)
6203 return NULL;
6204 if (mch_dirname(retval, MAXPATHL) == FAIL ||
6205 (fnamelen = (int)STRLEN(retval)) == 0)
6206 {
6207 vim_free(retval);
6208 return NULL;
6209 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006210 if (!after_pathsep(retval, retval + fnamelen))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006211 {
6212 retval[fnamelen++] = PATHSEP;
6213 retval[fnamelen] = NUL;
6214 }
6215#ifndef SHORT_FNAME
6216 prepend_dot = FALSE; /* nothing to prepend a dot to */
6217#endif
6218 }
6219 else
6220 {
6221 fnamelen = (int)STRLEN(fname);
6222 retval = alloc((unsigned)(fnamelen + extlen + 3));
6223 if (retval == NULL)
6224 return NULL;
6225 STRCPY(retval, fname);
6226#ifdef VMS
6227 vms_remove_version(retval); /* we do not need versions here */
6228#endif
6229 }
6230
6231 /*
6232 * search backwards until we hit a '/', '\' or ':' replacing all '.'
6233 * by '_' for MSDOS or when shortname option set and ext starts with a dot.
6234 * Then truncate what is after the '/', '\' or ':' to 8 characters for
6235 * MSDOS and 26 characters for AMIGA, a lot more for UNIX.
6236 */
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006237 for (ptr = retval + fnamelen; ptr > retval; mb_ptr_back(retval, ptr))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006238 {
6239#ifndef RISCOS
6240 if (*ext == '.'
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006241# ifdef USE_LONG_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00006242 && (!USE_LONG_FNAME || shortname)
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006243# else
6244# ifndef SHORT_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00006245 && shortname
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006246# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006247# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006248 )
6249 if (*ptr == '.') /* replace '.' by '_' */
6250 *ptr = '_';
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006251#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006252 if (vim_ispathsep(*ptr))
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006253 {
6254 ++ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006255 break;
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006256 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006257 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006258
6259 /* the file name has at most BASENAMELEN characters. */
6260#ifndef SHORT_FNAME
6261 if (STRLEN(ptr) > (unsigned)BASENAMELEN)
6262 ptr[BASENAMELEN] = '\0';
6263#endif
6264
6265 s = ptr + STRLEN(ptr);
6266
6267 /*
6268 * For 8.3 file names we may have to reduce the length.
6269 */
6270#ifdef USE_LONG_FNAME
6271 if (!USE_LONG_FNAME || shortname)
6272#else
6273# ifndef SHORT_FNAME
6274 if (shortname)
6275# endif
6276#endif
6277 {
6278 /*
6279 * If there is no file name, or the file name ends in '/', and the
6280 * extension starts with '.', put a '_' before the dot, because just
6281 * ".ext" is invalid.
6282 */
6283 if (fname == NULL || *fname == NUL
6284 || vim_ispathsep(fname[STRLEN(fname) - 1]))
6285 {
6286#ifdef RISCOS
6287 if (*ext == '/')
6288#else
6289 if (*ext == '.')
6290#endif
6291 *s++ = '_';
6292 }
6293 /*
6294 * If the extension starts with '.', truncate the base name at 8
6295 * characters
6296 */
6297#ifdef RISCOS
6298 /* We normally use '/', but swap files are '_' */
6299 else if (*ext == '/' || *ext == '_')
6300#else
6301 else if (*ext == '.')
6302#endif
6303 {
Bram Moolenaar78a15312009-05-15 19:33:18 +00006304 if ((size_t)(s - ptr) > (size_t)8)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006305 {
6306 s = ptr + 8;
6307 *s = '\0';
6308 }
6309 }
6310 /*
6311 * If the extension doesn't start with '.', and the file name
6312 * doesn't have an extension yet, append a '.'
6313 */
6314#ifdef RISCOS
6315 else if ((e = vim_strchr(ptr, '/')) == NULL)
6316 *s++ = '/';
6317#else
6318 else if ((e = vim_strchr(ptr, '.')) == NULL)
6319 *s++ = '.';
6320#endif
6321 /*
6322 * If the extension doesn't start with '.', and there already is an
Bram Moolenaar7263a772007-05-10 17:35:54 +00006323 * extension, it may need to be truncated
Bram Moolenaar071d4272004-06-13 20:20:40 +00006324 */
6325 else if ((int)STRLEN(e) + extlen > 4)
6326 s = e + 4 - extlen;
6327 }
6328#if defined(OS2) || defined(USE_LONG_FNAME) || defined(WIN3264)
6329 /*
6330 * If there is no file name, and the extension starts with '.', put a
6331 * '_' before the dot, because just ".ext" may be invalid if it's on a
6332 * FAT partition, and on HPFS it doesn't matter.
6333 */
6334 else if ((fname == NULL || *fname == NUL) && *ext == '.')
6335 *s++ = '_';
6336#endif
6337
6338 /*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006339 * Append the extension.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006340 * ext can start with '.' and cannot exceed 3 more characters.
6341 */
6342 STRCPY(s, ext);
6343
6344#ifndef SHORT_FNAME
6345 /*
6346 * Prepend the dot.
6347 */
6348 if (prepend_dot && !shortname && *(e = gettail(retval)) !=
6349#ifdef RISCOS
6350 '/'
6351#else
6352 '.'
6353#endif
6354#ifdef USE_LONG_FNAME
6355 && USE_LONG_FNAME
6356#endif
6357 )
6358 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006359 STRMOVE(e + 1, e);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006360#ifdef RISCOS
6361 *e = '/';
6362#else
6363 *e = '.';
6364#endif
6365 }
6366#endif
6367
6368 /*
6369 * Check that, after appending the extension, the file name is really
6370 * different.
6371 */
6372 if (fname != NULL && STRCMP(fname, retval) == 0)
6373 {
6374 /* we search for a character that can be replaced by '_' */
6375 while (--s >= ptr)
6376 {
6377 if (*s != '_')
6378 {
6379 *s = '_';
6380 break;
6381 }
6382 }
6383 if (s < ptr) /* fname was "________.<ext>", how tricky! */
6384 *ptr = 'v';
6385 }
6386 return retval;
6387}
6388
6389/*
6390 * Like fgets(), but if the file line is too long, it is truncated and the
6391 * rest of the line is thrown away. Returns TRUE for end-of-file.
6392 */
6393 int
6394vim_fgets(buf, size, fp)
6395 char_u *buf;
6396 int size;
6397 FILE *fp;
6398{
6399 char *eof;
6400#define FGETS_SIZE 200
6401 char tbuf[FGETS_SIZE];
6402
6403 buf[size - 2] = NUL;
6404#ifdef USE_CR
6405 eof = fgets_cr((char *)buf, size, fp);
6406#else
6407 eof = fgets((char *)buf, size, fp);
6408#endif
6409 if (buf[size - 2] != NUL && buf[size - 2] != '\n')
6410 {
6411 buf[size - 1] = NUL; /* Truncate the line */
6412
6413 /* Now throw away the rest of the line: */
6414 do
6415 {
6416 tbuf[FGETS_SIZE - 2] = NUL;
6417#ifdef USE_CR
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006418 ignoredp = fgets_cr((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006419#else
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006420 ignoredp = fgets((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006421#endif
6422 } while (tbuf[FGETS_SIZE - 2] != NUL && tbuf[FGETS_SIZE - 2] != '\n');
6423 }
6424 return (eof == NULL);
6425}
6426
6427#if defined(USE_CR) || defined(PROTO)
6428/*
6429 * Like vim_fgets(), but accept any line terminator: CR, CR-LF or LF.
6430 * Returns TRUE for end-of-file.
6431 * Only used for the Mac, because it's much slower than vim_fgets().
6432 */
6433 int
6434tag_fgets(buf, size, fp)
6435 char_u *buf;
6436 int size;
6437 FILE *fp;
6438{
6439 int i = 0;
6440 int c;
6441 int eof = FALSE;
6442
6443 for (;;)
6444 {
6445 c = fgetc(fp);
6446 if (c == EOF)
6447 {
6448 eof = TRUE;
6449 break;
6450 }
6451 if (c == '\r')
6452 {
6453 /* Always store a NL for end-of-line. */
6454 if (i < size - 1)
6455 buf[i++] = '\n';
6456 c = fgetc(fp);
6457 if (c != '\n') /* Macintosh format: single CR. */
6458 ungetc(c, fp);
6459 break;
6460 }
6461 if (i < size - 1)
6462 buf[i++] = c;
6463 if (c == '\n')
6464 break;
6465 }
6466 buf[i] = NUL;
6467 return eof;
6468}
6469#endif
6470
6471/*
6472 * rename() only works if both files are on the same file system, this
6473 * function will (attempts to?) copy the file across if rename fails -- webb
6474 * Return -1 for failure, 0 for success.
6475 */
6476 int
6477vim_rename(from, to)
6478 char_u *from;
6479 char_u *to;
6480{
6481 int fd_in;
6482 int fd_out;
6483 int n;
6484 char *errmsg = NULL;
6485 char *buffer;
6486#ifdef AMIGA
6487 BPTR flock;
6488#endif
6489 struct stat st;
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006490 long perm;
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006491#ifdef HAVE_ACL
6492 vim_acl_T acl; /* ACL from original file */
6493#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006494#if defined(UNIX) || defined(CASE_INSENSITIVE_FILENAME)
6495 int use_tmp_file = FALSE;
6496#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006497
6498 /*
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006499 * When the names are identical, there is nothing to do. When they refer
6500 * to the same file (ignoring case and slash/backslash differences) but
6501 * the file name differs we need to go through a temp file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006502 */
6503 if (fnamecmp(from, to) == 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006504 {
6505#ifdef CASE_INSENSITIVE_FILENAME
6506 if (STRCMP(gettail(from), gettail(to)) != 0)
6507 use_tmp_file = TRUE;
6508 else
6509#endif
6510 return 0;
6511 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006512
6513 /*
6514 * Fail if the "from" file doesn't exist. Avoids that "to" is deleted.
6515 */
6516 if (mch_stat((char *)from, &st) < 0)
6517 return -1;
6518
Bram Moolenaar3576da72008-12-30 15:15:57 +00006519#ifdef UNIX
6520 {
6521 struct stat st_to;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006522
6523 /* It's possible for the source and destination to be the same file.
6524 * This happens when "from" and "to" differ in case and are on a FAT32
6525 * filesystem. In that case go through a temp file name. */
6526 if (mch_stat((char *)to, &st_to) >= 0
6527 && st.st_dev == st_to.st_dev
6528 && st.st_ino == st_to.st_ino)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006529 use_tmp_file = TRUE;
6530 }
6531#endif
6532
6533#if defined(UNIX) || defined(CASE_INSENSITIVE_FILENAME)
6534 if (use_tmp_file)
6535 {
6536 char tempname[MAXPATHL + 1];
6537
6538 /*
6539 * Find a name that doesn't exist and is in the same directory.
6540 * Rename "from" to "tempname" and then rename "tempname" to "to".
6541 */
6542 if (STRLEN(from) >= MAXPATHL - 5)
6543 return -1;
6544 STRCPY(tempname, from);
6545 for (n = 123; n < 99999; ++n)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006546 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006547 sprintf((char *)gettail((char_u *)tempname), "%d", n);
6548 if (mch_stat(tempname, &st) < 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006549 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006550 if (mch_rename((char *)from, tempname) == 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006551 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006552 if (mch_rename(tempname, (char *)to) == 0)
6553 return 0;
6554 /* Strange, the second step failed. Try moving the
6555 * file back and return failure. */
6556 mch_rename(tempname, (char *)from);
Bram Moolenaar3576da72008-12-30 15:15:57 +00006557 return -1;
6558 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006559 /* If it fails for one temp name it will most likely fail
6560 * for any temp name, give up. */
6561 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006562 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006563 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006564 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006565 }
6566#endif
6567
Bram Moolenaar071d4272004-06-13 20:20:40 +00006568 /*
6569 * Delete the "to" file, this is required on some systems to make the
6570 * mch_rename() work, on other systems it makes sure that we don't have
6571 * two files when the mch_rename() fails.
6572 */
6573
6574#ifdef AMIGA
6575 /*
6576 * With MSDOS-compatible filesystems (crossdos, messydos) it is possible
6577 * that the name of the "to" file is the same as the "from" file, even
Bram Moolenaar7263a772007-05-10 17:35:54 +00006578 * though the names are different. To avoid the chance of accidentally
Bram Moolenaar071d4272004-06-13 20:20:40 +00006579 * deleting the "from" file (horror!) we lock it during the remove.
6580 *
6581 * When used for making a backup before writing the file: This should not
6582 * happen with ":w", because startscript() should detect this problem and
6583 * set buf->b_shortname, causing modname() to return a correct ".bak" file
6584 * name. This problem does exist with ":w filename", but then the
6585 * original file will be somewhere else so the backup isn't really
6586 * important. If autoscripting is off the rename may fail.
6587 */
6588 flock = Lock((UBYTE *)from, (long)ACCESS_READ);
6589#endif
6590 mch_remove(to);
6591#ifdef AMIGA
6592 if (flock)
6593 UnLock(flock);
6594#endif
6595
6596 /*
6597 * First try a normal rename, return if it works.
6598 */
6599 if (mch_rename((char *)from, (char *)to) == 0)
6600 return 0;
6601
6602 /*
6603 * Rename() failed, try copying the file.
6604 */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006605 perm = mch_getperm(from);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006606#ifdef HAVE_ACL
6607 /* For systems that support ACL: get the ACL from the original file. */
6608 acl = mch_get_acl(from);
6609#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006610 fd_in = mch_open((char *)from, O_RDONLY|O_EXTRA, 0);
6611 if (fd_in == -1)
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006612 {
6613#ifdef HAVE_ACL
6614 mch_free_acl(acl);
6615#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006616 return -1;
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006617 }
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006618
6619 /* Create the new file with same permissions as the original. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00006620 fd_out = mch_open((char *)to,
6621 O_CREAT|O_EXCL|O_WRONLY|O_EXTRA|O_NOFOLLOW, (int)perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006622 if (fd_out == -1)
6623 {
6624 close(fd_in);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006625#ifdef HAVE_ACL
6626 mch_free_acl(acl);
6627#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006628 return -1;
6629 }
6630
6631 buffer = (char *)alloc(BUFSIZE);
6632 if (buffer == NULL)
6633 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006634 close(fd_out);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006635 close(fd_in);
6636#ifdef HAVE_ACL
6637 mch_free_acl(acl);
6638#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006639 return -1;
6640 }
6641
6642 while ((n = vim_read(fd_in, buffer, BUFSIZE)) > 0)
6643 if (vim_write(fd_out, buffer, n) != n)
6644 {
6645 errmsg = _("E208: Error writing to \"%s\"");
6646 break;
6647 }
6648
6649 vim_free(buffer);
6650 close(fd_in);
6651 if (close(fd_out) < 0)
6652 errmsg = _("E209: Error closing \"%s\"");
6653 if (n < 0)
6654 {
6655 errmsg = _("E210: Error reading \"%s\"");
6656 to = from;
6657 }
Bram Moolenaar7263a772007-05-10 17:35:54 +00006658#ifndef UNIX /* for Unix mch_open() already set the permission */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006659 mch_setperm(to, perm);
Bram Moolenaarc6039d82005-12-02 00:44:04 +00006660#endif
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006661#ifdef HAVE_ACL
6662 mch_set_acl(to, acl);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006663 mch_free_acl(acl);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006664#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006665 if (errmsg != NULL)
6666 {
6667 EMSG2(errmsg, to);
6668 return -1;
6669 }
6670 mch_remove(from);
6671 return 0;
6672}
6673
6674static int already_warned = FALSE;
6675
6676/*
6677 * Check if any not hidden buffer has been changed.
6678 * Postpone the check if there are characters in the stuff buffer, a global
6679 * command is being executed, a mapping is being executed or an autocommand is
6680 * busy.
6681 * Returns TRUE if some message was written (screen should be redrawn and
6682 * cursor positioned).
6683 */
6684 int
6685check_timestamps(focus)
6686 int focus; /* called for GUI focus event */
6687{
6688 buf_T *buf;
6689 int didit = 0;
6690 int n;
6691
6692 /* Don't check timestamps while system() or another low-level function may
6693 * cause us to lose and gain focus. */
6694 if (no_check_timestamps > 0)
6695 return FALSE;
6696
6697 /* Avoid doing a check twice. The OK/Reload dialog can cause a focus
6698 * event and we would keep on checking if the file is steadily growing.
6699 * Do check again after typing something. */
6700 if (focus && did_check_timestamps)
6701 {
6702 need_check_timestamps = TRUE;
6703 return FALSE;
6704 }
6705
6706 if (!stuff_empty() || global_busy || !typebuf_typed()
6707#ifdef FEAT_AUTOCMD
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006708 || autocmd_busy || curbuf_lock > 0 || allbuf_lock > 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00006709#endif
6710 )
6711 need_check_timestamps = TRUE; /* check later */
6712 else
6713 {
6714 ++no_wait_return;
6715 did_check_timestamps = TRUE;
6716 already_warned = FALSE;
6717 for (buf = firstbuf; buf != NULL; )
6718 {
6719 /* Only check buffers in a window. */
6720 if (buf->b_nwindows > 0)
6721 {
6722 n = buf_check_timestamp(buf, focus);
6723 if (didit < n)
6724 didit = n;
6725 if (n > 0 && !buf_valid(buf))
6726 {
6727 /* Autocommands have removed the buffer, start at the
6728 * first one again. */
6729 buf = firstbuf;
6730 continue;
6731 }
6732 }
6733 buf = buf->b_next;
6734 }
6735 --no_wait_return;
6736 need_check_timestamps = FALSE;
6737 if (need_wait_return && didit == 2)
6738 {
6739 /* make sure msg isn't overwritten */
6740 msg_puts((char_u *)"\n");
6741 out_flush();
6742 }
6743 }
6744 return didit;
6745}
6746
6747/*
6748 * Move all the lines from buffer "frombuf" to buffer "tobuf".
6749 * Return OK or FAIL. When FAIL "tobuf" is incomplete and/or "frombuf" is not
6750 * empty.
6751 */
6752 static int
6753move_lines(frombuf, tobuf)
6754 buf_T *frombuf;
6755 buf_T *tobuf;
6756{
6757 buf_T *tbuf = curbuf;
6758 int retval = OK;
6759 linenr_T lnum;
6760 char_u *p;
6761
6762 /* Copy the lines in "frombuf" to "tobuf". */
6763 curbuf = tobuf;
6764 for (lnum = 1; lnum <= frombuf->b_ml.ml_line_count; ++lnum)
6765 {
6766 p = vim_strsave(ml_get_buf(frombuf, lnum, FALSE));
6767 if (p == NULL || ml_append(lnum - 1, p, 0, FALSE) == FAIL)
6768 {
6769 vim_free(p);
6770 retval = FAIL;
6771 break;
6772 }
6773 vim_free(p);
6774 }
6775
6776 /* Delete all the lines in "frombuf". */
6777 if (retval != FAIL)
6778 {
6779 curbuf = frombuf;
Bram Moolenaar9460b9d2007-01-09 14:37:01 +00006780 for (lnum = curbuf->b_ml.ml_line_count; lnum > 0; --lnum)
6781 if (ml_delete(lnum, FALSE) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006782 {
6783 /* Oops! We could try putting back the saved lines, but that
6784 * might fail again... */
6785 retval = FAIL;
6786 break;
6787 }
6788 }
6789
6790 curbuf = tbuf;
6791 return retval;
6792}
6793
6794/*
6795 * Check if buffer "buf" has been changed.
6796 * Also check if the file for a new buffer unexpectedly appeared.
6797 * return 1 if a changed buffer was found.
6798 * return 2 if a message has been displayed.
6799 * return 0 otherwise.
6800 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006801 int
6802buf_check_timestamp(buf, focus)
6803 buf_T *buf;
Bram Moolenaar78a15312009-05-15 19:33:18 +00006804 int focus UNUSED; /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006805{
6806 struct stat st;
6807 int stat_res;
6808 int retval = 0;
6809 char_u *path;
6810 char_u *tbuf;
6811 char *mesg = NULL;
Bram Moolenaar44ecf652005-03-07 23:09:59 +00006812 char *mesg2 = "";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006813 int helpmesg = FALSE;
6814 int reload = FALSE;
6815#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6816 int can_reload = FALSE;
6817#endif
Bram Moolenaar914703b2010-05-31 21:59:46 +02006818 off_t orig_size = buf->b_orig_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006819 int orig_mode = buf->b_orig_mode;
6820#ifdef FEAT_GUI
6821 int save_mouse_correct = need_mouse_correct;
6822#endif
6823#ifdef FEAT_AUTOCMD
6824 static int busy = FALSE;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006825 int n;
6826 char_u *s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006827#endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006828 char *reason;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006829
6830 /* If there is no file name, the buffer is not loaded, 'buftype' is
6831 * set, we are in the middle of a save or being called recursively: ignore
6832 * this buffer. */
6833 if (buf->b_ffname == NULL
6834 || buf->b_ml.ml_mfp == NULL
6835#if defined(FEAT_QUICKFIX)
6836 || *buf->b_p_bt != NUL
6837#endif
6838 || buf->b_saving
6839#ifdef FEAT_AUTOCMD
6840 || busy
6841#endif
Bram Moolenaar009b2592004-10-24 19:18:58 +00006842#ifdef FEAT_NETBEANS_INTG
6843 || isNetbeansBuffer(buf)
6844#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006845 )
6846 return 0;
6847
6848 if ( !(buf->b_flags & BF_NOTEDITED)
6849 && buf->b_mtime != 0
6850 && ((stat_res = mch_stat((char *)buf->b_ffname, &st)) < 0
6851 || time_differs((long)st.st_mtime, buf->b_mtime)
6852#ifdef HAVE_ST_MODE
6853 || (int)st.st_mode != buf->b_orig_mode
6854#else
6855 || mch_getperm(buf->b_ffname) != buf->b_orig_mode
6856#endif
6857 ))
6858 {
6859 retval = 1;
6860
Bram Moolenaar316059c2006-01-14 21:18:42 +00006861 /* set b_mtime to stop further warnings (e.g., when executing
6862 * FileChangedShell autocmd) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006863 if (stat_res < 0)
6864 {
6865 buf->b_mtime = 0;
6866 buf->b_orig_size = 0;
6867 buf->b_orig_mode = 0;
6868 }
6869 else
6870 buf_store_time(buf, &st, buf->b_ffname);
6871
6872 /* Don't do anything for a directory. Might contain the file
6873 * explorer. */
6874 if (mch_isdir(buf->b_fname))
6875 ;
6876
6877 /*
6878 * If 'autoread' is set, the buffer has no changes and the file still
6879 * exists, reload the buffer. Use the buffer-local option value if it
6880 * was set, the global option value otherwise.
6881 */
6882 else if ((buf->b_p_ar >= 0 ? buf->b_p_ar : p_ar)
6883 && !bufIsChanged(buf) && stat_res >= 0)
6884 reload = TRUE;
6885 else
6886 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006887 if (stat_res < 0)
6888 reason = "deleted";
6889 else if (bufIsChanged(buf))
6890 reason = "conflict";
6891 else if (orig_size != buf->b_orig_size || buf_contents_changed(buf))
6892 reason = "changed";
6893 else if (orig_mode != buf->b_orig_mode)
6894 reason = "mode";
6895 else
6896 reason = "time";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006897
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006898#ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006899 /*
6900 * Only give the warning if there are no FileChangedShell
6901 * autocommands.
6902 * Avoid being called recursively by setting "busy".
6903 */
6904 busy = TRUE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00006905# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006906 set_vim_var_string(VV_FCS_REASON, (char_u *)reason, -1);
6907 set_vim_var_string(VV_FCS_CHOICE, (char_u *)"", -1);
Bram Moolenaar1e015462005-09-25 22:16:38 +00006908# endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006909 ++allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006910 n = apply_autocmds(EVENT_FILECHANGEDSHELL,
6911 buf->b_fname, buf->b_fname, FALSE, buf);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006912 --allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006913 busy = FALSE;
6914 if (n)
6915 {
6916 if (!buf_valid(buf))
6917 EMSG(_("E246: FileChangedShell autocommand deleted buffer"));
Bram Moolenaar1e015462005-09-25 22:16:38 +00006918# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006919 s = get_vim_var_str(VV_FCS_CHOICE);
6920 if (STRCMP(s, "reload") == 0 && *reason != 'd')
6921 reload = TRUE;
6922 else if (STRCMP(s, "ask") == 0)
6923 n = FALSE;
6924 else
Bram Moolenaar1e015462005-09-25 22:16:38 +00006925# endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006926 return 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006927 }
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006928 if (!n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006929#endif
6930 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006931 if (*reason == 'd')
6932 mesg = _("E211: File \"%s\" no longer available");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006933 else
6934 {
6935 helpmesg = TRUE;
6936#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6937 can_reload = TRUE;
6938#endif
6939 /*
6940 * Check if the file contents really changed to avoid
6941 * giving a warning when only the timestamp was set (e.g.,
6942 * checked out of CVS). Always warn when the buffer was
6943 * changed.
6944 */
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006945 if (reason[2] == 'n')
6946 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006947 mesg = _("W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006948 mesg2 = _("See \":help W12\" for more info.");
6949 }
6950 else if (reason[1] == 'h')
6951 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006952 mesg = _("W11: Warning: File \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006953 mesg2 = _("See \":help W11\" for more info.");
6954 }
6955 else if (*reason == 'm')
6956 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006957 mesg = _("W16: Warning: Mode of file \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006958 mesg2 = _("See \":help W16\" for more info.");
6959 }
Bram Moolenaar85388b52009-06-24 09:58:32 +00006960 else
6961 /* Only timestamp changed, store it to avoid a warning
6962 * in check_mtime() later. */
6963 buf->b_mtime_read = buf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006964 }
6965 }
6966 }
6967
6968 }
6969 else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W)
6970 && vim_fexists(buf->b_ffname))
6971 {
6972 retval = 1;
6973 mesg = _("W13: Warning: File \"%s\" has been created after editing started");
6974 buf->b_flags |= BF_NEW_W;
6975#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6976 can_reload = TRUE;
6977#endif
6978 }
6979
6980 if (mesg != NULL)
6981 {
6982 path = home_replace_save(buf, buf->b_fname);
6983 if (path != NULL)
6984 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006985 if (!helpmesg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006986 mesg2 = "";
6987 tbuf = alloc((unsigned)(STRLEN(path) + STRLEN(mesg)
6988 + STRLEN(mesg2) + 2));
6989 sprintf((char *)tbuf, mesg, path);
Bram Moolenaar496c5262009-03-18 14:42:00 +00006990#ifdef FEAT_EVAL
6991 /* Set warningmsg here, before the unimportant and output-specific
6992 * mesg2 has been appended. */
6993 set_vim_var_string(VV_WARNINGMSG, tbuf, -1);
6994#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006995#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6996 if (can_reload)
6997 {
6998 if (*mesg2 != NUL)
6999 {
7000 STRCAT(tbuf, "\n");
7001 STRCAT(tbuf, mesg2);
7002 }
7003 if (do_dialog(VIM_WARNING, (char_u *)_("Warning"), tbuf,
7004 (char_u *)_("&OK\n&Load File"), 1, NULL) == 2)
7005 reload = TRUE;
7006 }
7007 else
7008#endif
7009 if (State > NORMAL_BUSY || (State & CMDLINE) || already_warned)
7010 {
7011 if (*mesg2 != NUL)
7012 {
7013 STRCAT(tbuf, "; ");
7014 STRCAT(tbuf, mesg2);
7015 }
7016 EMSG(tbuf);
7017 retval = 2;
7018 }
7019 else
7020 {
Bram Moolenaared203462004-06-16 11:19:22 +00007021# ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00007022 if (!autocmd_busy)
Bram Moolenaared203462004-06-16 11:19:22 +00007023# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007024 {
7025 msg_start();
7026 msg_puts_attr(tbuf, hl_attr(HLF_E) + MSG_HIST);
7027 if (*mesg2 != NUL)
7028 msg_puts_attr((char_u *)mesg2,
7029 hl_attr(HLF_W) + MSG_HIST);
7030 msg_clr_eos();
7031 (void)msg_end();
7032 if (emsg_silent == 0)
7033 {
7034 out_flush();
Bram Moolenaared203462004-06-16 11:19:22 +00007035# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00007036 if (!focus)
Bram Moolenaared203462004-06-16 11:19:22 +00007037# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007038 /* give the user some time to think about it */
7039 ui_delay(1000L, TRUE);
7040
7041 /* don't redraw and erase the message */
7042 redraw_cmdline = FALSE;
7043 }
7044 }
7045 already_warned = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007046 }
7047
7048 vim_free(path);
7049 vim_free(tbuf);
7050 }
7051 }
7052
7053 if (reload)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007054 /* Reload the buffer. */
Bram Moolenaar316059c2006-01-14 21:18:42 +00007055 buf_reload(buf, orig_mode);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007056
Bram Moolenaar56718732006-03-15 22:53:57 +00007057#ifdef FEAT_AUTOCMD
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00007058 /* Trigger FileChangedShell when the file was changed in any way. */
7059 if (buf_valid(buf) && retval != 0)
Bram Moolenaar56718732006-03-15 22:53:57 +00007060 (void)apply_autocmds(EVENT_FILECHANGEDSHELLPOST,
7061 buf->b_fname, buf->b_fname, FALSE, buf);
7062#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007063#ifdef FEAT_GUI
7064 /* restore this in case an autocommand has set it; it would break
7065 * 'mousefocus' */
7066 need_mouse_correct = save_mouse_correct;
7067#endif
7068
7069 return retval;
7070}
7071
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007072/*
7073 * Reload a buffer that is already loaded.
7074 * Used when the file was changed outside of Vim.
Bram Moolenaar316059c2006-01-14 21:18:42 +00007075 * "orig_mode" is buf->b_orig_mode before the need for reloading was detected.
7076 * buf->b_orig_mode may have been reset already.
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007077 */
7078 void
Bram Moolenaar316059c2006-01-14 21:18:42 +00007079buf_reload(buf, orig_mode)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007080 buf_T *buf;
Bram Moolenaar316059c2006-01-14 21:18:42 +00007081 int orig_mode;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007082{
7083 exarg_T ea;
7084 pos_T old_cursor;
7085 linenr_T old_topline;
7086 int old_ro = buf->b_p_ro;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007087 buf_T *savebuf;
7088 int saved = OK;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007089 aco_save_T aco;
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007090 int flags = READ_NEW;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007091
7092 /* set curwin/curbuf for "buf" and save some things */
7093 aucmd_prepbuf(&aco, buf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007094
7095 /* We only want to read the text from the file, not reset the syntax
7096 * highlighting, clear marks, diff status, etc. Force the fileformat
7097 * and encoding to be the same. */
7098 if (prep_exarg(&ea, buf) == OK)
7099 {
7100 old_cursor = curwin->w_cursor;
7101 old_topline = curwin->w_topline;
7102
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007103 if (p_ur < 0 || curbuf->b_ml.ml_line_count <= p_ur)
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007104 {
7105 /* Save all the text, so that the reload can be undone.
7106 * Sync first so that this is a separate undo-able action. */
7107 u_sync(FALSE);
7108 saved = u_savecommon(0, curbuf->b_ml.ml_line_count + 1, 0, TRUE);
7109 flags |= READ_KEEP_UNDO;
7110 }
7111
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007112 /*
7113 * To behave like when a new file is edited (matters for
7114 * BufReadPost autocommands) we first need to delete the current
7115 * buffer contents. But if reading the file fails we should keep
7116 * the old contents. Can't use memory only, the file might be
7117 * too big. Use a hidden buffer to move the buffer contents to.
7118 */
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007119 if (bufempty() || saved == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007120 savebuf = NULL;
7121 else
7122 {
7123 /* Allocate a buffer without putting it in the buffer list. */
7124 savebuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007125 if (savebuf != NULL && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007126 {
7127 /* Open the memline. */
7128 curbuf = savebuf;
7129 curwin->w_buffer = savebuf;
Bram Moolenaar4770d092006-01-12 23:22:24 +00007130 saved = ml_open(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007131 curbuf = buf;
7132 curwin->w_buffer = buf;
7133 }
Bram Moolenaar8424a622006-04-19 21:23:36 +00007134 if (savebuf == NULL || saved == FAIL || buf != curbuf
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007135 || move_lines(buf, savebuf) == FAIL)
7136 {
7137 EMSG2(_("E462: Could not prepare for reloading \"%s\""),
7138 buf->b_fname);
7139 saved = FAIL;
7140 }
7141 }
7142
7143 if (saved == OK)
7144 {
7145 curbuf->b_flags |= BF_CHECK_RO; /* check for RO again */
7146#ifdef FEAT_AUTOCMD
7147 keep_filetype = TRUE; /* don't detect 'filetype' */
7148#endif
7149 if (readfile(buf->b_ffname, buf->b_fname, (linenr_T)0,
7150 (linenr_T)0,
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007151 (linenr_T)MAXLNUM, &ea, flags) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007152 {
7153#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
7154 if (!aborting())
7155#endif
7156 EMSG2(_("E321: Could not reload \"%s\""), buf->b_fname);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007157 if (savebuf != NULL && buf_valid(savebuf) && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007158 {
7159 /* Put the text back from the save buffer. First
7160 * delete any lines that readfile() added. */
7161 while (!bufempty())
Bram Moolenaar8424a622006-04-19 21:23:36 +00007162 if (ml_delete(buf->b_ml.ml_line_count, FALSE) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007163 break;
7164 (void)move_lines(savebuf, buf);
7165 }
7166 }
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007167 else if (buf == curbuf) /* "buf" still valid */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007168 {
7169 /* Mark the buffer as unmodified and free undo info. */
7170 unchanged(buf, TRUE);
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007171 if ((flags & READ_KEEP_UNDO) == 0)
7172 {
7173 u_blockfree(buf);
7174 u_clearall(buf);
7175 }
7176 else
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007177 {
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007178 /* Mark all undo states as changed. */
7179 u_unchanged(curbuf);
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007180 }
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007181 }
7182 }
7183 vim_free(ea.cmd);
7184
Bram Moolenaar8424a622006-04-19 21:23:36 +00007185 if (savebuf != NULL && buf_valid(savebuf))
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007186 wipe_buffer(savebuf, FALSE);
7187
7188#ifdef FEAT_DIFF
7189 /* Invalidate diff info if necessary. */
Bram Moolenaar8424a622006-04-19 21:23:36 +00007190 diff_invalidate(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007191#endif
7192
7193 /* Restore the topline and cursor position and check it (lines may
7194 * have been removed). */
7195 if (old_topline > curbuf->b_ml.ml_line_count)
7196 curwin->w_topline = curbuf->b_ml.ml_line_count;
7197 else
7198 curwin->w_topline = old_topline;
7199 curwin->w_cursor = old_cursor;
7200 check_cursor();
7201 update_topline();
7202#ifdef FEAT_AUTOCMD
7203 keep_filetype = FALSE;
7204#endif
7205#ifdef FEAT_FOLDING
7206 {
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007207 win_T *wp;
7208 tabpage_T *tp;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007209
7210 /* Update folds unless they are defined manually. */
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007211 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007212 if (wp->w_buffer == curwin->w_buffer
7213 && !foldmethodIsManual(wp))
7214 foldUpdateAll(wp);
7215 }
7216#endif
7217 /* If the mode didn't change and 'readonly' was set, keep the old
7218 * value; the user probably used the ":view" command. But don't
7219 * reset it, might have had a read error. */
7220 if (orig_mode == curbuf->b_orig_mode)
7221 curbuf->b_p_ro |= old_ro;
7222 }
7223
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007224 /* restore curwin/curbuf and a few other things */
7225 aucmd_restbuf(&aco);
7226 /* Careful: autocommands may have made "buf" invalid! */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007227}
7228
Bram Moolenaar071d4272004-06-13 20:20:40 +00007229 void
7230buf_store_time(buf, st, fname)
7231 buf_T *buf;
7232 struct stat *st;
Bram Moolenaar78a15312009-05-15 19:33:18 +00007233 char_u *fname UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007234{
7235 buf->b_mtime = (long)st->st_mtime;
Bram Moolenaar914703b2010-05-31 21:59:46 +02007236 buf->b_orig_size = st->st_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007237#ifdef HAVE_ST_MODE
7238 buf->b_orig_mode = (int)st->st_mode;
7239#else
7240 buf->b_orig_mode = mch_getperm(fname);
7241#endif
7242}
7243
7244/*
7245 * Adjust the line with missing eol, used for the next write.
7246 * Used for do_filter(), when the input lines for the filter are deleted.
7247 */
7248 void
7249write_lnum_adjust(offset)
7250 linenr_T offset;
7251{
Bram Moolenaardf177f62005-02-22 08:39:57 +00007252 if (write_no_eol_lnum != 0) /* only if there is a missing eol */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007253 write_no_eol_lnum += offset;
7254}
7255
7256#if defined(TEMPDIRNAMES) || defined(PROTO)
7257static long temp_count = 0; /* Temp filename counter. */
7258
7259/*
7260 * Delete the temp directory and all files it contains.
7261 */
7262 void
7263vim_deltempdir()
7264{
7265 char_u **files;
7266 int file_count;
7267 int i;
7268
7269 if (vim_tempdir != NULL)
7270 {
7271 sprintf((char *)NameBuff, "%s*", vim_tempdir);
7272 if (gen_expand_wildcards(1, &NameBuff, &file_count, &files,
7273 EW_DIR|EW_FILE|EW_SILENT) == OK)
7274 {
7275 for (i = 0; i < file_count; ++i)
7276 mch_remove(files[i]);
7277 FreeWild(file_count, files);
7278 }
7279 gettail(NameBuff)[-1] = NUL;
7280 (void)mch_rmdir(NameBuff);
7281
7282 vim_free(vim_tempdir);
7283 vim_tempdir = NULL;
7284 }
7285}
7286#endif
7287
Bram Moolenaar4592dee2009-11-18 19:11:58 +00007288#ifdef TEMPDIRNAMES
Bram Moolenaar071d4272004-06-13 20:20:40 +00007289/*
Bram Moolenaareaf03392009-11-17 11:08:52 +00007290 * Directory "tempdir" was created. Expand this name to a full path and put
7291 * it in "vim_tempdir". This avoids that using ":cd" would confuse us.
7292 * "tempdir" must be no longer than MAXPATHL.
7293 */
7294 static void
7295vim_settempdir(tempdir)
7296 char_u *tempdir;
7297{
7298 char_u *buf;
7299
7300 buf = alloc((unsigned)MAXPATHL + 2);
7301 if (buf != NULL)
7302 {
7303 if (vim_FullName(tempdir, buf, MAXPATHL, FALSE) == FAIL)
7304 STRCPY(buf, tempdir);
7305# ifdef __EMX__
7306 if (vim_strchr(buf, '/') != NULL)
7307 STRCAT(buf, "/");
7308 else
7309# endif
7310 add_pathsep(buf);
7311 vim_tempdir = vim_strsave(buf);
7312 vim_free(buf);
7313 }
7314}
Bram Moolenaar4592dee2009-11-18 19:11:58 +00007315#endif
Bram Moolenaareaf03392009-11-17 11:08:52 +00007316
7317/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007318 * vim_tempname(): Return a unique name that can be used for a temp file.
7319 *
7320 * The temp file is NOT created.
7321 *
7322 * The returned pointer is to allocated memory.
7323 * The returned pointer is NULL if no valid name was found.
7324 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007325 char_u *
7326vim_tempname(extra_char)
Bram Moolenaar78a15312009-05-15 19:33:18 +00007327 int extra_char UNUSED; /* char to use in the name instead of '?' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007328{
7329#ifdef USE_TMPNAM
7330 char_u itmp[L_tmpnam]; /* use tmpnam() */
7331#else
7332 char_u itmp[TEMPNAMELEN];
7333#endif
7334
7335#ifdef TEMPDIRNAMES
7336 static char *(tempdirs[]) = {TEMPDIRNAMES};
7337 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007338# ifndef EEXIST
7339 struct stat st;
7340# endif
7341
7342 /*
7343 * This will create a directory for private use by this instance of Vim.
7344 * This is done once, and the same directory is used for all temp files.
7345 * This method avoids security problems because of symlink attacks et al.
7346 * It's also a bit faster, because we only need to check for an existing
7347 * file when creating the directory and not for each temp file.
7348 */
7349 if (vim_tempdir == NULL)
7350 {
7351 /*
7352 * Try the entries in TEMPDIRNAMES to create the temp directory.
7353 */
Bram Moolenaar78a15312009-05-15 19:33:18 +00007354 for (i = 0; i < (int)(sizeof(tempdirs) / sizeof(char *)); ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007355 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007356# ifndef HAVE_MKDTEMP
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007357 size_t itmplen;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007358 long nr;
7359 long off;
7360# endif
7361
Bram Moolenaar071d4272004-06-13 20:20:40 +00007362 /* expand $TMP, leave room for "/v1100000/999999999" */
7363 expand_env((char_u *)tempdirs[i], itmp, TEMPNAMELEN - 20);
7364 if (mch_isdir(itmp)) /* directory exists */
7365 {
7366# ifdef __EMX__
7367 /* If $TMP contains a forward slash (perhaps using bash or
7368 * tcsh), don't add a backslash, use a forward slash!
7369 * Adding 2 backslashes didn't work. */
7370 if (vim_strchr(itmp, '/') != NULL)
7371 STRCAT(itmp, "/");
7372 else
7373# endif
7374 add_pathsep(itmp);
7375
Bram Moolenaareaf03392009-11-17 11:08:52 +00007376# ifdef HAVE_MKDTEMP
7377 /* Leave room for filename */
7378 STRCAT(itmp, "vXXXXXX");
7379 if (mkdtemp((char *)itmp) != NULL)
7380 vim_settempdir(itmp);
7381# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007382 /* Get an arbitrary number of up to 6 digits. When it's
7383 * unlikely that it already exists it will be faster,
7384 * otherwise it doesn't matter. The use of mkdir() avoids any
7385 * security problems because of the predictable number. */
7386 nr = (mch_get_pid() + (long)time(NULL)) % 1000000L;
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007387 itmplen = STRLEN(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007388
7389 /* Try up to 10000 different values until we find a name that
7390 * doesn't exist. */
7391 for (off = 0; off < 10000L; ++off)
7392 {
7393 int r;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007394# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007395 mode_t umask_save;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007396# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007397
Bram Moolenaareaf03392009-11-17 11:08:52 +00007398 sprintf((char *)itmp + itmplen, "v%ld", nr + off);
7399# ifndef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007400 /* If mkdir() does not set errno to EEXIST, check for
7401 * existing file here. There is a race condition then,
7402 * although it's fail-safe. */
7403 if (mch_stat((char *)itmp, &st) >= 0)
7404 continue;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007405# endif
7406# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007407 /* Make sure the umask doesn't remove the executable bit.
7408 * "repl" has been reported to use "177". */
7409 umask_save = umask(077);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007410# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007411 r = vim_mkdir(itmp, 0700);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007412# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007413 (void)umask(umask_save);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007414# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007415 if (r == 0)
7416 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007417 vim_settempdir(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007418 break;
7419 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007420# ifdef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007421 /* If the mkdir() didn't fail because the file/dir exists,
7422 * we probably can't create any dir here, try another
7423 * place. */
7424 if (errno != EEXIST)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007425# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007426 break;
7427 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007428# endif /* HAVE_MKDTEMP */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007429 if (vim_tempdir != NULL)
7430 break;
7431 }
7432 }
7433 }
7434
7435 if (vim_tempdir != NULL)
7436 {
7437 /* There is no need to check if the file exists, because we own the
7438 * directory and nobody else creates a file in it. */
7439 sprintf((char *)itmp, "%s%ld", vim_tempdir, temp_count++);
7440 return vim_strsave(itmp);
7441 }
7442
7443 return NULL;
7444
7445#else /* TEMPDIRNAMES */
7446
7447# ifdef WIN3264
7448 char szTempFile[_MAX_PATH + 1];
7449 char buf4[4];
7450 char_u *retval;
7451 char_u *p;
7452
7453 STRCPY(itmp, "");
7454 if (GetTempPath(_MAX_PATH, szTempFile) == 0)
7455 szTempFile[0] = NUL; /* GetTempPath() failed, use current dir */
7456 strcpy(buf4, "VIM");
7457 buf4[2] = extra_char; /* make it "VIa", "VIb", etc. */
7458 if (GetTempFileName(szTempFile, buf4, 0, itmp) == 0)
7459 return NULL;
7460 /* GetTempFileName() will create the file, we don't want that */
7461 (void)DeleteFile(itmp);
7462
7463 /* Backslashes in a temp file name cause problems when filtering with
7464 * "sh". NOTE: This also checks 'shellcmdflag' to help those people who
7465 * didn't set 'shellslash'. */
7466 retval = vim_strsave(itmp);
7467 if (*p_shcf == '-' || p_ssl)
7468 for (p = retval; *p; ++p)
7469 if (*p == '\\')
7470 *p = '/';
7471 return retval;
7472
7473# else /* WIN3264 */
7474
7475# ifdef USE_TMPNAM
7476 /* tmpnam() will make its own name */
7477 if (*tmpnam((char *)itmp) == NUL)
7478 return NULL;
7479# else
7480 char_u *p;
7481
7482# ifdef VMS_TEMPNAM
7483 /* mktemp() is not working on VMS. It seems to be
7484 * a do-nothing function. Therefore we use tempnam().
7485 */
7486 sprintf((char *)itmp, "VIM%c", extra_char);
7487 p = (char_u *)tempnam("tmp:", (char *)itmp);
7488 if (p != NULL)
7489 {
7490 /* VMS will use '.LOG' if we don't explicitly specify an extension,
7491 * and VIM will then be unable to find the file later */
7492 STRCPY(itmp, p);
7493 STRCAT(itmp, ".txt");
7494 free(p);
7495 }
7496 else
7497 return NULL;
7498# else
7499 STRCPY(itmp, TEMPNAME);
7500 if ((p = vim_strchr(itmp, '?')) != NULL)
7501 *p = extra_char;
7502 if (mktemp((char *)itmp) == NULL)
7503 return NULL;
7504# endif
7505# endif
7506
7507 return vim_strsave(itmp);
7508# endif /* WIN3264 */
7509#endif /* TEMPDIRNAMES */
7510}
7511
7512#if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
7513/*
7514 * Convert all backslashes in fname to forward slashes in-place.
7515 */
7516 void
7517forward_slash(fname)
7518 char_u *fname;
7519{
7520 char_u *p;
7521
7522 for (p = fname; *p != NUL; ++p)
7523# ifdef FEAT_MBYTE
7524 /* The Big5 encoding can have '\' in the trail byte. */
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00007525 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007526 ++p;
7527 else
7528# endif
7529 if (*p == '\\')
7530 *p = '/';
7531}
7532#endif
7533
7534
7535/*
7536 * Code for automatic commands.
7537 *
7538 * Only included when "FEAT_AUTOCMD" has been defined.
7539 */
7540
7541#if defined(FEAT_AUTOCMD) || defined(PROTO)
7542
7543/*
7544 * The autocommands are stored in a list for each event.
7545 * Autocommands for the same pattern, that are consecutive, are joined
7546 * together, to avoid having to match the pattern too often.
7547 * The result is an array of Autopat lists, which point to AutoCmd lists:
7548 *
7549 * first_autopat[0] --> Autopat.next --> Autopat.next --> NULL
7550 * Autopat.cmds Autopat.cmds
7551 * | |
7552 * V V
7553 * AutoCmd.next AutoCmd.next
7554 * | |
7555 * V V
7556 * AutoCmd.next NULL
7557 * |
7558 * V
7559 * NULL
7560 *
7561 * first_autopat[1] --> Autopat.next --> NULL
7562 * Autopat.cmds
7563 * |
7564 * V
7565 * AutoCmd.next
7566 * |
7567 * V
7568 * NULL
7569 * etc.
7570 *
7571 * The order of AutoCmds is important, this is the order in which they were
7572 * defined and will have to be executed.
7573 */
7574typedef struct AutoCmd
7575{
7576 char_u *cmd; /* The command to be executed (NULL
7577 when command has been removed) */
7578 char nested; /* If autocommands nest here */
7579 char last; /* last command in list */
7580#ifdef FEAT_EVAL
7581 scid_T scriptID; /* script ID where defined */
7582#endif
7583 struct AutoCmd *next; /* Next AutoCmd in list */
7584} AutoCmd;
7585
7586typedef struct AutoPat
7587{
7588 int group; /* group ID */
7589 char_u *pat; /* pattern as typed (NULL when pattern
7590 has been removed) */
7591 int patlen; /* strlen() of pat */
Bram Moolenaar748bf032005-02-02 23:04:36 +00007592 regprog_T *reg_prog; /* compiled regprog for pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007593 char allow_dirs; /* Pattern may match whole path */
7594 char last; /* last pattern for apply_autocmds() */
7595 AutoCmd *cmds; /* list of commands to do */
7596 struct AutoPat *next; /* next AutoPat in AutoPat list */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007597 int buflocal_nr; /* !=0 for buffer-local AutoPat */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007598} AutoPat;
7599
7600static struct event_name
7601{
7602 char *name; /* event name */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007603 event_T event; /* event number */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007604} event_names[] =
7605{
7606 {"BufAdd", EVENT_BUFADD},
7607 {"BufCreate", EVENT_BUFADD},
7608 {"BufDelete", EVENT_BUFDELETE},
7609 {"BufEnter", EVENT_BUFENTER},
7610 {"BufFilePost", EVENT_BUFFILEPOST},
7611 {"BufFilePre", EVENT_BUFFILEPRE},
7612 {"BufHidden", EVENT_BUFHIDDEN},
7613 {"BufLeave", EVENT_BUFLEAVE},
7614 {"BufNew", EVENT_BUFNEW},
7615 {"BufNewFile", EVENT_BUFNEWFILE},
7616 {"BufRead", EVENT_BUFREADPOST},
7617 {"BufReadCmd", EVENT_BUFREADCMD},
7618 {"BufReadPost", EVENT_BUFREADPOST},
7619 {"BufReadPre", EVENT_BUFREADPRE},
7620 {"BufUnload", EVENT_BUFUNLOAD},
7621 {"BufWinEnter", EVENT_BUFWINENTER},
7622 {"BufWinLeave", EVENT_BUFWINLEAVE},
7623 {"BufWipeout", EVENT_BUFWIPEOUT},
7624 {"BufWrite", EVENT_BUFWRITEPRE},
7625 {"BufWritePost", EVENT_BUFWRITEPOST},
7626 {"BufWritePre", EVENT_BUFWRITEPRE},
7627 {"BufWriteCmd", EVENT_BUFWRITECMD},
7628 {"CmdwinEnter", EVENT_CMDWINENTER},
7629 {"CmdwinLeave", EVENT_CMDWINLEAVE},
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007630 {"ColorScheme", EVENT_COLORSCHEME},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007631 {"CursorHold", EVENT_CURSORHOLD},
7632 {"CursorHoldI", EVENT_CURSORHOLDI},
7633 {"CursorMoved", EVENT_CURSORMOVED},
7634 {"CursorMovedI", EVENT_CURSORMOVEDI},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007635 {"EncodingChanged", EVENT_ENCODINGCHANGED},
7636 {"FileEncoding", EVENT_ENCODINGCHANGED},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007637 {"FileAppendPost", EVENT_FILEAPPENDPOST},
7638 {"FileAppendPre", EVENT_FILEAPPENDPRE},
7639 {"FileAppendCmd", EVENT_FILEAPPENDCMD},
7640 {"FileChangedShell",EVENT_FILECHANGEDSHELL},
Bram Moolenaar56718732006-03-15 22:53:57 +00007641 {"FileChangedShellPost",EVENT_FILECHANGEDSHELLPOST},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007642 {"FileChangedRO", EVENT_FILECHANGEDRO},
7643 {"FileReadPost", EVENT_FILEREADPOST},
7644 {"FileReadPre", EVENT_FILEREADPRE},
7645 {"FileReadCmd", EVENT_FILEREADCMD},
7646 {"FileType", EVENT_FILETYPE},
7647 {"FileWritePost", EVENT_FILEWRITEPOST},
7648 {"FileWritePre", EVENT_FILEWRITEPRE},
7649 {"FileWriteCmd", EVENT_FILEWRITECMD},
7650 {"FilterReadPost", EVENT_FILTERREADPOST},
7651 {"FilterReadPre", EVENT_FILTERREADPRE},
7652 {"FilterWritePost", EVENT_FILTERWRITEPOST},
7653 {"FilterWritePre", EVENT_FILTERWRITEPRE},
7654 {"FocusGained", EVENT_FOCUSGAINED},
7655 {"FocusLost", EVENT_FOCUSLOST},
7656 {"FuncUndefined", EVENT_FUNCUNDEFINED},
7657 {"GUIEnter", EVENT_GUIENTER},
Bram Moolenaar265e5072006-08-29 16:13:22 +00007658 {"GUIFailed", EVENT_GUIFAILED},
Bram Moolenaar843ee412004-06-30 16:16:41 +00007659 {"InsertChange", EVENT_INSERTCHANGE},
7660 {"InsertEnter", EVENT_INSERTENTER},
7661 {"InsertLeave", EVENT_INSERTLEAVE},
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00007662 {"MenuPopup", EVENT_MENUPOPUP},
Bram Moolenaar7c626922005-02-07 22:01:03 +00007663 {"QuickFixCmdPost", EVENT_QUICKFIXCMDPOST},
7664 {"QuickFixCmdPre", EVENT_QUICKFIXCMDPRE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007665 {"RemoteReply", EVENT_REMOTEREPLY},
Bram Moolenaar9372a112005-12-06 19:59:18 +00007666 {"SessionLoadPost", EVENT_SESSIONLOADPOST},
Bram Moolenaar5c4bab02006-03-10 21:37:46 +00007667 {"ShellCmdPost", EVENT_SHELLCMDPOST},
7668 {"ShellFilterPost", EVENT_SHELLFILTERPOST},
Bram Moolenaara2031822006-03-07 22:29:51 +00007669 {"SourcePre", EVENT_SOURCEPRE},
Bram Moolenaar8dd1aa52007-01-16 20:33:19 +00007670 {"SourceCmd", EVENT_SOURCECMD},
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00007671 {"SpellFileMissing",EVENT_SPELLFILEMISSING},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007672 {"StdinReadPost", EVENT_STDINREADPOST},
7673 {"StdinReadPre", EVENT_STDINREADPRE},
Bram Moolenaarb815dac2005-12-07 20:59:24 +00007674 {"SwapExists", EVENT_SWAPEXISTS},
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00007675 {"Syntax", EVENT_SYNTAX},
Bram Moolenaar70836c82006-02-20 21:28:49 +00007676 {"TabEnter", EVENT_TABENTER},
7677 {"TabLeave", EVENT_TABLEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007678 {"TermChanged", EVENT_TERMCHANGED},
7679 {"TermResponse", EVENT_TERMRESPONSE},
7680 {"User", EVENT_USER},
7681 {"VimEnter", EVENT_VIMENTER},
7682 {"VimLeave", EVENT_VIMLEAVE},
7683 {"VimLeavePre", EVENT_VIMLEAVEPRE},
7684 {"WinEnter", EVENT_WINENTER},
7685 {"WinLeave", EVENT_WINLEAVE},
Bram Moolenaar56718732006-03-15 22:53:57 +00007686 {"VimResized", EVENT_VIMRESIZED},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007687 {NULL, (event_T)0}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007688};
7689
7690static AutoPat *first_autopat[NUM_EVENTS] =
7691{
7692 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7693 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7694 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7695 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00007696 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7697 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007698};
7699
7700/*
7701 * struct used to keep status while executing autocommands for an event.
7702 */
7703typedef struct AutoPatCmd
7704{
7705 AutoPat *curpat; /* next AutoPat to examine */
7706 AutoCmd *nextcmd; /* next AutoCmd to execute */
7707 int group; /* group being used */
7708 char_u *fname; /* fname to match with */
7709 char_u *sfname; /* sfname to match with */
7710 char_u *tail; /* tail of fname */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007711 event_T event; /* current event */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007712 int arg_bufnr; /* initially equal to <abuf>, set to zero when
7713 buf is deleted */
7714 struct AutoPatCmd *next; /* chain of active apc-s for auto-invalidation*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00007715} AutoPatCmd;
7716
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007717static AutoPatCmd *active_apc_list = NULL; /* stack of active autocommands */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007718
Bram Moolenaar071d4272004-06-13 20:20:40 +00007719/*
7720 * augroups stores a list of autocmd group names.
7721 */
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007722static garray_T augroups = {0, 0, sizeof(char_u *), 10, NULL};
Bram Moolenaar071d4272004-06-13 20:20:40 +00007723#define AUGROUP_NAME(i) (((char_u **)augroups.ga_data)[i])
7724
7725/*
7726 * The ID of the current group. Group 0 is the default one.
7727 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007728static int current_augroup = AUGROUP_DEFAULT;
7729
7730static int au_need_clean = FALSE; /* need to delete marked patterns */
7731
Bram Moolenaar754b5602006-02-09 23:53:20 +00007732static void show_autocmd __ARGS((AutoPat *ap, event_T event));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007733static void au_remove_pat __ARGS((AutoPat *ap));
7734static void au_remove_cmds __ARGS((AutoPat *ap));
7735static void au_cleanup __ARGS((void));
7736static int au_new_group __ARGS((char_u *name));
7737static void au_del_group __ARGS((char_u *name));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007738static event_T event_name2nr __ARGS((char_u *start, char_u **end));
7739static char_u *event_nr2name __ARGS((event_T event));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007740static char_u *find_end_event __ARGS((char_u *arg, int have_group));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007741static int event_ignored __ARGS((event_T event));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007742static int au_get_grouparg __ARGS((char_u **argp));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007743static 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 +00007744static char_u *getnextac __ARGS((int c, void *cookie, int indent));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007745static 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 +00007746static void auto_next_pat __ARGS((AutoPatCmd *apc, int stop_at_last));
7747
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007748
Bram Moolenaar754b5602006-02-09 23:53:20 +00007749static event_T last_event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007750static int last_group;
Bram Moolenaar78ab3312007-09-29 12:16:41 +00007751static int autocmd_blocked = 0; /* block all autocmds */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007752
7753/*
7754 * Show the autocommands for one AutoPat.
7755 */
7756 static void
7757show_autocmd(ap, event)
7758 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007759 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007760{
7761 AutoCmd *ac;
7762
7763 /* Check for "got_int" (here and at various places below), which is set
7764 * when "q" has been hit for the "--more--" prompt */
7765 if (got_int)
7766 return;
7767 if (ap->pat == NULL) /* pattern has been removed */
7768 return;
7769
7770 msg_putchar('\n');
7771 if (got_int)
7772 return;
7773 if (event != last_event || ap->group != last_group)
7774 {
7775 if (ap->group != AUGROUP_DEFAULT)
7776 {
7777 if (AUGROUP_NAME(ap->group) == NULL)
7778 msg_puts_attr((char_u *)_("--Deleted--"), hl_attr(HLF_E));
7779 else
7780 msg_puts_attr(AUGROUP_NAME(ap->group), hl_attr(HLF_T));
7781 msg_puts((char_u *)" ");
7782 }
7783 msg_puts_attr(event_nr2name(event), hl_attr(HLF_T));
7784 last_event = event;
7785 last_group = ap->group;
7786 msg_putchar('\n');
7787 if (got_int)
7788 return;
7789 }
7790 msg_col = 4;
7791 msg_outtrans(ap->pat);
7792
7793 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7794 {
7795 if (ac->cmd != NULL) /* skip removed commands */
7796 {
7797 if (msg_col >= 14)
7798 msg_putchar('\n');
7799 msg_col = 14;
7800 if (got_int)
7801 return;
7802 msg_outtrans(ac->cmd);
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00007803#ifdef FEAT_EVAL
7804 if (p_verbose > 0)
7805 last_set_msg(ac->scriptID);
7806#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007807 if (got_int)
7808 return;
7809 if (ac->next != NULL)
7810 {
7811 msg_putchar('\n');
7812 if (got_int)
7813 return;
7814 }
7815 }
7816 }
7817}
7818
7819/*
7820 * Mark an autocommand pattern for deletion.
7821 */
7822 static void
7823au_remove_pat(ap)
7824 AutoPat *ap;
7825{
7826 vim_free(ap->pat);
7827 ap->pat = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007828 ap->buflocal_nr = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007829 au_need_clean = TRUE;
7830}
7831
7832/*
7833 * Mark all commands for a pattern for deletion.
7834 */
7835 static void
7836au_remove_cmds(ap)
7837 AutoPat *ap;
7838{
7839 AutoCmd *ac;
7840
7841 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7842 {
7843 vim_free(ac->cmd);
7844 ac->cmd = NULL;
7845 }
7846 au_need_clean = TRUE;
7847}
7848
7849/*
7850 * Cleanup autocommands and patterns that have been deleted.
7851 * This is only done when not executing autocommands.
7852 */
7853 static void
7854au_cleanup()
7855{
7856 AutoPat *ap, **prev_ap;
7857 AutoCmd *ac, **prev_ac;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007858 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007859
7860 if (autocmd_busy || !au_need_clean)
7861 return;
7862
7863 /* loop over all events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007864 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7865 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007866 {
7867 /* loop over all autocommand patterns */
7868 prev_ap = &(first_autopat[(int)event]);
7869 for (ap = *prev_ap; ap != NULL; ap = *prev_ap)
7870 {
7871 /* loop over all commands for this pattern */
7872 prev_ac = &(ap->cmds);
7873 for (ac = *prev_ac; ac != NULL; ac = *prev_ac)
7874 {
7875 /* remove the command if the pattern is to be deleted or when
7876 * the command has been marked for deletion */
7877 if (ap->pat == NULL || ac->cmd == NULL)
7878 {
7879 *prev_ac = ac->next;
7880 vim_free(ac->cmd);
7881 vim_free(ac);
7882 }
7883 else
7884 prev_ac = &(ac->next);
7885 }
7886
7887 /* remove the pattern if it has been marked for deletion */
7888 if (ap->pat == NULL)
7889 {
7890 *prev_ap = ap->next;
Bram Moolenaar748bf032005-02-02 23:04:36 +00007891 vim_free(ap->reg_prog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007892 vim_free(ap);
7893 }
7894 else
7895 prev_ap = &(ap->next);
7896 }
7897 }
7898
7899 au_need_clean = FALSE;
7900}
7901
7902/*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007903 * Called when buffer is freed, to remove/invalidate related buffer-local
7904 * autocmds.
7905 */
7906 void
7907aubuflocal_remove(buf)
7908 buf_T *buf;
7909{
7910 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007911 event_T event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007912 AutoPatCmd *apc;
7913
7914 /* invalidate currently executing autocommands */
7915 for (apc = active_apc_list; apc; apc = apc->next)
7916 if (buf->b_fnum == apc->arg_bufnr)
7917 apc->arg_bufnr = 0;
7918
7919 /* invalidate buflocals looping through events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007920 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7921 event = (event_T)((int)event + 1))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007922 /* loop over all autocommand patterns */
7923 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
7924 if (ap->buflocal_nr == buf->b_fnum)
7925 {
7926 au_remove_pat(ap);
7927 if (p_verbose >= 6)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007928 {
7929 verbose_enter();
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007930 smsg((char_u *)
7931 _("auto-removing autocommand: %s <buffer=%d>"),
7932 event_nr2name(event), buf->b_fnum);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007933 verbose_leave();
7934 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007935 }
7936 au_cleanup();
7937}
7938
7939/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007940 * Add an autocmd group name.
7941 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
7942 */
7943 static int
7944au_new_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 yet, add it */
7951 {
7952 /* First try using a free entry. */
7953 for (i = 0; i < augroups.ga_len; ++i)
7954 if (AUGROUP_NAME(i) == NULL)
7955 break;
7956 if (i == augroups.ga_len && ga_grow(&augroups, 1) == FAIL)
7957 return AUGROUP_ERROR;
7958
7959 AUGROUP_NAME(i) = vim_strsave(name);
7960 if (AUGROUP_NAME(i) == NULL)
7961 return AUGROUP_ERROR;
7962 if (i == augroups.ga_len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007963 ++augroups.ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007964 }
7965
7966 return i;
7967}
7968
7969 static void
7970au_del_group(name)
7971 char_u *name;
7972{
7973 int i;
7974
7975 i = au_find_group(name);
7976 if (i == AUGROUP_ERROR) /* the group doesn't exist */
7977 EMSG2(_("E367: No such group: \"%s\""), name);
7978 else
7979 {
7980 vim_free(AUGROUP_NAME(i));
7981 AUGROUP_NAME(i) = NULL;
7982 }
7983}
7984
7985/*
7986 * Find the ID of an autocmd group name.
7987 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
7988 */
7989 static int
7990au_find_group(name)
7991 char_u *name;
7992{
7993 int i;
7994
7995 for (i = 0; i < augroups.ga_len; ++i)
7996 if (AUGROUP_NAME(i) != NULL && STRCMP(AUGROUP_NAME(i), name) == 0)
7997 return i;
7998 return AUGROUP_ERROR;
7999}
8000
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008001/*
8002 * Return TRUE if augroup "name" exists.
8003 */
8004 int
8005au_has_group(name)
8006 char_u *name;
8007{
8008 return au_find_group(name) != AUGROUP_ERROR;
8009}
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008010
Bram Moolenaar071d4272004-06-13 20:20:40 +00008011/*
8012 * ":augroup {name}".
8013 */
8014 void
8015do_augroup(arg, del_group)
8016 char_u *arg;
8017 int del_group;
8018{
8019 int i;
8020
8021 if (del_group)
8022 {
8023 if (*arg == NUL)
8024 EMSG(_(e_argreq));
8025 else
8026 au_del_group(arg);
8027 }
8028 else if (STRICMP(arg, "end") == 0) /* ":aug end": back to group 0 */
8029 current_augroup = AUGROUP_DEFAULT;
8030 else if (*arg) /* ":aug xxx": switch to group xxx */
8031 {
8032 i = au_new_group(arg);
8033 if (i != AUGROUP_ERROR)
8034 current_augroup = i;
8035 }
8036 else /* ":aug": list the group names */
8037 {
8038 msg_start();
8039 for (i = 0; i < augroups.ga_len; ++i)
8040 {
8041 if (AUGROUP_NAME(i) != NULL)
8042 {
8043 msg_puts(AUGROUP_NAME(i));
8044 msg_puts((char_u *)" ");
8045 }
8046 }
8047 msg_clr_eos();
8048 msg_end();
8049 }
8050}
8051
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008052#if defined(EXITFREE) || defined(PROTO)
8053 void
8054free_all_autocmds()
8055{
8056 for (current_augroup = -1; current_augroup < augroups.ga_len;
8057 ++current_augroup)
8058 do_autocmd((char_u *)"", TRUE);
8059 ga_clear_strings(&augroups);
8060}
8061#endif
8062
Bram Moolenaar071d4272004-06-13 20:20:40 +00008063/*
8064 * Return the event number for event name "start".
8065 * Return NUM_EVENTS if the event name was not found.
8066 * Return a pointer to the next event name in "end".
8067 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008068 static event_T
Bram Moolenaar071d4272004-06-13 20:20:40 +00008069event_name2nr(start, end)
8070 char_u *start;
8071 char_u **end;
8072{
8073 char_u *p;
8074 int i;
8075 int len;
8076
8077 /* the event name ends with end of line, a blank or a comma */
8078 for (p = start; *p && !vim_iswhite(*p) && *p != ','; ++p)
8079 ;
8080 for (i = 0; event_names[i].name != NULL; ++i)
8081 {
8082 len = (int)STRLEN(event_names[i].name);
8083 if (len == p - start && STRNICMP(event_names[i].name, start, len) == 0)
8084 break;
8085 }
8086 if (*p == ',')
8087 ++p;
8088 *end = p;
8089 if (event_names[i].name == NULL)
8090 return NUM_EVENTS;
8091 return event_names[i].event;
8092}
8093
8094/*
8095 * Return the name for event "event".
8096 */
8097 static char_u *
8098event_nr2name(event)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008099 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008100{
8101 int i;
8102
8103 for (i = 0; event_names[i].name != NULL; ++i)
8104 if (event_names[i].event == event)
8105 return (char_u *)event_names[i].name;
8106 return (char_u *)"Unknown";
8107}
8108
8109/*
8110 * Scan over the events. "*" stands for all events.
8111 */
8112 static char_u *
8113find_end_event(arg, have_group)
8114 char_u *arg;
8115 int have_group; /* TRUE when group name was found */
8116{
8117 char_u *pat;
8118 char_u *p;
8119
8120 if (*arg == '*')
8121 {
8122 if (arg[1] && !vim_iswhite(arg[1]))
8123 {
8124 EMSG2(_("E215: Illegal character after *: %s"), arg);
8125 return NULL;
8126 }
8127 pat = arg + 1;
8128 }
8129 else
8130 {
8131 for (pat = arg; *pat && !vim_iswhite(*pat); pat = p)
8132 {
8133 if ((int)event_name2nr(pat, &p) >= (int)NUM_EVENTS)
8134 {
8135 if (have_group)
8136 EMSG2(_("E216: No such event: %s"), pat);
8137 else
8138 EMSG2(_("E216: No such group or event: %s"), pat);
8139 return NULL;
8140 }
8141 }
8142 }
8143 return pat;
8144}
8145
8146/*
8147 * Return TRUE if "event" is included in 'eventignore'.
8148 */
8149 static int
8150event_ignored(event)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008151 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008152{
8153 char_u *p = p_ei;
8154
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008155 while (*p != NUL)
8156 {
8157 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8158 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008159 if (event_name2nr(p, &p) == event)
8160 return TRUE;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008161 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008162
8163 return FALSE;
8164}
8165
8166/*
8167 * Return OK when the contents of p_ei is valid, FAIL otherwise.
8168 */
8169 int
8170check_ei()
8171{
8172 char_u *p = p_ei;
8173
Bram Moolenaar071d4272004-06-13 20:20:40 +00008174 while (*p)
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008175 {
8176 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8177 {
8178 p += 3;
8179 if (*p == ',')
8180 ++p;
8181 }
8182 else if (event_name2nr(p, &p) == NUM_EVENTS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008183 return FAIL;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008184 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008185
8186 return OK;
8187}
8188
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008189# if defined(FEAT_SYN_HL) || defined(PROTO)
8190
8191/*
8192 * Add "what" to 'eventignore' to skip loading syntax highlighting for every
8193 * buffer loaded into the window. "what" must start with a comma.
8194 * Returns the old value of 'eventignore' in allocated memory.
8195 */
8196 char_u *
8197au_event_disable(what)
8198 char *what;
8199{
8200 char_u *new_ei;
8201 char_u *save_ei;
8202
8203 save_ei = vim_strsave(p_ei);
8204 if (save_ei != NULL)
8205 {
Bram Moolenaara5792f52005-11-23 21:25:05 +00008206 new_ei = vim_strnsave(p_ei, (int)(STRLEN(p_ei) + STRLEN(what)));
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008207 if (new_ei != NULL)
8208 {
Bram Moolenaar8cac9fd2010-03-02 12:48:05 +01008209 if (*what == ',' && *p_ei == NUL)
8210 STRCPY(new_ei, what + 1);
8211 else
8212 STRCAT(new_ei, what);
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008213 set_string_option_direct((char_u *)"ei", -1, new_ei,
8214 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008215 vim_free(new_ei);
8216 }
8217 }
8218 return save_ei;
8219}
8220
8221 void
8222au_event_restore(old_ei)
8223 char_u *old_ei;
8224{
8225 if (old_ei != NULL)
8226 {
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008227 set_string_option_direct((char_u *)"ei", -1, old_ei,
8228 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008229 vim_free(old_ei);
8230 }
8231}
8232# endif /* FEAT_SYN_HL */
8233
Bram Moolenaar071d4272004-06-13 20:20:40 +00008234/*
8235 * do_autocmd() -- implements the :autocmd command. Can be used in the
8236 * following ways:
8237 *
8238 * :autocmd <event> <pat> <cmd> Add <cmd> to the list of commands that
8239 * will be automatically executed for <event>
8240 * when editing a file matching <pat>, in
8241 * the current group.
8242 * :autocmd <event> <pat> Show the auto-commands associated with
8243 * <event> and <pat>.
8244 * :autocmd <event> Show the auto-commands associated with
8245 * <event>.
8246 * :autocmd Show all auto-commands.
8247 * :autocmd! <event> <pat> <cmd> Remove all auto-commands associated with
8248 * <event> and <pat>, and add the command
8249 * <cmd>, for the current group.
8250 * :autocmd! <event> <pat> Remove all auto-commands associated with
8251 * <event> and <pat> for the current group.
8252 * :autocmd! <event> Remove all auto-commands associated with
8253 * <event> for the current group.
8254 * :autocmd! Remove ALL auto-commands for the current
8255 * group.
8256 *
8257 * Multiple events and patterns may be given separated by commas. Here are
8258 * some examples:
8259 * :autocmd bufread,bufenter *.c,*.h set tw=0 smartindent noic
8260 * :autocmd bufleave * set tw=79 nosmartindent ic infercase
8261 *
8262 * :autocmd * *.c show all autocommands for *.c files.
Bram Moolenaard35f9712005-12-18 22:02:33 +00008263 *
8264 * Mostly a {group} argument can optionally appear before <event>.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008265 */
8266 void
8267do_autocmd(arg, forceit)
8268 char_u *arg;
8269 int forceit;
8270{
8271 char_u *pat;
8272 char_u *envpat = NULL;
8273 char_u *cmd;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008274 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008275 int need_free = FALSE;
8276 int nested = FALSE;
8277 int group;
8278
8279 /*
8280 * Check for a legal group name. If not, use AUGROUP_ALL.
8281 */
8282 group = au_get_grouparg(&arg);
8283 if (arg == NULL) /* out of memory */
8284 return;
8285
8286 /*
8287 * Scan over the events.
8288 * If we find an illegal name, return here, don't do anything.
8289 */
8290 pat = find_end_event(arg, group != AUGROUP_ALL);
8291 if (pat == NULL)
8292 return;
8293
8294 /*
8295 * Scan over the pattern. Put a NUL at the end.
8296 */
8297 pat = skipwhite(pat);
8298 cmd = pat;
8299 while (*cmd && (!vim_iswhite(*cmd) || cmd[-1] == '\\'))
8300 cmd++;
8301 if (*cmd)
8302 *cmd++ = NUL;
8303
8304 /* Expand environment variables in the pattern. Set 'shellslash', we want
8305 * forward slashes here. */
8306 if (vim_strchr(pat, '$') != NULL || vim_strchr(pat, '~') != NULL)
8307 {
8308#ifdef BACKSLASH_IN_FILENAME
8309 int p_ssl_save = p_ssl;
8310
8311 p_ssl = TRUE;
8312#endif
8313 envpat = expand_env_save(pat);
8314#ifdef BACKSLASH_IN_FILENAME
8315 p_ssl = p_ssl_save;
8316#endif
8317 if (envpat != NULL)
8318 pat = envpat;
8319 }
8320
8321 /*
8322 * Check for "nested" flag.
8323 */
8324 cmd = skipwhite(cmd);
8325 if (*cmd != NUL && STRNCMP(cmd, "nested", 6) == 0 && vim_iswhite(cmd[6]))
8326 {
8327 nested = TRUE;
8328 cmd = skipwhite(cmd + 6);
8329 }
8330
8331 /*
8332 * Find the start of the commands.
8333 * Expand <sfile> in it.
8334 */
8335 if (*cmd != NUL)
8336 {
8337 cmd = expand_sfile(cmd);
8338 if (cmd == NULL) /* some error */
8339 return;
8340 need_free = TRUE;
8341 }
8342
8343 /*
8344 * Print header when showing autocommands.
8345 */
8346 if (!forceit && *cmd == NUL)
8347 {
8348 /* Highlight title */
8349 MSG_PUTS_TITLE(_("\n--- Auto-Commands ---"));
8350 }
8351
8352 /*
8353 * Loop over the events.
8354 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008355 last_event = (event_T)-1; /* for listing the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008356 last_group = AUGROUP_ERROR; /* for listing the group name */
8357 if (*arg == '*' || *arg == NUL)
8358 {
Bram Moolenaar754b5602006-02-09 23:53:20 +00008359 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8360 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008361 if (do_autocmd_event(event, pat,
8362 nested, cmd, forceit, group) == FAIL)
8363 break;
8364 }
8365 else
8366 {
8367 while (*arg && !vim_iswhite(*arg))
8368 if (do_autocmd_event(event_name2nr(arg, &arg), pat,
8369 nested, cmd, forceit, group) == FAIL)
8370 break;
8371 }
8372
8373 if (need_free)
8374 vim_free(cmd);
8375 vim_free(envpat);
8376}
8377
8378/*
8379 * Find the group ID in a ":autocmd" or ":doautocmd" argument.
8380 * The "argp" argument is advanced to the following argument.
8381 *
8382 * Returns the group ID, AUGROUP_ERROR for error (out of memory).
8383 */
8384 static int
8385au_get_grouparg(argp)
8386 char_u **argp;
8387{
8388 char_u *group_name;
8389 char_u *p;
8390 char_u *arg = *argp;
8391 int group = AUGROUP_ALL;
8392
8393 p = skiptowhite(arg);
8394 if (p > arg)
8395 {
8396 group_name = vim_strnsave(arg, (int)(p - arg));
8397 if (group_name == NULL) /* out of memory */
8398 return AUGROUP_ERROR;
8399 group = au_find_group(group_name);
8400 if (group == AUGROUP_ERROR)
8401 group = AUGROUP_ALL; /* no match, use all groups */
8402 else
8403 *argp = skipwhite(p); /* match, skip over group name */
8404 vim_free(group_name);
8405 }
8406 return group;
8407}
8408
8409/*
8410 * do_autocmd() for one event.
8411 * If *pat == NUL do for all patterns.
8412 * If *cmd == NUL show entries.
8413 * If forceit == TRUE delete entries.
8414 * If group is not AUGROUP_ALL, only use this group.
8415 */
8416 static int
8417do_autocmd_event(event, pat, nested, cmd, forceit, group)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008418 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008419 char_u *pat;
8420 int nested;
8421 char_u *cmd;
8422 int forceit;
8423 int group;
8424{
8425 AutoPat *ap;
8426 AutoPat **prev_ap;
8427 AutoCmd *ac;
8428 AutoCmd **prev_ac;
8429 int brace_level;
8430 char_u *endpat;
8431 int findgroup;
8432 int allgroups;
8433 int patlen;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00008434 int is_buflocal;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008435 int buflocal_nr;
8436 char_u buflocal_pat[25]; /* for "<buffer=X>" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008437
8438 if (group == AUGROUP_ALL)
8439 findgroup = current_augroup;
8440 else
8441 findgroup = group;
8442 allgroups = (group == AUGROUP_ALL && !forceit && *cmd == NUL);
8443
8444 /*
8445 * Show or delete all patterns for an event.
8446 */
8447 if (*pat == NUL)
8448 {
8449 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8450 {
8451 if (forceit) /* delete the AutoPat, if it's in the current group */
8452 {
8453 if (ap->group == findgroup)
8454 au_remove_pat(ap);
8455 }
8456 else if (group == AUGROUP_ALL || ap->group == group)
8457 show_autocmd(ap, event);
8458 }
8459 }
8460
8461 /*
8462 * Loop through all the specified patterns.
8463 */
8464 for ( ; *pat; pat = (*endpat == ',' ? endpat + 1 : endpat))
8465 {
8466 /*
8467 * Find end of the pattern.
8468 * Watch out for a comma in braces, like "*.\{obj,o\}".
8469 */
8470 brace_level = 0;
8471 for (endpat = pat; *endpat && (*endpat != ',' || brace_level
8472 || endpat[-1] == '\\'); ++endpat)
8473 {
8474 if (*endpat == '{')
8475 brace_level++;
8476 else if (*endpat == '}')
8477 brace_level--;
8478 }
8479 if (pat == endpat) /* ignore single comma */
8480 continue;
8481 patlen = (int)(endpat - pat);
8482
8483 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008484 * detect special <buflocal[=X]> buffer-local patterns
8485 */
8486 is_buflocal = FALSE;
8487 buflocal_nr = 0;
8488
8489 if (patlen >= 7 && STRNCMP(pat, "<buffer", 7) == 0
8490 && pat[patlen - 1] == '>')
8491 {
8492 /* Error will be printed only for addition. printing and removing
8493 * will proceed silently. */
8494 is_buflocal = TRUE;
8495 if (patlen == 8)
8496 buflocal_nr = curbuf->b_fnum;
8497 else if (patlen > 9 && pat[7] == '=')
8498 {
8499 /* <buffer=abuf> */
8500 if (patlen == 13 && STRNICMP(pat, "<buffer=abuf>", 13))
8501 buflocal_nr = autocmd_bufnr;
8502 /* <buffer=123> */
8503 else if (skipdigits(pat + 8) == pat + patlen - 1)
8504 buflocal_nr = atoi((char *)pat + 8);
8505 }
8506 }
8507
8508 if (is_buflocal)
8509 {
8510 /* normalize pat into standard "<buffer>#N" form */
8511 sprintf((char *)buflocal_pat, "<buffer=%d>", buflocal_nr);
8512 pat = buflocal_pat; /* can modify pat and patlen */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008513 patlen = (int)STRLEN(buflocal_pat); /* but not endpat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008514 }
8515
8516 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008517 * Find AutoPat entries with this pattern.
8518 */
8519 prev_ap = &first_autopat[(int)event];
8520 while ((ap = *prev_ap) != NULL)
8521 {
8522 if (ap->pat != NULL)
8523 {
8524 /* Accept a pattern when:
8525 * - a group was specified and it's that group, or a group was
8526 * not specified and it's the current group, or a group was
8527 * not specified and we are listing
8528 * - the length of the pattern matches
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008529 * - the pattern matches.
8530 * For <buffer[=X]>, this condition works because we normalize
8531 * all buffer-local patterns.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008532 */
8533 if ((allgroups || ap->group == findgroup)
8534 && ap->patlen == patlen
8535 && STRNCMP(pat, ap->pat, patlen) == 0)
8536 {
8537 /*
8538 * Remove existing autocommands.
8539 * If adding any new autocmd's for this AutoPat, don't
8540 * delete the pattern from the autopat list, append to
8541 * this list.
8542 */
8543 if (forceit)
8544 {
8545 if (*cmd != NUL && ap->next == NULL)
8546 {
8547 au_remove_cmds(ap);
8548 break;
8549 }
8550 au_remove_pat(ap);
8551 }
8552
8553 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008554 * Show autocmd's for this autopat, or buflocals <buffer=X>
Bram Moolenaar071d4272004-06-13 20:20:40 +00008555 */
8556 else if (*cmd == NUL)
8557 show_autocmd(ap, event);
8558
8559 /*
8560 * Add autocmd to this autopat, if it's the last one.
8561 */
8562 else if (ap->next == NULL)
8563 break;
8564 }
8565 }
8566 prev_ap = &ap->next;
8567 }
8568
8569 /*
8570 * Add a new command.
8571 */
8572 if (*cmd != NUL)
8573 {
8574 /*
8575 * If the pattern we want to add a command to does appear at the
8576 * end of the list (or not is not in the list at all), add the
8577 * pattern at the end of the list.
8578 */
8579 if (ap == NULL)
8580 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008581 /* refuse to add buffer-local ap if buffer number is invalid */
8582 if (is_buflocal && (buflocal_nr == 0
8583 || buflist_findnr(buflocal_nr) == NULL))
8584 {
8585 EMSGN(_("E680: <buffer=%d>: invalid buffer number "),
8586 buflocal_nr);
8587 return FAIL;
8588 }
8589
Bram Moolenaar071d4272004-06-13 20:20:40 +00008590 ap = (AutoPat *)alloc((unsigned)sizeof(AutoPat));
8591 if (ap == NULL)
8592 return FAIL;
8593 ap->pat = vim_strnsave(pat, patlen);
8594 ap->patlen = patlen;
8595 if (ap->pat == NULL)
8596 {
8597 vim_free(ap);
8598 return FAIL;
8599 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008600
8601 if (is_buflocal)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008602 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008603 ap->buflocal_nr = buflocal_nr;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008604 ap->reg_prog = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008605 }
8606 else
8607 {
Bram Moolenaar748bf032005-02-02 23:04:36 +00008608 char_u *reg_pat;
8609
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008610 ap->buflocal_nr = 0;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008611 reg_pat = file_pat_to_reg_pat(pat, endpat,
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008612 &ap->allow_dirs, TRUE);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008613 if (reg_pat != NULL)
8614 ap->reg_prog = vim_regcomp(reg_pat, RE_MAGIC);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008615 vim_free(reg_pat);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008616 if (reg_pat == NULL || ap->reg_prog == NULL)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008617 {
8618 vim_free(ap->pat);
8619 vim_free(ap);
8620 return FAIL;
8621 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008622 }
8623 ap->cmds = NULL;
8624 *prev_ap = ap;
8625 ap->next = NULL;
8626 if (group == AUGROUP_ALL)
8627 ap->group = current_augroup;
8628 else
8629 ap->group = group;
8630 }
8631
8632 /*
8633 * Add the autocmd at the end of the AutoCmd list.
8634 */
8635 prev_ac = &(ap->cmds);
8636 while ((ac = *prev_ac) != NULL)
8637 prev_ac = &ac->next;
8638 ac = (AutoCmd *)alloc((unsigned)sizeof(AutoCmd));
8639 if (ac == NULL)
8640 return FAIL;
8641 ac->cmd = vim_strsave(cmd);
8642#ifdef FEAT_EVAL
8643 ac->scriptID = current_SID;
8644#endif
8645 if (ac->cmd == NULL)
8646 {
8647 vim_free(ac);
8648 return FAIL;
8649 }
8650 ac->next = NULL;
8651 *prev_ac = ac;
8652 ac->nested = nested;
8653 }
8654 }
8655
8656 au_cleanup(); /* may really delete removed patterns/commands now */
8657 return OK;
8658}
8659
8660/*
8661 * Implementation of ":doautocmd [group] event [fname]".
8662 * Return OK for success, FAIL for failure;
8663 */
8664 int
8665do_doautocmd(arg, do_msg)
8666 char_u *arg;
8667 int do_msg; /* give message for no matching autocmds? */
8668{
8669 char_u *fname;
8670 int nothing_done = TRUE;
8671 int group;
8672
8673 /*
8674 * Check for a legal group name. If not, use AUGROUP_ALL.
8675 */
8676 group = au_get_grouparg(&arg);
8677 if (arg == NULL) /* out of memory */
8678 return FAIL;
8679
8680 if (*arg == '*')
8681 {
8682 EMSG(_("E217: Can't execute autocommands for ALL events"));
8683 return FAIL;
8684 }
8685
8686 /*
8687 * Scan over the events.
8688 * If we find an illegal name, return here, don't do anything.
8689 */
8690 fname = find_end_event(arg, group != AUGROUP_ALL);
8691 if (fname == NULL)
8692 return FAIL;
8693
8694 fname = skipwhite(fname);
8695
8696 /*
8697 * Loop over the events.
8698 */
8699 while (*arg && !vim_iswhite(*arg))
8700 if (apply_autocmds_group(event_name2nr(arg, &arg),
8701 fname, NULL, TRUE, group, curbuf, NULL))
8702 nothing_done = FALSE;
8703
8704 if (nothing_done && do_msg)
8705 MSG(_("No matching autocommands"));
8706
8707#ifdef FEAT_EVAL
8708 return aborting() ? FAIL : OK;
8709#else
8710 return OK;
8711#endif
8712}
8713
8714/*
8715 * ":doautoall": execute autocommands for each loaded buffer.
8716 */
8717 void
8718ex_doautoall(eap)
8719 exarg_T *eap;
8720{
8721 int retval;
8722 aco_save_T aco;
8723 buf_T *buf;
8724
8725 /*
8726 * This is a bit tricky: For some commands curwin->w_buffer needs to be
8727 * equal to curbuf, but for some buffers there may not be a window.
8728 * So we change the buffer for the current window for a moment. This
8729 * gives problems when the autocommands make changes to the list of
8730 * buffers or windows...
8731 */
8732 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8733 {
Bram Moolenaar3a847972008-07-08 09:36:58 +00008734 if (buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008735 {
8736 /* find a window for this buffer and save some values */
8737 aucmd_prepbuf(&aco, buf);
8738
8739 /* execute the autocommands for this buffer */
8740 retval = do_doautocmd(eap->arg, FALSE);
Bram Moolenaareeefcc72007-05-01 21:21:21 +00008741
8742 /* Execute the modeline settings, but don't set window-local
8743 * options if we are using the current window for another buffer. */
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008744 do_modelines(curwin == aucmd_win ? OPT_NOWIN : 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008745
8746 /* restore the current window */
8747 aucmd_restbuf(&aco);
8748
8749 /* stop if there is some error or buffer was deleted */
8750 if (retval == FAIL || !buf_valid(buf))
8751 break;
8752 }
8753 }
8754
8755 check_cursor(); /* just in case lines got deleted */
8756}
8757
8758/*
8759 * Prepare for executing autocommands for (hidden) buffer "buf".
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008760 * Search for a visible window containing the current buffer. If there isn't
8761 * one then use "aucmd_win".
Bram Moolenaar071d4272004-06-13 20:20:40 +00008762 * Set "curbuf" and "curwin" to match "buf".
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00008763 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008764 */
8765 void
8766aucmd_prepbuf(aco, buf)
8767 aco_save_T *aco; /* structure to save values in */
8768 buf_T *buf; /* new curbuf */
8769{
8770 win_T *win;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008771#ifdef FEAT_WINDOWS
8772 int save_ea;
8773#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008774
8775 /* Find a window that is for the new buffer */
8776 if (buf == curbuf) /* be quick when buf is curbuf */
8777 win = curwin;
8778 else
8779#ifdef FEAT_WINDOWS
8780 for (win = firstwin; win != NULL; win = win->w_next)
8781 if (win->w_buffer == buf)
8782 break;
8783#else
8784 win = NULL;
8785#endif
8786
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008787 /* Allocate "aucmd_win" when needed. If this fails (out of memory) fall
8788 * back to using the current window. */
8789 if (win == NULL && aucmd_win == NULL)
8790 {
8791 win_alloc_aucmd_win();
8792 if (aucmd_win == NULL)
8793 win = curwin;
8794 }
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008795 if (win == NULL && aucmd_win_used)
8796 /* Strange recursive autocommand, fall back to using the current
8797 * window. Expect a few side effects... */
8798 win = curwin;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008799
8800 aco->save_curwin = curwin;
8801 aco->save_curbuf = curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008802 if (win != NULL)
8803 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008804 /* There is a window for "buf" in the current tab page, make it the
8805 * curwin. This is preferred, it has the least side effects (esp. if
8806 * "buf" is curbuf). */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008807 aco->use_aucmd_win = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008808 curwin = win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008809 }
8810 else
8811 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008812 /* There is no window for "buf", use "aucmd_win". To minimize the side
8813 * effects, insert it in a the current tab page.
8814 * Anything related to a window (e.g., setting folds) may have
8815 * unexpected results. */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008816 aco->use_aucmd_win = TRUE;
8817 aucmd_win_used = TRUE;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008818 aucmd_win->w_buffer = buf;
Bram Moolenaarcdddaa42010-06-07 23:07:44 +02008819 aucmd_win->w_s = &buf->b_s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008820 ++buf->b_nwindows;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008821 win_init_empty(aucmd_win); /* set cursor and topline to safe values */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008822 vim_free(aucmd_win->w_localdir);
8823 aucmd_win->w_localdir = NULL;
8824
8825 /* Make sure w_localdir and globaldir are NULL to avoid a chdir() in
8826 * win_enter_ext(). */
8827 aucmd_win->w_localdir = NULL;
8828 aco->globaldir = globaldir;
8829 globaldir = NULL;
8830
Bram Moolenaar071d4272004-06-13 20:20:40 +00008831
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008832#ifdef FEAT_WINDOWS
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008833 /* Split the current window, put the aucmd_win in the upper half.
8834 * We don't want the BufEnter or WinEnter autocommands. */
8835 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008836 make_snapshot(SNAP_AUCMD_IDX);
8837 save_ea = p_ea;
8838 p_ea = FALSE;
8839 (void)win_split_ins(0, WSP_TOP, aucmd_win, 0);
8840 (void)win_comp_pos(); /* recompute window positions */
8841 p_ea = save_ea;
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008842 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008843#endif
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008844 curwin = aucmd_win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008845 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008846 curbuf = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008847 aco->new_curwin = curwin;
8848 aco->new_curbuf = curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008849}
8850
8851/*
8852 * Cleanup after executing autocommands for a (hidden) buffer.
8853 * Restore the window as it was (if possible).
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00008854 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008855 */
8856 void
8857aucmd_restbuf(aco)
8858 aco_save_T *aco; /* structure holding saved values */
8859{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008860#ifdef FEAT_WINDOWS
8861 int dummy;
8862#endif
8863
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008864 if (aco->use_aucmd_win)
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008865 {
8866 --curbuf->b_nwindows;
8867#ifdef FEAT_WINDOWS
8868 /* Find "aucmd_win", it can't be closed, but it may be in another tab
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008869 * page. Do not trigger autocommands here. */
8870 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008871 if (curwin != aucmd_win)
8872 {
8873 tabpage_T *tp;
8874 win_T *wp;
8875
8876 FOR_ALL_TAB_WINDOWS(tp, wp)
8877 {
8878 if (wp == aucmd_win)
8879 {
8880 if (tp != curtab)
8881 goto_tabpage_tp(tp);
8882 win_goto(aucmd_win);
8883 break;
8884 }
8885 }
8886 }
8887
8888 /* Remove the window and frame from the tree of frames. */
8889 (void)winframe_remove(curwin, &dummy, NULL);
8890 win_remove(curwin, NULL);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008891 aucmd_win_used = FALSE;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008892 last_status(FALSE); /* may need to remove last status line */
8893 restore_snapshot(SNAP_AUCMD_IDX, FALSE);
8894 (void)win_comp_pos(); /* recompute window positions */
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008895 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008896
8897 if (win_valid(aco->save_curwin))
8898 curwin = aco->save_curwin;
8899 else
8900 /* Hmm, original window disappeared. Just use the first one. */
8901 curwin = firstwin;
8902# ifdef FEAT_EVAL
8903 vars_clear(&aucmd_win->w_vars.dv_hashtab); /* free all w: variables */
Bram Moolenaar50daf402009-11-17 13:57:22 +00008904 hash_init(&aucmd_win->w_vars.dv_hashtab); /* re-use the hashtab */
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008905# endif
8906#else
8907 curwin = aco->save_curwin;
8908#endif
8909 curbuf = curwin->w_buffer;
8910
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008911 vim_free(globaldir);
8912 globaldir = aco->globaldir;
8913
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008914 /* the buffer contents may have changed */
8915 check_cursor();
8916 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
8917 {
8918 curwin->w_topline = curbuf->b_ml.ml_line_count;
8919#ifdef FEAT_DIFF
8920 curwin->w_topfill = 0;
8921#endif
8922 }
8923#if defined(FEAT_GUI)
8924 /* Hide the scrollbars from the aucmd_win and update. */
8925 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_LEFT], FALSE);
8926 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_RIGHT], FALSE);
8927 gui_may_update_scrollbars();
8928#endif
8929 }
8930 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00008931 {
8932 /* restore curwin */
8933#ifdef FEAT_WINDOWS
8934 if (win_valid(aco->save_curwin))
8935#endif
8936 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008937 /* Restore the buffer which was previously edited by curwin, if
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008938 * it was changed, we are still the same window and the buffer is
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008939 * valid. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008940 if (curwin == aco->new_curwin
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008941 && curbuf != aco->new_curbuf
8942 && buf_valid(aco->new_curbuf)
8943 && aco->new_curbuf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008944 {
8945 --curbuf->b_nwindows;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008946 curbuf = aco->new_curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008947 curwin->w_buffer = curbuf;
8948 ++curbuf->b_nwindows;
8949 }
8950
8951 curwin = aco->save_curwin;
8952 curbuf = curwin->w_buffer;
8953 }
8954 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008955}
8956
8957static int autocmd_nested = FALSE;
8958
8959/*
8960 * Execute autocommands for "event" and file name "fname".
8961 * Return TRUE if some commands were executed.
8962 */
8963 int
8964apply_autocmds(event, fname, fname_io, force, buf)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008965 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008966 char_u *fname; /* NULL or empty means use actual file name */
8967 char_u *fname_io; /* fname to use for <afile> on cmdline */
8968 int force; /* when TRUE, ignore autocmd_busy */
8969 buf_T *buf; /* buffer for <abuf> */
8970{
8971 return apply_autocmds_group(event, fname, fname_io, force,
8972 AUGROUP_ALL, buf, NULL);
8973}
8974
8975/*
8976 * Like apply_autocmds(), but with extra "eap" argument. This takes care of
8977 * setting v:filearg.
8978 */
8979 static int
8980apply_autocmds_exarg(event, fname, fname_io, force, buf, eap)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008981 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008982 char_u *fname;
8983 char_u *fname_io;
8984 int force;
8985 buf_T *buf;
8986 exarg_T *eap;
8987{
8988 return apply_autocmds_group(event, fname, fname_io, force,
8989 AUGROUP_ALL, buf, eap);
8990}
8991
8992/*
8993 * Like apply_autocmds(), but handles the caller's retval. If the script
8994 * processing is being aborted or if retval is FAIL when inside a try
8995 * conditional, no autocommands are executed. If otherwise the autocommands
8996 * cause the script to be aborted, retval is set to FAIL.
8997 */
8998 int
8999apply_autocmds_retval(event, fname, fname_io, force, buf, retval)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009000 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009001 char_u *fname; /* NULL or empty means use actual file name */
9002 char_u *fname_io; /* fname to use for <afile> on cmdline */
9003 int force; /* when TRUE, ignore autocmd_busy */
9004 buf_T *buf; /* buffer for <abuf> */
9005 int *retval; /* pointer to caller's retval */
9006{
9007 int did_cmd;
9008
Bram Moolenaar1e015462005-09-25 22:16:38 +00009009#ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00009010 if (should_abort(*retval))
9011 return FALSE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00009012#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009013
9014 did_cmd = apply_autocmds_group(event, fname, fname_io, force,
9015 AUGROUP_ALL, buf, NULL);
Bram Moolenaar1e015462005-09-25 22:16:38 +00009016 if (did_cmd
9017#ifdef FEAT_EVAL
9018 && aborting()
9019#endif
9020 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00009021 *retval = FAIL;
9022 return did_cmd;
9023}
9024
Bram Moolenaard35f9712005-12-18 22:02:33 +00009025/*
9026 * Return TRUE when there is a CursorHold autocommand defined.
9027 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009028 int
9029has_cursorhold()
9030{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009031 return (first_autopat[(int)(get_real_state() == NORMAL_BUSY
9032 ? EVENT_CURSORHOLD : EVENT_CURSORHOLDI)] != NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009033}
Bram Moolenaard35f9712005-12-18 22:02:33 +00009034
9035/*
9036 * Return TRUE if the CursorHold event can be triggered.
9037 */
9038 int
9039trigger_cursorhold()
9040{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009041 int state;
9042
Bram Moolenaard29a9ee2006-09-14 09:07:34 +00009043 if (!did_cursorhold && has_cursorhold() && !Recording
9044#ifdef FEAT_INS_EXPAND
9045 && !ins_compl_active()
9046#endif
9047 )
Bram Moolenaar754b5602006-02-09 23:53:20 +00009048 {
9049 state = get_real_state();
9050 if (state == NORMAL_BUSY || (state & INSERT) != 0)
9051 return TRUE;
9052 }
9053 return FALSE;
Bram Moolenaard35f9712005-12-18 22:02:33 +00009054}
Bram Moolenaar754b5602006-02-09 23:53:20 +00009055
9056/*
9057 * Return TRUE when there is a CursorMoved autocommand defined.
9058 */
9059 int
9060has_cursormoved()
9061{
9062 return (first_autopat[(int)EVENT_CURSORMOVED] != NULL);
9063}
9064
9065/*
9066 * Return TRUE when there is a CursorMovedI autocommand defined.
9067 */
9068 int
9069has_cursormovedI()
9070{
9071 return (first_autopat[(int)EVENT_CURSORMOVEDI] != NULL);
9072}
Bram Moolenaar071d4272004-06-13 20:20:40 +00009073
9074 static int
9075apply_autocmds_group(event, fname, fname_io, force, group, buf, eap)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009076 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009077 char_u *fname; /* NULL or empty means use actual file name */
9078 char_u *fname_io; /* fname to use for <afile> on cmdline, NULL means
9079 use fname */
9080 int force; /* when TRUE, ignore autocmd_busy */
9081 int group; /* group ID, or AUGROUP_ALL */
9082 buf_T *buf; /* buffer for <abuf> */
9083 exarg_T *eap; /* command arguments */
9084{
9085 char_u *sfname = NULL; /* short file name */
9086 char_u *tail;
9087 int save_changed;
9088 buf_T *old_curbuf;
9089 int retval = FALSE;
9090 char_u *save_sourcing_name;
9091 linenr_T save_sourcing_lnum;
9092 char_u *save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009093 int save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009094 int save_autocmd_bufnr;
9095 char_u *save_autocmd_match;
9096 int save_autocmd_busy;
9097 int save_autocmd_nested;
9098 static int nesting = 0;
9099 AutoPatCmd patcmd;
9100 AutoPat *ap;
9101#ifdef FEAT_EVAL
9102 scid_T save_current_SID;
9103 void *save_funccalp;
9104 char_u *save_cmdarg;
9105 long save_cmdbang;
9106#endif
9107 static int filechangeshell_busy = FALSE;
Bram Moolenaar05159a02005-02-26 23:04:13 +00009108#ifdef FEAT_PROFILE
9109 proftime_T wait_time;
9110#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009111
9112 /*
9113 * Quickly return if there are no autocommands for this event or
9114 * autocommands are blocked.
9115 */
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009116 if (first_autopat[(int)event] == NULL || autocmd_blocked > 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009117 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009118
9119 /*
9120 * When autocommands are busy, new autocommands are only executed when
9121 * explicitly enabled with the "nested" flag.
9122 */
9123 if (autocmd_busy && !(force || autocmd_nested))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009124 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009125
9126#ifdef FEAT_EVAL
9127 /*
Bram Moolenaar7263a772007-05-10 17:35:54 +00009128 * Quickly return when immediately aborting on error, or when an interrupt
Bram Moolenaar071d4272004-06-13 20:20:40 +00009129 * occurred or an exception was thrown but not caught.
9130 */
9131 if (aborting())
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009132 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009133#endif
9134
9135 /*
9136 * FileChangedShell never nests, because it can create an endless loop.
9137 */
Bram Moolenaar56718732006-03-15 22:53:57 +00009138 if (filechangeshell_busy && (event == EVENT_FILECHANGEDSHELL
9139 || event == EVENT_FILECHANGEDSHELLPOST))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009140 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009141
9142 /*
9143 * Ignore events in 'eventignore'.
9144 */
9145 if (event_ignored(event))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009146 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009147
9148 /*
9149 * Allow nesting of autocommands, but restrict the depth, because it's
9150 * possible to create an endless loop.
9151 */
9152 if (nesting == 10)
9153 {
9154 EMSG(_("E218: autocommand nesting too deep"));
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009155 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009156 }
9157
9158 /*
9159 * Check if these autocommands are disabled. Used when doing ":all" or
9160 * ":ball".
9161 */
9162 if ( (autocmd_no_enter
9163 && (event == EVENT_WINENTER || event == EVENT_BUFENTER))
9164 || (autocmd_no_leave
9165 && (event == EVENT_WINLEAVE || event == EVENT_BUFLEAVE)))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009166 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009167
9168 /*
9169 * Save the autocmd_* variables and info about the current buffer.
9170 */
9171 save_autocmd_fname = autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009172 save_autocmd_fname_full = autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009173 save_autocmd_bufnr = autocmd_bufnr;
9174 save_autocmd_match = autocmd_match;
9175 save_autocmd_busy = autocmd_busy;
9176 save_autocmd_nested = autocmd_nested;
9177 save_changed = curbuf->b_changed;
9178 old_curbuf = curbuf;
9179
9180 /*
9181 * Set the file name to be used for <afile>.
Bram Moolenaara0174af2008-01-02 20:08:25 +00009182 * Make a copy to avoid that changing a buffer name or directory makes it
9183 * invalid.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009184 */
9185 if (fname_io == NULL)
9186 {
9187 if (fname != NULL && *fname != NUL)
9188 autocmd_fname = fname;
9189 else if (buf != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009190 autocmd_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009191 else
9192 autocmd_fname = NULL;
9193 }
9194 else
9195 autocmd_fname = fname_io;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009196 if (autocmd_fname != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009197 autocmd_fname = vim_strsave(autocmd_fname);
9198 autocmd_fname_full = FALSE; /* call FullName_save() later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009199
9200 /*
9201 * Set the buffer number to be used for <abuf>.
9202 */
9203 if (buf == NULL)
9204 autocmd_bufnr = 0;
9205 else
9206 autocmd_bufnr = buf->b_fnum;
9207
9208 /*
9209 * When the file name is NULL or empty, use the file name of buffer "buf".
9210 * Always use the full path of the file name to match with, in case
9211 * "allow_dirs" is set.
9212 */
9213 if (fname == NULL || *fname == NUL)
9214 {
9215 if (buf == NULL)
9216 fname = NULL;
9217 else
9218 {
9219#ifdef FEAT_SYN_HL
9220 if (event == EVENT_SYNTAX)
9221 fname = buf->b_p_syn;
9222 else
9223#endif
9224 if (event == EVENT_FILETYPE)
9225 fname = buf->b_p_ft;
9226 else
9227 {
9228 if (buf->b_sfname != NULL)
9229 sfname = vim_strsave(buf->b_sfname);
9230 fname = buf->b_ffname;
9231 }
9232 }
9233 if (fname == NULL)
9234 fname = (char_u *)"";
9235 fname = vim_strsave(fname); /* make a copy, so we can change it */
9236 }
9237 else
9238 {
9239 sfname = vim_strsave(fname);
Bram Moolenaar5135d462009-04-29 16:03:38 +00009240 /* Don't try expanding FileType, Syntax, FuncUndefined, WindowID or
9241 * QuickFixCmd* */
Bram Moolenaar7c626922005-02-07 22:01:03 +00009242 if (event == EVENT_FILETYPE
9243 || event == EVENT_SYNTAX
Bram Moolenaar5135d462009-04-29 16:03:38 +00009244 || event == EVENT_FUNCUNDEFINED
Bram Moolenaar7c626922005-02-07 22:01:03 +00009245 || event == EVENT_REMOTEREPLY
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00009246 || event == EVENT_SPELLFILEMISSING
Bram Moolenaar7c626922005-02-07 22:01:03 +00009247 || event == EVENT_QUICKFIXCMDPRE
9248 || event == EVENT_QUICKFIXCMDPOST)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009249 fname = vim_strsave(fname);
9250 else
9251 fname = FullName_save(fname, FALSE);
9252 }
9253 if (fname == NULL) /* out of memory */
9254 {
9255 vim_free(sfname);
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009256 retval = FALSE;
9257 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009258 }
9259
9260#ifdef BACKSLASH_IN_FILENAME
9261 /*
9262 * Replace all backslashes with forward slashes. This makes the
9263 * autocommand patterns portable between Unix and MS-DOS.
9264 */
9265 if (sfname != NULL)
9266 forward_slash(sfname);
9267 forward_slash(fname);
9268#endif
9269
9270#ifdef VMS
9271 /* remove version for correct match */
9272 if (sfname != NULL)
9273 vms_remove_version(sfname);
9274 vms_remove_version(fname);
9275#endif
9276
9277 /*
9278 * Set the name to be used for <amatch>.
9279 */
9280 autocmd_match = fname;
9281
9282
9283 /* Don't redraw while doing auto commands. */
9284 ++RedrawingDisabled;
9285 save_sourcing_name = sourcing_name;
9286 sourcing_name = NULL; /* don't free this one */
9287 save_sourcing_lnum = sourcing_lnum;
9288 sourcing_lnum = 0; /* no line number here */
9289
9290#ifdef FEAT_EVAL
9291 save_current_SID = current_SID;
9292
Bram Moolenaar05159a02005-02-26 23:04:13 +00009293# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009294 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009295 prof_child_enter(&wait_time); /* doesn't count for the caller itself */
9296# endif
9297
Bram Moolenaar071d4272004-06-13 20:20:40 +00009298 /* Don't use local function variables, if called from a function */
9299 save_funccalp = save_funccal();
9300#endif
9301
9302 /*
9303 * When starting to execute autocommands, save the search patterns.
9304 */
9305 if (!autocmd_busy)
9306 {
9307 save_search_patterns();
9308 saveRedobuff();
9309 did_filetype = keep_filetype;
9310 }
9311
9312 /*
9313 * Note that we are applying autocmds. Some commands need to know.
9314 */
9315 autocmd_busy = TRUE;
9316 filechangeshell_busy = (event == EVENT_FILECHANGEDSHELL);
9317 ++nesting; /* see matching decrement below */
9318
9319 /* Remember that FileType was triggered. Used for did_filetype(). */
9320 if (event == EVENT_FILETYPE)
9321 did_filetype = TRUE;
9322
9323 tail = gettail(fname);
9324
9325 /* Find first autocommand that matches */
9326 patcmd.curpat = first_autopat[(int)event];
9327 patcmd.nextcmd = NULL;
9328 patcmd.group = group;
9329 patcmd.fname = fname;
9330 patcmd.sfname = sfname;
9331 patcmd.tail = tail;
9332 patcmd.event = event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009333 patcmd.arg_bufnr = autocmd_bufnr;
9334 patcmd.next = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009335 auto_next_pat(&patcmd, FALSE);
9336
9337 /* found one, start executing the autocommands */
9338 if (patcmd.curpat != NULL)
9339 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009340 /* add to active_apc_list */
9341 patcmd.next = active_apc_list;
9342 active_apc_list = &patcmd;
9343
Bram Moolenaar071d4272004-06-13 20:20:40 +00009344#ifdef FEAT_EVAL
9345 /* set v:cmdarg (only when there is a matching pattern) */
9346 save_cmdbang = get_vim_var_nr(VV_CMDBANG);
9347 if (eap != NULL)
9348 {
9349 save_cmdarg = set_cmdarg(eap, NULL);
9350 set_vim_var_nr(VV_CMDBANG, (long)eap->forceit);
9351 }
9352 else
9353 save_cmdarg = NULL; /* avoid gcc warning */
9354#endif
9355 retval = TRUE;
9356 /* mark the last pattern, to avoid an endless loop when more patterns
9357 * are added when executing autocommands */
9358 for (ap = patcmd.curpat; ap->next != NULL; ap = ap->next)
9359 ap->last = FALSE;
9360 ap->last = TRUE;
9361 check_lnums(TRUE); /* make sure cursor and topline are valid */
9362 do_cmdline(NULL, getnextac, (void *)&patcmd,
9363 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
9364#ifdef FEAT_EVAL
9365 if (eap != NULL)
9366 {
9367 (void)set_cmdarg(NULL, save_cmdarg);
9368 set_vim_var_nr(VV_CMDBANG, save_cmdbang);
9369 }
9370#endif
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009371 /* delete from active_apc_list */
9372 if (active_apc_list == &patcmd) /* just in case */
9373 active_apc_list = patcmd.next;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009374 }
9375
9376 --RedrawingDisabled;
9377 autocmd_busy = save_autocmd_busy;
9378 filechangeshell_busy = FALSE;
9379 autocmd_nested = save_autocmd_nested;
9380 vim_free(sourcing_name);
9381 sourcing_name = save_sourcing_name;
9382 sourcing_lnum = save_sourcing_lnum;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009383 vim_free(autocmd_fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009384 autocmd_fname = save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009385 autocmd_fname_full = save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009386 autocmd_bufnr = save_autocmd_bufnr;
9387 autocmd_match = save_autocmd_match;
9388#ifdef FEAT_EVAL
9389 current_SID = save_current_SID;
9390 restore_funccal(save_funccalp);
Bram Moolenaar05159a02005-02-26 23:04:13 +00009391# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009392 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009393 prof_child_exit(&wait_time);
9394# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009395#endif
9396 vim_free(fname);
9397 vim_free(sfname);
9398 --nesting; /* see matching increment above */
9399
9400 /*
9401 * When stopping to execute autocommands, restore the search patterns and
9402 * the redo buffer.
9403 */
9404 if (!autocmd_busy)
9405 {
9406 restore_search_patterns();
9407 restoreRedobuff();
9408 did_filetype = FALSE;
9409 }
9410
9411 /*
9412 * Some events don't set or reset the Changed flag.
9413 * Check if still in the same buffer!
9414 */
9415 if (curbuf == old_curbuf
9416 && (event == EVENT_BUFREADPOST
9417 || event == EVENT_BUFWRITEPOST
9418 || event == EVENT_FILEAPPENDPOST
9419 || event == EVENT_VIMLEAVE
9420 || event == EVENT_VIMLEAVEPRE))
9421 {
9422#ifdef FEAT_TITLE
9423 if (curbuf->b_changed != save_changed)
9424 need_maketitle = TRUE;
9425#endif
9426 curbuf->b_changed = save_changed;
9427 }
9428
9429 au_cleanup(); /* may really delete removed patterns/commands now */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009430
9431BYPASS_AU:
9432 /* When wiping out a buffer make sure all its buffer-local autocommands
9433 * are deleted. */
9434 if (event == EVENT_BUFWIPEOUT && buf != NULL)
9435 aubuflocal_remove(buf);
9436
Bram Moolenaar071d4272004-06-13 20:20:40 +00009437 return retval;
9438}
9439
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009440# ifdef FEAT_EVAL
9441static char_u *old_termresponse = NULL;
9442# endif
9443
9444/*
9445 * Block triggering autocommands until unblock_autocmd() is called.
9446 * Can be used recursively, so long as it's symmetric.
9447 */
9448 void
9449block_autocmds()
9450{
9451# ifdef FEAT_EVAL
9452 /* Remember the value of v:termresponse. */
9453 if (autocmd_blocked == 0)
9454 old_termresponse = get_vim_var_str(VV_TERMRESPONSE);
9455# endif
9456 ++autocmd_blocked;
9457}
9458
9459 void
9460unblock_autocmds()
9461{
9462 --autocmd_blocked;
9463
9464# ifdef FEAT_EVAL
9465 /* When v:termresponse was set while autocommands were blocked, trigger
9466 * the autocommands now. Esp. useful when executing a shell command
9467 * during startup (vimdiff). */
9468 if (autocmd_blocked == 0
9469 && get_vim_var_str(VV_TERMRESPONSE) != old_termresponse)
9470 apply_autocmds(EVENT_TERMRESPONSE, NULL, NULL, FALSE, curbuf);
9471# endif
9472}
9473
Bram Moolenaar071d4272004-06-13 20:20:40 +00009474/*
9475 * Find next autocommand pattern that matches.
9476 */
9477 static void
9478auto_next_pat(apc, stop_at_last)
9479 AutoPatCmd *apc;
9480 int stop_at_last; /* stop when 'last' flag is set */
9481{
9482 AutoPat *ap;
9483 AutoCmd *cp;
9484 char_u *name;
9485 char *s;
9486
9487 vim_free(sourcing_name);
9488 sourcing_name = NULL;
9489
9490 for (ap = apc->curpat; ap != NULL && !got_int; ap = ap->next)
9491 {
9492 apc->curpat = NULL;
9493
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009494 /* Only use a pattern when it has not been removed, has commands and
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009495 * the group matches. For buffer-local autocommands only check the
9496 * buffer number. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009497 if (ap->pat != NULL && ap->cmds != NULL
9498 && (apc->group == AUGROUP_ALL || apc->group == ap->group))
9499 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009500 /* execution-condition */
9501 if (ap->buflocal_nr == 0
Bram Moolenaar748bf032005-02-02 23:04:36 +00009502 ? (match_file_pat(NULL, ap->reg_prog, apc->fname,
9503 apc->sfname, apc->tail, ap->allow_dirs))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009504 : ap->buflocal_nr == apc->arg_bufnr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009505 {
9506 name = event_nr2name(apc->event);
9507 s = _("%s Auto commands for \"%s\"");
9508 sourcing_name = alloc((unsigned)(STRLEN(s)
9509 + STRLEN(name) + ap->patlen + 1));
9510 if (sourcing_name != NULL)
9511 {
9512 sprintf((char *)sourcing_name, s,
9513 (char *)name, (char *)ap->pat);
9514 if (p_verbose >= 8)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009515 {
9516 verbose_enter();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009517 smsg((char_u *)_("Executing %s"), sourcing_name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009518 verbose_leave();
9519 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009520 }
9521
9522 apc->curpat = ap;
9523 apc->nextcmd = ap->cmds;
9524 /* mark last command */
9525 for (cp = ap->cmds; cp->next != NULL; cp = cp->next)
9526 cp->last = FALSE;
9527 cp->last = TRUE;
9528 }
9529 line_breakcheck();
9530 if (apc->curpat != NULL) /* found a match */
9531 break;
9532 }
9533 if (stop_at_last && ap->last)
9534 break;
9535 }
9536}
9537
9538/*
9539 * Get next autocommand command.
9540 * Called by do_cmdline() to get the next line for ":if".
9541 * Returns allocated string, or NULL for end of autocommands.
9542 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009543 static char_u *
9544getnextac(c, cookie, indent)
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009545 int c UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009546 void *cookie;
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009547 int indent UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009548{
9549 AutoPatCmd *acp = (AutoPatCmd *)cookie;
9550 char_u *retval;
9551 AutoCmd *ac;
9552
9553 /* Can be called again after returning the last line. */
9554 if (acp->curpat == NULL)
9555 return NULL;
9556
9557 /* repeat until we find an autocommand to execute */
9558 for (;;)
9559 {
9560 /* skip removed commands */
9561 while (acp->nextcmd != NULL && acp->nextcmd->cmd == NULL)
9562 if (acp->nextcmd->last)
9563 acp->nextcmd = NULL;
9564 else
9565 acp->nextcmd = acp->nextcmd->next;
9566
9567 if (acp->nextcmd != NULL)
9568 break;
9569
9570 /* at end of commands, find next pattern that matches */
9571 if (acp->curpat->last)
9572 acp->curpat = NULL;
9573 else
9574 acp->curpat = acp->curpat->next;
9575 if (acp->curpat != NULL)
9576 auto_next_pat(acp, TRUE);
9577 if (acp->curpat == NULL)
9578 return NULL;
9579 }
9580
9581 ac = acp->nextcmd;
9582
9583 if (p_verbose >= 9)
9584 {
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009585 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009586 smsg((char_u *)_("autocommand %s"), ac->cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009587 msg_puts((char_u *)"\n"); /* don't overwrite this either */
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009588 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009589 }
9590 retval = vim_strsave(ac->cmd);
9591 autocmd_nested = ac->nested;
9592#ifdef FEAT_EVAL
9593 current_SID = ac->scriptID;
9594#endif
9595 if (ac->last)
9596 acp->nextcmd = NULL;
9597 else
9598 acp->nextcmd = ac->next;
9599 return retval;
9600}
9601
9602/*
9603 * Return TRUE if there is a matching autocommand for "fname".
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009604 * To account for buffer-local autocommands, function needs to know
9605 * in which buffer the file will be opened.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009606 */
9607 int
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009608has_autocmd(event, sfname, buf)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009609 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009610 char_u *sfname;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009611 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009612{
9613 AutoPat *ap;
9614 char_u *fname;
9615 char_u *tail = gettail(sfname);
9616 int retval = FALSE;
9617
9618 fname = FullName_save(sfname, FALSE);
9619 if (fname == NULL)
9620 return FALSE;
9621
9622#ifdef BACKSLASH_IN_FILENAME
9623 /*
9624 * Replace all backslashes with forward slashes. This makes the
9625 * autocommand patterns portable between Unix and MS-DOS.
9626 */
9627 sfname = vim_strsave(sfname);
9628 if (sfname != NULL)
9629 forward_slash(sfname);
9630 forward_slash(fname);
9631#endif
9632
9633 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
9634 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009635 && (ap->buflocal_nr == 0
Bram Moolenaar748bf032005-02-02 23:04:36 +00009636 ? match_file_pat(NULL, ap->reg_prog,
9637 fname, sfname, tail, ap->allow_dirs)
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009638 : buf != NULL && ap->buflocal_nr == buf->b_fnum
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009639 ))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009640 {
9641 retval = TRUE;
9642 break;
9643 }
9644
9645 vim_free(fname);
9646#ifdef BACKSLASH_IN_FILENAME
9647 vim_free(sfname);
9648#endif
9649
9650 return retval;
9651}
9652
9653#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
9654/*
9655 * Function given to ExpandGeneric() to obtain the list of autocommand group
9656 * names.
9657 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009658 char_u *
9659get_augroup_name(xp, idx)
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009660 expand_T *xp UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009661 int idx;
9662{
9663 if (idx == augroups.ga_len) /* add "END" add the end */
9664 return (char_u *)"END";
9665 if (idx >= augroups.ga_len) /* end of list */
9666 return NULL;
9667 if (AUGROUP_NAME(idx) == NULL) /* skip deleted entries */
9668 return (char_u *)"";
9669 return AUGROUP_NAME(idx); /* return a name */
9670}
9671
9672static int include_groups = FALSE;
9673
9674 char_u *
9675set_context_in_autocmd(xp, arg, doautocmd)
9676 expand_T *xp;
9677 char_u *arg;
Bram Moolenaard812df62008-11-09 12:46:09 +00009678 int doautocmd; /* TRUE for :doauto*, FALSE for :autocmd */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009679{
9680 char_u *p;
9681 int group;
9682
9683 /* check for a group name, skip it if present */
9684 include_groups = FALSE;
9685 p = arg;
9686 group = au_get_grouparg(&arg);
9687 if (group == AUGROUP_ERROR)
9688 return NULL;
9689 /* If there only is a group name that's what we expand. */
9690 if (*arg == NUL && group != AUGROUP_ALL && !vim_iswhite(arg[-1]))
9691 {
9692 arg = p;
9693 group = AUGROUP_ALL;
9694 }
9695
9696 /* skip over event name */
9697 for (p = arg; *p != NUL && !vim_iswhite(*p); ++p)
9698 if (*p == ',')
9699 arg = p + 1;
9700 if (*p == NUL)
9701 {
9702 if (group == AUGROUP_ALL)
9703 include_groups = TRUE;
9704 xp->xp_context = EXPAND_EVENTS; /* expand event name */
9705 xp->xp_pattern = arg;
9706 return NULL;
9707 }
9708
9709 /* skip over pattern */
9710 arg = skipwhite(p);
9711 while (*arg && (!vim_iswhite(*arg) || arg[-1] == '\\'))
9712 arg++;
9713 if (*arg)
9714 return arg; /* expand (next) command */
9715
9716 if (doautocmd)
9717 xp->xp_context = EXPAND_FILES; /* expand file names */
9718 else
9719 xp->xp_context = EXPAND_NOTHING; /* pattern is not expanded */
9720 return NULL;
9721}
9722
9723/*
9724 * Function given to ExpandGeneric() to obtain the list of event names.
9725 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009726 char_u *
9727get_event_name(xp, idx)
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009728 expand_T *xp UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009729 int idx;
9730{
9731 if (idx < augroups.ga_len) /* First list group names, if wanted */
9732 {
9733 if (!include_groups || AUGROUP_NAME(idx) == NULL)
9734 return (char_u *)""; /* skip deleted entries */
9735 return AUGROUP_NAME(idx); /* return a name */
9736 }
9737 return (char_u *)event_names[idx - augroups.ga_len].name;
9738}
9739
9740#endif /* FEAT_CMDL_COMPL */
9741
9742/*
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009743 * Return TRUE if autocmd is supported.
9744 */
9745 int
9746autocmd_supported(name)
9747 char_u *name;
9748{
9749 char_u *p;
9750
9751 return (event_name2nr(name, &p) != NUM_EVENTS);
9752}
9753
9754/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00009755 * Return TRUE if an autocommand is defined for a group, event and
9756 * pattern: The group can be omitted to accept any group. "event" and "pattern"
9757 * can be NULL to accept any event and pattern. "pattern" can be NULL to accept
9758 * any pattern. Buffer-local patterns <buffer> or <buffer=N> are accepted.
9759 * Used for:
9760 * exists("#Group") or
9761 * exists("#Group#Event") or
9762 * exists("#Group#Event#pat") or
9763 * exists("#Event") or
9764 * exists("#Event#pat")
Bram Moolenaar071d4272004-06-13 20:20:40 +00009765 */
9766 int
Bram Moolenaar195d6352005-12-19 22:08:24 +00009767au_exists(arg)
9768 char_u *arg;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009769{
Bram Moolenaar195d6352005-12-19 22:08:24 +00009770 char_u *arg_save;
9771 char_u *pattern = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009772 char_u *event_name;
9773 char_u *p;
Bram Moolenaar754b5602006-02-09 23:53:20 +00009774 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009775 AutoPat *ap;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009776 buf_T *buflocal_buf = NULL;
Bram Moolenaar195d6352005-12-19 22:08:24 +00009777 int group;
9778 int retval = FALSE;
9779
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009780 /* Make a copy so that we can change the '#' chars to a NUL. */
Bram Moolenaar195d6352005-12-19 22:08:24 +00009781 arg_save = vim_strsave(arg);
9782 if (arg_save == NULL)
9783 return FALSE;
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009784 p = vim_strchr(arg_save, '#');
Bram Moolenaar195d6352005-12-19 22:08:24 +00009785 if (p != NULL)
9786 *p++ = NUL;
9787
9788 /* First, look for an autocmd group name */
9789 group = au_find_group(arg_save);
9790 if (group == AUGROUP_ERROR)
9791 {
9792 /* Didn't match a group name, assume the first argument is an event. */
9793 group = AUGROUP_ALL;
9794 event_name = arg_save;
9795 }
9796 else
9797 {
9798 if (p == NULL)
9799 {
9800 /* "Group": group name is present and it's recognized */
9801 retval = TRUE;
9802 goto theend;
9803 }
9804
9805 /* Must be "Group#Event" or "Group#Event#pat". */
9806 event_name = p;
9807 p = vim_strchr(event_name, '#');
9808 if (p != NULL)
9809 *p++ = NUL; /* "Group#Event#pat" */
9810 }
9811
9812 pattern = p; /* "pattern" is NULL when there is no pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009813
9814 /* find the index (enum) for the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009815 event = event_name2nr(event_name, &p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009816
9817 /* return FALSE if the event name is not recognized */
Bram Moolenaar195d6352005-12-19 22:08:24 +00009818 if (event == NUM_EVENTS)
9819 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009820
9821 /* Find the first autocommand for this event.
9822 * If there isn't any, return FALSE;
9823 * If there is one and no pattern given, return TRUE; */
9824 ap = first_autopat[(int)event];
9825 if (ap == NULL)
Bram Moolenaar195d6352005-12-19 22:08:24 +00009826 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009827
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009828 /* if pattern is "<buffer>", special handling is needed which uses curbuf */
9829 /* for pattern "<buffer=N>, fnamecmp() will work fine */
Bram Moolenaar5b7880d2009-09-11 15:24:31 +00009830 if (pattern != NULL && STRICMP(pattern, "<buffer>") == 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009831 buflocal_buf = curbuf;
9832
Bram Moolenaar071d4272004-06-13 20:20:40 +00009833 /* Check if there is an autocommand with the given pattern. */
9834 for ( ; ap != NULL; ap = ap->next)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009835 /* only use a pattern when it has not been removed and has commands. */
9836 /* For buffer-local autocommands, fnamecmp() works fine. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009837 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaar195d6352005-12-19 22:08:24 +00009838 && (group == AUGROUP_ALL || ap->group == group)
Bram Moolenaar5b7880d2009-09-11 15:24:31 +00009839 && (pattern == NULL
9840 || (buflocal_buf == NULL
9841 ? fnamecmp(ap->pat, pattern) == 0
9842 : ap->buflocal_nr == buflocal_buf->b_fnum)))
Bram Moolenaar195d6352005-12-19 22:08:24 +00009843 {
9844 retval = TRUE;
9845 break;
9846 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009847
Bram Moolenaar195d6352005-12-19 22:08:24 +00009848theend:
9849 vim_free(arg_save);
9850 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009851}
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009852
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009853#else /* FEAT_AUTOCMD */
9854
9855/*
9856 * Prepare for executing commands for (hidden) buffer "buf".
9857 * This is the non-autocommand version, it simply saves "curbuf" and sets
9858 * "curbuf" and "curwin" to match "buf".
9859 */
9860 void
9861aucmd_prepbuf(aco, buf)
9862 aco_save_T *aco; /* structure to save values in */
9863 buf_T *buf; /* new curbuf */
9864{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009865 aco->save_curbuf = curbuf;
9866 --curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009867 curbuf = buf;
9868 curwin->w_buffer = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009869 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009870}
9871
9872/*
9873 * Restore after executing commands for a (hidden) buffer.
9874 * This is the non-autocommand version.
9875 */
9876 void
9877aucmd_restbuf(aco)
9878 aco_save_T *aco; /* structure holding saved values */
9879{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009880 --curbuf->b_nwindows;
9881 curbuf = aco->save_curbuf;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009882 curwin->w_buffer = curbuf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009883 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009884}
9885
Bram Moolenaar071d4272004-06-13 20:20:40 +00009886#endif /* FEAT_AUTOCMD */
9887
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009888
Bram Moolenaar071d4272004-06-13 20:20:40 +00009889#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN) || defined(PROTO)
9890/*
Bram Moolenaar748bf032005-02-02 23:04:36 +00009891 * Try matching a filename with a "pattern" ("prog" is NULL), or use the
9892 * precompiled regprog "prog" ("pattern" is NULL). That avoids calling
9893 * vim_regcomp() often.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009894 * Used for autocommands and 'wildignore'.
9895 * Returns TRUE if there is a match, FALSE otherwise.
9896 */
9897 int
Bram Moolenaar748bf032005-02-02 23:04:36 +00009898match_file_pat(pattern, prog, fname, sfname, tail, allow_dirs)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009899 char_u *pattern; /* pattern to match with */
Bram Moolenaar748bf032005-02-02 23:04:36 +00009900 regprog_T *prog; /* pre-compiled regprog or NULL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009901 char_u *fname; /* full path of file name */
9902 char_u *sfname; /* short file name or NULL */
9903 char_u *tail; /* tail of path */
9904 int allow_dirs; /* allow matching with dir */
9905{
9906 regmatch_T regmatch;
9907 int result = FALSE;
9908#ifdef FEAT_OSFILETYPE
9909 int no_pattern = FALSE; /* TRUE if check is filetype only */
9910 char_u *type_start;
9911 char_u c;
9912 int match = FALSE;
9913#endif
9914
9915#ifdef CASE_INSENSITIVE_FILENAME
9916 regmatch.rm_ic = TRUE; /* Always ignore case */
9917#else
9918 regmatch.rm_ic = FALSE; /* Don't ever ignore case */
9919#endif
9920#ifdef FEAT_OSFILETYPE
9921 if (*pattern == '<')
9922 {
9923 /* There is a filetype condition specified with this pattern.
9924 * Check the filetype matches first. If not, don't bother with the
9925 * pattern (set regprog to NULL).
9926 * Always use magic for the regexp.
9927 */
9928
9929 for (type_start = pattern + 1; (c = *pattern); pattern++)
9930 {
9931 if ((c == ';' || c == '>') && match == FALSE)
9932 {
9933 *pattern = NUL; /* Terminate the string */
9934 match = mch_check_filetype(fname, type_start);
9935 *pattern = c; /* Restore the terminator */
9936 type_start = pattern + 1;
9937 }
9938 if (c == '>')
9939 break;
9940 }
9941
9942 /* (c should never be NUL, but check anyway) */
9943 if (match == FALSE || c == NUL)
9944 regmatch.regprog = NULL; /* Doesn't match - don't check pat. */
9945 else if (*pattern == NUL)
9946 {
9947 regmatch.regprog = NULL; /* Vim will try to free regprog later */
9948 no_pattern = TRUE; /* Always matches - don't check pat. */
9949 }
9950 else
9951 regmatch.regprog = vim_regcomp(pattern + 1, RE_MAGIC);
9952 }
9953 else
9954#endif
Bram Moolenaar748bf032005-02-02 23:04:36 +00009955 {
9956 if (prog != NULL)
9957 regmatch.regprog = prog;
9958 else
9959 regmatch.regprog = vim_regcomp(pattern, RE_MAGIC);
9960 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009961
9962 /*
9963 * Try for a match with the pattern with:
9964 * 1. the full file name, when the pattern has a '/'.
9965 * 2. the short file name, when the pattern has a '/'.
9966 * 3. the tail of the file name, when the pattern has no '/'.
9967 */
9968 if (
9969#ifdef FEAT_OSFILETYPE
9970 /* If the check is for a filetype only and we don't care
9971 * about the path then skip all the regexp stuff.
9972 */
9973 no_pattern ||
9974#endif
9975 (regmatch.regprog != NULL
9976 && ((allow_dirs
9977 && (vim_regexec(&regmatch, fname, (colnr_T)0)
9978 || (sfname != NULL
9979 && vim_regexec(&regmatch, sfname, (colnr_T)0))))
9980 || (!allow_dirs && vim_regexec(&regmatch, tail, (colnr_T)0)))))
9981 result = TRUE;
9982
Bram Moolenaar748bf032005-02-02 23:04:36 +00009983 if (prog == NULL)
9984 vim_free(regmatch.regprog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009985 return result;
9986}
9987#endif
9988
9989#if defined(FEAT_WILDIGN) || defined(PROTO)
9990/*
9991 * Return TRUE if a file matches with a pattern in "list".
9992 * "list" is a comma-separated list of patterns, like 'wildignore'.
9993 * "sfname" is the short file name or NULL, "ffname" the long file name.
9994 */
9995 int
9996match_file_list(list, sfname, ffname)
9997 char_u *list;
9998 char_u *sfname;
9999 char_u *ffname;
10000{
10001 char_u buf[100];
10002 char_u *tail;
10003 char_u *regpat;
10004 char allow_dirs;
10005 int match;
10006 char_u *p;
10007
10008 tail = gettail(sfname);
10009
10010 /* try all patterns in 'wildignore' */
10011 p = list;
10012 while (*p)
10013 {
10014 copy_option_part(&p, buf, 100, ",");
10015 regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, FALSE);
10016 if (regpat == NULL)
10017 break;
Bram Moolenaar748bf032005-02-02 23:04:36 +000010018 match = match_file_pat(regpat, NULL, ffname, sfname,
10019 tail, (int)allow_dirs);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010020 vim_free(regpat);
10021 if (match)
10022 return TRUE;
10023 }
10024 return FALSE;
10025}
10026#endif
10027
10028/*
10029 * Convert the given pattern "pat" which has shell style wildcards in it, into
10030 * a regular expression, and return the result in allocated memory. If there
10031 * is a directory path separator to be matched, then TRUE is put in
10032 * allow_dirs, otherwise FALSE is put there -- webb.
10033 * Handle backslashes before special characters, like "\*" and "\ ".
10034 *
10035 * If FEAT_OSFILETYPE defined then pass initial <type> through unchanged. Eg:
10036 * '<html>myfile' becomes '<html>^myfile$' -- leonard.
10037 *
10038 * Returns NULL when out of memory.
10039 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010040 char_u *
10041file_pat_to_reg_pat(pat, pat_end, allow_dirs, no_bslash)
10042 char_u *pat;
10043 char_u *pat_end; /* first char after pattern or NULL */
10044 char *allow_dirs; /* Result passed back out in here */
Bram Moolenaar78a15312009-05-15 19:33:18 +000010045 int no_bslash UNUSED; /* Don't use a backward slash as pathsep */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010046{
10047 int size;
10048 char_u *endp;
10049 char_u *reg_pat;
10050 char_u *p;
10051 int i;
10052 int nested = 0;
10053 int add_dollar = TRUE;
10054#ifdef FEAT_OSFILETYPE
10055 int check_length = 0;
10056#endif
10057
10058 if (allow_dirs != NULL)
10059 *allow_dirs = FALSE;
10060 if (pat_end == NULL)
10061 pat_end = pat + STRLEN(pat);
10062
10063#ifdef FEAT_OSFILETYPE
10064 /* Find out how much of the string is the filetype check */
10065 if (*pat == '<')
10066 {
10067 /* Count chars until the next '>' */
10068 for (p = pat + 1; p < pat_end && *p != '>'; p++)
10069 ;
10070 if (p < pat_end)
10071 {
10072 /* Pattern is of the form <.*>.* */
10073 check_length = p - pat + 1;
10074 if (p + 1 >= pat_end)
10075 {
10076 /* The 'pattern' is a filetype check ONLY */
10077 reg_pat = (char_u *)alloc(check_length + 1);
10078 if (reg_pat != NULL)
10079 {
10080 mch_memmove(reg_pat, pat, (size_t)check_length);
10081 reg_pat[check_length] = NUL;
10082 }
10083 return reg_pat;
10084 }
10085 }
10086 /* else: there was no closing '>' - assume it was a normal pattern */
10087
10088 }
10089 pat += check_length;
10090 size = 2 + check_length;
10091#else
10092 size = 2; /* '^' at start, '$' at end */
10093#endif
10094
10095 for (p = pat; p < pat_end; p++)
10096 {
10097 switch (*p)
10098 {
10099 case '*':
10100 case '.':
10101 case ',':
10102 case '{':
10103 case '}':
10104 case '~':
10105 size += 2; /* extra backslash */
10106 break;
10107#ifdef BACKSLASH_IN_FILENAME
10108 case '\\':
10109 case '/':
10110 size += 4; /* could become "[\/]" */
10111 break;
10112#endif
10113 default:
10114 size++;
10115# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010116 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010117 {
10118 ++p;
10119 ++size;
10120 }
10121# endif
10122 break;
10123 }
10124 }
10125 reg_pat = alloc(size + 1);
10126 if (reg_pat == NULL)
10127 return NULL;
10128
10129#ifdef FEAT_OSFILETYPE
10130 /* Copy the type check in to the start. */
10131 if (check_length)
10132 mch_memmove(reg_pat, pat - check_length, (size_t)check_length);
10133 i = check_length;
10134#else
10135 i = 0;
10136#endif
10137
10138 if (pat[0] == '*')
10139 while (pat[0] == '*' && pat < pat_end - 1)
10140 pat++;
10141 else
10142 reg_pat[i++] = '^';
10143 endp = pat_end - 1;
10144 if (*endp == '*')
10145 {
10146 while (endp - pat > 0 && *endp == '*')
10147 endp--;
10148 add_dollar = FALSE;
10149 }
10150 for (p = pat; *p && nested >= 0 && p <= endp; p++)
10151 {
10152 switch (*p)
10153 {
10154 case '*':
10155 reg_pat[i++] = '.';
10156 reg_pat[i++] = '*';
Bram Moolenaar02743632005-07-25 20:42:36 +000010157 while (p[1] == '*') /* "**" matches like "*" */
10158 ++p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010159 break;
10160 case '.':
10161#ifdef RISCOS
10162 if (allow_dirs != NULL)
10163 *allow_dirs = TRUE;
10164 /* FALLTHROUGH */
10165#endif
10166 case '~':
10167 reg_pat[i++] = '\\';
10168 reg_pat[i++] = *p;
10169 break;
10170 case '?':
10171#ifdef RISCOS
10172 case '#':
10173#endif
10174 reg_pat[i++] = '.';
10175 break;
10176 case '\\':
10177 if (p[1] == NUL)
10178 break;
10179#ifdef BACKSLASH_IN_FILENAME
10180 if (!no_bslash)
10181 {
10182 /* translate:
10183 * "\x" to "\\x" e.g., "dir\file"
10184 * "\*" to "\\.*" e.g., "dir\*.c"
10185 * "\?" to "\\." e.g., "dir\??.c"
10186 * "\+" to "\+" e.g., "fileX\+.c"
10187 */
10188 if ((vim_isfilec(p[1]) || p[1] == '*' || p[1] == '?')
10189 && p[1] != '+')
10190 {
10191 reg_pat[i++] = '[';
10192 reg_pat[i++] = '\\';
10193 reg_pat[i++] = '/';
10194 reg_pat[i++] = ']';
10195 if (allow_dirs != NULL)
10196 *allow_dirs = TRUE;
10197 break;
10198 }
10199 }
10200#endif
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010201 /* Undo escaping from ExpandEscape():
10202 * foo\?bar -> foo?bar
10203 * foo\%bar -> foo%bar
10204 * foo\,bar -> foo,bar
10205 * foo\ bar -> foo bar
10206 * Don't unescape \, * and others that are also special in a
10207 * regexp. */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010208 if (*++p == '?'
10209#ifdef BACKSLASH_IN_FILENAME
10210 && no_bslash
10211#endif
10212 )
10213 reg_pat[i++] = '?';
10214 else
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010215 if (*p == ',' || *p == '%' || *p == '#' || *p == ' ')
10216 reg_pat[i++] = *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010217 else
10218 {
10219 if (allow_dirs != NULL && vim_ispathsep(*p)
10220#ifdef BACKSLASH_IN_FILENAME
10221 && (!no_bslash || *p != '\\')
10222#endif
10223 )
10224 *allow_dirs = TRUE;
10225 reg_pat[i++] = '\\';
10226 reg_pat[i++] = *p;
10227 }
10228 break;
10229#ifdef BACKSLASH_IN_FILENAME
10230 case '/':
10231 reg_pat[i++] = '[';
10232 reg_pat[i++] = '\\';
10233 reg_pat[i++] = '/';
10234 reg_pat[i++] = ']';
10235 if (allow_dirs != NULL)
10236 *allow_dirs = TRUE;
10237 break;
10238#endif
10239 case '{':
10240 reg_pat[i++] = '\\';
10241 reg_pat[i++] = '(';
10242 nested++;
10243 break;
10244 case '}':
10245 reg_pat[i++] = '\\';
10246 reg_pat[i++] = ')';
10247 --nested;
10248 break;
10249 case ',':
10250 if (nested)
10251 {
10252 reg_pat[i++] = '\\';
10253 reg_pat[i++] = '|';
10254 }
10255 else
10256 reg_pat[i++] = ',';
10257 break;
10258 default:
10259# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010260 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010261 reg_pat[i++] = *p++;
10262 else
10263# endif
10264 if (allow_dirs != NULL && vim_ispathsep(*p))
10265 *allow_dirs = TRUE;
10266 reg_pat[i++] = *p;
10267 break;
10268 }
10269 }
10270 if (add_dollar)
10271 reg_pat[i++] = '$';
10272 reg_pat[i] = NUL;
10273 if (nested != 0)
10274 {
10275 if (nested < 0)
10276 EMSG(_("E219: Missing {."));
10277 else
10278 EMSG(_("E220: Missing }."));
10279 vim_free(reg_pat);
10280 reg_pat = NULL;
10281 }
10282 return reg_pat;
10283}