blob: c3ff07c47379e946cea5259ca2f3765d8c86592c [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)
15# include <io.h> /* for lseek(), must be before vim.h */
16#endif
17
18#if defined __EMX__
19# include <io.h> /* for mktemp(), CJW 1997-12-03 */
20#endif
21
22#include "vim.h"
23
24#ifdef HAVE_FCNTL_H
25# include <fcntl.h>
26#endif
27
28#ifdef __TANDEM
29# include <limits.h> /* for SSIZE_MAX */
30#endif
31
32#if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
33# include <utime.h> /* for struct utimbuf */
34#endif
35
36#define BUFSIZE 8192 /* size of normal write buffer */
37#define SMBUFSIZE 256 /* size of emergency write buffer */
38
39#ifdef FEAT_CRYPT
40# define CRYPT_MAGIC "VimCrypt~01!" /* "01" is the version nr */
41# define CRYPT_MAGIC_LEN 12 /* must be multiple of 4! */
42#endif
43
44/* Is there any system that doesn't have access()? */
Bram Moolenaar9372a112005-12-06 19:59:18 +000045#define USE_MCH_ACCESS
Bram Moolenaar071d4272004-06-13 20:20:40 +000046
47#ifdef FEAT_MBYTE
48static char_u *next_fenc __ARGS((char_u **pp));
49# ifdef FEAT_EVAL
50static char_u *readfile_charconvert __ARGS((char_u *fname, char_u *fenc, int *fdp));
51# endif
52#endif
53#ifdef FEAT_VIMINFO
54static void check_marks_read __ARGS((void));
55#endif
56#ifdef FEAT_CRYPT
57static char_u *check_for_cryptkey __ARGS((char_u *cryptkey, char_u *ptr, long *sizep, long *filesizep, int newfile));
58#endif
59#ifdef UNIX
60static void set_file_time __ARGS((char_u *fname, time_t atime, time_t mtime));
61#endif
Bram Moolenaar2d3f4892006-01-20 23:02:51 +000062static int set_rw_fname __ARGS((char_u *fname, char_u *sfname));
Bram Moolenaar071d4272004-06-13 20:20:40 +000063static int msg_add_fileformat __ARGS((int eol_type));
Bram Moolenaar071d4272004-06-13 20:20:40 +000064static void msg_add_eol __ARGS((void));
65static int check_mtime __ARGS((buf_T *buf, struct stat *s));
66static int time_differs __ARGS((long t1, long t2));
67#ifdef FEAT_AUTOCMD
Bram Moolenaar754b5602006-02-09 23:53:20 +000068static 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 +000069static int au_find_group __ARGS((char_u *name));
70
71# define AUGROUP_DEFAULT -1 /* default autocmd group */
72# define AUGROUP_ERROR -2 /* errornouse autocmd group */
73# define AUGROUP_ALL -3 /* all autocmd groups */
Bram Moolenaar071d4272004-06-13 20:20:40 +000074#endif
75
76#if defined(FEAT_CRYPT) || defined(FEAT_MBYTE)
77# define HAS_BW_FLAGS
78# define FIO_LATIN1 0x01 /* convert Latin1 */
79# define FIO_UTF8 0x02 /* convert UTF-8 */
80# define FIO_UCS2 0x04 /* convert UCS-2 */
81# define FIO_UCS4 0x08 /* convert UCS-4 */
82# define FIO_UTF16 0x10 /* convert UTF-16 */
83# ifdef WIN3264
84# define FIO_CODEPAGE 0x20 /* convert MS-Windows codepage */
85# define FIO_PUT_CP(x) (((x) & 0xffff) << 16) /* put codepage in top word */
86# define FIO_GET_CP(x) (((x)>>16) & 0xffff) /* get codepage from top word */
87# endif
88# ifdef MACOS_X
89# define FIO_MACROMAN 0x20 /* convert MacRoman */
90# endif
91# define FIO_ENDIAN_L 0x80 /* little endian */
92# define FIO_ENCRYPTED 0x1000 /* encrypt written bytes */
93# define FIO_NOCONVERT 0x2000 /* skip encoding conversion */
94# define FIO_UCSBOM 0x4000 /* check for BOM at start of file */
95# define FIO_ALL -1 /* allow all formats */
96#endif
97
98/* When converting, a read() or write() may leave some bytes to be converted
99 * for the next call. The value is guessed... */
100#define CONV_RESTLEN 30
101
102/* We have to guess how much a sequence of bytes may expand when converting
103 * with iconv() to be able to allocate a buffer. */
104#define ICONV_MULT 8
105
106/*
107 * Structure to pass arguments from buf_write() to buf_write_bytes().
108 */
109struct bw_info
110{
111 int bw_fd; /* file descriptor */
112 char_u *bw_buf; /* buffer with data to be written */
113 int bw_len; /* lenght of data */
114#ifdef HAS_BW_FLAGS
115 int bw_flags; /* FIO_ flags */
116#endif
117#ifdef FEAT_MBYTE
118 char_u bw_rest[CONV_RESTLEN]; /* not converted bytes */
119 int bw_restlen; /* nr of bytes in bw_rest[] */
120 int bw_first; /* first write call */
121 char_u *bw_conv_buf; /* buffer for writing converted chars */
122 int bw_conv_buflen; /* size of bw_conv_buf */
123 int bw_conv_error; /* set for conversion error */
124# ifdef USE_ICONV
125 iconv_t bw_iconv_fd; /* descriptor for iconv() or -1 */
126# endif
127#endif
128};
129
130static int buf_write_bytes __ARGS((struct bw_info *ip));
131
132#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000133static linenr_T readfile_linenr __ARGS((linenr_T linecnt, char_u *p, char_u *endp));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000134static int ucs2bytes __ARGS((unsigned c, char_u **pp, int flags));
135static int same_encoding __ARGS((char_u *a, char_u *b));
136static int get_fio_flags __ARGS((char_u *ptr));
137static char_u *check_for_bom __ARGS((char_u *p, long size, int *lenp, int flags));
138static int make_bom __ARGS((char_u *buf, char_u *name));
139# ifdef WIN3264
140static int get_win_fio_flags __ARGS((char_u *ptr));
141# endif
142# ifdef MACOS_X
143static int get_mac_fio_flags __ARGS((char_u *ptr));
144# endif
145#endif
146static int move_lines __ARGS((buf_T *frombuf, buf_T *tobuf));
147
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000148
Bram Moolenaar071d4272004-06-13 20:20:40 +0000149 void
150filemess(buf, name, s, attr)
151 buf_T *buf;
152 char_u *name;
153 char_u *s;
154 int attr;
155{
156 int msg_scroll_save;
157
158 if (msg_silent != 0)
159 return;
160 msg_add_fname(buf, name); /* put file name in IObuff with quotes */
161 /* If it's extremely long, truncate it. */
162 if (STRLEN(IObuff) > IOSIZE - 80)
163 IObuff[IOSIZE - 80] = NUL;
164 STRCAT(IObuff, s);
165 /*
166 * For the first message may have to start a new line.
167 * For further ones overwrite the previous one, reset msg_scroll before
168 * calling filemess().
169 */
170 msg_scroll_save = msg_scroll;
171 if (shortmess(SHM_OVERALL) && !exiting && p_verbose == 0)
172 msg_scroll = FALSE;
173 if (!msg_scroll) /* wait a bit when overwriting an error msg */
174 check_for_delay(FALSE);
175 msg_start();
176 msg_scroll = msg_scroll_save;
177 msg_scrolled_ign = TRUE;
178 /* may truncate the message to avoid a hit-return prompt */
179 msg_outtrans_attr(msg_may_trunc(FALSE, IObuff), attr);
180 msg_clr_eos();
181 out_flush();
182 msg_scrolled_ign = FALSE;
183}
184
185/*
186 * Read lines from file "fname" into the buffer after line "from".
187 *
188 * 1. We allocate blocks with lalloc, as big as possible.
189 * 2. Each block is filled with characters from the file with a single read().
190 * 3. The lines are inserted in the buffer with ml_append().
191 *
192 * (caller must check that fname != NULL, unless READ_STDIN is used)
193 *
194 * "lines_to_skip" is the number of lines that must be skipped
195 * "lines_to_read" is the number of lines that are appended
196 * When not recovering lines_to_skip is 0 and lines_to_read MAXLNUM.
197 *
198 * flags:
199 * READ_NEW starting to edit a new buffer
200 * READ_FILTER reading filter output
201 * READ_STDIN read from stdin instead of a file
202 * READ_BUFFER read from curbuf instead of a file (converting after reading
203 * stdin)
204 * READ_DUMMY read into a dummy buffer (to check if file contents changed)
205 *
206 * return FAIL for failure, OK otherwise
207 */
208 int
209readfile(fname, sfname, from, lines_to_skip, lines_to_read, eap, flags)
210 char_u *fname;
211 char_u *sfname;
212 linenr_T from;
213 linenr_T lines_to_skip;
214 linenr_T lines_to_read;
215 exarg_T *eap; /* can be NULL! */
216 int flags;
217{
218 int fd = 0;
219 int newfile = (flags & READ_NEW);
220 int check_readonly;
221 int filtering = (flags & READ_FILTER);
222 int read_stdin = (flags & READ_STDIN);
223 int read_buffer = (flags & READ_BUFFER);
224 linenr_T read_buf_lnum = 1; /* next line to read from curbuf */
225 colnr_T read_buf_col = 0; /* next char to read from this line */
226 char_u c;
227 linenr_T lnum = from;
228 char_u *ptr = NULL; /* pointer into read buffer */
229 char_u *buffer = NULL; /* read buffer */
230 char_u *new_buffer = NULL; /* init to shut up gcc */
231 char_u *line_start = NULL; /* init to shut up gcc */
232 int wasempty; /* buffer was empty before reading */
233 colnr_T len;
234 long size = 0;
235 char_u *p;
236 long filesize = 0;
237 int skip_read = FALSE;
238#ifdef FEAT_CRYPT
239 char_u *cryptkey = NULL;
240#endif
241 int split = 0; /* number of split lines */
242#define UNKNOWN 0x0fffffff /* file size is unknown */
243 linenr_T linecnt;
244 int error = FALSE; /* errors encountered */
245 int ff_error = EOL_UNKNOWN; /* file format with errors */
246 long linerest = 0; /* remaining chars in line */
247#ifdef UNIX
248 int perm = 0;
249 int swap_mode = -1; /* protection bits for swap file */
250#else
251 int perm;
252#endif
253 int fileformat = 0; /* end-of-line format */
254 int keep_fileformat = FALSE;
255 struct stat st;
256 int file_readonly;
257 linenr_T skip_count = 0;
258 linenr_T read_count = 0;
259 int msg_save = msg_scroll;
260 linenr_T read_no_eol_lnum = 0; /* non-zero lnum when last line of
261 * last read was missing the eol */
262 int try_mac = (vim_strchr(p_ffs, 'm') != NULL);
263 int try_dos = (vim_strchr(p_ffs, 'd') != NULL);
264 int try_unix = (vim_strchr(p_ffs, 'x') != NULL);
265 int file_rewind = FALSE;
266#ifdef FEAT_MBYTE
267 int can_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000268 linenr_T conv_error = 0; /* line nr with conversion error */
269 linenr_T illegal_byte = 0; /* line nr with illegal byte */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000270 int keep_dest_enc = FALSE; /* don't retry when char doesn't fit
271 in destination encoding */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000272 int bad_char_behavior = BAD_REPLACE;
273 /* BAD_KEEP, BAD_DROP or character to
274 * replace with */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000275 char_u *tmpname = NULL; /* name of 'charconvert' output file */
276 int fio_flags = 0;
277 char_u *fenc; /* fileencoding to use */
278 int fenc_alloced; /* fenc_next is in allocated memory */
279 char_u *fenc_next = NULL; /* next item in 'fencs' or NULL */
280 int advance_fenc = FALSE;
281 long real_size = 0;
282# ifdef USE_ICONV
283 iconv_t iconv_fd = (iconv_t)-1; /* descriptor for iconv() or -1 */
284# ifdef FEAT_EVAL
285 int did_iconv = FALSE; /* TRUE when iconv() failed and trying
286 'charconvert' next */
287# endif
288# endif
289 int converted = FALSE; /* TRUE if conversion done */
290 int notconverted = FALSE; /* TRUE if conversion wanted but it
291 wasn't possible */
292 char_u conv_rest[CONV_RESTLEN];
293 int conv_restlen = 0; /* nr of bytes in conv_rest[] */
294#endif
295
Bram Moolenaar071d4272004-06-13 20:20:40 +0000296 write_no_eol_lnum = 0; /* in case it was set by the previous read */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000297
298 /*
299 * If there is no file name yet, use the one for the read file.
300 * BF_NOTEDITED is set to reflect this.
301 * Don't do this for a read from a filter.
302 * Only do this when 'cpoptions' contains the 'f' flag.
303 */
304 if (curbuf->b_ffname == NULL
305 && !filtering
306 && fname != NULL
307 && vim_strchr(p_cpo, CPO_FNAMER) != NULL
308 && !(flags & READ_DUMMY))
309 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000310 if (set_rw_fname(fname, sfname) == FAIL)
311 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000312 }
313
Bram Moolenaardf177f62005-02-22 08:39:57 +0000314 /* After reading a file the cursor line changes but we don't want to
315 * display the line. */
316 ex_no_reprint = TRUE;
317
Bram Moolenaar071d4272004-06-13 20:20:40 +0000318 /*
319 * For Unix: Use the short file name whenever possible.
320 * Avoids problems with networks and when directory names are changed.
321 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
322 * another directory, which we don't detect.
323 */
324 if (sfname == NULL)
325 sfname = fname;
326#if defined(UNIX) || defined(__EMX__)
327 fname = sfname;
328#endif
329
330#ifdef FEAT_AUTOCMD
331 /*
332 * The BufReadCmd and FileReadCmd events intercept the reading process by
333 * executing the associated commands instead.
334 */
335 if (!filtering && !read_stdin && !read_buffer)
336 {
337 pos_T pos;
338
339 pos = curbuf->b_op_start;
340
341 /* Set '[ mark to the line above where the lines go (line 1 if zero). */
342 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
343 curbuf->b_op_start.col = 0;
344
345 if (newfile)
346 {
347 if (apply_autocmds_exarg(EVENT_BUFREADCMD, NULL, sfname,
348 FALSE, curbuf, eap))
349#ifdef FEAT_EVAL
350 return aborting() ? FAIL : OK;
351#else
352 return OK;
353#endif
354 }
355 else if (apply_autocmds_exarg(EVENT_FILEREADCMD, sfname, sfname,
356 FALSE, NULL, eap))
357#ifdef FEAT_EVAL
358 return aborting() ? FAIL : OK;
359#else
360 return OK;
361#endif
362
363 curbuf->b_op_start = pos;
364 }
365#endif
366
367 if ((shortmess(SHM_OVER) || curbuf->b_help) && p_verbose == 0)
368 msg_scroll = FALSE; /* overwrite previous file message */
369 else
370 msg_scroll = TRUE; /* don't overwrite previous file message */
371
372 /*
373 * If the name ends in a path separator, we can't open it. Check here,
374 * because reading the file may actually work, but then creating the swap
375 * file may destroy it! Reported on MS-DOS and Win 95.
376 * If the name is too long we might crash further on, quit here.
377 */
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000378 if (fname != NULL && *fname != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000379 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000380 p = fname + STRLEN(fname);
381 if (after_pathsep(fname, p) || STRLEN(fname) >= MAXPATHL)
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000382 {
383 filemess(curbuf, fname, (char_u *)_("Illegal file name"), 0);
384 msg_end();
385 msg_scroll = msg_save;
386 return FAIL;
387 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000388 }
389
390#ifdef UNIX
391 /*
392 * On Unix it is possible to read a directory, so we have to
393 * check for it before the mch_open().
394 */
395 if (!read_stdin && !read_buffer)
396 {
397 perm = mch_getperm(fname);
398 if (perm >= 0 && !S_ISREG(perm) /* not a regular file ... */
399# ifdef S_ISFIFO
400 && !S_ISFIFO(perm) /* ... or fifo */
401# endif
402# ifdef S_ISSOCK
403 && !S_ISSOCK(perm) /* ... or socket */
404# endif
405 )
406 {
407 if (S_ISDIR(perm))
408 filemess(curbuf, fname, (char_u *)_("is a directory"), 0);
409 else
410 filemess(curbuf, fname, (char_u *)_("is not a file"), 0);
411 msg_end();
412 msg_scroll = msg_save;
413 return FAIL;
414 }
415 }
416#endif
417
418 /* set default 'fileformat' */
419 if (newfile)
420 {
421 if (eap != NULL && eap->force_ff != 0)
422 set_fileformat(get_fileformat_force(curbuf, eap), OPT_LOCAL);
423 else if (*p_ffs != NUL)
424 set_fileformat(default_fileformat(), OPT_LOCAL);
425 }
426
427 /* set or reset 'binary' */
428 if (eap != NULL && eap->force_bin != 0)
429 {
430 int oldval = curbuf->b_p_bin;
431
432 curbuf->b_p_bin = (eap->force_bin == FORCE_BIN);
433 set_options_bin(oldval, curbuf->b_p_bin, OPT_LOCAL);
434 }
435
436 /*
437 * When opening a new file we take the readonly flag from the file.
438 * Default is r/w, can be set to r/o below.
439 * Don't reset it when in readonly mode
440 * Only set/reset b_p_ro when BF_CHECK_RO is set.
441 */
442 check_readonly = (newfile && (curbuf->b_flags & BF_CHECK_RO));
Bram Moolenaar4399ef42005-02-12 14:29:27 +0000443 if (check_readonly && !readonlymode)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000444 curbuf->b_p_ro = FALSE;
445
446 if (newfile && !read_stdin && !read_buffer)
447 {
448 /* Remember time of file.
449 * For RISCOS, also remember the filetype.
450 */
451 if (mch_stat((char *)fname, &st) >= 0)
452 {
453 buf_store_time(curbuf, &st, fname);
454 curbuf->b_mtime_read = curbuf->b_mtime;
455
456#if defined(RISCOS) && defined(FEAT_OSFILETYPE)
457 /* Read the filetype into the buffer local filetype option. */
458 mch_read_filetype(fname);
459#endif
460#ifdef UNIX
461 /*
462 * Use the protection bits of the original file for the swap file.
463 * This makes it possible for others to read the name of the
464 * edited file from the swapfile, but only if they can read the
465 * edited file.
466 * Remove the "write" and "execute" bits for group and others
467 * (they must not write the swapfile).
468 * Add the "read" and "write" bits for the user, otherwise we may
469 * not be able to write to the file ourselves.
470 * Setting the bits is done below, after creating the swap file.
471 */
472 swap_mode = (st.st_mode & 0644) | 0600;
473#endif
474#ifdef FEAT_CW_EDITOR
475 /* Get the FSSpec on MacOS
476 * TODO: Update it properly when the buffer name changes
477 */
478 (void)GetFSSpecFromPath(curbuf->b_ffname, &curbuf->b_FSSpec);
479#endif
480#ifdef VMS
481 curbuf->b_fab_rfm = st.st_fab_rfm;
Bram Moolenaard4755bb2004-09-02 19:12:26 +0000482 curbuf->b_fab_rat = st.st_fab_rat;
483 curbuf->b_fab_mrs = st.st_fab_mrs;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000484#endif
485 }
486 else
487 {
488 curbuf->b_mtime = 0;
489 curbuf->b_mtime_read = 0;
490 curbuf->b_orig_size = 0;
491 curbuf->b_orig_mode = 0;
492 }
493
494 /* Reset the "new file" flag. It will be set again below when the
495 * file doesn't exist. */
496 curbuf->b_flags &= ~(BF_NEW | BF_NEW_W);
497 }
498
499/*
500 * for UNIX: check readonly with perm and mch_access()
501 * for RISCOS: same as Unix, otherwise file gets re-datestamped!
502 * for MSDOS and Amiga: check readonly by trying to open the file for writing
503 */
504 file_readonly = FALSE;
505 if (read_stdin)
506 {
507#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
508 /* Force binary I/O on stdin to avoid CR-LF -> LF conversion. */
509 setmode(0, O_BINARY);
510#endif
511 }
512 else if (!read_buffer)
513 {
514#ifdef USE_MCH_ACCESS
515 if (
516# ifdef UNIX
517 !(perm & 0222) ||
518# endif
519 mch_access((char *)fname, W_OK))
520 file_readonly = TRUE;
521 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
522#else
523 if (!newfile
524 || readonlymode
525 || (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0)
526 {
527 file_readonly = TRUE;
528 /* try to open ro */
529 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
530 }
531#endif
532 }
533
534 if (fd < 0) /* cannot open at all */
535 {
536#ifndef UNIX
537 int isdir_f;
538#endif
539 msg_scroll = msg_save;
540#ifndef UNIX
541 /*
542 * On MSDOS and Amiga we can't open a directory, check here.
543 */
544 isdir_f = (mch_isdir(fname));
545 perm = mch_getperm(fname); /* check if the file exists */
546 if (isdir_f)
547 {
548 filemess(curbuf, sfname, (char_u *)_("is a directory"), 0);
549 curbuf->b_p_ro = TRUE; /* must use "w!" now */
550 }
551 else
552#endif
553 if (newfile)
554 {
555 if (perm < 0)
556 {
557 /*
558 * Set the 'new-file' flag, so that when the file has
559 * been created by someone else, a ":w" will complain.
560 */
561 curbuf->b_flags |= BF_NEW;
562
563 /* Create a swap file now, so that other Vims are warned
564 * that we are editing this file. Don't do this for a
565 * "nofile" or "nowrite" buffer type. */
566#ifdef FEAT_QUICKFIX
567 if (!bt_dontwrite(curbuf))
568#endif
569 check_need_swap(newfile);
Bram Moolenaar5b962cf2005-12-12 21:58:40 +0000570 if (dir_of_file_exists(fname))
571 filemess(curbuf, sfname, (char_u *)_("[New File]"), 0);
572 else
573 filemess(curbuf, sfname,
574 (char_u *)_("[New DIRECTORY]"), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000575#ifdef FEAT_VIMINFO
576 /* Even though this is a new file, it might have been
577 * edited before and deleted. Get the old marks. */
578 check_marks_read();
579#endif
580#ifdef FEAT_MBYTE
581 if (eap != NULL && eap->force_enc != 0)
582 {
583 /* set forced 'fileencoding' */
584 fenc = enc_canonize(eap->cmd + eap->force_enc);
585 if (fenc != NULL)
586 set_string_option_direct((char_u *)"fenc", -1,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +0000587 fenc, OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000588 vim_free(fenc);
589 }
590#endif
591#ifdef FEAT_AUTOCMD
592 apply_autocmds_exarg(EVENT_BUFNEWFILE, sfname, sfname,
593 FALSE, curbuf, eap);
594#endif
595 /* remember the current fileformat */
596 save_file_ff(curbuf);
597
598#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
599 if (aborting()) /* autocmds may abort script processing */
600 return FAIL;
601#endif
602 return OK; /* a new file is not an error */
603 }
604 else
605 {
Bram Moolenaar202795b2005-10-11 20:29:39 +0000606 filemess(curbuf, sfname, (char_u *)(
607# ifdef EFBIG
608 (errno == EFBIG) ? _("[File too big]") :
609# endif
610 _("[Permission Denied]")), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000611 curbuf->b_p_ro = TRUE; /* must use "w!" now */
612 }
613 }
614
615 return FAIL;
616 }
617
618 /*
619 * Only set the 'ro' flag for readonly files the first time they are
620 * loaded. Help files always get readonly mode
621 */
622 if ((check_readonly && file_readonly) || curbuf->b_help)
623 curbuf->b_p_ro = TRUE;
624
625 if (newfile)
626 {
627 curbuf->b_p_eol = TRUE;
628 curbuf->b_start_eol = TRUE;
629#ifdef FEAT_MBYTE
630 curbuf->b_p_bomb = FALSE;
631#endif
632 }
633
634 /* Create a swap file now, so that other Vims are warned that we are
635 * editing this file.
636 * Don't do this for a "nofile" or "nowrite" buffer type. */
637#ifdef FEAT_QUICKFIX
638 if (!bt_dontwrite(curbuf))
639#endif
640 {
641 check_need_swap(newfile);
642#ifdef UNIX
643 /* Set swap file protection bits after creating it. */
644 if (swap_mode > 0 && curbuf->b_ml.ml_mfp->mf_fname != NULL)
645 (void)mch_setperm(curbuf->b_ml.ml_mfp->mf_fname, (long)swap_mode);
646#endif
647 }
648
Bram Moolenaarb815dac2005-12-07 20:59:24 +0000649#if defined(HAS_SWAP_EXISTS_ACTION)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000650 /* If "Quit" selected at ATTENTION dialog, don't load the file */
651 if (swap_exists_action == SEA_QUIT)
652 {
653 if (!read_buffer && !read_stdin)
654 close(fd);
655 return FAIL;
656 }
657#endif
658
659 ++no_wait_return; /* don't wait for return yet */
660
661 /*
662 * Set '[ mark to the line above where the lines go (line 1 if zero).
663 */
664 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
665 curbuf->b_op_start.col = 0;
666
667#ifdef FEAT_AUTOCMD
668 if (!read_buffer)
669 {
670 int m = msg_scroll;
671 int n = msg_scrolled;
672 buf_T *old_curbuf = curbuf;
673
674 /*
675 * The file must be closed again, the autocommands may want to change
676 * the file before reading it.
677 */
678 if (!read_stdin)
679 close(fd); /* ignore errors */
680
681 /*
682 * The output from the autocommands should not overwrite anything and
683 * should not be overwritten: Set msg_scroll, restore its value if no
684 * output was done.
685 */
686 msg_scroll = TRUE;
687 if (filtering)
688 apply_autocmds_exarg(EVENT_FILTERREADPRE, NULL, sfname,
689 FALSE, curbuf, eap);
690 else if (read_stdin)
691 apply_autocmds_exarg(EVENT_STDINREADPRE, NULL, sfname,
692 FALSE, curbuf, eap);
693 else if (newfile)
694 apply_autocmds_exarg(EVENT_BUFREADPRE, NULL, sfname,
695 FALSE, curbuf, eap);
696 else
697 apply_autocmds_exarg(EVENT_FILEREADPRE, sfname, sfname,
698 FALSE, NULL, eap);
699 if (msg_scrolled == n)
700 msg_scroll = m;
701
702#ifdef FEAT_EVAL
703 if (aborting()) /* autocmds may abort script processing */
704 {
705 --no_wait_return;
706 msg_scroll = msg_save;
707 curbuf->b_p_ro = TRUE; /* must use "w!" now */
708 return FAIL;
709 }
710#endif
711 /*
712 * Don't allow the autocommands to change the current buffer.
713 * Try to re-open the file.
714 */
715 if (!read_stdin && (curbuf != old_curbuf
716 || (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) < 0))
717 {
718 --no_wait_return;
719 msg_scroll = msg_save;
720 if (fd < 0)
721 EMSG(_("E200: *ReadPre autocommands made the file unreadable"));
722 else
723 EMSG(_("E201: *ReadPre autocommands must not change current buffer"));
724 curbuf->b_p_ro = TRUE; /* must use "w!" now */
725 return FAIL;
726 }
727 }
728#endif /* FEAT_AUTOCMD */
729
730 /* Autocommands may add lines to the file, need to check if it is empty */
731 wasempty = (curbuf->b_ml.ml_flags & ML_EMPTY);
732
733 if (!recoverymode && !filtering && !(flags & READ_DUMMY))
734 {
735 /*
736 * Show the user that we are busy reading the input. Sometimes this
737 * may take a while. When reading from stdin another program may
738 * still be running, don't move the cursor to the last line, unless
739 * always using the GUI.
740 */
741 if (read_stdin)
742 {
743#ifndef ALWAYS_USE_GUI
744 mch_msg(_("Vim: Reading from stdin...\n"));
745#endif
746#ifdef FEAT_GUI
747 /* Also write a message in the GUI window, if there is one. */
748 if (gui.in_use && !gui.dying && !gui.starting)
749 {
750 p = (char_u *)_("Reading from stdin...");
751 gui_write(p, (int)STRLEN(p));
752 }
753#endif
754 }
755 else if (!read_buffer)
756 filemess(curbuf, sfname, (char_u *)"", 0);
757 }
758
759 msg_scroll = FALSE; /* overwrite the file message */
760
761 /*
762 * Set linecnt now, before the "retry" caused by a wrong guess for
763 * fileformat, and after the autocommands, which may change them.
764 */
765 linecnt = curbuf->b_ml.ml_line_count;
766
767#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000768 /* "++bad=" argument. */
769 if (eap != NULL && eap->bad_char != 0)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000770 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000771 bad_char_behavior = eap->bad_char;
Bram Moolenaar195d6352005-12-19 22:08:24 +0000772 if (newfile)
773 curbuf->b_bad_char = eap->bad_char;
774 }
775 else
776 curbuf->b_bad_char = 0;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000777
Bram Moolenaar071d4272004-06-13 20:20:40 +0000778 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000779 * Decide which 'encoding' to use or use first.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000780 */
781 if (eap != NULL && eap->force_enc != 0)
782 {
783 fenc = enc_canonize(eap->cmd + eap->force_enc);
784 fenc_alloced = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000785 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000786 }
787 else if (curbuf->b_p_bin)
788 {
789 fenc = (char_u *)""; /* binary: don't convert */
790 fenc_alloced = FALSE;
791 }
792 else if (curbuf->b_help)
793 {
794 char_u firstline[80];
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000795 int fc;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000796
797 /* Help files are either utf-8 or latin1. Try utf-8 first, if this
798 * fails it must be latin1.
799 * Always do this when 'encoding' is "utf-8". Otherwise only do
800 * this when needed to avoid [converted] remarks all the time.
801 * It is needed when the first line contains non-ASCII characters.
802 * That is only in *.??x files. */
803 fenc = (char_u *)"latin1";
804 c = enc_utf8;
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000805 if (!c && !read_stdin)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000806 {
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000807 fc = fname[STRLEN(fname) - 1];
808 if (TOLOWER_ASC(fc) == 'x')
809 {
810 /* Read the first line (and a bit more). Immediately rewind to
811 * the start of the file. If the read() fails "len" is -1. */
812 len = vim_read(fd, firstline, 80);
813 lseek(fd, (off_t)0L, SEEK_SET);
814 for (p = firstline; p < firstline + len; ++p)
815 if (*p >= 0x80)
816 {
817 c = TRUE;
818 break;
819 }
820 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000821 }
822
823 if (c)
824 {
825 fenc_next = fenc;
826 fenc = (char_u *)"utf-8";
827
828 /* When the file is utf-8 but a character doesn't fit in
829 * 'encoding' don't retry. In help text editing utf-8 bytes
830 * doesn't make sense. */
831 keep_dest_enc = TRUE;
832 }
833 fenc_alloced = FALSE;
834 }
835 else if (*p_fencs == NUL)
836 {
837 fenc = curbuf->b_p_fenc; /* use format from buffer */
838 fenc_alloced = FALSE;
839 }
840 else
841 {
842 fenc_next = p_fencs; /* try items in 'fileencodings' */
843 fenc = next_fenc(&fenc_next);
844 fenc_alloced = TRUE;
845 }
846#endif
847
848 /*
849 * Jump back here to retry reading the file in different ways.
850 * Reasons to retry:
851 * - encoding conversion failed: try another one from "fenc_next"
852 * - BOM detected and fenc was set, need to setup conversion
853 * - "fileformat" check failed: try another
854 *
855 * Variables set for special retry actions:
856 * "file_rewind" Rewind the file to start reading it again.
857 * "advance_fenc" Advance "fenc" using "fenc_next".
858 * "skip_read" Re-use already read bytes (BOM detected).
859 * "did_iconv" iconv() conversion failed, try 'charconvert'.
860 * "keep_fileformat" Don't reset "fileformat".
861 *
862 * Other status indicators:
863 * "tmpname" When != NULL did conversion with 'charconvert'.
864 * Output file has to be deleted afterwards.
865 * "iconv_fd" When != -1 did conversion with iconv().
866 */
867retry:
868
869 if (file_rewind)
870 {
871 if (read_buffer)
872 {
873 read_buf_lnum = 1;
874 read_buf_col = 0;
875 }
876 else if (read_stdin || lseek(fd, (off_t)0L, SEEK_SET) != 0)
877 {
878 /* Can't rewind the file, give up. */
879 error = TRUE;
880 goto failed;
881 }
882 /* Delete the previously read lines. */
883 while (lnum > from)
884 ml_delete(lnum--, FALSE);
885 file_rewind = FALSE;
886#ifdef FEAT_MBYTE
887 if (newfile)
888 curbuf->b_p_bomb = FALSE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000889 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000890#endif
891 }
892
893 /*
894 * When retrying with another "fenc" and the first time "fileformat"
895 * will be reset.
896 */
897 if (keep_fileformat)
898 keep_fileformat = FALSE;
899 else
900 {
901 if (eap != NULL && eap->force_ff != 0)
902 fileformat = get_fileformat_force(curbuf, eap);
903 else if (curbuf->b_p_bin)
904 fileformat = EOL_UNIX; /* binary: use Unix format */
905 else if (*p_ffs == NUL)
906 fileformat = get_fileformat(curbuf);/* use format from buffer */
907 else
908 fileformat = EOL_UNKNOWN; /* detect from file */
909 }
910
911#ifdef FEAT_MBYTE
912# ifdef USE_ICONV
913 if (iconv_fd != (iconv_t)-1)
914 {
915 /* aborted conversion with iconv(), close the descriptor */
916 iconv_close(iconv_fd);
917 iconv_fd = (iconv_t)-1;
918 }
919# endif
920
921 if (advance_fenc)
922 {
923 /*
924 * Try the next entry in 'fileencodings'.
925 */
926 advance_fenc = FALSE;
927
928 if (eap != NULL && eap->force_enc != 0)
929 {
930 /* Conversion given with "++cc=" wasn't possible, read
931 * without conversion. */
932 notconverted = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000933 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000934 if (fenc_alloced)
935 vim_free(fenc);
936 fenc = (char_u *)"";
937 fenc_alloced = FALSE;
938 }
939 else
940 {
941 if (fenc_alloced)
942 vim_free(fenc);
943 if (fenc_next != NULL)
944 {
945 fenc = next_fenc(&fenc_next);
946 fenc_alloced = (fenc_next != NULL);
947 }
948 else
949 {
950 fenc = (char_u *)"";
951 fenc_alloced = FALSE;
952 }
953 }
954 if (tmpname != NULL)
955 {
956 mch_remove(tmpname); /* delete converted file */
957 vim_free(tmpname);
958 tmpname = NULL;
959 }
960 }
961
962 /*
963 * Conversion is required when the encoding of the file is different
964 * from 'encoding' or 'encoding' is UTF-16, UCS-2 or UCS-4 (requires
965 * conversion to UTF-8).
966 */
967 fio_flags = 0;
968 converted = (*fenc != NUL && !same_encoding(p_enc, fenc));
969 if (converted || enc_unicode != 0)
970 {
971
972 /* "ucs-bom" means we need to check the first bytes of the file
973 * for a BOM. */
974 if (STRCMP(fenc, ENC_UCSBOM) == 0)
975 fio_flags = FIO_UCSBOM;
976
977 /*
978 * Check if UCS-2/4 or Latin1 to UTF-8 conversion needs to be
979 * done. This is handled below after read(). Prepare the
980 * fio_flags to avoid having to parse the string each time.
981 * Also check for Unicode to Latin1 conversion, because iconv()
982 * appears not to handle this correctly. This works just like
983 * conversion to UTF-8 except how the resulting character is put in
984 * the buffer.
985 */
986 else if (enc_utf8 || STRCMP(p_enc, "latin1") == 0)
987 fio_flags = get_fio_flags(fenc);
988
989# ifdef WIN3264
990 /*
991 * Conversion from an MS-Windows codepage to UTF-8 or another codepage
992 * is handled with MultiByteToWideChar().
993 */
994 if (fio_flags == 0)
995 fio_flags = get_win_fio_flags(fenc);
996# endif
997
998# ifdef MACOS_X
999 /* Conversion from Apple MacRoman to latin1 or UTF-8 */
1000 if (fio_flags == 0)
1001 fio_flags = get_mac_fio_flags(fenc);
1002# endif
1003
1004# ifdef USE_ICONV
1005 /*
1006 * Try using iconv() if we can't convert internally.
1007 */
1008 if (fio_flags == 0
1009# ifdef FEAT_EVAL
1010 && !did_iconv
1011# endif
1012 )
1013 iconv_fd = (iconv_t)my_iconv_open(
1014 enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc);
1015# endif
1016
1017# ifdef FEAT_EVAL
1018 /*
1019 * Use the 'charconvert' expression when conversion is required
1020 * and we can't do it internally or with iconv().
1021 */
1022 if (fio_flags == 0 && !read_stdin && !read_buffer && *p_ccv != NUL
1023# ifdef USE_ICONV
1024 && iconv_fd == (iconv_t)-1
1025# endif
1026 )
1027 {
1028# ifdef USE_ICONV
1029 did_iconv = FALSE;
1030# endif
1031 /* Skip conversion when it's already done (retry for wrong
1032 * "fileformat"). */
1033 if (tmpname == NULL)
1034 {
1035 tmpname = readfile_charconvert(fname, fenc, &fd);
1036 if (tmpname == NULL)
1037 {
1038 /* Conversion failed. Try another one. */
1039 advance_fenc = TRUE;
1040 if (fd < 0)
1041 {
1042 /* Re-opening the original file failed! */
1043 EMSG(_("E202: Conversion made file unreadable!"));
1044 error = TRUE;
1045 goto failed;
1046 }
1047 goto retry;
1048 }
1049 }
1050 }
1051 else
1052# endif
1053 {
1054 if (fio_flags == 0
1055# ifdef USE_ICONV
1056 && iconv_fd == (iconv_t)-1
1057# endif
1058 )
1059 {
1060 /* Conversion wanted but we can't.
1061 * Try the next conversion in 'fileencodings' */
1062 advance_fenc = TRUE;
1063 goto retry;
1064 }
1065 }
1066 }
1067
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001068 /* Set "can_retry" when it's possible to rewind the file and try with
Bram Moolenaar071d4272004-06-13 20:20:40 +00001069 * another "fenc" value. It's FALSE when no other "fenc" to try, reading
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001070 * stdin or fixed at a specific encoding. */
1071 can_retry = (*fenc != NUL && !read_stdin && !keep_dest_enc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001072#endif
1073
1074 if (!skip_read)
1075 {
1076 linerest = 0;
1077 filesize = 0;
1078 skip_count = lines_to_skip;
1079 read_count = lines_to_read;
1080#ifdef FEAT_MBYTE
1081 conv_restlen = 0;
1082#endif
1083 }
1084
1085 while (!error && !got_int)
1086 {
1087 /*
1088 * We allocate as much space for the file as we can get, plus
1089 * space for the old line plus room for one terminating NUL.
1090 * The amount is limited by the fact that read() only can read
1091 * upto max_unsigned characters (and other things).
1092 */
1093#if SIZEOF_INT <= 2
1094 if (linerest >= 0x7ff0)
1095 {
1096 ++split;
1097 *ptr = NL; /* split line by inserting a NL */
1098 size = 1;
1099 }
1100 else
1101#endif
1102 {
1103 if (!skip_read)
1104 {
1105#if SIZEOF_INT > 2
1106# ifdef __TANDEM
1107 size = SSIZE_MAX; /* use max I/O size, 52K */
1108# else
1109 size = 0x10000L; /* use buffer >= 64K */
1110# endif
1111#else
1112 size = 0x7ff0L - linerest; /* limit buffer to 32K */
1113#endif
1114
1115 for ( ; size >= 10; size = (long_u)size >> 1)
1116 {
1117 if ((new_buffer = lalloc((long_u)(size + linerest + 1),
1118 FALSE)) != NULL)
1119 break;
1120 }
1121 if (new_buffer == NULL)
1122 {
1123 do_outofmem_msg((long_u)(size * 2 + linerest + 1));
1124 error = TRUE;
1125 break;
1126 }
1127 if (linerest) /* copy characters from the previous buffer */
1128 mch_memmove(new_buffer, ptr - linerest, (size_t)linerest);
1129 vim_free(buffer);
1130 buffer = new_buffer;
1131 ptr = buffer + linerest;
1132 line_start = buffer;
1133
1134#ifdef FEAT_MBYTE
1135 /* May need room to translate into.
1136 * For iconv() we don't really know the required space, use a
1137 * factor ICONV_MULT.
1138 * latin1 to utf-8: 1 byte becomes up to 2 bytes
1139 * utf-16 to utf-8: 2 bytes become up to 3 bytes, 4 bytes
1140 * become up to 4 bytes, size must be multiple of 2
1141 * ucs-2 to utf-8: 2 bytes become up to 3 bytes, size must be
1142 * multiple of 2
1143 * ucs-4 to utf-8: 4 bytes become up to 6 bytes, size must be
1144 * multiple of 4 */
1145 real_size = size;
1146# ifdef USE_ICONV
1147 if (iconv_fd != (iconv_t)-1)
1148 size = size / ICONV_MULT;
1149 else
1150# endif
1151 if (fio_flags & FIO_LATIN1)
1152 size = size / 2;
1153 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1154 size = (size * 2 / 3) & ~1;
1155 else if (fio_flags & FIO_UCS4)
1156 size = (size * 2 / 3) & ~3;
1157 else if (fio_flags == FIO_UCSBOM)
1158 size = size / ICONV_MULT; /* worst case */
1159# ifdef WIN3264
1160 else if (fio_flags & FIO_CODEPAGE)
1161 size = size / ICONV_MULT; /* also worst case */
1162# endif
1163# ifdef MACOS_X
1164 else if (fio_flags & FIO_MACROMAN)
1165 size = size / ICONV_MULT; /* also worst case */
1166# endif
1167#endif
1168
1169#ifdef FEAT_MBYTE
1170 if (conv_restlen > 0)
1171 {
1172 /* Insert unconverted bytes from previous line. */
1173 mch_memmove(ptr, conv_rest, conv_restlen);
1174 ptr += conv_restlen;
1175 size -= conv_restlen;
1176 }
1177#endif
1178
1179 if (read_buffer)
1180 {
1181 /*
1182 * Read bytes from curbuf. Used for converting text read
1183 * from stdin.
1184 */
1185 if (read_buf_lnum > from)
1186 size = 0;
1187 else
1188 {
1189 int n, ni;
1190 long tlen;
1191
1192 tlen = 0;
1193 for (;;)
1194 {
1195 p = ml_get(read_buf_lnum) + read_buf_col;
1196 n = (int)STRLEN(p);
1197 if ((int)tlen + n + 1 > size)
1198 {
1199 /* Filled up to "size", append partial line.
1200 * Change NL to NUL to reverse the effect done
1201 * below. */
1202 n = size - tlen;
1203 for (ni = 0; ni < n; ++ni)
1204 {
1205 if (p[ni] == NL)
1206 ptr[tlen++] = NUL;
1207 else
1208 ptr[tlen++] = p[ni];
1209 }
1210 read_buf_col += n;
1211 break;
1212 }
1213 else
1214 {
1215 /* Append whole line and new-line. Change NL
1216 * to NUL to reverse the effect done below. */
1217 for (ni = 0; ni < n; ++ni)
1218 {
1219 if (p[ni] == NL)
1220 ptr[tlen++] = NUL;
1221 else
1222 ptr[tlen++] = p[ni];
1223 }
1224 ptr[tlen++] = NL;
1225 read_buf_col = 0;
1226 if (++read_buf_lnum > from)
1227 {
1228 /* When the last line didn't have an
1229 * end-of-line don't add it now either. */
1230 if (!curbuf->b_p_eol)
1231 --tlen;
1232 size = tlen;
1233 break;
1234 }
1235 }
1236 }
1237 }
1238 }
1239 else
1240 {
1241 /*
1242 * Read bytes from the file.
1243 */
1244 size = vim_read(fd, ptr, size);
1245 }
1246
1247 if (size <= 0)
1248 {
1249 if (size < 0) /* read error */
1250 error = TRUE;
1251#ifdef FEAT_MBYTE
1252 else if (conv_restlen > 0)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001253 {
1254 /* Reached end-of-file but some trailing bytes could
1255 * not be converted. Trucated file? */
1256 if (conv_error == 0)
1257 conv_error = linecnt;
1258 if (bad_char_behavior != BAD_DROP)
1259 {
1260 fio_flags = 0; /* don't convert this */
1261 if (bad_char_behavior == BAD_KEEP)
1262 {
1263 /* Keep the trailing bytes as-is. */
1264 size = conv_restlen;
1265 ptr -= conv_restlen;
1266 }
1267 else
1268 {
1269 /* Replace the trailing bytes with the
1270 * replacement character. */
1271 size = 1;
1272 *--ptr = bad_char_behavior;
1273 }
1274 conv_restlen = 0;
1275 }
1276 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001277#endif
1278 }
1279
1280#ifdef FEAT_CRYPT
1281 /*
1282 * At start of file: Check for magic number of encryption.
1283 */
1284 if (filesize == 0)
1285 cryptkey = check_for_cryptkey(cryptkey, ptr, &size,
1286 &filesize, newfile);
1287 /*
1288 * Decrypt the read bytes.
1289 */
1290 if (cryptkey != NULL && size > 0)
1291 for (p = ptr; p < ptr + size; ++p)
1292 ZDECODE(*p);
1293#endif
1294 }
1295 skip_read = FALSE;
1296
1297#ifdef FEAT_MBYTE
1298 /*
1299 * At start of file (or after crypt magic number): Check for BOM.
1300 * Also check for a BOM for other Unicode encodings, but not after
1301 * converting with 'charconvert' or when a BOM has already been
1302 * found.
1303 */
1304 if ((filesize == 0
1305# ifdef FEAT_CRYPT
1306 || (filesize == CRYPT_MAGIC_LEN && cryptkey != NULL)
1307# endif
1308 )
1309 && (fio_flags == FIO_UCSBOM
1310 || (!curbuf->b_p_bomb
1311 && tmpname == NULL
1312 && (*fenc == 'u' || (*fenc == NUL && enc_utf8)))))
1313 {
1314 char_u *ccname;
1315 int blen;
1316
1317 /* no BOM detection in a short file or in binary mode */
1318 if (size < 2 || curbuf->b_p_bin)
1319 ccname = NULL;
1320 else
1321 ccname = check_for_bom(ptr, size, &blen,
1322 fio_flags == FIO_UCSBOM ? FIO_ALL : get_fio_flags(fenc));
1323 if (ccname != NULL)
1324 {
1325 /* Remove BOM from the text */
1326 filesize += blen;
1327 size -= blen;
1328 mch_memmove(ptr, ptr + blen, (size_t)size);
1329 if (newfile)
1330 curbuf->b_p_bomb = TRUE;
1331 }
1332
1333 if (fio_flags == FIO_UCSBOM)
1334 {
1335 if (ccname == NULL)
1336 {
1337 /* No BOM detected: retry with next encoding. */
1338 advance_fenc = TRUE;
1339 }
1340 else
1341 {
1342 /* BOM detected: set "fenc" and jump back */
1343 if (fenc_alloced)
1344 vim_free(fenc);
1345 fenc = ccname;
1346 fenc_alloced = FALSE;
1347 }
1348 /* retry reading without getting new bytes or rewinding */
1349 skip_read = TRUE;
1350 goto retry;
1351 }
1352 }
1353#endif
1354 /*
1355 * Break here for a read error or end-of-file.
1356 */
1357 if (size <= 0)
1358 break;
1359
1360#ifdef FEAT_MBYTE
1361
1362 /* Include not converted bytes. */
1363 ptr -= conv_restlen;
1364 size += conv_restlen;
1365 conv_restlen = 0;
1366
1367# ifdef USE_ICONV
1368 if (iconv_fd != (iconv_t)-1)
1369 {
1370 /*
1371 * Attempt conversion of the read bytes to 'encoding' using
1372 * iconv().
1373 */
1374 const char *fromp;
1375 char *top;
1376 size_t from_size;
1377 size_t to_size;
1378
1379 fromp = (char *)ptr;
1380 from_size = size;
1381 ptr += size;
1382 top = (char *)ptr;
1383 to_size = real_size - size;
1384
1385 /*
1386 * If there is conversion error or not enough room try using
Bram Moolenaar19a09a12005-03-04 23:39:37 +00001387 * another conversion. Except for when there is no
1388 * alternative (help files).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001389 */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001390 while ((iconv(iconv_fd, (void *)&fromp, &from_size,
1391 &top, &to_size)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001392 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
1393 || from_size > CONV_RESTLEN)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001394 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001395 if (can_retry)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001396 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001397 if (conv_error == 0)
1398 conv_error = readfile_linenr(linecnt,
1399 ptr, (char_u *)top);
Bram Moolenaar42eeac32005-06-29 22:40:58 +00001400
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001401 /* Deal with a bad byte and continue with the next. */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001402 ++fromp;
1403 --from_size;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001404 if (bad_char_behavior == BAD_KEEP)
1405 {
1406 *top++ = *(fromp - 1);
1407 --to_size;
1408 }
1409 else if (bad_char_behavior != BAD_DROP)
1410 {
1411 *top++ = bad_char_behavior;
1412 --to_size;
1413 }
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001414 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001415
1416 if (from_size > 0)
1417 {
1418 /* Some remaining characters, keep them for the next
1419 * round. */
1420 mch_memmove(conv_rest, (char_u *)fromp, from_size);
1421 conv_restlen = (int)from_size;
1422 }
1423
1424 /* move the linerest to before the converted characters */
1425 line_start = ptr - linerest;
1426 mch_memmove(line_start, buffer, (size_t)linerest);
1427 size = (long)((char_u *)top - ptr);
1428 }
1429# endif
1430
1431# ifdef WIN3264
1432 if (fio_flags & FIO_CODEPAGE)
1433 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001434 char_u *src, *dst;
1435 int u8c;
1436 WCHAR ucs2buf[3];
1437 int ucs2len;
1438 int codepage = FIO_GET_CP(fio_flags);
1439 int bytelen;
1440 int found_bad;
1441 char replstr[2];
1442
Bram Moolenaar071d4272004-06-13 20:20:40 +00001443 /*
1444 * Conversion from an MS-Windows codepage or UTF-8 to UTF-8 or
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001445 * a codepage, using standard MS-Windows functions. This
1446 * requires two steps:
1447 * 1. convert from 'fileencoding' to ucs-2
1448 * 2. convert from ucs-2 to 'encoding'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001449 *
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001450 * Because there may be illegal bytes AND an incomplete byte
1451 * sequence at the end, we may have to do the conversion one
1452 * character at a time to get it right.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001453 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001454
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001455 /* Replacement string for WideCharToMultiByte(). */
1456 if (bad_char_behavior > 0)
1457 replstr[0] = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001458 else
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001459 replstr[0] = '?';
1460 replstr[1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001461
1462 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001463 * Move the bytes to the end of the buffer, so that we have
1464 * room to put the result at the start.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001465 */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001466 src = ptr + real_size - size;
1467 mch_memmove(src, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001468
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001469 /*
1470 * Do the conversion.
1471 */
1472 dst = ptr;
1473 size = size;
1474 while (size > 0)
1475 {
1476 found_bad = FALSE;
1477
1478# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
1479 if (codepage == CP_UTF8)
1480 {
1481 /* Handle CP_UTF8 input ourselves to be able to handle
1482 * trailing bytes properly.
1483 * Get one UTF-8 character from src. */
1484 bytelen = utf_ptr2len_len(src, size);
1485 if (bytelen > size)
1486 {
1487 /* Only got some bytes of a character. Normally
1488 * it's put in "conv_rest", but if it's too long
1489 * deal with it as if they were illegal bytes. */
1490 if (bytelen <= CONV_RESTLEN)
1491 break;
1492
1493 /* weird overlong byte sequence */
1494 bytelen = size;
1495 found_bad = TRUE;
1496 }
1497 else
1498 {
1499 u8c = utf_ptr2char(src);
Bram Moolenaar86e01082005-12-29 22:45:34 +00001500 if (u8c > 0xffff || (*src >= 0x80 && bytelen == 1))
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001501 found_bad = TRUE;
1502 ucs2buf[0] = u8c;
1503 ucs2len = 1;
1504 }
1505 }
1506 else
1507# endif
1508 {
1509 /* We don't know how long the byte sequence is, try
1510 * from one to three bytes. */
1511 for (bytelen = 1; bytelen <= size && bytelen <= 3;
1512 ++bytelen)
1513 {
1514 ucs2len = MultiByteToWideChar(codepage,
1515 MB_ERR_INVALID_CHARS,
1516 (LPCSTR)src, bytelen,
1517 ucs2buf, 3);
1518 if (ucs2len > 0)
1519 break;
1520 }
1521 if (ucs2len == 0)
1522 {
1523 /* If we have only one byte then it's probably an
1524 * incomplete byte sequence. Otherwise discard
1525 * one byte as a bad character. */
1526 if (size == 1)
1527 break;
1528 found_bad = TRUE;
1529 bytelen = 1;
1530 }
1531 }
1532
1533 if (!found_bad)
1534 {
1535 int i;
1536
1537 /* Convert "ucs2buf[ucs2len]" to 'enc' in "dst". */
1538 if (enc_utf8)
1539 {
1540 /* From UCS-2 to UTF-8. Cannot fail. */
1541 for (i = 0; i < ucs2len; ++i)
1542 dst += utf_char2bytes(ucs2buf[i], dst);
1543 }
1544 else
1545 {
1546 BOOL bad = FALSE;
1547 int dstlen;
1548
1549 /* From UCS-2 to "enc_codepage". If the
1550 * conversion uses the default character "?",
1551 * the data doesn't fit in this encoding. */
1552 dstlen = WideCharToMultiByte(enc_codepage, 0,
1553 (LPCWSTR)ucs2buf, ucs2len,
1554 (LPSTR)dst, (src - dst),
1555 replstr, &bad);
1556 if (bad)
1557 found_bad = TRUE;
1558 else
1559 dst += dstlen;
1560 }
1561 }
1562
1563 if (found_bad)
1564 {
1565 /* Deal with bytes we can't convert. */
1566 if (can_retry)
1567 goto rewind_retry;
1568 if (conv_error == 0)
1569 conv_error = readfile_linenr(linecnt, ptr, dst);
1570 if (bad_char_behavior != BAD_DROP)
1571 {
1572 if (bad_char_behavior == BAD_KEEP)
1573 {
1574 mch_memmove(dst, src, bytelen);
1575 dst += bytelen;
1576 }
1577 else
1578 *dst++ = bad_char_behavior;
1579 }
1580 }
1581
1582 src += bytelen;
1583 size -= bytelen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001584 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001585
1586 if (size > 0)
1587 {
1588 /* An incomplete byte sequence remaining. */
1589 mch_memmove(conv_rest, src, size);
1590 conv_restlen = size;
1591 }
1592
1593 /* The new size is equal to how much "dst" was advanced. */
1594 size = dst - ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001595 }
1596 else
1597# endif
1598# ifdef MACOS_X
1599 if (fio_flags & FIO_MACROMAN)
1600 {
1601 /*
1602 * Conversion from Apple MacRoman char encoding to UTF-8 or
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001603 * latin1. This is in os_mac_conv.c.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001604 */
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001605 if (macroman2enc(ptr, &size, real_size) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001606 goto rewind_retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001607 }
1608 else
1609# endif
1610 if (fio_flags != 0)
1611 {
1612 int u8c;
1613 char_u *dest;
1614 char_u *tail = NULL;
1615
1616 /*
1617 * "enc_utf8" set: Convert Unicode or Latin1 to UTF-8.
1618 * "enc_utf8" not set: Convert Unicode to Latin1.
1619 * Go from end to start through the buffer, because the number
1620 * of bytes may increase.
1621 * "dest" points to after where the UTF-8 bytes go, "p" points
1622 * to after the next character to convert.
1623 */
1624 dest = ptr + real_size;
1625 if (fio_flags == FIO_LATIN1 || fio_flags == FIO_UTF8)
1626 {
1627 p = ptr + size;
1628 if (fio_flags == FIO_UTF8)
1629 {
1630 /* Check for a trailing incomplete UTF-8 sequence */
1631 tail = ptr + size - 1;
1632 while (tail > ptr && (*tail & 0xc0) == 0x80)
1633 --tail;
1634 if (tail + utf_byte2len(*tail) <= ptr + size)
1635 tail = NULL;
1636 else
1637 p = tail;
1638 }
1639 }
1640 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1641 {
1642 /* Check for a trailing byte */
1643 p = ptr + (size & ~1);
1644 if (size & 1)
1645 tail = p;
1646 if ((fio_flags & FIO_UTF16) && p > ptr)
1647 {
1648 /* Check for a trailing leading word */
1649 if (fio_flags & FIO_ENDIAN_L)
1650 {
1651 u8c = (*--p << 8);
1652 u8c += *--p;
1653 }
1654 else
1655 {
1656 u8c = *--p;
1657 u8c += (*--p << 8);
1658 }
1659 if (u8c >= 0xd800 && u8c <= 0xdbff)
1660 tail = p;
1661 else
1662 p += 2;
1663 }
1664 }
1665 else /* FIO_UCS4 */
1666 {
1667 /* Check for trailing 1, 2 or 3 bytes */
1668 p = ptr + (size & ~3);
1669 if (size & 3)
1670 tail = p;
1671 }
1672
1673 /* If there is a trailing incomplete sequence move it to
1674 * conv_rest[]. */
1675 if (tail != NULL)
1676 {
1677 conv_restlen = (int)((ptr + size) - tail);
1678 mch_memmove(conv_rest, (char_u *)tail, conv_restlen);
1679 size -= conv_restlen;
1680 }
1681
1682
1683 while (p > ptr)
1684 {
1685 if (fio_flags & FIO_LATIN1)
1686 u8c = *--p;
1687 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1688 {
1689 if (fio_flags & FIO_ENDIAN_L)
1690 {
1691 u8c = (*--p << 8);
1692 u8c += *--p;
1693 }
1694 else
1695 {
1696 u8c = *--p;
1697 u8c += (*--p << 8);
1698 }
1699 if ((fio_flags & FIO_UTF16)
1700 && u8c >= 0xdc00 && u8c <= 0xdfff)
1701 {
1702 int u16c;
1703
1704 if (p == ptr)
1705 {
1706 /* Missing leading word. */
1707 if (can_retry)
1708 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001709 if (conv_error == 0)
1710 conv_error = readfile_linenr(linecnt,
1711 ptr, p);
1712 if (bad_char_behavior == BAD_DROP)
1713 continue;
1714 if (bad_char_behavior != BAD_KEEP)
1715 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001716 }
1717
1718 /* found second word of double-word, get the first
1719 * word and compute the resulting character */
1720 if (fio_flags & FIO_ENDIAN_L)
1721 {
1722 u16c = (*--p << 8);
1723 u16c += *--p;
1724 }
1725 else
1726 {
1727 u16c = *--p;
1728 u16c += (*--p << 8);
1729 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001730 u8c = 0x10000 + ((u16c & 0x3ff) << 10)
1731 + (u8c & 0x3ff);
1732
Bram Moolenaar071d4272004-06-13 20:20:40 +00001733 /* Check if the word is indeed a leading word. */
1734 if (u16c < 0xd800 || u16c > 0xdbff)
1735 {
1736 if (can_retry)
1737 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001738 if (conv_error == 0)
1739 conv_error = readfile_linenr(linecnt,
1740 ptr, p);
1741 if (bad_char_behavior == BAD_DROP)
1742 continue;
1743 if (bad_char_behavior != BAD_KEEP)
1744 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001745 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001746 }
1747 }
1748 else if (fio_flags & FIO_UCS4)
1749 {
1750 if (fio_flags & FIO_ENDIAN_L)
1751 {
1752 u8c = (*--p << 24);
1753 u8c += (*--p << 16);
1754 u8c += (*--p << 8);
1755 u8c += *--p;
1756 }
1757 else /* big endian */
1758 {
1759 u8c = *--p;
1760 u8c += (*--p << 8);
1761 u8c += (*--p << 16);
1762 u8c += (*--p << 24);
1763 }
1764 }
1765 else /* UTF-8 */
1766 {
1767 if (*--p < 0x80)
1768 u8c = *p;
1769 else
1770 {
1771 len = utf_head_off(ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001772 p -= len;
1773 u8c = utf_ptr2char(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001774 if (len == 0)
1775 {
1776 /* Not a valid UTF-8 character, retry with
1777 * another fenc when possible, otherwise just
1778 * report the error. */
1779 if (can_retry)
1780 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001781 if (conv_error == 0)
1782 conv_error = readfile_linenr(linecnt,
1783 ptr, p);
1784 if (bad_char_behavior == BAD_DROP)
1785 continue;
1786 if (bad_char_behavior != BAD_KEEP)
1787 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001788 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001789 }
1790 }
1791 if (enc_utf8) /* produce UTF-8 */
1792 {
1793 dest -= utf_char2len(u8c);
1794 (void)utf_char2bytes(u8c, dest);
1795 }
1796 else /* produce Latin1 */
1797 {
1798 --dest;
1799 if (u8c >= 0x100)
1800 {
1801 /* character doesn't fit in latin1, retry with
1802 * another fenc when possible, otherwise just
1803 * report the error. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001804 if (can_retry)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001805 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001806 if (conv_error == 0)
1807 conv_error = readfile_linenr(linecnt, ptr, p);
1808 if (bad_char_behavior == BAD_DROP)
1809 ++dest;
1810 else if (bad_char_behavior == BAD_KEEP)
1811 *dest = u8c;
1812 else if (eap != NULL && eap->bad_char != 0)
1813 *dest = bad_char_behavior;
1814 else
1815 *dest = 0xBF;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001816 }
1817 else
1818 *dest = u8c;
1819 }
1820 }
1821
1822 /* move the linerest to before the converted characters */
1823 line_start = dest - linerest;
1824 mch_memmove(line_start, buffer, (size_t)linerest);
1825 size = (long)((ptr + real_size) - dest);
1826 ptr = dest;
1827 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001828 else if (enc_utf8 && conv_error == 0 && !curbuf->b_p_bin)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001829 {
1830 /* Reading UTF-8: Check if the bytes are valid UTF-8.
1831 * Need to start before "ptr" when part of the character was
1832 * read in the previous read() call. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001833 for (p = ptr - utf_head_off(buffer, ptr); ; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001834 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001835 int todo = (ptr + size) - p;
1836 int l;
1837
1838 if (todo <= 0)
1839 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001840 if (*p >= 0x80)
1841 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001842 /* A length of 1 means it's an illegal byte. Accept
1843 * an incomplete character at the end though, the next
1844 * read() will get the next bytes, we'll check it
1845 * then. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001846 l = utf_ptr2len_len(p, todo);
1847 if (l > todo)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001848 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001849 /* Incomplete byte sequence, the next read()
1850 * should get them and check the bytes. */
1851 p += todo;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001852 break;
1853 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001854 if (l == 1)
1855 {
1856 /* Illegal byte. If we can try another encoding
1857 * do that. */
1858 if (can_retry)
1859 break;
1860
1861 /* Remember the first linenr with an illegal byte */
1862 if (illegal_byte == 0)
1863 illegal_byte = readfile_linenr(linecnt, ptr, p);
1864# ifdef USE_ICONV
1865 /* When we did a conversion report an error. */
1866 if (iconv_fd != (iconv_t)-1 && conv_error == 0)
1867 conv_error = readfile_linenr(linecnt, ptr, p);
1868# endif
1869
1870 /* Drop, keep or replace the bad byte. */
1871 if (bad_char_behavior == BAD_DROP)
1872 {
1873 mch_memmove(p, p+1, todo - 1);
1874 --p;
1875 --size;
1876 }
1877 else if (bad_char_behavior != BAD_KEEP)
1878 *p = bad_char_behavior;
1879 }
1880 p += l - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001881 }
1882 }
1883 if (p < ptr + size)
1884 {
1885 /* Detected a UTF-8 error. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001886rewind_retry:
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001887 /* Retry reading with another conversion. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001888# if defined(FEAT_EVAL) && defined(USE_ICONV)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001889 if (*p_ccv != NUL && iconv_fd != (iconv_t)-1)
1890 /* iconv() failed, try 'charconvert' */
1891 did_iconv = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001892 else
1893# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001894 /* use next item from 'fileencodings' */
1895 advance_fenc = TRUE;
1896 file_rewind = TRUE;
1897 goto retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001898 }
1899 }
1900#endif
1901
1902 /* count the number of characters (after conversion!) */
1903 filesize += size;
1904
1905 /*
1906 * when reading the first part of a file: guess EOL type
1907 */
1908 if (fileformat == EOL_UNKNOWN)
1909 {
1910 /* First try finding a NL, for Dos and Unix */
1911 if (try_dos || try_unix)
1912 {
1913 for (p = ptr; p < ptr + size; ++p)
1914 {
1915 if (*p == NL)
1916 {
1917 if (!try_unix
1918 || (try_dos && p > ptr && p[-1] == CAR))
1919 fileformat = EOL_DOS;
1920 else
1921 fileformat = EOL_UNIX;
1922 break;
1923 }
1924 }
1925
1926 /* Don't give in to EOL_UNIX if EOL_MAC is more likely */
1927 if (fileformat == EOL_UNIX && try_mac)
1928 {
1929 /* Need to reset the counters when retrying fenc. */
1930 try_mac = 1;
1931 try_unix = 1;
1932 for (; p >= ptr && *p != CAR; p--)
1933 ;
1934 if (p >= ptr)
1935 {
1936 for (p = ptr; p < ptr + size; ++p)
1937 {
1938 if (*p == NL)
1939 try_unix++;
1940 else if (*p == CAR)
1941 try_mac++;
1942 }
1943 if (try_mac > try_unix)
1944 fileformat = EOL_MAC;
1945 }
1946 }
1947 }
1948
1949 /* No NL found: may use Mac format */
1950 if (fileformat == EOL_UNKNOWN && try_mac)
1951 fileformat = EOL_MAC;
1952
1953 /* Still nothing found? Use first format in 'ffs' */
1954 if (fileformat == EOL_UNKNOWN)
1955 fileformat = default_fileformat();
1956
1957 /* if editing a new file: may set p_tx and p_ff */
1958 if (newfile)
1959 set_fileformat(fileformat, OPT_LOCAL);
1960 }
1961 }
1962
1963 /*
1964 * This loop is executed once for every character read.
1965 * Keep it fast!
1966 */
1967 if (fileformat == EOL_MAC)
1968 {
1969 --ptr;
1970 while (++ptr, --size >= 0)
1971 {
1972 /* catch most common case first */
1973 if ((c = *ptr) != NUL && c != CAR && c != NL)
1974 continue;
1975 if (c == NUL)
1976 *ptr = NL; /* NULs are replaced by newlines! */
1977 else if (c == NL)
1978 *ptr = CAR; /* NLs are replaced by CRs! */
1979 else
1980 {
1981 if (skip_count == 0)
1982 {
1983 *ptr = NUL; /* end of line */
1984 len = (colnr_T) (ptr - line_start + 1);
1985 if (ml_append(lnum, line_start, len, newfile) == FAIL)
1986 {
1987 error = TRUE;
1988 break;
1989 }
1990 ++lnum;
1991 if (--read_count == 0)
1992 {
1993 error = TRUE; /* break loop */
1994 line_start = ptr; /* nothing left to write */
1995 break;
1996 }
1997 }
1998 else
1999 --skip_count;
2000 line_start = ptr + 1;
2001 }
2002 }
2003 }
2004 else
2005 {
2006 --ptr;
2007 while (++ptr, --size >= 0)
2008 {
2009 if ((c = *ptr) != NUL && c != NL) /* catch most common case */
2010 continue;
2011 if (c == NUL)
2012 *ptr = NL; /* NULs are replaced by newlines! */
2013 else
2014 {
2015 if (skip_count == 0)
2016 {
2017 *ptr = NUL; /* end of line */
2018 len = (colnr_T)(ptr - line_start + 1);
2019 if (fileformat == EOL_DOS)
2020 {
2021 if (ptr[-1] == CAR) /* remove CR */
2022 {
2023 ptr[-1] = NUL;
2024 --len;
2025 }
2026 /*
2027 * Reading in Dos format, but no CR-LF found!
2028 * When 'fileformats' includes "unix", delete all
2029 * the lines read so far and start all over again.
2030 * Otherwise give an error message later.
2031 */
2032 else if (ff_error != EOL_DOS)
2033 {
2034 if ( try_unix
2035 && !read_stdin
2036 && (read_buffer
2037 || lseek(fd, (off_t)0L, SEEK_SET) == 0))
2038 {
2039 fileformat = EOL_UNIX;
2040 if (newfile)
2041 set_fileformat(EOL_UNIX, OPT_LOCAL);
2042 file_rewind = TRUE;
2043 keep_fileformat = TRUE;
2044 goto retry;
2045 }
2046 ff_error = EOL_DOS;
2047 }
2048 }
2049 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2050 {
2051 error = TRUE;
2052 break;
2053 }
2054 ++lnum;
2055 if (--read_count == 0)
2056 {
2057 error = TRUE; /* break loop */
2058 line_start = ptr; /* nothing left to write */
2059 break;
2060 }
2061 }
2062 else
2063 --skip_count;
2064 line_start = ptr + 1;
2065 }
2066 }
2067 }
2068 linerest = (long)(ptr - line_start);
2069 ui_breakcheck();
2070 }
2071
2072failed:
2073 /* not an error, max. number of lines reached */
2074 if (error && read_count == 0)
2075 error = FALSE;
2076
2077 /*
2078 * If we get EOF in the middle of a line, note the fact and
2079 * complete the line ourselves.
2080 * In Dos format ignore a trailing CTRL-Z, unless 'binary' set.
2081 */
2082 if (!error
2083 && !got_int
2084 && linerest != 0
2085 && !(!curbuf->b_p_bin
2086 && fileformat == EOL_DOS
2087 && *line_start == Ctrl_Z
2088 && ptr == line_start + 1))
2089 {
2090 if (newfile) /* remember for when writing */
2091 curbuf->b_p_eol = FALSE;
2092 *ptr = NUL;
2093 if (ml_append(lnum, line_start,
2094 (colnr_T)(ptr - line_start + 1), newfile) == FAIL)
2095 error = TRUE;
2096 else
2097 read_no_eol_lnum = ++lnum;
2098 }
2099
2100 if (newfile)
2101 save_file_ff(curbuf); /* remember the current file format */
2102
2103#ifdef FEAT_CRYPT
2104 if (cryptkey != curbuf->b_p_key)
2105 vim_free(cryptkey);
2106#endif
2107
2108#ifdef FEAT_MBYTE
2109 /* If editing a new file: set 'fenc' for the current buffer. */
2110 if (newfile)
2111 set_string_option_direct((char_u *)"fenc", -1, fenc,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00002112 OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002113 if (fenc_alloced)
2114 vim_free(fenc);
2115# ifdef USE_ICONV
2116 if (iconv_fd != (iconv_t)-1)
2117 {
2118 iconv_close(iconv_fd);
2119 iconv_fd = (iconv_t)-1;
2120 }
2121# endif
2122#endif
2123
2124 if (!read_buffer && !read_stdin)
2125 close(fd); /* errors are ignored */
2126 vim_free(buffer);
2127
2128#ifdef HAVE_DUP
2129 if (read_stdin)
2130 {
2131 /* Use stderr for stdin, makes shell commands work. */
2132 close(0);
2133 dup(2);
2134 }
2135#endif
2136
2137#ifdef FEAT_MBYTE
2138 if (tmpname != NULL)
2139 {
2140 mch_remove(tmpname); /* delete converted file */
2141 vim_free(tmpname);
2142 }
2143#endif
2144 --no_wait_return; /* may wait for return now */
2145
2146 /*
2147 * In recovery mode everything but autocommands is skipped.
2148 */
2149 if (!recoverymode)
2150 {
2151 /* need to delete the last line, which comes from the empty buffer */
2152 if (newfile && wasempty && !(curbuf->b_ml.ml_flags & ML_EMPTY))
2153 {
2154#ifdef FEAT_NETBEANS_INTG
2155 netbeansFireChanges = 0;
2156#endif
2157 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
2158#ifdef FEAT_NETBEANS_INTG
2159 netbeansFireChanges = 1;
2160#endif
2161 --linecnt;
2162 }
2163 linecnt = curbuf->b_ml.ml_line_count - linecnt;
2164 if (filesize == 0)
2165 linecnt = 0;
2166 if (newfile || read_buffer)
2167 redraw_curbuf_later(NOT_VALID);
2168 else if (linecnt) /* appended at least one line */
2169 appended_lines_mark(from, linecnt);
2170
2171#ifdef FEAT_DIFF
2172 /* After reading the text into the buffer the diff info needs to be
2173 * updated. */
Bram Moolenaar49d7bf12006-02-17 21:45:41 +00002174 if (newfile || read_buffer)
2175 diff_invalidate(curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002176#endif
2177#ifndef ALWAYS_USE_GUI
2178 /*
2179 * If we were reading from the same terminal as where messages go,
2180 * the screen will have been messed up.
2181 * Switch on raw mode now and clear the screen.
2182 */
2183 if (read_stdin)
2184 {
2185 settmode(TMODE_RAW); /* set to raw mode */
2186 starttermcap();
2187 screenclear();
2188 }
2189#endif
2190
2191 if (got_int)
2192 {
2193 if (!(flags & READ_DUMMY))
2194 {
2195 filemess(curbuf, sfname, (char_u *)_(e_interr), 0);
2196 if (newfile)
2197 curbuf->b_p_ro = TRUE; /* must use "w!" now */
2198 }
2199 msg_scroll = msg_save;
2200#ifdef FEAT_VIMINFO
2201 check_marks_read();
2202#endif
2203 return OK; /* an interrupt isn't really an error */
2204 }
2205
2206 if (!filtering && !(flags & READ_DUMMY))
2207 {
2208 msg_add_fname(curbuf, sfname); /* fname in IObuff with quotes */
2209 c = FALSE;
2210
2211#ifdef UNIX
2212# ifdef S_ISFIFO
2213 if (S_ISFIFO(perm)) /* fifo or socket */
2214 {
2215 STRCAT(IObuff, _("[fifo/socket]"));
2216 c = TRUE;
2217 }
2218# else
2219# ifdef S_IFIFO
2220 if ((perm & S_IFMT) == S_IFIFO) /* fifo */
2221 {
2222 STRCAT(IObuff, _("[fifo]"));
2223 c = TRUE;
2224 }
2225# endif
2226# ifdef S_IFSOCK
2227 if ((perm & S_IFMT) == S_IFSOCK) /* or socket */
2228 {
2229 STRCAT(IObuff, _("[socket]"));
2230 c = TRUE;
2231 }
2232# endif
2233# endif
2234#endif
2235 if (curbuf->b_p_ro)
2236 {
2237 STRCAT(IObuff, shortmess(SHM_RO) ? _("[RO]") : _("[readonly]"));
2238 c = TRUE;
2239 }
2240 if (read_no_eol_lnum)
2241 {
2242 msg_add_eol();
2243 c = TRUE;
2244 }
2245 if (ff_error == EOL_DOS)
2246 {
2247 STRCAT(IObuff, _("[CR missing]"));
2248 c = TRUE;
2249 }
2250 if (ff_error == EOL_MAC)
2251 {
2252 STRCAT(IObuff, _("[NL found]"));
2253 c = TRUE;
2254 }
2255 if (split)
2256 {
2257 STRCAT(IObuff, _("[long lines split]"));
2258 c = TRUE;
2259 }
2260#ifdef FEAT_MBYTE
2261 if (notconverted)
2262 {
2263 STRCAT(IObuff, _("[NOT converted]"));
2264 c = TRUE;
2265 }
2266 else if (converted)
2267 {
2268 STRCAT(IObuff, _("[converted]"));
2269 c = TRUE;
2270 }
2271#endif
2272#ifdef FEAT_CRYPT
2273 if (cryptkey != NULL)
2274 {
2275 STRCAT(IObuff, _("[crypted]"));
2276 c = TRUE;
2277 }
2278#endif
2279#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002280 if (conv_error != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002281 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002282 sprintf((char *)IObuff + STRLEN(IObuff),
2283 _("[CONVERSION ERROR in line %ld]"), (long)conv_error);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002284 c = TRUE;
2285 }
2286 else if (illegal_byte > 0)
2287 {
2288 sprintf((char *)IObuff + STRLEN(IObuff),
2289 _("[ILLEGAL BYTE in line %ld]"), (long)illegal_byte);
2290 c = TRUE;
2291 }
2292 else
2293#endif
2294 if (error)
2295 {
2296 STRCAT(IObuff, _("[READ ERRORS]"));
2297 c = TRUE;
2298 }
2299 if (msg_add_fileformat(fileformat))
2300 c = TRUE;
2301#ifdef FEAT_CRYPT
2302 if (cryptkey != NULL)
2303 msg_add_lines(c, (long)linecnt, filesize - CRYPT_MAGIC_LEN);
2304 else
2305#endif
2306 msg_add_lines(c, (long)linecnt, filesize);
2307
2308 vim_free(keep_msg);
2309 keep_msg = NULL;
2310 msg_scrolled_ign = TRUE;
2311#ifdef ALWAYS_USE_GUI
2312 /* Don't show the message when reading stdin, it would end up in a
2313 * message box (which might be shown when exiting!) */
2314 if (read_stdin || read_buffer)
2315 p = msg_may_trunc(FALSE, IObuff);
2316 else
2317#endif
2318 p = msg_trunc_attr(IObuff, FALSE, 0);
2319 if (read_stdin || read_buffer || restart_edit != 0
Bram Moolenaar1c7715d2005-10-03 22:02:18 +00002320 || (msg_scrolled != 0 && !need_wait_return))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002321 /* Need to repeat the message after redrawing when:
2322 * - When reading from stdin (the screen will be cleared next).
2323 * - When restart_edit is set (otherwise there will be a delay
2324 * before redrawing).
2325 * - When the screen was scrolled but there is no wait-return
2326 * prompt. */
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002327 set_keep_msg(p, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002328 msg_scrolled_ign = FALSE;
2329 }
2330
2331 /* with errors writing the file requires ":w!" */
2332 if (newfile && (error
2333#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002334 || conv_error != 0
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002335 || (illegal_byte > 0 && bad_char_behavior != BAD_KEEP)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002336#endif
2337 ))
2338 curbuf->b_p_ro = TRUE;
2339
2340 u_clearline(); /* cannot use "U" command after adding lines */
2341
2342 /*
2343 * In Ex mode: cursor at last new line.
2344 * Otherwise: cursor at first new line.
2345 */
2346 if (exmode_active)
2347 curwin->w_cursor.lnum = from + linecnt;
2348 else
2349 curwin->w_cursor.lnum = from + 1;
2350 check_cursor_lnum();
2351 beginline(BL_WHITE | BL_FIX); /* on first non-blank */
2352
2353 /*
2354 * Set '[ and '] marks to the newly read lines.
2355 */
2356 curbuf->b_op_start.lnum = from + 1;
2357 curbuf->b_op_start.col = 0;
2358 curbuf->b_op_end.lnum = from + linecnt;
2359 curbuf->b_op_end.col = 0;
2360 }
2361 msg_scroll = msg_save;
2362
2363#ifdef FEAT_VIMINFO
2364 /*
2365 * Get the marks before executing autocommands, so they can be used there.
2366 */
2367 check_marks_read();
2368#endif
2369
Bram Moolenaar071d4272004-06-13 20:20:40 +00002370 /*
2371 * Trick: We remember if the last line of the read didn't have
2372 * an eol for when writing it again. This is required for
2373 * ":autocmd FileReadPost *.gz set bin|'[,']!gunzip" to work.
2374 */
2375 write_no_eol_lnum = read_no_eol_lnum;
2376
Bram Moolenaardf177f62005-02-22 08:39:57 +00002377#ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00002378 if (!read_stdin && !read_buffer)
2379 {
2380 int m = msg_scroll;
2381 int n = msg_scrolled;
2382
2383 /* Save the fileformat now, otherwise the buffer will be considered
2384 * modified if the format/encoding was automatically detected. */
2385 if (newfile)
2386 save_file_ff(curbuf);
2387
2388 /*
2389 * The output from the autocommands should not overwrite anything and
2390 * should not be overwritten: Set msg_scroll, restore its value if no
2391 * output was done.
2392 */
2393 msg_scroll = TRUE;
2394 if (filtering)
2395 apply_autocmds_exarg(EVENT_FILTERREADPOST, NULL, sfname,
2396 FALSE, curbuf, eap);
2397 else if (newfile)
2398 apply_autocmds_exarg(EVENT_BUFREADPOST, NULL, sfname,
2399 FALSE, curbuf, eap);
2400 else
2401 apply_autocmds_exarg(EVENT_FILEREADPOST, sfname, sfname,
2402 FALSE, NULL, eap);
2403 if (msg_scrolled == n)
2404 msg_scroll = m;
2405#ifdef FEAT_EVAL
2406 if (aborting()) /* autocmds may abort script processing */
2407 return FAIL;
2408#endif
2409 }
2410#endif
2411
2412 if (recoverymode && error)
2413 return FAIL;
2414 return OK;
2415}
2416
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002417#ifdef FEAT_MBYTE
2418
2419/*
2420 * From the current line count and characters read after that, estimate the
2421 * line number where we are now.
2422 * Used for error messages that include a line number.
2423 */
2424 static linenr_T
2425readfile_linenr(linecnt, p, endp)
2426 linenr_T linecnt; /* line count before reading more bytes */
2427 char_u *p; /* start of more bytes read */
2428 char_u *endp; /* end of more bytes read */
2429{
2430 char_u *s;
2431 linenr_T lnum;
2432
2433 lnum = curbuf->b_ml.ml_line_count - linecnt + 1;
2434 for (s = p; s < endp; ++s)
2435 if (*s == '\n')
2436 ++lnum;
2437 return lnum;
2438}
2439#endif
2440
Bram Moolenaar071d4272004-06-13 20:20:40 +00002441/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00002442 * Fill "*eap" to force the 'fileencoding', 'fileformat' and 'binary to be
2443 * equal to the buffer "buf". Used for calling readfile().
Bram Moolenaar071d4272004-06-13 20:20:40 +00002444 * Returns OK or FAIL.
2445 */
2446 int
2447prep_exarg(eap, buf)
2448 exarg_T *eap;
2449 buf_T *buf;
2450{
2451 eap->cmd = alloc((unsigned)(STRLEN(buf->b_p_ff)
2452#ifdef FEAT_MBYTE
2453 + STRLEN(buf->b_p_fenc)
2454#endif
2455 + 15));
2456 if (eap->cmd == NULL)
2457 return FAIL;
2458
2459#ifdef FEAT_MBYTE
2460 sprintf((char *)eap->cmd, "e ++ff=%s ++enc=%s", buf->b_p_ff, buf->b_p_fenc);
2461 eap->force_enc = 14 + (int)STRLEN(buf->b_p_ff);
Bram Moolenaar195d6352005-12-19 22:08:24 +00002462 eap->bad_char = buf->b_bad_char;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002463#else
2464 sprintf((char *)eap->cmd, "e ++ff=%s", buf->b_p_ff);
2465#endif
2466 eap->force_ff = 7;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002467
2468 eap->force_bin = buf->b_p_bin ? FORCE_BIN : FORCE_NOBIN;
2469 eap->forceit = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002470 return OK;
2471}
2472
2473#ifdef FEAT_MBYTE
2474/*
2475 * Find next fileencoding to use from 'fileencodings'.
2476 * "pp" points to fenc_next. It's advanced to the next item.
2477 * When there are no more items, an empty string is returned and *pp is set to
2478 * NULL.
2479 * When *pp is not set to NULL, the result is in allocated memory.
2480 */
2481 static char_u *
2482next_fenc(pp)
2483 char_u **pp;
2484{
2485 char_u *p;
2486 char_u *r;
2487
2488 if (**pp == NUL)
2489 {
2490 *pp = NULL;
2491 return (char_u *)"";
2492 }
2493 p = vim_strchr(*pp, ',');
2494 if (p == NULL)
2495 {
2496 r = enc_canonize(*pp);
2497 *pp += STRLEN(*pp);
2498 }
2499 else
2500 {
2501 r = vim_strnsave(*pp, (int)(p - *pp));
2502 *pp = p + 1;
2503 if (r != NULL)
2504 {
2505 p = enc_canonize(r);
2506 vim_free(r);
2507 r = p;
2508 }
2509 }
2510 if (r == NULL) /* out of memory */
2511 {
2512 r = (char_u *)"";
2513 *pp = NULL;
2514 }
2515 return r;
2516}
2517
2518# ifdef FEAT_EVAL
2519/*
2520 * Convert a file with the 'charconvert' expression.
2521 * This closes the file which is to be read, converts it and opens the
2522 * resulting file for reading.
2523 * Returns name of the resulting converted file (the caller should delete it
2524 * after reading it).
2525 * Returns NULL if the conversion failed ("*fdp" is not set) .
2526 */
2527 static char_u *
2528readfile_charconvert(fname, fenc, fdp)
2529 char_u *fname; /* name of input file */
2530 char_u *fenc; /* converted from */
2531 int *fdp; /* in/out: file descriptor of file */
2532{
2533 char_u *tmpname;
2534 char_u *errmsg = NULL;
2535
2536 tmpname = vim_tempname('r');
2537 if (tmpname == NULL)
2538 errmsg = (char_u *)_("Can't find temp file for conversion");
2539 else
2540 {
2541 close(*fdp); /* close the input file, ignore errors */
2542 *fdp = -1;
2543 if (eval_charconvert(fenc, enc_utf8 ? (char_u *)"utf-8" : p_enc,
2544 fname, tmpname) == FAIL)
2545 errmsg = (char_u *)_("Conversion with 'charconvert' failed");
2546 if (errmsg == NULL && (*fdp = mch_open((char *)tmpname,
2547 O_RDONLY | O_EXTRA, 0)) < 0)
2548 errmsg = (char_u *)_("can't read output of 'charconvert'");
2549 }
2550
2551 if (errmsg != NULL)
2552 {
2553 /* Don't use emsg(), it breaks mappings, the retry with
2554 * another type of conversion might still work. */
2555 MSG(errmsg);
2556 if (tmpname != NULL)
2557 {
2558 mch_remove(tmpname); /* delete converted file */
2559 vim_free(tmpname);
2560 tmpname = NULL;
2561 }
2562 }
2563
2564 /* If the input file is closed, open it (caller should check for error). */
2565 if (*fdp < 0)
2566 *fdp = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
2567
2568 return tmpname;
2569}
2570# endif
2571
2572#endif
2573
2574#ifdef FEAT_VIMINFO
2575/*
2576 * Read marks for the current buffer from the viminfo file, when we support
2577 * buffer marks and the buffer has a name.
2578 */
2579 static void
2580check_marks_read()
2581{
2582 if (!curbuf->b_marks_read && get_viminfo_parameter('\'') > 0
2583 && curbuf->b_ffname != NULL)
2584 read_viminfo(NULL, FALSE, TRUE, FALSE);
2585
2586 /* Always set b_marks_read; needed when 'viminfo' is changed to include
2587 * the ' parameter after opening a buffer. */
2588 curbuf->b_marks_read = TRUE;
2589}
2590#endif
2591
2592#ifdef FEAT_CRYPT
2593/*
2594 * Check for magic number used for encryption.
2595 * If found, the magic number is removed from ptr[*sizep] and *sizep and
2596 * *filesizep are updated.
2597 * Return the (new) encryption key, NULL for no encryption.
2598 */
2599 static char_u *
2600check_for_cryptkey(cryptkey, ptr, sizep, filesizep, newfile)
2601 char_u *cryptkey; /* previous encryption key or NULL */
2602 char_u *ptr; /* pointer to read bytes */
2603 long *sizep; /* length of read bytes */
2604 long *filesizep; /* nr of bytes used from file */
2605 int newfile; /* editing a new buffer */
2606{
2607 if (*sizep >= CRYPT_MAGIC_LEN
2608 && STRNCMP(ptr, CRYPT_MAGIC, CRYPT_MAGIC_LEN) == 0)
2609 {
2610 if (cryptkey == NULL)
2611 {
2612 if (*curbuf->b_p_key)
2613 cryptkey = curbuf->b_p_key;
2614 else
2615 {
2616 /* When newfile is TRUE, store the typed key
2617 * in the 'key' option and don't free it. */
2618 cryptkey = get_crypt_key(newfile, FALSE);
2619 /* check if empty key entered */
2620 if (cryptkey != NULL && *cryptkey == NUL)
2621 {
2622 if (cryptkey != curbuf->b_p_key)
2623 vim_free(cryptkey);
2624 cryptkey = NULL;
2625 }
2626 }
2627 }
2628
2629 if (cryptkey != NULL)
2630 {
2631 crypt_init_keys(cryptkey);
2632
2633 /* Remove magic number from the text */
2634 *filesizep += CRYPT_MAGIC_LEN;
2635 *sizep -= CRYPT_MAGIC_LEN;
2636 mch_memmove(ptr, ptr + CRYPT_MAGIC_LEN, (size_t)*sizep);
2637 }
2638 }
2639 /* When starting to edit a new file which does not have
2640 * encryption, clear the 'key' option, except when
2641 * starting up (called with -x argument) */
2642 else if (newfile && *curbuf->b_p_key && !starting)
2643 set_option_value((char_u *)"key", 0L, (char_u *)"", OPT_LOCAL);
2644
2645 return cryptkey;
2646}
2647#endif
2648
2649#ifdef UNIX
2650 static void
2651set_file_time(fname, atime, mtime)
2652 char_u *fname;
2653 time_t atime; /* access time */
2654 time_t mtime; /* modification time */
2655{
2656# if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
2657 struct utimbuf buf;
2658
2659 buf.actime = atime;
2660 buf.modtime = mtime;
2661 (void)utime((char *)fname, &buf);
2662# else
2663# if defined(HAVE_UTIMES)
2664 struct timeval tvp[2];
2665
2666 tvp[0].tv_sec = atime;
2667 tvp[0].tv_usec = 0;
2668 tvp[1].tv_sec = mtime;
2669 tvp[1].tv_usec = 0;
2670# ifdef NeXT
2671 (void)utimes((char *)fname, tvp);
2672# else
2673 (void)utimes((char *)fname, (const struct timeval *)&tvp);
2674# endif
2675# endif
2676# endif
2677}
2678#endif /* UNIX */
2679
Bram Moolenaard4755bb2004-09-02 19:12:26 +00002680#if defined(VMS) && !defined(MIN)
2681/* Older DECC compiler for VAX doesn't define MIN() */
2682# define MIN(a, b) ((a) < (b) ? (a) : (b))
2683#endif
2684
Bram Moolenaar071d4272004-06-13 20:20:40 +00002685/*
Bram Moolenaar292ad192005-12-11 21:29:51 +00002686 * buf_write() - write to file "fname" lines "start" through "end"
Bram Moolenaar071d4272004-06-13 20:20:40 +00002687 *
2688 * We do our own buffering here because fwrite() is so slow.
2689 *
Bram Moolenaar292ad192005-12-11 21:29:51 +00002690 * If "forceit" is true, we don't care for errors when attempting backups.
2691 * In case of an error everything possible is done to restore the original
2692 * file. But when "forceit" is TRUE, we risk loosing it.
2693 *
2694 * When "reset_changed" is TRUE and "append" == FALSE and "start" == 1 and
2695 * "end" == curbuf->b_ml.ml_line_count, reset curbuf->b_changed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002696 *
2697 * This function must NOT use NameBuff (because it's called by autowrite()).
2698 *
2699 * return FAIL for failure, OK otherwise
2700 */
2701 int
2702buf_write(buf, fname, sfname, start, end, eap, append, forceit,
2703 reset_changed, filtering)
2704 buf_T *buf;
2705 char_u *fname;
2706 char_u *sfname;
2707 linenr_T start, end;
2708 exarg_T *eap; /* for forced 'ff' and 'fenc', can be
2709 NULL! */
Bram Moolenaar292ad192005-12-11 21:29:51 +00002710 int append; /* append to the file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002711 int forceit;
2712 int reset_changed;
2713 int filtering;
2714{
2715 int fd;
2716 char_u *backup = NULL;
2717 int backup_copy = FALSE; /* copy the original file? */
2718 int dobackup;
2719 char_u *ffname;
2720 char_u *wfname = NULL; /* name of file to write to */
2721 char_u *s;
2722 char_u *ptr;
2723 char_u c;
2724 int len;
2725 linenr_T lnum;
2726 long nchars;
2727 char_u *errmsg = NULL;
2728 char_u *errnum = NULL;
2729 char_u *buffer;
2730 char_u smallbuf[SMBUFSIZE];
2731 char_u *backup_ext;
2732 int bufsize;
2733 long perm; /* file permissions */
2734 int retval = OK;
2735 int newfile = FALSE; /* TRUE if file doesn't exist yet */
2736 int msg_save = msg_scroll;
2737 int overwriting; /* TRUE if writing over original */
2738 int no_eol = FALSE; /* no end-of-line written */
2739 int device = FALSE; /* writing to a device */
2740 struct stat st_old;
2741 int prev_got_int = got_int;
2742 int file_readonly = FALSE; /* overwritten file is read-only */
2743 static char *err_readonly = "is read-only (cannot override: \"W\" in 'cpoptions')";
2744#if defined(UNIX) || defined(__EMX__XX) /*XXX fix me sometime? */
2745 int made_writable = FALSE; /* 'w' bit has been set */
2746#endif
2747 /* writing everything */
2748 int whole = (start == 1 && end == buf->b_ml.ml_line_count);
2749#ifdef FEAT_AUTOCMD
2750 linenr_T old_line_count = buf->b_ml.ml_line_count;
2751#endif
2752 int attr;
2753 int fileformat;
2754 int write_bin;
2755 struct bw_info write_info; /* info for buf_write_bytes() */
2756#ifdef FEAT_MBYTE
2757 int converted = FALSE;
2758 int notconverted = FALSE;
2759 char_u *fenc; /* effective 'fileencoding' */
2760 char_u *fenc_tofree = NULL; /* allocated "fenc" */
2761#endif
2762#ifdef HAS_BW_FLAGS
2763 int wb_flags = 0;
2764#endif
2765#ifdef HAVE_ACL
2766 vim_acl_T acl = NULL; /* ACL copied from original file to
2767 backup or new file */
2768#endif
2769
2770 if (fname == NULL || *fname == NUL) /* safety check */
2771 return FAIL;
2772
2773 /*
2774 * Disallow writing from .exrc and .vimrc in current directory for
2775 * security reasons.
2776 */
2777 if (check_secure())
2778 return FAIL;
2779
2780 /* Avoid a crash for a long name. */
2781 if (STRLEN(fname) >= MAXPATHL)
2782 {
2783 EMSG(_(e_longname));
2784 return FAIL;
2785 }
2786
2787#ifdef FEAT_MBYTE
2788 /* must init bw_conv_buf and bw_iconv_fd before jumping to "fail" */
2789 write_info.bw_conv_buf = NULL;
2790 write_info.bw_conv_error = FALSE;
2791 write_info.bw_restlen = 0;
2792# ifdef USE_ICONV
2793 write_info.bw_iconv_fd = (iconv_t)-1;
2794# endif
2795#endif
2796
Bram Moolenaardf177f62005-02-22 08:39:57 +00002797 /* After writing a file changedtick changes but we don't want to display
2798 * the line. */
2799 ex_no_reprint = TRUE;
2800
Bram Moolenaar071d4272004-06-13 20:20:40 +00002801 /*
2802 * If there is no file name yet, use the one for the written file.
2803 * BF_NOTEDITED is set to reflect this (in case the write fails).
2804 * Don't do this when the write is for a filter command.
Bram Moolenaar292ad192005-12-11 21:29:51 +00002805 * Don't do this when appending.
2806 * Only do this when 'cpoptions' contains the 'F' flag.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002807 */
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00002808 if (buf->b_ffname == NULL
2809 && reset_changed
Bram Moolenaar071d4272004-06-13 20:20:40 +00002810 && whole
2811 && buf == curbuf
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00002812#ifdef FEAT_QUICKFIX
2813 && !bt_nofile(buf)
2814#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002815 && !filtering
Bram Moolenaar292ad192005-12-11 21:29:51 +00002816 && (!append || vim_strchr(p_cpo, CPO_FNAMEAPP) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002817 && vim_strchr(p_cpo, CPO_FNAMEW) != NULL)
2818 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00002819 if (set_rw_fname(fname, sfname) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002820 return FAIL;
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00002821 buf = curbuf; /* just in case autocmds made "buf" invalid */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002822 }
2823
2824 if (sfname == NULL)
2825 sfname = fname;
2826 /*
2827 * For Unix: Use the short file name whenever possible.
2828 * Avoids problems with networks and when directory names are changed.
2829 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
2830 * another directory, which we don't detect
2831 */
2832 ffname = fname; /* remember full fname */
2833#ifdef UNIX
2834 fname = sfname;
2835#endif
2836
2837 if (buf->b_ffname != NULL && fnamecmp(ffname, buf->b_ffname) == 0)
2838 overwriting = TRUE;
2839 else
2840 overwriting = FALSE;
2841
2842 if (exiting)
2843 settmode(TMODE_COOK); /* when exiting allow typahead now */
2844
2845 ++no_wait_return; /* don't wait for return yet */
2846
2847 /*
2848 * Set '[ and '] marks to the lines to be written.
2849 */
2850 buf->b_op_start.lnum = start;
2851 buf->b_op_start.col = 0;
2852 buf->b_op_end.lnum = end;
2853 buf->b_op_end.col = 0;
2854
2855#ifdef FEAT_AUTOCMD
2856 {
2857 aco_save_T aco;
2858 int buf_ffname = FALSE;
2859 int buf_sfname = FALSE;
2860 int buf_fname_f = FALSE;
2861 int buf_fname_s = FALSE;
2862 int did_cmd = FALSE;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00002863 int nofile_err = FALSE;
Bram Moolenaar7c626922005-02-07 22:01:03 +00002864 int empty_memline = (buf->b_ml.ml_mfp == NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002865
2866 /*
2867 * Apply PRE aucocommands.
2868 * Set curbuf to the buffer to be written.
2869 * Careful: The autocommands may call buf_write() recursively!
2870 */
2871 if (ffname == buf->b_ffname)
2872 buf_ffname = TRUE;
2873 if (sfname == buf->b_sfname)
2874 buf_sfname = TRUE;
2875 if (fname == buf->b_ffname)
2876 buf_fname_f = TRUE;
2877 if (fname == buf->b_sfname)
2878 buf_fname_s = TRUE;
2879
2880 /* set curwin/curbuf to buf and save a few things */
2881 aucmd_prepbuf(&aco, buf);
2882
2883 if (append)
2884 {
2885 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD,
2886 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00002887 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00002888#ifdef FEAT_QUICKFIX
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00002889 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00002890 nofile_err = TRUE;
2891 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00002892#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00002893 apply_autocmds_exarg(EVENT_FILEAPPENDPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00002894 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00002895 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002896 }
2897 else if (filtering)
2898 {
2899 apply_autocmds_exarg(EVENT_FILTERWRITEPRE,
2900 NULL, sfname, FALSE, curbuf, eap);
2901 }
2902 else if (reset_changed && whole)
2903 {
2904 if (!(did_cmd = apply_autocmds_exarg(EVENT_BUFWRITECMD,
2905 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00002906 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00002907#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00002908 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00002909 nofile_err = TRUE;
2910 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00002911#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00002912 apply_autocmds_exarg(EVENT_BUFWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00002913 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00002914 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002915 }
2916 else
2917 {
2918 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD,
2919 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00002920 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00002921#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00002922 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00002923 nofile_err = TRUE;
2924 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00002925#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00002926 apply_autocmds_exarg(EVENT_FILEWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00002927 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00002928 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002929 }
2930
2931 /* restore curwin/curbuf and a few other things */
2932 aucmd_restbuf(&aco);
2933
2934 /*
2935 * In three situations we return here and don't write the file:
2936 * 1. the autocommands deleted or unloaded the buffer.
2937 * 2. The autocommands abort script processing.
2938 * 3. If one of the "Cmd" autocommands was executed.
2939 */
2940 if (!buf_valid(buf))
2941 buf = NULL;
Bram Moolenaar7c626922005-02-07 22:01:03 +00002942 if (buf == NULL || (buf->b_ml.ml_mfp == NULL && !empty_memline)
Bram Moolenaar1e015462005-09-25 22:16:38 +00002943 || did_cmd || nofile_err
2944#ifdef FEAT_EVAL
2945 || aborting()
2946#endif
2947 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00002948 {
2949 --no_wait_return;
2950 msg_scroll = msg_save;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00002951 if (nofile_err)
2952 EMSG(_("E676: No matching autocommands for acwrite buffer"));
2953
Bram Moolenaar1e015462005-09-25 22:16:38 +00002954 if (nofile_err
2955#ifdef FEAT_EVAL
2956 || aborting()
2957#endif
2958 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00002959 /* An aborting error, interrupt or exception in the
2960 * autocommands. */
2961 return FAIL;
2962 if (did_cmd)
2963 {
2964 if (buf == NULL)
2965 /* The buffer was deleted. We assume it was written
2966 * (can't retry anyway). */
2967 return OK;
2968 if (overwriting)
2969 {
2970 /* Assume the buffer was written, update the timestamp. */
2971 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00002972 if (append)
2973 buf->b_flags &= ~BF_NEW;
2974 else
2975 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002976 }
Bram Moolenaar292ad192005-12-11 21:29:51 +00002977 if (reset_changed && buf->b_changed && !append
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002978 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002979 /* Buffer still changed, the autocommands didn't work
2980 * properly. */
2981 return FAIL;
2982 return OK;
2983 }
2984#ifdef FEAT_EVAL
2985 if (!aborting())
2986#endif
2987 EMSG(_("E203: Autocommands deleted or unloaded buffer to be written"));
2988 return FAIL;
2989 }
2990
2991 /*
2992 * The autocommands may have changed the number of lines in the file.
2993 * When writing the whole file, adjust the end.
2994 * When writing part of the file, assume that the autocommands only
2995 * changed the number of lines that are to be written (tricky!).
2996 */
2997 if (buf->b_ml.ml_line_count != old_line_count)
2998 {
2999 if (whole) /* write all */
3000 end = buf->b_ml.ml_line_count;
3001 else if (buf->b_ml.ml_line_count > old_line_count) /* more lines */
3002 end += buf->b_ml.ml_line_count - old_line_count;
3003 else /* less lines */
3004 {
3005 end -= old_line_count - buf->b_ml.ml_line_count;
3006 if (end < start)
3007 {
3008 --no_wait_return;
3009 msg_scroll = msg_save;
3010 EMSG(_("E204: Autocommand changed number of lines in unexpected way"));
3011 return FAIL;
3012 }
3013 }
3014 }
3015
3016 /*
3017 * The autocommands may have changed the name of the buffer, which may
3018 * be kept in fname, ffname and sfname.
3019 */
3020 if (buf_ffname)
3021 ffname = buf->b_ffname;
3022 if (buf_sfname)
3023 sfname = buf->b_sfname;
3024 if (buf_fname_f)
3025 fname = buf->b_ffname;
3026 if (buf_fname_s)
3027 fname = buf->b_sfname;
3028 }
3029#endif
3030
3031#ifdef FEAT_NETBEANS_INTG
3032 if (usingNetbeans && isNetbeansBuffer(buf))
3033 {
3034 if (whole)
3035 {
3036 /*
3037 * b_changed can be 0 after an undo, but we still need to write
3038 * the buffer to NetBeans.
3039 */
3040 if (buf->b_changed || isNetbeansModified(buf))
3041 {
Bram Moolenaar009b2592004-10-24 19:18:58 +00003042 --no_wait_return; /* may wait for return now */
3043 msg_scroll = msg_save;
3044 netbeans_save_buffer(buf); /* no error checking... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003045 return retval;
3046 }
3047 else
3048 {
3049 errnum = (char_u *)"E656: ";
3050 errmsg = (char_u *)_("NetBeans dissallows writes of unmodified buffers");
3051 buffer = NULL;
3052 goto fail;
3053 }
3054 }
3055 else
3056 {
3057 errnum = (char_u *)"E657: ";
3058 errmsg = (char_u *)_("Partial writes disallowed for NetBeans buffers");
3059 buffer = NULL;
3060 goto fail;
3061 }
3062 }
3063#endif
3064
3065 if (shortmess(SHM_OVER) && !exiting)
3066 msg_scroll = FALSE; /* overwrite previous file message */
3067 else
3068 msg_scroll = TRUE; /* don't overwrite previous file message */
3069 if (!filtering)
3070 filemess(buf,
3071#ifndef UNIX
3072 sfname,
3073#else
3074 fname,
3075#endif
3076 (char_u *)"", 0); /* show that we are busy */
3077 msg_scroll = FALSE; /* always overwrite the file message now */
3078
3079 buffer = alloc(BUFSIZE);
3080 if (buffer == NULL) /* can't allocate big buffer, use small
3081 * one (to be able to write when out of
3082 * memory) */
3083 {
3084 buffer = smallbuf;
3085 bufsize = SMBUFSIZE;
3086 }
3087 else
3088 bufsize = BUFSIZE;
3089
3090 /*
3091 * Get information about original file (if there is one).
3092 */
3093#if defined(UNIX) && !defined(ARCHIE)
3094 st_old.st_dev = st_old.st_ino = 0;
3095 perm = -1;
3096 if (mch_stat((char *)fname, &st_old) < 0)
3097 newfile = TRUE;
3098 else
3099 {
3100 perm = st_old.st_mode;
3101 if (!S_ISREG(st_old.st_mode)) /* not a file */
3102 {
3103 if (S_ISDIR(st_old.st_mode))
3104 {
3105 errnum = (char_u *)"E502: ";
3106 errmsg = (char_u *)_("is a directory");
3107 goto fail;
3108 }
3109 if (mch_nodetype(fname) != NODE_WRITABLE)
3110 {
3111 errnum = (char_u *)"E503: ";
3112 errmsg = (char_u *)_("is not a file or writable device");
3113 goto fail;
3114 }
3115 /* It's a device of some kind (or a fifo) which we can write to
3116 * but for which we can't make a backup. */
3117 device = TRUE;
3118 newfile = TRUE;
3119 perm = -1;
3120 }
3121 }
3122#else /* !UNIX */
3123 /*
3124 * Check for a writable device name.
3125 */
3126 c = mch_nodetype(fname);
3127 if (c == NODE_OTHER)
3128 {
3129 errnum = (char_u *)"E503: ";
3130 errmsg = (char_u *)_("is not a file or writable device");
3131 goto fail;
3132 }
3133 if (c == NODE_WRITABLE)
3134 {
3135 device = TRUE;
3136 newfile = TRUE;
3137 perm = -1;
3138 }
3139 else
3140 {
3141 perm = mch_getperm(fname);
3142 if (perm < 0)
3143 newfile = TRUE;
3144 else if (mch_isdir(fname))
3145 {
3146 errnum = (char_u *)"E502: ";
3147 errmsg = (char_u *)_("is a directory");
3148 goto fail;
3149 }
3150 if (overwriting)
3151 (void)mch_stat((char *)fname, &st_old);
3152 }
3153#endif /* !UNIX */
3154
3155 if (!device && !newfile)
3156 {
3157 /*
3158 * Check if the file is really writable (when renaming the file to
3159 * make a backup we won't discover it later).
3160 */
3161 file_readonly = (
3162# ifdef USE_MCH_ACCESS
3163# ifdef UNIX
3164 (perm & 0222) == 0 ||
3165# endif
3166 mch_access((char *)fname, W_OK)
3167# else
3168 (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0
3169 ? TRUE : (close(fd), FALSE)
3170# endif
3171 );
3172 if (!forceit && file_readonly)
3173 {
3174 if (vim_strchr(p_cpo, CPO_FWRITE) != NULL)
3175 {
3176 errnum = (char_u *)"E504: ";
3177 errmsg = (char_u *)_(err_readonly);
3178 }
3179 else
3180 {
3181 errnum = (char_u *)"E505: ";
3182 errmsg = (char_u *)_("is read-only (add ! to override)");
3183 }
3184 goto fail;
3185 }
3186
3187 /*
3188 * Check if the timestamp hasn't changed since reading the file.
3189 */
3190 if (overwriting)
3191 {
3192 retval = check_mtime(buf, &st_old);
3193 if (retval == FAIL)
3194 goto fail;
3195 }
3196 }
3197
3198#ifdef HAVE_ACL
3199 /*
3200 * For systems that support ACL: get the ACL from the original file.
3201 */
3202 if (!newfile)
3203 acl = mch_get_acl(fname);
3204#endif
3205
3206 /*
3207 * If 'backupskip' is not empty, don't make a backup for some files.
3208 */
3209 dobackup = (p_wb || p_bk || *p_pm != NUL);
3210#ifdef FEAT_WILDIGN
3211 if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname))
3212 dobackup = FALSE;
3213#endif
3214
3215 /*
3216 * Save the value of got_int and reset it. We don't want a previous
3217 * interruption cancel writing, only hitting CTRL-C while writing should
3218 * abort it.
3219 */
3220 prev_got_int = got_int;
3221 got_int = FALSE;
3222
3223 /* Mark the buffer as 'being saved' to prevent changed buffer warnings */
3224 buf->b_saving = TRUE;
3225
3226 /*
3227 * If we are not appending or filtering, the file exists, and the
3228 * 'writebackup', 'backup' or 'patchmode' option is set, need a backup.
3229 * When 'patchmode' is set also make a backup when appending.
3230 *
3231 * Do not make any backup, if 'writebackup' and 'backup' are both switched
3232 * off. This helps when editing large files on almost-full disks.
3233 */
3234 if (!(append && *p_pm == NUL) && !filtering && perm >= 0 && dobackup)
3235 {
3236#if defined(UNIX) || defined(WIN32)
3237 struct stat st;
3238#endif
3239
3240 if ((bkc_flags & BKC_YES) || append) /* "yes" */
3241 backup_copy = TRUE;
3242#if defined(UNIX) || defined(WIN32)
3243 else if ((bkc_flags & BKC_AUTO)) /* "auto" */
3244 {
3245 int i;
3246
3247# ifdef UNIX
3248 /*
3249 * Don't rename the file when:
3250 * - it's a hard link
3251 * - it's a symbolic link
3252 * - we don't have write permission in the directory
3253 * - we can't set the owner/group of the new file
3254 */
3255 if (st_old.st_nlink > 1
3256 || mch_lstat((char *)fname, &st) < 0
3257 || st.st_dev != st_old.st_dev
Bram Moolenaara5792f52005-11-23 21:25:05 +00003258 || st.st_ino != st_old.st_ino
3259# ifndef HAVE_FCHOWN
3260 || st.st_uid != st_old.st_uid
3261 || st.st_gid != st_old.st_gid
3262# endif
3263 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003264 backup_copy = TRUE;
3265 else
3266# endif
3267 {
3268 /*
3269 * Check if we can create a file and set the owner/group to
3270 * the ones from the original file.
3271 * First find a file name that doesn't exist yet (use some
3272 * arbitrary numbers).
3273 */
3274 STRCPY(IObuff, fname);
3275 for (i = 4913; ; i += 123)
3276 {
3277 sprintf((char *)gettail(IObuff), "%d", i);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003278 if (mch_lstat((char *)IObuff, &st) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003279 break;
3280 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00003281 fd = mch_open((char *)IObuff,
3282 O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003283 if (fd < 0) /* can't write in directory */
3284 backup_copy = TRUE;
3285 else
3286 {
3287# ifdef UNIX
Bram Moolenaara5792f52005-11-23 21:25:05 +00003288# ifdef HAVE_FCHOWN
3289 fchown(fd, st_old.st_uid, st_old.st_gid);
3290# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003291 if (mch_stat((char *)IObuff, &st) < 0
3292 || st.st_uid != st_old.st_uid
3293 || st.st_gid != st_old.st_gid
3294 || st.st_mode != perm)
3295 backup_copy = TRUE;
3296# endif
Bram Moolenaar98358622005-11-28 22:58:23 +00003297 /* Close the file before removing it, on MS-Windows we
3298 * can't delete an open file. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003299 close(fd);
Bram Moolenaar98358622005-11-28 22:58:23 +00003300 mch_remove(IObuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003301 }
3302 }
3303 }
3304
3305# ifdef UNIX
3306 /*
3307 * Break symlinks and/or hardlinks if we've been asked to.
3308 */
3309 if ((bkc_flags & BKC_BREAKSYMLINK) || (bkc_flags & BKC_BREAKHARDLINK))
3310 {
3311 int lstat_res;
3312
3313 lstat_res = mch_lstat((char *)fname, &st);
3314
3315 /* Symlinks. */
3316 if ((bkc_flags & BKC_BREAKSYMLINK)
3317 && lstat_res == 0
3318 && st.st_ino != st_old.st_ino)
3319 backup_copy = FALSE;
3320
3321 /* Hardlinks. */
3322 if ((bkc_flags & BKC_BREAKHARDLINK)
3323 && st_old.st_nlink > 1
3324 && (lstat_res != 0 || st.st_ino == st_old.st_ino))
3325 backup_copy = FALSE;
3326 }
3327#endif
3328
3329#endif
3330
3331 /* make sure we have a valid backup extension to use */
3332 if (*p_bex == NUL)
3333 {
3334#ifdef RISCOS
3335 backup_ext = (char_u *)"/bak";
3336#else
3337 backup_ext = (char_u *)".bak";
3338#endif
3339 }
3340 else
3341 backup_ext = p_bex;
3342
3343 if (backup_copy
3344 && (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) >= 0)
3345 {
3346 int bfd;
3347 char_u *copybuf, *wp;
3348 int some_error = FALSE;
3349 struct stat st_new;
3350 char_u *dirp;
3351 char_u *rootname;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003352#if defined(UNIX) && !defined(SHORT_FNAME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003353 int did_set_shortname;
3354#endif
3355
3356 copybuf = alloc(BUFSIZE + 1);
3357 if (copybuf == NULL)
3358 {
3359 some_error = TRUE; /* out of memory */
3360 goto nobackup;
3361 }
3362
3363 /*
3364 * Try to make the backup in each directory in the 'bdir' option.
3365 *
3366 * Unix semantics has it, that we may have a writable file,
3367 * that cannot be recreated with a simple open(..., O_CREAT, ) e.g:
3368 * - the directory is not writable,
3369 * - the file may be a symbolic link,
3370 * - the file may belong to another user/group, etc.
3371 *
3372 * For these reasons, the existing writable file must be truncated
3373 * and reused. Creation of a backup COPY will be attempted.
3374 */
3375 dirp = p_bdir;
3376 while (*dirp)
3377 {
3378#ifdef UNIX
3379 st_new.st_ino = 0;
3380 st_new.st_dev = 0;
3381 st_new.st_gid = 0;
3382#endif
3383
3384 /*
3385 * Isolate one directory name, using an entry in 'bdir'.
3386 */
3387 (void)copy_option_part(&dirp, copybuf, BUFSIZE, ",");
3388 rootname = get_file_in_dir(fname, copybuf);
3389 if (rootname == NULL)
3390 {
3391 some_error = TRUE; /* out of memory */
3392 goto nobackup;
3393 }
3394
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003395#if defined(UNIX) && !defined(SHORT_FNAME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003396 did_set_shortname = FALSE;
3397#endif
3398
3399 /*
3400 * May try twice if 'shortname' not set.
3401 */
3402 for (;;)
3403 {
3404 /*
3405 * Make backup file name.
3406 */
3407 backup = buf_modname(
3408#ifdef SHORT_FNAME
3409 TRUE,
3410#else
3411 (buf->b_p_sn || buf->b_shortname),
3412#endif
3413 rootname, backup_ext, FALSE);
3414 if (backup == NULL)
3415 {
3416 vim_free(rootname);
3417 some_error = TRUE; /* out of memory */
3418 goto nobackup;
3419 }
3420
3421 /*
3422 * Check if backup file already exists.
3423 */
3424 if (mch_stat((char *)backup, &st_new) >= 0)
3425 {
3426#ifdef UNIX
3427 /*
3428 * Check if backup file is same as original file.
3429 * May happen when modname() gave the same file back.
3430 * E.g. silly link, or file name-length reached.
3431 * If we don't check here, we either ruin the file
3432 * when copying or erase it after writing. jw.
3433 */
3434 if (st_new.st_dev == st_old.st_dev
3435 && st_new.st_ino == st_old.st_ino)
3436 {
3437 vim_free(backup);
3438 backup = NULL; /* no backup file to delete */
3439# ifndef SHORT_FNAME
3440 /*
3441 * may try again with 'shortname' set
3442 */
3443 if (!(buf->b_shortname || buf->b_p_sn))
3444 {
3445 buf->b_shortname = TRUE;
3446 did_set_shortname = TRUE;
3447 continue;
3448 }
3449 /* setting shortname didn't help */
3450 if (did_set_shortname)
3451 buf->b_shortname = FALSE;
3452# endif
3453 break;
3454 }
3455#endif
3456
3457 /*
3458 * If we are not going to keep the backup file, don't
3459 * delete an existing one, try to use another name.
3460 * Change one character, just before the extension.
3461 */
3462 if (!p_bk)
3463 {
3464 wp = backup + STRLEN(backup) - 1
3465 - STRLEN(backup_ext);
3466 if (wp < backup) /* empty file name ??? */
3467 wp = backup;
3468 *wp = 'z';
3469 while (*wp > 'a'
3470 && mch_stat((char *)backup, &st_new) >= 0)
3471 --*wp;
3472 /* They all exist??? Must be something wrong. */
3473 if (*wp == 'a')
3474 {
3475 vim_free(backup);
3476 backup = NULL;
3477 }
3478 }
3479 }
3480 break;
3481 }
3482 vim_free(rootname);
3483
3484 /*
3485 * Try to create the backup file
3486 */
3487 if (backup != NULL)
3488 {
3489 /* remove old backup, if present */
3490 mch_remove(backup);
3491 /* Open with O_EXCL to avoid the file being created while
3492 * we were sleeping (symlink hacker attack?) */
3493 bfd = mch_open((char *)backup,
Bram Moolenaara5792f52005-11-23 21:25:05 +00003494 O_WRONLY|O_CREAT|O_EXTRA|O_EXCL|O_NOFOLLOW,
3495 perm & 0777);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003496 if (bfd < 0)
3497 {
3498 vim_free(backup);
3499 backup = NULL;
3500 }
3501 else
3502 {
3503 /* set file protection same as original file, but
3504 * strip s-bit */
3505 (void)mch_setperm(backup, perm & 0777);
3506
3507#ifdef UNIX
3508 /*
3509 * Try to set the group of the backup same as the
3510 * original file. If this fails, set the protection
3511 * bits for the group same as the protection bits for
3512 * others.
3513 */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003514 if (st_new.st_gid != st_old.st_gid
Bram Moolenaar071d4272004-06-13 20:20:40 +00003515# ifdef HAVE_FCHOWN /* sequent-ptx lacks fchown() */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003516 && fchown(bfd, (uid_t)-1, st_old.st_gid) != 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00003517# endif
3518 )
3519 mch_setperm(backup,
3520 (perm & 0707) | ((perm & 07) << 3));
3521#endif
3522
3523 /*
3524 * copy the file.
3525 */
3526 write_info.bw_fd = bfd;
3527 write_info.bw_buf = copybuf;
3528#ifdef HAS_BW_FLAGS
3529 write_info.bw_flags = FIO_NOCONVERT;
3530#endif
3531 while ((write_info.bw_len = vim_read(fd, copybuf,
3532 BUFSIZE)) > 0)
3533 {
3534 if (buf_write_bytes(&write_info) == FAIL)
3535 {
3536 errmsg = (char_u *)_("E506: Can't write to backup file (add ! to override)");
3537 break;
3538 }
3539 ui_breakcheck();
3540 if (got_int)
3541 {
3542 errmsg = (char_u *)_(e_interr);
3543 break;
3544 }
3545 }
3546
3547 if (close(bfd) < 0 && errmsg == NULL)
3548 errmsg = (char_u *)_("E507: Close error for backup file (add ! to override)");
3549 if (write_info.bw_len < 0)
3550 errmsg = (char_u *)_("E508: Can't read file for backup (add ! to override)");
3551#ifdef UNIX
3552 set_file_time(backup, st_old.st_atime, st_old.st_mtime);
3553#endif
3554#ifdef HAVE_ACL
3555 mch_set_acl(backup, acl);
3556#endif
3557 break;
3558 }
3559 }
3560 }
3561 nobackup:
3562 close(fd); /* ignore errors for closing read file */
3563 vim_free(copybuf);
3564
3565 if (backup == NULL && errmsg == NULL)
3566 errmsg = (char_u *)_("E509: Cannot create backup file (add ! to override)");
3567 /* ignore errors when forceit is TRUE */
3568 if ((some_error || errmsg != NULL) && !forceit)
3569 {
3570 retval = FAIL;
3571 goto fail;
3572 }
3573 errmsg = NULL;
3574 }
3575 else
3576 {
3577 char_u *dirp;
3578 char_u *p;
3579 char_u *rootname;
3580
3581 /*
3582 * Make a backup by renaming the original file.
3583 */
3584 /*
3585 * If 'cpoptions' includes the "W" flag, we don't want to
3586 * overwrite a read-only file. But rename may be possible
3587 * anyway, thus we need an extra check here.
3588 */
3589 if (file_readonly && vim_strchr(p_cpo, CPO_FWRITE) != NULL)
3590 {
3591 errnum = (char_u *)"E504: ";
3592 errmsg = (char_u *)_(err_readonly);
3593 goto fail;
3594 }
3595
3596 /*
3597 *
3598 * Form the backup file name - change path/fo.o.h to
3599 * path/fo.o.h.bak Try all directories in 'backupdir', first one
3600 * that works is used.
3601 */
3602 dirp = p_bdir;
3603 while (*dirp)
3604 {
3605 /*
3606 * Isolate one directory name and make the backup file name.
3607 */
3608 (void)copy_option_part(&dirp, IObuff, IOSIZE, ",");
3609 rootname = get_file_in_dir(fname, IObuff);
3610 if (rootname == NULL)
3611 backup = NULL;
3612 else
3613 {
3614 backup = buf_modname(
3615#ifdef SHORT_FNAME
3616 TRUE,
3617#else
3618 (buf->b_p_sn || buf->b_shortname),
3619#endif
3620 rootname, backup_ext, FALSE);
3621 vim_free(rootname);
3622 }
3623
3624 if (backup != NULL)
3625 {
3626 /*
3627 * If we are not going to keep the backup file, don't
3628 * delete an existing one, try to use another name.
3629 * Change one character, just before the extension.
3630 */
3631 if (!p_bk && mch_getperm(backup) >= 0)
3632 {
3633 p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext);
3634 if (p < backup) /* empty file name ??? */
3635 p = backup;
3636 *p = 'z';
3637 while (*p > 'a' && mch_getperm(backup) >= 0)
3638 --*p;
3639 /* They all exist??? Must be something wrong! */
3640 if (*p == 'a')
3641 {
3642 vim_free(backup);
3643 backup = NULL;
3644 }
3645 }
3646 }
3647 if (backup != NULL)
3648 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00003649 /*
Bram Moolenaarbfd8fc02005-09-20 23:22:24 +00003650 * Delete any existing backup and move the current version
3651 * to the backup. For safety, we don't remove the backup
3652 * until the write has finished successfully. And if the
3653 * 'backup' option is set, leave it around.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003654 */
3655 /*
3656 * If the renaming of the original file to the backup file
3657 * works, quit here.
3658 */
3659 if (vim_rename(fname, backup) == 0)
3660 break;
3661
3662 vim_free(backup); /* don't do the rename below */
3663 backup = NULL;
3664 }
3665 }
3666 if (backup == NULL && !forceit)
3667 {
3668 errmsg = (char_u *)_("E510: Can't make backup file (add ! to override)");
3669 goto fail;
3670 }
3671 }
3672 }
3673
3674#if defined(UNIX) && !defined(ARCHIE)
3675 /* When using ":w!" and the file was read-only: make it writable */
3676 if (forceit && perm >= 0 && !(perm & 0200) && st_old.st_uid == getuid()
3677 && vim_strchr(p_cpo, CPO_FWRITE) == NULL)
3678 {
3679 perm |= 0200;
3680 (void)mch_setperm(fname, perm);
3681 made_writable = TRUE;
3682 }
3683#endif
3684
3685 /* When using ":w!" and writing to the current file, readonly makes no
Bram Moolenaar4399ef42005-02-12 14:29:27 +00003686 * sense, reset it, unless 'Z' appears in 'cpoptions'. */
3687 if (forceit && overwriting && vim_strchr(p_cpo, CPO_KEEPRO) == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003688 {
3689 buf->b_p_ro = FALSE;
3690#ifdef FEAT_TITLE
3691 need_maketitle = TRUE; /* set window title later */
3692#endif
3693#ifdef FEAT_WINDOWS
3694 status_redraw_all(); /* redraw status lines later */
3695#endif
3696 }
3697
3698 if (end > buf->b_ml.ml_line_count)
3699 end = buf->b_ml.ml_line_count;
3700 if (buf->b_ml.ml_flags & ML_EMPTY)
3701 start = end + 1;
3702
3703 /*
3704 * If the original file is being overwritten, there is a small chance that
3705 * we crash in the middle of writing. Therefore the file is preserved now.
3706 * This makes all block numbers positive so that recovery does not need
3707 * the original file.
3708 * Don't do this if there is a backup file and we are exiting.
3709 */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003710 if (reset_changed && !newfile && overwriting
Bram Moolenaar071d4272004-06-13 20:20:40 +00003711 && !(exiting && backup != NULL))
3712 {
3713 ml_preserve(buf, FALSE);
3714 if (got_int)
3715 {
3716 errmsg = (char_u *)_(e_interr);
3717 goto restore_backup;
3718 }
3719 }
3720
3721#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
3722 /*
3723 * Before risking to lose the original file verify if there's
3724 * a resource fork to preserve, and if cannot be done warn
3725 * the users. This happens when overwriting without backups.
3726 */
3727 if (backup == NULL && overwriting && !append)
3728 if (mch_has_resource_fork(fname))
3729 {
3730 errmsg = (char_u *)_("E460: The resource fork would be lost (add ! to override)");
3731 goto restore_backup;
3732 }
3733#endif
3734
3735#ifdef VMS
3736 vms_remove_version(fname); /* remove version */
3737#endif
3738 /* Default: write the the file directly. May write to a temp file for
3739 * multi-byte conversion. */
3740 wfname = fname;
3741
3742#ifdef FEAT_MBYTE
3743 /* Check for forced 'fileencoding' from "++opt=val" argument. */
3744 if (eap != NULL && eap->force_enc != 0)
3745 {
3746 fenc = eap->cmd + eap->force_enc;
3747 fenc = enc_canonize(fenc);
3748 fenc_tofree = fenc;
3749 }
3750 else
3751 fenc = buf->b_p_fenc;
3752
3753 /*
3754 * The file needs to be converted when 'fileencoding' is set and
3755 * 'fileencoding' differs from 'encoding'.
3756 */
3757 converted = (*fenc != NUL && !same_encoding(p_enc, fenc));
3758
3759 /*
3760 * Check if UTF-8 to UCS-2/4 or Latin1 conversion needs to be done. Or
3761 * Latin1 to Unicode conversion. This is handled in buf_write_bytes().
3762 * Prepare the flags for it and allocate bw_conv_buf when needed.
3763 */
3764 if (converted && (enc_utf8 || STRCMP(p_enc, "latin1") == 0))
3765 {
3766 wb_flags = get_fio_flags(fenc);
3767 if (wb_flags & (FIO_UCS2 | FIO_UCS4 | FIO_UTF16 | FIO_UTF8))
3768 {
3769 /* Need to allocate a buffer to translate into. */
3770 if (wb_flags & (FIO_UCS2 | FIO_UTF16 | FIO_UTF8))
3771 write_info.bw_conv_buflen = bufsize * 2;
3772 else /* FIO_UCS4 */
3773 write_info.bw_conv_buflen = bufsize * 4;
3774 write_info.bw_conv_buf
3775 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
3776 if (write_info.bw_conv_buf == NULL)
3777 end = 0;
3778 }
3779 }
3780
3781# ifdef WIN3264
3782 if (converted && wb_flags == 0 && (wb_flags = get_win_fio_flags(fenc)) != 0)
3783 {
3784 /* Convert UTF-8 -> UCS-2 and UCS-2 -> DBCS. Worst-case * 4: */
3785 write_info.bw_conv_buflen = bufsize * 4;
3786 write_info.bw_conv_buf
3787 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
3788 if (write_info.bw_conv_buf == NULL)
3789 end = 0;
3790 }
3791# endif
3792
3793# ifdef MACOS_X
3794 if (converted && wb_flags == 0 && (wb_flags = get_mac_fio_flags(fenc)) != 0)
3795 {
3796 write_info.bw_conv_buflen = bufsize * 3;
3797 write_info.bw_conv_buf
3798 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
3799 if (write_info.bw_conv_buf == NULL)
3800 end = 0;
3801 }
3802# endif
3803
3804# if defined(FEAT_EVAL) || defined(USE_ICONV)
3805 if (converted && wb_flags == 0)
3806 {
3807# ifdef USE_ICONV
3808 /*
3809 * Use iconv() conversion when conversion is needed and it's not done
3810 * internally.
3811 */
3812 write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc,
3813 enc_utf8 ? (char_u *)"utf-8" : p_enc);
3814 if (write_info.bw_iconv_fd != (iconv_t)-1)
3815 {
3816 /* We're going to use iconv(), allocate a buffer to convert in. */
3817 write_info.bw_conv_buflen = bufsize * ICONV_MULT;
3818 write_info.bw_conv_buf
3819 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
3820 if (write_info.bw_conv_buf == NULL)
3821 end = 0;
3822 write_info.bw_first = TRUE;
3823 }
3824# ifdef FEAT_EVAL
3825 else
3826# endif
3827# endif
3828
3829# ifdef FEAT_EVAL
3830 /*
3831 * When the file needs to be converted with 'charconvert' after
3832 * writing, write to a temp file instead and let the conversion
3833 * overwrite the original file.
3834 */
3835 if (*p_ccv != NUL)
3836 {
3837 wfname = vim_tempname('w');
3838 if (wfname == NULL) /* Can't write without a tempfile! */
3839 {
3840 errmsg = (char_u *)_("E214: Can't find temp file for writing");
3841 goto restore_backup;
3842 }
3843 }
3844# endif
3845 }
3846# endif
3847 if (converted && wb_flags == 0
3848# ifdef USE_ICONV
3849 && write_info.bw_iconv_fd == (iconv_t)-1
3850# endif
3851# ifdef FEAT_EVAL
3852 && wfname == fname
3853# endif
3854 )
3855 {
3856 if (!forceit)
3857 {
3858 errmsg = (char_u *)_("E213: Cannot convert (add ! to write without conversion)");
3859 goto restore_backup;
3860 }
3861 notconverted = TRUE;
3862 }
3863#endif
3864
3865 /*
3866 * Open the file "wfname" for writing.
3867 * We may try to open the file twice: If we can't write to the
3868 * file and forceit is TRUE we delete the existing file and try to create
3869 * a new one. If this still fails we may have lost the original file!
3870 * (this may happen when the user reached his quotum for number of files).
3871 * Appending will fail if the file does not exist and forceit is FALSE.
3872 */
3873 while ((fd = mch_open((char *)wfname, O_WRONLY | O_EXTRA | (append
3874 ? (forceit ? (O_APPEND | O_CREAT) : O_APPEND)
3875 : (O_CREAT | O_TRUNC))
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00003876 , perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003877 {
3878 /*
3879 * A forced write will try to create a new file if the old one is
3880 * still readonly. This may also happen when the directory is
3881 * read-only. In that case the mch_remove() will fail.
3882 */
3883 if (errmsg == NULL)
3884 {
3885#ifdef UNIX
3886 struct stat st;
3887
3888 /* Don't delete the file when it's a hard or symbolic link. */
3889 if ((!newfile && st_old.st_nlink > 1)
3890 || (mch_lstat((char *)fname, &st) == 0
3891 && (st.st_dev != st_old.st_dev
3892 || st.st_ino != st_old.st_ino)))
3893 errmsg = (char_u *)_("E166: Can't open linked file for writing");
3894 else
3895#endif
3896 {
3897 errmsg = (char_u *)_("E212: Can't open file for writing");
3898 if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL
3899 && perm >= 0)
3900 {
3901#ifdef UNIX
3902 /* we write to the file, thus it should be marked
3903 writable after all */
3904 if (!(perm & 0200))
3905 made_writable = TRUE;
3906 perm |= 0200;
3907 if (st_old.st_uid != getuid() || st_old.st_gid != getgid())
3908 perm &= 0777;
3909#endif
3910 if (!append) /* don't remove when appending */
3911 mch_remove(wfname);
3912 continue;
3913 }
3914 }
3915 }
3916
3917restore_backup:
3918 {
3919 struct stat st;
3920
3921 /*
3922 * If we failed to open the file, we don't need a backup. Throw it
3923 * away. If we moved or removed the original file try to put the
3924 * backup in its place.
3925 */
3926 if (backup != NULL && wfname == fname)
3927 {
3928 if (backup_copy)
3929 {
3930 /*
3931 * There is a small chance that we removed the original,
3932 * try to move the copy in its place.
3933 * This may not work if the vim_rename() fails.
3934 * In that case we leave the copy around.
3935 */
3936 /* If file does not exist, put the copy in its place */
3937 if (mch_stat((char *)fname, &st) < 0)
3938 vim_rename(backup, fname);
3939 /* if original file does exist throw away the copy */
3940 if (mch_stat((char *)fname, &st) >= 0)
3941 mch_remove(backup);
3942 }
3943 else
3944 {
3945 /* try to put the original file back */
3946 vim_rename(backup, fname);
3947 }
3948 }
3949
3950 /* if original file no longer exists give an extra warning */
3951 if (!newfile && mch_stat((char *)fname, &st) < 0)
3952 end = 0;
3953 }
3954
3955#ifdef FEAT_MBYTE
3956 if (wfname != fname)
3957 vim_free(wfname);
3958#endif
3959 goto fail;
3960 }
3961 errmsg = NULL;
3962
3963#if defined(MACOS_CLASSIC) || defined(WIN3264)
3964 /* TODO: Is it need for MACOS_X? (Dany) */
3965 /*
3966 * On macintosh copy the original files attributes (i.e. the backup)
3967 * This is done in order to preserve the ressource fork and the
3968 * Finder attribute (label, comments, custom icons, file creatore)
3969 */
3970 if (backup != NULL && overwriting && !append)
3971 {
3972 if (backup_copy)
3973 (void)mch_copy_file_attribute(wfname, backup);
3974 else
3975 (void)mch_copy_file_attribute(backup, wfname);
3976 }
3977
3978 if (!overwriting && !append)
3979 {
3980 if (buf->b_ffname != NULL)
3981 (void)mch_copy_file_attribute(buf->b_ffname, wfname);
3982 /* Should copy ressource fork */
3983 }
3984#endif
3985
3986 write_info.bw_fd = fd;
3987
3988#ifdef FEAT_CRYPT
3989 if (*buf->b_p_key && !filtering)
3990 {
3991 crypt_init_keys(buf->b_p_key);
3992 /* Write magic number, so that Vim knows that this file is encrypted
3993 * when reading it again. This also undergoes utf-8 to ucs-2/4
3994 * conversion when needed. */
3995 write_info.bw_buf = (char_u *)CRYPT_MAGIC;
3996 write_info.bw_len = CRYPT_MAGIC_LEN;
3997 write_info.bw_flags = FIO_NOCONVERT;
3998 if (buf_write_bytes(&write_info) == FAIL)
3999 end = 0;
4000 wb_flags |= FIO_ENCRYPTED;
4001 }
4002#endif
4003
4004 write_info.bw_buf = buffer;
4005 nchars = 0;
4006
4007 /* use "++bin", "++nobin" or 'binary' */
4008 if (eap != NULL && eap->force_bin != 0)
4009 write_bin = (eap->force_bin == FORCE_BIN);
4010 else
4011 write_bin = buf->b_p_bin;
4012
4013#ifdef FEAT_MBYTE
4014 /*
4015 * The BOM is written just after the encryption magic number.
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004016 * Skip it when appending and the file already existed, the BOM only makes
4017 * sense at the start of the file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004018 */
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004019 if (buf->b_p_bomb && !write_bin && (!append || perm < 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004020 {
4021 write_info.bw_len = make_bom(buffer, fenc);
4022 if (write_info.bw_len > 0)
4023 {
4024 /* don't convert, do encryption */
4025 write_info.bw_flags = FIO_NOCONVERT | wb_flags;
4026 if (buf_write_bytes(&write_info) == FAIL)
4027 end = 0;
4028 else
4029 nchars += write_info.bw_len;
4030 }
4031 }
4032#endif
4033
4034 write_info.bw_len = bufsize;
4035#ifdef HAS_BW_FLAGS
4036 write_info.bw_flags = wb_flags;
4037#endif
4038 fileformat = get_fileformat_force(buf, eap);
4039 s = buffer;
4040 len = 0;
4041 for (lnum = start; lnum <= end; ++lnum)
4042 {
4043 /*
4044 * The next while loop is done once for each character written.
4045 * Keep it fast!
4046 */
4047 ptr = ml_get_buf(buf, lnum, FALSE) - 1;
4048 while ((c = *++ptr) != NUL)
4049 {
4050 if (c == NL)
4051 *s = NUL; /* replace newlines with NULs */
4052 else if (c == CAR && fileformat == EOL_MAC)
4053 *s = NL; /* Mac: replace CRs with NLs */
4054 else
4055 *s = c;
4056 ++s;
4057 if (++len != bufsize)
4058 continue;
4059 if (buf_write_bytes(&write_info) == FAIL)
4060 {
4061 end = 0; /* write error: break loop */
4062 break;
4063 }
4064 nchars += bufsize;
4065 s = buffer;
4066 len = 0;
4067 }
4068 /* write failed or last line has no EOL: stop here */
4069 if (end == 0
4070 || (lnum == end
4071 && write_bin
4072 && (lnum == write_no_eol_lnum
4073 || (lnum == buf->b_ml.ml_line_count && !buf->b_p_eol))))
4074 {
4075 ++lnum; /* written the line, count it */
4076 no_eol = TRUE;
4077 break;
4078 }
4079 if (fileformat == EOL_UNIX)
4080 *s++ = NL;
4081 else
4082 {
4083 *s++ = CAR; /* EOL_MAC or EOL_DOS: write CR */
4084 if (fileformat == EOL_DOS) /* write CR-NL */
4085 {
4086 if (++len == bufsize)
4087 {
4088 if (buf_write_bytes(&write_info) == FAIL)
4089 {
4090 end = 0; /* write error: break loop */
4091 break;
4092 }
4093 nchars += bufsize;
4094 s = buffer;
4095 len = 0;
4096 }
4097 *s++ = NL;
4098 }
4099 }
4100 if (++len == bufsize && end)
4101 {
4102 if (buf_write_bytes(&write_info) == FAIL)
4103 {
4104 end = 0; /* write error: break loop */
4105 break;
4106 }
4107 nchars += bufsize;
4108 s = buffer;
4109 len = 0;
4110
4111 ui_breakcheck();
4112 if (got_int)
4113 {
4114 end = 0; /* Interrupted, break loop */
4115 break;
4116 }
4117 }
4118#ifdef VMS
4119 /*
4120 * On VMS there is a problem: newlines get added when writing blocks
4121 * at a time. Fix it by writing a line at a time.
4122 * This is much slower!
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004123 * Explanation: VAX/DECC RTL insists that records in some RMS
4124 * structures end with a newline (carriage return) character, and if
4125 * they don't it adds one.
4126 * With other RMS structures it works perfect without this fix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004127 */
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004128 if ((buf->b_fab_rat & (FAB$M_FTN | FAB$M_CR)) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004129 {
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004130 int b2write;
4131
4132 buf->b_fab_mrs = (buf->b_fab_mrs == 0
4133 ? MIN(4096, bufsize)
4134 : MIN(buf->b_fab_mrs, bufsize));
4135
4136 b2write = len;
4137 while (b2write > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004138 {
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004139 write_info.bw_len = MIN(b2write, buf->b_fab_mrs);
4140 if (buf_write_bytes(&write_info) == FAIL)
4141 {
4142 end = 0;
4143 break;
4144 }
4145 b2write -= MIN(b2write, buf->b_fab_mrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004146 }
4147 write_info.bw_len = bufsize;
4148 nchars += len;
4149 s = buffer;
4150 len = 0;
4151 }
4152#endif
4153 }
4154 if (len > 0 && end > 0)
4155 {
4156 write_info.bw_len = len;
4157 if (buf_write_bytes(&write_info) == FAIL)
4158 end = 0; /* write error */
4159 nchars += len;
4160 }
4161
4162#if defined(UNIX) && defined(HAVE_FSYNC)
4163 /* On many journalling file systems there is a bug that causes both the
4164 * original and the backup file to be lost when halting the system right
4165 * after writing the file. That's because only the meta-data is
4166 * journalled. Syncing the file slows down the system, but assures it has
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004167 * been written to disk and we don't lose it.
4168 * For a device do try the fsync() but don't complain if it does not work
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00004169 * (could be a pipe).
4170 * If the 'fsync' option is FALSE, don't fsync(). Useful for laptops. */
4171 if (p_fs && fsync(fd) != 0 && !device)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004172 {
4173 errmsg = (char_u *)_("E667: Fsync failed");
4174 end = 0;
4175 }
4176#endif
4177
Bram Moolenaara5792f52005-11-23 21:25:05 +00004178#ifdef UNIX
4179 /* When creating a new file, set its owner/group to that of the original
4180 * file. Get the new device and inode number. */
4181 if (backup != NULL && !backup_copy)
4182 {
4183# ifdef HAVE_FCHOWN
4184 struct stat st;
4185
4186 /* don't change the owner when it's already OK, some systems remove
4187 * permission or ACL stuff */
4188 if (mch_stat((char *)wfname, &st) < 0
4189 || st.st_uid != st_old.st_uid
4190 || st.st_gid != st_old.st_gid)
4191 {
4192 fchown(fd, st_old.st_uid, st_old.st_gid);
4193 if (perm >= 0) /* set permission again, may have changed */
4194 (void)mch_setperm(wfname, perm);
4195 }
4196# endif
4197 buf_setino(buf);
4198 }
Bram Moolenaar8fa04452005-12-23 22:13:51 +00004199 else if (buf->b_dev < 0)
4200 /* Set the inode when creating a new file. */
4201 buf_setino(buf);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004202#endif
4203
Bram Moolenaar071d4272004-06-13 20:20:40 +00004204 if (close(fd) != 0)
4205 {
4206 errmsg = (char_u *)_("E512: Close failed");
4207 end = 0;
4208 }
4209
4210#ifdef UNIX
4211 if (made_writable)
4212 perm &= ~0200; /* reset 'w' bit for security reasons */
4213#endif
4214 if (perm >= 0) /* set perm. of new file same as old file */
4215 (void)mch_setperm(wfname, perm);
4216#ifdef RISCOS
4217 if (!append && !filtering)
4218 /* Set the filetype after writing the file. */
4219 mch_set_filetype(wfname, buf->b_p_oft);
4220#endif
4221#ifdef HAVE_ACL
4222 /* Probably need to set the ACL before changing the user (can't set the
4223 * ACL on a file the user doesn't own). */
4224 if (!backup_copy)
4225 mch_set_acl(wfname, acl);
4226#endif
4227
Bram Moolenaar071d4272004-06-13 20:20:40 +00004228
4229#if defined(FEAT_MBYTE) && defined(FEAT_EVAL)
4230 if (wfname != fname)
4231 {
4232 /*
4233 * The file was written to a temp file, now it needs to be converted
4234 * with 'charconvert' to (overwrite) the output file.
4235 */
4236 if (end != 0)
4237 {
4238 if (eval_charconvert(enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc,
4239 wfname, fname) == FAIL)
4240 {
4241 write_info.bw_conv_error = TRUE;
4242 end = 0;
4243 }
4244 }
4245 mch_remove(wfname);
4246 vim_free(wfname);
4247 }
4248#endif
4249
4250 if (end == 0)
4251 {
4252 if (errmsg == NULL)
4253 {
4254#ifdef FEAT_MBYTE
4255 if (write_info.bw_conv_error)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004256 errmsg = (char_u *)_("E513: write error, conversion failed (make 'fenc' empty to override)");
Bram Moolenaar071d4272004-06-13 20:20:40 +00004257 else
4258#endif
4259 if (got_int)
4260 errmsg = (char_u *)_(e_interr);
4261 else
4262 errmsg = (char_u *)_("E514: write error (file system full?)");
4263 }
4264
4265 /*
4266 * If we have a backup file, try to put it in place of the new file,
4267 * because the new file is probably corrupt. This avoids loosing the
4268 * original file when trying to make a backup when writing the file a
4269 * second time.
4270 * When "backup_copy" is set we need to copy the backup over the new
4271 * file. Otherwise rename the backup file.
4272 * If this is OK, don't give the extra warning message.
4273 */
4274 if (backup != NULL)
4275 {
4276 if (backup_copy)
4277 {
4278 /* This may take a while, if we were interrupted let the user
4279 * know we got the message. */
4280 if (got_int)
4281 {
4282 MSG(_(e_interr));
4283 out_flush();
4284 }
4285 if ((fd = mch_open((char *)backup, O_RDONLY | O_EXTRA, 0)) >= 0)
4286 {
4287 if ((write_info.bw_fd = mch_open((char *)fname,
Bram Moolenaar9be038d2005-03-08 22:34:32 +00004288 O_WRONLY | O_CREAT | O_TRUNC | O_EXTRA,
4289 perm & 0777)) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004290 {
4291 /* copy the file. */
4292 write_info.bw_buf = smallbuf;
4293#ifdef HAS_BW_FLAGS
4294 write_info.bw_flags = FIO_NOCONVERT;
4295#endif
4296 while ((write_info.bw_len = vim_read(fd, smallbuf,
4297 SMBUFSIZE)) > 0)
4298 if (buf_write_bytes(&write_info) == FAIL)
4299 break;
4300
4301 if (close(write_info.bw_fd) >= 0
4302 && write_info.bw_len == 0)
4303 end = 1; /* success */
4304 }
4305 close(fd); /* ignore errors for closing read file */
4306 }
4307 }
4308 else
4309 {
4310 if (vim_rename(backup, fname) == 0)
4311 end = 1;
4312 }
4313 }
4314 goto fail;
4315 }
4316
4317 lnum -= start; /* compute number of written lines */
4318 --no_wait_return; /* may wait for return now */
4319
4320#if !(defined(UNIX) || defined(VMS))
4321 fname = sfname; /* use shortname now, for the messages */
4322#endif
4323 if (!filtering)
4324 {
4325 msg_add_fname(buf, fname); /* put fname in IObuff with quotes */
4326 c = FALSE;
4327#ifdef FEAT_MBYTE
4328 if (write_info.bw_conv_error)
4329 {
4330 STRCAT(IObuff, _(" CONVERSION ERROR"));
4331 c = TRUE;
4332 }
4333 else if (notconverted)
4334 {
4335 STRCAT(IObuff, _("[NOT converted]"));
4336 c = TRUE;
4337 }
4338 else if (converted)
4339 {
4340 STRCAT(IObuff, _("[converted]"));
4341 c = TRUE;
4342 }
4343#endif
4344 if (device)
4345 {
4346 STRCAT(IObuff, _("[Device]"));
4347 c = TRUE;
4348 }
4349 else if (newfile)
4350 {
4351 STRCAT(IObuff, shortmess(SHM_NEW) ? _("[New]") : _("[New File]"));
4352 c = TRUE;
4353 }
4354 if (no_eol)
4355 {
4356 msg_add_eol();
4357 c = TRUE;
4358 }
4359 /* may add [unix/dos/mac] */
4360 if (msg_add_fileformat(fileformat))
4361 c = TRUE;
4362#ifdef FEAT_CRYPT
4363 if (wb_flags & FIO_ENCRYPTED)
4364 {
4365 STRCAT(IObuff, _("[crypted]"));
4366 c = TRUE;
4367 }
4368#endif
4369 msg_add_lines(c, (long)lnum, nchars); /* add line/char count */
4370 if (!shortmess(SHM_WRITE))
4371 {
4372 if (append)
4373 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended"));
4374 else
4375 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written"));
4376 }
4377
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00004378 set_keep_msg(msg_trunc_attr(IObuff, FALSE, 0), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004379 }
4380
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004381 /* When written everything correctly: reset 'modified'. Unless not
4382 * writing to the original file and '+' is not in 'cpoptions'. */
Bram Moolenaar292ad192005-12-11 21:29:51 +00004383 if (reset_changed && whole && !append
Bram Moolenaar071d4272004-06-13 20:20:40 +00004384#ifdef FEAT_MBYTE
4385 && !write_info.bw_conv_error
4386#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004387 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL)
4388 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004389 {
4390 unchanged(buf, TRUE);
4391 u_unchanged(buf);
4392 }
4393
4394 /*
4395 * If written to the current file, update the timestamp of the swap file
4396 * and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
4397 */
4398 if (overwriting)
4399 {
4400 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00004401 if (append)
4402 buf->b_flags &= ~BF_NEW;
4403 else
4404 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004405 }
4406
4407 /*
4408 * If we kept a backup until now, and we are in patch mode, then we make
4409 * the backup file our 'original' file.
4410 */
4411 if (*p_pm && dobackup)
4412 {
4413 char *org = (char *)buf_modname(
4414#ifdef SHORT_FNAME
4415 TRUE,
4416#else
4417 (buf->b_p_sn || buf->b_shortname),
4418#endif
4419 fname, p_pm, FALSE);
4420
4421 if (backup != NULL)
4422 {
4423 struct stat st;
4424
4425 /*
4426 * If the original file does not exist yet
4427 * the current backup file becomes the original file
4428 */
4429 if (org == NULL)
4430 EMSG(_("E205: Patchmode: can't save original file"));
4431 else if (mch_stat(org, &st) < 0)
4432 {
4433 vim_rename(backup, (char_u *)org);
4434 vim_free(backup); /* don't delete the file */
4435 backup = NULL;
4436#ifdef UNIX
4437 set_file_time((char_u *)org, st_old.st_atime, st_old.st_mtime);
4438#endif
4439 }
4440 }
4441 /*
4442 * If there is no backup file, remember that a (new) file was
4443 * created.
4444 */
4445 else
4446 {
4447 int empty_fd;
4448
4449 if (org == NULL
Bram Moolenaara5792f52005-11-23 21:25:05 +00004450 || (empty_fd = mch_open(org,
4451 O_CREAT | O_EXTRA | O_EXCL | O_NOFOLLOW,
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00004452 perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004453 EMSG(_("E206: patchmode: can't touch empty original file"));
4454 else
4455 close(empty_fd);
4456 }
4457 if (org != NULL)
4458 {
4459 mch_setperm((char_u *)org, mch_getperm(fname) & 0777);
4460 vim_free(org);
4461 }
4462 }
4463
4464 /*
4465 * Remove the backup unless 'backup' option is set
4466 */
4467 if (!p_bk && backup != NULL && mch_remove(backup) != 0)
4468 EMSG(_("E207: Can't delete backup file"));
4469
4470#ifdef FEAT_SUN_WORKSHOP
4471 if (usingSunWorkShop)
4472 workshop_file_saved((char *) ffname);
4473#endif
4474
4475 goto nofail;
4476
4477 /*
4478 * Finish up. We get here either after failure or success.
4479 */
4480fail:
4481 --no_wait_return; /* may wait for return now */
4482nofail:
4483
4484 /* Done saving, we accept changed buffer warnings again */
4485 buf->b_saving = FALSE;
4486
4487 vim_free(backup);
4488 if (buffer != smallbuf)
4489 vim_free(buffer);
4490#ifdef FEAT_MBYTE
4491 vim_free(fenc_tofree);
4492 vim_free(write_info.bw_conv_buf);
4493# ifdef USE_ICONV
4494 if (write_info.bw_iconv_fd != (iconv_t)-1)
4495 {
4496 iconv_close(write_info.bw_iconv_fd);
4497 write_info.bw_iconv_fd = (iconv_t)-1;
4498 }
4499# endif
4500#endif
4501#ifdef HAVE_ACL
4502 mch_free_acl(acl);
4503#endif
4504
4505 if (errmsg != NULL)
4506 {
4507 int numlen = errnum != NULL ? STRLEN(errnum) : 0;
4508
4509 attr = hl_attr(HLF_E); /* set highlight for error messages */
4510 msg_add_fname(buf,
4511#ifndef UNIX
4512 sfname
4513#else
4514 fname
4515#endif
4516 ); /* put file name in IObuff with quotes */
4517 if (STRLEN(IObuff) + STRLEN(errmsg) + numlen >= IOSIZE)
4518 IObuff[IOSIZE - STRLEN(errmsg) - numlen - 1] = NUL;
4519 /* If the error message has the form "is ...", put the error number in
4520 * front of the file name. */
4521 if (errnum != NULL)
4522 {
4523 mch_memmove(IObuff + numlen, IObuff, STRLEN(IObuff) + 1);
4524 mch_memmove(IObuff, errnum, (size_t)numlen);
4525 }
4526 STRCAT(IObuff, errmsg);
4527 emsg(IObuff);
4528
4529 retval = FAIL;
4530 if (end == 0)
4531 {
4532 MSG_PUTS_ATTR(_("\nWARNING: Original file may be lost or damaged\n"),
4533 attr | MSG_HIST);
4534 MSG_PUTS_ATTR(_("don't quit the editor until the file is successfully written!"),
4535 attr | MSG_HIST);
4536
4537 /* Update the timestamp to avoid an "overwrite changed file"
4538 * prompt when writing again. */
4539 if (mch_stat((char *)fname, &st_old) >= 0)
4540 {
4541 buf_store_time(buf, &st_old, fname);
4542 buf->b_mtime_read = buf->b_mtime;
4543 }
4544 }
4545 }
4546 msg_scroll = msg_save;
4547
4548#ifdef FEAT_AUTOCMD
4549#ifdef FEAT_EVAL
4550 if (!should_abort(retval))
4551#else
4552 if (!got_int)
4553#endif
4554 {
4555 aco_save_T aco;
4556
4557 write_no_eol_lnum = 0; /* in case it was set by the previous read */
4558
4559 /*
4560 * Apply POST autocommands.
4561 * Careful: The autocommands may call buf_write() recursively!
4562 */
4563 aucmd_prepbuf(&aco, buf);
4564
4565 if (append)
4566 apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname,
4567 FALSE, curbuf, eap);
4568 else if (filtering)
4569 apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname,
4570 FALSE, curbuf, eap);
4571 else if (reset_changed && whole)
4572 apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname,
4573 FALSE, curbuf, eap);
4574 else
4575 apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname,
4576 FALSE, curbuf, eap);
4577
4578 /* restore curwin/curbuf and a few other things */
4579 aucmd_restbuf(&aco);
4580
4581#ifdef FEAT_EVAL
4582 if (aborting()) /* autocmds may abort script processing */
4583 retval = FALSE;
4584#endif
4585 }
4586#endif
4587
4588 got_int |= prev_got_int;
4589
4590#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
4591 /* Update machine specific information. */
4592 mch_post_buffer_write(buf);
4593#endif
4594 return retval;
4595}
4596
4597/*
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00004598 * Set the name of the current buffer. Use when the buffer doesn't have a
4599 * name and a ":r" or ":w" command with a file name is used.
4600 */
4601 static int
4602set_rw_fname(fname, sfname)
4603 char_u *fname;
4604 char_u *sfname;
4605{
4606#ifdef FEAT_AUTOCMD
4607 /* It's like the unnamed buffer is deleted.... */
4608 if (curbuf->b_p_bl)
4609 apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
4610 apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf);
4611# ifdef FEAT_EVAL
4612 if (aborting()) /* autocmds may abort script processing */
4613 return FAIL;
4614# endif
4615#endif
4616
4617 if (setfname(curbuf, fname, sfname, FALSE) == OK)
4618 curbuf->b_flags |= BF_NOTEDITED;
4619
4620#ifdef FEAT_AUTOCMD
4621 /* ....and a new named one is created */
4622 apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, curbuf);
4623 if (curbuf->b_p_bl)
4624 apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf);
4625# ifdef FEAT_EVAL
4626 if (aborting()) /* autocmds may abort script processing */
4627 return FAIL;
4628# endif
4629
4630 /* Do filetype detection now if 'filetype' is empty. */
4631 if (*curbuf->b_p_ft == NUL)
4632 {
Bram Moolenaar70836c82006-02-20 21:28:49 +00004633 if (au_find_group((char_u *)"filetypedetect") != AUGROUP_ERROR)
4634 (void)do_doautocmd((char_u *)"filetypedetect BufRead", FALSE);
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00004635 do_modelines(FALSE);
4636 }
4637#endif
4638
4639 return OK;
4640}
4641
4642/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004643 * Put file name into IObuff with quotes.
4644 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00004645 void
Bram Moolenaar071d4272004-06-13 20:20:40 +00004646msg_add_fname(buf, fname)
4647 buf_T *buf;
4648 char_u *fname;
4649{
4650 if (fname == NULL)
4651 fname = (char_u *)"-stdin-";
4652 home_replace(buf, fname, IObuff + 1, IOSIZE - 4, TRUE);
4653 IObuff[0] = '"';
4654 STRCAT(IObuff, "\" ");
4655}
4656
4657/*
4658 * Append message for text mode to IObuff.
4659 * Return TRUE if something appended.
4660 */
4661 static int
4662msg_add_fileformat(eol_type)
4663 int eol_type;
4664{
4665#ifndef USE_CRNL
4666 if (eol_type == EOL_DOS)
4667 {
4668 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[dos]") : _("[dos format]"));
4669 return TRUE;
4670 }
4671#endif
4672#ifndef USE_CR
4673 if (eol_type == EOL_MAC)
4674 {
4675 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[mac]") : _("[mac format]"));
4676 return TRUE;
4677 }
4678#endif
4679#if defined(USE_CRNL) || defined(USE_CR)
4680 if (eol_type == EOL_UNIX)
4681 {
4682 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[unix]") : _("[unix format]"));
4683 return TRUE;
4684 }
4685#endif
4686 return FALSE;
4687}
4688
4689/*
4690 * Append line and character count to IObuff.
4691 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00004692 void
Bram Moolenaar071d4272004-06-13 20:20:40 +00004693msg_add_lines(insert_space, lnum, nchars)
4694 int insert_space;
4695 long lnum;
4696 long nchars;
4697{
4698 char_u *p;
4699
4700 p = IObuff + STRLEN(IObuff);
4701
4702 if (insert_space)
4703 *p++ = ' ';
4704 if (shortmess(SHM_LINES))
4705 sprintf((char *)p, "%ldL, %ldC", lnum, nchars);
4706 else
4707 {
4708 if (lnum == 1)
4709 STRCPY(p, _("1 line, "));
4710 else
4711 sprintf((char *)p, _("%ld lines, "), lnum);
4712 p += STRLEN(p);
4713 if (nchars == 1)
4714 STRCPY(p, _("1 character"));
4715 else
4716 sprintf((char *)p, _("%ld characters"), nchars);
4717 }
4718}
4719
4720/*
4721 * Append message for missing line separator to IObuff.
4722 */
4723 static void
4724msg_add_eol()
4725{
4726 STRCAT(IObuff, shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]"));
4727}
4728
4729/*
4730 * Check modification time of file, before writing to it.
4731 * The size isn't checked, because using a tool like "gzip" takes care of
4732 * using the same timestamp but can't set the size.
4733 */
4734 static int
4735check_mtime(buf, st)
4736 buf_T *buf;
4737 struct stat *st;
4738{
4739 if (buf->b_mtime_read != 0
4740 && time_differs((long)st->st_mtime, buf->b_mtime_read))
4741 {
4742 msg_scroll = TRUE; /* don't overwrite messages here */
4743 msg_silent = 0; /* must give this prompt */
4744 /* don't use emsg() here, don't want to flush the buffers */
4745 MSG_ATTR(_("WARNING: The file has been changed since reading it!!!"),
4746 hl_attr(HLF_E));
4747 if (ask_yesno((char_u *)_("Do you really want to write to it"),
4748 TRUE) == 'n')
4749 return FAIL;
4750 msg_scroll = FALSE; /* always overwrite the file message now */
4751 }
4752 return OK;
4753}
4754
4755 static int
4756time_differs(t1, t2)
4757 long t1, t2;
4758{
4759#if defined(__linux__) || defined(MSDOS) || defined(MSWIN)
4760 /* On a FAT filesystem, esp. under Linux, there are only 5 bits to store
4761 * the seconds. Since the roundoff is done when flushing the inode, the
4762 * time may change unexpectedly by one second!!! */
4763 return (t1 - t2 > 1 || t2 - t1 > 1);
4764#else
4765 return (t1 != t2);
4766#endif
4767}
4768
4769/*
4770 * Call write() to write a number of bytes to the file.
4771 * Also handles encryption and 'encoding' conversion.
4772 *
4773 * Return FAIL for failure, OK otherwise.
4774 */
4775 static int
4776buf_write_bytes(ip)
4777 struct bw_info *ip;
4778{
4779 int wlen;
4780 char_u *buf = ip->bw_buf; /* data to write */
4781 int len = ip->bw_len; /* length of data */
4782#ifdef HAS_BW_FLAGS
4783 int flags = ip->bw_flags; /* extra flags */
4784#endif
4785
4786#ifdef FEAT_MBYTE
4787 /*
4788 * Skip conversion when writing the crypt magic number or the BOM.
4789 */
4790 if (!(flags & FIO_NOCONVERT))
4791 {
4792 char_u *p;
4793 unsigned c;
4794 int n;
4795
4796 if (flags & FIO_UTF8)
4797 {
4798 /*
4799 * Convert latin1 in the buffer to UTF-8 in the file.
4800 */
4801 p = ip->bw_conv_buf; /* translate to buffer */
4802 for (wlen = 0; wlen < len; ++wlen)
4803 p += utf_char2bytes(buf[wlen], p);
4804 buf = ip->bw_conv_buf;
4805 len = (int)(p - ip->bw_conv_buf);
4806 }
4807 else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1))
4808 {
4809 /*
4810 * Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
4811 * Latin1 chars in the file.
4812 */
4813 if (flags & FIO_LATIN1)
4814 p = buf; /* translate in-place (can only get shorter) */
4815 else
4816 p = ip->bw_conv_buf; /* translate to buffer */
4817 for (wlen = 0; wlen < len; wlen += n)
4818 {
4819 if (wlen == 0 && ip->bw_restlen != 0)
4820 {
4821 int l;
4822
4823 /* Use remainder of previous call. Append the start of
4824 * buf[] to get a full sequence. Might still be too
4825 * short! */
4826 l = CONV_RESTLEN - ip->bw_restlen;
4827 if (l > len)
4828 l = len;
4829 mch_memmove(ip->bw_rest + ip->bw_restlen, buf, (size_t)l);
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00004830 n = utf_ptr2len_len(ip->bw_rest, ip->bw_restlen + l);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004831 if (n > ip->bw_restlen + len)
4832 {
4833 /* We have an incomplete byte sequence at the end to
4834 * be written. We can't convert it without the
4835 * remaining bytes. Keep them for the next call. */
4836 if (ip->bw_restlen + len > CONV_RESTLEN)
4837 return FAIL;
4838 ip->bw_restlen += len;
4839 break;
4840 }
4841 if (n > 1)
4842 c = utf_ptr2char(ip->bw_rest);
4843 else
4844 c = ip->bw_rest[0];
4845 if (n >= ip->bw_restlen)
4846 {
4847 n -= ip->bw_restlen;
4848 ip->bw_restlen = 0;
4849 }
4850 else
4851 {
4852 ip->bw_restlen -= n;
4853 mch_memmove(ip->bw_rest, ip->bw_rest + n,
4854 (size_t)ip->bw_restlen);
4855 n = 0;
4856 }
4857 }
4858 else
4859 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00004860 n = utf_ptr2len_len(buf + wlen, len - wlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004861 if (n > len - wlen)
4862 {
4863 /* We have an incomplete byte sequence at the end to
4864 * be written. We can't convert it without the
4865 * remaining bytes. Keep them for the next call. */
4866 if (len - wlen > CONV_RESTLEN)
4867 return FAIL;
4868 ip->bw_restlen = len - wlen;
4869 mch_memmove(ip->bw_rest, buf + wlen,
4870 (size_t)ip->bw_restlen);
4871 break;
4872 }
4873 if (n > 1)
4874 c = utf_ptr2char(buf + wlen);
4875 else
4876 c = buf[wlen];
4877 }
4878
4879 ip->bw_conv_error |= ucs2bytes(c, &p, flags);
4880 }
4881 if (flags & FIO_LATIN1)
4882 len = (int)(p - buf);
4883 else
4884 {
4885 buf = ip->bw_conv_buf;
4886 len = (int)(p - ip->bw_conv_buf);
4887 }
4888 }
4889
4890# ifdef WIN3264
4891 else if (flags & FIO_CODEPAGE)
4892 {
4893 /*
4894 * Convert UTF-8 or codepage to UCS-2 and then to MS-Windows
4895 * codepage.
4896 */
4897 char_u *from;
4898 size_t fromlen;
4899 char_u *to;
4900 int u8c;
4901 BOOL bad = FALSE;
4902 int needed;
4903
4904 if (ip->bw_restlen > 0)
4905 {
4906 /* Need to concatenate the remainder of the previous call and
4907 * the bytes of the current call. Use the end of the
4908 * conversion buffer for this. */
4909 fromlen = len + ip->bw_restlen;
4910 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
4911 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
4912 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
4913 }
4914 else
4915 {
4916 from = buf;
4917 fromlen = len;
4918 }
4919
4920 to = ip->bw_conv_buf;
4921 if (enc_utf8)
4922 {
4923 /* Convert from UTF-8 to UCS-2, to the start of the buffer.
4924 * The buffer has been allocated to be big enough. */
4925 while (fromlen > 0)
4926 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00004927 n = utf_ptr2len_len(from, fromlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004928 if (n > (int)fromlen) /* incomplete byte sequence */
4929 break;
4930 u8c = utf_ptr2char(from);
4931 *to++ = (u8c & 0xff);
4932 *to++ = (u8c >> 8);
4933 fromlen -= n;
4934 from += n;
4935 }
4936
4937 /* Copy remainder to ip->bw_rest[] to be used for the next
4938 * call. */
4939 if (fromlen > CONV_RESTLEN)
4940 {
4941 /* weird overlong sequence */
4942 ip->bw_conv_error = TRUE;
4943 return FAIL;
4944 }
4945 mch_memmove(ip->bw_rest, from, fromlen);
4946 ip->bw_restlen = fromlen;
4947 }
4948 else
4949 {
4950 /* Convert from enc_codepage to UCS-2, to the start of the
4951 * buffer. The buffer has been allocated to be big enough. */
4952 ip->bw_restlen = 0;
4953 needed = MultiByteToWideChar(enc_codepage,
4954 MB_ERR_INVALID_CHARS, (LPCSTR)from, fromlen,
4955 NULL, 0);
4956 if (needed == 0)
4957 {
4958 /* When conversion fails there may be a trailing byte. */
4959 needed = MultiByteToWideChar(enc_codepage,
4960 MB_ERR_INVALID_CHARS, (LPCSTR)from, fromlen - 1,
4961 NULL, 0);
4962 if (needed == 0)
4963 {
4964 /* Conversion doesn't work. */
4965 ip->bw_conv_error = TRUE;
4966 return FAIL;
4967 }
4968 /* Save the trailing byte for the next call. */
4969 ip->bw_rest[0] = from[fromlen - 1];
4970 ip->bw_restlen = 1;
4971 }
4972 needed = MultiByteToWideChar(enc_codepage, MB_ERR_INVALID_CHARS,
4973 (LPCSTR)from, fromlen - ip->bw_restlen,
4974 (LPWSTR)to, needed);
4975 if (needed == 0)
4976 {
4977 /* Safety check: Conversion doesn't work. */
4978 ip->bw_conv_error = TRUE;
4979 return FAIL;
4980 }
4981 to += needed * 2;
4982 }
4983
4984 fromlen = to - ip->bw_conv_buf;
4985 buf = to;
4986# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
4987 if (FIO_GET_CP(flags) == CP_UTF8)
4988 {
4989 /* Convert from UCS-2 to UTF-8, using the remainder of the
4990 * conversion buffer. Fails when out of space. */
4991 for (from = ip->bw_conv_buf; fromlen > 1; fromlen -= 2)
4992 {
4993 u8c = *from++;
4994 u8c += (*from++ << 8);
4995 to += utf_char2bytes(u8c, to);
4996 if (to + 6 >= ip->bw_conv_buf + ip->bw_conv_buflen)
4997 {
4998 ip->bw_conv_error = TRUE;
4999 return FAIL;
5000 }
5001 }
5002 len = to - buf;
5003 }
5004 else
5005#endif
5006 {
5007 /* Convert from UCS-2 to the codepage, using the remainder of
5008 * the conversion buffer. If the conversion uses the default
5009 * character "0", the data doesn't fit in this encoding, so
5010 * fail. */
5011 len = WideCharToMultiByte(FIO_GET_CP(flags), 0,
5012 (LPCWSTR)ip->bw_conv_buf, (int)fromlen / sizeof(WCHAR),
5013 (LPSTR)to, ip->bw_conv_buflen - fromlen, 0, &bad);
5014 if (bad)
5015 {
5016 ip->bw_conv_error = TRUE;
5017 return FAIL;
5018 }
5019 }
5020 }
5021# endif
5022
5023# ifdef MACOS_X
5024 else if (flags & FIO_MACROMAN)
5025 {
5026 /*
5027 * Convert UTF-8 or latin1 to Apple MacRoman.
5028 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005029 char_u *from;
5030 size_t fromlen;
5031
5032 if (ip->bw_restlen > 0)
5033 {
5034 /* Need to concatenate the remainder of the previous call and
5035 * the bytes of the current call. Use the end of the
5036 * conversion buffer for this. */
5037 fromlen = len + ip->bw_restlen;
5038 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5039 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5040 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5041 }
5042 else
5043 {
5044 from = buf;
5045 fromlen = len;
5046 }
5047
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00005048 if (enc2macroman(from, fromlen,
5049 ip->bw_conv_buf, &len, ip->bw_conv_buflen,
5050 ip->bw_rest, &ip->bw_restlen) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005051 {
5052 ip->bw_conv_error = TRUE;
5053 return FAIL;
5054 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005055 buf = ip->bw_conv_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005056 }
5057# endif
5058
5059# ifdef USE_ICONV
5060 if (ip->bw_iconv_fd != (iconv_t)-1)
5061 {
5062 const char *from;
5063 size_t fromlen;
5064 char *to;
5065 size_t tolen;
5066
5067 /* Convert with iconv(). */
5068 if (ip->bw_restlen > 0)
5069 {
5070 /* Need to concatenate the remainder of the previous call and
5071 * the bytes of the current call. Use the end of the
5072 * conversion buffer for this. */
5073 fromlen = len + ip->bw_restlen;
5074 from = (char *)ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5075 mch_memmove((void *)from, ip->bw_rest, (size_t)ip->bw_restlen);
5076 mch_memmove((void *)(from + ip->bw_restlen), buf, (size_t)len);
5077 tolen = ip->bw_conv_buflen - fromlen;
5078 }
5079 else
5080 {
5081 from = (const char *)buf;
5082 fromlen = len;
5083 tolen = ip->bw_conv_buflen;
5084 }
5085 to = (char *)ip->bw_conv_buf;
5086
5087 if (ip->bw_first)
5088 {
5089 size_t save_len = tolen;
5090
5091 /* output the initial shift state sequence */
5092 (void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen);
5093
5094 /* There is a bug in iconv() on Linux (which appears to be
5095 * wide-spread) which sets "to" to NULL and messes up "tolen".
5096 */
5097 if (to == NULL)
5098 {
5099 to = (char *)ip->bw_conv_buf;
5100 tolen = save_len;
5101 }
5102 ip->bw_first = FALSE;
5103 }
5104
5105 /*
5106 * If iconv() has an error or there is not enough room, fail.
5107 */
5108 if ((iconv(ip->bw_iconv_fd, (void *)&from, &fromlen, &to, &tolen)
5109 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
5110 || fromlen > CONV_RESTLEN)
5111 {
5112 ip->bw_conv_error = TRUE;
5113 return FAIL;
5114 }
5115
5116 /* copy remainder to ip->bw_rest[] to be used for the next call. */
5117 if (fromlen > 0)
5118 mch_memmove(ip->bw_rest, (void *)from, fromlen);
5119 ip->bw_restlen = (int)fromlen;
5120
5121 buf = ip->bw_conv_buf;
5122 len = (int)((char_u *)to - ip->bw_conv_buf);
5123 }
5124# endif
5125 }
5126#endif /* FEAT_MBYTE */
5127
5128#ifdef FEAT_CRYPT
5129 if (flags & FIO_ENCRYPTED) /* encrypt the data */
5130 {
5131 int ztemp, t, i;
5132
5133 for (i = 0; i < len; i++)
5134 {
5135 ztemp = buf[i];
5136 buf[i] = ZENCODE(ztemp, t);
5137 }
5138 }
5139#endif
5140
5141 /* Repeat the write(), it may be interrupted by a signal. */
5142 while (len)
5143 {
5144 wlen = vim_write(ip->bw_fd, buf, len);
5145 if (wlen <= 0) /* error! */
5146 return FAIL;
5147 len -= wlen;
5148 buf += wlen;
5149 }
5150 return OK;
5151}
5152
5153#ifdef FEAT_MBYTE
5154/*
5155 * Convert a Unicode character to bytes.
5156 */
5157 static int
5158ucs2bytes(c, pp, flags)
5159 unsigned c; /* in: character */
5160 char_u **pp; /* in/out: pointer to result */
5161 int flags; /* FIO_ flags */
5162{
5163 char_u *p = *pp;
5164 int error = FALSE;
5165 int cc;
5166
5167
5168 if (flags & FIO_UCS4)
5169 {
5170 if (flags & FIO_ENDIAN_L)
5171 {
5172 *p++ = c;
5173 *p++ = (c >> 8);
5174 *p++ = (c >> 16);
5175 *p++ = (c >> 24);
5176 }
5177 else
5178 {
5179 *p++ = (c >> 24);
5180 *p++ = (c >> 16);
5181 *p++ = (c >> 8);
5182 *p++ = c;
5183 }
5184 }
5185 else if (flags & (FIO_UCS2 | FIO_UTF16))
5186 {
5187 if (c >= 0x10000)
5188 {
5189 if (flags & FIO_UTF16)
5190 {
5191 /* Make two words, ten bits of the character in each. First
5192 * word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff */
5193 c -= 0x10000;
5194 if (c >= 0x100000)
5195 error = TRUE;
5196 cc = ((c >> 10) & 0x3ff) + 0xd800;
5197 if (flags & FIO_ENDIAN_L)
5198 {
5199 *p++ = cc;
5200 *p++ = ((unsigned)cc >> 8);
5201 }
5202 else
5203 {
5204 *p++ = ((unsigned)cc >> 8);
5205 *p++ = cc;
5206 }
5207 c = (c & 0x3ff) + 0xdc00;
5208 }
5209 else
5210 error = TRUE;
5211 }
5212 if (flags & FIO_ENDIAN_L)
5213 {
5214 *p++ = c;
5215 *p++ = (c >> 8);
5216 }
5217 else
5218 {
5219 *p++ = (c >> 8);
5220 *p++ = c;
5221 }
5222 }
5223 else /* Latin1 */
5224 {
5225 if (c >= 0x100)
5226 {
5227 error = TRUE;
5228 *p++ = 0xBF;
5229 }
5230 else
5231 *p++ = c;
5232 }
5233
5234 *pp = p;
5235 return error;
5236}
5237
5238/*
5239 * Return TRUE if "a" and "b" are the same 'encoding'.
5240 * Ignores difference between "ansi" and "latin1", "ucs-4" and "ucs-4be", etc.
5241 */
5242 static int
5243same_encoding(a, b)
5244 char_u *a;
5245 char_u *b;
5246{
5247 int f;
5248
5249 if (STRCMP(a, b) == 0)
5250 return TRUE;
5251 f = get_fio_flags(a);
5252 return (f != 0 && get_fio_flags(b) == f);
5253}
5254
5255/*
5256 * Check "ptr" for a unicode encoding and return the FIO_ flags needed for the
5257 * internal conversion.
5258 * if "ptr" is an empty string, use 'encoding'.
5259 */
5260 static int
5261get_fio_flags(ptr)
5262 char_u *ptr;
5263{
5264 int prop;
5265
5266 if (*ptr == NUL)
5267 ptr = p_enc;
5268
5269 prop = enc_canon_props(ptr);
5270 if (prop & ENC_UNICODE)
5271 {
5272 if (prop & ENC_2BYTE)
5273 {
5274 if (prop & ENC_ENDIAN_L)
5275 return FIO_UCS2 | FIO_ENDIAN_L;
5276 return FIO_UCS2;
5277 }
5278 if (prop & ENC_4BYTE)
5279 {
5280 if (prop & ENC_ENDIAN_L)
5281 return FIO_UCS4 | FIO_ENDIAN_L;
5282 return FIO_UCS4;
5283 }
5284 if (prop & ENC_2WORD)
5285 {
5286 if (prop & ENC_ENDIAN_L)
5287 return FIO_UTF16 | FIO_ENDIAN_L;
5288 return FIO_UTF16;
5289 }
5290 return FIO_UTF8;
5291 }
5292 if (prop & ENC_LATIN1)
5293 return FIO_LATIN1;
5294 /* must be ENC_DBCS, requires iconv() */
5295 return 0;
5296}
5297
5298#ifdef WIN3264
5299/*
5300 * Check "ptr" for a MS-Windows codepage name and return the FIO_ flags needed
5301 * for the conversion MS-Windows can do for us. Also accept "utf-8".
5302 * Used for conversion between 'encoding' and 'fileencoding'.
5303 */
5304 static int
5305get_win_fio_flags(ptr)
5306 char_u *ptr;
5307{
5308 int cp;
5309
5310 /* Cannot do this when 'encoding' is not utf-8 and not a codepage. */
5311 if (!enc_utf8 && enc_codepage <= 0)
5312 return 0;
5313
5314 cp = encname2codepage(ptr);
5315 if (cp == 0)
5316 {
5317# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5318 if (STRCMP(ptr, "utf-8") == 0)
5319 cp = CP_UTF8;
5320 else
5321# endif
5322 return 0;
5323 }
5324 return FIO_PUT_CP(cp) | FIO_CODEPAGE;
5325}
5326#endif
5327
5328#ifdef MACOS_X
5329/*
5330 * Check "ptr" for a Carbon supported encoding and return the FIO_ flags
5331 * needed for the internal conversion to/from utf-8 or latin1.
5332 */
5333 static int
5334get_mac_fio_flags(ptr)
5335 char_u *ptr;
5336{
5337 if ((enc_utf8 || STRCMP(p_enc, "latin1") == 0)
5338 && (enc_canon_props(ptr) & ENC_MACROMAN))
5339 return FIO_MACROMAN;
5340 return 0;
5341}
5342#endif
5343
5344/*
5345 * Check for a Unicode BOM (Byte Order Mark) at the start of p[size].
5346 * "size" must be at least 2.
5347 * Return the name of the encoding and set "*lenp" to the length.
5348 * Returns NULL when no BOM found.
5349 */
5350 static char_u *
5351check_for_bom(p, size, lenp, flags)
5352 char_u *p;
5353 long size;
5354 int *lenp;
5355 int flags;
5356{
5357 char *name = NULL;
5358 int len = 2;
5359
5360 if (p[0] == 0xef && p[1] == 0xbb && size >= 3 && p[2] == 0xbf
5361 && (flags == FIO_ALL || flags == 0))
5362 {
5363 name = "utf-8"; /* EF BB BF */
5364 len = 3;
5365 }
5366 else if (p[0] == 0xff && p[1] == 0xfe)
5367 {
5368 if (size >= 4 && p[2] == 0 && p[3] == 0
5369 && (flags == FIO_ALL || flags == (FIO_UCS4 | FIO_ENDIAN_L)))
5370 {
5371 name = "ucs-4le"; /* FF FE 00 00 */
5372 len = 4;
5373 }
5374 else if (flags == FIO_ALL || flags == (FIO_UCS2 | FIO_ENDIAN_L))
5375 name = "ucs-2le"; /* FF FE */
5376 else if (flags == (FIO_UTF16 | FIO_ENDIAN_L))
5377 name = "utf-16le"; /* FF FE */
5378 }
5379 else if (p[0] == 0xfe && p[1] == 0xff
5380 && (flags == FIO_ALL || flags == FIO_UCS2 || flags == FIO_UTF16))
5381 {
5382 if (flags == FIO_UTF16)
5383 name = "utf-16"; /* FE FF */
5384 else
5385 name = "ucs-2"; /* FE FF */
5386 }
5387 else if (size >= 4 && p[0] == 0 && p[1] == 0 && p[2] == 0xfe
5388 && p[3] == 0xff && (flags == FIO_ALL || flags == FIO_UCS4))
5389 {
5390 name = "ucs-4"; /* 00 00 FE FF */
5391 len = 4;
5392 }
5393
5394 *lenp = len;
5395 return (char_u *)name;
5396}
5397
5398/*
5399 * Generate a BOM in "buf[4]" for encoding "name".
5400 * Return the length of the BOM (zero when no BOM).
5401 */
5402 static int
5403make_bom(buf, name)
5404 char_u *buf;
5405 char_u *name;
5406{
5407 int flags;
5408 char_u *p;
5409
5410 flags = get_fio_flags(name);
5411
5412 /* Can't put a BOM in a non-Unicode file. */
5413 if (flags == FIO_LATIN1 || flags == 0)
5414 return 0;
5415
5416 if (flags == FIO_UTF8) /* UTF-8 */
5417 {
5418 buf[0] = 0xef;
5419 buf[1] = 0xbb;
5420 buf[2] = 0xbf;
5421 return 3;
5422 }
5423 p = buf;
5424 (void)ucs2bytes(0xfeff, &p, flags);
5425 return (int)(p - buf);
5426}
5427#endif
5428
5429/*
5430 * Try to find a shortname by comparing the fullname with the current
5431 * directory.
5432 * Returns NULL if not shorter name possible, pointer into "full_path"
5433 * otherwise.
5434 */
5435 char_u *
5436shorten_fname(full_path, dir_name)
5437 char_u *full_path;
5438 char_u *dir_name;
5439{
5440 int len;
5441 char_u *p;
5442
5443 if (full_path == NULL)
5444 return NULL;
5445 len = (int)STRLEN(dir_name);
5446 if (fnamencmp(dir_name, full_path, len) == 0)
5447 {
5448 p = full_path + len;
5449#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
5450 /*
5451 * MSDOS: when a file is in the root directory, dir_name will end in a
5452 * slash, since C: by itself does not define a specific dir. In this
5453 * case p may already be correct. <negri>
5454 */
5455 if (!((len > 2) && (*(p - 2) == ':')))
5456#endif
5457 {
5458 if (vim_ispathsep(*p))
5459 ++p;
5460#ifndef VMS /* the path separator is always part of the path */
5461 else
5462 p = NULL;
5463#endif
5464 }
5465 }
5466#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
5467 /*
5468 * When using a file in the current drive, remove the drive name:
5469 * "A:\dir\file" -> "\dir\file". This helps when moving a session file on
5470 * a floppy from "A:\dir" to "B:\dir".
5471 */
5472 else if (len > 3
5473 && TOUPPER_LOC(full_path[0]) == TOUPPER_LOC(dir_name[0])
5474 && full_path[1] == ':'
5475 && vim_ispathsep(full_path[2]))
5476 p = full_path + 2;
5477#endif
5478 else
5479 p = NULL;
5480 return p;
5481}
5482
5483/*
5484 * Shorten filenames for all buffers.
5485 * When "force" is TRUE: Use full path from now on for files currently being
5486 * edited, both for file name and swap file name. Try to shorten the file
5487 * names a bit, if safe to do so.
5488 * When "force" is FALSE: Only try to shorten absolute file names.
5489 * For buffers that have buftype "nofile" or "scratch": never change the file
5490 * name.
5491 */
5492 void
5493shorten_fnames(force)
5494 int force;
5495{
5496 char_u dirname[MAXPATHL];
5497 buf_T *buf;
5498 char_u *p;
5499
5500 mch_dirname(dirname, MAXPATHL);
5501 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
5502 {
5503 if (buf->b_fname != NULL
5504#ifdef FEAT_QUICKFIX
5505 && !bt_nofile(buf)
5506#endif
5507 && !path_with_url(buf->b_fname)
5508 && (force
5509 || buf->b_sfname == NULL
5510 || mch_isFullName(buf->b_sfname)))
5511 {
5512 vim_free(buf->b_sfname);
5513 buf->b_sfname = NULL;
5514 p = shorten_fname(buf->b_ffname, dirname);
5515 if (p != NULL)
5516 {
5517 buf->b_sfname = vim_strsave(p);
5518 buf->b_fname = buf->b_sfname;
5519 }
5520 if (p == NULL || buf->b_fname == NULL)
5521 buf->b_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005522 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00005523
5524 /* Always make the swap file name a full path, a "nofile" buffer may
5525 * also have a swap file. */
5526 mf_fullname(buf->b_ml.ml_mfp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005527 }
5528#ifdef FEAT_WINDOWS
5529 status_redraw_all();
Bram Moolenaar49d7bf12006-02-17 21:45:41 +00005530 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005531#endif
5532}
5533
5534#if (defined(FEAT_DND) && defined(FEAT_GUI_GTK)) \
5535 || defined(FEAT_GUI_MSWIN) \
5536 || defined(FEAT_GUI_MAC) \
5537 || defined(PROTO)
5538/*
5539 * Shorten all filenames in "fnames[count]" by current directory.
5540 */
5541 void
5542shorten_filenames(fnames, count)
5543 char_u **fnames;
5544 int count;
5545{
5546 int i;
5547 char_u dirname[MAXPATHL];
5548 char_u *p;
5549
5550 if (fnames == NULL || count < 1)
5551 return;
5552 mch_dirname(dirname, sizeof(dirname));
5553 for (i = 0; i < count; ++i)
5554 {
5555 if ((p = shorten_fname(fnames[i], dirname)) != NULL)
5556 {
5557 /* shorten_fname() returns pointer in given "fnames[i]". If free
5558 * "fnames[i]" first, "p" becomes invalid. So we need to copy
5559 * "p" first then free fnames[i]. */
5560 p = vim_strsave(p);
5561 vim_free(fnames[i]);
5562 fnames[i] = p;
5563 }
5564 }
5565}
5566#endif
5567
5568/*
5569 * add extention to file name - change path/fo.o.h to path/fo.o.h.ext or
5570 * fo_o_h.ext for MSDOS or when shortname option set.
5571 *
5572 * Assumed that fname is a valid name found in the filesystem we assure that
5573 * the return value is a different name and ends in 'ext'.
5574 * "ext" MUST be at most 4 characters long if it starts with a dot, 3
5575 * characters otherwise.
5576 * Space for the returned name is allocated, must be freed later.
5577 * Returns NULL when out of memory.
5578 */
5579 char_u *
5580modname(fname, ext, prepend_dot)
5581 char_u *fname, *ext;
5582 int prepend_dot; /* may prepend a '.' to file name */
5583{
5584 return buf_modname(
5585#ifdef SHORT_FNAME
5586 TRUE,
5587#else
5588 (curbuf->b_p_sn || curbuf->b_shortname),
5589#endif
5590 fname, ext, prepend_dot);
5591}
5592
5593 char_u *
5594buf_modname(shortname, fname, ext, prepend_dot)
5595 int shortname; /* use 8.3 file name */
5596 char_u *fname, *ext;
5597 int prepend_dot; /* may prepend a '.' to file name */
5598{
5599 char_u *retval;
5600 char_u *s;
5601 char_u *e;
5602 char_u *ptr;
5603 int fnamelen, extlen;
5604
5605 extlen = (int)STRLEN(ext);
5606
5607 /*
5608 * If there is no file name we must get the name of the current directory
5609 * (we need the full path in case :cd is used).
5610 */
5611 if (fname == NULL || *fname == NUL)
5612 {
5613 retval = alloc((unsigned)(MAXPATHL + extlen + 3));
5614 if (retval == NULL)
5615 return NULL;
5616 if (mch_dirname(retval, MAXPATHL) == FAIL ||
5617 (fnamelen = (int)STRLEN(retval)) == 0)
5618 {
5619 vim_free(retval);
5620 return NULL;
5621 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005622 if (!after_pathsep(retval, retval + fnamelen))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005623 {
5624 retval[fnamelen++] = PATHSEP;
5625 retval[fnamelen] = NUL;
5626 }
5627#ifndef SHORT_FNAME
5628 prepend_dot = FALSE; /* nothing to prepend a dot to */
5629#endif
5630 }
5631 else
5632 {
5633 fnamelen = (int)STRLEN(fname);
5634 retval = alloc((unsigned)(fnamelen + extlen + 3));
5635 if (retval == NULL)
5636 return NULL;
5637 STRCPY(retval, fname);
5638#ifdef VMS
5639 vms_remove_version(retval); /* we do not need versions here */
5640#endif
5641 }
5642
5643 /*
5644 * search backwards until we hit a '/', '\' or ':' replacing all '.'
5645 * by '_' for MSDOS or when shortname option set and ext starts with a dot.
5646 * Then truncate what is after the '/', '\' or ':' to 8 characters for
5647 * MSDOS and 26 characters for AMIGA, a lot more for UNIX.
5648 */
Bram Moolenaar53180ce2005-07-05 21:48:14 +00005649 for (ptr = retval + fnamelen; ptr > retval; mb_ptr_back(retval, ptr))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005650 {
5651#ifndef RISCOS
5652 if (*ext == '.'
Bram Moolenaar53180ce2005-07-05 21:48:14 +00005653# ifdef USE_LONG_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00005654 && (!USE_LONG_FNAME || shortname)
Bram Moolenaar53180ce2005-07-05 21:48:14 +00005655# else
5656# ifndef SHORT_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00005657 && shortname
Bram Moolenaar53180ce2005-07-05 21:48:14 +00005658# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005659# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005660 )
5661 if (*ptr == '.') /* replace '.' by '_' */
5662 *ptr = '_';
Bram Moolenaar53180ce2005-07-05 21:48:14 +00005663#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005664 if (vim_ispathsep(*ptr))
Bram Moolenaar53180ce2005-07-05 21:48:14 +00005665 {
5666 ++ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005667 break;
Bram Moolenaar53180ce2005-07-05 21:48:14 +00005668 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005669 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005670
5671 /* the file name has at most BASENAMELEN characters. */
5672#ifndef SHORT_FNAME
5673 if (STRLEN(ptr) > (unsigned)BASENAMELEN)
5674 ptr[BASENAMELEN] = '\0';
5675#endif
5676
5677 s = ptr + STRLEN(ptr);
5678
5679 /*
5680 * For 8.3 file names we may have to reduce the length.
5681 */
5682#ifdef USE_LONG_FNAME
5683 if (!USE_LONG_FNAME || shortname)
5684#else
5685# ifndef SHORT_FNAME
5686 if (shortname)
5687# endif
5688#endif
5689 {
5690 /*
5691 * If there is no file name, or the file name ends in '/', and the
5692 * extension starts with '.', put a '_' before the dot, because just
5693 * ".ext" is invalid.
5694 */
5695 if (fname == NULL || *fname == NUL
5696 || vim_ispathsep(fname[STRLEN(fname) - 1]))
5697 {
5698#ifdef RISCOS
5699 if (*ext == '/')
5700#else
5701 if (*ext == '.')
5702#endif
5703 *s++ = '_';
5704 }
5705 /*
5706 * If the extension starts with '.', truncate the base name at 8
5707 * characters
5708 */
5709#ifdef RISCOS
5710 /* We normally use '/', but swap files are '_' */
5711 else if (*ext == '/' || *ext == '_')
5712#else
5713 else if (*ext == '.')
5714#endif
5715 {
5716 if (s - ptr > (size_t)8)
5717 {
5718 s = ptr + 8;
5719 *s = '\0';
5720 }
5721 }
5722 /*
5723 * If the extension doesn't start with '.', and the file name
5724 * doesn't have an extension yet, append a '.'
5725 */
5726#ifdef RISCOS
5727 else if ((e = vim_strchr(ptr, '/')) == NULL)
5728 *s++ = '/';
5729#else
5730 else if ((e = vim_strchr(ptr, '.')) == NULL)
5731 *s++ = '.';
5732#endif
5733 /*
5734 * If the extension doesn't start with '.', and there already is an
5735 * extension, it may need to be tructated
5736 */
5737 else if ((int)STRLEN(e) + extlen > 4)
5738 s = e + 4 - extlen;
5739 }
5740#if defined(OS2) || defined(USE_LONG_FNAME) || defined(WIN3264)
5741 /*
5742 * If there is no file name, and the extension starts with '.', put a
5743 * '_' before the dot, because just ".ext" may be invalid if it's on a
5744 * FAT partition, and on HPFS it doesn't matter.
5745 */
5746 else if ((fname == NULL || *fname == NUL) && *ext == '.')
5747 *s++ = '_';
5748#endif
5749
5750 /*
5751 * Append the extention.
5752 * ext can start with '.' and cannot exceed 3 more characters.
5753 */
5754 STRCPY(s, ext);
5755
5756#ifndef SHORT_FNAME
5757 /*
5758 * Prepend the dot.
5759 */
5760 if (prepend_dot && !shortname && *(e = gettail(retval)) !=
5761#ifdef RISCOS
5762 '/'
5763#else
5764 '.'
5765#endif
5766#ifdef USE_LONG_FNAME
5767 && USE_LONG_FNAME
5768#endif
5769 )
5770 {
5771 mch_memmove(e + 1, e, STRLEN(e) + 1);
5772#ifdef RISCOS
5773 *e = '/';
5774#else
5775 *e = '.';
5776#endif
5777 }
5778#endif
5779
5780 /*
5781 * Check that, after appending the extension, the file name is really
5782 * different.
5783 */
5784 if (fname != NULL && STRCMP(fname, retval) == 0)
5785 {
5786 /* we search for a character that can be replaced by '_' */
5787 while (--s >= ptr)
5788 {
5789 if (*s != '_')
5790 {
5791 *s = '_';
5792 break;
5793 }
5794 }
5795 if (s < ptr) /* fname was "________.<ext>", how tricky! */
5796 *ptr = 'v';
5797 }
5798 return retval;
5799}
5800
5801/*
5802 * Like fgets(), but if the file line is too long, it is truncated and the
5803 * rest of the line is thrown away. Returns TRUE for end-of-file.
5804 */
5805 int
5806vim_fgets(buf, size, fp)
5807 char_u *buf;
5808 int size;
5809 FILE *fp;
5810{
5811 char *eof;
5812#define FGETS_SIZE 200
5813 char tbuf[FGETS_SIZE];
5814
5815 buf[size - 2] = NUL;
5816#ifdef USE_CR
5817 eof = fgets_cr((char *)buf, size, fp);
5818#else
5819 eof = fgets((char *)buf, size, fp);
5820#endif
5821 if (buf[size - 2] != NUL && buf[size - 2] != '\n')
5822 {
5823 buf[size - 1] = NUL; /* Truncate the line */
5824
5825 /* Now throw away the rest of the line: */
5826 do
5827 {
5828 tbuf[FGETS_SIZE - 2] = NUL;
5829#ifdef USE_CR
5830 fgets_cr((char *)tbuf, FGETS_SIZE, fp);
5831#else
5832 fgets((char *)tbuf, FGETS_SIZE, fp);
5833#endif
5834 } while (tbuf[FGETS_SIZE - 2] != NUL && tbuf[FGETS_SIZE - 2] != '\n');
5835 }
5836 return (eof == NULL);
5837}
5838
5839#if defined(USE_CR) || defined(PROTO)
5840/*
5841 * Like vim_fgets(), but accept any line terminator: CR, CR-LF or LF.
5842 * Returns TRUE for end-of-file.
5843 * Only used for the Mac, because it's much slower than vim_fgets().
5844 */
5845 int
5846tag_fgets(buf, size, fp)
5847 char_u *buf;
5848 int size;
5849 FILE *fp;
5850{
5851 int i = 0;
5852 int c;
5853 int eof = FALSE;
5854
5855 for (;;)
5856 {
5857 c = fgetc(fp);
5858 if (c == EOF)
5859 {
5860 eof = TRUE;
5861 break;
5862 }
5863 if (c == '\r')
5864 {
5865 /* Always store a NL for end-of-line. */
5866 if (i < size - 1)
5867 buf[i++] = '\n';
5868 c = fgetc(fp);
5869 if (c != '\n') /* Macintosh format: single CR. */
5870 ungetc(c, fp);
5871 break;
5872 }
5873 if (i < size - 1)
5874 buf[i++] = c;
5875 if (c == '\n')
5876 break;
5877 }
5878 buf[i] = NUL;
5879 return eof;
5880}
5881#endif
5882
5883/*
5884 * rename() only works if both files are on the same file system, this
5885 * function will (attempts to?) copy the file across if rename fails -- webb
5886 * Return -1 for failure, 0 for success.
5887 */
5888 int
5889vim_rename(from, to)
5890 char_u *from;
5891 char_u *to;
5892{
5893 int fd_in;
5894 int fd_out;
5895 int n;
5896 char *errmsg = NULL;
5897 char *buffer;
5898#ifdef AMIGA
5899 BPTR flock;
5900#endif
5901 struct stat st;
Bram Moolenaar9be038d2005-03-08 22:34:32 +00005902 long perm;
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00005903#ifdef HAVE_ACL
5904 vim_acl_T acl; /* ACL from original file */
5905#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005906
5907 /*
5908 * When the names are identical, there is nothing to do.
5909 */
5910 if (fnamecmp(from, to) == 0)
5911 return 0;
5912
5913 /*
5914 * Fail if the "from" file doesn't exist. Avoids that "to" is deleted.
5915 */
5916 if (mch_stat((char *)from, &st) < 0)
5917 return -1;
5918
5919 /*
5920 * Delete the "to" file, this is required on some systems to make the
5921 * mch_rename() work, on other systems it makes sure that we don't have
5922 * two files when the mch_rename() fails.
5923 */
5924
5925#ifdef AMIGA
5926 /*
5927 * With MSDOS-compatible filesystems (crossdos, messydos) it is possible
5928 * that the name of the "to" file is the same as the "from" file, even
5929 * though the names are different. To avoid the chance of accidently
5930 * deleting the "from" file (horror!) we lock it during the remove.
5931 *
5932 * When used for making a backup before writing the file: This should not
5933 * happen with ":w", because startscript() should detect this problem and
5934 * set buf->b_shortname, causing modname() to return a correct ".bak" file
5935 * name. This problem does exist with ":w filename", but then the
5936 * original file will be somewhere else so the backup isn't really
5937 * important. If autoscripting is off the rename may fail.
5938 */
5939 flock = Lock((UBYTE *)from, (long)ACCESS_READ);
5940#endif
5941 mch_remove(to);
5942#ifdef AMIGA
5943 if (flock)
5944 UnLock(flock);
5945#endif
5946
5947 /*
5948 * First try a normal rename, return if it works.
5949 */
5950 if (mch_rename((char *)from, (char *)to) == 0)
5951 return 0;
5952
5953 /*
5954 * Rename() failed, try copying the file.
5955 */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00005956 perm = mch_getperm(from);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00005957#ifdef HAVE_ACL
5958 /* For systems that support ACL: get the ACL from the original file. */
5959 acl = mch_get_acl(from);
5960#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005961 fd_in = mch_open((char *)from, O_RDONLY|O_EXTRA, 0);
5962 if (fd_in == -1)
5963 return -1;
Bram Moolenaar9be038d2005-03-08 22:34:32 +00005964
5965 /* Create the new file with same permissions as the original. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00005966 fd_out = mch_open((char *)to,
5967 O_CREAT|O_EXCL|O_WRONLY|O_EXTRA|O_NOFOLLOW, (int)perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005968 if (fd_out == -1)
5969 {
5970 close(fd_in);
5971 return -1;
5972 }
5973
5974 buffer = (char *)alloc(BUFSIZE);
5975 if (buffer == NULL)
5976 {
5977 close(fd_in);
5978 close(fd_out);
5979 return -1;
5980 }
5981
5982 while ((n = vim_read(fd_in, buffer, BUFSIZE)) > 0)
5983 if (vim_write(fd_out, buffer, n) != n)
5984 {
5985 errmsg = _("E208: Error writing to \"%s\"");
5986 break;
5987 }
5988
5989 vim_free(buffer);
5990 close(fd_in);
5991 if (close(fd_out) < 0)
5992 errmsg = _("E209: Error closing \"%s\"");
5993 if (n < 0)
5994 {
5995 errmsg = _("E210: Error reading \"%s\"");
5996 to = from;
5997 }
Bram Moolenaarc6039d82005-12-02 00:44:04 +00005998#ifndef UNIX /* for Unix mch_open() already set ther permission */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00005999 mch_setperm(to, perm);
Bram Moolenaarc6039d82005-12-02 00:44:04 +00006000#endif
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006001#ifdef HAVE_ACL
6002 mch_set_acl(to, acl);
6003#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006004 if (errmsg != NULL)
6005 {
6006 EMSG2(errmsg, to);
6007 return -1;
6008 }
6009 mch_remove(from);
6010 return 0;
6011}
6012
6013static int already_warned = FALSE;
6014
6015/*
6016 * Check if any not hidden buffer has been changed.
6017 * Postpone the check if there are characters in the stuff buffer, a global
6018 * command is being executed, a mapping is being executed or an autocommand is
6019 * busy.
6020 * Returns TRUE if some message was written (screen should be redrawn and
6021 * cursor positioned).
6022 */
6023 int
6024check_timestamps(focus)
6025 int focus; /* called for GUI focus event */
6026{
6027 buf_T *buf;
6028 int didit = 0;
6029 int n;
6030
6031 /* Don't check timestamps while system() or another low-level function may
6032 * cause us to lose and gain focus. */
6033 if (no_check_timestamps > 0)
6034 return FALSE;
6035
6036 /* Avoid doing a check twice. The OK/Reload dialog can cause a focus
6037 * event and we would keep on checking if the file is steadily growing.
6038 * Do check again after typing something. */
6039 if (focus && did_check_timestamps)
6040 {
6041 need_check_timestamps = TRUE;
6042 return FALSE;
6043 }
6044
6045 if (!stuff_empty() || global_busy || !typebuf_typed()
6046#ifdef FEAT_AUTOCMD
6047 || autocmd_busy
6048#endif
6049 )
6050 need_check_timestamps = TRUE; /* check later */
6051 else
6052 {
6053 ++no_wait_return;
6054 did_check_timestamps = TRUE;
6055 already_warned = FALSE;
6056 for (buf = firstbuf; buf != NULL; )
6057 {
6058 /* Only check buffers in a window. */
6059 if (buf->b_nwindows > 0)
6060 {
6061 n = buf_check_timestamp(buf, focus);
6062 if (didit < n)
6063 didit = n;
6064 if (n > 0 && !buf_valid(buf))
6065 {
6066 /* Autocommands have removed the buffer, start at the
6067 * first one again. */
6068 buf = firstbuf;
6069 continue;
6070 }
6071 }
6072 buf = buf->b_next;
6073 }
6074 --no_wait_return;
6075 need_check_timestamps = FALSE;
6076 if (need_wait_return && didit == 2)
6077 {
6078 /* make sure msg isn't overwritten */
6079 msg_puts((char_u *)"\n");
6080 out_flush();
6081 }
6082 }
6083 return didit;
6084}
6085
6086/*
6087 * Move all the lines from buffer "frombuf" to buffer "tobuf".
6088 * Return OK or FAIL. When FAIL "tobuf" is incomplete and/or "frombuf" is not
6089 * empty.
6090 */
6091 static int
6092move_lines(frombuf, tobuf)
6093 buf_T *frombuf;
6094 buf_T *tobuf;
6095{
6096 buf_T *tbuf = curbuf;
6097 int retval = OK;
6098 linenr_T lnum;
6099 char_u *p;
6100
6101 /* Copy the lines in "frombuf" to "tobuf". */
6102 curbuf = tobuf;
6103 for (lnum = 1; lnum <= frombuf->b_ml.ml_line_count; ++lnum)
6104 {
6105 p = vim_strsave(ml_get_buf(frombuf, lnum, FALSE));
6106 if (p == NULL || ml_append(lnum - 1, p, 0, FALSE) == FAIL)
6107 {
6108 vim_free(p);
6109 retval = FAIL;
6110 break;
6111 }
6112 vim_free(p);
6113 }
6114
6115 /* Delete all the lines in "frombuf". */
6116 if (retval != FAIL)
6117 {
6118 curbuf = frombuf;
6119 while (!bufempty())
6120 if (ml_delete(curbuf->b_ml.ml_line_count, FALSE) == FAIL)
6121 {
6122 /* Oops! We could try putting back the saved lines, but that
6123 * might fail again... */
6124 retval = FAIL;
6125 break;
6126 }
6127 }
6128
6129 curbuf = tbuf;
6130 return retval;
6131}
6132
6133/*
6134 * Check if buffer "buf" has been changed.
6135 * Also check if the file for a new buffer unexpectedly appeared.
6136 * return 1 if a changed buffer was found.
6137 * return 2 if a message has been displayed.
6138 * return 0 otherwise.
6139 */
6140/*ARGSUSED*/
6141 int
6142buf_check_timestamp(buf, focus)
6143 buf_T *buf;
6144 int focus; /* called for GUI focus event */
6145{
6146 struct stat st;
6147 int stat_res;
6148 int retval = 0;
6149 char_u *path;
6150 char_u *tbuf;
6151 char *mesg = NULL;
Bram Moolenaar44ecf652005-03-07 23:09:59 +00006152 char *mesg2 = "";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006153 int helpmesg = FALSE;
6154 int reload = FALSE;
6155#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6156 int can_reload = FALSE;
6157#endif
6158 size_t orig_size = buf->b_orig_size;
6159 int orig_mode = buf->b_orig_mode;
6160#ifdef FEAT_GUI
6161 int save_mouse_correct = need_mouse_correct;
6162#endif
6163#ifdef FEAT_AUTOCMD
6164 static int busy = FALSE;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006165 int n;
6166 char_u *s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006167#endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006168 char *reason;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006169
6170 /* If there is no file name, the buffer is not loaded, 'buftype' is
6171 * set, we are in the middle of a save or being called recursively: ignore
6172 * this buffer. */
6173 if (buf->b_ffname == NULL
6174 || buf->b_ml.ml_mfp == NULL
6175#if defined(FEAT_QUICKFIX)
6176 || *buf->b_p_bt != NUL
6177#endif
6178 || buf->b_saving
6179#ifdef FEAT_AUTOCMD
6180 || busy
6181#endif
Bram Moolenaar009b2592004-10-24 19:18:58 +00006182#ifdef FEAT_NETBEANS_INTG
6183 || isNetbeansBuffer(buf)
6184#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006185 )
6186 return 0;
6187
6188 if ( !(buf->b_flags & BF_NOTEDITED)
6189 && buf->b_mtime != 0
6190 && ((stat_res = mch_stat((char *)buf->b_ffname, &st)) < 0
6191 || time_differs((long)st.st_mtime, buf->b_mtime)
6192#ifdef HAVE_ST_MODE
6193 || (int)st.st_mode != buf->b_orig_mode
6194#else
6195 || mch_getperm(buf->b_ffname) != buf->b_orig_mode
6196#endif
6197 ))
6198 {
6199 retval = 1;
6200
Bram Moolenaar316059c2006-01-14 21:18:42 +00006201 /* set b_mtime to stop further warnings (e.g., when executing
6202 * FileChangedShell autocmd) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006203 if (stat_res < 0)
6204 {
6205 buf->b_mtime = 0;
6206 buf->b_orig_size = 0;
6207 buf->b_orig_mode = 0;
6208 }
6209 else
6210 buf_store_time(buf, &st, buf->b_ffname);
6211
6212 /* Don't do anything for a directory. Might contain the file
6213 * explorer. */
6214 if (mch_isdir(buf->b_fname))
6215 ;
6216
6217 /*
6218 * If 'autoread' is set, the buffer has no changes and the file still
6219 * exists, reload the buffer. Use the buffer-local option value if it
6220 * was set, the global option value otherwise.
6221 */
6222 else if ((buf->b_p_ar >= 0 ? buf->b_p_ar : p_ar)
6223 && !bufIsChanged(buf) && stat_res >= 0)
6224 reload = TRUE;
6225 else
6226 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006227 if (stat_res < 0)
6228 reason = "deleted";
6229 else if (bufIsChanged(buf))
6230 reason = "conflict";
6231 else if (orig_size != buf->b_orig_size || buf_contents_changed(buf))
6232 reason = "changed";
6233 else if (orig_mode != buf->b_orig_mode)
6234 reason = "mode";
6235 else
6236 reason = "time";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006237
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006238#ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006239 /*
6240 * Only give the warning if there are no FileChangedShell
6241 * autocommands.
6242 * Avoid being called recursively by setting "busy".
6243 */
6244 busy = TRUE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00006245# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006246 set_vim_var_string(VV_FCS_REASON, (char_u *)reason, -1);
6247 set_vim_var_string(VV_FCS_CHOICE, (char_u *)"", -1);
Bram Moolenaar1e015462005-09-25 22:16:38 +00006248# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006249 n = apply_autocmds(EVENT_FILECHANGEDSHELL,
6250 buf->b_fname, buf->b_fname, FALSE, buf);
6251 busy = FALSE;
6252 if (n)
6253 {
6254 if (!buf_valid(buf))
6255 EMSG(_("E246: FileChangedShell autocommand deleted buffer"));
Bram Moolenaar1e015462005-09-25 22:16:38 +00006256# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006257 s = get_vim_var_str(VV_FCS_CHOICE);
6258 if (STRCMP(s, "reload") == 0 && *reason != 'd')
6259 reload = TRUE;
6260 else if (STRCMP(s, "ask") == 0)
6261 n = FALSE;
6262 else
Bram Moolenaar1e015462005-09-25 22:16:38 +00006263# endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006264 return 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006265 }
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006266 if (!n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006267#endif
6268 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006269 if (*reason == 'd')
6270 mesg = _("E211: File \"%s\" no longer available");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006271 else
6272 {
6273 helpmesg = TRUE;
6274#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6275 can_reload = TRUE;
6276#endif
6277 /*
6278 * Check if the file contents really changed to avoid
6279 * giving a warning when only the timestamp was set (e.g.,
6280 * checked out of CVS). Always warn when the buffer was
6281 * changed.
6282 */
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006283 if (reason[2] == 'n')
6284 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006285 mesg = _("W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006286 mesg2 = _("See \":help W12\" for more info.");
6287 }
6288 else if (reason[1] == 'h')
6289 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006290 mesg = _("W11: Warning: File \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006291 mesg2 = _("See \":help W11\" for more info.");
6292 }
6293 else if (*reason == 'm')
6294 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006295 mesg = _("W16: Warning: Mode of file \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006296 mesg2 = _("See \":help W16\" for more info.");
6297 }
6298 /* Else: only timestamp changed, ignored */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006299 }
6300 }
6301 }
6302
6303 }
6304 else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W)
6305 && vim_fexists(buf->b_ffname))
6306 {
6307 retval = 1;
6308 mesg = _("W13: Warning: File \"%s\" has been created after editing started");
6309 buf->b_flags |= BF_NEW_W;
6310#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6311 can_reload = TRUE;
6312#endif
6313 }
6314
6315 if (mesg != NULL)
6316 {
6317 path = home_replace_save(buf, buf->b_fname);
6318 if (path != NULL)
6319 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006320 if (!helpmesg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006321 mesg2 = "";
6322 tbuf = alloc((unsigned)(STRLEN(path) + STRLEN(mesg)
6323 + STRLEN(mesg2) + 2));
6324 sprintf((char *)tbuf, mesg, path);
6325#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6326 if (can_reload)
6327 {
6328 if (*mesg2 != NUL)
6329 {
6330 STRCAT(tbuf, "\n");
6331 STRCAT(tbuf, mesg2);
6332 }
6333 if (do_dialog(VIM_WARNING, (char_u *)_("Warning"), tbuf,
6334 (char_u *)_("&OK\n&Load File"), 1, NULL) == 2)
6335 reload = TRUE;
6336 }
6337 else
6338#endif
6339 if (State > NORMAL_BUSY || (State & CMDLINE) || already_warned)
6340 {
6341 if (*mesg2 != NUL)
6342 {
6343 STRCAT(tbuf, "; ");
6344 STRCAT(tbuf, mesg2);
6345 }
6346 EMSG(tbuf);
6347 retval = 2;
6348 }
6349 else
6350 {
Bram Moolenaared203462004-06-16 11:19:22 +00006351# ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006352 if (!autocmd_busy)
Bram Moolenaared203462004-06-16 11:19:22 +00006353# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006354 {
6355 msg_start();
6356 msg_puts_attr(tbuf, hl_attr(HLF_E) + MSG_HIST);
6357 if (*mesg2 != NUL)
6358 msg_puts_attr((char_u *)mesg2,
6359 hl_attr(HLF_W) + MSG_HIST);
6360 msg_clr_eos();
6361 (void)msg_end();
6362 if (emsg_silent == 0)
6363 {
6364 out_flush();
Bram Moolenaared203462004-06-16 11:19:22 +00006365# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00006366 if (!focus)
Bram Moolenaared203462004-06-16 11:19:22 +00006367# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006368 /* give the user some time to think about it */
6369 ui_delay(1000L, TRUE);
6370
6371 /* don't redraw and erase the message */
6372 redraw_cmdline = FALSE;
6373 }
6374 }
6375 already_warned = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006376 }
6377
6378 vim_free(path);
6379 vim_free(tbuf);
6380 }
6381 }
6382
6383 if (reload)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006384 /* Reload the buffer. */
Bram Moolenaar316059c2006-01-14 21:18:42 +00006385 buf_reload(buf, orig_mode);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006386
6387#ifdef FEAT_GUI
6388 /* restore this in case an autocommand has set it; it would break
6389 * 'mousefocus' */
6390 need_mouse_correct = save_mouse_correct;
6391#endif
6392
6393 return retval;
6394}
6395
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006396/*
6397 * Reload a buffer that is already loaded.
6398 * Used when the file was changed outside of Vim.
Bram Moolenaar316059c2006-01-14 21:18:42 +00006399 * "orig_mode" is buf->b_orig_mode before the need for reloading was detected.
6400 * buf->b_orig_mode may have been reset already.
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006401 */
6402 void
Bram Moolenaar316059c2006-01-14 21:18:42 +00006403buf_reload(buf, orig_mode)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006404 buf_T *buf;
Bram Moolenaar316059c2006-01-14 21:18:42 +00006405 int orig_mode;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006406{
6407 exarg_T ea;
6408 pos_T old_cursor;
6409 linenr_T old_topline;
6410 int old_ro = buf->b_p_ro;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006411 buf_T *savebuf;
6412 int saved = OK;
6413#ifdef FEAT_AUTOCMD
6414 aco_save_T aco;
6415
6416 /* set curwin/curbuf for "buf" and save some things */
6417 aucmd_prepbuf(&aco, buf);
6418#else
6419 buf_T *save_curbuf = curbuf;
6420
6421 curbuf = buf;
6422 curwin->w_buffer = buf;
6423#endif
6424
6425 /* We only want to read the text from the file, not reset the syntax
6426 * highlighting, clear marks, diff status, etc. Force the fileformat
6427 * and encoding to be the same. */
6428 if (prep_exarg(&ea, buf) == OK)
6429 {
6430 old_cursor = curwin->w_cursor;
6431 old_topline = curwin->w_topline;
6432
6433 /*
6434 * To behave like when a new file is edited (matters for
6435 * BufReadPost autocommands) we first need to delete the current
6436 * buffer contents. But if reading the file fails we should keep
6437 * the old contents. Can't use memory only, the file might be
6438 * too big. Use a hidden buffer to move the buffer contents to.
6439 */
6440 if (bufempty())
6441 savebuf = NULL;
6442 else
6443 {
6444 /* Allocate a buffer without putting it in the buffer list. */
6445 savebuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
6446 if (savebuf != NULL)
6447 {
6448 /* Open the memline. */
6449 curbuf = savebuf;
6450 curwin->w_buffer = savebuf;
Bram Moolenaar4770d092006-01-12 23:22:24 +00006451 saved = ml_open(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006452 curbuf = buf;
6453 curwin->w_buffer = buf;
6454 }
6455 if (savebuf == NULL || saved == FAIL
6456 || move_lines(buf, savebuf) == FAIL)
6457 {
6458 EMSG2(_("E462: Could not prepare for reloading \"%s\""),
6459 buf->b_fname);
6460 saved = FAIL;
6461 }
6462 }
6463
6464 if (saved == OK)
6465 {
6466 curbuf->b_flags |= BF_CHECK_RO; /* check for RO again */
6467#ifdef FEAT_AUTOCMD
6468 keep_filetype = TRUE; /* don't detect 'filetype' */
6469#endif
6470 if (readfile(buf->b_ffname, buf->b_fname, (linenr_T)0,
6471 (linenr_T)0,
6472 (linenr_T)MAXLNUM, &ea, READ_NEW) == FAIL)
6473 {
6474#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
6475 if (!aborting())
6476#endif
6477 EMSG2(_("E321: Could not reload \"%s\""), buf->b_fname);
6478 if (savebuf != NULL)
6479 {
6480 /* Put the text back from the save buffer. First
6481 * delete any lines that readfile() added. */
6482 while (!bufempty())
6483 if (ml_delete(curbuf->b_ml.ml_line_count, FALSE)
6484 == FAIL)
6485 break;
6486 (void)move_lines(savebuf, buf);
6487 }
6488 }
6489 else
6490 {
6491 /* Mark the buffer as unmodified and free undo info. */
6492 unchanged(buf, TRUE);
6493 u_blockfree(buf);
6494 u_clearall(buf);
6495 }
6496 }
6497 vim_free(ea.cmd);
6498
6499 if (savebuf != NULL)
6500 wipe_buffer(savebuf, FALSE);
6501
6502#ifdef FEAT_DIFF
6503 /* Invalidate diff info if necessary. */
Bram Moolenaar49d7bf12006-02-17 21:45:41 +00006504 diff_invalidate(buf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006505#endif
6506
6507 /* Restore the topline and cursor position and check it (lines may
6508 * have been removed). */
6509 if (old_topline > curbuf->b_ml.ml_line_count)
6510 curwin->w_topline = curbuf->b_ml.ml_line_count;
6511 else
6512 curwin->w_topline = old_topline;
6513 curwin->w_cursor = old_cursor;
6514 check_cursor();
6515 update_topline();
6516#ifdef FEAT_AUTOCMD
6517 keep_filetype = FALSE;
6518#endif
6519#ifdef FEAT_FOLDING
6520 {
6521 win_T *wp;
6522
6523 /* Update folds unless they are defined manually. */
6524 FOR_ALL_WINDOWS(wp)
6525 if (wp->w_buffer == curwin->w_buffer
6526 && !foldmethodIsManual(wp))
6527 foldUpdateAll(wp);
6528 }
6529#endif
6530 /* If the mode didn't change and 'readonly' was set, keep the old
6531 * value; the user probably used the ":view" command. But don't
6532 * reset it, might have had a read error. */
6533 if (orig_mode == curbuf->b_orig_mode)
6534 curbuf->b_p_ro |= old_ro;
6535 }
6536
6537#ifdef FEAT_AUTOCMD
6538 /* restore curwin/curbuf and a few other things */
6539 aucmd_restbuf(&aco);
6540 /* Careful: autocommands may have made "buf" invalid! */
6541#else
6542 curwin->w_buffer = save_curbuf;
6543 curbuf = save_curbuf;
6544#endif
6545}
6546
Bram Moolenaar071d4272004-06-13 20:20:40 +00006547/*ARGSUSED*/
6548 void
6549buf_store_time(buf, st, fname)
6550 buf_T *buf;
6551 struct stat *st;
6552 char_u *fname;
6553{
6554 buf->b_mtime = (long)st->st_mtime;
6555 buf->b_orig_size = (size_t)st->st_size;
6556#ifdef HAVE_ST_MODE
6557 buf->b_orig_mode = (int)st->st_mode;
6558#else
6559 buf->b_orig_mode = mch_getperm(fname);
6560#endif
6561}
6562
6563/*
6564 * Adjust the line with missing eol, used for the next write.
6565 * Used for do_filter(), when the input lines for the filter are deleted.
6566 */
6567 void
6568write_lnum_adjust(offset)
6569 linenr_T offset;
6570{
Bram Moolenaardf177f62005-02-22 08:39:57 +00006571 if (write_no_eol_lnum != 0) /* only if there is a missing eol */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006572 write_no_eol_lnum += offset;
6573}
6574
6575#if defined(TEMPDIRNAMES) || defined(PROTO)
6576static long temp_count = 0; /* Temp filename counter. */
6577
6578/*
6579 * Delete the temp directory and all files it contains.
6580 */
6581 void
6582vim_deltempdir()
6583{
6584 char_u **files;
6585 int file_count;
6586 int i;
6587
6588 if (vim_tempdir != NULL)
6589 {
6590 sprintf((char *)NameBuff, "%s*", vim_tempdir);
6591 if (gen_expand_wildcards(1, &NameBuff, &file_count, &files,
6592 EW_DIR|EW_FILE|EW_SILENT) == OK)
6593 {
6594 for (i = 0; i < file_count; ++i)
6595 mch_remove(files[i]);
6596 FreeWild(file_count, files);
6597 }
6598 gettail(NameBuff)[-1] = NUL;
6599 (void)mch_rmdir(NameBuff);
6600
6601 vim_free(vim_tempdir);
6602 vim_tempdir = NULL;
6603 }
6604}
6605#endif
6606
6607/*
6608 * vim_tempname(): Return a unique name that can be used for a temp file.
6609 *
6610 * The temp file is NOT created.
6611 *
6612 * The returned pointer is to allocated memory.
6613 * The returned pointer is NULL if no valid name was found.
6614 */
6615/*ARGSUSED*/
6616 char_u *
6617vim_tempname(extra_char)
6618 int extra_char; /* character to use in the name instead of '?' */
6619{
6620#ifdef USE_TMPNAM
6621 char_u itmp[L_tmpnam]; /* use tmpnam() */
6622#else
6623 char_u itmp[TEMPNAMELEN];
6624#endif
6625
6626#ifdef TEMPDIRNAMES
6627 static char *(tempdirs[]) = {TEMPDIRNAMES};
6628 int i;
6629 long nr;
6630 long off;
6631# ifndef EEXIST
6632 struct stat st;
6633# endif
6634
6635 /*
6636 * This will create a directory for private use by this instance of Vim.
6637 * This is done once, and the same directory is used for all temp files.
6638 * This method avoids security problems because of symlink attacks et al.
6639 * It's also a bit faster, because we only need to check for an existing
6640 * file when creating the directory and not for each temp file.
6641 */
6642 if (vim_tempdir == NULL)
6643 {
6644 /*
6645 * Try the entries in TEMPDIRNAMES to create the temp directory.
6646 */
6647 for (i = 0; i < sizeof(tempdirs) / sizeof(char *); ++i)
6648 {
6649 /* expand $TMP, leave room for "/v1100000/999999999" */
6650 expand_env((char_u *)tempdirs[i], itmp, TEMPNAMELEN - 20);
6651 if (mch_isdir(itmp)) /* directory exists */
6652 {
6653# ifdef __EMX__
6654 /* If $TMP contains a forward slash (perhaps using bash or
6655 * tcsh), don't add a backslash, use a forward slash!
6656 * Adding 2 backslashes didn't work. */
6657 if (vim_strchr(itmp, '/') != NULL)
6658 STRCAT(itmp, "/");
6659 else
6660# endif
6661 add_pathsep(itmp);
6662
6663 /* Get an arbitrary number of up to 6 digits. When it's
6664 * unlikely that it already exists it will be faster,
6665 * otherwise it doesn't matter. The use of mkdir() avoids any
6666 * security problems because of the predictable number. */
6667 nr = (mch_get_pid() + (long)time(NULL)) % 1000000L;
6668
6669 /* Try up to 10000 different values until we find a name that
6670 * doesn't exist. */
6671 for (off = 0; off < 10000L; ++off)
6672 {
6673 int r;
6674#if defined(UNIX) || defined(VMS)
6675 mode_t umask_save;
6676#endif
6677
6678 sprintf((char *)itmp + STRLEN(itmp), "v%ld", nr + off);
6679# ifndef EEXIST
6680 /* If mkdir() does not set errno to EEXIST, check for
6681 * existing file here. There is a race condition then,
6682 * although it's fail-safe. */
6683 if (mch_stat((char *)itmp, &st) >= 0)
6684 continue;
6685# endif
6686#if defined(UNIX) || defined(VMS)
6687 /* Make sure the umask doesn't remove the executable bit.
6688 * "repl" has been reported to use "177". */
6689 umask_save = umask(077);
6690#endif
6691 r = vim_mkdir(itmp, 0700);
6692#if defined(UNIX) || defined(VMS)
6693 (void)umask(umask_save);
6694#endif
6695 if (r == 0)
6696 {
6697 char_u *buf;
6698
6699 /* Directory was created, use this name.
6700 * Expand to full path; When using the current
6701 * directory a ":cd" would confuse us. */
6702 buf = alloc((unsigned)MAXPATHL + 1);
6703 if (buf != NULL)
6704 {
6705 if (vim_FullName(itmp, buf, MAXPATHL, FALSE)
6706 == FAIL)
6707 STRCPY(buf, itmp);
6708# ifdef __EMX__
6709 if (vim_strchr(buf, '/') != NULL)
6710 STRCAT(buf, "/");
6711 else
6712# endif
6713 add_pathsep(buf);
6714 vim_tempdir = vim_strsave(buf);
6715 vim_free(buf);
6716 }
6717 break;
6718 }
6719# ifdef EEXIST
6720 /* If the mkdir() didn't fail because the file/dir exists,
6721 * we probably can't create any dir here, try another
6722 * place. */
6723 if (errno != EEXIST)
6724# endif
6725 break;
6726 }
6727 if (vim_tempdir != NULL)
6728 break;
6729 }
6730 }
6731 }
6732
6733 if (vim_tempdir != NULL)
6734 {
6735 /* There is no need to check if the file exists, because we own the
6736 * directory and nobody else creates a file in it. */
6737 sprintf((char *)itmp, "%s%ld", vim_tempdir, temp_count++);
6738 return vim_strsave(itmp);
6739 }
6740
6741 return NULL;
6742
6743#else /* TEMPDIRNAMES */
6744
6745# ifdef WIN3264
6746 char szTempFile[_MAX_PATH + 1];
6747 char buf4[4];
6748 char_u *retval;
6749 char_u *p;
6750
6751 STRCPY(itmp, "");
6752 if (GetTempPath(_MAX_PATH, szTempFile) == 0)
6753 szTempFile[0] = NUL; /* GetTempPath() failed, use current dir */
6754 strcpy(buf4, "VIM");
6755 buf4[2] = extra_char; /* make it "VIa", "VIb", etc. */
6756 if (GetTempFileName(szTempFile, buf4, 0, itmp) == 0)
6757 return NULL;
6758 /* GetTempFileName() will create the file, we don't want that */
6759 (void)DeleteFile(itmp);
6760
6761 /* Backslashes in a temp file name cause problems when filtering with
6762 * "sh". NOTE: This also checks 'shellcmdflag' to help those people who
6763 * didn't set 'shellslash'. */
6764 retval = vim_strsave(itmp);
6765 if (*p_shcf == '-' || p_ssl)
6766 for (p = retval; *p; ++p)
6767 if (*p == '\\')
6768 *p = '/';
6769 return retval;
6770
6771# else /* WIN3264 */
6772
6773# ifdef USE_TMPNAM
6774 /* tmpnam() will make its own name */
6775 if (*tmpnam((char *)itmp) == NUL)
6776 return NULL;
6777# else
6778 char_u *p;
6779
6780# ifdef VMS_TEMPNAM
6781 /* mktemp() is not working on VMS. It seems to be
6782 * a do-nothing function. Therefore we use tempnam().
6783 */
6784 sprintf((char *)itmp, "VIM%c", extra_char);
6785 p = (char_u *)tempnam("tmp:", (char *)itmp);
6786 if (p != NULL)
6787 {
6788 /* VMS will use '.LOG' if we don't explicitly specify an extension,
6789 * and VIM will then be unable to find the file later */
6790 STRCPY(itmp, p);
6791 STRCAT(itmp, ".txt");
6792 free(p);
6793 }
6794 else
6795 return NULL;
6796# else
6797 STRCPY(itmp, TEMPNAME);
6798 if ((p = vim_strchr(itmp, '?')) != NULL)
6799 *p = extra_char;
6800 if (mktemp((char *)itmp) == NULL)
6801 return NULL;
6802# endif
6803# endif
6804
6805 return vim_strsave(itmp);
6806# endif /* WIN3264 */
6807#endif /* TEMPDIRNAMES */
6808}
6809
6810#if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
6811/*
6812 * Convert all backslashes in fname to forward slashes in-place.
6813 */
6814 void
6815forward_slash(fname)
6816 char_u *fname;
6817{
6818 char_u *p;
6819
6820 for (p = fname; *p != NUL; ++p)
6821# ifdef FEAT_MBYTE
6822 /* The Big5 encoding can have '\' in the trail byte. */
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00006823 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006824 ++p;
6825 else
6826# endif
6827 if (*p == '\\')
6828 *p = '/';
6829}
6830#endif
6831
6832
6833/*
6834 * Code for automatic commands.
6835 *
6836 * Only included when "FEAT_AUTOCMD" has been defined.
6837 */
6838
6839#if defined(FEAT_AUTOCMD) || defined(PROTO)
6840
6841/*
6842 * The autocommands are stored in a list for each event.
6843 * Autocommands for the same pattern, that are consecutive, are joined
6844 * together, to avoid having to match the pattern too often.
6845 * The result is an array of Autopat lists, which point to AutoCmd lists:
6846 *
6847 * first_autopat[0] --> Autopat.next --> Autopat.next --> NULL
6848 * Autopat.cmds Autopat.cmds
6849 * | |
6850 * V V
6851 * AutoCmd.next AutoCmd.next
6852 * | |
6853 * V V
6854 * AutoCmd.next NULL
6855 * |
6856 * V
6857 * NULL
6858 *
6859 * first_autopat[1] --> Autopat.next --> NULL
6860 * Autopat.cmds
6861 * |
6862 * V
6863 * AutoCmd.next
6864 * |
6865 * V
6866 * NULL
6867 * etc.
6868 *
6869 * The order of AutoCmds is important, this is the order in which they were
6870 * defined and will have to be executed.
6871 */
6872typedef struct AutoCmd
6873{
6874 char_u *cmd; /* The command to be executed (NULL
6875 when command has been removed) */
6876 char nested; /* If autocommands nest here */
6877 char last; /* last command in list */
6878#ifdef FEAT_EVAL
6879 scid_T scriptID; /* script ID where defined */
6880#endif
6881 struct AutoCmd *next; /* Next AutoCmd in list */
6882} AutoCmd;
6883
6884typedef struct AutoPat
6885{
6886 int group; /* group ID */
6887 char_u *pat; /* pattern as typed (NULL when pattern
6888 has been removed) */
6889 int patlen; /* strlen() of pat */
Bram Moolenaar748bf032005-02-02 23:04:36 +00006890 regprog_T *reg_prog; /* compiled regprog for pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006891 char allow_dirs; /* Pattern may match whole path */
6892 char last; /* last pattern for apply_autocmds() */
6893 AutoCmd *cmds; /* list of commands to do */
6894 struct AutoPat *next; /* next AutoPat in AutoPat list */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00006895 int buflocal_nr; /* !=0 for buffer-local AutoPat */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006896} AutoPat;
6897
6898static struct event_name
6899{
6900 char *name; /* event name */
Bram Moolenaar754b5602006-02-09 23:53:20 +00006901 event_T event; /* event number */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006902} event_names[] =
6903{
6904 {"BufAdd", EVENT_BUFADD},
6905 {"BufCreate", EVENT_BUFADD},
6906 {"BufDelete", EVENT_BUFDELETE},
6907 {"BufEnter", EVENT_BUFENTER},
6908 {"BufFilePost", EVENT_BUFFILEPOST},
6909 {"BufFilePre", EVENT_BUFFILEPRE},
6910 {"BufHidden", EVENT_BUFHIDDEN},
6911 {"BufLeave", EVENT_BUFLEAVE},
6912 {"BufNew", EVENT_BUFNEW},
6913 {"BufNewFile", EVENT_BUFNEWFILE},
6914 {"BufRead", EVENT_BUFREADPOST},
6915 {"BufReadCmd", EVENT_BUFREADCMD},
6916 {"BufReadPost", EVENT_BUFREADPOST},
6917 {"BufReadPre", EVENT_BUFREADPRE},
6918 {"BufUnload", EVENT_BUFUNLOAD},
6919 {"BufWinEnter", EVENT_BUFWINENTER},
6920 {"BufWinLeave", EVENT_BUFWINLEAVE},
6921 {"BufWipeout", EVENT_BUFWIPEOUT},
6922 {"BufWrite", EVENT_BUFWRITEPRE},
6923 {"BufWritePost", EVENT_BUFWRITEPOST},
6924 {"BufWritePre", EVENT_BUFWRITEPRE},
6925 {"BufWriteCmd", EVENT_BUFWRITECMD},
6926 {"CmdwinEnter", EVENT_CMDWINENTER},
6927 {"CmdwinLeave", EVENT_CMDWINLEAVE},
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00006928 {"ColorScheme", EVENT_COLORSCHEME},
Bram Moolenaar754b5602006-02-09 23:53:20 +00006929 {"CursorHold", EVENT_CURSORHOLD},
6930 {"CursorHoldI", EVENT_CURSORHOLDI},
6931 {"CursorMoved", EVENT_CURSORMOVED},
6932 {"CursorMovedI", EVENT_CURSORMOVEDI},
Bram Moolenaar071d4272004-06-13 20:20:40 +00006933 {"EncodingChanged", EVENT_ENCODINGCHANGED},
6934 {"FileEncoding", EVENT_ENCODINGCHANGED},
Bram Moolenaar071d4272004-06-13 20:20:40 +00006935 {"FileAppendPost", EVENT_FILEAPPENDPOST},
6936 {"FileAppendPre", EVENT_FILEAPPENDPRE},
6937 {"FileAppendCmd", EVENT_FILEAPPENDCMD},
6938 {"FileChangedShell",EVENT_FILECHANGEDSHELL},
6939 {"FileChangedRO", EVENT_FILECHANGEDRO},
6940 {"FileReadPost", EVENT_FILEREADPOST},
6941 {"FileReadPre", EVENT_FILEREADPRE},
6942 {"FileReadCmd", EVENT_FILEREADCMD},
6943 {"FileType", EVENT_FILETYPE},
6944 {"FileWritePost", EVENT_FILEWRITEPOST},
6945 {"FileWritePre", EVENT_FILEWRITEPRE},
6946 {"FileWriteCmd", EVENT_FILEWRITECMD},
6947 {"FilterReadPost", EVENT_FILTERREADPOST},
6948 {"FilterReadPre", EVENT_FILTERREADPRE},
6949 {"FilterWritePost", EVENT_FILTERWRITEPOST},
6950 {"FilterWritePre", EVENT_FILTERWRITEPRE},
6951 {"FocusGained", EVENT_FOCUSGAINED},
6952 {"FocusLost", EVENT_FOCUSLOST},
6953 {"FuncUndefined", EVENT_FUNCUNDEFINED},
6954 {"GUIEnter", EVENT_GUIENTER},
Bram Moolenaar843ee412004-06-30 16:16:41 +00006955 {"InsertChange", EVENT_INSERTCHANGE},
6956 {"InsertEnter", EVENT_INSERTENTER},
6957 {"InsertLeave", EVENT_INSERTLEAVE},
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00006958 {"MenuPopup", EVENT_MENUPOPUP},
Bram Moolenaar7c626922005-02-07 22:01:03 +00006959 {"QuickFixCmdPost", EVENT_QUICKFIXCMDPOST},
6960 {"QuickFixCmdPre", EVENT_QUICKFIXCMDPRE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00006961 {"RemoteReply", EVENT_REMOTEREPLY},
Bram Moolenaar9372a112005-12-06 19:59:18 +00006962 {"SessionLoadPost", EVENT_SESSIONLOADPOST},
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00006963 {"SpellFileMissing",EVENT_SPELLFILEMISSING},
Bram Moolenaar071d4272004-06-13 20:20:40 +00006964 {"StdinReadPost", EVENT_STDINREADPOST},
6965 {"StdinReadPre", EVENT_STDINREADPRE},
Bram Moolenaarb815dac2005-12-07 20:59:24 +00006966 {"SwapExists", EVENT_SWAPEXISTS},
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00006967 {"Syntax", EVENT_SYNTAX},
Bram Moolenaar70836c82006-02-20 21:28:49 +00006968 {"TabEnter", EVENT_TABENTER},
6969 {"TabLeave", EVENT_TABLEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00006970 {"TermChanged", EVENT_TERMCHANGED},
6971 {"TermResponse", EVENT_TERMRESPONSE},
6972 {"User", EVENT_USER},
6973 {"VimEnter", EVENT_VIMENTER},
6974 {"VimLeave", EVENT_VIMLEAVE},
6975 {"VimLeavePre", EVENT_VIMLEAVEPRE},
6976 {"WinEnter", EVENT_WINENTER},
6977 {"WinLeave", EVENT_WINLEAVE},
Bram Moolenaar754b5602006-02-09 23:53:20 +00006978 {NULL, (event_T)0}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006979};
6980
6981static AutoPat *first_autopat[NUM_EVENTS] =
6982{
6983 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
6984 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
6985 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
6986 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00006987 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
6988 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00006989};
6990
6991/*
6992 * struct used to keep status while executing autocommands for an event.
6993 */
6994typedef struct AutoPatCmd
6995{
6996 AutoPat *curpat; /* next AutoPat to examine */
6997 AutoCmd *nextcmd; /* next AutoCmd to execute */
6998 int group; /* group being used */
6999 char_u *fname; /* fname to match with */
7000 char_u *sfname; /* sfname to match with */
7001 char_u *tail; /* tail of fname */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007002 event_T event; /* current event */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007003 int arg_bufnr; /* initially equal to <abuf>, set to zero when
7004 buf is deleted */
7005 struct AutoPatCmd *next; /* chain of active apc-s for auto-invalidation*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00007006} AutoPatCmd;
7007
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007008static AutoPatCmd *active_apc_list = NULL; /* stack of active autocommands */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007009
Bram Moolenaar071d4272004-06-13 20:20:40 +00007010/*
7011 * augroups stores a list of autocmd group names.
7012 */
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007013static garray_T augroups = {0, 0, sizeof(char_u *), 10, NULL};
Bram Moolenaar071d4272004-06-13 20:20:40 +00007014#define AUGROUP_NAME(i) (((char_u **)augroups.ga_data)[i])
7015
7016/*
7017 * The ID of the current group. Group 0 is the default one.
7018 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007019static int current_augroup = AUGROUP_DEFAULT;
7020
7021static int au_need_clean = FALSE; /* need to delete marked patterns */
7022
Bram Moolenaar754b5602006-02-09 23:53:20 +00007023static void show_autocmd __ARGS((AutoPat *ap, event_T event));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007024static void au_remove_pat __ARGS((AutoPat *ap));
7025static void au_remove_cmds __ARGS((AutoPat *ap));
7026static void au_cleanup __ARGS((void));
7027static int au_new_group __ARGS((char_u *name));
7028static void au_del_group __ARGS((char_u *name));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007029static event_T event_name2nr __ARGS((char_u *start, char_u **end));
7030static char_u *event_nr2name __ARGS((event_T event));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007031static char_u *find_end_event __ARGS((char_u *arg, int have_group));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007032static int event_ignored __ARGS((event_T event));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007033static int au_get_grouparg __ARGS((char_u **argp));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007034static 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 +00007035static char_u *getnextac __ARGS((int c, void *cookie, int indent));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007036static 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 +00007037static void auto_next_pat __ARGS((AutoPatCmd *apc, int stop_at_last));
7038
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007039
Bram Moolenaar754b5602006-02-09 23:53:20 +00007040static event_T last_event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007041static int last_group;
7042
7043/*
7044 * Show the autocommands for one AutoPat.
7045 */
7046 static void
7047show_autocmd(ap, event)
7048 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007049 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007050{
7051 AutoCmd *ac;
7052
7053 /* Check for "got_int" (here and at various places below), which is set
7054 * when "q" has been hit for the "--more--" prompt */
7055 if (got_int)
7056 return;
7057 if (ap->pat == NULL) /* pattern has been removed */
7058 return;
7059
7060 msg_putchar('\n');
7061 if (got_int)
7062 return;
7063 if (event != last_event || ap->group != last_group)
7064 {
7065 if (ap->group != AUGROUP_DEFAULT)
7066 {
7067 if (AUGROUP_NAME(ap->group) == NULL)
7068 msg_puts_attr((char_u *)_("--Deleted--"), hl_attr(HLF_E));
7069 else
7070 msg_puts_attr(AUGROUP_NAME(ap->group), hl_attr(HLF_T));
7071 msg_puts((char_u *)" ");
7072 }
7073 msg_puts_attr(event_nr2name(event), hl_attr(HLF_T));
7074 last_event = event;
7075 last_group = ap->group;
7076 msg_putchar('\n');
7077 if (got_int)
7078 return;
7079 }
7080 msg_col = 4;
7081 msg_outtrans(ap->pat);
7082
7083 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7084 {
7085 if (ac->cmd != NULL) /* skip removed commands */
7086 {
7087 if (msg_col >= 14)
7088 msg_putchar('\n');
7089 msg_col = 14;
7090 if (got_int)
7091 return;
7092 msg_outtrans(ac->cmd);
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00007093#ifdef FEAT_EVAL
7094 if (p_verbose > 0)
7095 last_set_msg(ac->scriptID);
7096#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007097 if (got_int)
7098 return;
7099 if (ac->next != NULL)
7100 {
7101 msg_putchar('\n');
7102 if (got_int)
7103 return;
7104 }
7105 }
7106 }
7107}
7108
7109/*
7110 * Mark an autocommand pattern for deletion.
7111 */
7112 static void
7113au_remove_pat(ap)
7114 AutoPat *ap;
7115{
7116 vim_free(ap->pat);
7117 ap->pat = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007118 ap->buflocal_nr = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007119 au_need_clean = TRUE;
7120}
7121
7122/*
7123 * Mark all commands for a pattern for deletion.
7124 */
7125 static void
7126au_remove_cmds(ap)
7127 AutoPat *ap;
7128{
7129 AutoCmd *ac;
7130
7131 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7132 {
7133 vim_free(ac->cmd);
7134 ac->cmd = NULL;
7135 }
7136 au_need_clean = TRUE;
7137}
7138
7139/*
7140 * Cleanup autocommands and patterns that have been deleted.
7141 * This is only done when not executing autocommands.
7142 */
7143 static void
7144au_cleanup()
7145{
7146 AutoPat *ap, **prev_ap;
7147 AutoCmd *ac, **prev_ac;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007148 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007149
7150 if (autocmd_busy || !au_need_clean)
7151 return;
7152
7153 /* loop over all events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007154 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7155 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007156 {
7157 /* loop over all autocommand patterns */
7158 prev_ap = &(first_autopat[(int)event]);
7159 for (ap = *prev_ap; ap != NULL; ap = *prev_ap)
7160 {
7161 /* loop over all commands for this pattern */
7162 prev_ac = &(ap->cmds);
7163 for (ac = *prev_ac; ac != NULL; ac = *prev_ac)
7164 {
7165 /* remove the command if the pattern is to be deleted or when
7166 * the command has been marked for deletion */
7167 if (ap->pat == NULL || ac->cmd == NULL)
7168 {
7169 *prev_ac = ac->next;
7170 vim_free(ac->cmd);
7171 vim_free(ac);
7172 }
7173 else
7174 prev_ac = &(ac->next);
7175 }
7176
7177 /* remove the pattern if it has been marked for deletion */
7178 if (ap->pat == NULL)
7179 {
7180 *prev_ap = ap->next;
Bram Moolenaar748bf032005-02-02 23:04:36 +00007181 vim_free(ap->reg_prog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007182 vim_free(ap);
7183 }
7184 else
7185 prev_ap = &(ap->next);
7186 }
7187 }
7188
7189 au_need_clean = FALSE;
7190}
7191
7192/*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007193 * Called when buffer is freed, to remove/invalidate related buffer-local
7194 * autocmds.
7195 */
7196 void
7197aubuflocal_remove(buf)
7198 buf_T *buf;
7199{
7200 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007201 event_T event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007202 AutoPatCmd *apc;
7203
7204 /* invalidate currently executing autocommands */
7205 for (apc = active_apc_list; apc; apc = apc->next)
7206 if (buf->b_fnum == apc->arg_bufnr)
7207 apc->arg_bufnr = 0;
7208
7209 /* invalidate buflocals looping through events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007210 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7211 event = (event_T)((int)event + 1))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007212 /* loop over all autocommand patterns */
7213 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
7214 if (ap->buflocal_nr == buf->b_fnum)
7215 {
7216 au_remove_pat(ap);
7217 if (p_verbose >= 6)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007218 {
7219 verbose_enter();
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007220 smsg((char_u *)
7221 _("auto-removing autocommand: %s <buffer=%d>"),
7222 event_nr2name(event), buf->b_fnum);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007223 verbose_leave();
7224 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007225 }
7226 au_cleanup();
7227}
7228
7229/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007230 * Add an autocmd group name.
7231 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
7232 */
7233 static int
7234au_new_group(name)
7235 char_u *name;
7236{
7237 int i;
7238
7239 i = au_find_group(name);
7240 if (i == AUGROUP_ERROR) /* the group doesn't exist yet, add it */
7241 {
7242 /* First try using a free entry. */
7243 for (i = 0; i < augroups.ga_len; ++i)
7244 if (AUGROUP_NAME(i) == NULL)
7245 break;
7246 if (i == augroups.ga_len && ga_grow(&augroups, 1) == FAIL)
7247 return AUGROUP_ERROR;
7248
7249 AUGROUP_NAME(i) = vim_strsave(name);
7250 if (AUGROUP_NAME(i) == NULL)
7251 return AUGROUP_ERROR;
7252 if (i == augroups.ga_len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007253 ++augroups.ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007254 }
7255
7256 return i;
7257}
7258
7259 static void
7260au_del_group(name)
7261 char_u *name;
7262{
7263 int i;
7264
7265 i = au_find_group(name);
7266 if (i == AUGROUP_ERROR) /* the group doesn't exist */
7267 EMSG2(_("E367: No such group: \"%s\""), name);
7268 else
7269 {
7270 vim_free(AUGROUP_NAME(i));
7271 AUGROUP_NAME(i) = NULL;
7272 }
7273}
7274
7275/*
7276 * Find the ID of an autocmd group name.
7277 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
7278 */
7279 static int
7280au_find_group(name)
7281 char_u *name;
7282{
7283 int i;
7284
7285 for (i = 0; i < augroups.ga_len; ++i)
7286 if (AUGROUP_NAME(i) != NULL && STRCMP(AUGROUP_NAME(i), name) == 0)
7287 return i;
7288 return AUGROUP_ERROR;
7289}
7290
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00007291#if defined(FEAT_BROWSE) || defined(PROTO)
7292/*
7293 * Return TRUE if augroup "name" exists.
7294 */
7295 int
7296au_has_group(name)
7297 char_u *name;
7298{
7299 return au_find_group(name) != AUGROUP_ERROR;
7300}
7301#endif
7302
Bram Moolenaar071d4272004-06-13 20:20:40 +00007303/*
7304 * ":augroup {name}".
7305 */
7306 void
7307do_augroup(arg, del_group)
7308 char_u *arg;
7309 int del_group;
7310{
7311 int i;
7312
7313 if (del_group)
7314 {
7315 if (*arg == NUL)
7316 EMSG(_(e_argreq));
7317 else
7318 au_del_group(arg);
7319 }
7320 else if (STRICMP(arg, "end") == 0) /* ":aug end": back to group 0 */
7321 current_augroup = AUGROUP_DEFAULT;
7322 else if (*arg) /* ":aug xxx": switch to group xxx */
7323 {
7324 i = au_new_group(arg);
7325 if (i != AUGROUP_ERROR)
7326 current_augroup = i;
7327 }
7328 else /* ":aug": list the group names */
7329 {
7330 msg_start();
7331 for (i = 0; i < augroups.ga_len; ++i)
7332 {
7333 if (AUGROUP_NAME(i) != NULL)
7334 {
7335 msg_puts(AUGROUP_NAME(i));
7336 msg_puts((char_u *)" ");
7337 }
7338 }
7339 msg_clr_eos();
7340 msg_end();
7341 }
7342}
7343
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00007344#if defined(EXITFREE) || defined(PROTO)
7345 void
7346free_all_autocmds()
7347{
7348 for (current_augroup = -1; current_augroup < augroups.ga_len;
7349 ++current_augroup)
7350 do_autocmd((char_u *)"", TRUE);
7351 ga_clear_strings(&augroups);
7352}
7353#endif
7354
Bram Moolenaar071d4272004-06-13 20:20:40 +00007355/*
7356 * Return the event number for event name "start".
7357 * Return NUM_EVENTS if the event name was not found.
7358 * Return a pointer to the next event name in "end".
7359 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007360 static event_T
Bram Moolenaar071d4272004-06-13 20:20:40 +00007361event_name2nr(start, end)
7362 char_u *start;
7363 char_u **end;
7364{
7365 char_u *p;
7366 int i;
7367 int len;
7368
7369 /* the event name ends with end of line, a blank or a comma */
7370 for (p = start; *p && !vim_iswhite(*p) && *p != ','; ++p)
7371 ;
7372 for (i = 0; event_names[i].name != NULL; ++i)
7373 {
7374 len = (int)STRLEN(event_names[i].name);
7375 if (len == p - start && STRNICMP(event_names[i].name, start, len) == 0)
7376 break;
7377 }
7378 if (*p == ',')
7379 ++p;
7380 *end = p;
7381 if (event_names[i].name == NULL)
7382 return NUM_EVENTS;
7383 return event_names[i].event;
7384}
7385
7386/*
7387 * Return the name for event "event".
7388 */
7389 static char_u *
7390event_nr2name(event)
Bram Moolenaar754b5602006-02-09 23:53:20 +00007391 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007392{
7393 int i;
7394
7395 for (i = 0; event_names[i].name != NULL; ++i)
7396 if (event_names[i].event == event)
7397 return (char_u *)event_names[i].name;
7398 return (char_u *)"Unknown";
7399}
7400
7401/*
7402 * Scan over the events. "*" stands for all events.
7403 */
7404 static char_u *
7405find_end_event(arg, have_group)
7406 char_u *arg;
7407 int have_group; /* TRUE when group name was found */
7408{
7409 char_u *pat;
7410 char_u *p;
7411
7412 if (*arg == '*')
7413 {
7414 if (arg[1] && !vim_iswhite(arg[1]))
7415 {
7416 EMSG2(_("E215: Illegal character after *: %s"), arg);
7417 return NULL;
7418 }
7419 pat = arg + 1;
7420 }
7421 else
7422 {
7423 for (pat = arg; *pat && !vim_iswhite(*pat); pat = p)
7424 {
7425 if ((int)event_name2nr(pat, &p) >= (int)NUM_EVENTS)
7426 {
7427 if (have_group)
7428 EMSG2(_("E216: No such event: %s"), pat);
7429 else
7430 EMSG2(_("E216: No such group or event: %s"), pat);
7431 return NULL;
7432 }
7433 }
7434 }
7435 return pat;
7436}
7437
7438/*
7439 * Return TRUE if "event" is included in 'eventignore'.
7440 */
7441 static int
7442event_ignored(event)
Bram Moolenaar754b5602006-02-09 23:53:20 +00007443 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007444{
7445 char_u *p = p_ei;
7446
7447 if (STRICMP(p_ei, "all") == 0)
7448 return TRUE;
7449
7450 while (*p)
7451 if (event_name2nr(p, &p) == event)
7452 return TRUE;
7453
7454 return FALSE;
7455}
7456
7457/*
7458 * Return OK when the contents of p_ei is valid, FAIL otherwise.
7459 */
7460 int
7461check_ei()
7462{
7463 char_u *p = p_ei;
7464
7465 if (STRICMP(p_ei, "all") == 0)
7466 return OK;
7467
7468 while (*p)
7469 if (event_name2nr(p, &p) == NUM_EVENTS)
7470 return FAIL;
7471
7472 return OK;
7473}
7474
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00007475# if defined(FEAT_SYN_HL) || defined(PROTO)
7476
7477/*
7478 * Add "what" to 'eventignore' to skip loading syntax highlighting for every
7479 * buffer loaded into the window. "what" must start with a comma.
7480 * Returns the old value of 'eventignore' in allocated memory.
7481 */
7482 char_u *
7483au_event_disable(what)
7484 char *what;
7485{
7486 char_u *new_ei;
7487 char_u *save_ei;
7488
7489 save_ei = vim_strsave(p_ei);
7490 if (save_ei != NULL)
7491 {
Bram Moolenaara5792f52005-11-23 21:25:05 +00007492 new_ei = vim_strnsave(p_ei, (int)(STRLEN(p_ei) + STRLEN(what)));
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00007493 if (new_ei != NULL)
7494 {
7495 STRCAT(new_ei, what);
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00007496 set_string_option_direct((char_u *)"ei", -1, new_ei,
7497 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00007498 vim_free(new_ei);
7499 }
7500 }
7501 return save_ei;
7502}
7503
7504 void
7505au_event_restore(old_ei)
7506 char_u *old_ei;
7507{
7508 if (old_ei != NULL)
7509 {
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00007510 set_string_option_direct((char_u *)"ei", -1, old_ei,
7511 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00007512 vim_free(old_ei);
7513 }
7514}
7515# endif /* FEAT_SYN_HL */
7516
Bram Moolenaar071d4272004-06-13 20:20:40 +00007517/*
7518 * do_autocmd() -- implements the :autocmd command. Can be used in the
7519 * following ways:
7520 *
7521 * :autocmd <event> <pat> <cmd> Add <cmd> to the list of commands that
7522 * will be automatically executed for <event>
7523 * when editing a file matching <pat>, in
7524 * the current group.
7525 * :autocmd <event> <pat> Show the auto-commands associated with
7526 * <event> and <pat>.
7527 * :autocmd <event> Show the auto-commands associated with
7528 * <event>.
7529 * :autocmd Show all auto-commands.
7530 * :autocmd! <event> <pat> <cmd> Remove all auto-commands associated with
7531 * <event> and <pat>, and add the command
7532 * <cmd>, for the current group.
7533 * :autocmd! <event> <pat> Remove all auto-commands associated with
7534 * <event> and <pat> for the current group.
7535 * :autocmd! <event> Remove all auto-commands associated with
7536 * <event> for the current group.
7537 * :autocmd! Remove ALL auto-commands for the current
7538 * group.
7539 *
7540 * Multiple events and patterns may be given separated by commas. Here are
7541 * some examples:
7542 * :autocmd bufread,bufenter *.c,*.h set tw=0 smartindent noic
7543 * :autocmd bufleave * set tw=79 nosmartindent ic infercase
7544 *
7545 * :autocmd * *.c show all autocommands for *.c files.
Bram Moolenaard35f9712005-12-18 22:02:33 +00007546 *
7547 * Mostly a {group} argument can optionally appear before <event>.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007548 */
7549 void
7550do_autocmd(arg, forceit)
7551 char_u *arg;
7552 int forceit;
7553{
7554 char_u *pat;
7555 char_u *envpat = NULL;
7556 char_u *cmd;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007557 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007558 int need_free = FALSE;
7559 int nested = FALSE;
7560 int group;
7561
7562 /*
7563 * Check for a legal group name. If not, use AUGROUP_ALL.
7564 */
7565 group = au_get_grouparg(&arg);
7566 if (arg == NULL) /* out of memory */
7567 return;
7568
7569 /*
7570 * Scan over the events.
7571 * If we find an illegal name, return here, don't do anything.
7572 */
7573 pat = find_end_event(arg, group != AUGROUP_ALL);
7574 if (pat == NULL)
7575 return;
7576
7577 /*
7578 * Scan over the pattern. Put a NUL at the end.
7579 */
7580 pat = skipwhite(pat);
7581 cmd = pat;
7582 while (*cmd && (!vim_iswhite(*cmd) || cmd[-1] == '\\'))
7583 cmd++;
7584 if (*cmd)
7585 *cmd++ = NUL;
7586
7587 /* Expand environment variables in the pattern. Set 'shellslash', we want
7588 * forward slashes here. */
7589 if (vim_strchr(pat, '$') != NULL || vim_strchr(pat, '~') != NULL)
7590 {
7591#ifdef BACKSLASH_IN_FILENAME
7592 int p_ssl_save = p_ssl;
7593
7594 p_ssl = TRUE;
7595#endif
7596 envpat = expand_env_save(pat);
7597#ifdef BACKSLASH_IN_FILENAME
7598 p_ssl = p_ssl_save;
7599#endif
7600 if (envpat != NULL)
7601 pat = envpat;
7602 }
7603
7604 /*
7605 * Check for "nested" flag.
7606 */
7607 cmd = skipwhite(cmd);
7608 if (*cmd != NUL && STRNCMP(cmd, "nested", 6) == 0 && vim_iswhite(cmd[6]))
7609 {
7610 nested = TRUE;
7611 cmd = skipwhite(cmd + 6);
7612 }
7613
7614 /*
7615 * Find the start of the commands.
7616 * Expand <sfile> in it.
7617 */
7618 if (*cmd != NUL)
7619 {
7620 cmd = expand_sfile(cmd);
7621 if (cmd == NULL) /* some error */
7622 return;
7623 need_free = TRUE;
7624 }
7625
7626 /*
7627 * Print header when showing autocommands.
7628 */
7629 if (!forceit && *cmd == NUL)
7630 {
7631 /* Highlight title */
7632 MSG_PUTS_TITLE(_("\n--- Auto-Commands ---"));
7633 }
7634
7635 /*
7636 * Loop over the events.
7637 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007638 last_event = (event_T)-1; /* for listing the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007639 last_group = AUGROUP_ERROR; /* for listing the group name */
7640 if (*arg == '*' || *arg == NUL)
7641 {
Bram Moolenaar754b5602006-02-09 23:53:20 +00007642 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7643 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007644 if (do_autocmd_event(event, pat,
7645 nested, cmd, forceit, group) == FAIL)
7646 break;
7647 }
7648 else
7649 {
7650 while (*arg && !vim_iswhite(*arg))
7651 if (do_autocmd_event(event_name2nr(arg, &arg), pat,
7652 nested, cmd, forceit, group) == FAIL)
7653 break;
7654 }
7655
7656 if (need_free)
7657 vim_free(cmd);
7658 vim_free(envpat);
7659}
7660
7661/*
7662 * Find the group ID in a ":autocmd" or ":doautocmd" argument.
7663 * The "argp" argument is advanced to the following argument.
7664 *
7665 * Returns the group ID, AUGROUP_ERROR for error (out of memory).
7666 */
7667 static int
7668au_get_grouparg(argp)
7669 char_u **argp;
7670{
7671 char_u *group_name;
7672 char_u *p;
7673 char_u *arg = *argp;
7674 int group = AUGROUP_ALL;
7675
7676 p = skiptowhite(arg);
7677 if (p > arg)
7678 {
7679 group_name = vim_strnsave(arg, (int)(p - arg));
7680 if (group_name == NULL) /* out of memory */
7681 return AUGROUP_ERROR;
7682 group = au_find_group(group_name);
7683 if (group == AUGROUP_ERROR)
7684 group = AUGROUP_ALL; /* no match, use all groups */
7685 else
7686 *argp = skipwhite(p); /* match, skip over group name */
7687 vim_free(group_name);
7688 }
7689 return group;
7690}
7691
7692/*
7693 * do_autocmd() for one event.
7694 * If *pat == NUL do for all patterns.
7695 * If *cmd == NUL show entries.
7696 * If forceit == TRUE delete entries.
7697 * If group is not AUGROUP_ALL, only use this group.
7698 */
7699 static int
7700do_autocmd_event(event, pat, nested, cmd, forceit, group)
Bram Moolenaar754b5602006-02-09 23:53:20 +00007701 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007702 char_u *pat;
7703 int nested;
7704 char_u *cmd;
7705 int forceit;
7706 int group;
7707{
7708 AutoPat *ap;
7709 AutoPat **prev_ap;
7710 AutoCmd *ac;
7711 AutoCmd **prev_ac;
7712 int brace_level;
7713 char_u *endpat;
7714 int findgroup;
7715 int allgroups;
7716 int patlen;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007717 int is_buflocal;
7718 int buflocal_nr;
7719 char_u buflocal_pat[25]; /* for "<buffer=X>" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007720
7721 if (group == AUGROUP_ALL)
7722 findgroup = current_augroup;
7723 else
7724 findgroup = group;
7725 allgroups = (group == AUGROUP_ALL && !forceit && *cmd == NUL);
7726
7727 /*
7728 * Show or delete all patterns for an event.
7729 */
7730 if (*pat == NUL)
7731 {
7732 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
7733 {
7734 if (forceit) /* delete the AutoPat, if it's in the current group */
7735 {
7736 if (ap->group == findgroup)
7737 au_remove_pat(ap);
7738 }
7739 else if (group == AUGROUP_ALL || ap->group == group)
7740 show_autocmd(ap, event);
7741 }
7742 }
7743
7744 /*
7745 * Loop through all the specified patterns.
7746 */
7747 for ( ; *pat; pat = (*endpat == ',' ? endpat + 1 : endpat))
7748 {
7749 /*
7750 * Find end of the pattern.
7751 * Watch out for a comma in braces, like "*.\{obj,o\}".
7752 */
7753 brace_level = 0;
7754 for (endpat = pat; *endpat && (*endpat != ',' || brace_level
7755 || endpat[-1] == '\\'); ++endpat)
7756 {
7757 if (*endpat == '{')
7758 brace_level++;
7759 else if (*endpat == '}')
7760 brace_level--;
7761 }
7762 if (pat == endpat) /* ignore single comma */
7763 continue;
7764 patlen = (int)(endpat - pat);
7765
7766 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007767 * detect special <buflocal[=X]> buffer-local patterns
7768 */
7769 is_buflocal = FALSE;
7770 buflocal_nr = 0;
7771
7772 if (patlen >= 7 && STRNCMP(pat, "<buffer", 7) == 0
7773 && pat[patlen - 1] == '>')
7774 {
7775 /* Error will be printed only for addition. printing and removing
7776 * will proceed silently. */
7777 is_buflocal = TRUE;
7778 if (patlen == 8)
7779 buflocal_nr = curbuf->b_fnum;
7780 else if (patlen > 9 && pat[7] == '=')
7781 {
7782 /* <buffer=abuf> */
7783 if (patlen == 13 && STRNICMP(pat, "<buffer=abuf>", 13))
7784 buflocal_nr = autocmd_bufnr;
7785 /* <buffer=123> */
7786 else if (skipdigits(pat + 8) == pat + patlen - 1)
7787 buflocal_nr = atoi((char *)pat + 8);
7788 }
7789 }
7790
7791 if (is_buflocal)
7792 {
7793 /* normalize pat into standard "<buffer>#N" form */
7794 sprintf((char *)buflocal_pat, "<buffer=%d>", buflocal_nr);
7795 pat = buflocal_pat; /* can modify pat and patlen */
7796 patlen = STRLEN(buflocal_pat); /* but not endpat */
7797 }
7798
7799 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007800 * Find AutoPat entries with this pattern.
7801 */
7802 prev_ap = &first_autopat[(int)event];
7803 while ((ap = *prev_ap) != NULL)
7804 {
7805 if (ap->pat != NULL)
7806 {
7807 /* Accept a pattern when:
7808 * - a group was specified and it's that group, or a group was
7809 * not specified and it's the current group, or a group was
7810 * not specified and we are listing
7811 * - the length of the pattern matches
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007812 * - the pattern matches.
7813 * For <buffer[=X]>, this condition works because we normalize
7814 * all buffer-local patterns.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007815 */
7816 if ((allgroups || ap->group == findgroup)
7817 && ap->patlen == patlen
7818 && STRNCMP(pat, ap->pat, patlen) == 0)
7819 {
7820 /*
7821 * Remove existing autocommands.
7822 * If adding any new autocmd's for this AutoPat, don't
7823 * delete the pattern from the autopat list, append to
7824 * this list.
7825 */
7826 if (forceit)
7827 {
7828 if (*cmd != NUL && ap->next == NULL)
7829 {
7830 au_remove_cmds(ap);
7831 break;
7832 }
7833 au_remove_pat(ap);
7834 }
7835
7836 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007837 * Show autocmd's for this autopat, or buflocals <buffer=X>
Bram Moolenaar071d4272004-06-13 20:20:40 +00007838 */
7839 else if (*cmd == NUL)
7840 show_autocmd(ap, event);
7841
7842 /*
7843 * Add autocmd to this autopat, if it's the last one.
7844 */
7845 else if (ap->next == NULL)
7846 break;
7847 }
7848 }
7849 prev_ap = &ap->next;
7850 }
7851
7852 /*
7853 * Add a new command.
7854 */
7855 if (*cmd != NUL)
7856 {
7857 /*
7858 * If the pattern we want to add a command to does appear at the
7859 * end of the list (or not is not in the list at all), add the
7860 * pattern at the end of the list.
7861 */
7862 if (ap == NULL)
7863 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007864 /* refuse to add buffer-local ap if buffer number is invalid */
7865 if (is_buflocal && (buflocal_nr == 0
7866 || buflist_findnr(buflocal_nr) == NULL))
7867 {
7868 EMSGN(_("E680: <buffer=%d>: invalid buffer number "),
7869 buflocal_nr);
7870 return FAIL;
7871 }
7872
Bram Moolenaar071d4272004-06-13 20:20:40 +00007873 ap = (AutoPat *)alloc((unsigned)sizeof(AutoPat));
7874 if (ap == NULL)
7875 return FAIL;
7876 ap->pat = vim_strnsave(pat, patlen);
7877 ap->patlen = patlen;
7878 if (ap->pat == NULL)
7879 {
7880 vim_free(ap);
7881 return FAIL;
7882 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007883
7884 if (is_buflocal)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007885 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007886 ap->buflocal_nr = buflocal_nr;
Bram Moolenaar748bf032005-02-02 23:04:36 +00007887 ap->reg_prog = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007888 }
7889 else
7890 {
Bram Moolenaar748bf032005-02-02 23:04:36 +00007891 char_u *reg_pat;
7892
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007893 ap->buflocal_nr = 0;
Bram Moolenaar748bf032005-02-02 23:04:36 +00007894 reg_pat = file_pat_to_reg_pat(pat, endpat,
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007895 &ap->allow_dirs, TRUE);
Bram Moolenaar748bf032005-02-02 23:04:36 +00007896 if (reg_pat != NULL)
7897 ap->reg_prog = vim_regcomp(reg_pat, RE_MAGIC);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00007898 vim_free(reg_pat);
Bram Moolenaar748bf032005-02-02 23:04:36 +00007899 if (reg_pat == NULL || ap->reg_prog == NULL)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007900 {
7901 vim_free(ap->pat);
7902 vim_free(ap);
7903 return FAIL;
7904 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007905 }
7906 ap->cmds = NULL;
7907 *prev_ap = ap;
7908 ap->next = NULL;
7909 if (group == AUGROUP_ALL)
7910 ap->group = current_augroup;
7911 else
7912 ap->group = group;
7913 }
7914
7915 /*
7916 * Add the autocmd at the end of the AutoCmd list.
7917 */
7918 prev_ac = &(ap->cmds);
7919 while ((ac = *prev_ac) != NULL)
7920 prev_ac = &ac->next;
7921 ac = (AutoCmd *)alloc((unsigned)sizeof(AutoCmd));
7922 if (ac == NULL)
7923 return FAIL;
7924 ac->cmd = vim_strsave(cmd);
7925#ifdef FEAT_EVAL
7926 ac->scriptID = current_SID;
7927#endif
7928 if (ac->cmd == NULL)
7929 {
7930 vim_free(ac);
7931 return FAIL;
7932 }
7933 ac->next = NULL;
7934 *prev_ac = ac;
7935 ac->nested = nested;
7936 }
7937 }
7938
7939 au_cleanup(); /* may really delete removed patterns/commands now */
7940 return OK;
7941}
7942
7943/*
7944 * Implementation of ":doautocmd [group] event [fname]".
7945 * Return OK for success, FAIL for failure;
7946 */
7947 int
7948do_doautocmd(arg, do_msg)
7949 char_u *arg;
7950 int do_msg; /* give message for no matching autocmds? */
7951{
7952 char_u *fname;
7953 int nothing_done = TRUE;
7954 int group;
7955
7956 /*
7957 * Check for a legal group name. If not, use AUGROUP_ALL.
7958 */
7959 group = au_get_grouparg(&arg);
7960 if (arg == NULL) /* out of memory */
7961 return FAIL;
7962
7963 if (*arg == '*')
7964 {
7965 EMSG(_("E217: Can't execute autocommands for ALL events"));
7966 return FAIL;
7967 }
7968
7969 /*
7970 * Scan over the events.
7971 * If we find an illegal name, return here, don't do anything.
7972 */
7973 fname = find_end_event(arg, group != AUGROUP_ALL);
7974 if (fname == NULL)
7975 return FAIL;
7976
7977 fname = skipwhite(fname);
7978
7979 /*
7980 * Loop over the events.
7981 */
7982 while (*arg && !vim_iswhite(*arg))
7983 if (apply_autocmds_group(event_name2nr(arg, &arg),
7984 fname, NULL, TRUE, group, curbuf, NULL))
7985 nothing_done = FALSE;
7986
7987 if (nothing_done && do_msg)
7988 MSG(_("No matching autocommands"));
7989
7990#ifdef FEAT_EVAL
7991 return aborting() ? FAIL : OK;
7992#else
7993 return OK;
7994#endif
7995}
7996
7997/*
7998 * ":doautoall": execute autocommands for each loaded buffer.
7999 */
8000 void
8001ex_doautoall(eap)
8002 exarg_T *eap;
8003{
8004 int retval;
8005 aco_save_T aco;
8006 buf_T *buf;
8007
8008 /*
8009 * This is a bit tricky: For some commands curwin->w_buffer needs to be
8010 * equal to curbuf, but for some buffers there may not be a window.
8011 * So we change the buffer for the current window for a moment. This
8012 * gives problems when the autocommands make changes to the list of
8013 * buffers or windows...
8014 */
8015 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8016 {
8017 if (curbuf->b_ml.ml_mfp != NULL)
8018 {
8019 /* find a window for this buffer and save some values */
8020 aucmd_prepbuf(&aco, buf);
8021
8022 /* execute the autocommands for this buffer */
8023 retval = do_doautocmd(eap->arg, FALSE);
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +00008024 do_modelines(FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008025
8026 /* restore the current window */
8027 aucmd_restbuf(&aco);
8028
8029 /* stop if there is some error or buffer was deleted */
8030 if (retval == FAIL || !buf_valid(buf))
8031 break;
8032 }
8033 }
8034
8035 check_cursor(); /* just in case lines got deleted */
8036}
8037
8038/*
8039 * Prepare for executing autocommands for (hidden) buffer "buf".
8040 * Search a window for the current buffer. Save the cursor position and
8041 * screen offset.
8042 * Set "curbuf" and "curwin" to match "buf".
8043 */
8044 void
8045aucmd_prepbuf(aco, buf)
8046 aco_save_T *aco; /* structure to save values in */
8047 buf_T *buf; /* new curbuf */
8048{
8049 win_T *win;
8050
8051 aco->new_curbuf = buf;
8052
8053 /* Find a window that is for the new buffer */
8054 if (buf == curbuf) /* be quick when buf is curbuf */
8055 win = curwin;
8056 else
8057#ifdef FEAT_WINDOWS
8058 for (win = firstwin; win != NULL; win = win->w_next)
8059 if (win->w_buffer == buf)
8060 break;
8061#else
8062 win = NULL;
8063#endif
8064
8065 /*
8066 * Prefer to use an existing window for the buffer, it has the least side
8067 * effects (esp. if "buf" is curbuf).
8068 * Otherwise, use curwin for "buf". It might make some items in the
8069 * window invalid. At least save the cursor and topline.
8070 */
8071 if (win != NULL)
8072 {
8073 /* there is a window for "buf", make it the curwin */
8074 aco->save_curwin = curwin;
8075 curwin = win;
8076 aco->save_buf = win->w_buffer;
8077 aco->new_curwin = win;
8078 }
8079 else
8080 {
8081 /* there is no window for "buf", use curwin */
8082 aco->save_curwin = NULL;
8083 aco->save_buf = curbuf;
8084 --curbuf->b_nwindows;
8085 curwin->w_buffer = buf;
8086 ++buf->b_nwindows;
8087
8088 /* save cursor and topline, set them to safe values */
8089 aco->save_cursor = curwin->w_cursor;
8090 curwin->w_cursor.lnum = 1;
8091 curwin->w_cursor.col = 0;
8092 aco->save_topline = curwin->w_topline;
8093 curwin->w_topline = 1;
8094#ifdef FEAT_DIFF
8095 aco->save_topfill = curwin->w_topfill;
8096 curwin->w_topfill = 0;
8097#endif
8098 }
8099
8100 curbuf = buf;
8101}
8102
8103/*
8104 * Cleanup after executing autocommands for a (hidden) buffer.
8105 * Restore the window as it was (if possible).
8106 */
8107 void
8108aucmd_restbuf(aco)
8109 aco_save_T *aco; /* structure holding saved values */
8110{
8111 if (aco->save_curwin != NULL)
8112 {
8113 /* restore curwin */
8114#ifdef FEAT_WINDOWS
8115 if (win_valid(aco->save_curwin))
8116#endif
8117 {
8118 /* restore the buffer which was previously edited by curwin, if
8119 * it's still the same window and it's valid */
8120 if (curwin == aco->new_curwin
8121 && buf_valid(aco->save_buf)
8122 && aco->save_buf->b_ml.ml_mfp != NULL)
8123 {
8124 --curbuf->b_nwindows;
8125 curbuf = aco->save_buf;
8126 curwin->w_buffer = curbuf;
8127 ++curbuf->b_nwindows;
8128 }
8129
8130 curwin = aco->save_curwin;
8131 curbuf = curwin->w_buffer;
8132 }
8133 }
8134 else
8135 {
8136 /* restore buffer for curwin if it still exists and is loaded */
8137 if (buf_valid(aco->save_buf) && aco->save_buf->b_ml.ml_mfp != NULL)
8138 {
8139 --curbuf->b_nwindows;
8140 curbuf = aco->save_buf;
8141 curwin->w_buffer = curbuf;
8142 ++curbuf->b_nwindows;
8143 curwin->w_cursor = aco->save_cursor;
8144 check_cursor();
8145 /* check topline < line_count, in case lines got deleted */
8146 if (aco->save_topline <= curbuf->b_ml.ml_line_count)
8147 {
8148 curwin->w_topline = aco->save_topline;
8149#ifdef FEAT_DIFF
8150 curwin->w_topfill = aco->save_topfill;
8151#endif
8152 }
8153 else
8154 {
8155 curwin->w_topline = curbuf->b_ml.ml_line_count;
8156#ifdef FEAT_DIFF
8157 curwin->w_topfill = 0;
8158#endif
8159 }
8160 }
8161 }
8162}
8163
8164static int autocmd_nested = FALSE;
8165
8166/*
8167 * Execute autocommands for "event" and file name "fname".
8168 * Return TRUE if some commands were executed.
8169 */
8170 int
8171apply_autocmds(event, fname, fname_io, force, buf)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008172 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008173 char_u *fname; /* NULL or empty means use actual file name */
8174 char_u *fname_io; /* fname to use for <afile> on cmdline */
8175 int force; /* when TRUE, ignore autocmd_busy */
8176 buf_T *buf; /* buffer for <abuf> */
8177{
8178 return apply_autocmds_group(event, fname, fname_io, force,
8179 AUGROUP_ALL, buf, NULL);
8180}
8181
8182/*
8183 * Like apply_autocmds(), but with extra "eap" argument. This takes care of
8184 * setting v:filearg.
8185 */
8186 static int
8187apply_autocmds_exarg(event, fname, fname_io, force, buf, eap)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008188 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008189 char_u *fname;
8190 char_u *fname_io;
8191 int force;
8192 buf_T *buf;
8193 exarg_T *eap;
8194{
8195 return apply_autocmds_group(event, fname, fname_io, force,
8196 AUGROUP_ALL, buf, eap);
8197}
8198
8199/*
8200 * Like apply_autocmds(), but handles the caller's retval. If the script
8201 * processing is being aborted or if retval is FAIL when inside a try
8202 * conditional, no autocommands are executed. If otherwise the autocommands
8203 * cause the script to be aborted, retval is set to FAIL.
8204 */
8205 int
8206apply_autocmds_retval(event, fname, fname_io, force, buf, retval)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008207 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008208 char_u *fname; /* NULL or empty means use actual file name */
8209 char_u *fname_io; /* fname to use for <afile> on cmdline */
8210 int force; /* when TRUE, ignore autocmd_busy */
8211 buf_T *buf; /* buffer for <abuf> */
8212 int *retval; /* pointer to caller's retval */
8213{
8214 int did_cmd;
8215
Bram Moolenaar1e015462005-09-25 22:16:38 +00008216#ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00008217 if (should_abort(*retval))
8218 return FALSE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00008219#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008220
8221 did_cmd = apply_autocmds_group(event, fname, fname_io, force,
8222 AUGROUP_ALL, buf, NULL);
Bram Moolenaar1e015462005-09-25 22:16:38 +00008223 if (did_cmd
8224#ifdef FEAT_EVAL
8225 && aborting()
8226#endif
8227 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00008228 *retval = FAIL;
8229 return did_cmd;
8230}
8231
Bram Moolenaard35f9712005-12-18 22:02:33 +00008232/*
8233 * Return TRUE when there is a CursorHold autocommand defined.
8234 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008235 int
8236has_cursorhold()
8237{
Bram Moolenaar754b5602006-02-09 23:53:20 +00008238 return (first_autopat[(int)(get_real_state() == NORMAL_BUSY
8239 ? EVENT_CURSORHOLD : EVENT_CURSORHOLDI)] != NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008240}
Bram Moolenaard35f9712005-12-18 22:02:33 +00008241
8242/*
8243 * Return TRUE if the CursorHold event can be triggered.
8244 */
8245 int
8246trigger_cursorhold()
8247{
Bram Moolenaar754b5602006-02-09 23:53:20 +00008248 int state;
8249
8250 if (!did_cursorhold && has_cursorhold() && !Recording)
8251 {
8252 state = get_real_state();
8253 if (state == NORMAL_BUSY || (state & INSERT) != 0)
8254 return TRUE;
8255 }
8256 return FALSE;
Bram Moolenaard35f9712005-12-18 22:02:33 +00008257}
Bram Moolenaar754b5602006-02-09 23:53:20 +00008258
8259/*
8260 * Return TRUE when there is a CursorMoved autocommand defined.
8261 */
8262 int
8263has_cursormoved()
8264{
8265 return (first_autopat[(int)EVENT_CURSORMOVED] != NULL);
8266}
8267
8268/*
8269 * Return TRUE when there is a CursorMovedI autocommand defined.
8270 */
8271 int
8272has_cursormovedI()
8273{
8274 return (first_autopat[(int)EVENT_CURSORMOVEDI] != NULL);
8275}
Bram Moolenaar071d4272004-06-13 20:20:40 +00008276
8277 static int
8278apply_autocmds_group(event, fname, fname_io, force, group, buf, eap)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008279 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008280 char_u *fname; /* NULL or empty means use actual file name */
8281 char_u *fname_io; /* fname to use for <afile> on cmdline, NULL means
8282 use fname */
8283 int force; /* when TRUE, ignore autocmd_busy */
8284 int group; /* group ID, or AUGROUP_ALL */
8285 buf_T *buf; /* buffer for <abuf> */
8286 exarg_T *eap; /* command arguments */
8287{
8288 char_u *sfname = NULL; /* short file name */
8289 char_u *tail;
8290 int save_changed;
8291 buf_T *old_curbuf;
8292 int retval = FALSE;
8293 char_u *save_sourcing_name;
8294 linenr_T save_sourcing_lnum;
8295 char_u *save_autocmd_fname;
8296 int save_autocmd_bufnr;
8297 char_u *save_autocmd_match;
8298 int save_autocmd_busy;
8299 int save_autocmd_nested;
8300 static int nesting = 0;
8301 AutoPatCmd patcmd;
8302 AutoPat *ap;
8303#ifdef FEAT_EVAL
8304 scid_T save_current_SID;
8305 void *save_funccalp;
8306 char_u *save_cmdarg;
8307 long save_cmdbang;
8308#endif
8309 static int filechangeshell_busy = FALSE;
Bram Moolenaar05159a02005-02-26 23:04:13 +00008310#ifdef FEAT_PROFILE
8311 proftime_T wait_time;
8312#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008313
8314 /*
8315 * Quickly return if there are no autocommands for this event or
8316 * autocommands are blocked.
8317 */
8318 if (first_autopat[(int)event] == NULL || autocmd_block > 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008319 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008320
8321 /*
8322 * When autocommands are busy, new autocommands are only executed when
8323 * explicitly enabled with the "nested" flag.
8324 */
8325 if (autocmd_busy && !(force || autocmd_nested))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008326 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008327
8328#ifdef FEAT_EVAL
8329 /*
8330 * Quickly return when immdediately aborting on error, or when an interrupt
8331 * occurred or an exception was thrown but not caught.
8332 */
8333 if (aborting())
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008334 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008335#endif
8336
8337 /*
8338 * FileChangedShell never nests, because it can create an endless loop.
8339 */
8340 if (filechangeshell_busy && event == EVENT_FILECHANGEDSHELL)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008341 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008342
8343 /*
8344 * Ignore events in 'eventignore'.
8345 */
8346 if (event_ignored(event))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008347 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008348
8349 /*
8350 * Allow nesting of autocommands, but restrict the depth, because it's
8351 * possible to create an endless loop.
8352 */
8353 if (nesting == 10)
8354 {
8355 EMSG(_("E218: autocommand nesting too deep"));
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008356 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008357 }
8358
8359 /*
8360 * Check if these autocommands are disabled. Used when doing ":all" or
8361 * ":ball".
8362 */
8363 if ( (autocmd_no_enter
8364 && (event == EVENT_WINENTER || event == EVENT_BUFENTER))
8365 || (autocmd_no_leave
8366 && (event == EVENT_WINLEAVE || event == EVENT_BUFLEAVE)))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008367 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008368
8369 /*
8370 * Save the autocmd_* variables and info about the current buffer.
8371 */
8372 save_autocmd_fname = autocmd_fname;
8373 save_autocmd_bufnr = autocmd_bufnr;
8374 save_autocmd_match = autocmd_match;
8375 save_autocmd_busy = autocmd_busy;
8376 save_autocmd_nested = autocmd_nested;
8377 save_changed = curbuf->b_changed;
8378 old_curbuf = curbuf;
8379
8380 /*
8381 * Set the file name to be used for <afile>.
8382 */
8383 if (fname_io == NULL)
8384 {
8385 if (fname != NULL && *fname != NUL)
8386 autocmd_fname = fname;
8387 else if (buf != NULL)
8388 autocmd_fname = buf->b_fname;
8389 else
8390 autocmd_fname = NULL;
8391 }
8392 else
8393 autocmd_fname = fname_io;
8394
8395 /*
8396 * Set the buffer number to be used for <abuf>.
8397 */
8398 if (buf == NULL)
8399 autocmd_bufnr = 0;
8400 else
8401 autocmd_bufnr = buf->b_fnum;
8402
8403 /*
8404 * When the file name is NULL or empty, use the file name of buffer "buf".
8405 * Always use the full path of the file name to match with, in case
8406 * "allow_dirs" is set.
8407 */
8408 if (fname == NULL || *fname == NUL)
8409 {
8410 if (buf == NULL)
8411 fname = NULL;
8412 else
8413 {
8414#ifdef FEAT_SYN_HL
8415 if (event == EVENT_SYNTAX)
8416 fname = buf->b_p_syn;
8417 else
8418#endif
8419 if (event == EVENT_FILETYPE)
8420 fname = buf->b_p_ft;
8421 else
8422 {
8423 if (buf->b_sfname != NULL)
8424 sfname = vim_strsave(buf->b_sfname);
8425 fname = buf->b_ffname;
8426 }
8427 }
8428 if (fname == NULL)
8429 fname = (char_u *)"";
8430 fname = vim_strsave(fname); /* make a copy, so we can change it */
8431 }
8432 else
8433 {
8434 sfname = vim_strsave(fname);
Bram Moolenaar7c626922005-02-07 22:01:03 +00008435 /* Don't try expanding FileType, Syntax, WindowID or QuickFixCmd* */
8436 if (event == EVENT_FILETYPE
8437 || event == EVENT_SYNTAX
8438 || event == EVENT_REMOTEREPLY
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00008439 || event == EVENT_SPELLFILEMISSING
Bram Moolenaar7c626922005-02-07 22:01:03 +00008440 || event == EVENT_QUICKFIXCMDPRE
8441 || event == EVENT_QUICKFIXCMDPOST)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008442 fname = vim_strsave(fname);
8443 else
8444 fname = FullName_save(fname, FALSE);
8445 }
8446 if (fname == NULL) /* out of memory */
8447 {
8448 vim_free(sfname);
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008449 retval = FALSE;
8450 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008451 }
8452
8453#ifdef BACKSLASH_IN_FILENAME
8454 /*
8455 * Replace all backslashes with forward slashes. This makes the
8456 * autocommand patterns portable between Unix and MS-DOS.
8457 */
8458 if (sfname != NULL)
8459 forward_slash(sfname);
8460 forward_slash(fname);
8461#endif
8462
8463#ifdef VMS
8464 /* remove version for correct match */
8465 if (sfname != NULL)
8466 vms_remove_version(sfname);
8467 vms_remove_version(fname);
8468#endif
8469
8470 /*
8471 * Set the name to be used for <amatch>.
8472 */
8473 autocmd_match = fname;
8474
8475
8476 /* Don't redraw while doing auto commands. */
8477 ++RedrawingDisabled;
8478 save_sourcing_name = sourcing_name;
8479 sourcing_name = NULL; /* don't free this one */
8480 save_sourcing_lnum = sourcing_lnum;
8481 sourcing_lnum = 0; /* no line number here */
8482
8483#ifdef FEAT_EVAL
8484 save_current_SID = current_SID;
8485
Bram Moolenaar05159a02005-02-26 23:04:13 +00008486# ifdef FEAT_PROFILE
8487 if (do_profiling)
8488 prof_child_enter(&wait_time); /* doesn't count for the caller itself */
8489# endif
8490
Bram Moolenaar071d4272004-06-13 20:20:40 +00008491 /* Don't use local function variables, if called from a function */
8492 save_funccalp = save_funccal();
8493#endif
8494
8495 /*
8496 * When starting to execute autocommands, save the search patterns.
8497 */
8498 if (!autocmd_busy)
8499 {
8500 save_search_patterns();
8501 saveRedobuff();
8502 did_filetype = keep_filetype;
8503 }
8504
8505 /*
8506 * Note that we are applying autocmds. Some commands need to know.
8507 */
8508 autocmd_busy = TRUE;
8509 filechangeshell_busy = (event == EVENT_FILECHANGEDSHELL);
8510 ++nesting; /* see matching decrement below */
8511
8512 /* Remember that FileType was triggered. Used for did_filetype(). */
8513 if (event == EVENT_FILETYPE)
8514 did_filetype = TRUE;
8515
8516 tail = gettail(fname);
8517
8518 /* Find first autocommand that matches */
8519 patcmd.curpat = first_autopat[(int)event];
8520 patcmd.nextcmd = NULL;
8521 patcmd.group = group;
8522 patcmd.fname = fname;
8523 patcmd.sfname = sfname;
8524 patcmd.tail = tail;
8525 patcmd.event = event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008526 patcmd.arg_bufnr = autocmd_bufnr;
8527 patcmd.next = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008528 auto_next_pat(&patcmd, FALSE);
8529
8530 /* found one, start executing the autocommands */
8531 if (patcmd.curpat != NULL)
8532 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008533 /* add to active_apc_list */
8534 patcmd.next = active_apc_list;
8535 active_apc_list = &patcmd;
8536
Bram Moolenaar071d4272004-06-13 20:20:40 +00008537#ifdef FEAT_EVAL
8538 /* set v:cmdarg (only when there is a matching pattern) */
8539 save_cmdbang = get_vim_var_nr(VV_CMDBANG);
8540 if (eap != NULL)
8541 {
8542 save_cmdarg = set_cmdarg(eap, NULL);
8543 set_vim_var_nr(VV_CMDBANG, (long)eap->forceit);
8544 }
8545 else
8546 save_cmdarg = NULL; /* avoid gcc warning */
8547#endif
8548 retval = TRUE;
8549 /* mark the last pattern, to avoid an endless loop when more patterns
8550 * are added when executing autocommands */
8551 for (ap = patcmd.curpat; ap->next != NULL; ap = ap->next)
8552 ap->last = FALSE;
8553 ap->last = TRUE;
8554 check_lnums(TRUE); /* make sure cursor and topline are valid */
8555 do_cmdline(NULL, getnextac, (void *)&patcmd,
8556 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
8557#ifdef FEAT_EVAL
8558 if (eap != NULL)
8559 {
8560 (void)set_cmdarg(NULL, save_cmdarg);
8561 set_vim_var_nr(VV_CMDBANG, save_cmdbang);
8562 }
8563#endif
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008564 /* delete from active_apc_list */
8565 if (active_apc_list == &patcmd) /* just in case */
8566 active_apc_list = patcmd.next;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008567 }
8568
8569 --RedrawingDisabled;
8570 autocmd_busy = save_autocmd_busy;
8571 filechangeshell_busy = FALSE;
8572 autocmd_nested = save_autocmd_nested;
8573 vim_free(sourcing_name);
8574 sourcing_name = save_sourcing_name;
8575 sourcing_lnum = save_sourcing_lnum;
8576 autocmd_fname = save_autocmd_fname;
8577 autocmd_bufnr = save_autocmd_bufnr;
8578 autocmd_match = save_autocmd_match;
8579#ifdef FEAT_EVAL
8580 current_SID = save_current_SID;
8581 restore_funccal(save_funccalp);
Bram Moolenaar05159a02005-02-26 23:04:13 +00008582# ifdef FEAT_PROFILE
8583 if (do_profiling)
8584 prof_child_exit(&wait_time);
8585# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008586#endif
8587 vim_free(fname);
8588 vim_free(sfname);
8589 --nesting; /* see matching increment above */
8590
8591 /*
8592 * When stopping to execute autocommands, restore the search patterns and
8593 * the redo buffer.
8594 */
8595 if (!autocmd_busy)
8596 {
8597 restore_search_patterns();
8598 restoreRedobuff();
8599 did_filetype = FALSE;
8600 }
8601
8602 /*
8603 * Some events don't set or reset the Changed flag.
8604 * Check if still in the same buffer!
8605 */
8606 if (curbuf == old_curbuf
8607 && (event == EVENT_BUFREADPOST
8608 || event == EVENT_BUFWRITEPOST
8609 || event == EVENT_FILEAPPENDPOST
8610 || event == EVENT_VIMLEAVE
8611 || event == EVENT_VIMLEAVEPRE))
8612 {
8613#ifdef FEAT_TITLE
8614 if (curbuf->b_changed != save_changed)
8615 need_maketitle = TRUE;
8616#endif
8617 curbuf->b_changed = save_changed;
8618 }
8619
8620 au_cleanup(); /* may really delete removed patterns/commands now */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008621
8622BYPASS_AU:
8623 /* When wiping out a buffer make sure all its buffer-local autocommands
8624 * are deleted. */
8625 if (event == EVENT_BUFWIPEOUT && buf != NULL)
8626 aubuflocal_remove(buf);
8627
Bram Moolenaar071d4272004-06-13 20:20:40 +00008628 return retval;
8629}
8630
8631/*
8632 * Find next autocommand pattern that matches.
8633 */
8634 static void
8635auto_next_pat(apc, stop_at_last)
8636 AutoPatCmd *apc;
8637 int stop_at_last; /* stop when 'last' flag is set */
8638{
8639 AutoPat *ap;
8640 AutoCmd *cp;
8641 char_u *name;
8642 char *s;
8643
8644 vim_free(sourcing_name);
8645 sourcing_name = NULL;
8646
8647 for (ap = apc->curpat; ap != NULL && !got_int; ap = ap->next)
8648 {
8649 apc->curpat = NULL;
8650
8651 /* only use a pattern when it has not been removed, has commands and
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008652 * the group matches. For buffer-local autocommands only check the
8653 * buffer number. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008654 if (ap->pat != NULL && ap->cmds != NULL
8655 && (apc->group == AUGROUP_ALL || apc->group == ap->group))
8656 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008657 /* execution-condition */
8658 if (ap->buflocal_nr == 0
Bram Moolenaar748bf032005-02-02 23:04:36 +00008659 ? (match_file_pat(NULL, ap->reg_prog, apc->fname,
8660 apc->sfname, apc->tail, ap->allow_dirs))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008661 : ap->buflocal_nr == apc->arg_bufnr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008662 {
8663 name = event_nr2name(apc->event);
8664 s = _("%s Auto commands for \"%s\"");
8665 sourcing_name = alloc((unsigned)(STRLEN(s)
8666 + STRLEN(name) + ap->patlen + 1));
8667 if (sourcing_name != NULL)
8668 {
8669 sprintf((char *)sourcing_name, s,
8670 (char *)name, (char *)ap->pat);
8671 if (p_verbose >= 8)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00008672 {
8673 verbose_enter();
Bram Moolenaar051b7822005-05-19 21:00:46 +00008674 smsg((char_u *)_("Executing %s"), sourcing_name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00008675 verbose_leave();
8676 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008677 }
8678
8679 apc->curpat = ap;
8680 apc->nextcmd = ap->cmds;
8681 /* mark last command */
8682 for (cp = ap->cmds; cp->next != NULL; cp = cp->next)
8683 cp->last = FALSE;
8684 cp->last = TRUE;
8685 }
8686 line_breakcheck();
8687 if (apc->curpat != NULL) /* found a match */
8688 break;
8689 }
8690 if (stop_at_last && ap->last)
8691 break;
8692 }
8693}
8694
8695/*
8696 * Get next autocommand command.
8697 * Called by do_cmdline() to get the next line for ":if".
8698 * Returns allocated string, or NULL for end of autocommands.
8699 */
8700/* ARGSUSED */
8701 static char_u *
8702getnextac(c, cookie, indent)
8703 int c; /* not used */
8704 void *cookie;
8705 int indent; /* not used */
8706{
8707 AutoPatCmd *acp = (AutoPatCmd *)cookie;
8708 char_u *retval;
8709 AutoCmd *ac;
8710
8711 /* Can be called again after returning the last line. */
8712 if (acp->curpat == NULL)
8713 return NULL;
8714
8715 /* repeat until we find an autocommand to execute */
8716 for (;;)
8717 {
8718 /* skip removed commands */
8719 while (acp->nextcmd != NULL && acp->nextcmd->cmd == NULL)
8720 if (acp->nextcmd->last)
8721 acp->nextcmd = NULL;
8722 else
8723 acp->nextcmd = acp->nextcmd->next;
8724
8725 if (acp->nextcmd != NULL)
8726 break;
8727
8728 /* at end of commands, find next pattern that matches */
8729 if (acp->curpat->last)
8730 acp->curpat = NULL;
8731 else
8732 acp->curpat = acp->curpat->next;
8733 if (acp->curpat != NULL)
8734 auto_next_pat(acp, TRUE);
8735 if (acp->curpat == NULL)
8736 return NULL;
8737 }
8738
8739 ac = acp->nextcmd;
8740
8741 if (p_verbose >= 9)
8742 {
Bram Moolenaara04f10b2005-05-31 22:09:46 +00008743 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00008744 smsg((char_u *)_("autocommand %s"), ac->cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008745 msg_puts((char_u *)"\n"); /* don't overwrite this either */
Bram Moolenaara04f10b2005-05-31 22:09:46 +00008746 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00008747 }
8748 retval = vim_strsave(ac->cmd);
8749 autocmd_nested = ac->nested;
8750#ifdef FEAT_EVAL
8751 current_SID = ac->scriptID;
8752#endif
8753 if (ac->last)
8754 acp->nextcmd = NULL;
8755 else
8756 acp->nextcmd = ac->next;
8757 return retval;
8758}
8759
8760/*
8761 * Return TRUE if there is a matching autocommand for "fname".
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008762 * To account for buffer-local autocommands, function needs to know
8763 * in which buffer the file will be opened.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008764 */
8765 int
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008766has_autocmd(event, sfname, buf)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008767 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008768 char_u *sfname;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008769 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008770{
8771 AutoPat *ap;
8772 char_u *fname;
8773 char_u *tail = gettail(sfname);
8774 int retval = FALSE;
8775
8776 fname = FullName_save(sfname, FALSE);
8777 if (fname == NULL)
8778 return FALSE;
8779
8780#ifdef BACKSLASH_IN_FILENAME
8781 /*
8782 * Replace all backslashes with forward slashes. This makes the
8783 * autocommand patterns portable between Unix and MS-DOS.
8784 */
8785 sfname = vim_strsave(sfname);
8786 if (sfname != NULL)
8787 forward_slash(sfname);
8788 forward_slash(fname);
8789#endif
8790
8791 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8792 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008793 && (ap->buflocal_nr == 0
Bram Moolenaar748bf032005-02-02 23:04:36 +00008794 ? match_file_pat(NULL, ap->reg_prog,
8795 fname, sfname, tail, ap->allow_dirs)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008796 : buf != NULL && ap->buflocal_nr == buf->b_fnum
8797 ))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008798 {
8799 retval = TRUE;
8800 break;
8801 }
8802
8803 vim_free(fname);
8804#ifdef BACKSLASH_IN_FILENAME
8805 vim_free(sfname);
8806#endif
8807
8808 return retval;
8809}
8810
8811#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
8812/*
8813 * Function given to ExpandGeneric() to obtain the list of autocommand group
8814 * names.
8815 */
8816/*ARGSUSED*/
8817 char_u *
8818get_augroup_name(xp, idx)
8819 expand_T *xp;
8820 int idx;
8821{
8822 if (idx == augroups.ga_len) /* add "END" add the end */
8823 return (char_u *)"END";
8824 if (idx >= augroups.ga_len) /* end of list */
8825 return NULL;
8826 if (AUGROUP_NAME(idx) == NULL) /* skip deleted entries */
8827 return (char_u *)"";
8828 return AUGROUP_NAME(idx); /* return a name */
8829}
8830
8831static int include_groups = FALSE;
8832
8833 char_u *
8834set_context_in_autocmd(xp, arg, doautocmd)
8835 expand_T *xp;
8836 char_u *arg;
8837 int doautocmd; /* TRUE for :doautocmd, FALSE for :autocmd */
8838{
8839 char_u *p;
8840 int group;
8841
8842 /* check for a group name, skip it if present */
8843 include_groups = FALSE;
8844 p = arg;
8845 group = au_get_grouparg(&arg);
8846 if (group == AUGROUP_ERROR)
8847 return NULL;
8848 /* If there only is a group name that's what we expand. */
8849 if (*arg == NUL && group != AUGROUP_ALL && !vim_iswhite(arg[-1]))
8850 {
8851 arg = p;
8852 group = AUGROUP_ALL;
8853 }
8854
8855 /* skip over event name */
8856 for (p = arg; *p != NUL && !vim_iswhite(*p); ++p)
8857 if (*p == ',')
8858 arg = p + 1;
8859 if (*p == NUL)
8860 {
8861 if (group == AUGROUP_ALL)
8862 include_groups = TRUE;
8863 xp->xp_context = EXPAND_EVENTS; /* expand event name */
8864 xp->xp_pattern = arg;
8865 return NULL;
8866 }
8867
8868 /* skip over pattern */
8869 arg = skipwhite(p);
8870 while (*arg && (!vim_iswhite(*arg) || arg[-1] == '\\'))
8871 arg++;
8872 if (*arg)
8873 return arg; /* expand (next) command */
8874
8875 if (doautocmd)
8876 xp->xp_context = EXPAND_FILES; /* expand file names */
8877 else
8878 xp->xp_context = EXPAND_NOTHING; /* pattern is not expanded */
8879 return NULL;
8880}
8881
8882/*
8883 * Function given to ExpandGeneric() to obtain the list of event names.
8884 */
8885/*ARGSUSED*/
8886 char_u *
8887get_event_name(xp, idx)
8888 expand_T *xp;
8889 int idx;
8890{
8891 if (idx < augroups.ga_len) /* First list group names, if wanted */
8892 {
8893 if (!include_groups || AUGROUP_NAME(idx) == NULL)
8894 return (char_u *)""; /* skip deleted entries */
8895 return AUGROUP_NAME(idx); /* return a name */
8896 }
8897 return (char_u *)event_names[idx - augroups.ga_len].name;
8898}
8899
8900#endif /* FEAT_CMDL_COMPL */
8901
8902/*
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00008903 * Return TRUE if autocmd is supported.
8904 */
8905 int
8906autocmd_supported(name)
8907 char_u *name;
8908{
8909 char_u *p;
8910
8911 return (event_name2nr(name, &p) != NUM_EVENTS);
8912}
8913
8914/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00008915 * Return TRUE if an autocommand is defined for a group, event and
8916 * pattern: The group can be omitted to accept any group. "event" and "pattern"
8917 * can be NULL to accept any event and pattern. "pattern" can be NULL to accept
8918 * any pattern. Buffer-local patterns <buffer> or <buffer=N> are accepted.
8919 * Used for:
8920 * exists("#Group") or
8921 * exists("#Group#Event") or
8922 * exists("#Group#Event#pat") or
8923 * exists("#Event") or
8924 * exists("#Event#pat")
Bram Moolenaar071d4272004-06-13 20:20:40 +00008925 */
8926 int
Bram Moolenaar195d6352005-12-19 22:08:24 +00008927au_exists(arg)
8928 char_u *arg;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008929{
Bram Moolenaar195d6352005-12-19 22:08:24 +00008930 char_u *arg_save;
8931 char_u *pattern = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008932 char_u *event_name;
8933 char_u *p;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008934 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008935 AutoPat *ap;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008936 buf_T *buflocal_buf = NULL;
Bram Moolenaar195d6352005-12-19 22:08:24 +00008937 int group;
8938 int retval = FALSE;
8939
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00008940 /* Make a copy so that we can change the '#' chars to a NUL. */
Bram Moolenaar195d6352005-12-19 22:08:24 +00008941 arg_save = vim_strsave(arg);
8942 if (arg_save == NULL)
8943 return FALSE;
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00008944 p = vim_strchr(arg_save, '#');
Bram Moolenaar195d6352005-12-19 22:08:24 +00008945 if (p != NULL)
8946 *p++ = NUL;
8947
8948 /* First, look for an autocmd group name */
8949 group = au_find_group(arg_save);
8950 if (group == AUGROUP_ERROR)
8951 {
8952 /* Didn't match a group name, assume the first argument is an event. */
8953 group = AUGROUP_ALL;
8954 event_name = arg_save;
8955 }
8956 else
8957 {
8958 if (p == NULL)
8959 {
8960 /* "Group": group name is present and it's recognized */
8961 retval = TRUE;
8962 goto theend;
8963 }
8964
8965 /* Must be "Group#Event" or "Group#Event#pat". */
8966 event_name = p;
8967 p = vim_strchr(event_name, '#');
8968 if (p != NULL)
8969 *p++ = NUL; /* "Group#Event#pat" */
8970 }
8971
8972 pattern = p; /* "pattern" is NULL when there is no pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008973
8974 /* find the index (enum) for the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008975 event = event_name2nr(event_name, &p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008976
8977 /* return FALSE if the event name is not recognized */
Bram Moolenaar195d6352005-12-19 22:08:24 +00008978 if (event == NUM_EVENTS)
8979 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008980
8981 /* Find the first autocommand for this event.
8982 * If there isn't any, return FALSE;
8983 * If there is one and no pattern given, return TRUE; */
8984 ap = first_autopat[(int)event];
8985 if (ap == NULL)
Bram Moolenaar195d6352005-12-19 22:08:24 +00008986 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008987 if (pattern == NULL)
Bram Moolenaar195d6352005-12-19 22:08:24 +00008988 {
8989 retval = TRUE;
8990 goto theend;
8991 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008992
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008993 /* if pattern is "<buffer>", special handling is needed which uses curbuf */
8994 /* for pattern "<buffer=N>, fnamecmp() will work fine */
8995 if (STRICMP(pattern, "<buffer>") == 0)
8996 buflocal_buf = curbuf;
8997
Bram Moolenaar071d4272004-06-13 20:20:40 +00008998 /* Check if there is an autocommand with the given pattern. */
8999 for ( ; ap != NULL; ap = ap->next)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009000 /* only use a pattern when it has not been removed and has commands. */
9001 /* For buffer-local autocommands, fnamecmp() works fine. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009002 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaar195d6352005-12-19 22:08:24 +00009003 && (group == AUGROUP_ALL || ap->group == group)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009004 && (buflocal_buf == NULL
9005 ? fnamecmp(ap->pat, pattern) == 0
9006 : ap->buflocal_nr == buflocal_buf->b_fnum))
Bram Moolenaar195d6352005-12-19 22:08:24 +00009007 {
9008 retval = TRUE;
9009 break;
9010 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009011
Bram Moolenaar195d6352005-12-19 22:08:24 +00009012theend:
9013 vim_free(arg_save);
9014 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009015}
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009016
Bram Moolenaar071d4272004-06-13 20:20:40 +00009017#endif /* FEAT_AUTOCMD */
9018
9019#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN) || defined(PROTO)
9020/*
Bram Moolenaar748bf032005-02-02 23:04:36 +00009021 * Try matching a filename with a "pattern" ("prog" is NULL), or use the
9022 * precompiled regprog "prog" ("pattern" is NULL). That avoids calling
9023 * vim_regcomp() often.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009024 * Used for autocommands and 'wildignore'.
9025 * Returns TRUE if there is a match, FALSE otherwise.
9026 */
9027 int
Bram Moolenaar748bf032005-02-02 23:04:36 +00009028match_file_pat(pattern, prog, fname, sfname, tail, allow_dirs)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009029 char_u *pattern; /* pattern to match with */
Bram Moolenaar748bf032005-02-02 23:04:36 +00009030 regprog_T *prog; /* pre-compiled regprog or NULL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009031 char_u *fname; /* full path of file name */
9032 char_u *sfname; /* short file name or NULL */
9033 char_u *tail; /* tail of path */
9034 int allow_dirs; /* allow matching with dir */
9035{
9036 regmatch_T regmatch;
9037 int result = FALSE;
9038#ifdef FEAT_OSFILETYPE
9039 int no_pattern = FALSE; /* TRUE if check is filetype only */
9040 char_u *type_start;
9041 char_u c;
9042 int match = FALSE;
9043#endif
9044
9045#ifdef CASE_INSENSITIVE_FILENAME
9046 regmatch.rm_ic = TRUE; /* Always ignore case */
9047#else
9048 regmatch.rm_ic = FALSE; /* Don't ever ignore case */
9049#endif
9050#ifdef FEAT_OSFILETYPE
9051 if (*pattern == '<')
9052 {
9053 /* There is a filetype condition specified with this pattern.
9054 * Check the filetype matches first. If not, don't bother with the
9055 * pattern (set regprog to NULL).
9056 * Always use magic for the regexp.
9057 */
9058
9059 for (type_start = pattern + 1; (c = *pattern); pattern++)
9060 {
9061 if ((c == ';' || c == '>') && match == FALSE)
9062 {
9063 *pattern = NUL; /* Terminate the string */
9064 match = mch_check_filetype(fname, type_start);
9065 *pattern = c; /* Restore the terminator */
9066 type_start = pattern + 1;
9067 }
9068 if (c == '>')
9069 break;
9070 }
9071
9072 /* (c should never be NUL, but check anyway) */
9073 if (match == FALSE || c == NUL)
9074 regmatch.regprog = NULL; /* Doesn't match - don't check pat. */
9075 else if (*pattern == NUL)
9076 {
9077 regmatch.regprog = NULL; /* Vim will try to free regprog later */
9078 no_pattern = TRUE; /* Always matches - don't check pat. */
9079 }
9080 else
9081 regmatch.regprog = vim_regcomp(pattern + 1, RE_MAGIC);
9082 }
9083 else
9084#endif
Bram Moolenaar748bf032005-02-02 23:04:36 +00009085 {
9086 if (prog != NULL)
9087 regmatch.regprog = prog;
9088 else
9089 regmatch.regprog = vim_regcomp(pattern, RE_MAGIC);
9090 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009091
9092 /*
9093 * Try for a match with the pattern with:
9094 * 1. the full file name, when the pattern has a '/'.
9095 * 2. the short file name, when the pattern has a '/'.
9096 * 3. the tail of the file name, when the pattern has no '/'.
9097 */
9098 if (
9099#ifdef FEAT_OSFILETYPE
9100 /* If the check is for a filetype only and we don't care
9101 * about the path then skip all the regexp stuff.
9102 */
9103 no_pattern ||
9104#endif
9105 (regmatch.regprog != NULL
9106 && ((allow_dirs
9107 && (vim_regexec(&regmatch, fname, (colnr_T)0)
9108 || (sfname != NULL
9109 && vim_regexec(&regmatch, sfname, (colnr_T)0))))
9110 || (!allow_dirs && vim_regexec(&regmatch, tail, (colnr_T)0)))))
9111 result = TRUE;
9112
Bram Moolenaar748bf032005-02-02 23:04:36 +00009113 if (prog == NULL)
9114 vim_free(regmatch.regprog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009115 return result;
9116}
9117#endif
9118
9119#if defined(FEAT_WILDIGN) || defined(PROTO)
9120/*
9121 * Return TRUE if a file matches with a pattern in "list".
9122 * "list" is a comma-separated list of patterns, like 'wildignore'.
9123 * "sfname" is the short file name or NULL, "ffname" the long file name.
9124 */
9125 int
9126match_file_list(list, sfname, ffname)
9127 char_u *list;
9128 char_u *sfname;
9129 char_u *ffname;
9130{
9131 char_u buf[100];
9132 char_u *tail;
9133 char_u *regpat;
9134 char allow_dirs;
9135 int match;
9136 char_u *p;
9137
9138 tail = gettail(sfname);
9139
9140 /* try all patterns in 'wildignore' */
9141 p = list;
9142 while (*p)
9143 {
9144 copy_option_part(&p, buf, 100, ",");
9145 regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, FALSE);
9146 if (regpat == NULL)
9147 break;
Bram Moolenaar748bf032005-02-02 23:04:36 +00009148 match = match_file_pat(regpat, NULL, ffname, sfname,
9149 tail, (int)allow_dirs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009150 vim_free(regpat);
9151 if (match)
9152 return TRUE;
9153 }
9154 return FALSE;
9155}
9156#endif
9157
9158/*
9159 * Convert the given pattern "pat" which has shell style wildcards in it, into
9160 * a regular expression, and return the result in allocated memory. If there
9161 * is a directory path separator to be matched, then TRUE is put in
9162 * allow_dirs, otherwise FALSE is put there -- webb.
9163 * Handle backslashes before special characters, like "\*" and "\ ".
9164 *
9165 * If FEAT_OSFILETYPE defined then pass initial <type> through unchanged. Eg:
9166 * '<html>myfile' becomes '<html>^myfile$' -- leonard.
9167 *
9168 * Returns NULL when out of memory.
9169 */
9170/*ARGSUSED*/
9171 char_u *
9172file_pat_to_reg_pat(pat, pat_end, allow_dirs, no_bslash)
9173 char_u *pat;
9174 char_u *pat_end; /* first char after pattern or NULL */
9175 char *allow_dirs; /* Result passed back out in here */
9176 int no_bslash; /* Don't use a backward slash as pathsep */
9177{
9178 int size;
9179 char_u *endp;
9180 char_u *reg_pat;
9181 char_u *p;
9182 int i;
9183 int nested = 0;
9184 int add_dollar = TRUE;
9185#ifdef FEAT_OSFILETYPE
9186 int check_length = 0;
9187#endif
9188
9189 if (allow_dirs != NULL)
9190 *allow_dirs = FALSE;
9191 if (pat_end == NULL)
9192 pat_end = pat + STRLEN(pat);
9193
9194#ifdef FEAT_OSFILETYPE
9195 /* Find out how much of the string is the filetype check */
9196 if (*pat == '<')
9197 {
9198 /* Count chars until the next '>' */
9199 for (p = pat + 1; p < pat_end && *p != '>'; p++)
9200 ;
9201 if (p < pat_end)
9202 {
9203 /* Pattern is of the form <.*>.* */
9204 check_length = p - pat + 1;
9205 if (p + 1 >= pat_end)
9206 {
9207 /* The 'pattern' is a filetype check ONLY */
9208 reg_pat = (char_u *)alloc(check_length + 1);
9209 if (reg_pat != NULL)
9210 {
9211 mch_memmove(reg_pat, pat, (size_t)check_length);
9212 reg_pat[check_length] = NUL;
9213 }
9214 return reg_pat;
9215 }
9216 }
9217 /* else: there was no closing '>' - assume it was a normal pattern */
9218
9219 }
9220 pat += check_length;
9221 size = 2 + check_length;
9222#else
9223 size = 2; /* '^' at start, '$' at end */
9224#endif
9225
9226 for (p = pat; p < pat_end; p++)
9227 {
9228 switch (*p)
9229 {
9230 case '*':
9231 case '.':
9232 case ',':
9233 case '{':
9234 case '}':
9235 case '~':
9236 size += 2; /* extra backslash */
9237 break;
9238#ifdef BACKSLASH_IN_FILENAME
9239 case '\\':
9240 case '/':
9241 size += 4; /* could become "[\/]" */
9242 break;
9243#endif
9244 default:
9245 size++;
9246# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00009247 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009248 {
9249 ++p;
9250 ++size;
9251 }
9252# endif
9253 break;
9254 }
9255 }
9256 reg_pat = alloc(size + 1);
9257 if (reg_pat == NULL)
9258 return NULL;
9259
9260#ifdef FEAT_OSFILETYPE
9261 /* Copy the type check in to the start. */
9262 if (check_length)
9263 mch_memmove(reg_pat, pat - check_length, (size_t)check_length);
9264 i = check_length;
9265#else
9266 i = 0;
9267#endif
9268
9269 if (pat[0] == '*')
9270 while (pat[0] == '*' && pat < pat_end - 1)
9271 pat++;
9272 else
9273 reg_pat[i++] = '^';
9274 endp = pat_end - 1;
9275 if (*endp == '*')
9276 {
9277 while (endp - pat > 0 && *endp == '*')
9278 endp--;
9279 add_dollar = FALSE;
9280 }
9281 for (p = pat; *p && nested >= 0 && p <= endp; p++)
9282 {
9283 switch (*p)
9284 {
9285 case '*':
9286 reg_pat[i++] = '.';
9287 reg_pat[i++] = '*';
Bram Moolenaar02743632005-07-25 20:42:36 +00009288 while (p[1] == '*') /* "**" matches like "*" */
9289 ++p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009290 break;
9291 case '.':
9292#ifdef RISCOS
9293 if (allow_dirs != NULL)
9294 *allow_dirs = TRUE;
9295 /* FALLTHROUGH */
9296#endif
9297 case '~':
9298 reg_pat[i++] = '\\';
9299 reg_pat[i++] = *p;
9300 break;
9301 case '?':
9302#ifdef RISCOS
9303 case '#':
9304#endif
9305 reg_pat[i++] = '.';
9306 break;
9307 case '\\':
9308 if (p[1] == NUL)
9309 break;
9310#ifdef BACKSLASH_IN_FILENAME
9311 if (!no_bslash)
9312 {
9313 /* translate:
9314 * "\x" to "\\x" e.g., "dir\file"
9315 * "\*" to "\\.*" e.g., "dir\*.c"
9316 * "\?" to "\\." e.g., "dir\??.c"
9317 * "\+" to "\+" e.g., "fileX\+.c"
9318 */
9319 if ((vim_isfilec(p[1]) || p[1] == '*' || p[1] == '?')
9320 && p[1] != '+')
9321 {
9322 reg_pat[i++] = '[';
9323 reg_pat[i++] = '\\';
9324 reg_pat[i++] = '/';
9325 reg_pat[i++] = ']';
9326 if (allow_dirs != NULL)
9327 *allow_dirs = TRUE;
9328 break;
9329 }
9330 }
9331#endif
9332 if (*++p == '?'
9333#ifdef BACKSLASH_IN_FILENAME
9334 && no_bslash
9335#endif
9336 )
9337 reg_pat[i++] = '?';
9338 else
9339 if (*p == ',')
9340 reg_pat[i++] = ',';
9341 else
9342 {
9343 if (allow_dirs != NULL && vim_ispathsep(*p)
9344#ifdef BACKSLASH_IN_FILENAME
9345 && (!no_bslash || *p != '\\')
9346#endif
9347 )
9348 *allow_dirs = TRUE;
9349 reg_pat[i++] = '\\';
9350 reg_pat[i++] = *p;
9351 }
9352 break;
9353#ifdef BACKSLASH_IN_FILENAME
9354 case '/':
9355 reg_pat[i++] = '[';
9356 reg_pat[i++] = '\\';
9357 reg_pat[i++] = '/';
9358 reg_pat[i++] = ']';
9359 if (allow_dirs != NULL)
9360 *allow_dirs = TRUE;
9361 break;
9362#endif
9363 case '{':
9364 reg_pat[i++] = '\\';
9365 reg_pat[i++] = '(';
9366 nested++;
9367 break;
9368 case '}':
9369 reg_pat[i++] = '\\';
9370 reg_pat[i++] = ')';
9371 --nested;
9372 break;
9373 case ',':
9374 if (nested)
9375 {
9376 reg_pat[i++] = '\\';
9377 reg_pat[i++] = '|';
9378 }
9379 else
9380 reg_pat[i++] = ',';
9381 break;
9382 default:
9383# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00009384 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009385 reg_pat[i++] = *p++;
9386 else
9387# endif
9388 if (allow_dirs != NULL && vim_ispathsep(*p))
9389 *allow_dirs = TRUE;
9390 reg_pat[i++] = *p;
9391 break;
9392 }
9393 }
9394 if (add_dollar)
9395 reg_pat[i++] = '$';
9396 reg_pat[i] = NUL;
9397 if (nested != 0)
9398 {
9399 if (nested < 0)
9400 EMSG(_("E219: Missing {."));
9401 else
9402 EMSG(_("E220: Missing }."));
9403 vim_free(reg_pat);
9404 reg_pat = NULL;
9405 }
9406 return reg_pat;
9407}