blob: b6127d9dd4093a7b0f2dc16069c883296697558f [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
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000320#ifdef FEAT_AUTOCMD
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200321 buf_T *old_curbuf;
322 char_u *old_b_ffname;
323 char_u *old_b_fname;
324 int using_b_ffname;
325 int using_b_fname;
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000326#endif
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200327
Bram Moolenaar071d4272004-06-13 20:20:40 +0000328 write_no_eol_lnum = 0; /* in case it was set by the previous read */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000329
330 /*
331 * If there is no file name yet, use the one for the read file.
332 * BF_NOTEDITED is set to reflect this.
333 * Don't do this for a read from a filter.
334 * Only do this when 'cpoptions' contains the 'f' flag.
335 */
336 if (curbuf->b_ffname == NULL
337 && !filtering
338 && fname != NULL
339 && vim_strchr(p_cpo, CPO_FNAMER) != NULL
340 && !(flags & READ_DUMMY))
341 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000342 if (set_rw_fname(fname, sfname) == FAIL)
343 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000344 }
345
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200346#ifdef FEAT_AUTOCMD
347 /* Remember the initial values of curbuf, curbuf->b_ffname and
348 * curbuf->b_fname to detect whether they are altered as a result of
349 * executing nasty autocommands. Also check if "fname" and "sfname"
350 * point to one of these values. */
351 old_curbuf = curbuf;
352 old_b_ffname = curbuf->b_ffname;
353 old_b_fname = curbuf->b_fname;
354 using_b_ffname = (fname == curbuf->b_ffname)
355 || (sfname == curbuf->b_ffname);
356 using_b_fname = (fname == curbuf->b_fname) || (sfname == curbuf->b_fname);
357#endif
358
Bram Moolenaardf177f62005-02-22 08:39:57 +0000359 /* After reading a file the cursor line changes but we don't want to
360 * display the line. */
361 ex_no_reprint = TRUE;
362
Bram Moolenaar55b7cf82006-09-09 12:52:42 +0000363 /* don't display the file info for another buffer now */
364 need_fileinfo = FALSE;
365
Bram Moolenaar071d4272004-06-13 20:20:40 +0000366 /*
367 * For Unix: Use the short file name whenever possible.
368 * Avoids problems with networks and when directory names are changed.
369 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
370 * another directory, which we don't detect.
371 */
372 if (sfname == NULL)
373 sfname = fname;
374#if defined(UNIX) || defined(__EMX__)
375 fname = sfname;
376#endif
377
378#ifdef FEAT_AUTOCMD
379 /*
380 * The BufReadCmd and FileReadCmd events intercept the reading process by
381 * executing the associated commands instead.
382 */
383 if (!filtering && !read_stdin && !read_buffer)
384 {
385 pos_T pos;
386
387 pos = curbuf->b_op_start;
388
389 /* Set '[ mark to the line above where the lines go (line 1 if zero). */
390 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
391 curbuf->b_op_start.col = 0;
392
393 if (newfile)
394 {
395 if (apply_autocmds_exarg(EVENT_BUFREADCMD, NULL, sfname,
396 FALSE, curbuf, eap))
397#ifdef FEAT_EVAL
398 return aborting() ? FAIL : OK;
399#else
400 return OK;
401#endif
402 }
403 else if (apply_autocmds_exarg(EVENT_FILEREADCMD, sfname, sfname,
404 FALSE, NULL, eap))
405#ifdef FEAT_EVAL
406 return aborting() ? FAIL : OK;
407#else
408 return OK;
409#endif
410
411 curbuf->b_op_start = pos;
412 }
413#endif
414
415 if ((shortmess(SHM_OVER) || curbuf->b_help) && p_verbose == 0)
416 msg_scroll = FALSE; /* overwrite previous file message */
417 else
418 msg_scroll = TRUE; /* don't overwrite previous file message */
419
420 /*
421 * If the name ends in a path separator, we can't open it. Check here,
422 * because reading the file may actually work, but then creating the swap
423 * file may destroy it! Reported on MS-DOS and Win 95.
424 * If the name is too long we might crash further on, quit here.
425 */
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000426 if (fname != NULL && *fname != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000427 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000428 p = fname + STRLEN(fname);
429 if (after_pathsep(fname, p) || STRLEN(fname) >= MAXPATHL)
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000430 {
431 filemess(curbuf, fname, (char_u *)_("Illegal file name"), 0);
432 msg_end();
433 msg_scroll = msg_save;
434 return FAIL;
435 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000436 }
437
438#ifdef UNIX
439 /*
440 * On Unix it is possible to read a directory, so we have to
441 * check for it before the mch_open().
442 */
443 if (!read_stdin && !read_buffer)
444 {
445 perm = mch_getperm(fname);
446 if (perm >= 0 && !S_ISREG(perm) /* not a regular file ... */
447# ifdef S_ISFIFO
448 && !S_ISFIFO(perm) /* ... or fifo */
449# endif
450# ifdef S_ISSOCK
451 && !S_ISSOCK(perm) /* ... or socket */
452# endif
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +0000453# ifdef OPEN_CHR_FILES
454 && !(S_ISCHR(perm) && is_dev_fd_file(fname))
455 /* ... or a character special file named /dev/fd/<n> */
456# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000457 )
458 {
459 if (S_ISDIR(perm))
460 filemess(curbuf, fname, (char_u *)_("is a directory"), 0);
461 else
462 filemess(curbuf, fname, (char_u *)_("is not a file"), 0);
463 msg_end();
464 msg_scroll = msg_save;
465 return FAIL;
466 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000467
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000468# if defined(MSDOS) || defined(MSWIN) || defined(OS2)
469 /*
470 * MS-Windows allows opening a device, but we will probably get stuck
471 * trying to read it.
472 */
473 if (!p_odev && mch_nodetype(fname) == NODE_WRITABLE)
474 {
Bram Moolenaar5386a122007-06-28 20:02:32 +0000475 filemess(curbuf, fname, (char_u *)_("is a device (disabled with 'opendevice' option)"), 0);
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000476 msg_end();
477 msg_scroll = msg_save;
478 return FAIL;
479 }
480# endif
Bram Moolenaar043545e2006-10-10 16:44:07 +0000481 }
482#endif
483
Bram Moolenaar071d4272004-06-13 20:20:40 +0000484 /* set default 'fileformat' */
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000485 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000486 {
487 if (eap != NULL && eap->force_ff != 0)
488 set_fileformat(get_fileformat_force(curbuf, eap), OPT_LOCAL);
489 else if (*p_ffs != NUL)
490 set_fileformat(default_fileformat(), OPT_LOCAL);
491 }
492
493 /* set or reset 'binary' */
494 if (eap != NULL && eap->force_bin != 0)
495 {
496 int oldval = curbuf->b_p_bin;
497
498 curbuf->b_p_bin = (eap->force_bin == FORCE_BIN);
499 set_options_bin(oldval, curbuf->b_p_bin, OPT_LOCAL);
500 }
501
502 /*
503 * When opening a new file we take the readonly flag from the file.
504 * Default is r/w, can be set to r/o below.
505 * Don't reset it when in readonly mode
506 * Only set/reset b_p_ro when BF_CHECK_RO is set.
507 */
508 check_readonly = (newfile && (curbuf->b_flags & BF_CHECK_RO));
Bram Moolenaar4399ef42005-02-12 14:29:27 +0000509 if (check_readonly && !readonlymode)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000510 curbuf->b_p_ro = FALSE;
511
512 if (newfile && !read_stdin && !read_buffer)
513 {
514 /* Remember time of file.
515 * For RISCOS, also remember the filetype.
516 */
517 if (mch_stat((char *)fname, &st) >= 0)
518 {
519 buf_store_time(curbuf, &st, fname);
520 curbuf->b_mtime_read = curbuf->b_mtime;
521
522#if defined(RISCOS) && defined(FEAT_OSFILETYPE)
523 /* Read the filetype into the buffer local filetype option. */
524 mch_read_filetype(fname);
525#endif
526#ifdef UNIX
527 /*
528 * Use the protection bits of the original file for the swap file.
529 * This makes it possible for others to read the name of the
530 * edited file from the swapfile, but only if they can read the
531 * edited file.
532 * Remove the "write" and "execute" bits for group and others
533 * (they must not write the swapfile).
534 * Add the "read" and "write" bits for the user, otherwise we may
535 * not be able to write to the file ourselves.
536 * Setting the bits is done below, after creating the swap file.
537 */
538 swap_mode = (st.st_mode & 0644) | 0600;
539#endif
540#ifdef FEAT_CW_EDITOR
541 /* Get the FSSpec on MacOS
542 * TODO: Update it properly when the buffer name changes
543 */
544 (void)GetFSSpecFromPath(curbuf->b_ffname, &curbuf->b_FSSpec);
545#endif
546#ifdef VMS
547 curbuf->b_fab_rfm = st.st_fab_rfm;
Bram Moolenaard4755bb2004-09-02 19:12:26 +0000548 curbuf->b_fab_rat = st.st_fab_rat;
549 curbuf->b_fab_mrs = st.st_fab_mrs;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000550#endif
551 }
552 else
553 {
554 curbuf->b_mtime = 0;
555 curbuf->b_mtime_read = 0;
556 curbuf->b_orig_size = 0;
557 curbuf->b_orig_mode = 0;
558 }
559
560 /* Reset the "new file" flag. It will be set again below when the
561 * file doesn't exist. */
562 curbuf->b_flags &= ~(BF_NEW | BF_NEW_W);
563 }
564
565/*
566 * for UNIX: check readonly with perm and mch_access()
567 * for RISCOS: same as Unix, otherwise file gets re-datestamped!
568 * for MSDOS and Amiga: check readonly by trying to open the file for writing
569 */
570 file_readonly = FALSE;
571 if (read_stdin)
572 {
573#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
574 /* Force binary I/O on stdin to avoid CR-LF -> LF conversion. */
575 setmode(0, O_BINARY);
576#endif
577 }
578 else if (!read_buffer)
579 {
580#ifdef USE_MCH_ACCESS
581 if (
582# ifdef UNIX
583 !(perm & 0222) ||
584# endif
585 mch_access((char *)fname, W_OK))
586 file_readonly = TRUE;
587 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
588#else
589 if (!newfile
590 || readonlymode
591 || (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0)
592 {
593 file_readonly = TRUE;
594 /* try to open ro */
595 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
596 }
597#endif
598 }
599
600 if (fd < 0) /* cannot open at all */
601 {
602#ifndef UNIX
603 int isdir_f;
604#endif
605 msg_scroll = msg_save;
606#ifndef UNIX
607 /*
608 * On MSDOS and Amiga we can't open a directory, check here.
609 */
610 isdir_f = (mch_isdir(fname));
611 perm = mch_getperm(fname); /* check if the file exists */
612 if (isdir_f)
613 {
614 filemess(curbuf, sfname, (char_u *)_("is a directory"), 0);
615 curbuf->b_p_ro = TRUE; /* must use "w!" now */
616 }
617 else
618#endif
619 if (newfile)
620 {
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200621 if (perm < 0
622#ifdef ENOENT
623 && errno == ENOENT
624#endif
625 )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000626 {
627 /*
628 * Set the 'new-file' flag, so that when the file has
629 * been created by someone else, a ":w" will complain.
630 */
631 curbuf->b_flags |= BF_NEW;
632
633 /* Create a swap file now, so that other Vims are warned
634 * that we are editing this file. Don't do this for a
635 * "nofile" or "nowrite" buffer type. */
636#ifdef FEAT_QUICKFIX
637 if (!bt_dontwrite(curbuf))
638#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000639 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000640 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000641#ifdef FEAT_AUTOCMD
642 /* SwapExists autocommand may mess things up */
643 if (curbuf != old_curbuf
644 || (using_b_ffname
645 && (old_b_ffname != curbuf->b_ffname))
646 || (using_b_fname
647 && (old_b_fname != curbuf->b_fname)))
648 {
649 EMSG(_(e_auchangedbuf));
650 return FAIL;
651 }
652#endif
653 }
Bram Moolenaar5b962cf2005-12-12 21:58:40 +0000654 if (dir_of_file_exists(fname))
655 filemess(curbuf, sfname, (char_u *)_("[New File]"), 0);
656 else
657 filemess(curbuf, sfname,
658 (char_u *)_("[New DIRECTORY]"), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000659#ifdef FEAT_VIMINFO
660 /* Even though this is a new file, it might have been
661 * edited before and deleted. Get the old marks. */
662 check_marks_read();
663#endif
664#ifdef FEAT_MBYTE
665 if (eap != NULL && eap->force_enc != 0)
666 {
667 /* set forced 'fileencoding' */
668 fenc = enc_canonize(eap->cmd + eap->force_enc);
669 if (fenc != NULL)
670 set_string_option_direct((char_u *)"fenc", -1,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +0000671 fenc, OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000672 vim_free(fenc);
673 }
674#endif
675#ifdef FEAT_AUTOCMD
676 apply_autocmds_exarg(EVENT_BUFNEWFILE, sfname, sfname,
677 FALSE, curbuf, eap);
678#endif
679 /* remember the current fileformat */
680 save_file_ff(curbuf);
681
682#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
683 if (aborting()) /* autocmds may abort script processing */
684 return FAIL;
685#endif
686 return OK; /* a new file is not an error */
687 }
688 else
689 {
Bram Moolenaar202795b2005-10-11 20:29:39 +0000690 filemess(curbuf, sfname, (char_u *)(
691# ifdef EFBIG
692 (errno == EFBIG) ? _("[File too big]") :
693# endif
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200694# ifdef EOVERFLOW
695 (errno == EOVERFLOW) ? _("[File too big]") :
696# endif
Bram Moolenaar202795b2005-10-11 20:29:39 +0000697 _("[Permission Denied]")), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000698 curbuf->b_p_ro = TRUE; /* must use "w!" now */
699 }
700 }
701
702 return FAIL;
703 }
704
705 /*
706 * Only set the 'ro' flag for readonly files the first time they are
707 * loaded. Help files always get readonly mode
708 */
709 if ((check_readonly && file_readonly) || curbuf->b_help)
710 curbuf->b_p_ro = TRUE;
711
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000712 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000713 {
Bram Moolenaar690ffc02008-01-04 15:31:21 +0000714 /* Don't change 'eol' if reading from buffer as it will already be
715 * correctly set when reading stdin. */
716 if (!read_buffer)
717 {
718 curbuf->b_p_eol = TRUE;
719 curbuf->b_start_eol = TRUE;
720 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000721#ifdef FEAT_MBYTE
722 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000723 curbuf->b_start_bomb = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000724#endif
725 }
726
727 /* Create a swap file now, so that other Vims are warned that we are
728 * editing this file.
729 * Don't do this for a "nofile" or "nowrite" buffer type. */
730#ifdef FEAT_QUICKFIX
731 if (!bt_dontwrite(curbuf))
732#endif
733 {
734 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000735#ifdef FEAT_AUTOCMD
736 if (!read_stdin && (curbuf != old_curbuf
737 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
738 || (using_b_fname && (old_b_fname != curbuf->b_fname))))
739 {
740 EMSG(_(e_auchangedbuf));
741 if (!read_buffer)
742 close(fd);
743 return FAIL;
744 }
745#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000746#ifdef UNIX
747 /* Set swap file protection bits after creating it. */
Bram Moolenaarf061e0b2009-06-24 15:32:01 +0000748 if (swap_mode > 0 && curbuf->b_ml.ml_mfp != NULL
749 && curbuf->b_ml.ml_mfp->mf_fname != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000750 (void)mch_setperm(curbuf->b_ml.ml_mfp->mf_fname, (long)swap_mode);
751#endif
752 }
753
Bram Moolenaarb815dac2005-12-07 20:59:24 +0000754#if defined(HAS_SWAP_EXISTS_ACTION)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000755 /* If "Quit" selected at ATTENTION dialog, don't load the file */
756 if (swap_exists_action == SEA_QUIT)
757 {
758 if (!read_buffer && !read_stdin)
759 close(fd);
760 return FAIL;
761 }
762#endif
763
764 ++no_wait_return; /* don't wait for return yet */
765
766 /*
767 * Set '[ mark to the line above where the lines go (line 1 if zero).
768 */
769 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
770 curbuf->b_op_start.col = 0;
771
772#ifdef FEAT_AUTOCMD
773 if (!read_buffer)
774 {
775 int m = msg_scroll;
776 int n = msg_scrolled;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000777
778 /*
779 * The file must be closed again, the autocommands may want to change
780 * the file before reading it.
781 */
782 if (!read_stdin)
783 close(fd); /* ignore errors */
784
785 /*
786 * The output from the autocommands should not overwrite anything and
787 * should not be overwritten: Set msg_scroll, restore its value if no
788 * output was done.
789 */
790 msg_scroll = TRUE;
791 if (filtering)
792 apply_autocmds_exarg(EVENT_FILTERREADPRE, NULL, sfname,
793 FALSE, curbuf, eap);
794 else if (read_stdin)
795 apply_autocmds_exarg(EVENT_STDINREADPRE, NULL, sfname,
796 FALSE, curbuf, eap);
797 else if (newfile)
798 apply_autocmds_exarg(EVENT_BUFREADPRE, NULL, sfname,
799 FALSE, curbuf, eap);
800 else
801 apply_autocmds_exarg(EVENT_FILEREADPRE, sfname, sfname,
802 FALSE, NULL, eap);
803 if (msg_scrolled == n)
804 msg_scroll = m;
805
806#ifdef FEAT_EVAL
807 if (aborting()) /* autocmds may abort script processing */
808 {
809 --no_wait_return;
810 msg_scroll = msg_save;
811 curbuf->b_p_ro = TRUE; /* must use "w!" now */
812 return FAIL;
813 }
814#endif
815 /*
816 * Don't allow the autocommands to change the current buffer.
817 * Try to re-open the file.
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000818 *
819 * Don't allow the autocommands to change the buffer name either
820 * (cd for example) if it invalidates fname or sfname.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000821 */
822 if (!read_stdin && (curbuf != old_curbuf
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000823 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
824 || (using_b_fname && (old_b_fname != curbuf->b_fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000825 || (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) < 0))
826 {
827 --no_wait_return;
828 msg_scroll = msg_save;
829 if (fd < 0)
830 EMSG(_("E200: *ReadPre autocommands made the file unreadable"));
831 else
832 EMSG(_("E201: *ReadPre autocommands must not change current buffer"));
833 curbuf->b_p_ro = TRUE; /* must use "w!" now */
834 return FAIL;
835 }
836 }
837#endif /* FEAT_AUTOCMD */
838
839 /* Autocommands may add lines to the file, need to check if it is empty */
840 wasempty = (curbuf->b_ml.ml_flags & ML_EMPTY);
841
842 if (!recoverymode && !filtering && !(flags & READ_DUMMY))
843 {
844 /*
845 * Show the user that we are busy reading the input. Sometimes this
846 * may take a while. When reading from stdin another program may
847 * still be running, don't move the cursor to the last line, unless
848 * always using the GUI.
849 */
850 if (read_stdin)
851 {
852#ifndef ALWAYS_USE_GUI
853 mch_msg(_("Vim: Reading from stdin...\n"));
854#endif
855#ifdef FEAT_GUI
856 /* Also write a message in the GUI window, if there is one. */
857 if (gui.in_use && !gui.dying && !gui.starting)
858 {
859 p = (char_u *)_("Reading from stdin...");
860 gui_write(p, (int)STRLEN(p));
861 }
862#endif
863 }
864 else if (!read_buffer)
865 filemess(curbuf, sfname, (char_u *)"", 0);
866 }
867
868 msg_scroll = FALSE; /* overwrite the file message */
869
870 /*
871 * Set linecnt now, before the "retry" caused by a wrong guess for
872 * fileformat, and after the autocommands, which may change them.
873 */
874 linecnt = curbuf->b_ml.ml_line_count;
875
876#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000877 /* "++bad=" argument. */
878 if (eap != NULL && eap->bad_char != 0)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000879 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000880 bad_char_behavior = eap->bad_char;
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000881 if (set_options)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000882 curbuf->b_bad_char = eap->bad_char;
883 }
884 else
885 curbuf->b_bad_char = 0;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000886
Bram Moolenaar071d4272004-06-13 20:20:40 +0000887 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000888 * Decide which 'encoding' to use or use first.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000889 */
890 if (eap != NULL && eap->force_enc != 0)
891 {
892 fenc = enc_canonize(eap->cmd + eap->force_enc);
893 fenc_alloced = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000894 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000895 }
896 else if (curbuf->b_p_bin)
897 {
898 fenc = (char_u *)""; /* binary: don't convert */
899 fenc_alloced = FALSE;
900 }
901 else if (curbuf->b_help)
902 {
903 char_u firstline[80];
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000904 int fc;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000905
906 /* Help files are either utf-8 or latin1. Try utf-8 first, if this
907 * fails it must be latin1.
908 * Always do this when 'encoding' is "utf-8". Otherwise only do
909 * this when needed to avoid [converted] remarks all the time.
910 * It is needed when the first line contains non-ASCII characters.
911 * That is only in *.??x files. */
912 fenc = (char_u *)"latin1";
913 c = enc_utf8;
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000914 if (!c && !read_stdin)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000915 {
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000916 fc = fname[STRLEN(fname) - 1];
917 if (TOLOWER_ASC(fc) == 'x')
918 {
919 /* Read the first line (and a bit more). Immediately rewind to
920 * the start of the file. If the read() fails "len" is -1. */
921 len = vim_read(fd, firstline, 80);
922 lseek(fd, (off_t)0L, SEEK_SET);
923 for (p = firstline; p < firstline + len; ++p)
924 if (*p >= 0x80)
925 {
926 c = TRUE;
927 break;
928 }
929 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000930 }
931
932 if (c)
933 {
934 fenc_next = fenc;
935 fenc = (char_u *)"utf-8";
936
937 /* When the file is utf-8 but a character doesn't fit in
938 * 'encoding' don't retry. In help text editing utf-8 bytes
939 * doesn't make sense. */
Bram Moolenaarf193fff2006-04-27 00:02:13 +0000940 if (!enc_utf8)
941 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000942 }
943 fenc_alloced = FALSE;
944 }
945 else if (*p_fencs == NUL)
946 {
947 fenc = curbuf->b_p_fenc; /* use format from buffer */
948 fenc_alloced = FALSE;
949 }
950 else
951 {
952 fenc_next = p_fencs; /* try items in 'fileencodings' */
953 fenc = next_fenc(&fenc_next);
954 fenc_alloced = TRUE;
955 }
956#endif
957
958 /*
959 * Jump back here to retry reading the file in different ways.
960 * Reasons to retry:
961 * - encoding conversion failed: try another one from "fenc_next"
962 * - BOM detected and fenc was set, need to setup conversion
963 * - "fileformat" check failed: try another
964 *
965 * Variables set for special retry actions:
966 * "file_rewind" Rewind the file to start reading it again.
967 * "advance_fenc" Advance "fenc" using "fenc_next".
968 * "skip_read" Re-use already read bytes (BOM detected).
969 * "did_iconv" iconv() conversion failed, try 'charconvert'.
970 * "keep_fileformat" Don't reset "fileformat".
971 *
972 * Other status indicators:
973 * "tmpname" When != NULL did conversion with 'charconvert'.
974 * Output file has to be deleted afterwards.
975 * "iconv_fd" When != -1 did conversion with iconv().
976 */
977retry:
978
979 if (file_rewind)
980 {
981 if (read_buffer)
982 {
983 read_buf_lnum = 1;
984 read_buf_col = 0;
985 }
986 else if (read_stdin || lseek(fd, (off_t)0L, SEEK_SET) != 0)
987 {
988 /* Can't rewind the file, give up. */
989 error = TRUE;
990 goto failed;
991 }
992 /* Delete the previously read lines. */
993 while (lnum > from)
994 ml_delete(lnum--, FALSE);
995 file_rewind = FALSE;
996#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000997 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000998 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000999 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001000 curbuf->b_start_bomb = FALSE;
1001 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001002 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001003#endif
1004 }
1005
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001006#ifdef FEAT_CRYPT
1007 if (cryptkey != NULL)
1008 /* Need to reset the state, but keep the key, don't want to ask for it
1009 * again. */
1010 crypt_pop_state();
1011#endif
1012
Bram Moolenaar071d4272004-06-13 20:20:40 +00001013 /*
1014 * When retrying with another "fenc" and the first time "fileformat"
1015 * will be reset.
1016 */
1017 if (keep_fileformat)
1018 keep_fileformat = FALSE;
1019 else
1020 {
1021 if (eap != NULL && eap->force_ff != 0)
Bram Moolenaar1c860362008-11-12 15:05:21 +00001022 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001023 fileformat = get_fileformat_force(curbuf, eap);
Bram Moolenaar1c860362008-11-12 15:05:21 +00001024 try_unix = try_dos = try_mac = FALSE;
1025 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001026 else if (curbuf->b_p_bin)
1027 fileformat = EOL_UNIX; /* binary: use Unix format */
1028 else if (*p_ffs == NUL)
1029 fileformat = get_fileformat(curbuf);/* use format from buffer */
1030 else
1031 fileformat = EOL_UNKNOWN; /* detect from file */
1032 }
1033
1034#ifdef FEAT_MBYTE
1035# ifdef USE_ICONV
1036 if (iconv_fd != (iconv_t)-1)
1037 {
1038 /* aborted conversion with iconv(), close the descriptor */
1039 iconv_close(iconv_fd);
1040 iconv_fd = (iconv_t)-1;
1041 }
1042# endif
1043
1044 if (advance_fenc)
1045 {
1046 /*
1047 * Try the next entry in 'fileencodings'.
1048 */
1049 advance_fenc = FALSE;
1050
1051 if (eap != NULL && eap->force_enc != 0)
1052 {
1053 /* Conversion given with "++cc=" wasn't possible, read
1054 * without conversion. */
1055 notconverted = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001056 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001057 if (fenc_alloced)
1058 vim_free(fenc);
1059 fenc = (char_u *)"";
1060 fenc_alloced = FALSE;
1061 }
1062 else
1063 {
1064 if (fenc_alloced)
1065 vim_free(fenc);
1066 if (fenc_next != NULL)
1067 {
1068 fenc = next_fenc(&fenc_next);
1069 fenc_alloced = (fenc_next != NULL);
1070 }
1071 else
1072 {
1073 fenc = (char_u *)"";
1074 fenc_alloced = FALSE;
1075 }
1076 }
1077 if (tmpname != NULL)
1078 {
1079 mch_remove(tmpname); /* delete converted file */
1080 vim_free(tmpname);
1081 tmpname = NULL;
1082 }
1083 }
1084
1085 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001086 * Conversion may be required when the encoding of the file is different
1087 * from 'encoding' or 'encoding' is UTF-16, UCS-2 or UCS-4.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001088 */
1089 fio_flags = 0;
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001090 converted = need_conversion(fenc);
1091 if (converted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001092 {
1093
1094 /* "ucs-bom" means we need to check the first bytes of the file
1095 * for a BOM. */
1096 if (STRCMP(fenc, ENC_UCSBOM) == 0)
1097 fio_flags = FIO_UCSBOM;
1098
1099 /*
1100 * Check if UCS-2/4 or Latin1 to UTF-8 conversion needs to be
1101 * done. This is handled below after read(). Prepare the
1102 * fio_flags to avoid having to parse the string each time.
1103 * Also check for Unicode to Latin1 conversion, because iconv()
1104 * appears not to handle this correctly. This works just like
1105 * conversion to UTF-8 except how the resulting character is put in
1106 * the buffer.
1107 */
1108 else if (enc_utf8 || STRCMP(p_enc, "latin1") == 0)
1109 fio_flags = get_fio_flags(fenc);
1110
1111# ifdef WIN3264
1112 /*
1113 * Conversion from an MS-Windows codepage to UTF-8 or another codepage
1114 * is handled with MultiByteToWideChar().
1115 */
1116 if (fio_flags == 0)
1117 fio_flags = get_win_fio_flags(fenc);
1118# endif
1119
1120# ifdef MACOS_X
1121 /* Conversion from Apple MacRoman to latin1 or UTF-8 */
1122 if (fio_flags == 0)
1123 fio_flags = get_mac_fio_flags(fenc);
1124# endif
1125
1126# ifdef USE_ICONV
1127 /*
1128 * Try using iconv() if we can't convert internally.
1129 */
1130 if (fio_flags == 0
1131# ifdef FEAT_EVAL
1132 && !did_iconv
1133# endif
1134 )
1135 iconv_fd = (iconv_t)my_iconv_open(
1136 enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc);
1137# endif
1138
1139# ifdef FEAT_EVAL
1140 /*
1141 * Use the 'charconvert' expression when conversion is required
1142 * and we can't do it internally or with iconv().
1143 */
1144 if (fio_flags == 0 && !read_stdin && !read_buffer && *p_ccv != NUL
1145# ifdef USE_ICONV
1146 && iconv_fd == (iconv_t)-1
1147# endif
1148 )
1149 {
1150# ifdef USE_ICONV
1151 did_iconv = FALSE;
1152# endif
1153 /* Skip conversion when it's already done (retry for wrong
1154 * "fileformat"). */
1155 if (tmpname == NULL)
1156 {
1157 tmpname = readfile_charconvert(fname, fenc, &fd);
1158 if (tmpname == NULL)
1159 {
1160 /* Conversion failed. Try another one. */
1161 advance_fenc = TRUE;
1162 if (fd < 0)
1163 {
1164 /* Re-opening the original file failed! */
1165 EMSG(_("E202: Conversion made file unreadable!"));
1166 error = TRUE;
1167 goto failed;
1168 }
1169 goto retry;
1170 }
1171 }
1172 }
1173 else
1174# endif
1175 {
1176 if (fio_flags == 0
1177# ifdef USE_ICONV
1178 && iconv_fd == (iconv_t)-1
1179# endif
1180 )
1181 {
1182 /* Conversion wanted but we can't.
1183 * Try the next conversion in 'fileencodings' */
1184 advance_fenc = TRUE;
1185 goto retry;
1186 }
1187 }
1188 }
1189
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001190 /* Set "can_retry" when it's possible to rewind the file and try with
Bram Moolenaar071d4272004-06-13 20:20:40 +00001191 * another "fenc" value. It's FALSE when no other "fenc" to try, reading
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001192 * stdin or fixed at a specific encoding. */
1193 can_retry = (*fenc != NUL && !read_stdin && !keep_dest_enc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001194#endif
1195
1196 if (!skip_read)
1197 {
1198 linerest = 0;
1199 filesize = 0;
1200 skip_count = lines_to_skip;
1201 read_count = lines_to_read;
1202#ifdef FEAT_MBYTE
1203 conv_restlen = 0;
1204#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001205#ifdef FEAT_PERSISTENT_UNDO
Bram Moolenaar59f931e2010-07-24 20:27:03 +02001206 read_undo_file = (newfile && (flags & READ_KEEP_UNDO) == 0
1207 && curbuf->b_ffname != NULL
1208 && curbuf->b_p_udf
1209 && !filtering
1210 && !read_stdin
1211 && !read_buffer);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001212 if (read_undo_file)
1213 sha256_start(&sha_ctx);
1214#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001215 }
1216
1217 while (!error && !got_int)
1218 {
1219 /*
1220 * We allocate as much space for the file as we can get, plus
1221 * space for the old line plus room for one terminating NUL.
1222 * The amount is limited by the fact that read() only can read
1223 * upto max_unsigned characters (and other things).
1224 */
1225#if SIZEOF_INT <= 2
1226 if (linerest >= 0x7ff0)
1227 {
1228 ++split;
1229 *ptr = NL; /* split line by inserting a NL */
1230 size = 1;
1231 }
1232 else
1233#endif
1234 {
1235 if (!skip_read)
1236 {
1237#if SIZEOF_INT > 2
Bram Moolenaar311d9822007-02-27 15:48:28 +00001238# if defined(SSIZE_MAX) && (SSIZE_MAX < 0x10000L)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001239 size = SSIZE_MAX; /* use max I/O size, 52K */
1240# else
1241 size = 0x10000L; /* use buffer >= 64K */
1242# endif
1243#else
1244 size = 0x7ff0L - linerest; /* limit buffer to 32K */
1245#endif
1246
Bram Moolenaarc1e37902006-04-18 21:55:01 +00001247 for ( ; size >= 10; size = (long)((long_u)size >> 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001248 {
1249 if ((new_buffer = lalloc((long_u)(size + linerest + 1),
1250 FALSE)) != NULL)
1251 break;
1252 }
1253 if (new_buffer == NULL)
1254 {
1255 do_outofmem_msg((long_u)(size * 2 + linerest + 1));
1256 error = TRUE;
1257 break;
1258 }
1259 if (linerest) /* copy characters from the previous buffer */
1260 mch_memmove(new_buffer, ptr - linerest, (size_t)linerest);
1261 vim_free(buffer);
1262 buffer = new_buffer;
1263 ptr = buffer + linerest;
1264 line_start = buffer;
1265
1266#ifdef FEAT_MBYTE
1267 /* May need room to translate into.
1268 * For iconv() we don't really know the required space, use a
1269 * factor ICONV_MULT.
1270 * latin1 to utf-8: 1 byte becomes up to 2 bytes
1271 * utf-16 to utf-8: 2 bytes become up to 3 bytes, 4 bytes
1272 * become up to 4 bytes, size must be multiple of 2
1273 * ucs-2 to utf-8: 2 bytes become up to 3 bytes, size must be
1274 * multiple of 2
1275 * ucs-4 to utf-8: 4 bytes become up to 6 bytes, size must be
1276 * multiple of 4 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001277 real_size = (int)size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001278# ifdef USE_ICONV
1279 if (iconv_fd != (iconv_t)-1)
1280 size = size / ICONV_MULT;
1281 else
1282# endif
1283 if (fio_flags & FIO_LATIN1)
1284 size = size / 2;
1285 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1286 size = (size * 2 / 3) & ~1;
1287 else if (fio_flags & FIO_UCS4)
1288 size = (size * 2 / 3) & ~3;
1289 else if (fio_flags == FIO_UCSBOM)
1290 size = size / ICONV_MULT; /* worst case */
1291# ifdef WIN3264
1292 else if (fio_flags & FIO_CODEPAGE)
1293 size = size / ICONV_MULT; /* also worst case */
1294# endif
1295# ifdef MACOS_X
1296 else if (fio_flags & FIO_MACROMAN)
1297 size = size / ICONV_MULT; /* also worst case */
1298# endif
1299#endif
1300
1301#ifdef FEAT_MBYTE
1302 if (conv_restlen > 0)
1303 {
1304 /* Insert unconverted bytes from previous line. */
1305 mch_memmove(ptr, conv_rest, conv_restlen);
1306 ptr += conv_restlen;
1307 size -= conv_restlen;
1308 }
1309#endif
1310
1311 if (read_buffer)
1312 {
1313 /*
1314 * Read bytes from curbuf. Used for converting text read
1315 * from stdin.
1316 */
1317 if (read_buf_lnum > from)
1318 size = 0;
1319 else
1320 {
1321 int n, ni;
1322 long tlen;
1323
1324 tlen = 0;
1325 for (;;)
1326 {
1327 p = ml_get(read_buf_lnum) + read_buf_col;
1328 n = (int)STRLEN(p);
1329 if ((int)tlen + n + 1 > size)
1330 {
1331 /* Filled up to "size", append partial line.
1332 * Change NL to NUL to reverse the effect done
1333 * below. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001334 n = (int)(size - tlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001335 for (ni = 0; ni < n; ++ni)
1336 {
1337 if (p[ni] == NL)
1338 ptr[tlen++] = NUL;
1339 else
1340 ptr[tlen++] = p[ni];
1341 }
1342 read_buf_col += n;
1343 break;
1344 }
1345 else
1346 {
1347 /* Append whole line and new-line. Change NL
1348 * to NUL to reverse the effect done below. */
1349 for (ni = 0; ni < n; ++ni)
1350 {
1351 if (p[ni] == NL)
1352 ptr[tlen++] = NUL;
1353 else
1354 ptr[tlen++] = p[ni];
1355 }
1356 ptr[tlen++] = NL;
1357 read_buf_col = 0;
1358 if (++read_buf_lnum > from)
1359 {
1360 /* When the last line didn't have an
1361 * end-of-line don't add it now either. */
1362 if (!curbuf->b_p_eol)
1363 --tlen;
1364 size = tlen;
1365 break;
1366 }
1367 }
1368 }
1369 }
1370 }
1371 else
1372 {
1373 /*
1374 * Read bytes from the file.
1375 */
1376 size = vim_read(fd, ptr, size);
1377 }
1378
1379 if (size <= 0)
1380 {
1381 if (size < 0) /* read error */
1382 error = TRUE;
1383#ifdef FEAT_MBYTE
1384 else if (conv_restlen > 0)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001385 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001386 /*
1387 * Reached end-of-file but some trailing bytes could
1388 * not be converted. Truncated file?
1389 */
1390
1391 /* When we did a conversion report an error. */
1392 if (fio_flags != 0
1393# ifdef USE_ICONV
1394 || iconv_fd != (iconv_t)-1
1395# endif
1396 )
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001397 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001398 if (conv_error == 0)
1399 conv_error = curbuf->b_ml.ml_line_count
1400 - linecnt + 1;
1401 }
1402 /* Remember the first linenr with an illegal byte */
1403 else if (illegal_byte == 0)
1404 illegal_byte = curbuf->b_ml.ml_line_count
1405 - linecnt + 1;
1406 if (bad_char_behavior == BAD_DROP)
1407 {
1408 *(ptr - conv_restlen) = NUL;
1409 conv_restlen = 0;
1410 }
1411 else
1412 {
1413 /* Replace the trailing bytes with the replacement
1414 * character if we were converting; if we weren't,
1415 * leave the UTF8 checking code to do it, as it
1416 * works slightly differently. */
1417 if (bad_char_behavior != BAD_KEEP && (fio_flags != 0
1418# ifdef USE_ICONV
1419 || iconv_fd != (iconv_t)-1
1420# endif
1421 ))
1422 {
1423 while (conv_restlen > 0)
1424 {
1425 *(--ptr) = bad_char_behavior;
1426 --conv_restlen;
1427 }
1428 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001429 fio_flags = 0; /* don't convert this */
Bram Moolenaarb21e5842006-04-16 18:30:08 +00001430# ifdef USE_ICONV
1431 if (iconv_fd != (iconv_t)-1)
1432 {
1433 iconv_close(iconv_fd);
1434 iconv_fd = (iconv_t)-1;
1435 }
1436# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001437 }
1438 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001439#endif
1440 }
1441
1442#ifdef FEAT_CRYPT
1443 /*
1444 * At start of file: Check for magic number of encryption.
1445 */
1446 if (filesize == 0)
1447 cryptkey = check_for_cryptkey(cryptkey, ptr, &size,
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001448 &filesize, newfile, sfname,
1449 &did_ask_for_key);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001450 /*
1451 * Decrypt the read bytes.
1452 */
1453 if (cryptkey != NULL && size > 0)
Bram Moolenaar04c9baf2010-06-01 23:37:39 +02001454 crypt_decode(ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001455#endif
1456 }
1457 skip_read = FALSE;
1458
1459#ifdef FEAT_MBYTE
1460 /*
1461 * At start of file (or after crypt magic number): Check for BOM.
1462 * Also check for a BOM for other Unicode encodings, but not after
1463 * converting with 'charconvert' or when a BOM has already been
1464 * found.
1465 */
1466 if ((filesize == 0
1467# ifdef FEAT_CRYPT
Bram Moolenaar40e6a712010-05-16 22:32:54 +02001468 || (filesize == (CRYPT_MAGIC_LEN
Bram Moolenaar80794b12010-06-13 05:20:42 +02001469 + crypt_salt_len[use_crypt_method]
Bram Moolenaar40e6a712010-05-16 22:32:54 +02001470 + crypt_seed_len[use_crypt_method])
1471 && cryptkey != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001472# endif
1473 )
1474 && (fio_flags == FIO_UCSBOM
1475 || (!curbuf->b_p_bomb
1476 && tmpname == NULL
1477 && (*fenc == 'u' || (*fenc == NUL && enc_utf8)))))
1478 {
1479 char_u *ccname;
1480 int blen;
1481
1482 /* no BOM detection in a short file or in binary mode */
1483 if (size < 2 || curbuf->b_p_bin)
1484 ccname = NULL;
1485 else
1486 ccname = check_for_bom(ptr, size, &blen,
1487 fio_flags == FIO_UCSBOM ? FIO_ALL : get_fio_flags(fenc));
1488 if (ccname != NULL)
1489 {
1490 /* Remove BOM from the text */
1491 filesize += blen;
1492 size -= blen;
1493 mch_memmove(ptr, ptr + blen, (size_t)size);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00001494 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001495 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001496 curbuf->b_p_bomb = TRUE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001497 curbuf->b_start_bomb = TRUE;
1498 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001499 }
1500
1501 if (fio_flags == FIO_UCSBOM)
1502 {
1503 if (ccname == NULL)
1504 {
1505 /* No BOM detected: retry with next encoding. */
1506 advance_fenc = TRUE;
1507 }
1508 else
1509 {
1510 /* BOM detected: set "fenc" and jump back */
1511 if (fenc_alloced)
1512 vim_free(fenc);
1513 fenc = ccname;
1514 fenc_alloced = FALSE;
1515 }
1516 /* retry reading without getting new bytes or rewinding */
1517 skip_read = TRUE;
1518 goto retry;
1519 }
1520 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001521
1522 /* Include not converted bytes. */
1523 ptr -= conv_restlen;
1524 size += conv_restlen;
1525 conv_restlen = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001526#endif
1527 /*
1528 * Break here for a read error or end-of-file.
1529 */
1530 if (size <= 0)
1531 break;
1532
1533#ifdef FEAT_MBYTE
1534
Bram Moolenaar071d4272004-06-13 20:20:40 +00001535# ifdef USE_ICONV
1536 if (iconv_fd != (iconv_t)-1)
1537 {
1538 /*
1539 * Attempt conversion of the read bytes to 'encoding' using
1540 * iconv().
1541 */
1542 const char *fromp;
1543 char *top;
1544 size_t from_size;
1545 size_t to_size;
1546
1547 fromp = (char *)ptr;
1548 from_size = size;
1549 ptr += size;
1550 top = (char *)ptr;
1551 to_size = real_size - size;
1552
1553 /*
1554 * If there is conversion error or not enough room try using
Bram Moolenaar19a09a12005-03-04 23:39:37 +00001555 * another conversion. Except for when there is no
1556 * alternative (help files).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001557 */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001558 while ((iconv(iconv_fd, (void *)&fromp, &from_size,
1559 &top, &to_size)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001560 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
1561 || from_size > CONV_RESTLEN)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001562 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001563 if (can_retry)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001564 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001565 if (conv_error == 0)
1566 conv_error = readfile_linenr(linecnt,
1567 ptr, (char_u *)top);
Bram Moolenaar42eeac32005-06-29 22:40:58 +00001568
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001569 /* Deal with a bad byte and continue with the next. */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001570 ++fromp;
1571 --from_size;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001572 if (bad_char_behavior == BAD_KEEP)
1573 {
1574 *top++ = *(fromp - 1);
1575 --to_size;
1576 }
1577 else if (bad_char_behavior != BAD_DROP)
1578 {
1579 *top++ = bad_char_behavior;
1580 --to_size;
1581 }
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001582 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001583
1584 if (from_size > 0)
1585 {
1586 /* Some remaining characters, keep them for the next
1587 * round. */
1588 mch_memmove(conv_rest, (char_u *)fromp, from_size);
1589 conv_restlen = (int)from_size;
1590 }
1591
1592 /* move the linerest to before the converted characters */
1593 line_start = ptr - linerest;
1594 mch_memmove(line_start, buffer, (size_t)linerest);
1595 size = (long)((char_u *)top - ptr);
1596 }
1597# endif
1598
1599# ifdef WIN3264
1600 if (fio_flags & FIO_CODEPAGE)
1601 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001602 char_u *src, *dst;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001603 WCHAR ucs2buf[3];
1604 int ucs2len;
1605 int codepage = FIO_GET_CP(fio_flags);
1606 int bytelen;
1607 int found_bad;
1608 char replstr[2];
1609
Bram Moolenaar071d4272004-06-13 20:20:40 +00001610 /*
1611 * Conversion from an MS-Windows codepage or UTF-8 to UTF-8 or
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001612 * a codepage, using standard MS-Windows functions. This
1613 * requires two steps:
1614 * 1. convert from 'fileencoding' to ucs-2
1615 * 2. convert from ucs-2 to 'encoding'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001616 *
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001617 * Because there may be illegal bytes AND an incomplete byte
1618 * sequence at the end, we may have to do the conversion one
1619 * character at a time to get it right.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001620 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001621
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001622 /* Replacement string for WideCharToMultiByte(). */
1623 if (bad_char_behavior > 0)
1624 replstr[0] = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001625 else
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001626 replstr[0] = '?';
1627 replstr[1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001628
1629 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001630 * Move the bytes to the end of the buffer, so that we have
1631 * room to put the result at the start.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001632 */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001633 src = ptr + real_size - size;
1634 mch_memmove(src, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001635
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001636 /*
1637 * Do the conversion.
1638 */
1639 dst = ptr;
1640 size = size;
1641 while (size > 0)
1642 {
1643 found_bad = FALSE;
1644
1645# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
1646 if (codepage == CP_UTF8)
1647 {
1648 /* Handle CP_UTF8 input ourselves to be able to handle
1649 * trailing bytes properly.
1650 * Get one UTF-8 character from src. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001651 bytelen = (int)utf_ptr2len_len(src, size);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001652 if (bytelen > size)
1653 {
1654 /* Only got some bytes of a character. Normally
1655 * it's put in "conv_rest", but if it's too long
1656 * deal with it as if they were illegal bytes. */
1657 if (bytelen <= CONV_RESTLEN)
1658 break;
1659
1660 /* weird overlong byte sequence */
1661 bytelen = size;
1662 found_bad = TRUE;
1663 }
1664 else
1665 {
Bram Moolenaarc01140a2006-03-24 22:21:52 +00001666 int u8c = utf_ptr2char(src);
1667
Bram Moolenaar86e01082005-12-29 22:45:34 +00001668 if (u8c > 0xffff || (*src >= 0x80 && bytelen == 1))
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001669 found_bad = TRUE;
1670 ucs2buf[0] = u8c;
1671 ucs2len = 1;
1672 }
1673 }
1674 else
1675# endif
1676 {
1677 /* We don't know how long the byte sequence is, try
1678 * from one to three bytes. */
1679 for (bytelen = 1; bytelen <= size && bytelen <= 3;
1680 ++bytelen)
1681 {
1682 ucs2len = MultiByteToWideChar(codepage,
1683 MB_ERR_INVALID_CHARS,
1684 (LPCSTR)src, bytelen,
1685 ucs2buf, 3);
1686 if (ucs2len > 0)
1687 break;
1688 }
1689 if (ucs2len == 0)
1690 {
1691 /* If we have only one byte then it's probably an
1692 * incomplete byte sequence. Otherwise discard
1693 * one byte as a bad character. */
1694 if (size == 1)
1695 break;
1696 found_bad = TRUE;
1697 bytelen = 1;
1698 }
1699 }
1700
1701 if (!found_bad)
1702 {
1703 int i;
1704
1705 /* Convert "ucs2buf[ucs2len]" to 'enc' in "dst". */
1706 if (enc_utf8)
1707 {
1708 /* From UCS-2 to UTF-8. Cannot fail. */
1709 for (i = 0; i < ucs2len; ++i)
1710 dst += utf_char2bytes(ucs2buf[i], dst);
1711 }
1712 else
1713 {
1714 BOOL bad = FALSE;
1715 int dstlen;
1716
1717 /* From UCS-2 to "enc_codepage". If the
1718 * conversion uses the default character "?",
1719 * the data doesn't fit in this encoding. */
1720 dstlen = WideCharToMultiByte(enc_codepage, 0,
1721 (LPCWSTR)ucs2buf, ucs2len,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001722 (LPSTR)dst, (int)(src - dst),
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001723 replstr, &bad);
1724 if (bad)
1725 found_bad = TRUE;
1726 else
1727 dst += dstlen;
1728 }
1729 }
1730
1731 if (found_bad)
1732 {
1733 /* Deal with bytes we can't convert. */
1734 if (can_retry)
1735 goto rewind_retry;
1736 if (conv_error == 0)
1737 conv_error = readfile_linenr(linecnt, ptr, dst);
1738 if (bad_char_behavior != BAD_DROP)
1739 {
1740 if (bad_char_behavior == BAD_KEEP)
1741 {
1742 mch_memmove(dst, src, bytelen);
1743 dst += bytelen;
1744 }
1745 else
1746 *dst++ = bad_char_behavior;
1747 }
1748 }
1749
1750 src += bytelen;
1751 size -= bytelen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001752 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001753
1754 if (size > 0)
1755 {
1756 /* An incomplete byte sequence remaining. */
1757 mch_memmove(conv_rest, src, size);
1758 conv_restlen = size;
1759 }
1760
1761 /* The new size is equal to how much "dst" was advanced. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001762 size = (long)(dst - ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001763 }
1764 else
1765# endif
Bram Moolenaar56718732006-03-15 22:53:57 +00001766# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001767 if (fio_flags & FIO_MACROMAN)
1768 {
1769 /*
1770 * Conversion from Apple MacRoman char encoding to UTF-8 or
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001771 * latin1. This is in os_mac_conv.c.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001772 */
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001773 if (macroman2enc(ptr, &size, real_size) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001774 goto rewind_retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001775 }
1776 else
1777# endif
1778 if (fio_flags != 0)
1779 {
1780 int u8c;
1781 char_u *dest;
1782 char_u *tail = NULL;
1783
1784 /*
1785 * "enc_utf8" set: Convert Unicode or Latin1 to UTF-8.
1786 * "enc_utf8" not set: Convert Unicode to Latin1.
1787 * Go from end to start through the buffer, because the number
1788 * of bytes may increase.
1789 * "dest" points to after where the UTF-8 bytes go, "p" points
1790 * to after the next character to convert.
1791 */
1792 dest = ptr + real_size;
1793 if (fio_flags == FIO_LATIN1 || fio_flags == FIO_UTF8)
1794 {
1795 p = ptr + size;
1796 if (fio_flags == FIO_UTF8)
1797 {
1798 /* Check for a trailing incomplete UTF-8 sequence */
1799 tail = ptr + size - 1;
1800 while (tail > ptr && (*tail & 0xc0) == 0x80)
1801 --tail;
1802 if (tail + utf_byte2len(*tail) <= ptr + size)
1803 tail = NULL;
1804 else
1805 p = tail;
1806 }
1807 }
1808 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1809 {
1810 /* Check for a trailing byte */
1811 p = ptr + (size & ~1);
1812 if (size & 1)
1813 tail = p;
1814 if ((fio_flags & FIO_UTF16) && p > ptr)
1815 {
1816 /* Check for a trailing leading word */
1817 if (fio_flags & FIO_ENDIAN_L)
1818 {
1819 u8c = (*--p << 8);
1820 u8c += *--p;
1821 }
1822 else
1823 {
1824 u8c = *--p;
1825 u8c += (*--p << 8);
1826 }
1827 if (u8c >= 0xd800 && u8c <= 0xdbff)
1828 tail = p;
1829 else
1830 p += 2;
1831 }
1832 }
1833 else /* FIO_UCS4 */
1834 {
1835 /* Check for trailing 1, 2 or 3 bytes */
1836 p = ptr + (size & ~3);
1837 if (size & 3)
1838 tail = p;
1839 }
1840
1841 /* If there is a trailing incomplete sequence move it to
1842 * conv_rest[]. */
1843 if (tail != NULL)
1844 {
1845 conv_restlen = (int)((ptr + size) - tail);
1846 mch_memmove(conv_rest, (char_u *)tail, conv_restlen);
1847 size -= conv_restlen;
1848 }
1849
1850
1851 while (p > ptr)
1852 {
1853 if (fio_flags & FIO_LATIN1)
1854 u8c = *--p;
1855 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1856 {
1857 if (fio_flags & FIO_ENDIAN_L)
1858 {
1859 u8c = (*--p << 8);
1860 u8c += *--p;
1861 }
1862 else
1863 {
1864 u8c = *--p;
1865 u8c += (*--p << 8);
1866 }
1867 if ((fio_flags & FIO_UTF16)
1868 && u8c >= 0xdc00 && u8c <= 0xdfff)
1869 {
1870 int u16c;
1871
1872 if (p == ptr)
1873 {
1874 /* Missing leading word. */
1875 if (can_retry)
1876 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001877 if (conv_error == 0)
1878 conv_error = readfile_linenr(linecnt,
1879 ptr, p);
1880 if (bad_char_behavior == BAD_DROP)
1881 continue;
1882 if (bad_char_behavior != BAD_KEEP)
1883 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001884 }
1885
1886 /* found second word of double-word, get the first
1887 * word and compute the resulting character */
1888 if (fio_flags & FIO_ENDIAN_L)
1889 {
1890 u16c = (*--p << 8);
1891 u16c += *--p;
1892 }
1893 else
1894 {
1895 u16c = *--p;
1896 u16c += (*--p << 8);
1897 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001898 u8c = 0x10000 + ((u16c & 0x3ff) << 10)
1899 + (u8c & 0x3ff);
1900
Bram Moolenaar071d4272004-06-13 20:20:40 +00001901 /* Check if the word is indeed a leading word. */
1902 if (u16c < 0xd800 || u16c > 0xdbff)
1903 {
1904 if (can_retry)
1905 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001906 if (conv_error == 0)
1907 conv_error = readfile_linenr(linecnt,
1908 ptr, p);
1909 if (bad_char_behavior == BAD_DROP)
1910 continue;
1911 if (bad_char_behavior != BAD_KEEP)
1912 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001913 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001914 }
1915 }
1916 else if (fio_flags & FIO_UCS4)
1917 {
1918 if (fio_flags & FIO_ENDIAN_L)
1919 {
1920 u8c = (*--p << 24);
1921 u8c += (*--p << 16);
1922 u8c += (*--p << 8);
1923 u8c += *--p;
1924 }
1925 else /* big endian */
1926 {
1927 u8c = *--p;
1928 u8c += (*--p << 8);
1929 u8c += (*--p << 16);
1930 u8c += (*--p << 24);
1931 }
1932 }
1933 else /* UTF-8 */
1934 {
1935 if (*--p < 0x80)
1936 u8c = *p;
1937 else
1938 {
1939 len = utf_head_off(ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001940 p -= len;
1941 u8c = utf_ptr2char(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001942 if (len == 0)
1943 {
1944 /* Not a valid UTF-8 character, retry with
1945 * another fenc when possible, otherwise just
1946 * report the error. */
1947 if (can_retry)
1948 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001949 if (conv_error == 0)
1950 conv_error = readfile_linenr(linecnt,
1951 ptr, p);
1952 if (bad_char_behavior == BAD_DROP)
1953 continue;
1954 if (bad_char_behavior != BAD_KEEP)
1955 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001956 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001957 }
1958 }
1959 if (enc_utf8) /* produce UTF-8 */
1960 {
1961 dest -= utf_char2len(u8c);
1962 (void)utf_char2bytes(u8c, dest);
1963 }
1964 else /* produce Latin1 */
1965 {
1966 --dest;
1967 if (u8c >= 0x100)
1968 {
1969 /* character doesn't fit in latin1, retry with
1970 * another fenc when possible, otherwise just
1971 * report the error. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001972 if (can_retry)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001973 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001974 if (conv_error == 0)
1975 conv_error = readfile_linenr(linecnt, ptr, p);
1976 if (bad_char_behavior == BAD_DROP)
1977 ++dest;
1978 else if (bad_char_behavior == BAD_KEEP)
1979 *dest = u8c;
1980 else if (eap != NULL && eap->bad_char != 0)
1981 *dest = bad_char_behavior;
1982 else
1983 *dest = 0xBF;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001984 }
1985 else
1986 *dest = u8c;
1987 }
1988 }
1989
1990 /* move the linerest to before the converted characters */
1991 line_start = dest - linerest;
1992 mch_memmove(line_start, buffer, (size_t)linerest);
1993 size = (long)((ptr + real_size) - dest);
1994 ptr = dest;
1995 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001996 else if (enc_utf8 && !curbuf->b_p_bin)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001997 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001998 int incomplete_tail = FALSE;
1999
2000 /* Reading UTF-8: Check if the bytes are valid UTF-8. */
2001 for (p = ptr; ; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002002 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002003 int todo = (int)((ptr + size) - p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002004 int l;
2005
2006 if (todo <= 0)
2007 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002008 if (*p >= 0x80)
2009 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002010 /* A length of 1 means it's an illegal byte. Accept
2011 * an incomplete character at the end though, the next
2012 * read() will get the next bytes, we'll check it
2013 * then. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002014 l = utf_ptr2len_len(p, todo);
Bram Moolenaarf453d352008-06-04 17:37:34 +00002015 if (l > todo && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002016 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002017 /* Avoid retrying with a different encoding when
2018 * a truncated file is more likely, or attempting
2019 * to read the rest of an incomplete sequence when
2020 * we have already done so. */
2021 if (p > ptr || filesize > 0)
2022 incomplete_tail = TRUE;
2023 /* Incomplete byte sequence, move it to conv_rest[]
2024 * and try to read the rest of it, unless we've
2025 * already done so. */
2026 if (p > ptr)
2027 {
2028 conv_restlen = todo;
2029 mch_memmove(conv_rest, p, conv_restlen);
2030 size -= conv_restlen;
2031 break;
2032 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002033 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002034 if (l == 1 || l > todo)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002035 {
2036 /* Illegal byte. If we can try another encoding
Bram Moolenaarf453d352008-06-04 17:37:34 +00002037 * do that, unless at EOF where a truncated
2038 * file is more likely than a conversion error. */
2039 if (can_retry && !incomplete_tail)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002040 break;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002041# ifdef USE_ICONV
2042 /* When we did a conversion report an error. */
2043 if (iconv_fd != (iconv_t)-1 && conv_error == 0)
2044 conv_error = readfile_linenr(linecnt, ptr, p);
2045# endif
Bram Moolenaarf453d352008-06-04 17:37:34 +00002046 /* Remember the first linenr with an illegal byte */
2047 if (conv_error == 0 && illegal_byte == 0)
2048 illegal_byte = readfile_linenr(linecnt, ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002049
2050 /* Drop, keep or replace the bad byte. */
2051 if (bad_char_behavior == BAD_DROP)
2052 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002053 mch_memmove(p, p + 1, todo - 1);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002054 --p;
2055 --size;
2056 }
2057 else if (bad_char_behavior != BAD_KEEP)
2058 *p = bad_char_behavior;
2059 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002060 else
2061 p += l - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002062 }
2063 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002064 if (p < ptr + size && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002065 {
2066 /* Detected a UTF-8 error. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002067rewind_retry:
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002068 /* Retry reading with another conversion. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002069# if defined(FEAT_EVAL) && defined(USE_ICONV)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002070 if (*p_ccv != NUL && iconv_fd != (iconv_t)-1)
2071 /* iconv() failed, try 'charconvert' */
2072 did_iconv = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002073 else
2074# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002075 /* use next item from 'fileencodings' */
2076 advance_fenc = TRUE;
2077 file_rewind = TRUE;
2078 goto retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002079 }
2080 }
2081#endif
2082
2083 /* count the number of characters (after conversion!) */
2084 filesize += size;
2085
2086 /*
2087 * when reading the first part of a file: guess EOL type
2088 */
2089 if (fileformat == EOL_UNKNOWN)
2090 {
2091 /* First try finding a NL, for Dos and Unix */
2092 if (try_dos || try_unix)
2093 {
2094 for (p = ptr; p < ptr + size; ++p)
2095 {
2096 if (*p == NL)
2097 {
2098 if (!try_unix
2099 || (try_dos && p > ptr && p[-1] == CAR))
2100 fileformat = EOL_DOS;
2101 else
2102 fileformat = EOL_UNIX;
2103 break;
2104 }
2105 }
2106
2107 /* Don't give in to EOL_UNIX if EOL_MAC is more likely */
2108 if (fileformat == EOL_UNIX && try_mac)
2109 {
2110 /* Need to reset the counters when retrying fenc. */
2111 try_mac = 1;
2112 try_unix = 1;
2113 for (; p >= ptr && *p != CAR; p--)
2114 ;
2115 if (p >= ptr)
2116 {
2117 for (p = ptr; p < ptr + size; ++p)
2118 {
2119 if (*p == NL)
2120 try_unix++;
2121 else if (*p == CAR)
2122 try_mac++;
2123 }
2124 if (try_mac > try_unix)
2125 fileformat = EOL_MAC;
2126 }
2127 }
2128 }
2129
2130 /* No NL found: may use Mac format */
2131 if (fileformat == EOL_UNKNOWN && try_mac)
2132 fileformat = EOL_MAC;
2133
2134 /* Still nothing found? Use first format in 'ffs' */
2135 if (fileformat == EOL_UNKNOWN)
2136 fileformat = default_fileformat();
2137
2138 /* if editing a new file: may set p_tx and p_ff */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002139 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002140 set_fileformat(fileformat, OPT_LOCAL);
2141 }
2142 }
2143
2144 /*
2145 * This loop is executed once for every character read.
2146 * Keep it fast!
2147 */
2148 if (fileformat == EOL_MAC)
2149 {
2150 --ptr;
2151 while (++ptr, --size >= 0)
2152 {
2153 /* catch most common case first */
2154 if ((c = *ptr) != NUL && c != CAR && c != NL)
2155 continue;
2156 if (c == NUL)
2157 *ptr = NL; /* NULs are replaced by newlines! */
2158 else if (c == NL)
2159 *ptr = CAR; /* NLs are replaced by CRs! */
2160 else
2161 {
2162 if (skip_count == 0)
2163 {
2164 *ptr = NUL; /* end of line */
2165 len = (colnr_T) (ptr - line_start + 1);
2166 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2167 {
2168 error = TRUE;
2169 break;
2170 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002171#ifdef FEAT_PERSISTENT_UNDO
2172 if (read_undo_file)
2173 sha256_update(&sha_ctx, line_start, len);
2174#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002175 ++lnum;
2176 if (--read_count == 0)
2177 {
2178 error = TRUE; /* break loop */
2179 line_start = ptr; /* nothing left to write */
2180 break;
2181 }
2182 }
2183 else
2184 --skip_count;
2185 line_start = ptr + 1;
2186 }
2187 }
2188 }
2189 else
2190 {
2191 --ptr;
2192 while (++ptr, --size >= 0)
2193 {
2194 if ((c = *ptr) != NUL && c != NL) /* catch most common case */
2195 continue;
2196 if (c == NUL)
2197 *ptr = NL; /* NULs are replaced by newlines! */
2198 else
2199 {
2200 if (skip_count == 0)
2201 {
2202 *ptr = NUL; /* end of line */
2203 len = (colnr_T)(ptr - line_start + 1);
2204 if (fileformat == EOL_DOS)
2205 {
2206 if (ptr[-1] == CAR) /* remove CR */
2207 {
2208 ptr[-1] = NUL;
2209 --len;
2210 }
2211 /*
2212 * Reading in Dos format, but no CR-LF found!
2213 * When 'fileformats' includes "unix", delete all
2214 * the lines read so far and start all over again.
2215 * Otherwise give an error message later.
2216 */
2217 else if (ff_error != EOL_DOS)
2218 {
2219 if ( try_unix
2220 && !read_stdin
2221 && (read_buffer
2222 || lseek(fd, (off_t)0L, SEEK_SET) == 0))
2223 {
2224 fileformat = EOL_UNIX;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002225 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002226 set_fileformat(EOL_UNIX, OPT_LOCAL);
2227 file_rewind = TRUE;
2228 keep_fileformat = TRUE;
2229 goto retry;
2230 }
2231 ff_error = EOL_DOS;
2232 }
2233 }
2234 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2235 {
2236 error = TRUE;
2237 break;
2238 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002239#ifdef FEAT_PERSISTENT_UNDO
2240 if (read_undo_file)
2241 sha256_update(&sha_ctx, line_start, len);
2242#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002243 ++lnum;
2244 if (--read_count == 0)
2245 {
2246 error = TRUE; /* break loop */
2247 line_start = ptr; /* nothing left to write */
2248 break;
2249 }
2250 }
2251 else
2252 --skip_count;
2253 line_start = ptr + 1;
2254 }
2255 }
2256 }
2257 linerest = (long)(ptr - line_start);
2258 ui_breakcheck();
2259 }
2260
2261failed:
2262 /* not an error, max. number of lines reached */
2263 if (error && read_count == 0)
2264 error = FALSE;
2265
2266 /*
2267 * If we get EOF in the middle of a line, note the fact and
2268 * complete the line ourselves.
2269 * In Dos format ignore a trailing CTRL-Z, unless 'binary' set.
2270 */
2271 if (!error
2272 && !got_int
2273 && linerest != 0
2274 && !(!curbuf->b_p_bin
2275 && fileformat == EOL_DOS
2276 && *line_start == Ctrl_Z
2277 && ptr == line_start + 1))
2278 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002279 /* remember for when writing */
2280 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002281 curbuf->b_p_eol = FALSE;
2282 *ptr = NUL;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002283 len = (colnr_T)(ptr - line_start + 1);
2284 if (ml_append(lnum, line_start, len, newfile) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002285 error = TRUE;
2286 else
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002287 {
2288#ifdef FEAT_PERSISTENT_UNDO
2289 if (read_undo_file)
2290 sha256_update(&sha_ctx, line_start, len);
2291#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002292 read_no_eol_lnum = ++lnum;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002293 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002294 }
2295
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002296 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002297 save_file_ff(curbuf); /* remember the current file format */
2298
2299#ifdef FEAT_CRYPT
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002300 if (cryptkey != NULL)
2301 {
2302 crypt_pop_state();
2303 if (cryptkey != curbuf->b_p_key)
2304 free_crypt_key(cryptkey);
2305 /* don't set cryptkey to NULL, it's used below as a flag that
2306 * encryption was used */
2307 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002308#endif
2309
2310#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002311 /* If editing a new file: set 'fenc' for the current buffer.
2312 * Also for ":read ++edit file". */
2313 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002314 set_string_option_direct((char_u *)"fenc", -1, fenc,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00002315 OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002316 if (fenc_alloced)
2317 vim_free(fenc);
2318# ifdef USE_ICONV
2319 if (iconv_fd != (iconv_t)-1)
2320 {
2321 iconv_close(iconv_fd);
2322 iconv_fd = (iconv_t)-1;
2323 }
2324# endif
2325#endif
2326
2327 if (!read_buffer && !read_stdin)
2328 close(fd); /* errors are ignored */
Bram Moolenaarf05da212009-11-17 16:13:15 +00002329#ifdef HAVE_FD_CLOEXEC
2330 else
2331 {
2332 int fdflags = fcntl(fd, F_GETFD);
2333 if (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0)
2334 fcntl(fd, F_SETFD, fdflags | FD_CLOEXEC);
2335 }
2336#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002337 vim_free(buffer);
2338
2339#ifdef HAVE_DUP
2340 if (read_stdin)
2341 {
2342 /* Use stderr for stdin, makes shell commands work. */
2343 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00002344 ignored = dup(2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002345 }
2346#endif
2347
2348#ifdef FEAT_MBYTE
2349 if (tmpname != NULL)
2350 {
2351 mch_remove(tmpname); /* delete converted file */
2352 vim_free(tmpname);
2353 }
2354#endif
2355 --no_wait_return; /* may wait for return now */
2356
2357 /*
2358 * In recovery mode everything but autocommands is skipped.
2359 */
2360 if (!recoverymode)
2361 {
2362 /* need to delete the last line, which comes from the empty buffer */
2363 if (newfile && wasempty && !(curbuf->b_ml.ml_flags & ML_EMPTY))
2364 {
2365#ifdef FEAT_NETBEANS_INTG
2366 netbeansFireChanges = 0;
2367#endif
2368 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
2369#ifdef FEAT_NETBEANS_INTG
2370 netbeansFireChanges = 1;
2371#endif
2372 --linecnt;
2373 }
2374 linecnt = curbuf->b_ml.ml_line_count - linecnt;
2375 if (filesize == 0)
2376 linecnt = 0;
2377 if (newfile || read_buffer)
Bram Moolenaar7263a772007-05-10 17:35:54 +00002378 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002379 redraw_curbuf_later(NOT_VALID);
Bram Moolenaar7263a772007-05-10 17:35:54 +00002380#ifdef FEAT_DIFF
2381 /* After reading the text into the buffer the diff info needs to
2382 * be updated. */
2383 diff_invalidate(curbuf);
2384#endif
2385#ifdef FEAT_FOLDING
2386 /* All folds in the window are invalid now. Mark them for update
2387 * before triggering autocommands. */
2388 foldUpdateAll(curwin);
2389#endif
2390 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002391 else if (linecnt) /* appended at least one line */
2392 appended_lines_mark(from, linecnt);
2393
Bram Moolenaar071d4272004-06-13 20:20:40 +00002394#ifndef ALWAYS_USE_GUI
2395 /*
2396 * If we were reading from the same terminal as where messages go,
2397 * the screen will have been messed up.
2398 * Switch on raw mode now and clear the screen.
2399 */
2400 if (read_stdin)
2401 {
2402 settmode(TMODE_RAW); /* set to raw mode */
2403 starttermcap();
2404 screenclear();
2405 }
2406#endif
2407
2408 if (got_int)
2409 {
2410 if (!(flags & READ_DUMMY))
2411 {
2412 filemess(curbuf, sfname, (char_u *)_(e_interr), 0);
2413 if (newfile)
2414 curbuf->b_p_ro = TRUE; /* must use "w!" now */
2415 }
2416 msg_scroll = msg_save;
2417#ifdef FEAT_VIMINFO
2418 check_marks_read();
2419#endif
2420 return OK; /* an interrupt isn't really an error */
2421 }
2422
2423 if (!filtering && !(flags & READ_DUMMY))
2424 {
2425 msg_add_fname(curbuf, sfname); /* fname in IObuff with quotes */
2426 c = FALSE;
2427
2428#ifdef UNIX
2429# ifdef S_ISFIFO
2430 if (S_ISFIFO(perm)) /* fifo or socket */
2431 {
2432 STRCAT(IObuff, _("[fifo/socket]"));
2433 c = TRUE;
2434 }
2435# else
2436# ifdef S_IFIFO
2437 if ((perm & S_IFMT) == S_IFIFO) /* fifo */
2438 {
2439 STRCAT(IObuff, _("[fifo]"));
2440 c = TRUE;
2441 }
2442# endif
2443# ifdef S_IFSOCK
2444 if ((perm & S_IFMT) == S_IFSOCK) /* or socket */
2445 {
2446 STRCAT(IObuff, _("[socket]"));
2447 c = TRUE;
2448 }
2449# endif
2450# endif
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002451# ifdef OPEN_CHR_FILES
2452 if (S_ISCHR(perm)) /* or character special */
2453 {
2454 STRCAT(IObuff, _("[character special]"));
2455 c = TRUE;
2456 }
2457# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002458#endif
2459 if (curbuf->b_p_ro)
2460 {
2461 STRCAT(IObuff, shortmess(SHM_RO) ? _("[RO]") : _("[readonly]"));
2462 c = TRUE;
2463 }
2464 if (read_no_eol_lnum)
2465 {
2466 msg_add_eol();
2467 c = TRUE;
2468 }
2469 if (ff_error == EOL_DOS)
2470 {
2471 STRCAT(IObuff, _("[CR missing]"));
2472 c = TRUE;
2473 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002474 if (split)
2475 {
2476 STRCAT(IObuff, _("[long lines split]"));
2477 c = TRUE;
2478 }
2479#ifdef FEAT_MBYTE
2480 if (notconverted)
2481 {
2482 STRCAT(IObuff, _("[NOT converted]"));
2483 c = TRUE;
2484 }
2485 else if (converted)
2486 {
2487 STRCAT(IObuff, _("[converted]"));
2488 c = TRUE;
2489 }
2490#endif
2491#ifdef FEAT_CRYPT
2492 if (cryptkey != NULL)
2493 {
2494 STRCAT(IObuff, _("[crypted]"));
2495 c = TRUE;
2496 }
2497#endif
2498#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002499 if (conv_error != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002500 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002501 sprintf((char *)IObuff + STRLEN(IObuff),
2502 _("[CONVERSION ERROR in line %ld]"), (long)conv_error);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002503 c = TRUE;
2504 }
2505 else if (illegal_byte > 0)
2506 {
2507 sprintf((char *)IObuff + STRLEN(IObuff),
2508 _("[ILLEGAL BYTE in line %ld]"), (long)illegal_byte);
2509 c = TRUE;
2510 }
2511 else
2512#endif
2513 if (error)
2514 {
2515 STRCAT(IObuff, _("[READ ERRORS]"));
2516 c = TRUE;
2517 }
2518 if (msg_add_fileformat(fileformat))
2519 c = TRUE;
2520#ifdef FEAT_CRYPT
2521 if (cryptkey != NULL)
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002522 msg_add_lines(c, (long)linecnt, filesize
Bram Moolenaar80794b12010-06-13 05:20:42 +02002523 - CRYPT_MAGIC_LEN
2524 - crypt_salt_len[use_crypt_method]
2525 - crypt_seed_len[use_crypt_method]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002526 else
2527#endif
2528 msg_add_lines(c, (long)linecnt, filesize);
2529
2530 vim_free(keep_msg);
2531 keep_msg = NULL;
2532 msg_scrolled_ign = TRUE;
2533#ifdef ALWAYS_USE_GUI
2534 /* Don't show the message when reading stdin, it would end up in a
2535 * message box (which might be shown when exiting!) */
2536 if (read_stdin || read_buffer)
2537 p = msg_may_trunc(FALSE, IObuff);
2538 else
2539#endif
2540 p = msg_trunc_attr(IObuff, FALSE, 0);
2541 if (read_stdin || read_buffer || restart_edit != 0
Bram Moolenaar1c7715d2005-10-03 22:02:18 +00002542 || (msg_scrolled != 0 && !need_wait_return))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002543 /* Need to repeat the message after redrawing when:
2544 * - When reading from stdin (the screen will be cleared next).
2545 * - When restart_edit is set (otherwise there will be a delay
2546 * before redrawing).
2547 * - When the screen was scrolled but there is no wait-return
2548 * prompt. */
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002549 set_keep_msg(p, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002550 msg_scrolled_ign = FALSE;
2551 }
2552
2553 /* with errors writing the file requires ":w!" */
2554 if (newfile && (error
2555#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002556 || conv_error != 0
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002557 || (illegal_byte > 0 && bad_char_behavior != BAD_KEEP)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002558#endif
2559 ))
2560 curbuf->b_p_ro = TRUE;
2561
2562 u_clearline(); /* cannot use "U" command after adding lines */
2563
2564 /*
2565 * In Ex mode: cursor at last new line.
2566 * Otherwise: cursor at first new line.
2567 */
2568 if (exmode_active)
2569 curwin->w_cursor.lnum = from + linecnt;
2570 else
2571 curwin->w_cursor.lnum = from + 1;
2572 check_cursor_lnum();
2573 beginline(BL_WHITE | BL_FIX); /* on first non-blank */
2574
2575 /*
2576 * Set '[ and '] marks to the newly read lines.
2577 */
2578 curbuf->b_op_start.lnum = from + 1;
2579 curbuf->b_op_start.col = 0;
2580 curbuf->b_op_end.lnum = from + linecnt;
2581 curbuf->b_op_end.col = 0;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002582
2583#ifdef WIN32
2584 /*
2585 * Work around a weird problem: When a file has two links (only
2586 * possible on NTFS) and we write through one link, then stat() it
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00002587 * through the other link, the timestamp information may be wrong.
Bram Moolenaar03f48552006-02-28 23:52:23 +00002588 * It's correct again after reading the file, thus reset the timestamp
2589 * here.
2590 */
2591 if (newfile && !read_stdin && !read_buffer
2592 && mch_stat((char *)fname, &st) >= 0)
2593 {
2594 buf_store_time(curbuf, &st, fname);
2595 curbuf->b_mtime_read = curbuf->b_mtime;
2596 }
2597#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002598 }
2599 msg_scroll = msg_save;
2600
2601#ifdef FEAT_VIMINFO
2602 /*
2603 * Get the marks before executing autocommands, so they can be used there.
2604 */
2605 check_marks_read();
2606#endif
2607
Bram Moolenaar071d4272004-06-13 20:20:40 +00002608 /*
2609 * Trick: We remember if the last line of the read didn't have
2610 * an eol for when writing it again. This is required for
2611 * ":autocmd FileReadPost *.gz set bin|'[,']!gunzip" to work.
2612 */
2613 write_no_eol_lnum = read_no_eol_lnum;
2614
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02002615 /* When reloading a buffer put the cursor at the first line that is
2616 * different. */
2617 if (flags & READ_KEEP_UNDO)
2618 u_find_first_changed();
2619
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002620#ifdef FEAT_PERSISTENT_UNDO
2621 /*
2622 * When opening a new file locate undo info and read it.
2623 */
2624 if (read_undo_file)
2625 {
2626 char_u hash[UNDO_HASH_SIZE];
2627
2628 sha256_finish(&sha_ctx, hash);
Bram Moolenaar6ed8ed82010-05-30 20:40:11 +02002629 u_read_undo(NULL, hash, fname);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002630 }
2631#endif
2632
Bram Moolenaardf177f62005-02-22 08:39:57 +00002633#ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00002634 if (!read_stdin && !read_buffer)
2635 {
2636 int m = msg_scroll;
2637 int n = msg_scrolled;
2638
2639 /* Save the fileformat now, otherwise the buffer will be considered
2640 * modified if the format/encoding was automatically detected. */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002641 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002642 save_file_ff(curbuf);
2643
2644 /*
2645 * The output from the autocommands should not overwrite anything and
2646 * should not be overwritten: Set msg_scroll, restore its value if no
2647 * output was done.
2648 */
2649 msg_scroll = TRUE;
2650 if (filtering)
2651 apply_autocmds_exarg(EVENT_FILTERREADPOST, NULL, sfname,
2652 FALSE, curbuf, eap);
2653 else if (newfile)
2654 apply_autocmds_exarg(EVENT_BUFREADPOST, NULL, sfname,
2655 FALSE, curbuf, eap);
2656 else
2657 apply_autocmds_exarg(EVENT_FILEREADPOST, sfname, sfname,
2658 FALSE, NULL, eap);
2659 if (msg_scrolled == n)
2660 msg_scroll = m;
2661#ifdef FEAT_EVAL
2662 if (aborting()) /* autocmds may abort script processing */
2663 return FAIL;
2664#endif
2665 }
2666#endif
2667
2668 if (recoverymode && error)
2669 return FAIL;
2670 return OK;
2671}
2672
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002673#ifdef OPEN_CHR_FILES
2674/*
2675 * Returns TRUE if the file name argument is of the form "/dev/fd/\d\+",
2676 * which is the name of files used for process substitution output by
2677 * some shells on some operating systems, e.g., bash on SunOS.
2678 * Do not accept "/dev/fd/[012]", opening these may hang Vim.
2679 */
2680 static int
2681is_dev_fd_file(fname)
2682 char_u *fname;
2683{
2684 return (STRNCMP(fname, "/dev/fd/", 8) == 0
2685 && VIM_ISDIGIT(fname[8])
2686 && *skipdigits(fname + 9) == NUL
2687 && (fname[9] != NUL
2688 || (fname[8] != '0' && fname[8] != '1' && fname[8] != '2')));
2689}
2690#endif
2691
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002692#ifdef FEAT_MBYTE
2693
2694/*
2695 * From the current line count and characters read after that, estimate the
2696 * line number where we are now.
2697 * Used for error messages that include a line number.
2698 */
2699 static linenr_T
2700readfile_linenr(linecnt, p, endp)
2701 linenr_T linecnt; /* line count before reading more bytes */
2702 char_u *p; /* start of more bytes read */
2703 char_u *endp; /* end of more bytes read */
2704{
2705 char_u *s;
2706 linenr_T lnum;
2707
2708 lnum = curbuf->b_ml.ml_line_count - linecnt + 1;
2709 for (s = p; s < endp; ++s)
2710 if (*s == '\n')
2711 ++lnum;
2712 return lnum;
2713}
2714#endif
2715
Bram Moolenaar071d4272004-06-13 20:20:40 +00002716/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00002717 * Fill "*eap" to force the 'fileencoding', 'fileformat' and 'binary to be
2718 * equal to the buffer "buf". Used for calling readfile().
Bram Moolenaar071d4272004-06-13 20:20:40 +00002719 * Returns OK or FAIL.
2720 */
2721 int
2722prep_exarg(eap, buf)
2723 exarg_T *eap;
2724 buf_T *buf;
2725{
2726 eap->cmd = alloc((unsigned)(STRLEN(buf->b_p_ff)
2727#ifdef FEAT_MBYTE
2728 + STRLEN(buf->b_p_fenc)
2729#endif
2730 + 15));
2731 if (eap->cmd == NULL)
2732 return FAIL;
2733
2734#ifdef FEAT_MBYTE
2735 sprintf((char *)eap->cmd, "e ++ff=%s ++enc=%s", buf->b_p_ff, buf->b_p_fenc);
2736 eap->force_enc = 14 + (int)STRLEN(buf->b_p_ff);
Bram Moolenaar195d6352005-12-19 22:08:24 +00002737 eap->bad_char = buf->b_bad_char;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002738#else
2739 sprintf((char *)eap->cmd, "e ++ff=%s", buf->b_p_ff);
2740#endif
2741 eap->force_ff = 7;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002742
2743 eap->force_bin = buf->b_p_bin ? FORCE_BIN : FORCE_NOBIN;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002744 eap->read_edit = FALSE;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002745 eap->forceit = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002746 return OK;
2747}
2748
2749#ifdef FEAT_MBYTE
2750/*
2751 * Find next fileencoding to use from 'fileencodings'.
2752 * "pp" points to fenc_next. It's advanced to the next item.
2753 * When there are no more items, an empty string is returned and *pp is set to
2754 * NULL.
2755 * When *pp is not set to NULL, the result is in allocated memory.
2756 */
2757 static char_u *
2758next_fenc(pp)
2759 char_u **pp;
2760{
2761 char_u *p;
2762 char_u *r;
2763
2764 if (**pp == NUL)
2765 {
2766 *pp = NULL;
2767 return (char_u *)"";
2768 }
2769 p = vim_strchr(*pp, ',');
2770 if (p == NULL)
2771 {
2772 r = enc_canonize(*pp);
2773 *pp += STRLEN(*pp);
2774 }
2775 else
2776 {
2777 r = vim_strnsave(*pp, (int)(p - *pp));
2778 *pp = p + 1;
2779 if (r != NULL)
2780 {
2781 p = enc_canonize(r);
2782 vim_free(r);
2783 r = p;
2784 }
2785 }
2786 if (r == NULL) /* out of memory */
2787 {
2788 r = (char_u *)"";
2789 *pp = NULL;
2790 }
2791 return r;
2792}
2793
2794# ifdef FEAT_EVAL
2795/*
2796 * Convert a file with the 'charconvert' expression.
2797 * This closes the file which is to be read, converts it and opens the
2798 * resulting file for reading.
2799 * Returns name of the resulting converted file (the caller should delete it
2800 * after reading it).
2801 * Returns NULL if the conversion failed ("*fdp" is not set) .
2802 */
2803 static char_u *
2804readfile_charconvert(fname, fenc, fdp)
2805 char_u *fname; /* name of input file */
2806 char_u *fenc; /* converted from */
2807 int *fdp; /* in/out: file descriptor of file */
2808{
2809 char_u *tmpname;
2810 char_u *errmsg = NULL;
2811
2812 tmpname = vim_tempname('r');
2813 if (tmpname == NULL)
2814 errmsg = (char_u *)_("Can't find temp file for conversion");
2815 else
2816 {
2817 close(*fdp); /* close the input file, ignore errors */
2818 *fdp = -1;
2819 if (eval_charconvert(fenc, enc_utf8 ? (char_u *)"utf-8" : p_enc,
2820 fname, tmpname) == FAIL)
2821 errmsg = (char_u *)_("Conversion with 'charconvert' failed");
2822 if (errmsg == NULL && (*fdp = mch_open((char *)tmpname,
2823 O_RDONLY | O_EXTRA, 0)) < 0)
2824 errmsg = (char_u *)_("can't read output of 'charconvert'");
2825 }
2826
2827 if (errmsg != NULL)
2828 {
2829 /* Don't use emsg(), it breaks mappings, the retry with
2830 * another type of conversion might still work. */
2831 MSG(errmsg);
2832 if (tmpname != NULL)
2833 {
2834 mch_remove(tmpname); /* delete converted file */
2835 vim_free(tmpname);
2836 tmpname = NULL;
2837 }
2838 }
2839
2840 /* If the input file is closed, open it (caller should check for error). */
2841 if (*fdp < 0)
2842 *fdp = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
2843
2844 return tmpname;
2845}
2846# endif
2847
2848#endif
2849
2850#ifdef FEAT_VIMINFO
2851/*
2852 * Read marks for the current buffer from the viminfo file, when we support
2853 * buffer marks and the buffer has a name.
2854 */
2855 static void
2856check_marks_read()
2857{
2858 if (!curbuf->b_marks_read && get_viminfo_parameter('\'') > 0
2859 && curbuf->b_ffname != NULL)
Bram Moolenaard812df62008-11-09 12:46:09 +00002860 read_viminfo(NULL, VIF_WANT_MARKS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002861
2862 /* Always set b_marks_read; needed when 'viminfo' is changed to include
2863 * the ' parameter after opening a buffer. */
2864 curbuf->b_marks_read = TRUE;
2865}
2866#endif
2867
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002868#if defined(FEAT_CRYPT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002869/*
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002870 * Get the crypt method used for a file from "ptr[len]", the magic text at the
2871 * start of the file.
2872 * Returns -1 when no encryption used.
2873 */
2874 static int
Bram Moolenaar49771f42010-07-20 17:32:38 +02002875crypt_method_from_magic(ptr, len)
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002876 char *ptr;
2877 int len;
2878{
2879 int i;
2880
2881 for (i = 0; i < (int)(sizeof(crypt_magic) / sizeof(crypt_magic[0])); i++)
2882 {
Bram Moolenaar80794b12010-06-13 05:20:42 +02002883 if (len < (CRYPT_MAGIC_LEN + crypt_salt_len[i] + crypt_seed_len[i]))
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002884 continue;
2885 if (memcmp(ptr, crypt_magic[i], CRYPT_MAGIC_LEN) == 0)
2886 return i;
2887 }
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002888
Bram Moolenaar442b4222010-05-24 21:34:22 +02002889 i = (int)STRLEN(crypt_magic_head);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002890 if (len >= i && memcmp(ptr, crypt_magic_head, i) == 0)
2891 EMSG(_("E821: File is encrypted with unknown method"));
2892
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002893 return -1;
2894}
2895
2896/*
2897 * Check for magic number used for encryption. Applies to the current buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002898 * If found, the magic number is removed from ptr[*sizep] and *sizep and
2899 * *filesizep are updated.
2900 * Return the (new) encryption key, NULL for no encryption.
2901 */
2902 static char_u *
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002903check_for_cryptkey(cryptkey, ptr, sizep, filesizep, newfile, fname, did_ask)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002904 char_u *cryptkey; /* previous encryption key or NULL */
2905 char_u *ptr; /* pointer to read bytes */
2906 long *sizep; /* length of read bytes */
Bram Moolenaar914703b2010-05-31 21:59:46 +02002907 off_t *filesizep; /* nr of bytes used from file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002908 int newfile; /* editing a new buffer */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002909 char_u *fname; /* file name to display */
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002910 int *did_ask; /* flag: whether already asked for key */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002911{
Bram Moolenaar49771f42010-07-20 17:32:38 +02002912 int method = crypt_method_from_magic((char *)ptr, *sizep);
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002913
2914 if (method >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002915 {
Bram Moolenaar49771f42010-07-20 17:32:38 +02002916 set_crypt_method(curbuf, method);
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002917 if (method > 0)
2918 (void)blowfish_self_test();
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002919 if (cryptkey == NULL && !*did_ask)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002920 {
2921 if (*curbuf->b_p_key)
2922 cryptkey = curbuf->b_p_key;
2923 else
2924 {
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002925 /* When newfile is TRUE, store the typed key in the 'key'
2926 * option and don't free it. bf needs hash of the key saved.
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002927 * Don't ask for the key again when first time Enter was hit.
2928 * Happens when retrying to detect encoding. */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002929 smsg((char_u *)_(need_key_msg), fname);
2930 msg_scroll = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002931 cryptkey = get_crypt_key(newfile, FALSE);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002932 *did_ask = TRUE;
2933
Bram Moolenaar071d4272004-06-13 20:20:40 +00002934 /* check if empty key entered */
2935 if (cryptkey != NULL && *cryptkey == NUL)
2936 {
2937 if (cryptkey != curbuf->b_p_key)
2938 vim_free(cryptkey);
2939 cryptkey = NULL;
2940 }
2941 }
2942 }
2943
2944 if (cryptkey != NULL)
2945 {
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002946 int seed_len = crypt_seed_len[method];
Bram Moolenaar80794b12010-06-13 05:20:42 +02002947 int salt_len = crypt_salt_len[method];
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002948
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002949 crypt_push_state();
2950 use_crypt_method = method;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002951 if (method == 0)
2952 crypt_init_keys(cryptkey);
2953 else
2954 {
Bram Moolenaar80794b12010-06-13 05:20:42 +02002955 bf_key_init(cryptkey, ptr + CRYPT_MAGIC_LEN, salt_len);
2956 bf_ofb_init(ptr + CRYPT_MAGIC_LEN + salt_len, seed_len);
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002957 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002958
2959 /* Remove magic number from the text */
Bram Moolenaar80794b12010-06-13 05:20:42 +02002960 *filesizep += CRYPT_MAGIC_LEN + salt_len + seed_len;
2961 *sizep -= CRYPT_MAGIC_LEN + salt_len + seed_len;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002962 mch_memmove(ptr, ptr + CRYPT_MAGIC_LEN + salt_len + seed_len,
2963 (size_t)*sizep);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002964 }
2965 }
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002966 /* When starting to edit a new file which does not have encryption, clear
2967 * the 'key' option, except when starting up (called with -x argument) */
Bram Moolenaarfa0ff9a2010-07-25 16:05:19 +02002968 else if (newfile && *curbuf->b_p_key != NUL && !starting)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002969 set_option_value((char_u *)"key", 0L, (char_u *)"", OPT_LOCAL);
2970
2971 return cryptkey;
2972}
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002973
2974/*
2975 * Check for magic number used for encryption. Applies to the current buffer.
2976 * If found and decryption is possible returns OK;
2977 */
2978 int
2979prepare_crypt_read(fp)
2980 FILE *fp;
2981{
2982 int method;
Bram Moolenaar80794b12010-06-13 05:20:42 +02002983 char_u buffer[CRYPT_MAGIC_LEN + CRYPT_SALT_LEN_MAX
2984 + CRYPT_SEED_LEN_MAX + 2];
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002985
2986 if (fread(buffer, CRYPT_MAGIC_LEN, 1, fp) != 1)
2987 return FAIL;
Bram Moolenaar49771f42010-07-20 17:32:38 +02002988 method = crypt_method_from_magic((char *)buffer,
Bram Moolenaar80794b12010-06-13 05:20:42 +02002989 CRYPT_MAGIC_LEN +
Bram Moolenaarcc448b32010-07-14 16:52:17 +02002990 CRYPT_SEED_LEN_MAX +
2991 CRYPT_SALT_LEN_MAX);
Bram Moolenaar49771f42010-07-20 17:32:38 +02002992 if (method < 0 || method != get_crypt_method(curbuf))
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002993 return FAIL;
2994
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002995 crypt_push_state();
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002996 if (method == 0)
2997 crypt_init_keys(curbuf->b_p_key);
2998 else
2999 {
Bram Moolenaar80794b12010-06-13 05:20:42 +02003000 int salt_len = crypt_salt_len[method];
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003001 int seed_len = crypt_seed_len[method];
3002
Bram Moolenaar80794b12010-06-13 05:20:42 +02003003 if (fread(buffer, salt_len + seed_len, 1, fp) != 1)
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003004 return FAIL;
Bram Moolenaar80794b12010-06-13 05:20:42 +02003005 bf_key_init(curbuf->b_p_key, buffer, salt_len);
3006 bf_ofb_init(buffer + salt_len, seed_len);
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003007 }
3008 return OK;
3009}
3010
3011/*
3012 * Prepare for writing encrypted bytes for buffer "buf".
3013 * Returns a pointer to an allocated header of length "*lenp".
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003014 * When out of memory returns NULL.
3015 * Otherwise calls crypt_push_state(), call crypt_pop_state() later.
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003016 */
3017 char_u *
3018prepare_crypt_write(buf, lenp)
3019 buf_T *buf;
3020 int *lenp;
3021{
3022 char_u *header;
Bram Moolenaar49771f42010-07-20 17:32:38 +02003023 int seed_len = crypt_seed_len[get_crypt_method(buf)];
3024 int salt_len = crypt_salt_len[get_crypt_method(buf)];
Bram Moolenaar80794b12010-06-13 05:20:42 +02003025 char_u *salt;
3026 char_u *seed;
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003027
Bram Moolenaar80794b12010-06-13 05:20:42 +02003028 header = alloc_clear(CRYPT_MAGIC_LEN + CRYPT_SALT_LEN_MAX
3029 + CRYPT_SEED_LEN_MAX + 2);
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003030 if (header != NULL)
3031 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003032 crypt_push_state();
Bram Moolenaar49771f42010-07-20 17:32:38 +02003033 use_crypt_method = get_crypt_method(buf); /* select zip or blowfish */
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003034 vim_strncpy(header, (char_u *)crypt_magic[use_crypt_method],
3035 CRYPT_MAGIC_LEN);
Bram Moolenaar49771f42010-07-20 17:32:38 +02003036 if (use_crypt_method == 0)
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003037 crypt_init_keys(buf->b_p_key);
3038 else
3039 {
Bram Moolenaar80794b12010-06-13 05:20:42 +02003040 /* Using blowfish, add salt and seed. */
3041 salt = header + CRYPT_MAGIC_LEN;
3042 seed = salt + salt_len;
3043 sha2_seed(salt, salt_len, seed, seed_len);
3044 bf_key_init(buf->b_p_key, salt, salt_len);
3045 bf_ofb_init(seed, seed_len);
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003046 }
3047 }
Bram Moolenaar80794b12010-06-13 05:20:42 +02003048 *lenp = CRYPT_MAGIC_LEN + salt_len + seed_len;
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003049 return header;
3050}
3051
Bram Moolenaar80794b12010-06-13 05:20:42 +02003052#endif /* FEAT_CRYPT */
3053
Bram Moolenaar071d4272004-06-13 20:20:40 +00003054#ifdef UNIX
3055 static void
3056set_file_time(fname, atime, mtime)
3057 char_u *fname;
3058 time_t atime; /* access time */
3059 time_t mtime; /* modification time */
3060{
3061# if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
3062 struct utimbuf buf;
3063
3064 buf.actime = atime;
3065 buf.modtime = mtime;
3066 (void)utime((char *)fname, &buf);
3067# else
3068# if defined(HAVE_UTIMES)
3069 struct timeval tvp[2];
3070
3071 tvp[0].tv_sec = atime;
3072 tvp[0].tv_usec = 0;
3073 tvp[1].tv_sec = mtime;
3074 tvp[1].tv_usec = 0;
3075# ifdef NeXT
3076 (void)utimes((char *)fname, tvp);
3077# else
3078 (void)utimes((char *)fname, (const struct timeval *)&tvp);
3079# endif
3080# endif
3081# endif
3082}
3083#endif /* UNIX */
3084
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003085#if defined(VMS) && !defined(MIN)
3086/* Older DECC compiler for VAX doesn't define MIN() */
3087# define MIN(a, b) ((a) < (b) ? (a) : (b))
3088#endif
3089
Bram Moolenaar071d4272004-06-13 20:20:40 +00003090/*
Bram Moolenaar5386a122007-06-28 20:02:32 +00003091 * Return TRUE if a file appears to be read-only from the file permissions.
3092 */
3093 int
3094check_file_readonly(fname, perm)
3095 char_u *fname; /* full path to file */
3096 int perm; /* known permissions on file */
3097{
3098#ifndef USE_MCH_ACCESS
3099 int fd = 0;
3100#endif
3101
3102 return (
3103#ifdef USE_MCH_ACCESS
3104# ifdef UNIX
3105 (perm & 0222) == 0 ||
3106# endif
3107 mch_access((char *)fname, W_OK)
3108#else
3109 (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0
3110 ? TRUE : (close(fd), FALSE)
3111#endif
3112 );
3113}
3114
3115
3116/*
Bram Moolenaar292ad192005-12-11 21:29:51 +00003117 * buf_write() - write to file "fname" lines "start" through "end"
Bram Moolenaar071d4272004-06-13 20:20:40 +00003118 *
3119 * We do our own buffering here because fwrite() is so slow.
3120 *
Bram Moolenaar292ad192005-12-11 21:29:51 +00003121 * If "forceit" is true, we don't care for errors when attempting backups.
3122 * In case of an error everything possible is done to restore the original
Bram Moolenaare37d50a2008-08-06 17:06:04 +00003123 * file. But when "forceit" is TRUE, we risk losing it.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003124 *
3125 * When "reset_changed" is TRUE and "append" == FALSE and "start" == 1 and
3126 * "end" == curbuf->b_ml.ml_line_count, reset curbuf->b_changed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003127 *
3128 * This function must NOT use NameBuff (because it's called by autowrite()).
3129 *
3130 * return FAIL for failure, OK otherwise
3131 */
3132 int
3133buf_write(buf, fname, sfname, start, end, eap, append, forceit,
3134 reset_changed, filtering)
3135 buf_T *buf;
3136 char_u *fname;
3137 char_u *sfname;
3138 linenr_T start, end;
3139 exarg_T *eap; /* for forced 'ff' and 'fenc', can be
3140 NULL! */
Bram Moolenaar292ad192005-12-11 21:29:51 +00003141 int append; /* append to the file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003142 int forceit;
3143 int reset_changed;
3144 int filtering;
3145{
3146 int fd;
3147 char_u *backup = NULL;
3148 int backup_copy = FALSE; /* copy the original file? */
3149 int dobackup;
3150 char_u *ffname;
3151 char_u *wfname = NULL; /* name of file to write to */
3152 char_u *s;
3153 char_u *ptr;
3154 char_u c;
3155 int len;
3156 linenr_T lnum;
3157 long nchars;
3158 char_u *errmsg = NULL;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003159 int errmsg_allocated = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003160 char_u *errnum = NULL;
3161 char_u *buffer;
3162 char_u smallbuf[SMBUFSIZE];
3163 char_u *backup_ext;
3164 int bufsize;
3165 long perm; /* file permissions */
3166 int retval = OK;
3167 int newfile = FALSE; /* TRUE if file doesn't exist yet */
3168 int msg_save = msg_scroll;
3169 int overwriting; /* TRUE if writing over original */
3170 int no_eol = FALSE; /* no end-of-line written */
3171 int device = FALSE; /* writing to a device */
3172 struct stat st_old;
3173 int prev_got_int = got_int;
3174 int file_readonly = FALSE; /* overwritten file is read-only */
3175 static char *err_readonly = "is read-only (cannot override: \"W\" in 'cpoptions')";
3176#if defined(UNIX) || defined(__EMX__XX) /*XXX fix me sometime? */
3177 int made_writable = FALSE; /* 'w' bit has been set */
3178#endif
3179 /* writing everything */
3180 int whole = (start == 1 && end == buf->b_ml.ml_line_count);
3181#ifdef FEAT_AUTOCMD
3182 linenr_T old_line_count = buf->b_ml.ml_line_count;
3183#endif
3184 int attr;
3185 int fileformat;
3186 int write_bin;
3187 struct bw_info write_info; /* info for buf_write_bytes() */
3188#ifdef FEAT_MBYTE
3189 int converted = FALSE;
3190 int notconverted = FALSE;
3191 char_u *fenc; /* effective 'fileencoding' */
3192 char_u *fenc_tofree = NULL; /* allocated "fenc" */
3193#endif
3194#ifdef HAS_BW_FLAGS
3195 int wb_flags = 0;
3196#endif
3197#ifdef HAVE_ACL
3198 vim_acl_T acl = NULL; /* ACL copied from original file to
3199 backup or new file */
3200#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003201#ifdef FEAT_PERSISTENT_UNDO
3202 int write_undo_file = FALSE;
3203 context_sha256_T sha_ctx;
3204#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003205
3206 if (fname == NULL || *fname == NUL) /* safety check */
3207 return FAIL;
Bram Moolenaar70d60e92009-12-31 13:53:33 +00003208 if (buf->b_ml.ml_mfp == NULL)
3209 {
3210 /* This can happen during startup when there is a stray "w" in the
3211 * vimrc file. */
3212 EMSG(_(e_emptybuf));
3213 return FAIL;
3214 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003215
3216 /*
3217 * Disallow writing from .exrc and .vimrc in current directory for
3218 * security reasons.
3219 */
3220 if (check_secure())
3221 return FAIL;
3222
3223 /* Avoid a crash for a long name. */
3224 if (STRLEN(fname) >= MAXPATHL)
3225 {
3226 EMSG(_(e_longname));
3227 return FAIL;
3228 }
3229
3230#ifdef FEAT_MBYTE
3231 /* must init bw_conv_buf and bw_iconv_fd before jumping to "fail" */
3232 write_info.bw_conv_buf = NULL;
3233 write_info.bw_conv_error = FALSE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003234 write_info.bw_conv_error_lnum = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003235 write_info.bw_restlen = 0;
3236# ifdef USE_ICONV
3237 write_info.bw_iconv_fd = (iconv_t)-1;
3238# endif
3239#endif
3240
Bram Moolenaardf177f62005-02-22 08:39:57 +00003241 /* After writing a file changedtick changes but we don't want to display
3242 * the line. */
3243 ex_no_reprint = TRUE;
3244
Bram Moolenaar071d4272004-06-13 20:20:40 +00003245 /*
3246 * If there is no file name yet, use the one for the written file.
3247 * BF_NOTEDITED is set to reflect this (in case the write fails).
3248 * Don't do this when the write is for a filter command.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003249 * Don't do this when appending.
3250 * Only do this when 'cpoptions' contains the 'F' flag.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003251 */
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003252 if (buf->b_ffname == NULL
3253 && reset_changed
Bram Moolenaar071d4272004-06-13 20:20:40 +00003254 && whole
3255 && buf == curbuf
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00003256#ifdef FEAT_QUICKFIX
3257 && !bt_nofile(buf)
3258#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003259 && !filtering
Bram Moolenaar292ad192005-12-11 21:29:51 +00003260 && (!append || vim_strchr(p_cpo, CPO_FNAMEAPP) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003261 && vim_strchr(p_cpo, CPO_FNAMEW) != NULL)
3262 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003263 if (set_rw_fname(fname, sfname) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003264 return FAIL;
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003265 buf = curbuf; /* just in case autocmds made "buf" invalid */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003266 }
3267
3268 if (sfname == NULL)
3269 sfname = fname;
3270 /*
3271 * For Unix: Use the short file name whenever possible.
3272 * Avoids problems with networks and when directory names are changed.
3273 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
3274 * another directory, which we don't detect
3275 */
3276 ffname = fname; /* remember full fname */
3277#ifdef UNIX
3278 fname = sfname;
3279#endif
3280
3281 if (buf->b_ffname != NULL && fnamecmp(ffname, buf->b_ffname) == 0)
3282 overwriting = TRUE;
3283 else
3284 overwriting = FALSE;
3285
3286 if (exiting)
3287 settmode(TMODE_COOK); /* when exiting allow typahead now */
3288
3289 ++no_wait_return; /* don't wait for return yet */
3290
3291 /*
3292 * Set '[ and '] marks to the lines to be written.
3293 */
3294 buf->b_op_start.lnum = start;
3295 buf->b_op_start.col = 0;
3296 buf->b_op_end.lnum = end;
3297 buf->b_op_end.col = 0;
3298
3299#ifdef FEAT_AUTOCMD
3300 {
3301 aco_save_T aco;
3302 int buf_ffname = FALSE;
3303 int buf_sfname = FALSE;
3304 int buf_fname_f = FALSE;
3305 int buf_fname_s = FALSE;
3306 int did_cmd = FALSE;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003307 int nofile_err = FALSE;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003308 int empty_memline = (buf->b_ml.ml_mfp == NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003309
3310 /*
3311 * Apply PRE aucocommands.
3312 * Set curbuf to the buffer to be written.
3313 * Careful: The autocommands may call buf_write() recursively!
3314 */
3315 if (ffname == buf->b_ffname)
3316 buf_ffname = TRUE;
3317 if (sfname == buf->b_sfname)
3318 buf_sfname = TRUE;
3319 if (fname == buf->b_ffname)
3320 buf_fname_f = TRUE;
3321 if (fname == buf->b_sfname)
3322 buf_fname_s = TRUE;
3323
3324 /* set curwin/curbuf to buf and save a few things */
3325 aucmd_prepbuf(&aco, buf);
3326
3327 if (append)
3328 {
3329 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD,
3330 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003331 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003332#ifdef FEAT_QUICKFIX
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00003333 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003334 nofile_err = TRUE;
3335 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003336#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003337 apply_autocmds_exarg(EVENT_FILEAPPENDPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003338 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003339 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003340 }
3341 else if (filtering)
3342 {
3343 apply_autocmds_exarg(EVENT_FILTERWRITEPRE,
3344 NULL, sfname, FALSE, curbuf, eap);
3345 }
3346 else if (reset_changed && whole)
3347 {
3348 if (!(did_cmd = apply_autocmds_exarg(EVENT_BUFWRITECMD,
3349 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003350 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003351#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003352 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003353 nofile_err = TRUE;
3354 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003355#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003356 apply_autocmds_exarg(EVENT_BUFWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003357 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003358 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003359 }
3360 else
3361 {
3362 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD,
3363 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003364 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003365#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003366 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003367 nofile_err = TRUE;
3368 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003369#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003370 apply_autocmds_exarg(EVENT_FILEWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003371 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003372 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003373 }
3374
3375 /* restore curwin/curbuf and a few other things */
3376 aucmd_restbuf(&aco);
3377
3378 /*
3379 * In three situations we return here and don't write the file:
3380 * 1. the autocommands deleted or unloaded the buffer.
3381 * 2. The autocommands abort script processing.
3382 * 3. If one of the "Cmd" autocommands was executed.
3383 */
3384 if (!buf_valid(buf))
3385 buf = NULL;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003386 if (buf == NULL || (buf->b_ml.ml_mfp == NULL && !empty_memline)
Bram Moolenaar1e015462005-09-25 22:16:38 +00003387 || did_cmd || nofile_err
3388#ifdef FEAT_EVAL
3389 || aborting()
3390#endif
3391 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003392 {
3393 --no_wait_return;
3394 msg_scroll = msg_save;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003395 if (nofile_err)
3396 EMSG(_("E676: No matching autocommands for acwrite buffer"));
3397
Bram Moolenaar1e015462005-09-25 22:16:38 +00003398 if (nofile_err
3399#ifdef FEAT_EVAL
3400 || aborting()
3401#endif
3402 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003403 /* An aborting error, interrupt or exception in the
3404 * autocommands. */
3405 return FAIL;
3406 if (did_cmd)
3407 {
3408 if (buf == NULL)
3409 /* The buffer was deleted. We assume it was written
3410 * (can't retry anyway). */
3411 return OK;
3412 if (overwriting)
3413 {
3414 /* Assume the buffer was written, update the timestamp. */
3415 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00003416 if (append)
3417 buf->b_flags &= ~BF_NEW;
3418 else
3419 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003420 }
Bram Moolenaar292ad192005-12-11 21:29:51 +00003421 if (reset_changed && buf->b_changed && !append
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003422 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003423 /* Buffer still changed, the autocommands didn't work
3424 * properly. */
3425 return FAIL;
3426 return OK;
3427 }
3428#ifdef FEAT_EVAL
3429 if (!aborting())
3430#endif
3431 EMSG(_("E203: Autocommands deleted or unloaded buffer to be written"));
3432 return FAIL;
3433 }
3434
3435 /*
3436 * The autocommands may have changed the number of lines in the file.
3437 * When writing the whole file, adjust the end.
3438 * When writing part of the file, assume that the autocommands only
3439 * changed the number of lines that are to be written (tricky!).
3440 */
3441 if (buf->b_ml.ml_line_count != old_line_count)
3442 {
3443 if (whole) /* write all */
3444 end = buf->b_ml.ml_line_count;
3445 else if (buf->b_ml.ml_line_count > old_line_count) /* more lines */
3446 end += buf->b_ml.ml_line_count - old_line_count;
3447 else /* less lines */
3448 {
3449 end -= old_line_count - buf->b_ml.ml_line_count;
3450 if (end < start)
3451 {
3452 --no_wait_return;
3453 msg_scroll = msg_save;
3454 EMSG(_("E204: Autocommand changed number of lines in unexpected way"));
3455 return FAIL;
3456 }
3457 }
3458 }
3459
3460 /*
3461 * The autocommands may have changed the name of the buffer, which may
3462 * be kept in fname, ffname and sfname.
3463 */
3464 if (buf_ffname)
3465 ffname = buf->b_ffname;
3466 if (buf_sfname)
3467 sfname = buf->b_sfname;
3468 if (buf_fname_f)
3469 fname = buf->b_ffname;
3470 if (buf_fname_s)
3471 fname = buf->b_sfname;
3472 }
3473#endif
3474
3475#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003476 if (netbeans_active() && isNetbeansBuffer(buf))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003477 {
3478 if (whole)
3479 {
3480 /*
3481 * b_changed can be 0 after an undo, but we still need to write
3482 * the buffer to NetBeans.
3483 */
3484 if (buf->b_changed || isNetbeansModified(buf))
3485 {
Bram Moolenaar009b2592004-10-24 19:18:58 +00003486 --no_wait_return; /* may wait for return now */
3487 msg_scroll = msg_save;
3488 netbeans_save_buffer(buf); /* no error checking... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003489 return retval;
3490 }
3491 else
3492 {
3493 errnum = (char_u *)"E656: ";
Bram Moolenaared0e7452008-06-27 19:17:34 +00003494 errmsg = (char_u *)_("NetBeans disallows writes of unmodified buffers");
Bram Moolenaar071d4272004-06-13 20:20:40 +00003495 buffer = NULL;
3496 goto fail;
3497 }
3498 }
3499 else
3500 {
3501 errnum = (char_u *)"E657: ";
3502 errmsg = (char_u *)_("Partial writes disallowed for NetBeans buffers");
3503 buffer = NULL;
3504 goto fail;
3505 }
3506 }
3507#endif
3508
3509 if (shortmess(SHM_OVER) && !exiting)
3510 msg_scroll = FALSE; /* overwrite previous file message */
3511 else
3512 msg_scroll = TRUE; /* don't overwrite previous file message */
3513 if (!filtering)
3514 filemess(buf,
3515#ifndef UNIX
3516 sfname,
3517#else
3518 fname,
3519#endif
3520 (char_u *)"", 0); /* show that we are busy */
3521 msg_scroll = FALSE; /* always overwrite the file message now */
3522
3523 buffer = alloc(BUFSIZE);
3524 if (buffer == NULL) /* can't allocate big buffer, use small
3525 * one (to be able to write when out of
3526 * memory) */
3527 {
3528 buffer = smallbuf;
3529 bufsize = SMBUFSIZE;
3530 }
3531 else
3532 bufsize = BUFSIZE;
3533
3534 /*
3535 * Get information about original file (if there is one).
3536 */
3537#if defined(UNIX) && !defined(ARCHIE)
Bram Moolenaar6f192452007-11-08 19:49:02 +00003538 st_old.st_dev = 0;
3539 st_old.st_ino = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003540 perm = -1;
3541 if (mch_stat((char *)fname, &st_old) < 0)
3542 newfile = TRUE;
3543 else
3544 {
3545 perm = st_old.st_mode;
3546 if (!S_ISREG(st_old.st_mode)) /* not a file */
3547 {
3548 if (S_ISDIR(st_old.st_mode))
3549 {
3550 errnum = (char_u *)"E502: ";
3551 errmsg = (char_u *)_("is a directory");
3552 goto fail;
3553 }
3554 if (mch_nodetype(fname) != NODE_WRITABLE)
3555 {
3556 errnum = (char_u *)"E503: ";
3557 errmsg = (char_u *)_("is not a file or writable device");
3558 goto fail;
3559 }
3560 /* It's a device of some kind (or a fifo) which we can write to
3561 * but for which we can't make a backup. */
3562 device = TRUE;
3563 newfile = TRUE;
3564 perm = -1;
3565 }
3566 }
3567#else /* !UNIX */
3568 /*
3569 * Check for a writable device name.
3570 */
3571 c = mch_nodetype(fname);
3572 if (c == NODE_OTHER)
3573 {
3574 errnum = (char_u *)"E503: ";
3575 errmsg = (char_u *)_("is not a file or writable device");
3576 goto fail;
3577 }
3578 if (c == NODE_WRITABLE)
3579 {
Bram Moolenaar043545e2006-10-10 16:44:07 +00003580# if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3581 /* MS-Windows allows opening a device, but we will probably get stuck
3582 * trying to write to it. */
3583 if (!p_odev)
3584 {
3585 errnum = (char_u *)"E796: ";
3586 errmsg = (char_u *)_("writing to device disabled with 'opendevice' option");
3587 goto fail;
3588 }
3589# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003590 device = TRUE;
3591 newfile = TRUE;
3592 perm = -1;
3593 }
3594 else
3595 {
3596 perm = mch_getperm(fname);
3597 if (perm < 0)
3598 newfile = TRUE;
3599 else if (mch_isdir(fname))
3600 {
3601 errnum = (char_u *)"E502: ";
3602 errmsg = (char_u *)_("is a directory");
3603 goto fail;
3604 }
3605 if (overwriting)
3606 (void)mch_stat((char *)fname, &st_old);
3607 }
3608#endif /* !UNIX */
3609
3610 if (!device && !newfile)
3611 {
3612 /*
3613 * Check if the file is really writable (when renaming the file to
3614 * make a backup we won't discover it later).
3615 */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003616 file_readonly = check_file_readonly(fname, (int)perm);
3617
Bram Moolenaar071d4272004-06-13 20:20:40 +00003618 if (!forceit && file_readonly)
3619 {
3620 if (vim_strchr(p_cpo, CPO_FWRITE) != NULL)
3621 {
3622 errnum = (char_u *)"E504: ";
3623 errmsg = (char_u *)_(err_readonly);
3624 }
3625 else
3626 {
3627 errnum = (char_u *)"E505: ";
3628 errmsg = (char_u *)_("is read-only (add ! to override)");
3629 }
3630 goto fail;
3631 }
3632
3633 /*
3634 * Check if the timestamp hasn't changed since reading the file.
3635 */
3636 if (overwriting)
3637 {
3638 retval = check_mtime(buf, &st_old);
3639 if (retval == FAIL)
3640 goto fail;
3641 }
3642 }
3643
3644#ifdef HAVE_ACL
3645 /*
3646 * For systems that support ACL: get the ACL from the original file.
3647 */
3648 if (!newfile)
3649 acl = mch_get_acl(fname);
3650#endif
3651
3652 /*
3653 * If 'backupskip' is not empty, don't make a backup for some files.
3654 */
3655 dobackup = (p_wb || p_bk || *p_pm != NUL);
3656#ifdef FEAT_WILDIGN
3657 if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname))
3658 dobackup = FALSE;
3659#endif
3660
3661 /*
3662 * Save the value of got_int and reset it. We don't want a previous
3663 * interruption cancel writing, only hitting CTRL-C while writing should
3664 * abort it.
3665 */
3666 prev_got_int = got_int;
3667 got_int = FALSE;
3668
3669 /* Mark the buffer as 'being saved' to prevent changed buffer warnings */
3670 buf->b_saving = TRUE;
3671
3672 /*
3673 * If we are not appending or filtering, the file exists, and the
3674 * 'writebackup', 'backup' or 'patchmode' option is set, need a backup.
3675 * When 'patchmode' is set also make a backup when appending.
3676 *
3677 * Do not make any backup, if 'writebackup' and 'backup' are both switched
3678 * off. This helps when editing large files on almost-full disks.
3679 */
3680 if (!(append && *p_pm == NUL) && !filtering && perm >= 0 && dobackup)
3681 {
3682#if defined(UNIX) || defined(WIN32)
3683 struct stat st;
3684#endif
3685
3686 if ((bkc_flags & BKC_YES) || append) /* "yes" */
3687 backup_copy = TRUE;
3688#if defined(UNIX) || defined(WIN32)
3689 else if ((bkc_flags & BKC_AUTO)) /* "auto" */
3690 {
3691 int i;
3692
3693# ifdef UNIX
3694 /*
3695 * Don't rename the file when:
3696 * - it's a hard link
3697 * - it's a symbolic link
3698 * - we don't have write permission in the directory
3699 * - we can't set the owner/group of the new file
3700 */
3701 if (st_old.st_nlink > 1
3702 || mch_lstat((char *)fname, &st) < 0
3703 || st.st_dev != st_old.st_dev
Bram Moolenaara5792f52005-11-23 21:25:05 +00003704 || st.st_ino != st_old.st_ino
3705# ifndef HAVE_FCHOWN
3706 || st.st_uid != st_old.st_uid
3707 || st.st_gid != st_old.st_gid
3708# endif
3709 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003710 backup_copy = TRUE;
3711 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003712# else
3713# ifdef WIN32
3714 /* On NTFS file systems hard links are possible. */
3715 if (mch_is_linked(fname))
3716 backup_copy = TRUE;
3717 else
3718# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003719# endif
3720 {
3721 /*
3722 * Check if we can create a file and set the owner/group to
3723 * the ones from the original file.
3724 * First find a file name that doesn't exist yet (use some
3725 * arbitrary numbers).
3726 */
3727 STRCPY(IObuff, fname);
3728 for (i = 4913; ; i += 123)
3729 {
3730 sprintf((char *)gettail(IObuff), "%d", i);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003731 if (mch_lstat((char *)IObuff, &st) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003732 break;
3733 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00003734 fd = mch_open((char *)IObuff,
3735 O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003736 if (fd < 0) /* can't write in directory */
3737 backup_copy = TRUE;
3738 else
3739 {
3740# ifdef UNIX
Bram Moolenaara5792f52005-11-23 21:25:05 +00003741# ifdef HAVE_FCHOWN
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00003742 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003743# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003744 if (mch_stat((char *)IObuff, &st) < 0
3745 || st.st_uid != st_old.st_uid
3746 || st.st_gid != st_old.st_gid
Bram Moolenaar78a15312009-05-15 19:33:18 +00003747 || (long)st.st_mode != perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003748 backup_copy = TRUE;
3749# endif
Bram Moolenaar98358622005-11-28 22:58:23 +00003750 /* Close the file before removing it, on MS-Windows we
3751 * can't delete an open file. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003752 close(fd);
Bram Moolenaar98358622005-11-28 22:58:23 +00003753 mch_remove(IObuff);
Bram Moolenaar3479c5d2010-08-08 18:46:06 +02003754# ifdef MSWIN
3755 /* MS-Windows may trigger a virus scanner to open the
3756 * file, we can't delete it then. Keep trying for half a
3757 * second. */
3758 {
3759 int try;
3760
3761 for (try = 0; try < 10; ++try)
3762 {
3763 if (mch_lstat((char *)IObuff, &st) < 0)
3764 break;
3765 ui_delay(50L, TRUE); /* wait 50 msec */
3766 mch_remove(IObuff);
3767 }
3768 }
3769# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003770 }
3771 }
3772 }
3773
3774# ifdef UNIX
3775 /*
3776 * Break symlinks and/or hardlinks if we've been asked to.
3777 */
3778 if ((bkc_flags & BKC_BREAKSYMLINK) || (bkc_flags & BKC_BREAKHARDLINK))
3779 {
3780 int lstat_res;
3781
3782 lstat_res = mch_lstat((char *)fname, &st);
3783
3784 /* Symlinks. */
3785 if ((bkc_flags & BKC_BREAKSYMLINK)
3786 && lstat_res == 0
3787 && st.st_ino != st_old.st_ino)
3788 backup_copy = FALSE;
3789
3790 /* Hardlinks. */
3791 if ((bkc_flags & BKC_BREAKHARDLINK)
3792 && st_old.st_nlink > 1
3793 && (lstat_res != 0 || st.st_ino == st_old.st_ino))
3794 backup_copy = FALSE;
3795 }
3796#endif
3797
3798#endif
3799
3800 /* make sure we have a valid backup extension to use */
3801 if (*p_bex == NUL)
3802 {
3803#ifdef RISCOS
3804 backup_ext = (char_u *)"/bak";
3805#else
3806 backup_ext = (char_u *)".bak";
3807#endif
3808 }
3809 else
3810 backup_ext = p_bex;
3811
3812 if (backup_copy
3813 && (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) >= 0)
3814 {
3815 int bfd;
3816 char_u *copybuf, *wp;
3817 int some_error = FALSE;
3818 struct stat st_new;
3819 char_u *dirp;
3820 char_u *rootname;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003821#if defined(UNIX) && !defined(SHORT_FNAME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003822 int did_set_shortname;
3823#endif
3824
3825 copybuf = alloc(BUFSIZE + 1);
3826 if (copybuf == NULL)
3827 {
3828 some_error = TRUE; /* out of memory */
3829 goto nobackup;
3830 }
3831
3832 /*
3833 * Try to make the backup in each directory in the 'bdir' option.
3834 *
3835 * Unix semantics has it, that we may have a writable file,
3836 * that cannot be recreated with a simple open(..., O_CREAT, ) e.g:
3837 * - the directory is not writable,
3838 * - the file may be a symbolic link,
3839 * - the file may belong to another user/group, etc.
3840 *
3841 * For these reasons, the existing writable file must be truncated
3842 * and reused. Creation of a backup COPY will be attempted.
3843 */
3844 dirp = p_bdir;
3845 while (*dirp)
3846 {
3847#ifdef UNIX
3848 st_new.st_ino = 0;
3849 st_new.st_dev = 0;
3850 st_new.st_gid = 0;
3851#endif
3852
3853 /*
3854 * Isolate one directory name, using an entry in 'bdir'.
3855 */
3856 (void)copy_option_part(&dirp, copybuf, BUFSIZE, ",");
3857 rootname = get_file_in_dir(fname, copybuf);
3858 if (rootname == NULL)
3859 {
3860 some_error = TRUE; /* out of memory */
3861 goto nobackup;
3862 }
3863
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003864#if defined(UNIX) && !defined(SHORT_FNAME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003865 did_set_shortname = FALSE;
3866#endif
3867
3868 /*
3869 * May try twice if 'shortname' not set.
3870 */
3871 for (;;)
3872 {
3873 /*
3874 * Make backup file name.
3875 */
3876 backup = buf_modname(
3877#ifdef SHORT_FNAME
3878 TRUE,
3879#else
3880 (buf->b_p_sn || buf->b_shortname),
3881#endif
3882 rootname, backup_ext, FALSE);
3883 if (backup == NULL)
3884 {
3885 vim_free(rootname);
3886 some_error = TRUE; /* out of memory */
3887 goto nobackup;
3888 }
3889
3890 /*
3891 * Check if backup file already exists.
3892 */
3893 if (mch_stat((char *)backup, &st_new) >= 0)
3894 {
3895#ifdef UNIX
3896 /*
3897 * Check if backup file is same as original file.
3898 * May happen when modname() gave the same file back.
3899 * E.g. silly link, or file name-length reached.
3900 * If we don't check here, we either ruin the file
3901 * when copying or erase it after writing. jw.
3902 */
3903 if (st_new.st_dev == st_old.st_dev
3904 && st_new.st_ino == st_old.st_ino)
3905 {
3906 vim_free(backup);
3907 backup = NULL; /* no backup file to delete */
3908# ifndef SHORT_FNAME
3909 /*
3910 * may try again with 'shortname' set
3911 */
3912 if (!(buf->b_shortname || buf->b_p_sn))
3913 {
3914 buf->b_shortname = TRUE;
3915 did_set_shortname = TRUE;
3916 continue;
3917 }
3918 /* setting shortname didn't help */
3919 if (did_set_shortname)
3920 buf->b_shortname = FALSE;
3921# endif
3922 break;
3923 }
3924#endif
3925
3926 /*
3927 * If we are not going to keep the backup file, don't
3928 * delete an existing one, try to use another name.
3929 * Change one character, just before the extension.
3930 */
3931 if (!p_bk)
3932 {
3933 wp = backup + STRLEN(backup) - 1
3934 - STRLEN(backup_ext);
3935 if (wp < backup) /* empty file name ??? */
3936 wp = backup;
3937 *wp = 'z';
3938 while (*wp > 'a'
3939 && mch_stat((char *)backup, &st_new) >= 0)
3940 --*wp;
3941 /* They all exist??? Must be something wrong. */
3942 if (*wp == 'a')
3943 {
3944 vim_free(backup);
3945 backup = NULL;
3946 }
3947 }
3948 }
3949 break;
3950 }
3951 vim_free(rootname);
3952
3953 /*
3954 * Try to create the backup file
3955 */
3956 if (backup != NULL)
3957 {
3958 /* remove old backup, if present */
3959 mch_remove(backup);
3960 /* Open with O_EXCL to avoid the file being created while
3961 * we were sleeping (symlink hacker attack?) */
3962 bfd = mch_open((char *)backup,
Bram Moolenaara5792f52005-11-23 21:25:05 +00003963 O_WRONLY|O_CREAT|O_EXTRA|O_EXCL|O_NOFOLLOW,
3964 perm & 0777);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003965 if (bfd < 0)
3966 {
3967 vim_free(backup);
3968 backup = NULL;
3969 }
3970 else
3971 {
3972 /* set file protection same as original file, but
3973 * strip s-bit */
3974 (void)mch_setperm(backup, perm & 0777);
3975
3976#ifdef UNIX
3977 /*
3978 * Try to set the group of the backup same as the
3979 * original file. If this fails, set the protection
3980 * bits for the group same as the protection bits for
3981 * others.
3982 */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003983 if (st_new.st_gid != st_old.st_gid
Bram Moolenaar071d4272004-06-13 20:20:40 +00003984# ifdef HAVE_FCHOWN /* sequent-ptx lacks fchown() */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003985 && fchown(bfd, (uid_t)-1, st_old.st_gid) != 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00003986# endif
3987 )
3988 mch_setperm(backup,
3989 (perm & 0707) | ((perm & 07) << 3));
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00003990# ifdef HAVE_SELINUX
3991 mch_copy_sec(fname, backup);
3992# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003993#endif
3994
3995 /*
3996 * copy the file.
3997 */
3998 write_info.bw_fd = bfd;
3999 write_info.bw_buf = copybuf;
4000#ifdef HAS_BW_FLAGS
4001 write_info.bw_flags = FIO_NOCONVERT;
4002#endif
4003 while ((write_info.bw_len = vim_read(fd, copybuf,
4004 BUFSIZE)) > 0)
4005 {
4006 if (buf_write_bytes(&write_info) == FAIL)
4007 {
4008 errmsg = (char_u *)_("E506: Can't write to backup file (add ! to override)");
4009 break;
4010 }
4011 ui_breakcheck();
4012 if (got_int)
4013 {
4014 errmsg = (char_u *)_(e_interr);
4015 break;
4016 }
4017 }
4018
4019 if (close(bfd) < 0 && errmsg == NULL)
4020 errmsg = (char_u *)_("E507: Close error for backup file (add ! to override)");
4021 if (write_info.bw_len < 0)
4022 errmsg = (char_u *)_("E508: Can't read file for backup (add ! to override)");
4023#ifdef UNIX
4024 set_file_time(backup, st_old.st_atime, st_old.st_mtime);
4025#endif
4026#ifdef HAVE_ACL
4027 mch_set_acl(backup, acl);
4028#endif
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004029#ifdef HAVE_SELINUX
4030 mch_copy_sec(fname, backup);
4031#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004032 break;
4033 }
4034 }
4035 }
4036 nobackup:
4037 close(fd); /* ignore errors for closing read file */
4038 vim_free(copybuf);
4039
4040 if (backup == NULL && errmsg == NULL)
4041 errmsg = (char_u *)_("E509: Cannot create backup file (add ! to override)");
4042 /* ignore errors when forceit is TRUE */
4043 if ((some_error || errmsg != NULL) && !forceit)
4044 {
4045 retval = FAIL;
4046 goto fail;
4047 }
4048 errmsg = NULL;
4049 }
4050 else
4051 {
4052 char_u *dirp;
4053 char_u *p;
4054 char_u *rootname;
4055
4056 /*
4057 * Make a backup by renaming the original file.
4058 */
4059 /*
4060 * If 'cpoptions' includes the "W" flag, we don't want to
4061 * overwrite a read-only file. But rename may be possible
4062 * anyway, thus we need an extra check here.
4063 */
4064 if (file_readonly && vim_strchr(p_cpo, CPO_FWRITE) != NULL)
4065 {
4066 errnum = (char_u *)"E504: ";
4067 errmsg = (char_u *)_(err_readonly);
4068 goto fail;
4069 }
4070
4071 /*
4072 *
4073 * Form the backup file name - change path/fo.o.h to
4074 * path/fo.o.h.bak Try all directories in 'backupdir', first one
4075 * that works is used.
4076 */
4077 dirp = p_bdir;
4078 while (*dirp)
4079 {
4080 /*
4081 * Isolate one directory name and make the backup file name.
4082 */
4083 (void)copy_option_part(&dirp, IObuff, IOSIZE, ",");
4084 rootname = get_file_in_dir(fname, IObuff);
4085 if (rootname == NULL)
4086 backup = NULL;
4087 else
4088 {
4089 backup = buf_modname(
4090#ifdef SHORT_FNAME
4091 TRUE,
4092#else
4093 (buf->b_p_sn || buf->b_shortname),
4094#endif
4095 rootname, backup_ext, FALSE);
4096 vim_free(rootname);
4097 }
4098
4099 if (backup != NULL)
4100 {
4101 /*
4102 * If we are not going to keep the backup file, don't
4103 * delete an existing one, try to use another name.
4104 * Change one character, just before the extension.
4105 */
4106 if (!p_bk && mch_getperm(backup) >= 0)
4107 {
4108 p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext);
4109 if (p < backup) /* empty file name ??? */
4110 p = backup;
4111 *p = 'z';
4112 while (*p > 'a' && mch_getperm(backup) >= 0)
4113 --*p;
4114 /* They all exist??? Must be something wrong! */
4115 if (*p == 'a')
4116 {
4117 vim_free(backup);
4118 backup = NULL;
4119 }
4120 }
4121 }
4122 if (backup != NULL)
4123 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004124 /*
Bram Moolenaarbfd8fc02005-09-20 23:22:24 +00004125 * Delete any existing backup and move the current version
4126 * to the backup. For safety, we don't remove the backup
4127 * until the write has finished successfully. And if the
4128 * 'backup' option is set, leave it around.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004129 */
4130 /*
4131 * If the renaming of the original file to the backup file
4132 * works, quit here.
4133 */
4134 if (vim_rename(fname, backup) == 0)
4135 break;
4136
4137 vim_free(backup); /* don't do the rename below */
4138 backup = NULL;
4139 }
4140 }
4141 if (backup == NULL && !forceit)
4142 {
4143 errmsg = (char_u *)_("E510: Can't make backup file (add ! to override)");
4144 goto fail;
4145 }
4146 }
4147 }
4148
4149#if defined(UNIX) && !defined(ARCHIE)
4150 /* When using ":w!" and the file was read-only: make it writable */
4151 if (forceit && perm >= 0 && !(perm & 0200) && st_old.st_uid == getuid()
4152 && vim_strchr(p_cpo, CPO_FWRITE) == NULL)
4153 {
4154 perm |= 0200;
4155 (void)mch_setperm(fname, perm);
4156 made_writable = TRUE;
4157 }
4158#endif
4159
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004160 /* When using ":w!" and writing to the current file, 'readonly' makes no
Bram Moolenaar4399ef42005-02-12 14:29:27 +00004161 * sense, reset it, unless 'Z' appears in 'cpoptions'. */
4162 if (forceit && overwriting && vim_strchr(p_cpo, CPO_KEEPRO) == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004163 {
4164 buf->b_p_ro = FALSE;
4165#ifdef FEAT_TITLE
4166 need_maketitle = TRUE; /* set window title later */
4167#endif
4168#ifdef FEAT_WINDOWS
4169 status_redraw_all(); /* redraw status lines later */
4170#endif
4171 }
4172
4173 if (end > buf->b_ml.ml_line_count)
4174 end = buf->b_ml.ml_line_count;
4175 if (buf->b_ml.ml_flags & ML_EMPTY)
4176 start = end + 1;
4177
4178 /*
4179 * If the original file is being overwritten, there is a small chance that
4180 * we crash in the middle of writing. Therefore the file is preserved now.
4181 * This makes all block numbers positive so that recovery does not need
4182 * the original file.
4183 * Don't do this if there is a backup file and we are exiting.
4184 */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004185 if (reset_changed && !newfile && overwriting
Bram Moolenaar071d4272004-06-13 20:20:40 +00004186 && !(exiting && backup != NULL))
4187 {
4188 ml_preserve(buf, FALSE);
4189 if (got_int)
4190 {
4191 errmsg = (char_u *)_(e_interr);
4192 goto restore_backup;
4193 }
4194 }
4195
4196#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
4197 /*
4198 * Before risking to lose the original file verify if there's
4199 * a resource fork to preserve, and if cannot be done warn
4200 * the users. This happens when overwriting without backups.
4201 */
4202 if (backup == NULL && overwriting && !append)
4203 if (mch_has_resource_fork(fname))
4204 {
4205 errmsg = (char_u *)_("E460: The resource fork would be lost (add ! to override)");
4206 goto restore_backup;
4207 }
4208#endif
4209
4210#ifdef VMS
4211 vms_remove_version(fname); /* remove version */
4212#endif
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00004213 /* Default: write the file directly. May write to a temp file for
Bram Moolenaar071d4272004-06-13 20:20:40 +00004214 * multi-byte conversion. */
4215 wfname = fname;
4216
4217#ifdef FEAT_MBYTE
4218 /* Check for forced 'fileencoding' from "++opt=val" argument. */
4219 if (eap != NULL && eap->force_enc != 0)
4220 {
4221 fenc = eap->cmd + eap->force_enc;
4222 fenc = enc_canonize(fenc);
4223 fenc_tofree = fenc;
4224 }
4225 else
4226 fenc = buf->b_p_fenc;
4227
4228 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004229 * Check if the file needs to be converted.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004230 */
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004231 converted = need_conversion(fenc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004232
4233 /*
4234 * Check if UTF-8 to UCS-2/4 or Latin1 conversion needs to be done. Or
4235 * Latin1 to Unicode conversion. This is handled in buf_write_bytes().
4236 * Prepare the flags for it and allocate bw_conv_buf when needed.
4237 */
4238 if (converted && (enc_utf8 || STRCMP(p_enc, "latin1") == 0))
4239 {
4240 wb_flags = get_fio_flags(fenc);
4241 if (wb_flags & (FIO_UCS2 | FIO_UCS4 | FIO_UTF16 | FIO_UTF8))
4242 {
4243 /* Need to allocate a buffer to translate into. */
4244 if (wb_flags & (FIO_UCS2 | FIO_UTF16 | FIO_UTF8))
4245 write_info.bw_conv_buflen = bufsize * 2;
4246 else /* FIO_UCS4 */
4247 write_info.bw_conv_buflen = bufsize * 4;
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 }
4254
4255# ifdef WIN3264
4256 if (converted && wb_flags == 0 && (wb_flags = get_win_fio_flags(fenc)) != 0)
4257 {
4258 /* Convert UTF-8 -> UCS-2 and UCS-2 -> DBCS. Worst-case * 4: */
4259 write_info.bw_conv_buflen = bufsize * 4;
4260 write_info.bw_conv_buf
4261 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4262 if (write_info.bw_conv_buf == NULL)
4263 end = 0;
4264 }
4265# endif
4266
4267# ifdef MACOS_X
4268 if (converted && wb_flags == 0 && (wb_flags = get_mac_fio_flags(fenc)) != 0)
4269 {
4270 write_info.bw_conv_buflen = bufsize * 3;
4271 write_info.bw_conv_buf
4272 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4273 if (write_info.bw_conv_buf == NULL)
4274 end = 0;
4275 }
4276# endif
4277
4278# if defined(FEAT_EVAL) || defined(USE_ICONV)
4279 if (converted && wb_flags == 0)
4280 {
4281# ifdef USE_ICONV
4282 /*
4283 * Use iconv() conversion when conversion is needed and it's not done
4284 * internally.
4285 */
4286 write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc,
4287 enc_utf8 ? (char_u *)"utf-8" : p_enc);
4288 if (write_info.bw_iconv_fd != (iconv_t)-1)
4289 {
4290 /* We're going to use iconv(), allocate a buffer to convert in. */
4291 write_info.bw_conv_buflen = bufsize * ICONV_MULT;
4292 write_info.bw_conv_buf
4293 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4294 if (write_info.bw_conv_buf == NULL)
4295 end = 0;
4296 write_info.bw_first = TRUE;
4297 }
4298# ifdef FEAT_EVAL
4299 else
4300# endif
4301# endif
4302
4303# ifdef FEAT_EVAL
4304 /*
4305 * When the file needs to be converted with 'charconvert' after
4306 * writing, write to a temp file instead and let the conversion
4307 * overwrite the original file.
4308 */
4309 if (*p_ccv != NUL)
4310 {
4311 wfname = vim_tempname('w');
4312 if (wfname == NULL) /* Can't write without a tempfile! */
4313 {
4314 errmsg = (char_u *)_("E214: Can't find temp file for writing");
4315 goto restore_backup;
4316 }
4317 }
4318# endif
4319 }
4320# endif
4321 if (converted && wb_flags == 0
4322# ifdef USE_ICONV
4323 && write_info.bw_iconv_fd == (iconv_t)-1
4324# endif
4325# ifdef FEAT_EVAL
4326 && wfname == fname
4327# endif
4328 )
4329 {
4330 if (!forceit)
4331 {
4332 errmsg = (char_u *)_("E213: Cannot convert (add ! to write without conversion)");
4333 goto restore_backup;
4334 }
4335 notconverted = TRUE;
4336 }
4337#endif
4338
4339 /*
4340 * Open the file "wfname" for writing.
4341 * We may try to open the file twice: If we can't write to the
4342 * file and forceit is TRUE we delete the existing file and try to create
4343 * a new one. If this still fails we may have lost the original file!
4344 * (this may happen when the user reached his quotum for number of files).
4345 * Appending will fail if the file does not exist and forceit is FALSE.
4346 */
4347 while ((fd = mch_open((char *)wfname, O_WRONLY | O_EXTRA | (append
4348 ? (forceit ? (O_APPEND | O_CREAT) : O_APPEND)
4349 : (O_CREAT | O_TRUNC))
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00004350 , perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004351 {
4352 /*
4353 * A forced write will try to create a new file if the old one is
4354 * still readonly. This may also happen when the directory is
4355 * read-only. In that case the mch_remove() will fail.
4356 */
4357 if (errmsg == NULL)
4358 {
4359#ifdef UNIX
4360 struct stat st;
4361
4362 /* Don't delete the file when it's a hard or symbolic link. */
4363 if ((!newfile && st_old.st_nlink > 1)
4364 || (mch_lstat((char *)fname, &st) == 0
4365 && (st.st_dev != st_old.st_dev
4366 || st.st_ino != st_old.st_ino)))
4367 errmsg = (char_u *)_("E166: Can't open linked file for writing");
4368 else
4369#endif
4370 {
4371 errmsg = (char_u *)_("E212: Can't open file for writing");
4372 if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL
4373 && perm >= 0)
4374 {
4375#ifdef UNIX
4376 /* we write to the file, thus it should be marked
4377 writable after all */
4378 if (!(perm & 0200))
4379 made_writable = TRUE;
4380 perm |= 0200;
4381 if (st_old.st_uid != getuid() || st_old.st_gid != getgid())
4382 perm &= 0777;
4383#endif
4384 if (!append) /* don't remove when appending */
4385 mch_remove(wfname);
4386 continue;
4387 }
4388 }
4389 }
4390
4391restore_backup:
4392 {
4393 struct stat st;
4394
4395 /*
4396 * If we failed to open the file, we don't need a backup. Throw it
4397 * away. If we moved or removed the original file try to put the
4398 * backup in its place.
4399 */
4400 if (backup != NULL && wfname == fname)
4401 {
4402 if (backup_copy)
4403 {
4404 /*
4405 * There is a small chance that we removed the original,
4406 * try to move the copy in its place.
4407 * This may not work if the vim_rename() fails.
4408 * In that case we leave the copy around.
4409 */
4410 /* If file does not exist, put the copy in its place */
4411 if (mch_stat((char *)fname, &st) < 0)
4412 vim_rename(backup, fname);
4413 /* if original file does exist throw away the copy */
4414 if (mch_stat((char *)fname, &st) >= 0)
4415 mch_remove(backup);
4416 }
4417 else
4418 {
4419 /* try to put the original file back */
4420 vim_rename(backup, fname);
4421 }
4422 }
4423
4424 /* if original file no longer exists give an extra warning */
4425 if (!newfile && mch_stat((char *)fname, &st) < 0)
4426 end = 0;
4427 }
4428
4429#ifdef FEAT_MBYTE
4430 if (wfname != fname)
4431 vim_free(wfname);
4432#endif
4433 goto fail;
4434 }
4435 errmsg = NULL;
4436
4437#if defined(MACOS_CLASSIC) || defined(WIN3264)
4438 /* TODO: Is it need for MACOS_X? (Dany) */
4439 /*
4440 * On macintosh copy the original files attributes (i.e. the backup)
Bram Moolenaar7263a772007-05-10 17:35:54 +00004441 * This is done in order to preserve the resource fork and the
4442 * Finder attribute (label, comments, custom icons, file creator)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004443 */
4444 if (backup != NULL && overwriting && !append)
4445 {
4446 if (backup_copy)
4447 (void)mch_copy_file_attribute(wfname, backup);
4448 else
4449 (void)mch_copy_file_attribute(backup, wfname);
4450 }
4451
4452 if (!overwriting && !append)
4453 {
4454 if (buf->b_ffname != NULL)
4455 (void)mch_copy_file_attribute(buf->b_ffname, wfname);
Bram Moolenaar7263a772007-05-10 17:35:54 +00004456 /* Should copy resource fork */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004457 }
4458#endif
4459
4460 write_info.bw_fd = fd;
4461
4462#ifdef FEAT_CRYPT
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004463 if (*buf->b_p_key != NUL && !filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004464 {
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02004465 char_u *header;
4466 int header_len;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004467
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02004468 header = prepare_crypt_write(buf, &header_len);
4469 if (header == NULL)
4470 end = 0;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004471 else
4472 {
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02004473 /* Write magic number, so that Vim knows that this file is
4474 * encrypted when reading it again. This also undergoes utf-8 to
4475 * ucs-2/4 conversion when needed. */
4476 write_info.bw_buf = header;
4477 write_info.bw_len = header_len;
4478 write_info.bw_flags = FIO_NOCONVERT;
4479 if (buf_write_bytes(&write_info) == FAIL)
4480 end = 0;
4481 wb_flags |= FIO_ENCRYPTED;
4482 vim_free(header);
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004483 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004484 }
4485#endif
4486
4487 write_info.bw_buf = buffer;
4488 nchars = 0;
4489
4490 /* use "++bin", "++nobin" or 'binary' */
4491 if (eap != NULL && eap->force_bin != 0)
4492 write_bin = (eap->force_bin == FORCE_BIN);
4493 else
4494 write_bin = buf->b_p_bin;
4495
4496#ifdef FEAT_MBYTE
4497 /*
4498 * The BOM is written just after the encryption magic number.
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004499 * Skip it when appending and the file already existed, the BOM only makes
4500 * sense at the start of the file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004501 */
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004502 if (buf->b_p_bomb && !write_bin && (!append || perm < 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004503 {
4504 write_info.bw_len = make_bom(buffer, fenc);
4505 if (write_info.bw_len > 0)
4506 {
4507 /* don't convert, do encryption */
4508 write_info.bw_flags = FIO_NOCONVERT | wb_flags;
4509 if (buf_write_bytes(&write_info) == FAIL)
4510 end = 0;
4511 else
4512 nchars += write_info.bw_len;
4513 }
4514 }
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004515 write_info.bw_start_lnum = start;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004516#endif
4517
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004518#ifdef FEAT_PERSISTENT_UNDO
4519 write_undo_file = (buf->b_p_udf && overwriting && !append
4520 && !filtering && reset_changed);
4521 if (write_undo_file)
4522 /* Prepare for computing the hash value of the text. */
4523 sha256_start(&sha_ctx);
4524#endif
4525
Bram Moolenaar071d4272004-06-13 20:20:40 +00004526 write_info.bw_len = bufsize;
4527#ifdef HAS_BW_FLAGS
4528 write_info.bw_flags = wb_flags;
4529#endif
4530 fileformat = get_fileformat_force(buf, eap);
4531 s = buffer;
4532 len = 0;
4533 for (lnum = start; lnum <= end; ++lnum)
4534 {
4535 /*
4536 * The next while loop is done once for each character written.
4537 * Keep it fast!
4538 */
4539 ptr = ml_get_buf(buf, lnum, FALSE) - 1;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004540#ifdef FEAT_PERSISTENT_UNDO
4541 if (write_undo_file)
Bram Moolenaar442b4222010-05-24 21:34:22 +02004542 sha256_update(&sha_ctx, ptr + 1, (UINT32_T)(STRLEN(ptr + 1) + 1));
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004543#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004544 while ((c = *++ptr) != NUL)
4545 {
4546 if (c == NL)
4547 *s = NUL; /* replace newlines with NULs */
4548 else if (c == CAR && fileformat == EOL_MAC)
4549 *s = NL; /* Mac: replace CRs with NLs */
4550 else
4551 *s = c;
4552 ++s;
4553 if (++len != bufsize)
4554 continue;
4555 if (buf_write_bytes(&write_info) == FAIL)
4556 {
4557 end = 0; /* write error: break loop */
4558 break;
4559 }
4560 nchars += bufsize;
4561 s = buffer;
4562 len = 0;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004563#ifdef FEAT_MBYTE
4564 write_info.bw_start_lnum = lnum;
4565#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004566 }
4567 /* write failed or last line has no EOL: stop here */
4568 if (end == 0
4569 || (lnum == end
4570 && write_bin
4571 && (lnum == write_no_eol_lnum
4572 || (lnum == buf->b_ml.ml_line_count && !buf->b_p_eol))))
4573 {
4574 ++lnum; /* written the line, count it */
4575 no_eol = TRUE;
4576 break;
4577 }
4578 if (fileformat == EOL_UNIX)
4579 *s++ = NL;
4580 else
4581 {
4582 *s++ = CAR; /* EOL_MAC or EOL_DOS: write CR */
4583 if (fileformat == EOL_DOS) /* write CR-NL */
4584 {
4585 if (++len == bufsize)
4586 {
4587 if (buf_write_bytes(&write_info) == FAIL)
4588 {
4589 end = 0; /* write error: break loop */
4590 break;
4591 }
4592 nchars += bufsize;
4593 s = buffer;
4594 len = 0;
4595 }
4596 *s++ = NL;
4597 }
4598 }
4599 if (++len == bufsize && end)
4600 {
4601 if (buf_write_bytes(&write_info) == FAIL)
4602 {
4603 end = 0; /* write error: break loop */
4604 break;
4605 }
4606 nchars += bufsize;
4607 s = buffer;
4608 len = 0;
4609
4610 ui_breakcheck();
4611 if (got_int)
4612 {
4613 end = 0; /* Interrupted, break loop */
4614 break;
4615 }
4616 }
4617#ifdef VMS
4618 /*
4619 * On VMS there is a problem: newlines get added when writing blocks
4620 * at a time. Fix it by writing a line at a time.
4621 * This is much slower!
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004622 * Explanation: VAX/DECC RTL insists that records in some RMS
4623 * structures end with a newline (carriage return) character, and if
4624 * they don't it adds one.
4625 * With other RMS structures it works perfect without this fix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004626 */
Bram Moolenaarb52e2602007-10-29 21:38:54 +00004627 if (buf->b_fab_rfm == FAB$C_VFC
4628 || ((buf->b_fab_rat & (FAB$M_FTN | FAB$M_CR)) != 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004629 {
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004630 int b2write;
4631
4632 buf->b_fab_mrs = (buf->b_fab_mrs == 0
4633 ? MIN(4096, bufsize)
4634 : MIN(buf->b_fab_mrs, bufsize));
4635
4636 b2write = len;
4637 while (b2write > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004638 {
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004639 write_info.bw_len = MIN(b2write, buf->b_fab_mrs);
4640 if (buf_write_bytes(&write_info) == FAIL)
4641 {
4642 end = 0;
4643 break;
4644 }
4645 b2write -= MIN(b2write, buf->b_fab_mrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004646 }
4647 write_info.bw_len = bufsize;
4648 nchars += len;
4649 s = buffer;
4650 len = 0;
4651 }
4652#endif
4653 }
4654 if (len > 0 && end > 0)
4655 {
4656 write_info.bw_len = len;
4657 if (buf_write_bytes(&write_info) == FAIL)
4658 end = 0; /* write error */
4659 nchars += len;
4660 }
4661
4662#if defined(UNIX) && defined(HAVE_FSYNC)
4663 /* On many journalling file systems there is a bug that causes both the
4664 * original and the backup file to be lost when halting the system right
4665 * after writing the file. That's because only the meta-data is
4666 * journalled. Syncing the file slows down the system, but assures it has
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004667 * been written to disk and we don't lose it.
4668 * For a device do try the fsync() but don't complain if it does not work
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00004669 * (could be a pipe).
4670 * If the 'fsync' option is FALSE, don't fsync(). Useful for laptops. */
4671 if (p_fs && fsync(fd) != 0 && !device)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004672 {
4673 errmsg = (char_u *)_("E667: Fsync failed");
4674 end = 0;
4675 }
4676#endif
4677
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004678#ifdef HAVE_SELINUX
4679 /* Probably need to set the security context. */
4680 if (!backup_copy)
4681 mch_copy_sec(backup, wfname);
4682#endif
4683
Bram Moolenaara5792f52005-11-23 21:25:05 +00004684#ifdef UNIX
4685 /* When creating a new file, set its owner/group to that of the original
4686 * file. Get the new device and inode number. */
4687 if (backup != NULL && !backup_copy)
4688 {
4689# ifdef HAVE_FCHOWN
4690 struct stat st;
4691
4692 /* don't change the owner when it's already OK, some systems remove
4693 * permission or ACL stuff */
4694 if (mch_stat((char *)wfname, &st) < 0
4695 || st.st_uid != st_old.st_uid
4696 || st.st_gid != st_old.st_gid)
4697 {
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004698 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004699 if (perm >= 0) /* set permission again, may have changed */
4700 (void)mch_setperm(wfname, perm);
4701 }
4702# endif
4703 buf_setino(buf);
4704 }
Bram Moolenaarf1726cc2009-05-13 18:48:16 +00004705 else if (!buf->b_dev_valid)
Bram Moolenaar8fa04452005-12-23 22:13:51 +00004706 /* Set the inode when creating a new file. */
4707 buf_setino(buf);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004708#endif
4709
Bram Moolenaar071d4272004-06-13 20:20:40 +00004710 if (close(fd) != 0)
4711 {
4712 errmsg = (char_u *)_("E512: Close failed");
4713 end = 0;
4714 }
4715
4716#ifdef UNIX
4717 if (made_writable)
4718 perm &= ~0200; /* reset 'w' bit for security reasons */
4719#endif
4720 if (perm >= 0) /* set perm. of new file same as old file */
4721 (void)mch_setperm(wfname, perm);
4722#ifdef RISCOS
4723 if (!append && !filtering)
4724 /* Set the filetype after writing the file. */
4725 mch_set_filetype(wfname, buf->b_p_oft);
4726#endif
4727#ifdef HAVE_ACL
4728 /* Probably need to set the ACL before changing the user (can't set the
4729 * ACL on a file the user doesn't own). */
4730 if (!backup_copy)
4731 mch_set_acl(wfname, acl);
4732#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004733#ifdef FEAT_CRYPT
4734 if (wb_flags & FIO_ENCRYPTED)
4735 crypt_pop_state();
4736#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004737
Bram Moolenaar071d4272004-06-13 20:20:40 +00004738
4739#if defined(FEAT_MBYTE) && defined(FEAT_EVAL)
4740 if (wfname != fname)
4741 {
4742 /*
4743 * The file was written to a temp file, now it needs to be converted
4744 * with 'charconvert' to (overwrite) the output file.
4745 */
4746 if (end != 0)
4747 {
4748 if (eval_charconvert(enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc,
4749 wfname, fname) == FAIL)
4750 {
4751 write_info.bw_conv_error = TRUE;
4752 end = 0;
4753 }
4754 }
4755 mch_remove(wfname);
4756 vim_free(wfname);
4757 }
4758#endif
4759
4760 if (end == 0)
4761 {
4762 if (errmsg == NULL)
4763 {
4764#ifdef FEAT_MBYTE
4765 if (write_info.bw_conv_error)
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004766 {
4767 if (write_info.bw_conv_error_lnum == 0)
4768 errmsg = (char_u *)_("E513: write error, conversion failed (make 'fenc' empty to override)");
4769 else
4770 {
4771 errmsg_allocated = TRUE;
4772 errmsg = alloc(300);
4773 vim_snprintf((char *)errmsg, 300, _("E513: write error, conversion failed in line %ld (make 'fenc' empty to override)"),
4774 (long)write_info.bw_conv_error_lnum);
4775 }
4776 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004777 else
4778#endif
4779 if (got_int)
4780 errmsg = (char_u *)_(e_interr);
4781 else
4782 errmsg = (char_u *)_("E514: write error (file system full?)");
4783 }
4784
4785 /*
4786 * If we have a backup file, try to put it in place of the new file,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004787 * because the new file is probably corrupt. This avoids losing the
Bram Moolenaar071d4272004-06-13 20:20:40 +00004788 * original file when trying to make a backup when writing the file a
4789 * second time.
4790 * When "backup_copy" is set we need to copy the backup over the new
4791 * file. Otherwise rename the backup file.
4792 * If this is OK, don't give the extra warning message.
4793 */
4794 if (backup != NULL)
4795 {
4796 if (backup_copy)
4797 {
4798 /* This may take a while, if we were interrupted let the user
4799 * know we got the message. */
4800 if (got_int)
4801 {
4802 MSG(_(e_interr));
4803 out_flush();
4804 }
4805 if ((fd = mch_open((char *)backup, O_RDONLY | O_EXTRA, 0)) >= 0)
4806 {
4807 if ((write_info.bw_fd = mch_open((char *)fname,
Bram Moolenaar9be038d2005-03-08 22:34:32 +00004808 O_WRONLY | O_CREAT | O_TRUNC | O_EXTRA,
4809 perm & 0777)) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004810 {
4811 /* copy the file. */
4812 write_info.bw_buf = smallbuf;
4813#ifdef HAS_BW_FLAGS
4814 write_info.bw_flags = FIO_NOCONVERT;
4815#endif
4816 while ((write_info.bw_len = vim_read(fd, smallbuf,
4817 SMBUFSIZE)) > 0)
4818 if (buf_write_bytes(&write_info) == FAIL)
4819 break;
4820
4821 if (close(write_info.bw_fd) >= 0
4822 && write_info.bw_len == 0)
4823 end = 1; /* success */
4824 }
4825 close(fd); /* ignore errors for closing read file */
4826 }
4827 }
4828 else
4829 {
4830 if (vim_rename(backup, fname) == 0)
4831 end = 1;
4832 }
4833 }
4834 goto fail;
4835 }
4836
4837 lnum -= start; /* compute number of written lines */
4838 --no_wait_return; /* may wait for return now */
4839
4840#if !(defined(UNIX) || defined(VMS))
4841 fname = sfname; /* use shortname now, for the messages */
4842#endif
4843 if (!filtering)
4844 {
4845 msg_add_fname(buf, fname); /* put fname in IObuff with quotes */
4846 c = FALSE;
4847#ifdef FEAT_MBYTE
4848 if (write_info.bw_conv_error)
4849 {
4850 STRCAT(IObuff, _(" CONVERSION ERROR"));
4851 c = TRUE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004852 if (write_info.bw_conv_error_lnum != 0)
Bram Moolenaara800b422010-06-27 01:15:55 +02004853 vim_snprintf_add((char *)IObuff, IOSIZE, _(" in line %ld;"),
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004854 (long)write_info.bw_conv_error_lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004855 }
4856 else if (notconverted)
4857 {
4858 STRCAT(IObuff, _("[NOT converted]"));
4859 c = TRUE;
4860 }
4861 else if (converted)
4862 {
4863 STRCAT(IObuff, _("[converted]"));
4864 c = TRUE;
4865 }
4866#endif
4867 if (device)
4868 {
4869 STRCAT(IObuff, _("[Device]"));
4870 c = TRUE;
4871 }
4872 else if (newfile)
4873 {
4874 STRCAT(IObuff, shortmess(SHM_NEW) ? _("[New]") : _("[New File]"));
4875 c = TRUE;
4876 }
4877 if (no_eol)
4878 {
4879 msg_add_eol();
4880 c = TRUE;
4881 }
4882 /* may add [unix/dos/mac] */
4883 if (msg_add_fileformat(fileformat))
4884 c = TRUE;
4885#ifdef FEAT_CRYPT
4886 if (wb_flags & FIO_ENCRYPTED)
4887 {
4888 STRCAT(IObuff, _("[crypted]"));
4889 c = TRUE;
4890 }
4891#endif
4892 msg_add_lines(c, (long)lnum, nchars); /* add line/char count */
4893 if (!shortmess(SHM_WRITE))
4894 {
4895 if (append)
4896 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended"));
4897 else
4898 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written"));
4899 }
4900
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00004901 set_keep_msg(msg_trunc_attr(IObuff, FALSE, 0), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004902 }
4903
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004904 /* When written everything correctly: reset 'modified'. Unless not
4905 * writing to the original file and '+' is not in 'cpoptions'. */
Bram Moolenaar292ad192005-12-11 21:29:51 +00004906 if (reset_changed && whole && !append
Bram Moolenaar071d4272004-06-13 20:20:40 +00004907#ifdef FEAT_MBYTE
4908 && !write_info.bw_conv_error
4909#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004910 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL)
4911 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004912 {
4913 unchanged(buf, TRUE);
4914 u_unchanged(buf);
Bram Moolenaar730cde92010-06-27 05:18:54 +02004915 u_update_save_nr(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004916 }
4917
4918 /*
4919 * If written to the current file, update the timestamp of the swap file
4920 * and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
4921 */
4922 if (overwriting)
4923 {
4924 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00004925 if (append)
4926 buf->b_flags &= ~BF_NEW;
4927 else
4928 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004929 }
4930
4931 /*
4932 * If we kept a backup until now, and we are in patch mode, then we make
4933 * the backup file our 'original' file.
4934 */
4935 if (*p_pm && dobackup)
4936 {
4937 char *org = (char *)buf_modname(
4938#ifdef SHORT_FNAME
4939 TRUE,
4940#else
4941 (buf->b_p_sn || buf->b_shortname),
4942#endif
4943 fname, p_pm, FALSE);
4944
4945 if (backup != NULL)
4946 {
4947 struct stat st;
4948
4949 /*
4950 * If the original file does not exist yet
4951 * the current backup file becomes the original file
4952 */
4953 if (org == NULL)
4954 EMSG(_("E205: Patchmode: can't save original file"));
4955 else if (mch_stat(org, &st) < 0)
4956 {
4957 vim_rename(backup, (char_u *)org);
4958 vim_free(backup); /* don't delete the file */
4959 backup = NULL;
4960#ifdef UNIX
4961 set_file_time((char_u *)org, st_old.st_atime, st_old.st_mtime);
4962#endif
4963 }
4964 }
4965 /*
4966 * If there is no backup file, remember that a (new) file was
4967 * created.
4968 */
4969 else
4970 {
4971 int empty_fd;
4972
4973 if (org == NULL
Bram Moolenaara5792f52005-11-23 21:25:05 +00004974 || (empty_fd = mch_open(org,
4975 O_CREAT | O_EXTRA | O_EXCL | O_NOFOLLOW,
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00004976 perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004977 EMSG(_("E206: patchmode: can't touch empty original file"));
4978 else
4979 close(empty_fd);
4980 }
4981 if (org != NULL)
4982 {
4983 mch_setperm((char_u *)org, mch_getperm(fname) & 0777);
4984 vim_free(org);
4985 }
4986 }
4987
4988 /*
4989 * Remove the backup unless 'backup' option is set
4990 */
4991 if (!p_bk && backup != NULL && mch_remove(backup) != 0)
4992 EMSG(_("E207: Can't delete backup file"));
4993
4994#ifdef FEAT_SUN_WORKSHOP
4995 if (usingSunWorkShop)
4996 workshop_file_saved((char *) ffname);
4997#endif
4998
4999 goto nofail;
5000
5001 /*
5002 * Finish up. We get here either after failure or success.
5003 */
5004fail:
5005 --no_wait_return; /* may wait for return now */
5006nofail:
5007
5008 /* Done saving, we accept changed buffer warnings again */
5009 buf->b_saving = FALSE;
5010
5011 vim_free(backup);
5012 if (buffer != smallbuf)
5013 vim_free(buffer);
5014#ifdef FEAT_MBYTE
5015 vim_free(fenc_tofree);
5016 vim_free(write_info.bw_conv_buf);
5017# ifdef USE_ICONV
5018 if (write_info.bw_iconv_fd != (iconv_t)-1)
5019 {
5020 iconv_close(write_info.bw_iconv_fd);
5021 write_info.bw_iconv_fd = (iconv_t)-1;
5022 }
5023# endif
5024#endif
5025#ifdef HAVE_ACL
5026 mch_free_acl(acl);
5027#endif
5028
5029 if (errmsg != NULL)
5030 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005031 int numlen = errnum != NULL ? (int)STRLEN(errnum) : 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005032
5033 attr = hl_attr(HLF_E); /* set highlight for error messages */
5034 msg_add_fname(buf,
5035#ifndef UNIX
5036 sfname
5037#else
5038 fname
5039#endif
5040 ); /* put file name in IObuff with quotes */
5041 if (STRLEN(IObuff) + STRLEN(errmsg) + numlen >= IOSIZE)
5042 IObuff[IOSIZE - STRLEN(errmsg) - numlen - 1] = NUL;
5043 /* If the error message has the form "is ...", put the error number in
5044 * front of the file name. */
5045 if (errnum != NULL)
5046 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00005047 STRMOVE(IObuff + numlen, IObuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005048 mch_memmove(IObuff, errnum, (size_t)numlen);
5049 }
5050 STRCAT(IObuff, errmsg);
5051 emsg(IObuff);
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005052 if (errmsg_allocated)
5053 vim_free(errmsg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005054
5055 retval = FAIL;
5056 if (end == 0)
5057 {
5058 MSG_PUTS_ATTR(_("\nWARNING: Original file may be lost or damaged\n"),
5059 attr | MSG_HIST);
5060 MSG_PUTS_ATTR(_("don't quit the editor until the file is successfully written!"),
5061 attr | MSG_HIST);
5062
5063 /* Update the timestamp to avoid an "overwrite changed file"
5064 * prompt when writing again. */
5065 if (mch_stat((char *)fname, &st_old) >= 0)
5066 {
5067 buf_store_time(buf, &st_old, fname);
5068 buf->b_mtime_read = buf->b_mtime;
5069 }
5070 }
5071 }
5072 msg_scroll = msg_save;
5073
Bram Moolenaar55debbe2010-05-23 23:34:36 +02005074#ifdef FEAT_PERSISTENT_UNDO
5075 /*
5076 * When writing the whole file and 'undofile' is set, also write the undo
5077 * file.
5078 */
5079 if (retval == OK && write_undo_file)
5080 {
5081 char_u hash[UNDO_HASH_SIZE];
5082
5083 sha256_finish(&sha_ctx, hash);
5084 u_write_undo(NULL, FALSE, buf, hash);
5085 }
5086#endif
5087
Bram Moolenaar071d4272004-06-13 20:20:40 +00005088#ifdef FEAT_AUTOCMD
5089#ifdef FEAT_EVAL
5090 if (!should_abort(retval))
5091#else
5092 if (!got_int)
5093#endif
5094 {
5095 aco_save_T aco;
5096
5097 write_no_eol_lnum = 0; /* in case it was set by the previous read */
5098
5099 /*
5100 * Apply POST autocommands.
5101 * Careful: The autocommands may call buf_write() recursively!
5102 */
5103 aucmd_prepbuf(&aco, buf);
5104
5105 if (append)
5106 apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname,
5107 FALSE, curbuf, eap);
5108 else if (filtering)
5109 apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname,
5110 FALSE, curbuf, eap);
5111 else if (reset_changed && whole)
5112 apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname,
5113 FALSE, curbuf, eap);
5114 else
5115 apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname,
5116 FALSE, curbuf, eap);
5117
5118 /* restore curwin/curbuf and a few other things */
5119 aucmd_restbuf(&aco);
5120
5121#ifdef FEAT_EVAL
5122 if (aborting()) /* autocmds may abort script processing */
5123 retval = FALSE;
5124#endif
5125 }
5126#endif
5127
5128 got_int |= prev_got_int;
5129
5130#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
5131 /* Update machine specific information. */
5132 mch_post_buffer_write(buf);
5133#endif
5134 return retval;
5135}
5136
5137/*
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005138 * Set the name of the current buffer. Use when the buffer doesn't have a
5139 * name and a ":r" or ":w" command with a file name is used.
5140 */
5141 static int
5142set_rw_fname(fname, sfname)
5143 char_u *fname;
5144 char_u *sfname;
5145{
5146#ifdef FEAT_AUTOCMD
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005147 buf_T *buf = curbuf;
5148
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005149 /* It's like the unnamed buffer is deleted.... */
5150 if (curbuf->b_p_bl)
5151 apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
5152 apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf);
5153# ifdef FEAT_EVAL
5154 if (aborting()) /* autocmds may abort script processing */
5155 return FAIL;
5156# endif
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005157 if (curbuf != buf)
5158 {
5159 /* We are in another buffer now, don't do the renaming. */
5160 EMSG(_(e_auchangedbuf));
5161 return FAIL;
5162 }
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005163#endif
5164
5165 if (setfname(curbuf, fname, sfname, FALSE) == OK)
5166 curbuf->b_flags |= BF_NOTEDITED;
5167
5168#ifdef FEAT_AUTOCMD
5169 /* ....and a new named one is created */
5170 apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, curbuf);
5171 if (curbuf->b_p_bl)
5172 apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf);
5173# ifdef FEAT_EVAL
5174 if (aborting()) /* autocmds may abort script processing */
5175 return FAIL;
5176# endif
5177
5178 /* Do filetype detection now if 'filetype' is empty. */
5179 if (*curbuf->b_p_ft == NUL)
5180 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005181 if (au_has_group((char_u *)"filetypedetect"))
Bram Moolenaar70836c82006-02-20 21:28:49 +00005182 (void)do_doautocmd((char_u *)"filetypedetect BufRead", FALSE);
Bram Moolenaara3227e22006-03-08 21:32:40 +00005183 do_modelines(0);
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005184 }
5185#endif
5186
5187 return OK;
5188}
5189
5190/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00005191 * Put file name into IObuff with quotes.
5192 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005193 void
Bram Moolenaar071d4272004-06-13 20:20:40 +00005194msg_add_fname(buf, fname)
5195 buf_T *buf;
5196 char_u *fname;
5197{
5198 if (fname == NULL)
5199 fname = (char_u *)"-stdin-";
5200 home_replace(buf, fname, IObuff + 1, IOSIZE - 4, TRUE);
5201 IObuff[0] = '"';
5202 STRCAT(IObuff, "\" ");
5203}
5204
5205/*
5206 * Append message for text mode to IObuff.
5207 * Return TRUE if something appended.
5208 */
5209 static int
5210msg_add_fileformat(eol_type)
5211 int eol_type;
5212{
5213#ifndef USE_CRNL
5214 if (eol_type == EOL_DOS)
5215 {
5216 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[dos]") : _("[dos format]"));
5217 return TRUE;
5218 }
5219#endif
5220#ifndef USE_CR
5221 if (eol_type == EOL_MAC)
5222 {
5223 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[mac]") : _("[mac format]"));
5224 return TRUE;
5225 }
5226#endif
5227#if defined(USE_CRNL) || defined(USE_CR)
5228 if (eol_type == EOL_UNIX)
5229 {
5230 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[unix]") : _("[unix format]"));
5231 return TRUE;
5232 }
5233#endif
5234 return FALSE;
5235}
5236
5237/*
5238 * Append line and character count to IObuff.
5239 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005240 void
Bram Moolenaar071d4272004-06-13 20:20:40 +00005241msg_add_lines(insert_space, lnum, nchars)
5242 int insert_space;
5243 long lnum;
Bram Moolenaar914703b2010-05-31 21:59:46 +02005244 off_t nchars;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005245{
5246 char_u *p;
5247
5248 p = IObuff + STRLEN(IObuff);
5249
5250 if (insert_space)
5251 *p++ = ' ';
5252 if (shortmess(SHM_LINES))
Bram Moolenaar914703b2010-05-31 21:59:46 +02005253 sprintf((char *)p,
5254#ifdef LONG_LONG_OFF_T
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005255 "%ldL, %lldC", lnum, nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005256#else
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005257 /* Explicit typecast avoids warning on Mac OS X 10.6 */
5258 "%ldL, %ldC", lnum, (long)nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005259#endif
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005260 );
Bram Moolenaar071d4272004-06-13 20:20:40 +00005261 else
5262 {
5263 if (lnum == 1)
5264 STRCPY(p, _("1 line, "));
5265 else
5266 sprintf((char *)p, _("%ld lines, "), lnum);
5267 p += STRLEN(p);
5268 if (nchars == 1)
5269 STRCPY(p, _("1 character"));
5270 else
Bram Moolenaar914703b2010-05-31 21:59:46 +02005271 sprintf((char *)p,
5272#ifdef LONG_LONG_OFF_T
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005273 _("%lld characters"), nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005274#else
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005275 /* Explicit typecast avoids warning on Mac OS X 10.6 */
5276 _("%ld characters"), (long)nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005277#endif
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005278 );
Bram Moolenaar071d4272004-06-13 20:20:40 +00005279 }
5280}
5281
5282/*
5283 * Append message for missing line separator to IObuff.
5284 */
5285 static void
5286msg_add_eol()
5287{
5288 STRCAT(IObuff, shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]"));
5289}
5290
5291/*
5292 * Check modification time of file, before writing to it.
5293 * The size isn't checked, because using a tool like "gzip" takes care of
5294 * using the same timestamp but can't set the size.
5295 */
5296 static int
5297check_mtime(buf, st)
5298 buf_T *buf;
5299 struct stat *st;
5300{
5301 if (buf->b_mtime_read != 0
5302 && time_differs((long)st->st_mtime, buf->b_mtime_read))
5303 {
5304 msg_scroll = TRUE; /* don't overwrite messages here */
5305 msg_silent = 0; /* must give this prompt */
5306 /* don't use emsg() here, don't want to flush the buffers */
5307 MSG_ATTR(_("WARNING: The file has been changed since reading it!!!"),
5308 hl_attr(HLF_E));
5309 if (ask_yesno((char_u *)_("Do you really want to write to it"),
5310 TRUE) == 'n')
5311 return FAIL;
5312 msg_scroll = FALSE; /* always overwrite the file message now */
5313 }
5314 return OK;
5315}
5316
5317 static int
5318time_differs(t1, t2)
5319 long t1, t2;
5320{
5321#if defined(__linux__) || defined(MSDOS) || defined(MSWIN)
5322 /* On a FAT filesystem, esp. under Linux, there are only 5 bits to store
5323 * the seconds. Since the roundoff is done when flushing the inode, the
5324 * time may change unexpectedly by one second!!! */
5325 return (t1 - t2 > 1 || t2 - t1 > 1);
5326#else
5327 return (t1 != t2);
5328#endif
5329}
5330
5331/*
5332 * Call write() to write a number of bytes to the file.
5333 * Also handles encryption and 'encoding' conversion.
5334 *
5335 * Return FAIL for failure, OK otherwise.
5336 */
5337 static int
5338buf_write_bytes(ip)
5339 struct bw_info *ip;
5340{
5341 int wlen;
5342 char_u *buf = ip->bw_buf; /* data to write */
5343 int len = ip->bw_len; /* length of data */
5344#ifdef HAS_BW_FLAGS
5345 int flags = ip->bw_flags; /* extra flags */
5346#endif
5347
5348#ifdef FEAT_MBYTE
5349 /*
5350 * Skip conversion when writing the crypt magic number or the BOM.
5351 */
5352 if (!(flags & FIO_NOCONVERT))
5353 {
5354 char_u *p;
5355 unsigned c;
5356 int n;
5357
5358 if (flags & FIO_UTF8)
5359 {
5360 /*
5361 * Convert latin1 in the buffer to UTF-8 in the file.
5362 */
5363 p = ip->bw_conv_buf; /* translate to buffer */
5364 for (wlen = 0; wlen < len; ++wlen)
5365 p += utf_char2bytes(buf[wlen], p);
5366 buf = ip->bw_conv_buf;
5367 len = (int)(p - ip->bw_conv_buf);
5368 }
5369 else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1))
5370 {
5371 /*
5372 * Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
5373 * Latin1 chars in the file.
5374 */
5375 if (flags & FIO_LATIN1)
5376 p = buf; /* translate in-place (can only get shorter) */
5377 else
5378 p = ip->bw_conv_buf; /* translate to buffer */
5379 for (wlen = 0; wlen < len; wlen += n)
5380 {
5381 if (wlen == 0 && ip->bw_restlen != 0)
5382 {
5383 int l;
5384
5385 /* Use remainder of previous call. Append the start of
5386 * buf[] to get a full sequence. Might still be too
5387 * short! */
5388 l = CONV_RESTLEN - ip->bw_restlen;
5389 if (l > len)
5390 l = len;
5391 mch_memmove(ip->bw_rest + ip->bw_restlen, buf, (size_t)l);
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005392 n = utf_ptr2len_len(ip->bw_rest, ip->bw_restlen + l);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005393 if (n > ip->bw_restlen + len)
5394 {
5395 /* We have an incomplete byte sequence at the end to
5396 * be written. We can't convert it without the
5397 * remaining bytes. Keep them for the next call. */
5398 if (ip->bw_restlen + len > CONV_RESTLEN)
5399 return FAIL;
5400 ip->bw_restlen += len;
5401 break;
5402 }
5403 if (n > 1)
5404 c = utf_ptr2char(ip->bw_rest);
5405 else
5406 c = ip->bw_rest[0];
5407 if (n >= ip->bw_restlen)
5408 {
5409 n -= ip->bw_restlen;
5410 ip->bw_restlen = 0;
5411 }
5412 else
5413 {
5414 ip->bw_restlen -= n;
5415 mch_memmove(ip->bw_rest, ip->bw_rest + n,
5416 (size_t)ip->bw_restlen);
5417 n = 0;
5418 }
5419 }
5420 else
5421 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005422 n = utf_ptr2len_len(buf + wlen, len - wlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005423 if (n > len - wlen)
5424 {
5425 /* We have an incomplete byte sequence at the end to
5426 * be written. We can't convert it without the
5427 * remaining bytes. Keep them for the next call. */
5428 if (len - wlen > CONV_RESTLEN)
5429 return FAIL;
5430 ip->bw_restlen = len - wlen;
5431 mch_memmove(ip->bw_rest, buf + wlen,
5432 (size_t)ip->bw_restlen);
5433 break;
5434 }
5435 if (n > 1)
5436 c = utf_ptr2char(buf + wlen);
5437 else
5438 c = buf[wlen];
5439 }
5440
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005441 if (ucs2bytes(c, &p, flags) && !ip->bw_conv_error)
5442 {
5443 ip->bw_conv_error = TRUE;
5444 ip->bw_conv_error_lnum = ip->bw_start_lnum;
5445 }
5446 if (c == NL)
5447 ++ip->bw_start_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005448 }
5449 if (flags & FIO_LATIN1)
5450 len = (int)(p - buf);
5451 else
5452 {
5453 buf = ip->bw_conv_buf;
5454 len = (int)(p - ip->bw_conv_buf);
5455 }
5456 }
5457
5458# ifdef WIN3264
5459 else if (flags & FIO_CODEPAGE)
5460 {
5461 /*
5462 * Convert UTF-8 or codepage to UCS-2 and then to MS-Windows
5463 * codepage.
5464 */
5465 char_u *from;
5466 size_t fromlen;
5467 char_u *to;
5468 int u8c;
5469 BOOL bad = FALSE;
5470 int needed;
5471
5472 if (ip->bw_restlen > 0)
5473 {
5474 /* Need to concatenate the remainder of the previous call and
5475 * the bytes of the current call. Use the end of the
5476 * conversion buffer for this. */
5477 fromlen = len + ip->bw_restlen;
5478 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5479 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5480 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5481 }
5482 else
5483 {
5484 from = buf;
5485 fromlen = len;
5486 }
5487
5488 to = ip->bw_conv_buf;
5489 if (enc_utf8)
5490 {
5491 /* Convert from UTF-8 to UCS-2, to the start of the buffer.
5492 * The buffer has been allocated to be big enough. */
5493 while (fromlen > 0)
5494 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005495 n = (int)utf_ptr2len_len(from, (int)fromlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005496 if (n > (int)fromlen) /* incomplete byte sequence */
5497 break;
5498 u8c = utf_ptr2char(from);
5499 *to++ = (u8c & 0xff);
5500 *to++ = (u8c >> 8);
5501 fromlen -= n;
5502 from += n;
5503 }
5504
5505 /* Copy remainder to ip->bw_rest[] to be used for the next
5506 * call. */
5507 if (fromlen > CONV_RESTLEN)
5508 {
5509 /* weird overlong sequence */
5510 ip->bw_conv_error = TRUE;
5511 return FAIL;
5512 }
5513 mch_memmove(ip->bw_rest, from, fromlen);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005514 ip->bw_restlen = (int)fromlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005515 }
5516 else
5517 {
5518 /* Convert from enc_codepage to UCS-2, to the start of the
5519 * buffer. The buffer has been allocated to be big enough. */
5520 ip->bw_restlen = 0;
5521 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005522 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005523 NULL, 0);
5524 if (needed == 0)
5525 {
5526 /* When conversion fails there may be a trailing byte. */
5527 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005528 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen - 1,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005529 NULL, 0);
5530 if (needed == 0)
5531 {
5532 /* Conversion doesn't work. */
5533 ip->bw_conv_error = TRUE;
5534 return FAIL;
5535 }
5536 /* Save the trailing byte for the next call. */
5537 ip->bw_rest[0] = from[fromlen - 1];
5538 ip->bw_restlen = 1;
5539 }
5540 needed = MultiByteToWideChar(enc_codepage, MB_ERR_INVALID_CHARS,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005541 (LPCSTR)from, (int)(fromlen - ip->bw_restlen),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005542 (LPWSTR)to, needed);
5543 if (needed == 0)
5544 {
5545 /* Safety check: Conversion doesn't work. */
5546 ip->bw_conv_error = TRUE;
5547 return FAIL;
5548 }
5549 to += needed * 2;
5550 }
5551
5552 fromlen = to - ip->bw_conv_buf;
5553 buf = to;
5554# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5555 if (FIO_GET_CP(flags) == CP_UTF8)
5556 {
5557 /* Convert from UCS-2 to UTF-8, using the remainder of the
5558 * conversion buffer. Fails when out of space. */
5559 for (from = ip->bw_conv_buf; fromlen > 1; fromlen -= 2)
5560 {
5561 u8c = *from++;
5562 u8c += (*from++ << 8);
5563 to += utf_char2bytes(u8c, to);
5564 if (to + 6 >= ip->bw_conv_buf + ip->bw_conv_buflen)
5565 {
5566 ip->bw_conv_error = TRUE;
5567 return FAIL;
5568 }
5569 }
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005570 len = (int)(to - buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005571 }
5572 else
5573#endif
5574 {
5575 /* Convert from UCS-2 to the codepage, using the remainder of
5576 * the conversion buffer. If the conversion uses the default
5577 * character "0", the data doesn't fit in this encoding, so
5578 * fail. */
5579 len = WideCharToMultiByte(FIO_GET_CP(flags), 0,
5580 (LPCWSTR)ip->bw_conv_buf, (int)fromlen / sizeof(WCHAR),
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005581 (LPSTR)to, (int)(ip->bw_conv_buflen - fromlen), 0,
5582 &bad);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005583 if (bad)
5584 {
5585 ip->bw_conv_error = TRUE;
5586 return FAIL;
5587 }
5588 }
5589 }
5590# endif
5591
Bram Moolenaar56718732006-03-15 22:53:57 +00005592# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00005593 else if (flags & FIO_MACROMAN)
5594 {
5595 /*
5596 * Convert UTF-8 or latin1 to Apple MacRoman.
5597 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005598 char_u *from;
5599 size_t fromlen;
5600
5601 if (ip->bw_restlen > 0)
5602 {
5603 /* Need to concatenate the remainder of the previous call and
5604 * the bytes of the current call. Use the end of the
5605 * conversion buffer for this. */
5606 fromlen = len + ip->bw_restlen;
5607 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5608 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5609 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5610 }
5611 else
5612 {
5613 from = buf;
5614 fromlen = len;
5615 }
5616
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00005617 if (enc2macroman(from, fromlen,
5618 ip->bw_conv_buf, &len, ip->bw_conv_buflen,
5619 ip->bw_rest, &ip->bw_restlen) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005620 {
5621 ip->bw_conv_error = TRUE;
5622 return FAIL;
5623 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005624 buf = ip->bw_conv_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005625 }
5626# endif
5627
5628# ifdef USE_ICONV
5629 if (ip->bw_iconv_fd != (iconv_t)-1)
5630 {
5631 const char *from;
5632 size_t fromlen;
5633 char *to;
5634 size_t tolen;
5635
5636 /* Convert with iconv(). */
5637 if (ip->bw_restlen > 0)
5638 {
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005639 char *fp;
5640
Bram Moolenaar071d4272004-06-13 20:20:40 +00005641 /* Need to concatenate the remainder of the previous call and
5642 * the bytes of the current call. Use the end of the
5643 * conversion buffer for this. */
5644 fromlen = len + ip->bw_restlen;
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005645 fp = (char *)ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5646 mch_memmove(fp, ip->bw_rest, (size_t)ip->bw_restlen);
5647 mch_memmove(fp + ip->bw_restlen, buf, (size_t)len);
5648 from = fp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005649 tolen = ip->bw_conv_buflen - fromlen;
5650 }
5651 else
5652 {
5653 from = (const char *)buf;
5654 fromlen = len;
5655 tolen = ip->bw_conv_buflen;
5656 }
5657 to = (char *)ip->bw_conv_buf;
5658
5659 if (ip->bw_first)
5660 {
5661 size_t save_len = tolen;
5662
5663 /* output the initial shift state sequence */
5664 (void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen);
5665
5666 /* There is a bug in iconv() on Linux (which appears to be
5667 * wide-spread) which sets "to" to NULL and messes up "tolen".
5668 */
5669 if (to == NULL)
5670 {
5671 to = (char *)ip->bw_conv_buf;
5672 tolen = save_len;
5673 }
5674 ip->bw_first = FALSE;
5675 }
5676
5677 /*
5678 * If iconv() has an error or there is not enough room, fail.
5679 */
5680 if ((iconv(ip->bw_iconv_fd, (void *)&from, &fromlen, &to, &tolen)
5681 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
5682 || fromlen > CONV_RESTLEN)
5683 {
5684 ip->bw_conv_error = TRUE;
5685 return FAIL;
5686 }
5687
5688 /* copy remainder to ip->bw_rest[] to be used for the next call. */
5689 if (fromlen > 0)
5690 mch_memmove(ip->bw_rest, (void *)from, fromlen);
5691 ip->bw_restlen = (int)fromlen;
5692
5693 buf = ip->bw_conv_buf;
5694 len = (int)((char_u *)to - ip->bw_conv_buf);
5695 }
5696# endif
5697 }
5698#endif /* FEAT_MBYTE */
5699
5700#ifdef FEAT_CRYPT
5701 if (flags & FIO_ENCRYPTED) /* encrypt the data */
Bram Moolenaar04c9baf2010-06-01 23:37:39 +02005702 crypt_encode(buf, len, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005703#endif
5704
5705 /* Repeat the write(), it may be interrupted by a signal. */
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005706 while (len > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005707 {
5708 wlen = vim_write(ip->bw_fd, buf, len);
5709 if (wlen <= 0) /* error! */
5710 return FAIL;
5711 len -= wlen;
5712 buf += wlen;
5713 }
5714 return OK;
5715}
5716
5717#ifdef FEAT_MBYTE
5718/*
5719 * Convert a Unicode character to bytes.
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005720 * Return TRUE for an error, FALSE when it's OK.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005721 */
5722 static int
5723ucs2bytes(c, pp, flags)
5724 unsigned c; /* in: character */
5725 char_u **pp; /* in/out: pointer to result */
5726 int flags; /* FIO_ flags */
5727{
5728 char_u *p = *pp;
5729 int error = FALSE;
5730 int cc;
5731
5732
5733 if (flags & FIO_UCS4)
5734 {
5735 if (flags & FIO_ENDIAN_L)
5736 {
5737 *p++ = c;
5738 *p++ = (c >> 8);
5739 *p++ = (c >> 16);
5740 *p++ = (c >> 24);
5741 }
5742 else
5743 {
5744 *p++ = (c >> 24);
5745 *p++ = (c >> 16);
5746 *p++ = (c >> 8);
5747 *p++ = c;
5748 }
5749 }
5750 else if (flags & (FIO_UCS2 | FIO_UTF16))
5751 {
5752 if (c >= 0x10000)
5753 {
5754 if (flags & FIO_UTF16)
5755 {
5756 /* Make two words, ten bits of the character in each. First
5757 * word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff */
5758 c -= 0x10000;
5759 if (c >= 0x100000)
5760 error = TRUE;
5761 cc = ((c >> 10) & 0x3ff) + 0xd800;
5762 if (flags & FIO_ENDIAN_L)
5763 {
5764 *p++ = cc;
5765 *p++ = ((unsigned)cc >> 8);
5766 }
5767 else
5768 {
5769 *p++ = ((unsigned)cc >> 8);
5770 *p++ = cc;
5771 }
5772 c = (c & 0x3ff) + 0xdc00;
5773 }
5774 else
5775 error = TRUE;
5776 }
5777 if (flags & FIO_ENDIAN_L)
5778 {
5779 *p++ = c;
5780 *p++ = (c >> 8);
5781 }
5782 else
5783 {
5784 *p++ = (c >> 8);
5785 *p++ = c;
5786 }
5787 }
5788 else /* Latin1 */
5789 {
5790 if (c >= 0x100)
5791 {
5792 error = TRUE;
5793 *p++ = 0xBF;
5794 }
5795 else
5796 *p++ = c;
5797 }
5798
5799 *pp = p;
5800 return error;
5801}
5802
5803/*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005804 * Return TRUE if file encoding "fenc" requires conversion from or to
5805 * 'encoding'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005806 */
5807 static int
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005808need_conversion(fenc)
5809 char_u *fenc;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005810{
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005811 int same_encoding;
5812 int enc_flags;
5813 int fenc_flags;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005814
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005815 if (*fenc == NUL || STRCMP(p_enc, fenc) == 0)
Bram Moolenaar442b4222010-05-24 21:34:22 +02005816 {
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005817 same_encoding = TRUE;
Bram Moolenaar442b4222010-05-24 21:34:22 +02005818 fenc_flags = 0;
5819 }
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005820 else
5821 {
5822 /* Ignore difference between "ansi" and "latin1", "ucs-4" and
5823 * "ucs-4be", etc. */
5824 enc_flags = get_fio_flags(p_enc);
5825 fenc_flags = get_fio_flags(fenc);
5826 same_encoding = (enc_flags != 0 && fenc_flags == enc_flags);
5827 }
5828 if (same_encoding)
5829 {
5830 /* Specified encoding matches with 'encoding'. This requires
5831 * conversion when 'encoding' is Unicode but not UTF-8. */
5832 return enc_unicode != 0;
5833 }
5834
5835 /* Encodings differ. However, conversion is not needed when 'enc' is any
5836 * Unicode encoding and the file is UTF-8. */
5837 return !(enc_utf8 && fenc_flags == FIO_UTF8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005838}
5839
5840/*
5841 * Check "ptr" for a unicode encoding and return the FIO_ flags needed for the
5842 * internal conversion.
5843 * if "ptr" is an empty string, use 'encoding'.
5844 */
5845 static int
5846get_fio_flags(ptr)
5847 char_u *ptr;
5848{
5849 int prop;
5850
5851 if (*ptr == NUL)
5852 ptr = p_enc;
5853
5854 prop = enc_canon_props(ptr);
5855 if (prop & ENC_UNICODE)
5856 {
5857 if (prop & ENC_2BYTE)
5858 {
5859 if (prop & ENC_ENDIAN_L)
5860 return FIO_UCS2 | FIO_ENDIAN_L;
5861 return FIO_UCS2;
5862 }
5863 if (prop & ENC_4BYTE)
5864 {
5865 if (prop & ENC_ENDIAN_L)
5866 return FIO_UCS4 | FIO_ENDIAN_L;
5867 return FIO_UCS4;
5868 }
5869 if (prop & ENC_2WORD)
5870 {
5871 if (prop & ENC_ENDIAN_L)
5872 return FIO_UTF16 | FIO_ENDIAN_L;
5873 return FIO_UTF16;
5874 }
5875 return FIO_UTF8;
5876 }
5877 if (prop & ENC_LATIN1)
5878 return FIO_LATIN1;
5879 /* must be ENC_DBCS, requires iconv() */
5880 return 0;
5881}
5882
5883#ifdef WIN3264
5884/*
5885 * Check "ptr" for a MS-Windows codepage name and return the FIO_ flags needed
5886 * for the conversion MS-Windows can do for us. Also accept "utf-8".
5887 * Used for conversion between 'encoding' and 'fileencoding'.
5888 */
5889 static int
5890get_win_fio_flags(ptr)
5891 char_u *ptr;
5892{
5893 int cp;
5894
5895 /* Cannot do this when 'encoding' is not utf-8 and not a codepage. */
5896 if (!enc_utf8 && enc_codepage <= 0)
5897 return 0;
5898
5899 cp = encname2codepage(ptr);
5900 if (cp == 0)
5901 {
5902# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5903 if (STRCMP(ptr, "utf-8") == 0)
5904 cp = CP_UTF8;
5905 else
5906# endif
5907 return 0;
5908 }
5909 return FIO_PUT_CP(cp) | FIO_CODEPAGE;
5910}
5911#endif
5912
5913#ifdef MACOS_X
5914/*
5915 * Check "ptr" for a Carbon supported encoding and return the FIO_ flags
5916 * needed for the internal conversion to/from utf-8 or latin1.
5917 */
5918 static int
5919get_mac_fio_flags(ptr)
5920 char_u *ptr;
5921{
5922 if ((enc_utf8 || STRCMP(p_enc, "latin1") == 0)
5923 && (enc_canon_props(ptr) & ENC_MACROMAN))
5924 return FIO_MACROMAN;
5925 return 0;
5926}
5927#endif
5928
5929/*
5930 * Check for a Unicode BOM (Byte Order Mark) at the start of p[size].
5931 * "size" must be at least 2.
5932 * Return the name of the encoding and set "*lenp" to the length.
5933 * Returns NULL when no BOM found.
5934 */
5935 static char_u *
5936check_for_bom(p, size, lenp, flags)
5937 char_u *p;
5938 long size;
5939 int *lenp;
5940 int flags;
5941{
5942 char *name = NULL;
5943 int len = 2;
5944
5945 if (p[0] == 0xef && p[1] == 0xbb && size >= 3 && p[2] == 0xbf
Bram Moolenaaree0f5a62008-07-24 20:09:16 +00005946 && (flags == FIO_ALL || flags == FIO_UTF8 || flags == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005947 {
5948 name = "utf-8"; /* EF BB BF */
5949 len = 3;
5950 }
5951 else if (p[0] == 0xff && p[1] == 0xfe)
5952 {
5953 if (size >= 4 && p[2] == 0 && p[3] == 0
5954 && (flags == FIO_ALL || flags == (FIO_UCS4 | FIO_ENDIAN_L)))
5955 {
5956 name = "ucs-4le"; /* FF FE 00 00 */
5957 len = 4;
5958 }
Bram Moolenaar223a1892008-11-11 20:57:11 +00005959 else if (flags == (FIO_UCS2 | FIO_ENDIAN_L))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005960 name = "ucs-2le"; /* FF FE */
Bram Moolenaar223a1892008-11-11 20:57:11 +00005961 else if (flags == FIO_ALL || flags == (FIO_UTF16 | FIO_ENDIAN_L))
5962 /* utf-16le is preferred, it also works for ucs-2le text */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005963 name = "utf-16le"; /* FF FE */
5964 }
5965 else if (p[0] == 0xfe && p[1] == 0xff
5966 && (flags == FIO_ALL || flags == FIO_UCS2 || flags == FIO_UTF16))
5967 {
Bram Moolenaarffd82c52008-02-20 17:15:26 +00005968 /* Default to utf-16, it works also for ucs-2 text. */
5969 if (flags == FIO_UCS2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005970 name = "ucs-2"; /* FE FF */
Bram Moolenaarffd82c52008-02-20 17:15:26 +00005971 else
5972 name = "utf-16"; /* FE FF */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005973 }
5974 else if (size >= 4 && p[0] == 0 && p[1] == 0 && p[2] == 0xfe
5975 && p[3] == 0xff && (flags == FIO_ALL || flags == FIO_UCS4))
5976 {
5977 name = "ucs-4"; /* 00 00 FE FF */
5978 len = 4;
5979 }
5980
5981 *lenp = len;
5982 return (char_u *)name;
5983}
5984
5985/*
5986 * Generate a BOM in "buf[4]" for encoding "name".
5987 * Return the length of the BOM (zero when no BOM).
5988 */
5989 static int
5990make_bom(buf, name)
5991 char_u *buf;
5992 char_u *name;
5993{
5994 int flags;
5995 char_u *p;
5996
5997 flags = get_fio_flags(name);
5998
5999 /* Can't put a BOM in a non-Unicode file. */
6000 if (flags == FIO_LATIN1 || flags == 0)
6001 return 0;
6002
6003 if (flags == FIO_UTF8) /* UTF-8 */
6004 {
6005 buf[0] = 0xef;
6006 buf[1] = 0xbb;
6007 buf[2] = 0xbf;
6008 return 3;
6009 }
6010 p = buf;
6011 (void)ucs2bytes(0xfeff, &p, flags);
6012 return (int)(p - buf);
6013}
6014#endif
6015
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00006016#if defined(FEAT_VIMINFO) || defined(FEAT_BROWSE) || \
Bram Moolenaara0174af2008-01-02 20:08:25 +00006017 defined(FEAT_QUICKFIX) || defined(FEAT_AUTOCMD) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006018/*
6019 * Try to find a shortname by comparing the fullname with the current
6020 * directory.
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006021 * Returns "full_path" or pointer into "full_path" if shortened.
6022 */
6023 char_u *
6024shorten_fname1(full_path)
6025 char_u *full_path;
6026{
6027 char_u dirname[MAXPATHL];
6028 char_u *p = full_path;
6029
6030 if (mch_dirname(dirname, MAXPATHL) == OK)
6031 {
6032 p = shorten_fname(full_path, dirname);
6033 if (p == NULL || *p == NUL)
6034 p = full_path;
6035 }
6036 return p;
6037}
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00006038#endif
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006039
6040/*
6041 * Try to find a shortname by comparing the fullname with the current
6042 * directory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006043 * Returns NULL if not shorter name possible, pointer into "full_path"
6044 * otherwise.
6045 */
6046 char_u *
6047shorten_fname(full_path, dir_name)
6048 char_u *full_path;
6049 char_u *dir_name;
6050{
6051 int len;
6052 char_u *p;
6053
6054 if (full_path == NULL)
6055 return NULL;
6056 len = (int)STRLEN(dir_name);
6057 if (fnamencmp(dir_name, full_path, len) == 0)
6058 {
6059 p = full_path + len;
6060#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
6061 /*
6062 * MSDOS: when a file is in the root directory, dir_name will end in a
6063 * slash, since C: by itself does not define a specific dir. In this
6064 * case p may already be correct. <negri>
6065 */
6066 if (!((len > 2) && (*(p - 2) == ':')))
6067#endif
6068 {
6069 if (vim_ispathsep(*p))
6070 ++p;
6071#ifndef VMS /* the path separator is always part of the path */
6072 else
6073 p = NULL;
6074#endif
6075 }
6076 }
6077#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
6078 /*
6079 * When using a file in the current drive, remove the drive name:
6080 * "A:\dir\file" -> "\dir\file". This helps when moving a session file on
6081 * a floppy from "A:\dir" to "B:\dir".
6082 */
6083 else if (len > 3
6084 && TOUPPER_LOC(full_path[0]) == TOUPPER_LOC(dir_name[0])
6085 && full_path[1] == ':'
6086 && vim_ispathsep(full_path[2]))
6087 p = full_path + 2;
6088#endif
6089 else
6090 p = NULL;
6091 return p;
6092}
6093
6094/*
6095 * Shorten filenames for all buffers.
6096 * When "force" is TRUE: Use full path from now on for files currently being
6097 * edited, both for file name and swap file name. Try to shorten the file
6098 * names a bit, if safe to do so.
6099 * When "force" is FALSE: Only try to shorten absolute file names.
6100 * For buffers that have buftype "nofile" or "scratch": never change the file
6101 * name.
6102 */
6103 void
6104shorten_fnames(force)
6105 int force;
6106{
6107 char_u dirname[MAXPATHL];
6108 buf_T *buf;
6109 char_u *p;
6110
6111 mch_dirname(dirname, MAXPATHL);
6112 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
6113 {
6114 if (buf->b_fname != NULL
6115#ifdef FEAT_QUICKFIX
6116 && !bt_nofile(buf)
6117#endif
6118 && !path_with_url(buf->b_fname)
6119 && (force
6120 || buf->b_sfname == NULL
6121 || mch_isFullName(buf->b_sfname)))
6122 {
6123 vim_free(buf->b_sfname);
6124 buf->b_sfname = NULL;
6125 p = shorten_fname(buf->b_ffname, dirname);
6126 if (p != NULL)
6127 {
6128 buf->b_sfname = vim_strsave(p);
6129 buf->b_fname = buf->b_sfname;
6130 }
6131 if (p == NULL || buf->b_fname == NULL)
6132 buf->b_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006133 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00006134
6135 /* Always make the swap file name a full path, a "nofile" buffer may
6136 * also have a swap file. */
6137 mf_fullname(buf->b_ml.ml_mfp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006138 }
6139#ifdef FEAT_WINDOWS
6140 status_redraw_all();
Bram Moolenaar49d7bf12006-02-17 21:45:41 +00006141 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006142#endif
6143}
6144
6145#if (defined(FEAT_DND) && defined(FEAT_GUI_GTK)) \
6146 || defined(FEAT_GUI_MSWIN) \
6147 || defined(FEAT_GUI_MAC) \
6148 || defined(PROTO)
6149/*
6150 * Shorten all filenames in "fnames[count]" by current directory.
6151 */
6152 void
6153shorten_filenames(fnames, count)
6154 char_u **fnames;
6155 int count;
6156{
6157 int i;
6158 char_u dirname[MAXPATHL];
6159 char_u *p;
6160
6161 if (fnames == NULL || count < 1)
6162 return;
6163 mch_dirname(dirname, sizeof(dirname));
6164 for (i = 0; i < count; ++i)
6165 {
6166 if ((p = shorten_fname(fnames[i], dirname)) != NULL)
6167 {
6168 /* shorten_fname() returns pointer in given "fnames[i]". If free
6169 * "fnames[i]" first, "p" becomes invalid. So we need to copy
6170 * "p" first then free fnames[i]. */
6171 p = vim_strsave(p);
6172 vim_free(fnames[i]);
6173 fnames[i] = p;
6174 }
6175 }
6176}
6177#endif
6178
6179/*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006180 * add extension to file name - change path/fo.o.h to path/fo.o.h.ext or
Bram Moolenaar071d4272004-06-13 20:20:40 +00006181 * fo_o_h.ext for MSDOS or when shortname option set.
6182 *
6183 * Assumed that fname is a valid name found in the filesystem we assure that
6184 * the return value is a different name and ends in 'ext'.
6185 * "ext" MUST be at most 4 characters long if it starts with a dot, 3
6186 * characters otherwise.
6187 * Space for the returned name is allocated, must be freed later.
6188 * Returns NULL when out of memory.
6189 */
6190 char_u *
6191modname(fname, ext, prepend_dot)
6192 char_u *fname, *ext;
6193 int prepend_dot; /* may prepend a '.' to file name */
6194{
6195 return buf_modname(
6196#ifdef SHORT_FNAME
6197 TRUE,
6198#else
6199 (curbuf->b_p_sn || curbuf->b_shortname),
6200#endif
6201 fname, ext, prepend_dot);
6202}
6203
6204 char_u *
6205buf_modname(shortname, fname, ext, prepend_dot)
6206 int shortname; /* use 8.3 file name */
6207 char_u *fname, *ext;
6208 int prepend_dot; /* may prepend a '.' to file name */
6209{
6210 char_u *retval;
6211 char_u *s;
6212 char_u *e;
6213 char_u *ptr;
6214 int fnamelen, extlen;
6215
6216 extlen = (int)STRLEN(ext);
6217
6218 /*
6219 * If there is no file name we must get the name of the current directory
6220 * (we need the full path in case :cd is used).
6221 */
6222 if (fname == NULL || *fname == NUL)
6223 {
6224 retval = alloc((unsigned)(MAXPATHL + extlen + 3));
6225 if (retval == NULL)
6226 return NULL;
6227 if (mch_dirname(retval, MAXPATHL) == FAIL ||
6228 (fnamelen = (int)STRLEN(retval)) == 0)
6229 {
6230 vim_free(retval);
6231 return NULL;
6232 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006233 if (!after_pathsep(retval, retval + fnamelen))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006234 {
6235 retval[fnamelen++] = PATHSEP;
6236 retval[fnamelen] = NUL;
6237 }
6238#ifndef SHORT_FNAME
6239 prepend_dot = FALSE; /* nothing to prepend a dot to */
6240#endif
6241 }
6242 else
6243 {
6244 fnamelen = (int)STRLEN(fname);
6245 retval = alloc((unsigned)(fnamelen + extlen + 3));
6246 if (retval == NULL)
6247 return NULL;
6248 STRCPY(retval, fname);
6249#ifdef VMS
6250 vms_remove_version(retval); /* we do not need versions here */
6251#endif
6252 }
6253
6254 /*
6255 * search backwards until we hit a '/', '\' or ':' replacing all '.'
6256 * by '_' for MSDOS or when shortname option set and ext starts with a dot.
6257 * Then truncate what is after the '/', '\' or ':' to 8 characters for
6258 * MSDOS and 26 characters for AMIGA, a lot more for UNIX.
6259 */
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006260 for (ptr = retval + fnamelen; ptr > retval; mb_ptr_back(retval, ptr))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006261 {
6262#ifndef RISCOS
6263 if (*ext == '.'
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006264# ifdef USE_LONG_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00006265 && (!USE_LONG_FNAME || shortname)
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006266# else
6267# ifndef SHORT_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00006268 && shortname
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006269# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006270# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006271 )
6272 if (*ptr == '.') /* replace '.' by '_' */
6273 *ptr = '_';
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006274#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006275 if (vim_ispathsep(*ptr))
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006276 {
6277 ++ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006278 break;
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006279 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006280 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006281
6282 /* the file name has at most BASENAMELEN characters. */
6283#ifndef SHORT_FNAME
6284 if (STRLEN(ptr) > (unsigned)BASENAMELEN)
6285 ptr[BASENAMELEN] = '\0';
6286#endif
6287
6288 s = ptr + STRLEN(ptr);
6289
6290 /*
6291 * For 8.3 file names we may have to reduce the length.
6292 */
6293#ifdef USE_LONG_FNAME
6294 if (!USE_LONG_FNAME || shortname)
6295#else
6296# ifndef SHORT_FNAME
6297 if (shortname)
6298# endif
6299#endif
6300 {
6301 /*
6302 * If there is no file name, or the file name ends in '/', and the
6303 * extension starts with '.', put a '_' before the dot, because just
6304 * ".ext" is invalid.
6305 */
6306 if (fname == NULL || *fname == NUL
6307 || vim_ispathsep(fname[STRLEN(fname) - 1]))
6308 {
6309#ifdef RISCOS
6310 if (*ext == '/')
6311#else
6312 if (*ext == '.')
6313#endif
6314 *s++ = '_';
6315 }
6316 /*
6317 * If the extension starts with '.', truncate the base name at 8
6318 * characters
6319 */
6320#ifdef RISCOS
6321 /* We normally use '/', but swap files are '_' */
6322 else if (*ext == '/' || *ext == '_')
6323#else
6324 else if (*ext == '.')
6325#endif
6326 {
Bram Moolenaar78a15312009-05-15 19:33:18 +00006327 if ((size_t)(s - ptr) > (size_t)8)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006328 {
6329 s = ptr + 8;
6330 *s = '\0';
6331 }
6332 }
6333 /*
6334 * If the extension doesn't start with '.', and the file name
6335 * doesn't have an extension yet, append a '.'
6336 */
6337#ifdef RISCOS
6338 else if ((e = vim_strchr(ptr, '/')) == NULL)
6339 *s++ = '/';
6340#else
6341 else if ((e = vim_strchr(ptr, '.')) == NULL)
6342 *s++ = '.';
6343#endif
6344 /*
6345 * If the extension doesn't start with '.', and there already is an
Bram Moolenaar7263a772007-05-10 17:35:54 +00006346 * extension, it may need to be truncated
Bram Moolenaar071d4272004-06-13 20:20:40 +00006347 */
6348 else if ((int)STRLEN(e) + extlen > 4)
6349 s = e + 4 - extlen;
6350 }
6351#if defined(OS2) || defined(USE_LONG_FNAME) || defined(WIN3264)
6352 /*
6353 * If there is no file name, and the extension starts with '.', put a
6354 * '_' before the dot, because just ".ext" may be invalid if it's on a
6355 * FAT partition, and on HPFS it doesn't matter.
6356 */
6357 else if ((fname == NULL || *fname == NUL) && *ext == '.')
6358 *s++ = '_';
6359#endif
6360
6361 /*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006362 * Append the extension.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006363 * ext can start with '.' and cannot exceed 3 more characters.
6364 */
6365 STRCPY(s, ext);
6366
6367#ifndef SHORT_FNAME
6368 /*
6369 * Prepend the dot.
6370 */
6371 if (prepend_dot && !shortname && *(e = gettail(retval)) !=
6372#ifdef RISCOS
6373 '/'
6374#else
6375 '.'
6376#endif
6377#ifdef USE_LONG_FNAME
6378 && USE_LONG_FNAME
6379#endif
6380 )
6381 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006382 STRMOVE(e + 1, e);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006383#ifdef RISCOS
6384 *e = '/';
6385#else
6386 *e = '.';
6387#endif
6388 }
6389#endif
6390
6391 /*
6392 * Check that, after appending the extension, the file name is really
6393 * different.
6394 */
6395 if (fname != NULL && STRCMP(fname, retval) == 0)
6396 {
6397 /* we search for a character that can be replaced by '_' */
6398 while (--s >= ptr)
6399 {
6400 if (*s != '_')
6401 {
6402 *s = '_';
6403 break;
6404 }
6405 }
6406 if (s < ptr) /* fname was "________.<ext>", how tricky! */
6407 *ptr = 'v';
6408 }
6409 return retval;
6410}
6411
6412/*
6413 * Like fgets(), but if the file line is too long, it is truncated and the
6414 * rest of the line is thrown away. Returns TRUE for end-of-file.
6415 */
6416 int
6417vim_fgets(buf, size, fp)
6418 char_u *buf;
6419 int size;
6420 FILE *fp;
6421{
6422 char *eof;
6423#define FGETS_SIZE 200
6424 char tbuf[FGETS_SIZE];
6425
6426 buf[size - 2] = NUL;
6427#ifdef USE_CR
6428 eof = fgets_cr((char *)buf, size, fp);
6429#else
6430 eof = fgets((char *)buf, size, fp);
6431#endif
6432 if (buf[size - 2] != NUL && buf[size - 2] != '\n')
6433 {
6434 buf[size - 1] = NUL; /* Truncate the line */
6435
6436 /* Now throw away the rest of the line: */
6437 do
6438 {
6439 tbuf[FGETS_SIZE - 2] = NUL;
6440#ifdef USE_CR
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006441 ignoredp = fgets_cr((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006442#else
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006443 ignoredp = fgets((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006444#endif
6445 } while (tbuf[FGETS_SIZE - 2] != NUL && tbuf[FGETS_SIZE - 2] != '\n');
6446 }
6447 return (eof == NULL);
6448}
6449
6450#if defined(USE_CR) || defined(PROTO)
6451/*
6452 * Like vim_fgets(), but accept any line terminator: CR, CR-LF or LF.
6453 * Returns TRUE for end-of-file.
6454 * Only used for the Mac, because it's much slower than vim_fgets().
6455 */
6456 int
6457tag_fgets(buf, size, fp)
6458 char_u *buf;
6459 int size;
6460 FILE *fp;
6461{
6462 int i = 0;
6463 int c;
6464 int eof = FALSE;
6465
6466 for (;;)
6467 {
6468 c = fgetc(fp);
6469 if (c == EOF)
6470 {
6471 eof = TRUE;
6472 break;
6473 }
6474 if (c == '\r')
6475 {
6476 /* Always store a NL for end-of-line. */
6477 if (i < size - 1)
6478 buf[i++] = '\n';
6479 c = fgetc(fp);
6480 if (c != '\n') /* Macintosh format: single CR. */
6481 ungetc(c, fp);
6482 break;
6483 }
6484 if (i < size - 1)
6485 buf[i++] = c;
6486 if (c == '\n')
6487 break;
6488 }
6489 buf[i] = NUL;
6490 return eof;
6491}
6492#endif
6493
6494/*
6495 * rename() only works if both files are on the same file system, this
6496 * function will (attempts to?) copy the file across if rename fails -- webb
6497 * Return -1 for failure, 0 for success.
6498 */
6499 int
6500vim_rename(from, to)
6501 char_u *from;
6502 char_u *to;
6503{
6504 int fd_in;
6505 int fd_out;
6506 int n;
6507 char *errmsg = NULL;
6508 char *buffer;
6509#ifdef AMIGA
6510 BPTR flock;
6511#endif
6512 struct stat st;
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006513 long perm;
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006514#ifdef HAVE_ACL
6515 vim_acl_T acl; /* ACL from original file */
6516#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006517#if defined(UNIX) || defined(CASE_INSENSITIVE_FILENAME)
6518 int use_tmp_file = FALSE;
6519#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006520
6521 /*
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006522 * When the names are identical, there is nothing to do. When they refer
6523 * to the same file (ignoring case and slash/backslash differences) but
6524 * the file name differs we need to go through a temp file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006525 */
6526 if (fnamecmp(from, to) == 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006527 {
6528#ifdef CASE_INSENSITIVE_FILENAME
6529 if (STRCMP(gettail(from), gettail(to)) != 0)
6530 use_tmp_file = TRUE;
6531 else
6532#endif
6533 return 0;
6534 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006535
6536 /*
6537 * Fail if the "from" file doesn't exist. Avoids that "to" is deleted.
6538 */
6539 if (mch_stat((char *)from, &st) < 0)
6540 return -1;
6541
Bram Moolenaar3576da72008-12-30 15:15:57 +00006542#ifdef UNIX
6543 {
6544 struct stat st_to;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006545
6546 /* It's possible for the source and destination to be the same file.
6547 * This happens when "from" and "to" differ in case and are on a FAT32
6548 * filesystem. In that case go through a temp file name. */
6549 if (mch_stat((char *)to, &st_to) >= 0
6550 && st.st_dev == st_to.st_dev
6551 && st.st_ino == st_to.st_ino)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006552 use_tmp_file = TRUE;
6553 }
6554#endif
6555
6556#if defined(UNIX) || defined(CASE_INSENSITIVE_FILENAME)
6557 if (use_tmp_file)
6558 {
6559 char tempname[MAXPATHL + 1];
6560
6561 /*
6562 * Find a name that doesn't exist and is in the same directory.
6563 * Rename "from" to "tempname" and then rename "tempname" to "to".
6564 */
6565 if (STRLEN(from) >= MAXPATHL - 5)
6566 return -1;
6567 STRCPY(tempname, from);
6568 for (n = 123; n < 99999; ++n)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006569 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006570 sprintf((char *)gettail((char_u *)tempname), "%d", n);
6571 if (mch_stat(tempname, &st) < 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006572 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006573 if (mch_rename((char *)from, tempname) == 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006574 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006575 if (mch_rename(tempname, (char *)to) == 0)
6576 return 0;
6577 /* Strange, the second step failed. Try moving the
6578 * file back and return failure. */
6579 mch_rename(tempname, (char *)from);
Bram Moolenaar3576da72008-12-30 15:15:57 +00006580 return -1;
6581 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006582 /* If it fails for one temp name it will most likely fail
6583 * for any temp name, give up. */
6584 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006585 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006586 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006587 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006588 }
6589#endif
6590
Bram Moolenaar071d4272004-06-13 20:20:40 +00006591 /*
6592 * Delete the "to" file, this is required on some systems to make the
6593 * mch_rename() work, on other systems it makes sure that we don't have
6594 * two files when the mch_rename() fails.
6595 */
6596
6597#ifdef AMIGA
6598 /*
6599 * With MSDOS-compatible filesystems (crossdos, messydos) it is possible
6600 * that the name of the "to" file is the same as the "from" file, even
Bram Moolenaar7263a772007-05-10 17:35:54 +00006601 * though the names are different. To avoid the chance of accidentally
Bram Moolenaar071d4272004-06-13 20:20:40 +00006602 * deleting the "from" file (horror!) we lock it during the remove.
6603 *
6604 * When used for making a backup before writing the file: This should not
6605 * happen with ":w", because startscript() should detect this problem and
6606 * set buf->b_shortname, causing modname() to return a correct ".bak" file
6607 * name. This problem does exist with ":w filename", but then the
6608 * original file will be somewhere else so the backup isn't really
6609 * important. If autoscripting is off the rename may fail.
6610 */
6611 flock = Lock((UBYTE *)from, (long)ACCESS_READ);
6612#endif
6613 mch_remove(to);
6614#ifdef AMIGA
6615 if (flock)
6616 UnLock(flock);
6617#endif
6618
6619 /*
6620 * First try a normal rename, return if it works.
6621 */
6622 if (mch_rename((char *)from, (char *)to) == 0)
6623 return 0;
6624
6625 /*
6626 * Rename() failed, try copying the file.
6627 */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006628 perm = mch_getperm(from);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006629#ifdef HAVE_ACL
6630 /* For systems that support ACL: get the ACL from the original file. */
6631 acl = mch_get_acl(from);
6632#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006633 fd_in = mch_open((char *)from, O_RDONLY|O_EXTRA, 0);
6634 if (fd_in == -1)
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006635 {
6636#ifdef HAVE_ACL
6637 mch_free_acl(acl);
6638#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006639 return -1;
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006640 }
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006641
6642 /* Create the new file with same permissions as the original. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00006643 fd_out = mch_open((char *)to,
6644 O_CREAT|O_EXCL|O_WRONLY|O_EXTRA|O_NOFOLLOW, (int)perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006645 if (fd_out == -1)
6646 {
6647 close(fd_in);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006648#ifdef HAVE_ACL
6649 mch_free_acl(acl);
6650#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006651 return -1;
6652 }
6653
6654 buffer = (char *)alloc(BUFSIZE);
6655 if (buffer == NULL)
6656 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006657 close(fd_out);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006658 close(fd_in);
6659#ifdef HAVE_ACL
6660 mch_free_acl(acl);
6661#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006662 return -1;
6663 }
6664
6665 while ((n = vim_read(fd_in, buffer, BUFSIZE)) > 0)
6666 if (vim_write(fd_out, buffer, n) != n)
6667 {
6668 errmsg = _("E208: Error writing to \"%s\"");
6669 break;
6670 }
6671
6672 vim_free(buffer);
6673 close(fd_in);
6674 if (close(fd_out) < 0)
6675 errmsg = _("E209: Error closing \"%s\"");
6676 if (n < 0)
6677 {
6678 errmsg = _("E210: Error reading \"%s\"");
6679 to = from;
6680 }
Bram Moolenaar7263a772007-05-10 17:35:54 +00006681#ifndef UNIX /* for Unix mch_open() already set the permission */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006682 mch_setperm(to, perm);
Bram Moolenaarc6039d82005-12-02 00:44:04 +00006683#endif
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006684#ifdef HAVE_ACL
6685 mch_set_acl(to, acl);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006686 mch_free_acl(acl);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006687#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006688 if (errmsg != NULL)
6689 {
6690 EMSG2(errmsg, to);
6691 return -1;
6692 }
6693 mch_remove(from);
6694 return 0;
6695}
6696
6697static int already_warned = FALSE;
6698
6699/*
6700 * Check if any not hidden buffer has been changed.
6701 * Postpone the check if there are characters in the stuff buffer, a global
6702 * command is being executed, a mapping is being executed or an autocommand is
6703 * busy.
6704 * Returns TRUE if some message was written (screen should be redrawn and
6705 * cursor positioned).
6706 */
6707 int
6708check_timestamps(focus)
6709 int focus; /* called for GUI focus event */
6710{
6711 buf_T *buf;
6712 int didit = 0;
6713 int n;
6714
6715 /* Don't check timestamps while system() or another low-level function may
6716 * cause us to lose and gain focus. */
6717 if (no_check_timestamps > 0)
6718 return FALSE;
6719
6720 /* Avoid doing a check twice. The OK/Reload dialog can cause a focus
6721 * event and we would keep on checking if the file is steadily growing.
6722 * Do check again after typing something. */
6723 if (focus && did_check_timestamps)
6724 {
6725 need_check_timestamps = TRUE;
6726 return FALSE;
6727 }
6728
6729 if (!stuff_empty() || global_busy || !typebuf_typed()
6730#ifdef FEAT_AUTOCMD
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006731 || autocmd_busy || curbuf_lock > 0 || allbuf_lock > 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00006732#endif
6733 )
6734 need_check_timestamps = TRUE; /* check later */
6735 else
6736 {
6737 ++no_wait_return;
6738 did_check_timestamps = TRUE;
6739 already_warned = FALSE;
6740 for (buf = firstbuf; buf != NULL; )
6741 {
6742 /* Only check buffers in a window. */
6743 if (buf->b_nwindows > 0)
6744 {
6745 n = buf_check_timestamp(buf, focus);
6746 if (didit < n)
6747 didit = n;
6748 if (n > 0 && !buf_valid(buf))
6749 {
6750 /* Autocommands have removed the buffer, start at the
6751 * first one again. */
6752 buf = firstbuf;
6753 continue;
6754 }
6755 }
6756 buf = buf->b_next;
6757 }
6758 --no_wait_return;
6759 need_check_timestamps = FALSE;
6760 if (need_wait_return && didit == 2)
6761 {
6762 /* make sure msg isn't overwritten */
6763 msg_puts((char_u *)"\n");
6764 out_flush();
6765 }
6766 }
6767 return didit;
6768}
6769
6770/*
6771 * Move all the lines from buffer "frombuf" to buffer "tobuf".
6772 * Return OK or FAIL. When FAIL "tobuf" is incomplete and/or "frombuf" is not
6773 * empty.
6774 */
6775 static int
6776move_lines(frombuf, tobuf)
6777 buf_T *frombuf;
6778 buf_T *tobuf;
6779{
6780 buf_T *tbuf = curbuf;
6781 int retval = OK;
6782 linenr_T lnum;
6783 char_u *p;
6784
6785 /* Copy the lines in "frombuf" to "tobuf". */
6786 curbuf = tobuf;
6787 for (lnum = 1; lnum <= frombuf->b_ml.ml_line_count; ++lnum)
6788 {
6789 p = vim_strsave(ml_get_buf(frombuf, lnum, FALSE));
6790 if (p == NULL || ml_append(lnum - 1, p, 0, FALSE) == FAIL)
6791 {
6792 vim_free(p);
6793 retval = FAIL;
6794 break;
6795 }
6796 vim_free(p);
6797 }
6798
6799 /* Delete all the lines in "frombuf". */
6800 if (retval != FAIL)
6801 {
6802 curbuf = frombuf;
Bram Moolenaar9460b9d2007-01-09 14:37:01 +00006803 for (lnum = curbuf->b_ml.ml_line_count; lnum > 0; --lnum)
6804 if (ml_delete(lnum, FALSE) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006805 {
6806 /* Oops! We could try putting back the saved lines, but that
6807 * might fail again... */
6808 retval = FAIL;
6809 break;
6810 }
6811 }
6812
6813 curbuf = tbuf;
6814 return retval;
6815}
6816
6817/*
6818 * Check if buffer "buf" has been changed.
6819 * Also check if the file for a new buffer unexpectedly appeared.
6820 * return 1 if a changed buffer was found.
6821 * return 2 if a message has been displayed.
6822 * return 0 otherwise.
6823 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006824 int
6825buf_check_timestamp(buf, focus)
6826 buf_T *buf;
Bram Moolenaar78a15312009-05-15 19:33:18 +00006827 int focus UNUSED; /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006828{
6829 struct stat st;
6830 int stat_res;
6831 int retval = 0;
6832 char_u *path;
6833 char_u *tbuf;
6834 char *mesg = NULL;
Bram Moolenaar44ecf652005-03-07 23:09:59 +00006835 char *mesg2 = "";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006836 int helpmesg = FALSE;
6837 int reload = FALSE;
6838#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6839 int can_reload = FALSE;
6840#endif
Bram Moolenaar914703b2010-05-31 21:59:46 +02006841 off_t orig_size = buf->b_orig_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006842 int orig_mode = buf->b_orig_mode;
6843#ifdef FEAT_GUI
6844 int save_mouse_correct = need_mouse_correct;
6845#endif
6846#ifdef FEAT_AUTOCMD
6847 static int busy = FALSE;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006848 int n;
6849 char_u *s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006850#endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006851 char *reason;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006852
6853 /* If there is no file name, the buffer is not loaded, 'buftype' is
6854 * set, we are in the middle of a save or being called recursively: ignore
6855 * this buffer. */
6856 if (buf->b_ffname == NULL
6857 || buf->b_ml.ml_mfp == NULL
6858#if defined(FEAT_QUICKFIX)
6859 || *buf->b_p_bt != NUL
6860#endif
6861 || buf->b_saving
6862#ifdef FEAT_AUTOCMD
6863 || busy
6864#endif
Bram Moolenaar009b2592004-10-24 19:18:58 +00006865#ifdef FEAT_NETBEANS_INTG
6866 || isNetbeansBuffer(buf)
6867#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006868 )
6869 return 0;
6870
6871 if ( !(buf->b_flags & BF_NOTEDITED)
6872 && buf->b_mtime != 0
6873 && ((stat_res = mch_stat((char *)buf->b_ffname, &st)) < 0
6874 || time_differs((long)st.st_mtime, buf->b_mtime)
6875#ifdef HAVE_ST_MODE
6876 || (int)st.st_mode != buf->b_orig_mode
6877#else
6878 || mch_getperm(buf->b_ffname) != buf->b_orig_mode
6879#endif
6880 ))
6881 {
6882 retval = 1;
6883
Bram Moolenaar316059c2006-01-14 21:18:42 +00006884 /* set b_mtime to stop further warnings (e.g., when executing
6885 * FileChangedShell autocmd) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006886 if (stat_res < 0)
6887 {
6888 buf->b_mtime = 0;
6889 buf->b_orig_size = 0;
6890 buf->b_orig_mode = 0;
6891 }
6892 else
6893 buf_store_time(buf, &st, buf->b_ffname);
6894
6895 /* Don't do anything for a directory. Might contain the file
6896 * explorer. */
6897 if (mch_isdir(buf->b_fname))
6898 ;
6899
6900 /*
6901 * If 'autoread' is set, the buffer has no changes and the file still
6902 * exists, reload the buffer. Use the buffer-local option value if it
6903 * was set, the global option value otherwise.
6904 */
6905 else if ((buf->b_p_ar >= 0 ? buf->b_p_ar : p_ar)
6906 && !bufIsChanged(buf) && stat_res >= 0)
6907 reload = TRUE;
6908 else
6909 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006910 if (stat_res < 0)
6911 reason = "deleted";
6912 else if (bufIsChanged(buf))
6913 reason = "conflict";
6914 else if (orig_size != buf->b_orig_size || buf_contents_changed(buf))
6915 reason = "changed";
6916 else if (orig_mode != buf->b_orig_mode)
6917 reason = "mode";
6918 else
6919 reason = "time";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006920
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006921#ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006922 /*
6923 * Only give the warning if there are no FileChangedShell
6924 * autocommands.
6925 * Avoid being called recursively by setting "busy".
6926 */
6927 busy = TRUE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00006928# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006929 set_vim_var_string(VV_FCS_REASON, (char_u *)reason, -1);
6930 set_vim_var_string(VV_FCS_CHOICE, (char_u *)"", -1);
Bram Moolenaar1e015462005-09-25 22:16:38 +00006931# endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006932 ++allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006933 n = apply_autocmds(EVENT_FILECHANGEDSHELL,
6934 buf->b_fname, buf->b_fname, FALSE, buf);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006935 --allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006936 busy = FALSE;
6937 if (n)
6938 {
6939 if (!buf_valid(buf))
6940 EMSG(_("E246: FileChangedShell autocommand deleted buffer"));
Bram Moolenaar1e015462005-09-25 22:16:38 +00006941# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006942 s = get_vim_var_str(VV_FCS_CHOICE);
6943 if (STRCMP(s, "reload") == 0 && *reason != 'd')
6944 reload = TRUE;
6945 else if (STRCMP(s, "ask") == 0)
6946 n = FALSE;
6947 else
Bram Moolenaar1e015462005-09-25 22:16:38 +00006948# endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006949 return 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006950 }
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006951 if (!n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006952#endif
6953 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006954 if (*reason == 'd')
6955 mesg = _("E211: File \"%s\" no longer available");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006956 else
6957 {
6958 helpmesg = TRUE;
6959#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6960 can_reload = TRUE;
6961#endif
6962 /*
6963 * Check if the file contents really changed to avoid
6964 * giving a warning when only the timestamp was set (e.g.,
6965 * checked out of CVS). Always warn when the buffer was
6966 * changed.
6967 */
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006968 if (reason[2] == 'n')
6969 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006970 mesg = _("W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006971 mesg2 = _("See \":help W12\" for more info.");
6972 }
6973 else if (reason[1] == 'h')
6974 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006975 mesg = _("W11: Warning: File \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006976 mesg2 = _("See \":help W11\" for more info.");
6977 }
6978 else if (*reason == 'm')
6979 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006980 mesg = _("W16: Warning: Mode of file \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006981 mesg2 = _("See \":help W16\" for more info.");
6982 }
Bram Moolenaar85388b52009-06-24 09:58:32 +00006983 else
6984 /* Only timestamp changed, store it to avoid a warning
6985 * in check_mtime() later. */
6986 buf->b_mtime_read = buf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006987 }
6988 }
6989 }
6990
6991 }
6992 else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W)
6993 && vim_fexists(buf->b_ffname))
6994 {
6995 retval = 1;
6996 mesg = _("W13: Warning: File \"%s\" has been created after editing started");
6997 buf->b_flags |= BF_NEW_W;
6998#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6999 can_reload = TRUE;
7000#endif
7001 }
7002
7003 if (mesg != NULL)
7004 {
7005 path = home_replace_save(buf, buf->b_fname);
7006 if (path != NULL)
7007 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007008 if (!helpmesg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007009 mesg2 = "";
7010 tbuf = alloc((unsigned)(STRLEN(path) + STRLEN(mesg)
7011 + STRLEN(mesg2) + 2));
7012 sprintf((char *)tbuf, mesg, path);
Bram Moolenaar496c5262009-03-18 14:42:00 +00007013#ifdef FEAT_EVAL
7014 /* Set warningmsg here, before the unimportant and output-specific
7015 * mesg2 has been appended. */
7016 set_vim_var_string(VV_WARNINGMSG, tbuf, -1);
7017#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007018#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
7019 if (can_reload)
7020 {
7021 if (*mesg2 != NUL)
7022 {
7023 STRCAT(tbuf, "\n");
7024 STRCAT(tbuf, mesg2);
7025 }
7026 if (do_dialog(VIM_WARNING, (char_u *)_("Warning"), tbuf,
7027 (char_u *)_("&OK\n&Load File"), 1, NULL) == 2)
7028 reload = TRUE;
7029 }
7030 else
7031#endif
7032 if (State > NORMAL_BUSY || (State & CMDLINE) || already_warned)
7033 {
7034 if (*mesg2 != NUL)
7035 {
7036 STRCAT(tbuf, "; ");
7037 STRCAT(tbuf, mesg2);
7038 }
7039 EMSG(tbuf);
7040 retval = 2;
7041 }
7042 else
7043 {
Bram Moolenaared203462004-06-16 11:19:22 +00007044# ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00007045 if (!autocmd_busy)
Bram Moolenaared203462004-06-16 11:19:22 +00007046# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007047 {
7048 msg_start();
7049 msg_puts_attr(tbuf, hl_attr(HLF_E) + MSG_HIST);
7050 if (*mesg2 != NUL)
7051 msg_puts_attr((char_u *)mesg2,
7052 hl_attr(HLF_W) + MSG_HIST);
7053 msg_clr_eos();
7054 (void)msg_end();
7055 if (emsg_silent == 0)
7056 {
7057 out_flush();
Bram Moolenaared203462004-06-16 11:19:22 +00007058# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00007059 if (!focus)
Bram Moolenaared203462004-06-16 11:19:22 +00007060# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007061 /* give the user some time to think about it */
7062 ui_delay(1000L, TRUE);
7063
7064 /* don't redraw and erase the message */
7065 redraw_cmdline = FALSE;
7066 }
7067 }
7068 already_warned = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007069 }
7070
7071 vim_free(path);
7072 vim_free(tbuf);
7073 }
7074 }
7075
7076 if (reload)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007077 /* Reload the buffer. */
Bram Moolenaar316059c2006-01-14 21:18:42 +00007078 buf_reload(buf, orig_mode);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007079
Bram Moolenaar56718732006-03-15 22:53:57 +00007080#ifdef FEAT_AUTOCMD
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00007081 /* Trigger FileChangedShell when the file was changed in any way. */
7082 if (buf_valid(buf) && retval != 0)
Bram Moolenaar56718732006-03-15 22:53:57 +00007083 (void)apply_autocmds(EVENT_FILECHANGEDSHELLPOST,
7084 buf->b_fname, buf->b_fname, FALSE, buf);
7085#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007086#ifdef FEAT_GUI
7087 /* restore this in case an autocommand has set it; it would break
7088 * 'mousefocus' */
7089 need_mouse_correct = save_mouse_correct;
7090#endif
7091
7092 return retval;
7093}
7094
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007095/*
7096 * Reload a buffer that is already loaded.
7097 * Used when the file was changed outside of Vim.
Bram Moolenaar316059c2006-01-14 21:18:42 +00007098 * "orig_mode" is buf->b_orig_mode before the need for reloading was detected.
7099 * buf->b_orig_mode may have been reset already.
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007100 */
7101 void
Bram Moolenaar316059c2006-01-14 21:18:42 +00007102buf_reload(buf, orig_mode)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007103 buf_T *buf;
Bram Moolenaar316059c2006-01-14 21:18:42 +00007104 int orig_mode;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007105{
7106 exarg_T ea;
7107 pos_T old_cursor;
7108 linenr_T old_topline;
7109 int old_ro = buf->b_p_ro;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007110 buf_T *savebuf;
7111 int saved = OK;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007112 aco_save_T aco;
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007113 int flags = READ_NEW;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007114
7115 /* set curwin/curbuf for "buf" and save some things */
7116 aucmd_prepbuf(&aco, buf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007117
7118 /* We only want to read the text from the file, not reset the syntax
7119 * highlighting, clear marks, diff status, etc. Force the fileformat
7120 * and encoding to be the same. */
7121 if (prep_exarg(&ea, buf) == OK)
7122 {
7123 old_cursor = curwin->w_cursor;
7124 old_topline = curwin->w_topline;
7125
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007126 if (p_ur < 0 || curbuf->b_ml.ml_line_count <= p_ur)
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007127 {
7128 /* Save all the text, so that the reload can be undone.
7129 * Sync first so that this is a separate undo-able action. */
7130 u_sync(FALSE);
7131 saved = u_savecommon(0, curbuf->b_ml.ml_line_count + 1, 0, TRUE);
7132 flags |= READ_KEEP_UNDO;
7133 }
7134
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007135 /*
7136 * To behave like when a new file is edited (matters for
7137 * BufReadPost autocommands) we first need to delete the current
7138 * buffer contents. But if reading the file fails we should keep
7139 * the old contents. Can't use memory only, the file might be
7140 * too big. Use a hidden buffer to move the buffer contents to.
7141 */
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007142 if (bufempty() || saved == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007143 savebuf = NULL;
7144 else
7145 {
7146 /* Allocate a buffer without putting it in the buffer list. */
7147 savebuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007148 if (savebuf != NULL && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007149 {
7150 /* Open the memline. */
7151 curbuf = savebuf;
7152 curwin->w_buffer = savebuf;
Bram Moolenaar4770d092006-01-12 23:22:24 +00007153 saved = ml_open(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007154 curbuf = buf;
7155 curwin->w_buffer = buf;
7156 }
Bram Moolenaar8424a622006-04-19 21:23:36 +00007157 if (savebuf == NULL || saved == FAIL || buf != curbuf
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007158 || move_lines(buf, savebuf) == FAIL)
7159 {
7160 EMSG2(_("E462: Could not prepare for reloading \"%s\""),
7161 buf->b_fname);
7162 saved = FAIL;
7163 }
7164 }
7165
7166 if (saved == OK)
7167 {
7168 curbuf->b_flags |= BF_CHECK_RO; /* check for RO again */
7169#ifdef FEAT_AUTOCMD
7170 keep_filetype = TRUE; /* don't detect 'filetype' */
7171#endif
7172 if (readfile(buf->b_ffname, buf->b_fname, (linenr_T)0,
7173 (linenr_T)0,
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007174 (linenr_T)MAXLNUM, &ea, flags) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007175 {
7176#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
7177 if (!aborting())
7178#endif
7179 EMSG2(_("E321: Could not reload \"%s\""), buf->b_fname);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007180 if (savebuf != NULL && buf_valid(savebuf) && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007181 {
7182 /* Put the text back from the save buffer. First
7183 * delete any lines that readfile() added. */
7184 while (!bufempty())
Bram Moolenaar8424a622006-04-19 21:23:36 +00007185 if (ml_delete(buf->b_ml.ml_line_count, FALSE) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007186 break;
7187 (void)move_lines(savebuf, buf);
7188 }
7189 }
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007190 else if (buf == curbuf) /* "buf" still valid */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007191 {
7192 /* Mark the buffer as unmodified and free undo info. */
7193 unchanged(buf, TRUE);
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007194 if ((flags & READ_KEEP_UNDO) == 0)
7195 {
7196 u_blockfree(buf);
7197 u_clearall(buf);
7198 }
7199 else
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007200 {
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007201 /* Mark all undo states as changed. */
7202 u_unchanged(curbuf);
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007203 }
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007204 }
7205 }
7206 vim_free(ea.cmd);
7207
Bram Moolenaar8424a622006-04-19 21:23:36 +00007208 if (savebuf != NULL && buf_valid(savebuf))
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007209 wipe_buffer(savebuf, FALSE);
7210
7211#ifdef FEAT_DIFF
7212 /* Invalidate diff info if necessary. */
Bram Moolenaar8424a622006-04-19 21:23:36 +00007213 diff_invalidate(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007214#endif
7215
7216 /* Restore the topline and cursor position and check it (lines may
7217 * have been removed). */
7218 if (old_topline > curbuf->b_ml.ml_line_count)
7219 curwin->w_topline = curbuf->b_ml.ml_line_count;
7220 else
7221 curwin->w_topline = old_topline;
7222 curwin->w_cursor = old_cursor;
7223 check_cursor();
7224 update_topline();
7225#ifdef FEAT_AUTOCMD
7226 keep_filetype = FALSE;
7227#endif
7228#ifdef FEAT_FOLDING
7229 {
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007230 win_T *wp;
7231 tabpage_T *tp;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007232
7233 /* Update folds unless they are defined manually. */
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007234 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007235 if (wp->w_buffer == curwin->w_buffer
7236 && !foldmethodIsManual(wp))
7237 foldUpdateAll(wp);
7238 }
7239#endif
7240 /* If the mode didn't change and 'readonly' was set, keep the old
7241 * value; the user probably used the ":view" command. But don't
7242 * reset it, might have had a read error. */
7243 if (orig_mode == curbuf->b_orig_mode)
7244 curbuf->b_p_ro |= old_ro;
7245 }
7246
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007247 /* restore curwin/curbuf and a few other things */
7248 aucmd_restbuf(&aco);
7249 /* Careful: autocommands may have made "buf" invalid! */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007250}
7251
Bram Moolenaar071d4272004-06-13 20:20:40 +00007252 void
7253buf_store_time(buf, st, fname)
7254 buf_T *buf;
7255 struct stat *st;
Bram Moolenaar78a15312009-05-15 19:33:18 +00007256 char_u *fname UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007257{
7258 buf->b_mtime = (long)st->st_mtime;
Bram Moolenaar914703b2010-05-31 21:59:46 +02007259 buf->b_orig_size = st->st_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007260#ifdef HAVE_ST_MODE
7261 buf->b_orig_mode = (int)st->st_mode;
7262#else
7263 buf->b_orig_mode = mch_getperm(fname);
7264#endif
7265}
7266
7267/*
7268 * Adjust the line with missing eol, used for the next write.
7269 * Used for do_filter(), when the input lines for the filter are deleted.
7270 */
7271 void
7272write_lnum_adjust(offset)
7273 linenr_T offset;
7274{
Bram Moolenaardf177f62005-02-22 08:39:57 +00007275 if (write_no_eol_lnum != 0) /* only if there is a missing eol */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007276 write_no_eol_lnum += offset;
7277}
7278
7279#if defined(TEMPDIRNAMES) || defined(PROTO)
7280static long temp_count = 0; /* Temp filename counter. */
7281
7282/*
7283 * Delete the temp directory and all files it contains.
7284 */
7285 void
7286vim_deltempdir()
7287{
7288 char_u **files;
7289 int file_count;
7290 int i;
7291
7292 if (vim_tempdir != NULL)
7293 {
7294 sprintf((char *)NameBuff, "%s*", vim_tempdir);
7295 if (gen_expand_wildcards(1, &NameBuff, &file_count, &files,
7296 EW_DIR|EW_FILE|EW_SILENT) == OK)
7297 {
7298 for (i = 0; i < file_count; ++i)
7299 mch_remove(files[i]);
7300 FreeWild(file_count, files);
7301 }
7302 gettail(NameBuff)[-1] = NUL;
7303 (void)mch_rmdir(NameBuff);
7304
7305 vim_free(vim_tempdir);
7306 vim_tempdir = NULL;
7307 }
7308}
7309#endif
7310
Bram Moolenaar4592dee2009-11-18 19:11:58 +00007311#ifdef TEMPDIRNAMES
Bram Moolenaar071d4272004-06-13 20:20:40 +00007312/*
Bram Moolenaareaf03392009-11-17 11:08:52 +00007313 * Directory "tempdir" was created. Expand this name to a full path and put
7314 * it in "vim_tempdir". This avoids that using ":cd" would confuse us.
7315 * "tempdir" must be no longer than MAXPATHL.
7316 */
7317 static void
7318vim_settempdir(tempdir)
7319 char_u *tempdir;
7320{
7321 char_u *buf;
7322
7323 buf = alloc((unsigned)MAXPATHL + 2);
7324 if (buf != NULL)
7325 {
7326 if (vim_FullName(tempdir, buf, MAXPATHL, FALSE) == FAIL)
7327 STRCPY(buf, tempdir);
7328# ifdef __EMX__
7329 if (vim_strchr(buf, '/') != NULL)
7330 STRCAT(buf, "/");
7331 else
7332# endif
7333 add_pathsep(buf);
7334 vim_tempdir = vim_strsave(buf);
7335 vim_free(buf);
7336 }
7337}
Bram Moolenaar4592dee2009-11-18 19:11:58 +00007338#endif
Bram Moolenaareaf03392009-11-17 11:08:52 +00007339
7340/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007341 * vim_tempname(): Return a unique name that can be used for a temp file.
7342 *
7343 * The temp file is NOT created.
7344 *
7345 * The returned pointer is to allocated memory.
7346 * The returned pointer is NULL if no valid name was found.
7347 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007348 char_u *
7349vim_tempname(extra_char)
Bram Moolenaar78a15312009-05-15 19:33:18 +00007350 int extra_char UNUSED; /* char to use in the name instead of '?' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007351{
7352#ifdef USE_TMPNAM
7353 char_u itmp[L_tmpnam]; /* use tmpnam() */
7354#else
7355 char_u itmp[TEMPNAMELEN];
7356#endif
7357
7358#ifdef TEMPDIRNAMES
7359 static char *(tempdirs[]) = {TEMPDIRNAMES};
7360 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007361# ifndef EEXIST
7362 struct stat st;
7363# endif
7364
7365 /*
7366 * This will create a directory for private use by this instance of Vim.
7367 * This is done once, and the same directory is used for all temp files.
7368 * This method avoids security problems because of symlink attacks et al.
7369 * It's also a bit faster, because we only need to check for an existing
7370 * file when creating the directory and not for each temp file.
7371 */
7372 if (vim_tempdir == NULL)
7373 {
7374 /*
7375 * Try the entries in TEMPDIRNAMES to create the temp directory.
7376 */
Bram Moolenaar78a15312009-05-15 19:33:18 +00007377 for (i = 0; i < (int)(sizeof(tempdirs) / sizeof(char *)); ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007378 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007379# ifndef HAVE_MKDTEMP
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007380 size_t itmplen;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007381 long nr;
7382 long off;
7383# endif
7384
Bram Moolenaar071d4272004-06-13 20:20:40 +00007385 /* expand $TMP, leave room for "/v1100000/999999999" */
7386 expand_env((char_u *)tempdirs[i], itmp, TEMPNAMELEN - 20);
7387 if (mch_isdir(itmp)) /* directory exists */
7388 {
7389# ifdef __EMX__
7390 /* If $TMP contains a forward slash (perhaps using bash or
7391 * tcsh), don't add a backslash, use a forward slash!
7392 * Adding 2 backslashes didn't work. */
7393 if (vim_strchr(itmp, '/') != NULL)
7394 STRCAT(itmp, "/");
7395 else
7396# endif
7397 add_pathsep(itmp);
7398
Bram Moolenaareaf03392009-11-17 11:08:52 +00007399# ifdef HAVE_MKDTEMP
7400 /* Leave room for filename */
7401 STRCAT(itmp, "vXXXXXX");
7402 if (mkdtemp((char *)itmp) != NULL)
7403 vim_settempdir(itmp);
7404# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007405 /* Get an arbitrary number of up to 6 digits. When it's
7406 * unlikely that it already exists it will be faster,
7407 * otherwise it doesn't matter. The use of mkdir() avoids any
7408 * security problems because of the predictable number. */
7409 nr = (mch_get_pid() + (long)time(NULL)) % 1000000L;
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007410 itmplen = STRLEN(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007411
7412 /* Try up to 10000 different values until we find a name that
7413 * doesn't exist. */
7414 for (off = 0; off < 10000L; ++off)
7415 {
7416 int r;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007417# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007418 mode_t umask_save;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007419# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007420
Bram Moolenaareaf03392009-11-17 11:08:52 +00007421 sprintf((char *)itmp + itmplen, "v%ld", nr + off);
7422# ifndef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007423 /* If mkdir() does not set errno to EEXIST, check for
7424 * existing file here. There is a race condition then,
7425 * although it's fail-safe. */
7426 if (mch_stat((char *)itmp, &st) >= 0)
7427 continue;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007428# endif
7429# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007430 /* Make sure the umask doesn't remove the executable bit.
7431 * "repl" has been reported to use "177". */
7432 umask_save = umask(077);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007433# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007434 r = vim_mkdir(itmp, 0700);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007435# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007436 (void)umask(umask_save);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007437# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007438 if (r == 0)
7439 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007440 vim_settempdir(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007441 break;
7442 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007443# ifdef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007444 /* If the mkdir() didn't fail because the file/dir exists,
7445 * we probably can't create any dir here, try another
7446 * place. */
7447 if (errno != EEXIST)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007448# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007449 break;
7450 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007451# endif /* HAVE_MKDTEMP */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007452 if (vim_tempdir != NULL)
7453 break;
7454 }
7455 }
7456 }
7457
7458 if (vim_tempdir != NULL)
7459 {
7460 /* There is no need to check if the file exists, because we own the
7461 * directory and nobody else creates a file in it. */
7462 sprintf((char *)itmp, "%s%ld", vim_tempdir, temp_count++);
7463 return vim_strsave(itmp);
7464 }
7465
7466 return NULL;
7467
7468#else /* TEMPDIRNAMES */
7469
7470# ifdef WIN3264
7471 char szTempFile[_MAX_PATH + 1];
7472 char buf4[4];
7473 char_u *retval;
7474 char_u *p;
7475
7476 STRCPY(itmp, "");
7477 if (GetTempPath(_MAX_PATH, szTempFile) == 0)
7478 szTempFile[0] = NUL; /* GetTempPath() failed, use current dir */
7479 strcpy(buf4, "VIM");
7480 buf4[2] = extra_char; /* make it "VIa", "VIb", etc. */
7481 if (GetTempFileName(szTempFile, buf4, 0, itmp) == 0)
7482 return NULL;
7483 /* GetTempFileName() will create the file, we don't want that */
7484 (void)DeleteFile(itmp);
7485
7486 /* Backslashes in a temp file name cause problems when filtering with
7487 * "sh". NOTE: This also checks 'shellcmdflag' to help those people who
7488 * didn't set 'shellslash'. */
7489 retval = vim_strsave(itmp);
7490 if (*p_shcf == '-' || p_ssl)
7491 for (p = retval; *p; ++p)
7492 if (*p == '\\')
7493 *p = '/';
7494 return retval;
7495
7496# else /* WIN3264 */
7497
7498# ifdef USE_TMPNAM
7499 /* tmpnam() will make its own name */
7500 if (*tmpnam((char *)itmp) == NUL)
7501 return NULL;
7502# else
7503 char_u *p;
7504
7505# ifdef VMS_TEMPNAM
7506 /* mktemp() is not working on VMS. It seems to be
7507 * a do-nothing function. Therefore we use tempnam().
7508 */
7509 sprintf((char *)itmp, "VIM%c", extra_char);
7510 p = (char_u *)tempnam("tmp:", (char *)itmp);
7511 if (p != NULL)
7512 {
7513 /* VMS will use '.LOG' if we don't explicitly specify an extension,
7514 * and VIM will then be unable to find the file later */
7515 STRCPY(itmp, p);
7516 STRCAT(itmp, ".txt");
7517 free(p);
7518 }
7519 else
7520 return NULL;
7521# else
7522 STRCPY(itmp, TEMPNAME);
7523 if ((p = vim_strchr(itmp, '?')) != NULL)
7524 *p = extra_char;
7525 if (mktemp((char *)itmp) == NULL)
7526 return NULL;
7527# endif
7528# endif
7529
7530 return vim_strsave(itmp);
7531# endif /* WIN3264 */
7532#endif /* TEMPDIRNAMES */
7533}
7534
7535#if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
7536/*
7537 * Convert all backslashes in fname to forward slashes in-place.
7538 */
7539 void
7540forward_slash(fname)
7541 char_u *fname;
7542{
7543 char_u *p;
7544
7545 for (p = fname; *p != NUL; ++p)
7546# ifdef FEAT_MBYTE
7547 /* The Big5 encoding can have '\' in the trail byte. */
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00007548 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007549 ++p;
7550 else
7551# endif
7552 if (*p == '\\')
7553 *p = '/';
7554}
7555#endif
7556
7557
7558/*
7559 * Code for automatic commands.
7560 *
7561 * Only included when "FEAT_AUTOCMD" has been defined.
7562 */
7563
7564#if defined(FEAT_AUTOCMD) || defined(PROTO)
7565
7566/*
7567 * The autocommands are stored in a list for each event.
7568 * Autocommands for the same pattern, that are consecutive, are joined
7569 * together, to avoid having to match the pattern too often.
7570 * The result is an array of Autopat lists, which point to AutoCmd lists:
7571 *
7572 * first_autopat[0] --> Autopat.next --> Autopat.next --> NULL
7573 * Autopat.cmds Autopat.cmds
7574 * | |
7575 * V V
7576 * AutoCmd.next AutoCmd.next
7577 * | |
7578 * V V
7579 * AutoCmd.next NULL
7580 * |
7581 * V
7582 * NULL
7583 *
7584 * first_autopat[1] --> Autopat.next --> NULL
7585 * Autopat.cmds
7586 * |
7587 * V
7588 * AutoCmd.next
7589 * |
7590 * V
7591 * NULL
7592 * etc.
7593 *
7594 * The order of AutoCmds is important, this is the order in which they were
7595 * defined and will have to be executed.
7596 */
7597typedef struct AutoCmd
7598{
7599 char_u *cmd; /* The command to be executed (NULL
7600 when command has been removed) */
7601 char nested; /* If autocommands nest here */
7602 char last; /* last command in list */
7603#ifdef FEAT_EVAL
7604 scid_T scriptID; /* script ID where defined */
7605#endif
7606 struct AutoCmd *next; /* Next AutoCmd in list */
7607} AutoCmd;
7608
7609typedef struct AutoPat
7610{
7611 int group; /* group ID */
7612 char_u *pat; /* pattern as typed (NULL when pattern
7613 has been removed) */
7614 int patlen; /* strlen() of pat */
Bram Moolenaar748bf032005-02-02 23:04:36 +00007615 regprog_T *reg_prog; /* compiled regprog for pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007616 char allow_dirs; /* Pattern may match whole path */
7617 char last; /* last pattern for apply_autocmds() */
7618 AutoCmd *cmds; /* list of commands to do */
7619 struct AutoPat *next; /* next AutoPat in AutoPat list */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007620 int buflocal_nr; /* !=0 for buffer-local AutoPat */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007621} AutoPat;
7622
7623static struct event_name
7624{
7625 char *name; /* event name */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007626 event_T event; /* event number */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007627} event_names[] =
7628{
7629 {"BufAdd", EVENT_BUFADD},
7630 {"BufCreate", EVENT_BUFADD},
7631 {"BufDelete", EVENT_BUFDELETE},
7632 {"BufEnter", EVENT_BUFENTER},
7633 {"BufFilePost", EVENT_BUFFILEPOST},
7634 {"BufFilePre", EVENT_BUFFILEPRE},
7635 {"BufHidden", EVENT_BUFHIDDEN},
7636 {"BufLeave", EVENT_BUFLEAVE},
7637 {"BufNew", EVENT_BUFNEW},
7638 {"BufNewFile", EVENT_BUFNEWFILE},
7639 {"BufRead", EVENT_BUFREADPOST},
7640 {"BufReadCmd", EVENT_BUFREADCMD},
7641 {"BufReadPost", EVENT_BUFREADPOST},
7642 {"BufReadPre", EVENT_BUFREADPRE},
7643 {"BufUnload", EVENT_BUFUNLOAD},
7644 {"BufWinEnter", EVENT_BUFWINENTER},
7645 {"BufWinLeave", EVENT_BUFWINLEAVE},
7646 {"BufWipeout", EVENT_BUFWIPEOUT},
7647 {"BufWrite", EVENT_BUFWRITEPRE},
7648 {"BufWritePost", EVENT_BUFWRITEPOST},
7649 {"BufWritePre", EVENT_BUFWRITEPRE},
7650 {"BufWriteCmd", EVENT_BUFWRITECMD},
7651 {"CmdwinEnter", EVENT_CMDWINENTER},
7652 {"CmdwinLeave", EVENT_CMDWINLEAVE},
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007653 {"ColorScheme", EVENT_COLORSCHEME},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007654 {"CursorHold", EVENT_CURSORHOLD},
7655 {"CursorHoldI", EVENT_CURSORHOLDI},
7656 {"CursorMoved", EVENT_CURSORMOVED},
7657 {"CursorMovedI", EVENT_CURSORMOVEDI},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007658 {"EncodingChanged", EVENT_ENCODINGCHANGED},
7659 {"FileEncoding", EVENT_ENCODINGCHANGED},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007660 {"FileAppendPost", EVENT_FILEAPPENDPOST},
7661 {"FileAppendPre", EVENT_FILEAPPENDPRE},
7662 {"FileAppendCmd", EVENT_FILEAPPENDCMD},
7663 {"FileChangedShell",EVENT_FILECHANGEDSHELL},
Bram Moolenaar56718732006-03-15 22:53:57 +00007664 {"FileChangedShellPost",EVENT_FILECHANGEDSHELLPOST},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007665 {"FileChangedRO", EVENT_FILECHANGEDRO},
7666 {"FileReadPost", EVENT_FILEREADPOST},
7667 {"FileReadPre", EVENT_FILEREADPRE},
7668 {"FileReadCmd", EVENT_FILEREADCMD},
7669 {"FileType", EVENT_FILETYPE},
7670 {"FileWritePost", EVENT_FILEWRITEPOST},
7671 {"FileWritePre", EVENT_FILEWRITEPRE},
7672 {"FileWriteCmd", EVENT_FILEWRITECMD},
7673 {"FilterReadPost", EVENT_FILTERREADPOST},
7674 {"FilterReadPre", EVENT_FILTERREADPRE},
7675 {"FilterWritePost", EVENT_FILTERWRITEPOST},
7676 {"FilterWritePre", EVENT_FILTERWRITEPRE},
7677 {"FocusGained", EVENT_FOCUSGAINED},
7678 {"FocusLost", EVENT_FOCUSLOST},
7679 {"FuncUndefined", EVENT_FUNCUNDEFINED},
7680 {"GUIEnter", EVENT_GUIENTER},
Bram Moolenaar265e5072006-08-29 16:13:22 +00007681 {"GUIFailed", EVENT_GUIFAILED},
Bram Moolenaar843ee412004-06-30 16:16:41 +00007682 {"InsertChange", EVENT_INSERTCHANGE},
7683 {"InsertEnter", EVENT_INSERTENTER},
7684 {"InsertLeave", EVENT_INSERTLEAVE},
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00007685 {"MenuPopup", EVENT_MENUPOPUP},
Bram Moolenaar7c626922005-02-07 22:01:03 +00007686 {"QuickFixCmdPost", EVENT_QUICKFIXCMDPOST},
7687 {"QuickFixCmdPre", EVENT_QUICKFIXCMDPRE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007688 {"RemoteReply", EVENT_REMOTEREPLY},
Bram Moolenaar9372a112005-12-06 19:59:18 +00007689 {"SessionLoadPost", EVENT_SESSIONLOADPOST},
Bram Moolenaar5c4bab02006-03-10 21:37:46 +00007690 {"ShellCmdPost", EVENT_SHELLCMDPOST},
7691 {"ShellFilterPost", EVENT_SHELLFILTERPOST},
Bram Moolenaara2031822006-03-07 22:29:51 +00007692 {"SourcePre", EVENT_SOURCEPRE},
Bram Moolenaar8dd1aa52007-01-16 20:33:19 +00007693 {"SourceCmd", EVENT_SOURCECMD},
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00007694 {"SpellFileMissing",EVENT_SPELLFILEMISSING},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007695 {"StdinReadPost", EVENT_STDINREADPOST},
7696 {"StdinReadPre", EVENT_STDINREADPRE},
Bram Moolenaarb815dac2005-12-07 20:59:24 +00007697 {"SwapExists", EVENT_SWAPEXISTS},
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00007698 {"Syntax", EVENT_SYNTAX},
Bram Moolenaar70836c82006-02-20 21:28:49 +00007699 {"TabEnter", EVENT_TABENTER},
7700 {"TabLeave", EVENT_TABLEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007701 {"TermChanged", EVENT_TERMCHANGED},
7702 {"TermResponse", EVENT_TERMRESPONSE},
7703 {"User", EVENT_USER},
7704 {"VimEnter", EVENT_VIMENTER},
7705 {"VimLeave", EVENT_VIMLEAVE},
7706 {"VimLeavePre", EVENT_VIMLEAVEPRE},
7707 {"WinEnter", EVENT_WINENTER},
7708 {"WinLeave", EVENT_WINLEAVE},
Bram Moolenaar56718732006-03-15 22:53:57 +00007709 {"VimResized", EVENT_VIMRESIZED},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007710 {NULL, (event_T)0}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007711};
7712
7713static AutoPat *first_autopat[NUM_EVENTS] =
7714{
7715 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7716 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7717 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7718 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00007719 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7720 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007721};
7722
7723/*
7724 * struct used to keep status while executing autocommands for an event.
7725 */
7726typedef struct AutoPatCmd
7727{
7728 AutoPat *curpat; /* next AutoPat to examine */
7729 AutoCmd *nextcmd; /* next AutoCmd to execute */
7730 int group; /* group being used */
7731 char_u *fname; /* fname to match with */
7732 char_u *sfname; /* sfname to match with */
7733 char_u *tail; /* tail of fname */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007734 event_T event; /* current event */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007735 int arg_bufnr; /* initially equal to <abuf>, set to zero when
7736 buf is deleted */
7737 struct AutoPatCmd *next; /* chain of active apc-s for auto-invalidation*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00007738} AutoPatCmd;
7739
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007740static AutoPatCmd *active_apc_list = NULL; /* stack of active autocommands */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007741
Bram Moolenaar071d4272004-06-13 20:20:40 +00007742/*
7743 * augroups stores a list of autocmd group names.
7744 */
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007745static garray_T augroups = {0, 0, sizeof(char_u *), 10, NULL};
Bram Moolenaar071d4272004-06-13 20:20:40 +00007746#define AUGROUP_NAME(i) (((char_u **)augroups.ga_data)[i])
7747
7748/*
7749 * The ID of the current group. Group 0 is the default one.
7750 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007751static int current_augroup = AUGROUP_DEFAULT;
7752
7753static int au_need_clean = FALSE; /* need to delete marked patterns */
7754
Bram Moolenaar754b5602006-02-09 23:53:20 +00007755static void show_autocmd __ARGS((AutoPat *ap, event_T event));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007756static void au_remove_pat __ARGS((AutoPat *ap));
7757static void au_remove_cmds __ARGS((AutoPat *ap));
7758static void au_cleanup __ARGS((void));
7759static int au_new_group __ARGS((char_u *name));
7760static void au_del_group __ARGS((char_u *name));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007761static event_T event_name2nr __ARGS((char_u *start, char_u **end));
7762static char_u *event_nr2name __ARGS((event_T event));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007763static char_u *find_end_event __ARGS((char_u *arg, int have_group));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007764static int event_ignored __ARGS((event_T event));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007765static int au_get_grouparg __ARGS((char_u **argp));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007766static 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 +00007767static char_u *getnextac __ARGS((int c, void *cookie, int indent));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007768static 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 +00007769static void auto_next_pat __ARGS((AutoPatCmd *apc, int stop_at_last));
7770
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007771
Bram Moolenaar754b5602006-02-09 23:53:20 +00007772static event_T last_event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007773static int last_group;
Bram Moolenaar78ab3312007-09-29 12:16:41 +00007774static int autocmd_blocked = 0; /* block all autocmds */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007775
7776/*
7777 * Show the autocommands for one AutoPat.
7778 */
7779 static void
7780show_autocmd(ap, event)
7781 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007782 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007783{
7784 AutoCmd *ac;
7785
7786 /* Check for "got_int" (here and at various places below), which is set
7787 * when "q" has been hit for the "--more--" prompt */
7788 if (got_int)
7789 return;
7790 if (ap->pat == NULL) /* pattern has been removed */
7791 return;
7792
7793 msg_putchar('\n');
7794 if (got_int)
7795 return;
7796 if (event != last_event || ap->group != last_group)
7797 {
7798 if (ap->group != AUGROUP_DEFAULT)
7799 {
7800 if (AUGROUP_NAME(ap->group) == NULL)
7801 msg_puts_attr((char_u *)_("--Deleted--"), hl_attr(HLF_E));
7802 else
7803 msg_puts_attr(AUGROUP_NAME(ap->group), hl_attr(HLF_T));
7804 msg_puts((char_u *)" ");
7805 }
7806 msg_puts_attr(event_nr2name(event), hl_attr(HLF_T));
7807 last_event = event;
7808 last_group = ap->group;
7809 msg_putchar('\n');
7810 if (got_int)
7811 return;
7812 }
7813 msg_col = 4;
7814 msg_outtrans(ap->pat);
7815
7816 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7817 {
7818 if (ac->cmd != NULL) /* skip removed commands */
7819 {
7820 if (msg_col >= 14)
7821 msg_putchar('\n');
7822 msg_col = 14;
7823 if (got_int)
7824 return;
7825 msg_outtrans(ac->cmd);
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00007826#ifdef FEAT_EVAL
7827 if (p_verbose > 0)
7828 last_set_msg(ac->scriptID);
7829#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007830 if (got_int)
7831 return;
7832 if (ac->next != NULL)
7833 {
7834 msg_putchar('\n');
7835 if (got_int)
7836 return;
7837 }
7838 }
7839 }
7840}
7841
7842/*
7843 * Mark an autocommand pattern for deletion.
7844 */
7845 static void
7846au_remove_pat(ap)
7847 AutoPat *ap;
7848{
7849 vim_free(ap->pat);
7850 ap->pat = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007851 ap->buflocal_nr = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007852 au_need_clean = TRUE;
7853}
7854
7855/*
7856 * Mark all commands for a pattern for deletion.
7857 */
7858 static void
7859au_remove_cmds(ap)
7860 AutoPat *ap;
7861{
7862 AutoCmd *ac;
7863
7864 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7865 {
7866 vim_free(ac->cmd);
7867 ac->cmd = NULL;
7868 }
7869 au_need_clean = TRUE;
7870}
7871
7872/*
7873 * Cleanup autocommands and patterns that have been deleted.
7874 * This is only done when not executing autocommands.
7875 */
7876 static void
7877au_cleanup()
7878{
7879 AutoPat *ap, **prev_ap;
7880 AutoCmd *ac, **prev_ac;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007881 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007882
7883 if (autocmd_busy || !au_need_clean)
7884 return;
7885
7886 /* loop over all events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007887 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7888 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007889 {
7890 /* loop over all autocommand patterns */
7891 prev_ap = &(first_autopat[(int)event]);
7892 for (ap = *prev_ap; ap != NULL; ap = *prev_ap)
7893 {
7894 /* loop over all commands for this pattern */
7895 prev_ac = &(ap->cmds);
7896 for (ac = *prev_ac; ac != NULL; ac = *prev_ac)
7897 {
7898 /* remove the command if the pattern is to be deleted or when
7899 * the command has been marked for deletion */
7900 if (ap->pat == NULL || ac->cmd == NULL)
7901 {
7902 *prev_ac = ac->next;
7903 vim_free(ac->cmd);
7904 vim_free(ac);
7905 }
7906 else
7907 prev_ac = &(ac->next);
7908 }
7909
7910 /* remove the pattern if it has been marked for deletion */
7911 if (ap->pat == NULL)
7912 {
7913 *prev_ap = ap->next;
Bram Moolenaar748bf032005-02-02 23:04:36 +00007914 vim_free(ap->reg_prog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007915 vim_free(ap);
7916 }
7917 else
7918 prev_ap = &(ap->next);
7919 }
7920 }
7921
7922 au_need_clean = FALSE;
7923}
7924
7925/*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007926 * Called when buffer is freed, to remove/invalidate related buffer-local
7927 * autocmds.
7928 */
7929 void
7930aubuflocal_remove(buf)
7931 buf_T *buf;
7932{
7933 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007934 event_T event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007935 AutoPatCmd *apc;
7936
7937 /* invalidate currently executing autocommands */
7938 for (apc = active_apc_list; apc; apc = apc->next)
7939 if (buf->b_fnum == apc->arg_bufnr)
7940 apc->arg_bufnr = 0;
7941
7942 /* invalidate buflocals looping through events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007943 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7944 event = (event_T)((int)event + 1))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007945 /* loop over all autocommand patterns */
7946 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
7947 if (ap->buflocal_nr == buf->b_fnum)
7948 {
7949 au_remove_pat(ap);
7950 if (p_verbose >= 6)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007951 {
7952 verbose_enter();
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007953 smsg((char_u *)
7954 _("auto-removing autocommand: %s <buffer=%d>"),
7955 event_nr2name(event), buf->b_fnum);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007956 verbose_leave();
7957 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007958 }
7959 au_cleanup();
7960}
7961
7962/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007963 * Add an autocmd group name.
7964 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
7965 */
7966 static int
7967au_new_group(name)
7968 char_u *name;
7969{
7970 int i;
7971
7972 i = au_find_group(name);
7973 if (i == AUGROUP_ERROR) /* the group doesn't exist yet, add it */
7974 {
7975 /* First try using a free entry. */
7976 for (i = 0; i < augroups.ga_len; ++i)
7977 if (AUGROUP_NAME(i) == NULL)
7978 break;
7979 if (i == augroups.ga_len && ga_grow(&augroups, 1) == FAIL)
7980 return AUGROUP_ERROR;
7981
7982 AUGROUP_NAME(i) = vim_strsave(name);
7983 if (AUGROUP_NAME(i) == NULL)
7984 return AUGROUP_ERROR;
7985 if (i == augroups.ga_len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007986 ++augroups.ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007987 }
7988
7989 return i;
7990}
7991
7992 static void
7993au_del_group(name)
7994 char_u *name;
7995{
7996 int i;
7997
7998 i = au_find_group(name);
7999 if (i == AUGROUP_ERROR) /* the group doesn't exist */
8000 EMSG2(_("E367: No such group: \"%s\""), name);
8001 else
8002 {
8003 vim_free(AUGROUP_NAME(i));
8004 AUGROUP_NAME(i) = NULL;
8005 }
8006}
8007
8008/*
8009 * Find the ID of an autocmd group name.
8010 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
8011 */
8012 static int
8013au_find_group(name)
8014 char_u *name;
8015{
8016 int i;
8017
8018 for (i = 0; i < augroups.ga_len; ++i)
8019 if (AUGROUP_NAME(i) != NULL && STRCMP(AUGROUP_NAME(i), name) == 0)
8020 return i;
8021 return AUGROUP_ERROR;
8022}
8023
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008024/*
8025 * Return TRUE if augroup "name" exists.
8026 */
8027 int
8028au_has_group(name)
8029 char_u *name;
8030{
8031 return au_find_group(name) != AUGROUP_ERROR;
8032}
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008033
Bram Moolenaar071d4272004-06-13 20:20:40 +00008034/*
8035 * ":augroup {name}".
8036 */
8037 void
8038do_augroup(arg, del_group)
8039 char_u *arg;
8040 int del_group;
8041{
8042 int i;
8043
8044 if (del_group)
8045 {
8046 if (*arg == NUL)
8047 EMSG(_(e_argreq));
8048 else
8049 au_del_group(arg);
8050 }
8051 else if (STRICMP(arg, "end") == 0) /* ":aug end": back to group 0 */
8052 current_augroup = AUGROUP_DEFAULT;
8053 else if (*arg) /* ":aug xxx": switch to group xxx */
8054 {
8055 i = au_new_group(arg);
8056 if (i != AUGROUP_ERROR)
8057 current_augroup = i;
8058 }
8059 else /* ":aug": list the group names */
8060 {
8061 msg_start();
8062 for (i = 0; i < augroups.ga_len; ++i)
8063 {
8064 if (AUGROUP_NAME(i) != NULL)
8065 {
8066 msg_puts(AUGROUP_NAME(i));
8067 msg_puts((char_u *)" ");
8068 }
8069 }
8070 msg_clr_eos();
8071 msg_end();
8072 }
8073}
8074
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008075#if defined(EXITFREE) || defined(PROTO)
8076 void
8077free_all_autocmds()
8078{
8079 for (current_augroup = -1; current_augroup < augroups.ga_len;
8080 ++current_augroup)
8081 do_autocmd((char_u *)"", TRUE);
8082 ga_clear_strings(&augroups);
8083}
8084#endif
8085
Bram Moolenaar071d4272004-06-13 20:20:40 +00008086/*
8087 * Return the event number for event name "start".
8088 * Return NUM_EVENTS if the event name was not found.
8089 * Return a pointer to the next event name in "end".
8090 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008091 static event_T
Bram Moolenaar071d4272004-06-13 20:20:40 +00008092event_name2nr(start, end)
8093 char_u *start;
8094 char_u **end;
8095{
8096 char_u *p;
8097 int i;
8098 int len;
8099
8100 /* the event name ends with end of line, a blank or a comma */
8101 for (p = start; *p && !vim_iswhite(*p) && *p != ','; ++p)
8102 ;
8103 for (i = 0; event_names[i].name != NULL; ++i)
8104 {
8105 len = (int)STRLEN(event_names[i].name);
8106 if (len == p - start && STRNICMP(event_names[i].name, start, len) == 0)
8107 break;
8108 }
8109 if (*p == ',')
8110 ++p;
8111 *end = p;
8112 if (event_names[i].name == NULL)
8113 return NUM_EVENTS;
8114 return event_names[i].event;
8115}
8116
8117/*
8118 * Return the name for event "event".
8119 */
8120 static char_u *
8121event_nr2name(event)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008122 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008123{
8124 int i;
8125
8126 for (i = 0; event_names[i].name != NULL; ++i)
8127 if (event_names[i].event == event)
8128 return (char_u *)event_names[i].name;
8129 return (char_u *)"Unknown";
8130}
8131
8132/*
8133 * Scan over the events. "*" stands for all events.
8134 */
8135 static char_u *
8136find_end_event(arg, have_group)
8137 char_u *arg;
8138 int have_group; /* TRUE when group name was found */
8139{
8140 char_u *pat;
8141 char_u *p;
8142
8143 if (*arg == '*')
8144 {
8145 if (arg[1] && !vim_iswhite(arg[1]))
8146 {
8147 EMSG2(_("E215: Illegal character after *: %s"), arg);
8148 return NULL;
8149 }
8150 pat = arg + 1;
8151 }
8152 else
8153 {
8154 for (pat = arg; *pat && !vim_iswhite(*pat); pat = p)
8155 {
8156 if ((int)event_name2nr(pat, &p) >= (int)NUM_EVENTS)
8157 {
8158 if (have_group)
8159 EMSG2(_("E216: No such event: %s"), pat);
8160 else
8161 EMSG2(_("E216: No such group or event: %s"), pat);
8162 return NULL;
8163 }
8164 }
8165 }
8166 return pat;
8167}
8168
8169/*
8170 * Return TRUE if "event" is included in 'eventignore'.
8171 */
8172 static int
8173event_ignored(event)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008174 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008175{
8176 char_u *p = p_ei;
8177
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008178 while (*p != NUL)
8179 {
8180 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8181 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008182 if (event_name2nr(p, &p) == event)
8183 return TRUE;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008184 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008185
8186 return FALSE;
8187}
8188
8189/*
8190 * Return OK when the contents of p_ei is valid, FAIL otherwise.
8191 */
8192 int
8193check_ei()
8194{
8195 char_u *p = p_ei;
8196
Bram Moolenaar071d4272004-06-13 20:20:40 +00008197 while (*p)
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008198 {
8199 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8200 {
8201 p += 3;
8202 if (*p == ',')
8203 ++p;
8204 }
8205 else if (event_name2nr(p, &p) == NUM_EVENTS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008206 return FAIL;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008207 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008208
8209 return OK;
8210}
8211
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008212# if defined(FEAT_SYN_HL) || defined(PROTO)
8213
8214/*
8215 * Add "what" to 'eventignore' to skip loading syntax highlighting for every
8216 * buffer loaded into the window. "what" must start with a comma.
8217 * Returns the old value of 'eventignore' in allocated memory.
8218 */
8219 char_u *
8220au_event_disable(what)
8221 char *what;
8222{
8223 char_u *new_ei;
8224 char_u *save_ei;
8225
8226 save_ei = vim_strsave(p_ei);
8227 if (save_ei != NULL)
8228 {
Bram Moolenaara5792f52005-11-23 21:25:05 +00008229 new_ei = vim_strnsave(p_ei, (int)(STRLEN(p_ei) + STRLEN(what)));
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008230 if (new_ei != NULL)
8231 {
Bram Moolenaar8cac9fd2010-03-02 12:48:05 +01008232 if (*what == ',' && *p_ei == NUL)
8233 STRCPY(new_ei, what + 1);
8234 else
8235 STRCAT(new_ei, what);
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008236 set_string_option_direct((char_u *)"ei", -1, new_ei,
8237 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008238 vim_free(new_ei);
8239 }
8240 }
8241 return save_ei;
8242}
8243
8244 void
8245au_event_restore(old_ei)
8246 char_u *old_ei;
8247{
8248 if (old_ei != NULL)
8249 {
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008250 set_string_option_direct((char_u *)"ei", -1, old_ei,
8251 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008252 vim_free(old_ei);
8253 }
8254}
8255# endif /* FEAT_SYN_HL */
8256
Bram Moolenaar071d4272004-06-13 20:20:40 +00008257/*
8258 * do_autocmd() -- implements the :autocmd command. Can be used in the
8259 * following ways:
8260 *
8261 * :autocmd <event> <pat> <cmd> Add <cmd> to the list of commands that
8262 * will be automatically executed for <event>
8263 * when editing a file matching <pat>, in
8264 * the current group.
8265 * :autocmd <event> <pat> Show the auto-commands associated with
8266 * <event> and <pat>.
8267 * :autocmd <event> Show the auto-commands associated with
8268 * <event>.
8269 * :autocmd Show all auto-commands.
8270 * :autocmd! <event> <pat> <cmd> Remove all auto-commands associated with
8271 * <event> and <pat>, and add the command
8272 * <cmd>, for the current group.
8273 * :autocmd! <event> <pat> Remove all auto-commands associated with
8274 * <event> and <pat> for the current group.
8275 * :autocmd! <event> Remove all auto-commands associated with
8276 * <event> for the current group.
8277 * :autocmd! Remove ALL auto-commands for the current
8278 * group.
8279 *
8280 * Multiple events and patterns may be given separated by commas. Here are
8281 * some examples:
8282 * :autocmd bufread,bufenter *.c,*.h set tw=0 smartindent noic
8283 * :autocmd bufleave * set tw=79 nosmartindent ic infercase
8284 *
8285 * :autocmd * *.c show all autocommands for *.c files.
Bram Moolenaard35f9712005-12-18 22:02:33 +00008286 *
8287 * Mostly a {group} argument can optionally appear before <event>.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008288 */
8289 void
8290do_autocmd(arg, forceit)
8291 char_u *arg;
8292 int forceit;
8293{
8294 char_u *pat;
8295 char_u *envpat = NULL;
8296 char_u *cmd;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008297 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008298 int need_free = FALSE;
8299 int nested = FALSE;
8300 int group;
8301
8302 /*
8303 * Check for a legal group name. If not, use AUGROUP_ALL.
8304 */
8305 group = au_get_grouparg(&arg);
8306 if (arg == NULL) /* out of memory */
8307 return;
8308
8309 /*
8310 * Scan over the events.
8311 * If we find an illegal name, return here, don't do anything.
8312 */
8313 pat = find_end_event(arg, group != AUGROUP_ALL);
8314 if (pat == NULL)
8315 return;
8316
8317 /*
8318 * Scan over the pattern. Put a NUL at the end.
8319 */
8320 pat = skipwhite(pat);
8321 cmd = pat;
8322 while (*cmd && (!vim_iswhite(*cmd) || cmd[-1] == '\\'))
8323 cmd++;
8324 if (*cmd)
8325 *cmd++ = NUL;
8326
8327 /* Expand environment variables in the pattern. Set 'shellslash', we want
8328 * forward slashes here. */
8329 if (vim_strchr(pat, '$') != NULL || vim_strchr(pat, '~') != NULL)
8330 {
8331#ifdef BACKSLASH_IN_FILENAME
8332 int p_ssl_save = p_ssl;
8333
8334 p_ssl = TRUE;
8335#endif
8336 envpat = expand_env_save(pat);
8337#ifdef BACKSLASH_IN_FILENAME
8338 p_ssl = p_ssl_save;
8339#endif
8340 if (envpat != NULL)
8341 pat = envpat;
8342 }
8343
8344 /*
8345 * Check for "nested" flag.
8346 */
8347 cmd = skipwhite(cmd);
8348 if (*cmd != NUL && STRNCMP(cmd, "nested", 6) == 0 && vim_iswhite(cmd[6]))
8349 {
8350 nested = TRUE;
8351 cmd = skipwhite(cmd + 6);
8352 }
8353
8354 /*
8355 * Find the start of the commands.
8356 * Expand <sfile> in it.
8357 */
8358 if (*cmd != NUL)
8359 {
8360 cmd = expand_sfile(cmd);
8361 if (cmd == NULL) /* some error */
8362 return;
8363 need_free = TRUE;
8364 }
8365
8366 /*
8367 * Print header when showing autocommands.
8368 */
8369 if (!forceit && *cmd == NUL)
8370 {
8371 /* Highlight title */
8372 MSG_PUTS_TITLE(_("\n--- Auto-Commands ---"));
8373 }
8374
8375 /*
8376 * Loop over the events.
8377 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008378 last_event = (event_T)-1; /* for listing the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008379 last_group = AUGROUP_ERROR; /* for listing the group name */
8380 if (*arg == '*' || *arg == NUL)
8381 {
Bram Moolenaar754b5602006-02-09 23:53:20 +00008382 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8383 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008384 if (do_autocmd_event(event, pat,
8385 nested, cmd, forceit, group) == FAIL)
8386 break;
8387 }
8388 else
8389 {
8390 while (*arg && !vim_iswhite(*arg))
8391 if (do_autocmd_event(event_name2nr(arg, &arg), pat,
8392 nested, cmd, forceit, group) == FAIL)
8393 break;
8394 }
8395
8396 if (need_free)
8397 vim_free(cmd);
8398 vim_free(envpat);
8399}
8400
8401/*
8402 * Find the group ID in a ":autocmd" or ":doautocmd" argument.
8403 * The "argp" argument is advanced to the following argument.
8404 *
8405 * Returns the group ID, AUGROUP_ERROR for error (out of memory).
8406 */
8407 static int
8408au_get_grouparg(argp)
8409 char_u **argp;
8410{
8411 char_u *group_name;
8412 char_u *p;
8413 char_u *arg = *argp;
8414 int group = AUGROUP_ALL;
8415
8416 p = skiptowhite(arg);
8417 if (p > arg)
8418 {
8419 group_name = vim_strnsave(arg, (int)(p - arg));
8420 if (group_name == NULL) /* out of memory */
8421 return AUGROUP_ERROR;
8422 group = au_find_group(group_name);
8423 if (group == AUGROUP_ERROR)
8424 group = AUGROUP_ALL; /* no match, use all groups */
8425 else
8426 *argp = skipwhite(p); /* match, skip over group name */
8427 vim_free(group_name);
8428 }
8429 return group;
8430}
8431
8432/*
8433 * do_autocmd() for one event.
8434 * If *pat == NUL do for all patterns.
8435 * If *cmd == NUL show entries.
8436 * If forceit == TRUE delete entries.
8437 * If group is not AUGROUP_ALL, only use this group.
8438 */
8439 static int
8440do_autocmd_event(event, pat, nested, cmd, forceit, group)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008441 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008442 char_u *pat;
8443 int nested;
8444 char_u *cmd;
8445 int forceit;
8446 int group;
8447{
8448 AutoPat *ap;
8449 AutoPat **prev_ap;
8450 AutoCmd *ac;
8451 AutoCmd **prev_ac;
8452 int brace_level;
8453 char_u *endpat;
8454 int findgroup;
8455 int allgroups;
8456 int patlen;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00008457 int is_buflocal;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008458 int buflocal_nr;
8459 char_u buflocal_pat[25]; /* for "<buffer=X>" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008460
8461 if (group == AUGROUP_ALL)
8462 findgroup = current_augroup;
8463 else
8464 findgroup = group;
8465 allgroups = (group == AUGROUP_ALL && !forceit && *cmd == NUL);
8466
8467 /*
8468 * Show or delete all patterns for an event.
8469 */
8470 if (*pat == NUL)
8471 {
8472 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8473 {
8474 if (forceit) /* delete the AutoPat, if it's in the current group */
8475 {
8476 if (ap->group == findgroup)
8477 au_remove_pat(ap);
8478 }
8479 else if (group == AUGROUP_ALL || ap->group == group)
8480 show_autocmd(ap, event);
8481 }
8482 }
8483
8484 /*
8485 * Loop through all the specified patterns.
8486 */
8487 for ( ; *pat; pat = (*endpat == ',' ? endpat + 1 : endpat))
8488 {
8489 /*
8490 * Find end of the pattern.
8491 * Watch out for a comma in braces, like "*.\{obj,o\}".
8492 */
8493 brace_level = 0;
8494 for (endpat = pat; *endpat && (*endpat != ',' || brace_level
8495 || endpat[-1] == '\\'); ++endpat)
8496 {
8497 if (*endpat == '{')
8498 brace_level++;
8499 else if (*endpat == '}')
8500 brace_level--;
8501 }
8502 if (pat == endpat) /* ignore single comma */
8503 continue;
8504 patlen = (int)(endpat - pat);
8505
8506 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008507 * detect special <buflocal[=X]> buffer-local patterns
8508 */
8509 is_buflocal = FALSE;
8510 buflocal_nr = 0;
8511
8512 if (patlen >= 7 && STRNCMP(pat, "<buffer", 7) == 0
8513 && pat[patlen - 1] == '>')
8514 {
8515 /* Error will be printed only for addition. printing and removing
8516 * will proceed silently. */
8517 is_buflocal = TRUE;
8518 if (patlen == 8)
8519 buflocal_nr = curbuf->b_fnum;
8520 else if (patlen > 9 && pat[7] == '=')
8521 {
8522 /* <buffer=abuf> */
8523 if (patlen == 13 && STRNICMP(pat, "<buffer=abuf>", 13))
8524 buflocal_nr = autocmd_bufnr;
8525 /* <buffer=123> */
8526 else if (skipdigits(pat + 8) == pat + patlen - 1)
8527 buflocal_nr = atoi((char *)pat + 8);
8528 }
8529 }
8530
8531 if (is_buflocal)
8532 {
8533 /* normalize pat into standard "<buffer>#N" form */
8534 sprintf((char *)buflocal_pat, "<buffer=%d>", buflocal_nr);
8535 pat = buflocal_pat; /* can modify pat and patlen */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008536 patlen = (int)STRLEN(buflocal_pat); /* but not endpat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008537 }
8538
8539 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008540 * Find AutoPat entries with this pattern.
8541 */
8542 prev_ap = &first_autopat[(int)event];
8543 while ((ap = *prev_ap) != NULL)
8544 {
8545 if (ap->pat != NULL)
8546 {
8547 /* Accept a pattern when:
8548 * - a group was specified and it's that group, or a group was
8549 * not specified and it's the current group, or a group was
8550 * not specified and we are listing
8551 * - the length of the pattern matches
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008552 * - the pattern matches.
8553 * For <buffer[=X]>, this condition works because we normalize
8554 * all buffer-local patterns.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008555 */
8556 if ((allgroups || ap->group == findgroup)
8557 && ap->patlen == patlen
8558 && STRNCMP(pat, ap->pat, patlen) == 0)
8559 {
8560 /*
8561 * Remove existing autocommands.
8562 * If adding any new autocmd's for this AutoPat, don't
8563 * delete the pattern from the autopat list, append to
8564 * this list.
8565 */
8566 if (forceit)
8567 {
8568 if (*cmd != NUL && ap->next == NULL)
8569 {
8570 au_remove_cmds(ap);
8571 break;
8572 }
8573 au_remove_pat(ap);
8574 }
8575
8576 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008577 * Show autocmd's for this autopat, or buflocals <buffer=X>
Bram Moolenaar071d4272004-06-13 20:20:40 +00008578 */
8579 else if (*cmd == NUL)
8580 show_autocmd(ap, event);
8581
8582 /*
8583 * Add autocmd to this autopat, if it's the last one.
8584 */
8585 else if (ap->next == NULL)
8586 break;
8587 }
8588 }
8589 prev_ap = &ap->next;
8590 }
8591
8592 /*
8593 * Add a new command.
8594 */
8595 if (*cmd != NUL)
8596 {
8597 /*
8598 * If the pattern we want to add a command to does appear at the
8599 * end of the list (or not is not in the list at all), add the
8600 * pattern at the end of the list.
8601 */
8602 if (ap == NULL)
8603 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008604 /* refuse to add buffer-local ap if buffer number is invalid */
8605 if (is_buflocal && (buflocal_nr == 0
8606 || buflist_findnr(buflocal_nr) == NULL))
8607 {
8608 EMSGN(_("E680: <buffer=%d>: invalid buffer number "),
8609 buflocal_nr);
8610 return FAIL;
8611 }
8612
Bram Moolenaar071d4272004-06-13 20:20:40 +00008613 ap = (AutoPat *)alloc((unsigned)sizeof(AutoPat));
8614 if (ap == NULL)
8615 return FAIL;
8616 ap->pat = vim_strnsave(pat, patlen);
8617 ap->patlen = patlen;
8618 if (ap->pat == NULL)
8619 {
8620 vim_free(ap);
8621 return FAIL;
8622 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008623
8624 if (is_buflocal)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008625 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008626 ap->buflocal_nr = buflocal_nr;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008627 ap->reg_prog = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008628 }
8629 else
8630 {
Bram Moolenaar748bf032005-02-02 23:04:36 +00008631 char_u *reg_pat;
8632
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008633 ap->buflocal_nr = 0;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008634 reg_pat = file_pat_to_reg_pat(pat, endpat,
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008635 &ap->allow_dirs, TRUE);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008636 if (reg_pat != NULL)
8637 ap->reg_prog = vim_regcomp(reg_pat, RE_MAGIC);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008638 vim_free(reg_pat);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008639 if (reg_pat == NULL || ap->reg_prog == NULL)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008640 {
8641 vim_free(ap->pat);
8642 vim_free(ap);
8643 return FAIL;
8644 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008645 }
8646 ap->cmds = NULL;
8647 *prev_ap = ap;
8648 ap->next = NULL;
8649 if (group == AUGROUP_ALL)
8650 ap->group = current_augroup;
8651 else
8652 ap->group = group;
8653 }
8654
8655 /*
8656 * Add the autocmd at the end of the AutoCmd list.
8657 */
8658 prev_ac = &(ap->cmds);
8659 while ((ac = *prev_ac) != NULL)
8660 prev_ac = &ac->next;
8661 ac = (AutoCmd *)alloc((unsigned)sizeof(AutoCmd));
8662 if (ac == NULL)
8663 return FAIL;
8664 ac->cmd = vim_strsave(cmd);
8665#ifdef FEAT_EVAL
8666 ac->scriptID = current_SID;
8667#endif
8668 if (ac->cmd == NULL)
8669 {
8670 vim_free(ac);
8671 return FAIL;
8672 }
8673 ac->next = NULL;
8674 *prev_ac = ac;
8675 ac->nested = nested;
8676 }
8677 }
8678
8679 au_cleanup(); /* may really delete removed patterns/commands now */
8680 return OK;
8681}
8682
8683/*
8684 * Implementation of ":doautocmd [group] event [fname]".
8685 * Return OK for success, FAIL for failure;
8686 */
8687 int
8688do_doautocmd(arg, do_msg)
8689 char_u *arg;
8690 int do_msg; /* give message for no matching autocmds? */
8691{
8692 char_u *fname;
8693 int nothing_done = TRUE;
8694 int group;
8695
8696 /*
8697 * Check for a legal group name. If not, use AUGROUP_ALL.
8698 */
8699 group = au_get_grouparg(&arg);
8700 if (arg == NULL) /* out of memory */
8701 return FAIL;
8702
8703 if (*arg == '*')
8704 {
8705 EMSG(_("E217: Can't execute autocommands for ALL events"));
8706 return FAIL;
8707 }
8708
8709 /*
8710 * Scan over the events.
8711 * If we find an illegal name, return here, don't do anything.
8712 */
8713 fname = find_end_event(arg, group != AUGROUP_ALL);
8714 if (fname == NULL)
8715 return FAIL;
8716
8717 fname = skipwhite(fname);
8718
8719 /*
8720 * Loop over the events.
8721 */
8722 while (*arg && !vim_iswhite(*arg))
8723 if (apply_autocmds_group(event_name2nr(arg, &arg),
8724 fname, NULL, TRUE, group, curbuf, NULL))
8725 nothing_done = FALSE;
8726
8727 if (nothing_done && do_msg)
8728 MSG(_("No matching autocommands"));
8729
8730#ifdef FEAT_EVAL
8731 return aborting() ? FAIL : OK;
8732#else
8733 return OK;
8734#endif
8735}
8736
8737/*
8738 * ":doautoall": execute autocommands for each loaded buffer.
8739 */
8740 void
8741ex_doautoall(eap)
8742 exarg_T *eap;
8743{
8744 int retval;
8745 aco_save_T aco;
8746 buf_T *buf;
8747
8748 /*
8749 * This is a bit tricky: For some commands curwin->w_buffer needs to be
8750 * equal to curbuf, but for some buffers there may not be a window.
8751 * So we change the buffer for the current window for a moment. This
8752 * gives problems when the autocommands make changes to the list of
8753 * buffers or windows...
8754 */
8755 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8756 {
Bram Moolenaar3a847972008-07-08 09:36:58 +00008757 if (buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008758 {
8759 /* find a window for this buffer and save some values */
8760 aucmd_prepbuf(&aco, buf);
8761
8762 /* execute the autocommands for this buffer */
8763 retval = do_doautocmd(eap->arg, FALSE);
Bram Moolenaareeefcc72007-05-01 21:21:21 +00008764
8765 /* Execute the modeline settings, but don't set window-local
8766 * options if we are using the current window for another buffer. */
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008767 do_modelines(curwin == aucmd_win ? OPT_NOWIN : 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008768
8769 /* restore the current window */
8770 aucmd_restbuf(&aco);
8771
8772 /* stop if there is some error or buffer was deleted */
8773 if (retval == FAIL || !buf_valid(buf))
8774 break;
8775 }
8776 }
8777
8778 check_cursor(); /* just in case lines got deleted */
8779}
8780
8781/*
8782 * Prepare for executing autocommands for (hidden) buffer "buf".
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008783 * Search for a visible window containing the current buffer. If there isn't
8784 * one then use "aucmd_win".
Bram Moolenaar071d4272004-06-13 20:20:40 +00008785 * Set "curbuf" and "curwin" to match "buf".
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00008786 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008787 */
8788 void
8789aucmd_prepbuf(aco, buf)
8790 aco_save_T *aco; /* structure to save values in */
8791 buf_T *buf; /* new curbuf */
8792{
8793 win_T *win;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008794#ifdef FEAT_WINDOWS
8795 int save_ea;
8796#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008797
8798 /* Find a window that is for the new buffer */
8799 if (buf == curbuf) /* be quick when buf is curbuf */
8800 win = curwin;
8801 else
8802#ifdef FEAT_WINDOWS
8803 for (win = firstwin; win != NULL; win = win->w_next)
8804 if (win->w_buffer == buf)
8805 break;
8806#else
8807 win = NULL;
8808#endif
8809
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008810 /* Allocate "aucmd_win" when needed. If this fails (out of memory) fall
8811 * back to using the current window. */
8812 if (win == NULL && aucmd_win == NULL)
8813 {
8814 win_alloc_aucmd_win();
8815 if (aucmd_win == NULL)
8816 win = curwin;
8817 }
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008818 if (win == NULL && aucmd_win_used)
8819 /* Strange recursive autocommand, fall back to using the current
8820 * window. Expect a few side effects... */
8821 win = curwin;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008822
8823 aco->save_curwin = curwin;
8824 aco->save_curbuf = curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008825 if (win != NULL)
8826 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008827 /* There is a window for "buf" in the current tab page, make it the
8828 * curwin. This is preferred, it has the least side effects (esp. if
8829 * "buf" is curbuf). */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008830 aco->use_aucmd_win = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008831 curwin = win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008832 }
8833 else
8834 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008835 /* There is no window for "buf", use "aucmd_win". To minimize the side
8836 * effects, insert it in a the current tab page.
8837 * Anything related to a window (e.g., setting folds) may have
8838 * unexpected results. */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008839 aco->use_aucmd_win = TRUE;
8840 aucmd_win_used = TRUE;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008841 aucmd_win->w_buffer = buf;
Bram Moolenaarcdddaa42010-06-07 23:07:44 +02008842 aucmd_win->w_s = &buf->b_s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008843 ++buf->b_nwindows;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008844 win_init_empty(aucmd_win); /* set cursor and topline to safe values */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008845 vim_free(aucmd_win->w_localdir);
8846 aucmd_win->w_localdir = NULL;
8847
8848 /* Make sure w_localdir and globaldir are NULL to avoid a chdir() in
8849 * win_enter_ext(). */
8850 aucmd_win->w_localdir = NULL;
8851 aco->globaldir = globaldir;
8852 globaldir = NULL;
8853
Bram Moolenaar071d4272004-06-13 20:20:40 +00008854
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008855#ifdef FEAT_WINDOWS
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008856 /* Split the current window, put the aucmd_win in the upper half.
8857 * We don't want the BufEnter or WinEnter autocommands. */
8858 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008859 make_snapshot(SNAP_AUCMD_IDX);
8860 save_ea = p_ea;
8861 p_ea = FALSE;
8862 (void)win_split_ins(0, WSP_TOP, aucmd_win, 0);
8863 (void)win_comp_pos(); /* recompute window positions */
8864 p_ea = save_ea;
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008865 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008866#endif
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008867 curwin = aucmd_win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008868 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008869 curbuf = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008870 aco->new_curwin = curwin;
8871 aco->new_curbuf = curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008872}
8873
8874/*
8875 * Cleanup after executing autocommands for a (hidden) buffer.
8876 * Restore the window as it was (if possible).
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00008877 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008878 */
8879 void
8880aucmd_restbuf(aco)
8881 aco_save_T *aco; /* structure holding saved values */
8882{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008883#ifdef FEAT_WINDOWS
8884 int dummy;
8885#endif
8886
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008887 if (aco->use_aucmd_win)
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008888 {
8889 --curbuf->b_nwindows;
8890#ifdef FEAT_WINDOWS
8891 /* Find "aucmd_win", it can't be closed, but it may be in another tab
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008892 * page. Do not trigger autocommands here. */
8893 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008894 if (curwin != aucmd_win)
8895 {
8896 tabpage_T *tp;
8897 win_T *wp;
8898
8899 FOR_ALL_TAB_WINDOWS(tp, wp)
8900 {
8901 if (wp == aucmd_win)
8902 {
8903 if (tp != curtab)
8904 goto_tabpage_tp(tp);
8905 win_goto(aucmd_win);
8906 break;
8907 }
8908 }
8909 }
8910
8911 /* Remove the window and frame from the tree of frames. */
8912 (void)winframe_remove(curwin, &dummy, NULL);
8913 win_remove(curwin, NULL);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008914 aucmd_win_used = FALSE;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008915 last_status(FALSE); /* may need to remove last status line */
8916 restore_snapshot(SNAP_AUCMD_IDX, FALSE);
8917 (void)win_comp_pos(); /* recompute window positions */
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008918 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008919
8920 if (win_valid(aco->save_curwin))
8921 curwin = aco->save_curwin;
8922 else
8923 /* Hmm, original window disappeared. Just use the first one. */
8924 curwin = firstwin;
8925# ifdef FEAT_EVAL
8926 vars_clear(&aucmd_win->w_vars.dv_hashtab); /* free all w: variables */
Bram Moolenaar50daf402009-11-17 13:57:22 +00008927 hash_init(&aucmd_win->w_vars.dv_hashtab); /* re-use the hashtab */
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008928# endif
8929#else
8930 curwin = aco->save_curwin;
8931#endif
8932 curbuf = curwin->w_buffer;
8933
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008934 vim_free(globaldir);
8935 globaldir = aco->globaldir;
8936
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008937 /* the buffer contents may have changed */
8938 check_cursor();
8939 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
8940 {
8941 curwin->w_topline = curbuf->b_ml.ml_line_count;
8942#ifdef FEAT_DIFF
8943 curwin->w_topfill = 0;
8944#endif
8945 }
8946#if defined(FEAT_GUI)
8947 /* Hide the scrollbars from the aucmd_win and update. */
8948 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_LEFT], FALSE);
8949 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_RIGHT], FALSE);
8950 gui_may_update_scrollbars();
8951#endif
8952 }
8953 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00008954 {
8955 /* restore curwin */
8956#ifdef FEAT_WINDOWS
8957 if (win_valid(aco->save_curwin))
8958#endif
8959 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008960 /* Restore the buffer which was previously edited by curwin, if
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008961 * it was changed, we are still the same window and the buffer is
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008962 * valid. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008963 if (curwin == aco->new_curwin
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008964 && curbuf != aco->new_curbuf
8965 && buf_valid(aco->new_curbuf)
8966 && aco->new_curbuf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008967 {
8968 --curbuf->b_nwindows;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008969 curbuf = aco->new_curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008970 curwin->w_buffer = curbuf;
8971 ++curbuf->b_nwindows;
8972 }
8973
8974 curwin = aco->save_curwin;
8975 curbuf = curwin->w_buffer;
8976 }
8977 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008978}
8979
8980static int autocmd_nested = FALSE;
8981
8982/*
8983 * Execute autocommands for "event" and file name "fname".
8984 * Return TRUE if some commands were executed.
8985 */
8986 int
8987apply_autocmds(event, fname, fname_io, force, buf)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008988 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008989 char_u *fname; /* NULL or empty means use actual file name */
8990 char_u *fname_io; /* fname to use for <afile> on cmdline */
8991 int force; /* when TRUE, ignore autocmd_busy */
8992 buf_T *buf; /* buffer for <abuf> */
8993{
8994 return apply_autocmds_group(event, fname, fname_io, force,
8995 AUGROUP_ALL, buf, NULL);
8996}
8997
8998/*
8999 * Like apply_autocmds(), but with extra "eap" argument. This takes care of
9000 * setting v:filearg.
9001 */
9002 static int
9003apply_autocmds_exarg(event, fname, fname_io, force, buf, eap)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009004 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009005 char_u *fname;
9006 char_u *fname_io;
9007 int force;
9008 buf_T *buf;
9009 exarg_T *eap;
9010{
9011 return apply_autocmds_group(event, fname, fname_io, force,
9012 AUGROUP_ALL, buf, eap);
9013}
9014
9015/*
9016 * Like apply_autocmds(), but handles the caller's retval. If the script
9017 * processing is being aborted or if retval is FAIL when inside a try
9018 * conditional, no autocommands are executed. If otherwise the autocommands
9019 * cause the script to be aborted, retval is set to FAIL.
9020 */
9021 int
9022apply_autocmds_retval(event, fname, fname_io, force, buf, retval)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009023 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009024 char_u *fname; /* NULL or empty means use actual file name */
9025 char_u *fname_io; /* fname to use for <afile> on cmdline */
9026 int force; /* when TRUE, ignore autocmd_busy */
9027 buf_T *buf; /* buffer for <abuf> */
9028 int *retval; /* pointer to caller's retval */
9029{
9030 int did_cmd;
9031
Bram Moolenaar1e015462005-09-25 22:16:38 +00009032#ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00009033 if (should_abort(*retval))
9034 return FALSE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00009035#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009036
9037 did_cmd = apply_autocmds_group(event, fname, fname_io, force,
9038 AUGROUP_ALL, buf, NULL);
Bram Moolenaar1e015462005-09-25 22:16:38 +00009039 if (did_cmd
9040#ifdef FEAT_EVAL
9041 && aborting()
9042#endif
9043 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00009044 *retval = FAIL;
9045 return did_cmd;
9046}
9047
Bram Moolenaard35f9712005-12-18 22:02:33 +00009048/*
9049 * Return TRUE when there is a CursorHold autocommand defined.
9050 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009051 int
9052has_cursorhold()
9053{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009054 return (first_autopat[(int)(get_real_state() == NORMAL_BUSY
9055 ? EVENT_CURSORHOLD : EVENT_CURSORHOLDI)] != NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009056}
Bram Moolenaard35f9712005-12-18 22:02:33 +00009057
9058/*
9059 * Return TRUE if the CursorHold event can be triggered.
9060 */
9061 int
9062trigger_cursorhold()
9063{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009064 int state;
9065
Bram Moolenaard29a9ee2006-09-14 09:07:34 +00009066 if (!did_cursorhold && has_cursorhold() && !Recording
9067#ifdef FEAT_INS_EXPAND
9068 && !ins_compl_active()
9069#endif
9070 )
Bram Moolenaar754b5602006-02-09 23:53:20 +00009071 {
9072 state = get_real_state();
9073 if (state == NORMAL_BUSY || (state & INSERT) != 0)
9074 return TRUE;
9075 }
9076 return FALSE;
Bram Moolenaard35f9712005-12-18 22:02:33 +00009077}
Bram Moolenaar754b5602006-02-09 23:53:20 +00009078
9079/*
9080 * Return TRUE when there is a CursorMoved autocommand defined.
9081 */
9082 int
9083has_cursormoved()
9084{
9085 return (first_autopat[(int)EVENT_CURSORMOVED] != NULL);
9086}
9087
9088/*
9089 * Return TRUE when there is a CursorMovedI autocommand defined.
9090 */
9091 int
9092has_cursormovedI()
9093{
9094 return (first_autopat[(int)EVENT_CURSORMOVEDI] != NULL);
9095}
Bram Moolenaar071d4272004-06-13 20:20:40 +00009096
9097 static int
9098apply_autocmds_group(event, fname, fname_io, force, group, buf, eap)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009099 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009100 char_u *fname; /* NULL or empty means use actual file name */
9101 char_u *fname_io; /* fname to use for <afile> on cmdline, NULL means
9102 use fname */
9103 int force; /* when TRUE, ignore autocmd_busy */
9104 int group; /* group ID, or AUGROUP_ALL */
9105 buf_T *buf; /* buffer for <abuf> */
9106 exarg_T *eap; /* command arguments */
9107{
9108 char_u *sfname = NULL; /* short file name */
9109 char_u *tail;
9110 int save_changed;
9111 buf_T *old_curbuf;
9112 int retval = FALSE;
9113 char_u *save_sourcing_name;
9114 linenr_T save_sourcing_lnum;
9115 char_u *save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009116 int save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009117 int save_autocmd_bufnr;
9118 char_u *save_autocmd_match;
9119 int save_autocmd_busy;
9120 int save_autocmd_nested;
9121 static int nesting = 0;
9122 AutoPatCmd patcmd;
9123 AutoPat *ap;
9124#ifdef FEAT_EVAL
9125 scid_T save_current_SID;
9126 void *save_funccalp;
9127 char_u *save_cmdarg;
9128 long save_cmdbang;
9129#endif
9130 static int filechangeshell_busy = FALSE;
Bram Moolenaar05159a02005-02-26 23:04:13 +00009131#ifdef FEAT_PROFILE
9132 proftime_T wait_time;
9133#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009134
9135 /*
9136 * Quickly return if there are no autocommands for this event or
9137 * autocommands are blocked.
9138 */
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009139 if (first_autopat[(int)event] == NULL || autocmd_blocked > 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009140 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009141
9142 /*
9143 * When autocommands are busy, new autocommands are only executed when
9144 * explicitly enabled with the "nested" flag.
9145 */
9146 if (autocmd_busy && !(force || autocmd_nested))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009147 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009148
9149#ifdef FEAT_EVAL
9150 /*
Bram Moolenaar7263a772007-05-10 17:35:54 +00009151 * Quickly return when immediately aborting on error, or when an interrupt
Bram Moolenaar071d4272004-06-13 20:20:40 +00009152 * occurred or an exception was thrown but not caught.
9153 */
9154 if (aborting())
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009155 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009156#endif
9157
9158 /*
9159 * FileChangedShell never nests, because it can create an endless loop.
9160 */
Bram Moolenaar56718732006-03-15 22:53:57 +00009161 if (filechangeshell_busy && (event == EVENT_FILECHANGEDSHELL
9162 || event == EVENT_FILECHANGEDSHELLPOST))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009163 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009164
9165 /*
9166 * Ignore events in 'eventignore'.
9167 */
9168 if (event_ignored(event))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009169 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009170
9171 /*
9172 * Allow nesting of autocommands, but restrict the depth, because it's
9173 * possible to create an endless loop.
9174 */
9175 if (nesting == 10)
9176 {
9177 EMSG(_("E218: autocommand nesting too deep"));
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009178 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009179 }
9180
9181 /*
9182 * Check if these autocommands are disabled. Used when doing ":all" or
9183 * ":ball".
9184 */
9185 if ( (autocmd_no_enter
9186 && (event == EVENT_WINENTER || event == EVENT_BUFENTER))
9187 || (autocmd_no_leave
9188 && (event == EVENT_WINLEAVE || event == EVENT_BUFLEAVE)))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009189 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009190
9191 /*
9192 * Save the autocmd_* variables and info about the current buffer.
9193 */
9194 save_autocmd_fname = autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009195 save_autocmd_fname_full = autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009196 save_autocmd_bufnr = autocmd_bufnr;
9197 save_autocmd_match = autocmd_match;
9198 save_autocmd_busy = autocmd_busy;
9199 save_autocmd_nested = autocmd_nested;
9200 save_changed = curbuf->b_changed;
9201 old_curbuf = curbuf;
9202
9203 /*
9204 * Set the file name to be used for <afile>.
Bram Moolenaara0174af2008-01-02 20:08:25 +00009205 * Make a copy to avoid that changing a buffer name or directory makes it
9206 * invalid.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009207 */
9208 if (fname_io == NULL)
9209 {
9210 if (fname != NULL && *fname != NUL)
9211 autocmd_fname = fname;
9212 else if (buf != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009213 autocmd_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009214 else
9215 autocmd_fname = NULL;
9216 }
9217 else
9218 autocmd_fname = fname_io;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009219 if (autocmd_fname != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009220 autocmd_fname = vim_strsave(autocmd_fname);
9221 autocmd_fname_full = FALSE; /* call FullName_save() later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009222
9223 /*
9224 * Set the buffer number to be used for <abuf>.
9225 */
9226 if (buf == NULL)
9227 autocmd_bufnr = 0;
9228 else
9229 autocmd_bufnr = buf->b_fnum;
9230
9231 /*
9232 * When the file name is NULL or empty, use the file name of buffer "buf".
9233 * Always use the full path of the file name to match with, in case
9234 * "allow_dirs" is set.
9235 */
9236 if (fname == NULL || *fname == NUL)
9237 {
9238 if (buf == NULL)
9239 fname = NULL;
9240 else
9241 {
9242#ifdef FEAT_SYN_HL
9243 if (event == EVENT_SYNTAX)
9244 fname = buf->b_p_syn;
9245 else
9246#endif
9247 if (event == EVENT_FILETYPE)
9248 fname = buf->b_p_ft;
9249 else
9250 {
9251 if (buf->b_sfname != NULL)
9252 sfname = vim_strsave(buf->b_sfname);
9253 fname = buf->b_ffname;
9254 }
9255 }
9256 if (fname == NULL)
9257 fname = (char_u *)"";
9258 fname = vim_strsave(fname); /* make a copy, so we can change it */
9259 }
9260 else
9261 {
9262 sfname = vim_strsave(fname);
Bram Moolenaar5135d462009-04-29 16:03:38 +00009263 /* Don't try expanding FileType, Syntax, FuncUndefined, WindowID or
9264 * QuickFixCmd* */
Bram Moolenaar7c626922005-02-07 22:01:03 +00009265 if (event == EVENT_FILETYPE
9266 || event == EVENT_SYNTAX
Bram Moolenaar5135d462009-04-29 16:03:38 +00009267 || event == EVENT_FUNCUNDEFINED
Bram Moolenaar7c626922005-02-07 22:01:03 +00009268 || event == EVENT_REMOTEREPLY
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00009269 || event == EVENT_SPELLFILEMISSING
Bram Moolenaar7c626922005-02-07 22:01:03 +00009270 || event == EVENT_QUICKFIXCMDPRE
9271 || event == EVENT_QUICKFIXCMDPOST)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009272 fname = vim_strsave(fname);
9273 else
9274 fname = FullName_save(fname, FALSE);
9275 }
9276 if (fname == NULL) /* out of memory */
9277 {
9278 vim_free(sfname);
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009279 retval = FALSE;
9280 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009281 }
9282
9283#ifdef BACKSLASH_IN_FILENAME
9284 /*
9285 * Replace all backslashes with forward slashes. This makes the
9286 * autocommand patterns portable between Unix and MS-DOS.
9287 */
9288 if (sfname != NULL)
9289 forward_slash(sfname);
9290 forward_slash(fname);
9291#endif
9292
9293#ifdef VMS
9294 /* remove version for correct match */
9295 if (sfname != NULL)
9296 vms_remove_version(sfname);
9297 vms_remove_version(fname);
9298#endif
9299
9300 /*
9301 * Set the name to be used for <amatch>.
9302 */
9303 autocmd_match = fname;
9304
9305
9306 /* Don't redraw while doing auto commands. */
9307 ++RedrawingDisabled;
9308 save_sourcing_name = sourcing_name;
9309 sourcing_name = NULL; /* don't free this one */
9310 save_sourcing_lnum = sourcing_lnum;
9311 sourcing_lnum = 0; /* no line number here */
9312
9313#ifdef FEAT_EVAL
9314 save_current_SID = current_SID;
9315
Bram Moolenaar05159a02005-02-26 23:04:13 +00009316# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009317 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009318 prof_child_enter(&wait_time); /* doesn't count for the caller itself */
9319# endif
9320
Bram Moolenaar071d4272004-06-13 20:20:40 +00009321 /* Don't use local function variables, if called from a function */
9322 save_funccalp = save_funccal();
9323#endif
9324
9325 /*
9326 * When starting to execute autocommands, save the search patterns.
9327 */
9328 if (!autocmd_busy)
9329 {
9330 save_search_patterns();
9331 saveRedobuff();
9332 did_filetype = keep_filetype;
9333 }
9334
9335 /*
9336 * Note that we are applying autocmds. Some commands need to know.
9337 */
9338 autocmd_busy = TRUE;
9339 filechangeshell_busy = (event == EVENT_FILECHANGEDSHELL);
9340 ++nesting; /* see matching decrement below */
9341
9342 /* Remember that FileType was triggered. Used for did_filetype(). */
9343 if (event == EVENT_FILETYPE)
9344 did_filetype = TRUE;
9345
9346 tail = gettail(fname);
9347
9348 /* Find first autocommand that matches */
9349 patcmd.curpat = first_autopat[(int)event];
9350 patcmd.nextcmd = NULL;
9351 patcmd.group = group;
9352 patcmd.fname = fname;
9353 patcmd.sfname = sfname;
9354 patcmd.tail = tail;
9355 patcmd.event = event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009356 patcmd.arg_bufnr = autocmd_bufnr;
9357 patcmd.next = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009358 auto_next_pat(&patcmd, FALSE);
9359
9360 /* found one, start executing the autocommands */
9361 if (patcmd.curpat != NULL)
9362 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009363 /* add to active_apc_list */
9364 patcmd.next = active_apc_list;
9365 active_apc_list = &patcmd;
9366
Bram Moolenaar071d4272004-06-13 20:20:40 +00009367#ifdef FEAT_EVAL
9368 /* set v:cmdarg (only when there is a matching pattern) */
9369 save_cmdbang = get_vim_var_nr(VV_CMDBANG);
9370 if (eap != NULL)
9371 {
9372 save_cmdarg = set_cmdarg(eap, NULL);
9373 set_vim_var_nr(VV_CMDBANG, (long)eap->forceit);
9374 }
9375 else
9376 save_cmdarg = NULL; /* avoid gcc warning */
9377#endif
9378 retval = TRUE;
9379 /* mark the last pattern, to avoid an endless loop when more patterns
9380 * are added when executing autocommands */
9381 for (ap = patcmd.curpat; ap->next != NULL; ap = ap->next)
9382 ap->last = FALSE;
9383 ap->last = TRUE;
9384 check_lnums(TRUE); /* make sure cursor and topline are valid */
9385 do_cmdline(NULL, getnextac, (void *)&patcmd,
9386 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
9387#ifdef FEAT_EVAL
9388 if (eap != NULL)
9389 {
9390 (void)set_cmdarg(NULL, save_cmdarg);
9391 set_vim_var_nr(VV_CMDBANG, save_cmdbang);
9392 }
9393#endif
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009394 /* delete from active_apc_list */
9395 if (active_apc_list == &patcmd) /* just in case */
9396 active_apc_list = patcmd.next;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009397 }
9398
9399 --RedrawingDisabled;
9400 autocmd_busy = save_autocmd_busy;
9401 filechangeshell_busy = FALSE;
9402 autocmd_nested = save_autocmd_nested;
9403 vim_free(sourcing_name);
9404 sourcing_name = save_sourcing_name;
9405 sourcing_lnum = save_sourcing_lnum;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009406 vim_free(autocmd_fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009407 autocmd_fname = save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009408 autocmd_fname_full = save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009409 autocmd_bufnr = save_autocmd_bufnr;
9410 autocmd_match = save_autocmd_match;
9411#ifdef FEAT_EVAL
9412 current_SID = save_current_SID;
9413 restore_funccal(save_funccalp);
Bram Moolenaar05159a02005-02-26 23:04:13 +00009414# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009415 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009416 prof_child_exit(&wait_time);
9417# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009418#endif
9419 vim_free(fname);
9420 vim_free(sfname);
9421 --nesting; /* see matching increment above */
9422
9423 /*
9424 * When stopping to execute autocommands, restore the search patterns and
9425 * the redo buffer.
9426 */
9427 if (!autocmd_busy)
9428 {
9429 restore_search_patterns();
9430 restoreRedobuff();
9431 did_filetype = FALSE;
9432 }
9433
9434 /*
9435 * Some events don't set or reset the Changed flag.
9436 * Check if still in the same buffer!
9437 */
9438 if (curbuf == old_curbuf
9439 && (event == EVENT_BUFREADPOST
9440 || event == EVENT_BUFWRITEPOST
9441 || event == EVENT_FILEAPPENDPOST
9442 || event == EVENT_VIMLEAVE
9443 || event == EVENT_VIMLEAVEPRE))
9444 {
9445#ifdef FEAT_TITLE
9446 if (curbuf->b_changed != save_changed)
9447 need_maketitle = TRUE;
9448#endif
9449 curbuf->b_changed = save_changed;
9450 }
9451
9452 au_cleanup(); /* may really delete removed patterns/commands now */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009453
9454BYPASS_AU:
9455 /* When wiping out a buffer make sure all its buffer-local autocommands
9456 * are deleted. */
9457 if (event == EVENT_BUFWIPEOUT && buf != NULL)
9458 aubuflocal_remove(buf);
9459
Bram Moolenaar071d4272004-06-13 20:20:40 +00009460 return retval;
9461}
9462
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009463# ifdef FEAT_EVAL
9464static char_u *old_termresponse = NULL;
9465# endif
9466
9467/*
9468 * Block triggering autocommands until unblock_autocmd() is called.
9469 * Can be used recursively, so long as it's symmetric.
9470 */
9471 void
9472block_autocmds()
9473{
9474# ifdef FEAT_EVAL
9475 /* Remember the value of v:termresponse. */
9476 if (autocmd_blocked == 0)
9477 old_termresponse = get_vim_var_str(VV_TERMRESPONSE);
9478# endif
9479 ++autocmd_blocked;
9480}
9481
9482 void
9483unblock_autocmds()
9484{
9485 --autocmd_blocked;
9486
9487# ifdef FEAT_EVAL
9488 /* When v:termresponse was set while autocommands were blocked, trigger
9489 * the autocommands now. Esp. useful when executing a shell command
9490 * during startup (vimdiff). */
9491 if (autocmd_blocked == 0
9492 && get_vim_var_str(VV_TERMRESPONSE) != old_termresponse)
9493 apply_autocmds(EVENT_TERMRESPONSE, NULL, NULL, FALSE, curbuf);
9494# endif
9495}
9496
Bram Moolenaar071d4272004-06-13 20:20:40 +00009497/*
9498 * Find next autocommand pattern that matches.
9499 */
9500 static void
9501auto_next_pat(apc, stop_at_last)
9502 AutoPatCmd *apc;
9503 int stop_at_last; /* stop when 'last' flag is set */
9504{
9505 AutoPat *ap;
9506 AutoCmd *cp;
9507 char_u *name;
9508 char *s;
9509
9510 vim_free(sourcing_name);
9511 sourcing_name = NULL;
9512
9513 for (ap = apc->curpat; ap != NULL && !got_int; ap = ap->next)
9514 {
9515 apc->curpat = NULL;
9516
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009517 /* Only use a pattern when it has not been removed, has commands and
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009518 * the group matches. For buffer-local autocommands only check the
9519 * buffer number. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009520 if (ap->pat != NULL && ap->cmds != NULL
9521 && (apc->group == AUGROUP_ALL || apc->group == ap->group))
9522 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009523 /* execution-condition */
9524 if (ap->buflocal_nr == 0
Bram Moolenaar748bf032005-02-02 23:04:36 +00009525 ? (match_file_pat(NULL, ap->reg_prog, apc->fname,
9526 apc->sfname, apc->tail, ap->allow_dirs))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009527 : ap->buflocal_nr == apc->arg_bufnr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009528 {
9529 name = event_nr2name(apc->event);
9530 s = _("%s Auto commands for \"%s\"");
9531 sourcing_name = alloc((unsigned)(STRLEN(s)
9532 + STRLEN(name) + ap->patlen + 1));
9533 if (sourcing_name != NULL)
9534 {
9535 sprintf((char *)sourcing_name, s,
9536 (char *)name, (char *)ap->pat);
9537 if (p_verbose >= 8)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009538 {
9539 verbose_enter();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009540 smsg((char_u *)_("Executing %s"), sourcing_name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009541 verbose_leave();
9542 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009543 }
9544
9545 apc->curpat = ap;
9546 apc->nextcmd = ap->cmds;
9547 /* mark last command */
9548 for (cp = ap->cmds; cp->next != NULL; cp = cp->next)
9549 cp->last = FALSE;
9550 cp->last = TRUE;
9551 }
9552 line_breakcheck();
9553 if (apc->curpat != NULL) /* found a match */
9554 break;
9555 }
9556 if (stop_at_last && ap->last)
9557 break;
9558 }
9559}
9560
9561/*
9562 * Get next autocommand command.
9563 * Called by do_cmdline() to get the next line for ":if".
9564 * Returns allocated string, or NULL for end of autocommands.
9565 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009566 static char_u *
9567getnextac(c, cookie, indent)
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009568 int c UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009569 void *cookie;
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009570 int indent UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009571{
9572 AutoPatCmd *acp = (AutoPatCmd *)cookie;
9573 char_u *retval;
9574 AutoCmd *ac;
9575
9576 /* Can be called again after returning the last line. */
9577 if (acp->curpat == NULL)
9578 return NULL;
9579
9580 /* repeat until we find an autocommand to execute */
9581 for (;;)
9582 {
9583 /* skip removed commands */
9584 while (acp->nextcmd != NULL && acp->nextcmd->cmd == NULL)
9585 if (acp->nextcmd->last)
9586 acp->nextcmd = NULL;
9587 else
9588 acp->nextcmd = acp->nextcmd->next;
9589
9590 if (acp->nextcmd != NULL)
9591 break;
9592
9593 /* at end of commands, find next pattern that matches */
9594 if (acp->curpat->last)
9595 acp->curpat = NULL;
9596 else
9597 acp->curpat = acp->curpat->next;
9598 if (acp->curpat != NULL)
9599 auto_next_pat(acp, TRUE);
9600 if (acp->curpat == NULL)
9601 return NULL;
9602 }
9603
9604 ac = acp->nextcmd;
9605
9606 if (p_verbose >= 9)
9607 {
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009608 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009609 smsg((char_u *)_("autocommand %s"), ac->cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009610 msg_puts((char_u *)"\n"); /* don't overwrite this either */
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009611 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009612 }
9613 retval = vim_strsave(ac->cmd);
9614 autocmd_nested = ac->nested;
9615#ifdef FEAT_EVAL
9616 current_SID = ac->scriptID;
9617#endif
9618 if (ac->last)
9619 acp->nextcmd = NULL;
9620 else
9621 acp->nextcmd = ac->next;
9622 return retval;
9623}
9624
9625/*
9626 * Return TRUE if there is a matching autocommand for "fname".
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009627 * To account for buffer-local autocommands, function needs to know
9628 * in which buffer the file will be opened.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009629 */
9630 int
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009631has_autocmd(event, sfname, buf)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009632 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009633 char_u *sfname;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009634 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009635{
9636 AutoPat *ap;
9637 char_u *fname;
9638 char_u *tail = gettail(sfname);
9639 int retval = FALSE;
9640
9641 fname = FullName_save(sfname, FALSE);
9642 if (fname == NULL)
9643 return FALSE;
9644
9645#ifdef BACKSLASH_IN_FILENAME
9646 /*
9647 * Replace all backslashes with forward slashes. This makes the
9648 * autocommand patterns portable between Unix and MS-DOS.
9649 */
9650 sfname = vim_strsave(sfname);
9651 if (sfname != NULL)
9652 forward_slash(sfname);
9653 forward_slash(fname);
9654#endif
9655
9656 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
9657 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009658 && (ap->buflocal_nr == 0
Bram Moolenaar748bf032005-02-02 23:04:36 +00009659 ? match_file_pat(NULL, ap->reg_prog,
9660 fname, sfname, tail, ap->allow_dirs)
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009661 : buf != NULL && ap->buflocal_nr == buf->b_fnum
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009662 ))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009663 {
9664 retval = TRUE;
9665 break;
9666 }
9667
9668 vim_free(fname);
9669#ifdef BACKSLASH_IN_FILENAME
9670 vim_free(sfname);
9671#endif
9672
9673 return retval;
9674}
9675
9676#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
9677/*
9678 * Function given to ExpandGeneric() to obtain the list of autocommand group
9679 * names.
9680 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009681 char_u *
9682get_augroup_name(xp, idx)
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009683 expand_T *xp UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009684 int idx;
9685{
9686 if (idx == augroups.ga_len) /* add "END" add the end */
9687 return (char_u *)"END";
9688 if (idx >= augroups.ga_len) /* end of list */
9689 return NULL;
9690 if (AUGROUP_NAME(idx) == NULL) /* skip deleted entries */
9691 return (char_u *)"";
9692 return AUGROUP_NAME(idx); /* return a name */
9693}
9694
9695static int include_groups = FALSE;
9696
9697 char_u *
9698set_context_in_autocmd(xp, arg, doautocmd)
9699 expand_T *xp;
9700 char_u *arg;
Bram Moolenaard812df62008-11-09 12:46:09 +00009701 int doautocmd; /* TRUE for :doauto*, FALSE for :autocmd */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009702{
9703 char_u *p;
9704 int group;
9705
9706 /* check for a group name, skip it if present */
9707 include_groups = FALSE;
9708 p = arg;
9709 group = au_get_grouparg(&arg);
9710 if (group == AUGROUP_ERROR)
9711 return NULL;
9712 /* If there only is a group name that's what we expand. */
9713 if (*arg == NUL && group != AUGROUP_ALL && !vim_iswhite(arg[-1]))
9714 {
9715 arg = p;
9716 group = AUGROUP_ALL;
9717 }
9718
9719 /* skip over event name */
9720 for (p = arg; *p != NUL && !vim_iswhite(*p); ++p)
9721 if (*p == ',')
9722 arg = p + 1;
9723 if (*p == NUL)
9724 {
9725 if (group == AUGROUP_ALL)
9726 include_groups = TRUE;
9727 xp->xp_context = EXPAND_EVENTS; /* expand event name */
9728 xp->xp_pattern = arg;
9729 return NULL;
9730 }
9731
9732 /* skip over pattern */
9733 arg = skipwhite(p);
9734 while (*arg && (!vim_iswhite(*arg) || arg[-1] == '\\'))
9735 arg++;
9736 if (*arg)
9737 return arg; /* expand (next) command */
9738
9739 if (doautocmd)
9740 xp->xp_context = EXPAND_FILES; /* expand file names */
9741 else
9742 xp->xp_context = EXPAND_NOTHING; /* pattern is not expanded */
9743 return NULL;
9744}
9745
9746/*
9747 * Function given to ExpandGeneric() to obtain the list of event names.
9748 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009749 char_u *
9750get_event_name(xp, idx)
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009751 expand_T *xp UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009752 int idx;
9753{
9754 if (idx < augroups.ga_len) /* First list group names, if wanted */
9755 {
9756 if (!include_groups || AUGROUP_NAME(idx) == NULL)
9757 return (char_u *)""; /* skip deleted entries */
9758 return AUGROUP_NAME(idx); /* return a name */
9759 }
9760 return (char_u *)event_names[idx - augroups.ga_len].name;
9761}
9762
9763#endif /* FEAT_CMDL_COMPL */
9764
9765/*
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009766 * Return TRUE if autocmd is supported.
9767 */
9768 int
9769autocmd_supported(name)
9770 char_u *name;
9771{
9772 char_u *p;
9773
9774 return (event_name2nr(name, &p) != NUM_EVENTS);
9775}
9776
9777/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00009778 * Return TRUE if an autocommand is defined for a group, event and
9779 * pattern: The group can be omitted to accept any group. "event" and "pattern"
9780 * can be NULL to accept any event and pattern. "pattern" can be NULL to accept
9781 * any pattern. Buffer-local patterns <buffer> or <buffer=N> are accepted.
9782 * Used for:
9783 * exists("#Group") or
9784 * exists("#Group#Event") or
9785 * exists("#Group#Event#pat") or
9786 * exists("#Event") or
9787 * exists("#Event#pat")
Bram Moolenaar071d4272004-06-13 20:20:40 +00009788 */
9789 int
Bram Moolenaar195d6352005-12-19 22:08:24 +00009790au_exists(arg)
9791 char_u *arg;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009792{
Bram Moolenaar195d6352005-12-19 22:08:24 +00009793 char_u *arg_save;
9794 char_u *pattern = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009795 char_u *event_name;
9796 char_u *p;
Bram Moolenaar754b5602006-02-09 23:53:20 +00009797 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009798 AutoPat *ap;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009799 buf_T *buflocal_buf = NULL;
Bram Moolenaar195d6352005-12-19 22:08:24 +00009800 int group;
9801 int retval = FALSE;
9802
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009803 /* Make a copy so that we can change the '#' chars to a NUL. */
Bram Moolenaar195d6352005-12-19 22:08:24 +00009804 arg_save = vim_strsave(arg);
9805 if (arg_save == NULL)
9806 return FALSE;
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009807 p = vim_strchr(arg_save, '#');
Bram Moolenaar195d6352005-12-19 22:08:24 +00009808 if (p != NULL)
9809 *p++ = NUL;
9810
9811 /* First, look for an autocmd group name */
9812 group = au_find_group(arg_save);
9813 if (group == AUGROUP_ERROR)
9814 {
9815 /* Didn't match a group name, assume the first argument is an event. */
9816 group = AUGROUP_ALL;
9817 event_name = arg_save;
9818 }
9819 else
9820 {
9821 if (p == NULL)
9822 {
9823 /* "Group": group name is present and it's recognized */
9824 retval = TRUE;
9825 goto theend;
9826 }
9827
9828 /* Must be "Group#Event" or "Group#Event#pat". */
9829 event_name = p;
9830 p = vim_strchr(event_name, '#');
9831 if (p != NULL)
9832 *p++ = NUL; /* "Group#Event#pat" */
9833 }
9834
9835 pattern = p; /* "pattern" is NULL when there is no pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009836
9837 /* find the index (enum) for the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009838 event = event_name2nr(event_name, &p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009839
9840 /* return FALSE if the event name is not recognized */
Bram Moolenaar195d6352005-12-19 22:08:24 +00009841 if (event == NUM_EVENTS)
9842 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009843
9844 /* Find the first autocommand for this event.
9845 * If there isn't any, return FALSE;
9846 * If there is one and no pattern given, return TRUE; */
9847 ap = first_autopat[(int)event];
9848 if (ap == NULL)
Bram Moolenaar195d6352005-12-19 22:08:24 +00009849 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009850
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009851 /* if pattern is "<buffer>", special handling is needed which uses curbuf */
9852 /* for pattern "<buffer=N>, fnamecmp() will work fine */
Bram Moolenaar5b7880d2009-09-11 15:24:31 +00009853 if (pattern != NULL && STRICMP(pattern, "<buffer>") == 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009854 buflocal_buf = curbuf;
9855
Bram Moolenaar071d4272004-06-13 20:20:40 +00009856 /* Check if there is an autocommand with the given pattern. */
9857 for ( ; ap != NULL; ap = ap->next)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009858 /* only use a pattern when it has not been removed and has commands. */
9859 /* For buffer-local autocommands, fnamecmp() works fine. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009860 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaar195d6352005-12-19 22:08:24 +00009861 && (group == AUGROUP_ALL || ap->group == group)
Bram Moolenaar5b7880d2009-09-11 15:24:31 +00009862 && (pattern == NULL
9863 || (buflocal_buf == NULL
9864 ? fnamecmp(ap->pat, pattern) == 0
9865 : ap->buflocal_nr == buflocal_buf->b_fnum)))
Bram Moolenaar195d6352005-12-19 22:08:24 +00009866 {
9867 retval = TRUE;
9868 break;
9869 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009870
Bram Moolenaar195d6352005-12-19 22:08:24 +00009871theend:
9872 vim_free(arg_save);
9873 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009874}
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009875
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009876#else /* FEAT_AUTOCMD */
9877
9878/*
9879 * Prepare for executing commands for (hidden) buffer "buf".
9880 * This is the non-autocommand version, it simply saves "curbuf" and sets
9881 * "curbuf" and "curwin" to match "buf".
9882 */
9883 void
9884aucmd_prepbuf(aco, buf)
9885 aco_save_T *aco; /* structure to save values in */
9886 buf_T *buf; /* new curbuf */
9887{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009888 aco->save_curbuf = curbuf;
9889 --curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009890 curbuf = buf;
9891 curwin->w_buffer = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009892 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009893}
9894
9895/*
9896 * Restore after executing commands for a (hidden) buffer.
9897 * This is the non-autocommand version.
9898 */
9899 void
9900aucmd_restbuf(aco)
9901 aco_save_T *aco; /* structure holding saved values */
9902{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009903 --curbuf->b_nwindows;
9904 curbuf = aco->save_curbuf;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009905 curwin->w_buffer = curbuf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009906 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009907}
9908
Bram Moolenaar071d4272004-06-13 20:20:40 +00009909#endif /* FEAT_AUTOCMD */
9910
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009911
Bram Moolenaar071d4272004-06-13 20:20:40 +00009912#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN) || defined(PROTO)
9913/*
Bram Moolenaar748bf032005-02-02 23:04:36 +00009914 * Try matching a filename with a "pattern" ("prog" is NULL), or use the
9915 * precompiled regprog "prog" ("pattern" is NULL). That avoids calling
9916 * vim_regcomp() often.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009917 * Used for autocommands and 'wildignore'.
9918 * Returns TRUE if there is a match, FALSE otherwise.
9919 */
9920 int
Bram Moolenaar748bf032005-02-02 23:04:36 +00009921match_file_pat(pattern, prog, fname, sfname, tail, allow_dirs)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009922 char_u *pattern; /* pattern to match with */
Bram Moolenaar748bf032005-02-02 23:04:36 +00009923 regprog_T *prog; /* pre-compiled regprog or NULL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009924 char_u *fname; /* full path of file name */
9925 char_u *sfname; /* short file name or NULL */
9926 char_u *tail; /* tail of path */
9927 int allow_dirs; /* allow matching with dir */
9928{
9929 regmatch_T regmatch;
9930 int result = FALSE;
9931#ifdef FEAT_OSFILETYPE
9932 int no_pattern = FALSE; /* TRUE if check is filetype only */
9933 char_u *type_start;
9934 char_u c;
9935 int match = FALSE;
9936#endif
9937
9938#ifdef CASE_INSENSITIVE_FILENAME
9939 regmatch.rm_ic = TRUE; /* Always ignore case */
9940#else
9941 regmatch.rm_ic = FALSE; /* Don't ever ignore case */
9942#endif
9943#ifdef FEAT_OSFILETYPE
9944 if (*pattern == '<')
9945 {
9946 /* There is a filetype condition specified with this pattern.
9947 * Check the filetype matches first. If not, don't bother with the
9948 * pattern (set regprog to NULL).
9949 * Always use magic for the regexp.
9950 */
9951
9952 for (type_start = pattern + 1; (c = *pattern); pattern++)
9953 {
9954 if ((c == ';' || c == '>') && match == FALSE)
9955 {
9956 *pattern = NUL; /* Terminate the string */
9957 match = mch_check_filetype(fname, type_start);
9958 *pattern = c; /* Restore the terminator */
9959 type_start = pattern + 1;
9960 }
9961 if (c == '>')
9962 break;
9963 }
9964
9965 /* (c should never be NUL, but check anyway) */
9966 if (match == FALSE || c == NUL)
9967 regmatch.regprog = NULL; /* Doesn't match - don't check pat. */
9968 else if (*pattern == NUL)
9969 {
9970 regmatch.regprog = NULL; /* Vim will try to free regprog later */
9971 no_pattern = TRUE; /* Always matches - don't check pat. */
9972 }
9973 else
9974 regmatch.regprog = vim_regcomp(pattern + 1, RE_MAGIC);
9975 }
9976 else
9977#endif
Bram Moolenaar748bf032005-02-02 23:04:36 +00009978 {
9979 if (prog != NULL)
9980 regmatch.regprog = prog;
9981 else
9982 regmatch.regprog = vim_regcomp(pattern, RE_MAGIC);
9983 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009984
9985 /*
9986 * Try for a match with the pattern with:
9987 * 1. the full file name, when the pattern has a '/'.
9988 * 2. the short file name, when the pattern has a '/'.
9989 * 3. the tail of the file name, when the pattern has no '/'.
9990 */
9991 if (
9992#ifdef FEAT_OSFILETYPE
9993 /* If the check is for a filetype only and we don't care
9994 * about the path then skip all the regexp stuff.
9995 */
9996 no_pattern ||
9997#endif
9998 (regmatch.regprog != NULL
9999 && ((allow_dirs
10000 && (vim_regexec(&regmatch, fname, (colnr_T)0)
10001 || (sfname != NULL
10002 && vim_regexec(&regmatch, sfname, (colnr_T)0))))
10003 || (!allow_dirs && vim_regexec(&regmatch, tail, (colnr_T)0)))))
10004 result = TRUE;
10005
Bram Moolenaar748bf032005-02-02 23:04:36 +000010006 if (prog == NULL)
10007 vim_free(regmatch.regprog);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010008 return result;
10009}
10010#endif
10011
10012#if defined(FEAT_WILDIGN) || defined(PROTO)
10013/*
10014 * Return TRUE if a file matches with a pattern in "list".
10015 * "list" is a comma-separated list of patterns, like 'wildignore'.
10016 * "sfname" is the short file name or NULL, "ffname" the long file name.
10017 */
10018 int
10019match_file_list(list, sfname, ffname)
10020 char_u *list;
10021 char_u *sfname;
10022 char_u *ffname;
10023{
10024 char_u buf[100];
10025 char_u *tail;
10026 char_u *regpat;
10027 char allow_dirs;
10028 int match;
10029 char_u *p;
10030
10031 tail = gettail(sfname);
10032
10033 /* try all patterns in 'wildignore' */
10034 p = list;
10035 while (*p)
10036 {
10037 copy_option_part(&p, buf, 100, ",");
10038 regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, FALSE);
10039 if (regpat == NULL)
10040 break;
Bram Moolenaar748bf032005-02-02 23:04:36 +000010041 match = match_file_pat(regpat, NULL, ffname, sfname,
10042 tail, (int)allow_dirs);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010043 vim_free(regpat);
10044 if (match)
10045 return TRUE;
10046 }
10047 return FALSE;
10048}
10049#endif
10050
10051/*
10052 * Convert the given pattern "pat" which has shell style wildcards in it, into
10053 * a regular expression, and return the result in allocated memory. If there
10054 * is a directory path separator to be matched, then TRUE is put in
10055 * allow_dirs, otherwise FALSE is put there -- webb.
10056 * Handle backslashes before special characters, like "\*" and "\ ".
10057 *
10058 * If FEAT_OSFILETYPE defined then pass initial <type> through unchanged. Eg:
10059 * '<html>myfile' becomes '<html>^myfile$' -- leonard.
10060 *
10061 * Returns NULL when out of memory.
10062 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010063 char_u *
10064file_pat_to_reg_pat(pat, pat_end, allow_dirs, no_bslash)
10065 char_u *pat;
10066 char_u *pat_end; /* first char after pattern or NULL */
10067 char *allow_dirs; /* Result passed back out in here */
Bram Moolenaar78a15312009-05-15 19:33:18 +000010068 int no_bslash UNUSED; /* Don't use a backward slash as pathsep */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010069{
10070 int size;
10071 char_u *endp;
10072 char_u *reg_pat;
10073 char_u *p;
10074 int i;
10075 int nested = 0;
10076 int add_dollar = TRUE;
10077#ifdef FEAT_OSFILETYPE
10078 int check_length = 0;
10079#endif
10080
10081 if (allow_dirs != NULL)
10082 *allow_dirs = FALSE;
10083 if (pat_end == NULL)
10084 pat_end = pat + STRLEN(pat);
10085
10086#ifdef FEAT_OSFILETYPE
10087 /* Find out how much of the string is the filetype check */
10088 if (*pat == '<')
10089 {
10090 /* Count chars until the next '>' */
10091 for (p = pat + 1; p < pat_end && *p != '>'; p++)
10092 ;
10093 if (p < pat_end)
10094 {
10095 /* Pattern is of the form <.*>.* */
10096 check_length = p - pat + 1;
10097 if (p + 1 >= pat_end)
10098 {
10099 /* The 'pattern' is a filetype check ONLY */
10100 reg_pat = (char_u *)alloc(check_length + 1);
10101 if (reg_pat != NULL)
10102 {
10103 mch_memmove(reg_pat, pat, (size_t)check_length);
10104 reg_pat[check_length] = NUL;
10105 }
10106 return reg_pat;
10107 }
10108 }
10109 /* else: there was no closing '>' - assume it was a normal pattern */
10110
10111 }
10112 pat += check_length;
10113 size = 2 + check_length;
10114#else
10115 size = 2; /* '^' at start, '$' at end */
10116#endif
10117
10118 for (p = pat; p < pat_end; p++)
10119 {
10120 switch (*p)
10121 {
10122 case '*':
10123 case '.':
10124 case ',':
10125 case '{':
10126 case '}':
10127 case '~':
10128 size += 2; /* extra backslash */
10129 break;
10130#ifdef BACKSLASH_IN_FILENAME
10131 case '\\':
10132 case '/':
10133 size += 4; /* could become "[\/]" */
10134 break;
10135#endif
10136 default:
10137 size++;
10138# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010139 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010140 {
10141 ++p;
10142 ++size;
10143 }
10144# endif
10145 break;
10146 }
10147 }
10148 reg_pat = alloc(size + 1);
10149 if (reg_pat == NULL)
10150 return NULL;
10151
10152#ifdef FEAT_OSFILETYPE
10153 /* Copy the type check in to the start. */
10154 if (check_length)
10155 mch_memmove(reg_pat, pat - check_length, (size_t)check_length);
10156 i = check_length;
10157#else
10158 i = 0;
10159#endif
10160
10161 if (pat[0] == '*')
10162 while (pat[0] == '*' && pat < pat_end - 1)
10163 pat++;
10164 else
10165 reg_pat[i++] = '^';
10166 endp = pat_end - 1;
10167 if (*endp == '*')
10168 {
10169 while (endp - pat > 0 && *endp == '*')
10170 endp--;
10171 add_dollar = FALSE;
10172 }
10173 for (p = pat; *p && nested >= 0 && p <= endp; p++)
10174 {
10175 switch (*p)
10176 {
10177 case '*':
10178 reg_pat[i++] = '.';
10179 reg_pat[i++] = '*';
Bram Moolenaar02743632005-07-25 20:42:36 +000010180 while (p[1] == '*') /* "**" matches like "*" */
10181 ++p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010182 break;
10183 case '.':
10184#ifdef RISCOS
10185 if (allow_dirs != NULL)
10186 *allow_dirs = TRUE;
10187 /* FALLTHROUGH */
10188#endif
10189 case '~':
10190 reg_pat[i++] = '\\';
10191 reg_pat[i++] = *p;
10192 break;
10193 case '?':
10194#ifdef RISCOS
10195 case '#':
10196#endif
10197 reg_pat[i++] = '.';
10198 break;
10199 case '\\':
10200 if (p[1] == NUL)
10201 break;
10202#ifdef BACKSLASH_IN_FILENAME
10203 if (!no_bslash)
10204 {
10205 /* translate:
10206 * "\x" to "\\x" e.g., "dir\file"
10207 * "\*" to "\\.*" e.g., "dir\*.c"
10208 * "\?" to "\\." e.g., "dir\??.c"
10209 * "\+" to "\+" e.g., "fileX\+.c"
10210 */
10211 if ((vim_isfilec(p[1]) || p[1] == '*' || p[1] == '?')
10212 && p[1] != '+')
10213 {
10214 reg_pat[i++] = '[';
10215 reg_pat[i++] = '\\';
10216 reg_pat[i++] = '/';
10217 reg_pat[i++] = ']';
10218 if (allow_dirs != NULL)
10219 *allow_dirs = TRUE;
10220 break;
10221 }
10222 }
10223#endif
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010224 /* Undo escaping from ExpandEscape():
10225 * foo\?bar -> foo?bar
10226 * foo\%bar -> foo%bar
10227 * foo\,bar -> foo,bar
10228 * foo\ bar -> foo bar
10229 * Don't unescape \, * and others that are also special in a
10230 * regexp. */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010231 if (*++p == '?'
10232#ifdef BACKSLASH_IN_FILENAME
10233 && no_bslash
10234#endif
10235 )
10236 reg_pat[i++] = '?';
10237 else
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010238 if (*p == ',' || *p == '%' || *p == '#' || *p == ' ')
10239 reg_pat[i++] = *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010240 else
10241 {
10242 if (allow_dirs != NULL && vim_ispathsep(*p)
10243#ifdef BACKSLASH_IN_FILENAME
10244 && (!no_bslash || *p != '\\')
10245#endif
10246 )
10247 *allow_dirs = TRUE;
10248 reg_pat[i++] = '\\';
10249 reg_pat[i++] = *p;
10250 }
10251 break;
10252#ifdef BACKSLASH_IN_FILENAME
10253 case '/':
10254 reg_pat[i++] = '[';
10255 reg_pat[i++] = '\\';
10256 reg_pat[i++] = '/';
10257 reg_pat[i++] = ']';
10258 if (allow_dirs != NULL)
10259 *allow_dirs = TRUE;
10260 break;
10261#endif
10262 case '{':
10263 reg_pat[i++] = '\\';
10264 reg_pat[i++] = '(';
10265 nested++;
10266 break;
10267 case '}':
10268 reg_pat[i++] = '\\';
10269 reg_pat[i++] = ')';
10270 --nested;
10271 break;
10272 case ',':
10273 if (nested)
10274 {
10275 reg_pat[i++] = '\\';
10276 reg_pat[i++] = '|';
10277 }
10278 else
10279 reg_pat[i++] = ',';
10280 break;
10281 default:
10282# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010283 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010284 reg_pat[i++] = *p++;
10285 else
10286# endif
10287 if (allow_dirs != NULL && vim_ispathsep(*p))
10288 *allow_dirs = TRUE;
10289 reg_pat[i++] = *p;
10290 break;
10291 }
10292 }
10293 if (add_dollar)
10294 reg_pat[i++] = '$';
10295 reg_pat[i] = NUL;
10296 if (nested != 0)
10297 {
10298 if (nested < 0)
10299 EMSG(_("E219: Missing {."));
10300 else
10301 EMSG(_("E220: Missing }."));
10302 vim_free(reg_pat);
10303 reg_pat = NULL;
10304 }
10305 return reg_pat;
10306}