Merge branch 'vim' into feat/code-check
[vim_extended.git] / src / fileio.c
blob8157f1ecd07190be21eeec5f45ae9243fe202118
1 /* vi:set ts=8 sts=4 sw=4:
3 * VIM - Vi IMproved by Bram Moolenaar
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 */
11 * fileio.c: read from and write to a file
14 #if defined(MSDOS) || defined(WIN16) || defined(WIN32) || defined(_WIN64)
15 # include "vimio.h" /* for lseek(), must be before vim.h */
16 #endif
18 #if defined __EMX__
19 # include "vimio.h" /* for mktemp(), CJW 1997-12-03 */
20 #endif
22 #include "vim.h"
24 #ifdef __TANDEM
25 # include <limits.h> /* for SSIZE_MAX */
26 #endif
28 #if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
29 # include <utime.h> /* for struct utimbuf */
30 #endif
32 #define BUFSIZE 8192 /* size of normal write buffer */
33 #define SMBUFSIZE 256 /* size of emergency write buffer */
35 #ifdef FEAT_CRYPT
36 # define CRYPT_MAGIC "VimCrypt~01!" /* "01" is the version nr */
37 # define CRYPT_MAGIC_LEN 12 /* must be multiple of 4! */
38 #endif
40 /* Is there any system that doesn't have access()? */
41 #define USE_MCH_ACCESS
43 #if defined(sun) && defined(S_ISCHR)
44 # define OPEN_CHR_FILES
45 static int is_dev_fd_file(char_u *fname);
46 #endif
47 #ifdef FEAT_MBYTE
48 static char_u *next_fenc __ARGS((char_u **pp));
49 # ifdef FEAT_EVAL
50 static char_u *readfile_charconvert __ARGS((char_u *fname, char_u *fenc, int *fdp));
51 # endif
52 #endif
53 #ifdef FEAT_VIMINFO
54 static void check_marks_read __ARGS((void));
55 #endif
56 #ifdef FEAT_CRYPT
57 static char_u *check_for_cryptkey __ARGS((char_u *cryptkey, char_u *ptr, long *sizep, long *filesizep, int newfile));
58 #endif
59 #ifdef UNIX
60 static void set_file_time __ARGS((char_u *fname, time_t atime, time_t mtime));
61 #endif
62 static int set_rw_fname __ARGS((char_u *fname, char_u *sfname));
63 static int msg_add_fileformat __ARGS((int eol_type));
64 static void msg_add_eol __ARGS((void));
65 static int check_mtime __ARGS((buf_T *buf, struct stat *s));
66 static int time_differs __ARGS((long t1, long t2));
67 #ifdef FEAT_AUTOCMD
68 static int apply_autocmds_exarg __ARGS((event_T event, char_u *fname, char_u *fname_io, int force, buf_T *buf, exarg_T *eap));
69 static int au_find_group __ARGS((char_u *name));
71 # define AUGROUP_DEFAULT -1 /* default autocmd group */
72 # define AUGROUP_ERROR -2 /* erroneous autocmd group */
73 # define AUGROUP_ALL -3 /* all autocmd groups */
74 #endif
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
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
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
107 * Structure to pass arguments from buf_write() to buf_write_bytes().
109 struct bw_info
111 int bw_fd; /* file descriptor */
112 char_u *bw_buf; /* buffer with data to be written */
113 int bw_len; /* length 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 linenr_T bw_conv_error_lnum; /* first line with error or zero */
125 linenr_T bw_start_lnum; /* line number at start of buffer */
126 # ifdef USE_ICONV
127 iconv_t bw_iconv_fd; /* descriptor for iconv() or -1 */
128 # endif
129 #endif
132 static int buf_write_bytes __ARGS((struct bw_info *ip));
134 #ifdef FEAT_MBYTE
135 static linenr_T readfile_linenr __ARGS((linenr_T linecnt, char_u *p, char_u *endp));
136 static int ucs2bytes __ARGS((unsigned c, char_u **pp, int flags));
137 static int need_conversion __ARGS((char_u *fenc));
138 static int get_fio_flags __ARGS((char_u *ptr));
139 static char_u *check_for_bom __ARGS((char_u *p, long size, int *lenp, int flags));
140 static int make_bom __ARGS((char_u *buf, char_u *name));
141 # ifdef WIN3264
142 static int get_win_fio_flags __ARGS((char_u *ptr));
143 # endif
144 # ifdef MACOS_X
145 static int get_mac_fio_flags __ARGS((char_u *ptr));
146 # endif
147 #endif
148 static int move_lines __ARGS((buf_T *frombuf, buf_T *tobuf));
149 static void vim_settempdir __ARGS((char_u *tempdir));
150 #ifdef FEAT_AUTOCMD
151 static char *e_auchangedbuf = N_("E812: Autocommands changed buffer or buffer name");
152 #endif
154 void
155 filemess(buf, name, s, attr)
156 buf_T *buf;
157 char_u *name;
158 char_u *s;
159 int attr;
161 int msg_scroll_save;
163 if (msg_silent != 0)
164 return;
165 msg_add_fname(buf, name); /* put file name in IObuff with quotes */
166 /* If it's extremely long, truncate it. */
167 if (STRLEN(IObuff) > IOSIZE - 80)
168 IObuff[IOSIZE - 80] = NUL;
169 STRCAT(IObuff, s);
171 * For the first message may have to start a new line.
172 * For further ones overwrite the previous one, reset msg_scroll before
173 * calling filemess().
175 msg_scroll_save = msg_scroll;
176 if (shortmess(SHM_OVERALL) && !exiting && p_verbose == 0)
177 msg_scroll = FALSE;
178 if (!msg_scroll) /* wait a bit when overwriting an error msg */
179 check_for_delay(FALSE);
180 msg_start();
181 msg_scroll = msg_scroll_save;
182 msg_scrolled_ign = TRUE;
183 /* may truncate the message to avoid a hit-return prompt */
184 msg_outtrans_attr(msg_may_trunc(FALSE, IObuff), attr);
185 msg_clr_eos();
186 out_flush();
187 msg_scrolled_ign = FALSE;
191 * Read lines from file "fname" into the buffer after line "from".
193 * 1. We allocate blocks with lalloc, as big as possible.
194 * 2. Each block is filled with characters from the file with a single read().
195 * 3. The lines are inserted in the buffer with ml_append().
197 * (caller must check that fname != NULL, unless READ_STDIN is used)
199 * "lines_to_skip" is the number of lines that must be skipped
200 * "lines_to_read" is the number of lines that are appended
201 * When not recovering lines_to_skip is 0 and lines_to_read MAXLNUM.
203 * flags:
204 * READ_NEW starting to edit a new buffer
205 * READ_FILTER reading filter output
206 * READ_STDIN read from stdin instead of a file
207 * READ_BUFFER read from curbuf instead of a file (converting after reading
208 * stdin)
209 * READ_DUMMY read into a dummy buffer (to check if file contents changed)
211 * return FAIL for failure, OK otherwise
214 readfile(fname, sfname, from, lines_to_skip, lines_to_read, eap, flags)
215 char_u *fname;
216 char_u *sfname;
217 linenr_T from;
218 linenr_T lines_to_skip;
219 linenr_T lines_to_read;
220 exarg_T *eap; /* can be NULL! */
221 int flags;
223 int fd = 0;
224 int newfile = (flags & READ_NEW);
225 int check_readonly;
226 int filtering = (flags & READ_FILTER);
227 int read_stdin = (flags & READ_STDIN);
228 int read_buffer = (flags & READ_BUFFER);
229 int set_options = newfile || read_buffer
230 || (eap != NULL && eap->read_edit);
231 linenr_T read_buf_lnum = 1; /* next line to read from curbuf */
232 colnr_T read_buf_col = 0; /* next char to read from this line */
233 char_u c;
234 linenr_T lnum = from;
235 char_u *ptr = NULL; /* pointer into read buffer */
236 char_u *buffer = NULL; /* read buffer */
237 char_u *new_buffer = NULL; /* init to shut up gcc */
238 char_u *line_start = NULL; /* init to shut up gcc */
239 int wasempty; /* buffer was empty before reading */
240 colnr_T len;
241 long size = 0;
242 char_u *p;
243 long filesize = 0;
244 int skip_read = FALSE;
245 #ifdef FEAT_CRYPT
246 char_u *cryptkey = NULL;
247 #endif
248 int split = 0; /* number of split lines */
249 #define UNKNOWN 0x0fffffff /* file size is unknown */
250 linenr_T linecnt;
251 int error = FALSE; /* errors encountered */
252 int ff_error = EOL_UNKNOWN; /* file format with errors */
253 long linerest = 0; /* remaining chars in line */
254 #ifdef UNIX
255 int perm = 0;
256 int swap_mode = -1; /* protection bits for swap file */
257 #else
258 int perm;
259 #endif
260 int fileformat = 0; /* end-of-line format */
261 int keep_fileformat = FALSE;
262 struct stat st;
263 int file_readonly;
264 linenr_T skip_count = 0;
265 linenr_T read_count = 0;
266 int msg_save = msg_scroll;
267 linenr_T read_no_eol_lnum = 0; /* non-zero lnum when last line of
268 * last read was missing the eol */
269 int try_mac = (vim_strchr(p_ffs, 'm') != NULL);
270 int try_dos = (vim_strchr(p_ffs, 'd') != NULL);
271 int try_unix = (vim_strchr(p_ffs, 'x') != NULL);
272 int file_rewind = FALSE;
273 #ifdef FEAT_MBYTE
274 int can_retry;
275 linenr_T conv_error = 0; /* line nr with conversion error */
276 linenr_T illegal_byte = 0; /* line nr with illegal byte */
277 int keep_dest_enc = FALSE; /* don't retry when char doesn't fit
278 in destination encoding */
279 int bad_char_behavior = BAD_REPLACE;
280 /* BAD_KEEP, BAD_DROP or character to
281 * replace with */
282 char_u *tmpname = NULL; /* name of 'charconvert' output file */
283 int fio_flags = 0;
284 char_u *fenc; /* fileencoding to use */
285 int fenc_alloced; /* fenc_next is in allocated memory */
286 char_u *fenc_next = NULL; /* next item in 'fencs' or NULL */
287 int advance_fenc = FALSE;
288 long real_size = 0;
289 # ifdef USE_ICONV
290 iconv_t iconv_fd = (iconv_t)-1; /* descriptor for iconv() or -1 */
291 # ifdef FEAT_EVAL
292 int did_iconv = FALSE; /* TRUE when iconv() failed and trying
293 'charconvert' next */
294 # endif
295 # endif
296 int converted = FALSE; /* TRUE if conversion done */
297 int notconverted = FALSE; /* TRUE if conversion wanted but it
298 wasn't possible */
299 char_u conv_rest[CONV_RESTLEN];
300 int conv_restlen = 0; /* nr of bytes in conv_rest[] */
301 #endif
303 #ifdef FEAT_AUTOCMD
304 /* Remember the initial values of curbuf, curbuf->b_ffname and
305 * curbuf->b_fname to detect whether they are altered as a result of
306 * executing nasty autocommands. Also check if "fname" and "sfname"
307 * point to one of these values. */
308 buf_T *old_curbuf = curbuf;
309 char_u *old_b_ffname = curbuf->b_ffname;
310 char_u *old_b_fname = curbuf->b_fname;
311 int using_b_ffname = (fname == curbuf->b_ffname)
312 || (sfname == curbuf->b_ffname);
313 int using_b_fname = (fname == curbuf->b_fname)
314 || (sfname == curbuf->b_fname);
315 #endif
316 write_no_eol_lnum = 0; /* in case it was set by the previous read */
319 * If there is no file name yet, use the one for the read file.
320 * BF_NOTEDITED is set to reflect this.
321 * Don't do this for a read from a filter.
322 * Only do this when 'cpoptions' contains the 'f' flag.
324 if (curbuf->b_ffname == NULL
325 && !filtering
326 && fname != NULL
327 && vim_strchr(p_cpo, CPO_FNAMER) != NULL
328 && !(flags & READ_DUMMY))
330 if (set_rw_fname(fname, sfname) == FAIL)
331 return FAIL;
334 /* After reading a file the cursor line changes but we don't want to
335 * display the line. */
336 ex_no_reprint = TRUE;
338 /* don't display the file info for another buffer now */
339 need_fileinfo = FALSE;
342 * For Unix: Use the short file name whenever possible.
343 * Avoids problems with networks and when directory names are changed.
344 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
345 * another directory, which we don't detect.
347 if (sfname == NULL)
348 sfname = fname;
349 #if defined(UNIX) || defined(__EMX__)
350 fname = sfname;
351 #endif
353 #ifdef FEAT_AUTOCMD
355 * The BufReadCmd and FileReadCmd events intercept the reading process by
356 * executing the associated commands instead.
358 if (!filtering && !read_stdin && !read_buffer)
360 pos_T pos;
362 pos = curbuf->b_op_start;
364 /* Set '[ mark to the line above where the lines go (line 1 if zero). */
365 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
366 curbuf->b_op_start.col = 0;
368 if (newfile)
370 if (apply_autocmds_exarg(EVENT_BUFREADCMD, NULL, sfname,
371 FALSE, curbuf, eap))
372 #ifdef FEAT_EVAL
373 return aborting() ? FAIL : OK;
374 #else
375 return OK;
376 #endif
378 else if (apply_autocmds_exarg(EVENT_FILEREADCMD, sfname, sfname,
379 FALSE, NULL, eap))
380 #ifdef FEAT_EVAL
381 return aborting() ? FAIL : OK;
382 #else
383 return OK;
384 #endif
386 curbuf->b_op_start = pos;
388 #endif
390 if ((shortmess(SHM_OVER) || curbuf->b_help) && p_verbose == 0)
391 msg_scroll = FALSE; /* overwrite previous file message */
392 else
393 msg_scroll = TRUE; /* don't overwrite previous file message */
396 * If the name ends in a path separator, we can't open it. Check here,
397 * because reading the file may actually work, but then creating the swap
398 * file may destroy it! Reported on MS-DOS and Win 95.
399 * If the name is too long we might crash further on, quit here.
401 if (fname != NULL && *fname != NUL)
403 p = fname + STRLEN(fname);
404 if (after_pathsep(fname, p) || STRLEN(fname) >= MAXPATHL)
406 filemess(curbuf, fname, (char_u *)_("Illegal file name"), 0);
407 msg_end();
408 msg_scroll = msg_save;
409 return FAIL;
413 #ifdef UNIX
415 * On Unix it is possible to read a directory, so we have to
416 * check for it before the mch_open().
418 if (!read_stdin && !read_buffer)
420 perm = mch_getperm(fname);
421 if (perm >= 0 && !S_ISREG(perm) /* not a regular file ... */
422 # ifdef S_ISFIFO
423 && !S_ISFIFO(perm) /* ... or fifo */
424 # endif
425 # ifdef S_ISSOCK
426 && !S_ISSOCK(perm) /* ... or socket */
427 # endif
428 # ifdef OPEN_CHR_FILES
429 && !(S_ISCHR(perm) && is_dev_fd_file(fname))
430 /* ... or a character special file named /dev/fd/<n> */
431 # endif
434 if (S_ISDIR(perm))
435 filemess(curbuf, fname, (char_u *)_("is a directory"), 0);
436 else
437 filemess(curbuf, fname, (char_u *)_("is not a file"), 0);
438 msg_end();
439 msg_scroll = msg_save;
440 return FAIL;
443 # if defined(MSDOS) || defined(MSWIN) || defined(OS2)
445 * MS-Windows allows opening a device, but we will probably get stuck
446 * trying to read it.
448 if (!p_odev && mch_nodetype(fname) == NODE_WRITABLE)
450 filemess(curbuf, fname, (char_u *)_("is a device (disabled with 'opendevice' option)"), 0);
451 msg_end();
452 msg_scroll = msg_save;
453 return FAIL;
455 # endif
457 #endif
459 /* set default 'fileformat' */
460 if (set_options)
462 if (eap != NULL && eap->force_ff != 0)
463 set_fileformat(get_fileformat_force(curbuf, eap), OPT_LOCAL);
464 else if (*p_ffs != NUL)
465 set_fileformat(default_fileformat(), OPT_LOCAL);
468 /* set or reset 'binary' */
469 if (eap != NULL && eap->force_bin != 0)
471 int oldval = curbuf->b_p_bin;
473 curbuf->b_p_bin = (eap->force_bin == FORCE_BIN);
474 set_options_bin(oldval, curbuf->b_p_bin, OPT_LOCAL);
478 * When opening a new file we take the readonly flag from the file.
479 * Default is r/w, can be set to r/o below.
480 * Don't reset it when in readonly mode
481 * Only set/reset b_p_ro when BF_CHECK_RO is set.
483 check_readonly = (newfile && (curbuf->b_flags & BF_CHECK_RO));
484 if (check_readonly && !readonlymode)
485 curbuf->b_p_ro = FALSE;
487 if (newfile && !read_stdin && !read_buffer)
489 /* Remember time of file.
490 * For RISCOS, also remember the filetype.
492 if (mch_stat((char *)fname, &st) >= 0)
494 buf_store_time(curbuf, &st, fname);
495 curbuf->b_mtime_read = curbuf->b_mtime;
497 #if defined(RISCOS) && defined(FEAT_OSFILETYPE)
498 /* Read the filetype into the buffer local filetype option. */
499 mch_read_filetype(fname);
500 #endif
501 #ifdef UNIX
503 * Use the protection bits of the original file for the swap file.
504 * This makes it possible for others to read the name of the
505 * edited file from the swapfile, but only if they can read the
506 * edited file.
507 * Remove the "write" and "execute" bits for group and others
508 * (they must not write the swapfile).
509 * Add the "read" and "write" bits for the user, otherwise we may
510 * not be able to write to the file ourselves.
511 * Setting the bits is done below, after creating the swap file.
513 swap_mode = (st.st_mode & 0644) | 0600;
514 #endif
515 #ifdef FEAT_CW_EDITOR
516 /* Get the FSSpec on MacOS
517 * TODO: Update it properly when the buffer name changes
519 (void)GetFSSpecFromPath(curbuf->b_ffname, &curbuf->b_FSSpec);
520 #endif
521 #ifdef VMS
522 curbuf->b_fab_rfm = st.st_fab_rfm;
523 curbuf->b_fab_rat = st.st_fab_rat;
524 curbuf->b_fab_mrs = st.st_fab_mrs;
525 #endif
527 else
529 curbuf->b_mtime = 0;
530 curbuf->b_mtime_read = 0;
531 curbuf->b_orig_size = 0;
532 curbuf->b_orig_mode = 0;
535 /* Reset the "new file" flag. It will be set again below when the
536 * file doesn't exist. */
537 curbuf->b_flags &= ~(BF_NEW | BF_NEW_W);
541 * for UNIX: check readonly with perm and mch_access()
542 * for RISCOS: same as Unix, otherwise file gets re-datestamped!
543 * for MSDOS and Amiga: check readonly by trying to open the file for writing
545 file_readonly = FALSE;
546 if (read_stdin)
548 #if defined(MSDOS) || defined(MSWIN) || defined(OS2)
549 /* Force binary I/O on stdin to avoid CR-LF -> LF conversion. */
550 setmode(0, O_BINARY);
551 #endif
553 else if (!read_buffer)
555 #ifdef USE_MCH_ACCESS
556 if (
557 # ifdef UNIX
558 !(perm & 0222) ||
559 # endif
560 mch_access((char *)fname, W_OK))
561 file_readonly = TRUE;
562 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
563 #else
564 if (!newfile
565 || readonlymode
566 || (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0)
568 file_readonly = TRUE;
569 /* try to open ro */
570 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
572 #endif
575 if (fd < 0) /* cannot open at all */
577 #ifndef UNIX
578 int isdir_f;
579 #endif
580 msg_scroll = msg_save;
581 #ifndef UNIX
583 * On MSDOS and Amiga we can't open a directory, check here.
585 isdir_f = (mch_isdir(fname));
586 perm = mch_getperm(fname); /* check if the file exists */
587 if (isdir_f)
589 filemess(curbuf, sfname, (char_u *)_("is a directory"), 0);
590 curbuf->b_p_ro = TRUE; /* must use "w!" now */
592 else
593 #endif
594 if (newfile)
596 if (perm < 0)
599 * Set the 'new-file' flag, so that when the file has
600 * been created by someone else, a ":w" will complain.
602 curbuf->b_flags |= BF_NEW;
604 /* Create a swap file now, so that other Vims are warned
605 * that we are editing this file. Don't do this for a
606 * "nofile" or "nowrite" buffer type. */
607 #ifdef FEAT_QUICKFIX
608 if (!bt_dontwrite(curbuf))
609 #endif
611 check_need_swap(newfile);
612 #ifdef FEAT_AUTOCMD
613 /* SwapExists autocommand may mess things up */
614 if (curbuf != old_curbuf
615 || (using_b_ffname
616 && (old_b_ffname != curbuf->b_ffname))
617 || (using_b_fname
618 && (old_b_fname != curbuf->b_fname)))
620 EMSG(_(e_auchangedbuf));
621 return FAIL;
623 #endif
625 if (dir_of_file_exists(fname))
626 filemess(curbuf, sfname, (char_u *)_("[New File]"), 0);
627 else
628 filemess(curbuf, sfname,
629 (char_u *)_("[New DIRECTORY]"), 0);
630 #ifdef FEAT_VIMINFO
631 /* Even though this is a new file, it might have been
632 * edited before and deleted. Get the old marks. */
633 check_marks_read();
634 #endif
635 #ifdef FEAT_MBYTE
636 if (eap != NULL && eap->force_enc != 0)
638 /* set forced 'fileencoding' */
639 fenc = enc_canonize(eap->cmd + eap->force_enc);
640 if (fenc != NULL)
641 set_string_option_direct((char_u *)"fenc", -1,
642 fenc, OPT_FREE|OPT_LOCAL, 0);
643 vim_free(fenc);
645 #endif
646 #ifdef FEAT_AUTOCMD
647 apply_autocmds_exarg(EVENT_BUFNEWFILE, sfname, sfname,
648 FALSE, curbuf, eap);
649 #endif
650 /* remember the current fileformat */
651 save_file_ff(curbuf);
653 #if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
654 if (aborting()) /* autocmds may abort script processing */
655 return FAIL;
656 #endif
657 return OK; /* a new file is not an error */
659 else
661 filemess(curbuf, sfname, (char_u *)(
662 # ifdef EFBIG
663 (errno == EFBIG) ? _("[File too big]") :
664 # endif
665 _("[Permission Denied]")), 0);
666 curbuf->b_p_ro = TRUE; /* must use "w!" now */
670 return FAIL;
674 * Only set the 'ro' flag for readonly files the first time they are
675 * loaded. Help files always get readonly mode
677 if ((check_readonly && file_readonly) || curbuf->b_help)
678 curbuf->b_p_ro = TRUE;
680 if (set_options)
682 /* Don't change 'eol' if reading from buffer as it will already be
683 * correctly set when reading stdin. */
684 if (!read_buffer)
686 curbuf->b_p_eol = TRUE;
687 curbuf->b_start_eol = TRUE;
689 #ifdef FEAT_MBYTE
690 curbuf->b_p_bomb = FALSE;
691 curbuf->b_start_bomb = FALSE;
692 #endif
695 /* Create a swap file now, so that other Vims are warned that we are
696 * editing this file.
697 * Don't do this for a "nofile" or "nowrite" buffer type. */
698 #ifdef FEAT_QUICKFIX
699 if (!bt_dontwrite(curbuf))
700 #endif
702 check_need_swap(newfile);
703 #ifdef FEAT_AUTOCMD
704 if (!read_stdin && (curbuf != old_curbuf
705 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
706 || (using_b_fname && (old_b_fname != curbuf->b_fname))))
708 EMSG(_(e_auchangedbuf));
709 if (!read_buffer)
710 close(fd);
711 return FAIL;
713 #endif
714 #ifdef UNIX
715 /* Set swap file protection bits after creating it. */
716 if (swap_mode > 0 && curbuf->b_ml.ml_mfp != NULL
717 && curbuf->b_ml.ml_mfp->mf_fname != NULL)
718 (void)mch_setperm(curbuf->b_ml.ml_mfp->mf_fname, (long)swap_mode);
719 #endif
722 #if defined(HAS_SWAP_EXISTS_ACTION)
723 /* If "Quit" selected at ATTENTION dialog, don't load the file */
724 if (swap_exists_action == SEA_QUIT)
726 if (!read_buffer && !read_stdin)
727 close(fd);
728 return FAIL;
730 #endif
732 ++no_wait_return; /* don't wait for return yet */
735 * Set '[ mark to the line above where the lines go (line 1 if zero).
737 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
738 curbuf->b_op_start.col = 0;
740 #ifdef FEAT_AUTOCMD
741 if (!read_buffer)
743 int m = msg_scroll;
744 int n = msg_scrolled;
747 * The file must be closed again, the autocommands may want to change
748 * the file before reading it.
750 if (!read_stdin)
751 close(fd); /* ignore errors */
754 * The output from the autocommands should not overwrite anything and
755 * should not be overwritten: Set msg_scroll, restore its value if no
756 * output was done.
758 msg_scroll = TRUE;
759 if (filtering)
760 apply_autocmds_exarg(EVENT_FILTERREADPRE, NULL, sfname,
761 FALSE, curbuf, eap);
762 else if (read_stdin)
763 apply_autocmds_exarg(EVENT_STDINREADPRE, NULL, sfname,
764 FALSE, curbuf, eap);
765 else if (newfile)
766 apply_autocmds_exarg(EVENT_BUFREADPRE, NULL, sfname,
767 FALSE, curbuf, eap);
768 else
769 apply_autocmds_exarg(EVENT_FILEREADPRE, sfname, sfname,
770 FALSE, NULL, eap);
771 if (msg_scrolled == n)
772 msg_scroll = m;
774 #ifdef FEAT_EVAL
775 if (aborting()) /* autocmds may abort script processing */
777 --no_wait_return;
778 msg_scroll = msg_save;
779 curbuf->b_p_ro = TRUE; /* must use "w!" now */
780 return FAIL;
782 #endif
784 * Don't allow the autocommands to change the current buffer.
785 * Try to re-open the file.
787 * Don't allow the autocommands to change the buffer name either
788 * (cd for example) if it invalidates fname or sfname.
790 if (!read_stdin && (curbuf != old_curbuf
791 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
792 || (using_b_fname && (old_b_fname != curbuf->b_fname))
793 || (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) < 0))
795 --no_wait_return;
796 msg_scroll = msg_save;
797 if (fd < 0)
798 EMSG(_("E200: *ReadPre autocommands made the file unreadable"));
799 else
800 EMSG(_("E201: *ReadPre autocommands must not change current buffer"));
801 curbuf->b_p_ro = TRUE; /* must use "w!" now */
802 return FAIL;
805 #endif /* FEAT_AUTOCMD */
807 /* Autocommands may add lines to the file, need to check if it is empty */
808 wasempty = (curbuf->b_ml.ml_flags & ML_EMPTY);
810 if (!recoverymode && !filtering && !(flags & READ_DUMMY))
813 * Show the user that we are busy reading the input. Sometimes this
814 * may take a while. When reading from stdin another program may
815 * still be running, don't move the cursor to the last line, unless
816 * always using the GUI.
818 if (read_stdin)
820 #ifndef ALWAYS_USE_GUI
821 mch_msg(_("Vim: Reading from stdin...\n"));
822 #endif
823 #ifdef FEAT_GUI
824 /* Also write a message in the GUI window, if there is one. */
825 if (gui.in_use && !gui.dying && !gui.starting)
827 p = (char_u *)_("Reading from stdin...");
828 gui_write(p, (int)STRLEN(p));
830 #endif
832 else if (!read_buffer)
833 filemess(curbuf, sfname, (char_u *)"", 0);
836 msg_scroll = FALSE; /* overwrite the file message */
839 * Set linecnt now, before the "retry" caused by a wrong guess for
840 * fileformat, and after the autocommands, which may change them.
842 linecnt = curbuf->b_ml.ml_line_count;
844 #ifdef FEAT_MBYTE
845 /* "++bad=" argument. */
846 if (eap != NULL && eap->bad_char != 0)
848 bad_char_behavior = eap->bad_char;
849 if (set_options)
850 curbuf->b_bad_char = eap->bad_char;
852 else
853 curbuf->b_bad_char = 0;
856 * Decide which 'encoding' to use or use first.
858 if (eap != NULL && eap->force_enc != 0)
860 fenc = enc_canonize(eap->cmd + eap->force_enc);
861 fenc_alloced = TRUE;
862 keep_dest_enc = TRUE;
864 else if (curbuf->b_p_bin)
866 fenc = (char_u *)""; /* binary: don't convert */
867 fenc_alloced = FALSE;
869 else if (curbuf->b_help)
871 char_u firstline[80];
872 int fc;
874 /* Help files are either utf-8 or latin1. Try utf-8 first, if this
875 * fails it must be latin1.
876 * Always do this when 'encoding' is "utf-8". Otherwise only do
877 * this when needed to avoid [converted] remarks all the time.
878 * It is needed when the first line contains non-ASCII characters.
879 * That is only in *.??x files. */
880 fenc = (char_u *)"latin1";
881 c = enc_utf8;
882 if (!c && !read_stdin)
884 fc = fname[STRLEN(fname) - 1];
885 if (TOLOWER_ASC(fc) == 'x')
887 /* Read the first line (and a bit more). Immediately rewind to
888 * the start of the file. If the read() fails "len" is -1. */
889 len = vim_read(fd, firstline, 80);
890 lseek(fd, (off_t)0L, SEEK_SET);
891 for (p = firstline; p < firstline + len; ++p)
892 if (*p >= 0x80)
894 c = TRUE;
895 break;
900 if (c)
902 fenc_next = fenc;
903 fenc = (char_u *)"utf-8";
905 /* When the file is utf-8 but a character doesn't fit in
906 * 'encoding' don't retry. In help text editing utf-8 bytes
907 * doesn't make sense. */
908 if (!enc_utf8)
909 keep_dest_enc = TRUE;
911 fenc_alloced = FALSE;
913 else if (*p_fencs == NUL)
915 fenc = curbuf->b_p_fenc; /* use format from buffer */
916 fenc_alloced = FALSE;
918 else
920 fenc_next = p_fencs; /* try items in 'fileencodings' */
921 fenc = next_fenc(&fenc_next);
922 fenc_alloced = TRUE;
924 #endif
927 * Jump back here to retry reading the file in different ways.
928 * Reasons to retry:
929 * - encoding conversion failed: try another one from "fenc_next"
930 * - BOM detected and fenc was set, need to setup conversion
931 * - "fileformat" check failed: try another
933 * Variables set for special retry actions:
934 * "file_rewind" Rewind the file to start reading it again.
935 * "advance_fenc" Advance "fenc" using "fenc_next".
936 * "skip_read" Re-use already read bytes (BOM detected).
937 * "did_iconv" iconv() conversion failed, try 'charconvert'.
938 * "keep_fileformat" Don't reset "fileformat".
940 * Other status indicators:
941 * "tmpname" When != NULL did conversion with 'charconvert'.
942 * Output file has to be deleted afterwards.
943 * "iconv_fd" When != -1 did conversion with iconv().
945 retry:
947 if (file_rewind)
949 if (read_buffer)
951 read_buf_lnum = 1;
952 read_buf_col = 0;
954 else if (read_stdin || lseek(fd, (off_t)0L, SEEK_SET) != 0)
956 /* Can't rewind the file, give up. */
957 error = TRUE;
958 goto failed;
960 /* Delete the previously read lines. */
961 while (lnum > from)
962 ml_delete(lnum--, FALSE);
963 file_rewind = FALSE;
964 #ifdef FEAT_MBYTE
965 if (set_options)
967 curbuf->b_p_bomb = FALSE;
968 curbuf->b_start_bomb = FALSE;
970 conv_error = 0;
971 #endif
975 * When retrying with another "fenc" and the first time "fileformat"
976 * will be reset.
978 if (keep_fileformat)
979 keep_fileformat = FALSE;
980 else
982 if (eap != NULL && eap->force_ff != 0)
984 fileformat = get_fileformat_force(curbuf, eap);
985 try_unix = try_dos = try_mac = FALSE;
987 else if (curbuf->b_p_bin)
988 fileformat = EOL_UNIX; /* binary: use Unix format */
989 else if (*p_ffs == NUL)
990 fileformat = get_fileformat(curbuf);/* use format from buffer */
991 else
992 fileformat = EOL_UNKNOWN; /* detect from file */
995 #ifdef FEAT_MBYTE
996 # ifdef USE_ICONV
997 if (iconv_fd != (iconv_t)-1)
999 /* aborted conversion with iconv(), close the descriptor */
1000 iconv_close(iconv_fd);
1001 iconv_fd = (iconv_t)-1;
1003 # endif
1005 if (advance_fenc)
1008 * Try the next entry in 'fileencodings'.
1010 advance_fenc = FALSE;
1012 if (eap != NULL && eap->force_enc != 0)
1014 /* Conversion given with "++cc=" wasn't possible, read
1015 * without conversion. */
1016 notconverted = TRUE;
1017 conv_error = 0;
1018 if (fenc_alloced)
1019 vim_free(fenc);
1020 fenc = (char_u *)"";
1021 fenc_alloced = FALSE;
1023 else
1025 if (fenc_alloced)
1026 vim_free(fenc);
1027 if (fenc_next != NULL)
1029 fenc = next_fenc(&fenc_next);
1030 fenc_alloced = (fenc_next != NULL);
1032 else
1034 fenc = (char_u *)"";
1035 fenc_alloced = FALSE;
1038 if (tmpname != NULL)
1040 mch_remove(tmpname); /* delete converted file */
1041 vim_free(tmpname);
1042 tmpname = NULL;
1047 * Conversion may be required when the encoding of the file is different
1048 * from 'encoding' or 'encoding' is UTF-16, UCS-2 or UCS-4.
1050 fio_flags = 0;
1051 converted = need_conversion(fenc);
1052 if (converted)
1055 /* "ucs-bom" means we need to check the first bytes of the file
1056 * for a BOM. */
1057 if (STRCMP(fenc, ENC_UCSBOM) == 0)
1058 fio_flags = FIO_UCSBOM;
1061 * Check if UCS-2/4 or Latin1 to UTF-8 conversion needs to be
1062 * done. This is handled below after read(). Prepare the
1063 * fio_flags to avoid having to parse the string each time.
1064 * Also check for Unicode to Latin1 conversion, because iconv()
1065 * appears not to handle this correctly. This works just like
1066 * conversion to UTF-8 except how the resulting character is put in
1067 * the buffer.
1069 else if (enc_utf8 || STRCMP(p_enc, "latin1") == 0)
1070 fio_flags = get_fio_flags(fenc);
1072 # ifdef WIN3264
1074 * Conversion from an MS-Windows codepage to UTF-8 or another codepage
1075 * is handled with MultiByteToWideChar().
1077 if (fio_flags == 0)
1078 fio_flags = get_win_fio_flags(fenc);
1079 # endif
1081 # ifdef MACOS_X
1082 /* Conversion from Apple MacRoman to latin1 or UTF-8 */
1083 if (fio_flags == 0)
1084 fio_flags = get_mac_fio_flags(fenc);
1085 # endif
1087 # ifdef USE_ICONV
1089 * Try using iconv() if we can't convert internally.
1091 if (fio_flags == 0
1092 # ifdef FEAT_EVAL
1093 && !did_iconv
1094 # endif
1096 iconv_fd = (iconv_t)my_iconv_open(
1097 enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc);
1098 # endif
1100 # ifdef FEAT_EVAL
1102 * Use the 'charconvert' expression when conversion is required
1103 * and we can't do it internally or with iconv().
1105 if (fio_flags == 0 && !read_stdin && !read_buffer && *p_ccv != NUL
1106 # ifdef USE_ICONV
1107 && iconv_fd == (iconv_t)-1
1108 # endif
1111 # ifdef USE_ICONV
1112 did_iconv = FALSE;
1113 # endif
1114 /* Skip conversion when it's already done (retry for wrong
1115 * "fileformat"). */
1116 if (tmpname == NULL)
1118 tmpname = readfile_charconvert(fname, fenc, &fd);
1119 if (tmpname == NULL)
1121 /* Conversion failed. Try another one. */
1122 advance_fenc = TRUE;
1123 if (fd < 0)
1125 /* Re-opening the original file failed! */
1126 EMSG(_("E202: Conversion made file unreadable!"));
1127 error = TRUE;
1128 goto failed;
1130 goto retry;
1134 else
1135 # endif
1137 if (fio_flags == 0
1138 # ifdef USE_ICONV
1139 && iconv_fd == (iconv_t)-1
1140 # endif
1143 /* Conversion wanted but we can't.
1144 * Try the next conversion in 'fileencodings' */
1145 advance_fenc = TRUE;
1146 goto retry;
1151 /* Set "can_retry" when it's possible to rewind the file and try with
1152 * another "fenc" value. It's FALSE when no other "fenc" to try, reading
1153 * stdin or fixed at a specific encoding. */
1154 can_retry = (*fenc != NUL && !read_stdin && !keep_dest_enc);
1155 #endif
1157 if (!skip_read)
1159 linerest = 0;
1160 filesize = 0;
1161 skip_count = lines_to_skip;
1162 read_count = lines_to_read;
1163 #ifdef FEAT_MBYTE
1164 conv_restlen = 0;
1165 #endif
1168 while (!error && !got_int)
1171 * We allocate as much space for the file as we can get, plus
1172 * space for the old line plus room for one terminating NUL.
1173 * The amount is limited by the fact that read() only can read
1174 * upto max_unsigned characters (and other things).
1176 #if SIZEOF_INT <= 2
1177 if (linerest >= 0x7ff0)
1179 ++split;
1180 *ptr = NL; /* split line by inserting a NL */
1181 size = 1;
1183 else
1184 #endif
1186 if (!skip_read)
1188 #if SIZEOF_INT > 2
1189 # if defined(SSIZE_MAX) && (SSIZE_MAX < 0x10000L)
1190 size = SSIZE_MAX; /* use max I/O size, 52K */
1191 # else
1192 size = 0x10000L; /* use buffer >= 64K */
1193 # endif
1194 #else
1195 size = 0x7ff0L - linerest; /* limit buffer to 32K */
1196 #endif
1198 for ( ; size >= 10; size = (long)((long_u)size >> 1))
1200 if ((new_buffer = lalloc((long_u)(size + linerest + 1),
1201 FALSE)) != NULL)
1202 break;
1204 if (new_buffer == NULL)
1206 do_outofmem_msg((long_u)(size * 2 + linerest + 1));
1207 error = TRUE;
1208 break;
1210 if (linerest) /* copy characters from the previous buffer */
1211 mch_memmove(new_buffer, ptr - linerest, (size_t)linerest);
1212 vim_free(buffer);
1213 buffer = new_buffer;
1214 ptr = buffer + linerest;
1215 line_start = buffer;
1217 #ifdef FEAT_MBYTE
1218 /* May need room to translate into.
1219 * For iconv() we don't really know the required space, use a
1220 * factor ICONV_MULT.
1221 * latin1 to utf-8: 1 byte becomes up to 2 bytes
1222 * utf-16 to utf-8: 2 bytes become up to 3 bytes, 4 bytes
1223 * become up to 4 bytes, size must be multiple of 2
1224 * ucs-2 to utf-8: 2 bytes become up to 3 bytes, size must be
1225 * multiple of 2
1226 * ucs-4 to utf-8: 4 bytes become up to 6 bytes, size must be
1227 * multiple of 4 */
1228 real_size = (int)size;
1229 # ifdef USE_ICONV
1230 if (iconv_fd != (iconv_t)-1)
1231 size = size / ICONV_MULT;
1232 else
1233 # endif
1234 if (fio_flags & FIO_LATIN1)
1235 size = size / 2;
1236 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1237 size = (size * 2 / 3) & ~1;
1238 else if (fio_flags & FIO_UCS4)
1239 size = (size * 2 / 3) & ~3;
1240 else if (fio_flags == FIO_UCSBOM)
1241 size = size / ICONV_MULT; /* worst case */
1242 # ifdef WIN3264
1243 else if (fio_flags & FIO_CODEPAGE)
1244 size = size / ICONV_MULT; /* also worst case */
1245 # endif
1246 # ifdef MACOS_X
1247 else if (fio_flags & FIO_MACROMAN)
1248 size = size / ICONV_MULT; /* also worst case */
1249 # endif
1250 #endif
1252 #ifdef FEAT_MBYTE
1253 if (conv_restlen > 0)
1255 /* Insert unconverted bytes from previous line. */
1256 mch_memmove(ptr, conv_rest, conv_restlen);
1257 ptr += conv_restlen;
1258 size -= conv_restlen;
1260 #endif
1262 if (read_buffer)
1265 * Read bytes from curbuf. Used for converting text read
1266 * from stdin.
1268 if (read_buf_lnum > from)
1269 size = 0;
1270 else
1272 int n, ni;
1273 long tlen;
1275 tlen = 0;
1276 for (;;)
1278 p = ml_get(read_buf_lnum) + read_buf_col;
1279 n = (int)STRLEN(p);
1280 if ((int)tlen + n + 1 > size)
1282 /* Filled up to "size", append partial line.
1283 * Change NL to NUL to reverse the effect done
1284 * below. */
1285 n = (int)(size - tlen);
1286 for (ni = 0; ni < n; ++ni)
1288 if (p[ni] == NL)
1289 ptr[tlen++] = NUL;
1290 else
1291 ptr[tlen++] = p[ni];
1293 read_buf_col += n;
1294 break;
1296 else
1298 /* Append whole line and new-line. Change NL
1299 * to NUL to reverse the effect done below. */
1300 for (ni = 0; ni < n; ++ni)
1302 if (p[ni] == NL)
1303 ptr[tlen++] = NUL;
1304 else
1305 ptr[tlen++] = p[ni];
1307 ptr[tlen++] = NL;
1308 read_buf_col = 0;
1309 if (++read_buf_lnum > from)
1311 /* When the last line didn't have an
1312 * end-of-line don't add it now either. */
1313 if (!curbuf->b_p_eol)
1314 --tlen;
1315 size = tlen;
1316 break;
1322 else
1325 * Read bytes from the file.
1327 size = vim_read(fd, ptr, size);
1330 if (size <= 0)
1332 if (size < 0) /* read error */
1333 error = TRUE;
1334 #ifdef FEAT_MBYTE
1335 else if (conv_restlen > 0)
1338 * Reached end-of-file but some trailing bytes could
1339 * not be converted. Truncated file?
1342 /* When we did a conversion report an error. */
1343 if (fio_flags != 0
1344 # ifdef USE_ICONV
1345 || iconv_fd != (iconv_t)-1
1346 # endif
1349 if (conv_error == 0)
1350 conv_error = curbuf->b_ml.ml_line_count
1351 - linecnt + 1;
1353 /* Remember the first linenr with an illegal byte */
1354 else if (illegal_byte == 0)
1355 illegal_byte = curbuf->b_ml.ml_line_count
1356 - linecnt + 1;
1357 if (bad_char_behavior == BAD_DROP)
1359 *(ptr - conv_restlen) = NUL;
1360 conv_restlen = 0;
1362 else
1364 /* Replace the trailing bytes with the replacement
1365 * character if we were converting; if we weren't,
1366 * leave the UTF8 checking code to do it, as it
1367 * works slightly differently. */
1368 if (bad_char_behavior != BAD_KEEP && (fio_flags != 0
1369 # ifdef USE_ICONV
1370 || iconv_fd != (iconv_t)-1
1371 # endif
1374 while (conv_restlen > 0)
1376 *(--ptr) = bad_char_behavior;
1377 --conv_restlen;
1380 fio_flags = 0; /* don't convert this */
1381 # ifdef USE_ICONV
1382 if (iconv_fd != (iconv_t)-1)
1384 iconv_close(iconv_fd);
1385 iconv_fd = (iconv_t)-1;
1387 # endif
1390 #endif
1393 #ifdef FEAT_CRYPT
1395 * At start of file: Check for magic number of encryption.
1397 if (filesize == 0)
1398 cryptkey = check_for_cryptkey(cryptkey, ptr, &size,
1399 &filesize, newfile);
1401 * Decrypt the read bytes.
1403 if (cryptkey != NULL && size > 0)
1404 for (p = ptr; p < ptr + size; ++p)
1405 ZDECODE(*p);
1406 #endif
1408 skip_read = FALSE;
1410 #ifdef FEAT_MBYTE
1412 * At start of file (or after crypt magic number): Check for BOM.
1413 * Also check for a BOM for other Unicode encodings, but not after
1414 * converting with 'charconvert' or when a BOM has already been
1415 * found.
1417 if ((filesize == 0
1418 # ifdef FEAT_CRYPT
1419 || (filesize == CRYPT_MAGIC_LEN && cryptkey != NULL)
1420 # endif
1422 && (fio_flags == FIO_UCSBOM
1423 || (!curbuf->b_p_bomb
1424 && tmpname == NULL
1425 && (*fenc == 'u' || (*fenc == NUL && enc_utf8)))))
1427 char_u *ccname;
1428 int blen;
1430 /* no BOM detection in a short file or in binary mode */
1431 if (size < 2 || curbuf->b_p_bin)
1432 ccname = NULL;
1433 else
1434 ccname = check_for_bom(ptr, size, &blen,
1435 fio_flags == FIO_UCSBOM ? FIO_ALL : get_fio_flags(fenc));
1436 if (ccname != NULL)
1438 /* Remove BOM from the text */
1439 filesize += blen;
1440 size -= blen;
1441 mch_memmove(ptr, ptr + blen, (size_t)size);
1442 if (set_options)
1444 curbuf->b_p_bomb = TRUE;
1445 curbuf->b_start_bomb = TRUE;
1449 if (fio_flags == FIO_UCSBOM)
1451 if (ccname == NULL)
1453 /* No BOM detected: retry with next encoding. */
1454 advance_fenc = TRUE;
1456 else
1458 /* BOM detected: set "fenc" and jump back */
1459 if (fenc_alloced)
1460 vim_free(fenc);
1461 fenc = ccname;
1462 fenc_alloced = FALSE;
1464 /* retry reading without getting new bytes or rewinding */
1465 skip_read = TRUE;
1466 goto retry;
1470 /* Include not converted bytes. */
1471 ptr -= conv_restlen;
1472 size += conv_restlen;
1473 conv_restlen = 0;
1474 #endif
1476 * Break here for a read error or end-of-file.
1478 if (size <= 0)
1479 break;
1481 #ifdef FEAT_MBYTE
1483 # ifdef USE_ICONV
1484 if (iconv_fd != (iconv_t)-1)
1487 * Attempt conversion of the read bytes to 'encoding' using
1488 * iconv().
1490 const char *fromp;
1491 char *top;
1492 size_t from_size;
1493 size_t to_size;
1495 fromp = (char *)ptr;
1496 from_size = size;
1497 ptr += size;
1498 top = (char *)ptr;
1499 to_size = real_size - size;
1502 * If there is conversion error or not enough room try using
1503 * another conversion. Except for when there is no
1504 * alternative (help files).
1506 while ((iconv(iconv_fd, (void *)&fromp, &from_size,
1507 &top, &to_size)
1508 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
1509 || from_size > CONV_RESTLEN)
1511 if (can_retry)
1512 goto rewind_retry;
1513 if (conv_error == 0)
1514 conv_error = readfile_linenr(linecnt,
1515 ptr, (char_u *)top);
1517 /* Deal with a bad byte and continue with the next. */
1518 ++fromp;
1519 --from_size;
1520 if (bad_char_behavior == BAD_KEEP)
1522 *top++ = *(fromp - 1);
1523 --to_size;
1525 else if (bad_char_behavior != BAD_DROP)
1527 *top++ = bad_char_behavior;
1528 --to_size;
1532 if (from_size > 0)
1534 /* Some remaining characters, keep them for the next
1535 * round. */
1536 mch_memmove(conv_rest, (char_u *)fromp, from_size);
1537 conv_restlen = (int)from_size;
1540 /* move the linerest to before the converted characters */
1541 line_start = ptr - linerest;
1542 mch_memmove(line_start, buffer, (size_t)linerest);
1543 size = (long)((char_u *)top - ptr);
1545 # endif
1547 # ifdef WIN3264
1548 if (fio_flags & FIO_CODEPAGE)
1550 char_u *src, *dst;
1551 WCHAR ucs2buf[3];
1552 int ucs2len;
1553 int codepage = FIO_GET_CP(fio_flags);
1554 int bytelen;
1555 int found_bad;
1556 char replstr[2];
1559 * Conversion from an MS-Windows codepage or UTF-8 to UTF-8 or
1560 * a codepage, using standard MS-Windows functions. This
1561 * requires two steps:
1562 * 1. convert from 'fileencoding' to ucs-2
1563 * 2. convert from ucs-2 to 'encoding'
1565 * Because there may be illegal bytes AND an incomplete byte
1566 * sequence at the end, we may have to do the conversion one
1567 * character at a time to get it right.
1570 /* Replacement string for WideCharToMultiByte(). */
1571 if (bad_char_behavior > 0)
1572 replstr[0] = bad_char_behavior;
1573 else
1574 replstr[0] = '?';
1575 replstr[1] = NUL;
1578 * Move the bytes to the end of the buffer, so that we have
1579 * room to put the result at the start.
1581 src = ptr + real_size - size;
1582 mch_memmove(src, ptr, size);
1585 * Do the conversion.
1587 dst = ptr;
1588 size = size;
1589 while (size > 0)
1591 found_bad = FALSE;
1593 # ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
1594 if (codepage == CP_UTF8)
1596 /* Handle CP_UTF8 input ourselves to be able to handle
1597 * trailing bytes properly.
1598 * Get one UTF-8 character from src. */
1599 bytelen = (int)utf_ptr2len_len(src, size);
1600 if (bytelen > size)
1602 /* Only got some bytes of a character. Normally
1603 * it's put in "conv_rest", but if it's too long
1604 * deal with it as if they were illegal bytes. */
1605 if (bytelen <= CONV_RESTLEN)
1606 break;
1608 /* weird overlong byte sequence */
1609 bytelen = size;
1610 found_bad = TRUE;
1612 else
1614 int u8c = utf_ptr2char(src);
1616 if (u8c > 0xffff || (*src >= 0x80 && bytelen == 1))
1617 found_bad = TRUE;
1618 ucs2buf[0] = u8c;
1619 ucs2len = 1;
1622 else
1623 # endif
1625 /* We don't know how long the byte sequence is, try
1626 * from one to three bytes. */
1627 for (bytelen = 1; bytelen <= size && bytelen <= 3;
1628 ++bytelen)
1630 ucs2len = MultiByteToWideChar(codepage,
1631 MB_ERR_INVALID_CHARS,
1632 (LPCSTR)src, bytelen,
1633 ucs2buf, 3);
1634 if (ucs2len > 0)
1635 break;
1637 if (ucs2len == 0)
1639 /* If we have only one byte then it's probably an
1640 * incomplete byte sequence. Otherwise discard
1641 * one byte as a bad character. */
1642 if (size == 1)
1643 break;
1644 found_bad = TRUE;
1645 bytelen = 1;
1649 if (!found_bad)
1651 int i;
1653 /* Convert "ucs2buf[ucs2len]" to 'enc' in "dst". */
1654 if (enc_utf8)
1656 /* From UCS-2 to UTF-8. Cannot fail. */
1657 for (i = 0; i < ucs2len; ++i)
1658 dst += utf_char2bytes(ucs2buf[i], dst);
1660 else
1662 BOOL bad = FALSE;
1663 int dstlen;
1665 /* From UCS-2 to "enc_codepage". If the
1666 * conversion uses the default character "?",
1667 * the data doesn't fit in this encoding. */
1668 dstlen = WideCharToMultiByte(enc_codepage, 0,
1669 (LPCWSTR)ucs2buf, ucs2len,
1670 (LPSTR)dst, (int)(src - dst),
1671 replstr, &bad);
1672 if (bad)
1673 found_bad = TRUE;
1674 else
1675 dst += dstlen;
1679 if (found_bad)
1681 /* Deal with bytes we can't convert. */
1682 if (can_retry)
1683 goto rewind_retry;
1684 if (conv_error == 0)
1685 conv_error = readfile_linenr(linecnt, ptr, dst);
1686 if (bad_char_behavior != BAD_DROP)
1688 if (bad_char_behavior == BAD_KEEP)
1690 mch_memmove(dst, src, bytelen);
1691 dst += bytelen;
1693 else
1694 *dst++ = bad_char_behavior;
1698 src += bytelen;
1699 size -= bytelen;
1702 if (size > 0)
1704 /* An incomplete byte sequence remaining. */
1705 mch_memmove(conv_rest, src, size);
1706 conv_restlen = size;
1709 /* The new size is equal to how much "dst" was advanced. */
1710 size = (long)(dst - ptr);
1712 else
1713 # endif
1714 # ifdef MACOS_CONVERT
1715 if (fio_flags & FIO_MACROMAN)
1718 * Conversion from Apple MacRoman char encoding to UTF-8 or
1719 * latin1. This is in os_mac_conv.c.
1721 if (macroman2enc(ptr, &size, real_size) == FAIL)
1722 goto rewind_retry;
1724 else
1725 # endif
1726 if (fio_flags != 0)
1728 int u8c;
1729 char_u *dest;
1730 char_u *tail = NULL;
1733 * "enc_utf8" set: Convert Unicode or Latin1 to UTF-8.
1734 * "enc_utf8" not set: Convert Unicode to Latin1.
1735 * Go from end to start through the buffer, because the number
1736 * of bytes may increase.
1737 * "dest" points to after where the UTF-8 bytes go, "p" points
1738 * to after the next character to convert.
1740 dest = ptr + real_size;
1741 if (fio_flags == FIO_LATIN1 || fio_flags == FIO_UTF8)
1743 p = ptr + size;
1744 if (fio_flags == FIO_UTF8)
1746 /* Check for a trailing incomplete UTF-8 sequence */
1747 tail = ptr + size - 1;
1748 while (tail > ptr && (*tail & 0xc0) == 0x80)
1749 --tail;
1750 if (tail + utf_byte2len(*tail) <= ptr + size)
1751 tail = NULL;
1752 else
1753 p = tail;
1756 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1758 /* Check for a trailing byte */
1759 p = ptr + (size & ~1);
1760 if (size & 1)
1761 tail = p;
1762 if ((fio_flags & FIO_UTF16) && p > ptr)
1764 /* Check for a trailing leading word */
1765 if (fio_flags & FIO_ENDIAN_L)
1767 u8c = (*--p << 8);
1768 u8c += *--p;
1770 else
1772 u8c = *--p;
1773 u8c += (*--p << 8);
1775 if (u8c >= 0xd800 && u8c <= 0xdbff)
1776 tail = p;
1777 else
1778 p += 2;
1781 else /* FIO_UCS4 */
1783 /* Check for trailing 1, 2 or 3 bytes */
1784 p = ptr + (size & ~3);
1785 if (size & 3)
1786 tail = p;
1789 /* If there is a trailing incomplete sequence move it to
1790 * conv_rest[]. */
1791 if (tail != NULL)
1793 conv_restlen = (int)((ptr + size) - tail);
1794 mch_memmove(conv_rest, (char_u *)tail, conv_restlen);
1795 size -= conv_restlen;
1799 while (p > ptr)
1801 if (fio_flags & FIO_LATIN1)
1802 u8c = *--p;
1803 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1805 if (fio_flags & FIO_ENDIAN_L)
1807 u8c = (*--p << 8);
1808 u8c += *--p;
1810 else
1812 u8c = *--p;
1813 u8c += (*--p << 8);
1815 if ((fio_flags & FIO_UTF16)
1816 && u8c >= 0xdc00 && u8c <= 0xdfff)
1818 int u16c;
1820 if (p == ptr)
1822 /* Missing leading word. */
1823 if (can_retry)
1824 goto rewind_retry;
1825 if (conv_error == 0)
1826 conv_error = readfile_linenr(linecnt,
1827 ptr, p);
1828 if (bad_char_behavior == BAD_DROP)
1829 continue;
1830 if (bad_char_behavior != BAD_KEEP)
1831 u8c = bad_char_behavior;
1834 /* found second word of double-word, get the first
1835 * word and compute the resulting character */
1836 if (fio_flags & FIO_ENDIAN_L)
1838 u16c = (*--p << 8);
1839 u16c += *--p;
1841 else
1843 u16c = *--p;
1844 u16c += (*--p << 8);
1846 u8c = 0x10000 + ((u16c & 0x3ff) << 10)
1847 + (u8c & 0x3ff);
1849 /* Check if the word is indeed a leading word. */
1850 if (u16c < 0xd800 || u16c > 0xdbff)
1852 if (can_retry)
1853 goto rewind_retry;
1854 if (conv_error == 0)
1855 conv_error = readfile_linenr(linecnt,
1856 ptr, p);
1857 if (bad_char_behavior == BAD_DROP)
1858 continue;
1859 if (bad_char_behavior != BAD_KEEP)
1860 u8c = bad_char_behavior;
1864 else if (fio_flags & FIO_UCS4)
1866 if (fio_flags & FIO_ENDIAN_L)
1868 u8c = (*--p << 24);
1869 u8c += (*--p << 16);
1870 u8c += (*--p << 8);
1871 u8c += *--p;
1873 else /* big endian */
1875 u8c = *--p;
1876 u8c += (*--p << 8);
1877 u8c += (*--p << 16);
1878 u8c += (*--p << 24);
1881 else /* UTF-8 */
1883 if (*--p < 0x80)
1884 u8c = *p;
1885 else
1887 len = utf_head_off(ptr, p);
1888 p -= len;
1889 u8c = utf_ptr2char(p);
1890 if (len == 0)
1892 /* Not a valid UTF-8 character, retry with
1893 * another fenc when possible, otherwise just
1894 * report the error. */
1895 if (can_retry)
1896 goto rewind_retry;
1897 if (conv_error == 0)
1898 conv_error = readfile_linenr(linecnt,
1899 ptr, p);
1900 if (bad_char_behavior == BAD_DROP)
1901 continue;
1902 if (bad_char_behavior != BAD_KEEP)
1903 u8c = bad_char_behavior;
1907 if (enc_utf8) /* produce UTF-8 */
1909 dest -= utf_char2len(u8c);
1910 (void)utf_char2bytes(u8c, dest);
1912 else /* produce Latin1 */
1914 --dest;
1915 if (u8c >= 0x100)
1917 /* character doesn't fit in latin1, retry with
1918 * another fenc when possible, otherwise just
1919 * report the error. */
1920 if (can_retry)
1921 goto rewind_retry;
1922 if (conv_error == 0)
1923 conv_error = readfile_linenr(linecnt, ptr, p);
1924 if (bad_char_behavior == BAD_DROP)
1925 ++dest;
1926 else if (bad_char_behavior == BAD_KEEP)
1927 *dest = u8c;
1928 else if (eap != NULL && eap->bad_char != 0)
1929 *dest = bad_char_behavior;
1930 else
1931 *dest = 0xBF;
1933 else
1934 *dest = u8c;
1938 /* move the linerest to before the converted characters */
1939 line_start = dest - linerest;
1940 mch_memmove(line_start, buffer, (size_t)linerest);
1941 size = (long)((ptr + real_size) - dest);
1942 ptr = dest;
1944 else if (enc_utf8 && !curbuf->b_p_bin)
1946 int incomplete_tail = FALSE;
1948 /* Reading UTF-8: Check if the bytes are valid UTF-8. */
1949 for (p = ptr; ; ++p)
1951 int todo = (int)((ptr + size) - p);
1952 int l;
1954 if (todo <= 0)
1955 break;
1956 if (*p >= 0x80)
1958 /* A length of 1 means it's an illegal byte. Accept
1959 * an incomplete character at the end though, the next
1960 * read() will get the next bytes, we'll check it
1961 * then. */
1962 l = utf_ptr2len_len(p, todo);
1963 if (l > todo && !incomplete_tail)
1965 /* Avoid retrying with a different encoding when
1966 * a truncated file is more likely, or attempting
1967 * to read the rest of an incomplete sequence when
1968 * we have already done so. */
1969 if (p > ptr || filesize > 0)
1970 incomplete_tail = TRUE;
1971 /* Incomplete byte sequence, move it to conv_rest[]
1972 * and try to read the rest of it, unless we've
1973 * already done so. */
1974 if (p > ptr)
1976 conv_restlen = todo;
1977 mch_memmove(conv_rest, p, conv_restlen);
1978 size -= conv_restlen;
1979 break;
1982 if (l == 1 || l > todo)
1984 /* Illegal byte. If we can try another encoding
1985 * do that, unless at EOF where a truncated
1986 * file is more likely than a conversion error. */
1987 if (can_retry && !incomplete_tail)
1988 break;
1989 # ifdef USE_ICONV
1990 /* When we did a conversion report an error. */
1991 if (iconv_fd != (iconv_t)-1 && conv_error == 0)
1992 conv_error = readfile_linenr(linecnt, ptr, p);
1993 # endif
1994 /* Remember the first linenr with an illegal byte */
1995 if (conv_error == 0 && illegal_byte == 0)
1996 illegal_byte = readfile_linenr(linecnt, ptr, p);
1998 /* Drop, keep or replace the bad byte. */
1999 if (bad_char_behavior == BAD_DROP)
2001 mch_memmove(p, p + 1, todo - 1);
2002 --p;
2003 --size;
2005 else if (bad_char_behavior != BAD_KEEP)
2006 *p = bad_char_behavior;
2008 else
2009 p += l - 1;
2012 if (p < ptr + size && !incomplete_tail)
2014 /* Detected a UTF-8 error. */
2015 rewind_retry:
2016 /* Retry reading with another conversion. */
2017 # if defined(FEAT_EVAL) && defined(USE_ICONV)
2018 if (*p_ccv != NUL && iconv_fd != (iconv_t)-1)
2019 /* iconv() failed, try 'charconvert' */
2020 did_iconv = TRUE;
2021 else
2022 # endif
2023 /* use next item from 'fileencodings' */
2024 advance_fenc = TRUE;
2025 file_rewind = TRUE;
2026 goto retry;
2029 #endif
2031 /* count the number of characters (after conversion!) */
2032 filesize += size;
2035 * when reading the first part of a file: guess EOL type
2037 if (fileformat == EOL_UNKNOWN)
2039 /* First try finding a NL, for Dos and Unix */
2040 if (try_dos || try_unix)
2042 for (p = ptr; p < ptr + size; ++p)
2044 if (*p == NL)
2046 if (!try_unix
2047 || (try_dos && p > ptr && p[-1] == CAR))
2048 fileformat = EOL_DOS;
2049 else
2050 fileformat = EOL_UNIX;
2051 break;
2055 /* Don't give in to EOL_UNIX if EOL_MAC is more likely */
2056 if (fileformat == EOL_UNIX && try_mac)
2058 /* Need to reset the counters when retrying fenc. */
2059 try_mac = 1;
2060 try_unix = 1;
2061 for (; p >= ptr && *p != CAR; p--)
2063 if (p >= ptr)
2065 for (p = ptr; p < ptr + size; ++p)
2067 if (*p == NL)
2068 try_unix++;
2069 else if (*p == CAR)
2070 try_mac++;
2072 if (try_mac > try_unix)
2073 fileformat = EOL_MAC;
2078 /* No NL found: may use Mac format */
2079 if (fileformat == EOL_UNKNOWN && try_mac)
2080 fileformat = EOL_MAC;
2082 /* Still nothing found? Use first format in 'ffs' */
2083 if (fileformat == EOL_UNKNOWN)
2084 fileformat = default_fileformat();
2086 /* if editing a new file: may set p_tx and p_ff */
2087 if (set_options)
2088 set_fileformat(fileformat, OPT_LOCAL);
2093 * This loop is executed once for every character read.
2094 * Keep it fast!
2096 if (fileformat == EOL_MAC)
2098 --ptr;
2099 while (++ptr, --size >= 0)
2101 /* catch most common case first */
2102 if ((c = *ptr) != NUL && c != CAR && c != NL)
2103 continue;
2104 if (c == NUL)
2105 *ptr = NL; /* NULs are replaced by newlines! */
2106 else if (c == NL)
2107 *ptr = CAR; /* NLs are replaced by CRs! */
2108 else
2110 if (skip_count == 0)
2112 *ptr = NUL; /* end of line */
2113 len = (colnr_T) (ptr - line_start + 1);
2114 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2116 error = TRUE;
2117 break;
2119 ++lnum;
2120 if (--read_count == 0)
2122 error = TRUE; /* break loop */
2123 line_start = ptr; /* nothing left to write */
2124 break;
2127 else
2128 --skip_count;
2129 line_start = ptr + 1;
2133 else
2135 --ptr;
2136 while (++ptr, --size >= 0)
2138 if ((c = *ptr) != NUL && c != NL) /* catch most common case */
2139 continue;
2140 if (c == NUL)
2141 *ptr = NL; /* NULs are replaced by newlines! */
2142 else
2144 if (skip_count == 0)
2146 *ptr = NUL; /* end of line */
2147 len = (colnr_T)(ptr - line_start + 1);
2148 if (fileformat == EOL_DOS)
2150 if (ptr[-1] == CAR) /* remove CR */
2152 ptr[-1] = NUL;
2153 --len;
2156 * Reading in Dos format, but no CR-LF found!
2157 * When 'fileformats' includes "unix", delete all
2158 * the lines read so far and start all over again.
2159 * Otherwise give an error message later.
2161 else if (ff_error != EOL_DOS)
2163 if ( try_unix
2164 && !read_stdin
2165 && (read_buffer
2166 || lseek(fd, (off_t)0L, SEEK_SET) == 0))
2168 fileformat = EOL_UNIX;
2169 if (set_options)
2170 set_fileformat(EOL_UNIX, OPT_LOCAL);
2171 file_rewind = TRUE;
2172 keep_fileformat = TRUE;
2173 goto retry;
2175 ff_error = EOL_DOS;
2178 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2180 error = TRUE;
2181 break;
2183 ++lnum;
2184 if (--read_count == 0)
2186 error = TRUE; /* break loop */
2187 line_start = ptr; /* nothing left to write */
2188 break;
2191 else
2192 --skip_count;
2193 line_start = ptr + 1;
2197 linerest = (long)(ptr - line_start);
2198 ui_breakcheck();
2201 failed:
2202 /* not an error, max. number of lines reached */
2203 if (error && read_count == 0)
2204 error = FALSE;
2207 * If we get EOF in the middle of a line, note the fact and
2208 * complete the line ourselves.
2209 * In Dos format ignore a trailing CTRL-Z, unless 'binary' set.
2211 if (!error
2212 && !got_int
2213 && linerest != 0
2214 && !(!curbuf->b_p_bin
2215 && fileformat == EOL_DOS
2216 && *line_start == Ctrl_Z
2217 && ptr == line_start + 1))
2219 /* remember for when writing */
2220 if (set_options)
2221 curbuf->b_p_eol = FALSE;
2222 *ptr = NUL;
2223 if (ml_append(lnum, line_start,
2224 (colnr_T)(ptr - line_start + 1), newfile) == FAIL)
2225 error = TRUE;
2226 else
2227 read_no_eol_lnum = ++lnum;
2230 if (set_options)
2231 save_file_ff(curbuf); /* remember the current file format */
2233 #ifdef FEAT_CRYPT
2234 if (cryptkey != curbuf->b_p_key)
2235 vim_free(cryptkey);
2236 #endif
2238 #ifdef FEAT_MBYTE
2239 /* If editing a new file: set 'fenc' for the current buffer.
2240 * Also for ":read ++edit file". */
2241 if (set_options)
2242 set_string_option_direct((char_u *)"fenc", -1, fenc,
2243 OPT_FREE|OPT_LOCAL, 0);
2244 if (fenc_alloced)
2245 vim_free(fenc);
2246 # ifdef USE_ICONV
2247 if (iconv_fd != (iconv_t)-1)
2249 iconv_close(iconv_fd);
2250 iconv_fd = (iconv_t)-1;
2252 # endif
2253 #endif
2255 if (!read_buffer && !read_stdin)
2256 close(fd); /* errors are ignored */
2257 #ifdef HAVE_FD_CLOEXEC
2258 else
2260 int fdflags = fcntl(fd, F_GETFD);
2261 if (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0)
2262 fcntl(fd, F_SETFD, fdflags | FD_CLOEXEC);
2264 #endif
2265 vim_free(buffer);
2267 #ifdef HAVE_DUP
2268 if (read_stdin)
2270 /* Use stderr for stdin, makes shell commands work. */
2271 close(0);
2272 ignored = dup(2);
2274 #endif
2276 #ifdef FEAT_MBYTE
2277 if (tmpname != NULL)
2279 mch_remove(tmpname); /* delete converted file */
2280 vim_free(tmpname);
2282 #endif
2283 --no_wait_return; /* may wait for return now */
2286 * In recovery mode everything but autocommands is skipped.
2288 if (!recoverymode)
2290 /* need to delete the last line, which comes from the empty buffer */
2291 if (newfile && wasempty && !(curbuf->b_ml.ml_flags & ML_EMPTY))
2293 #ifdef FEAT_NETBEANS_INTG
2294 netbeansFireChanges = 0;
2295 #endif
2296 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
2297 #ifdef FEAT_NETBEANS_INTG
2298 netbeansFireChanges = 1;
2299 #endif
2300 --linecnt;
2302 linecnt = curbuf->b_ml.ml_line_count - linecnt;
2303 if (filesize == 0)
2304 linecnt = 0;
2305 if (newfile || read_buffer)
2307 redraw_curbuf_later(NOT_VALID);
2308 #ifdef FEAT_DIFF
2309 /* After reading the text into the buffer the diff info needs to
2310 * be updated. */
2311 diff_invalidate(curbuf);
2312 #endif
2313 #ifdef FEAT_FOLDING
2314 /* All folds in the window are invalid now. Mark them for update
2315 * before triggering autocommands. */
2316 foldUpdateAll(curwin);
2317 #endif
2319 else if (linecnt) /* appended at least one line */
2320 appended_lines_mark(from, linecnt);
2322 #ifndef ALWAYS_USE_GUI
2324 * If we were reading from the same terminal as where messages go,
2325 * the screen will have been messed up.
2326 * Switch on raw mode now and clear the screen.
2328 if (read_stdin)
2330 settmode(TMODE_RAW); /* set to raw mode */
2331 starttermcap();
2332 screenclear();
2334 #endif
2336 if (got_int)
2338 if (!(flags & READ_DUMMY))
2340 filemess(curbuf, sfname, (char_u *)_(e_interr), 0);
2341 if (newfile)
2342 curbuf->b_p_ro = TRUE; /* must use "w!" now */
2344 msg_scroll = msg_save;
2345 #ifdef FEAT_VIMINFO
2346 check_marks_read();
2347 #endif
2348 return OK; /* an interrupt isn't really an error */
2351 if (!filtering && !(flags & READ_DUMMY))
2353 msg_add_fname(curbuf, sfname); /* fname in IObuff with quotes */
2354 c = FALSE;
2356 #ifdef UNIX
2357 # ifdef S_ISFIFO
2358 if (S_ISFIFO(perm)) /* fifo or socket */
2360 STRCAT(IObuff, _("[fifo/socket]"));
2361 c = TRUE;
2363 # else
2364 # ifdef S_IFIFO
2365 if ((perm & S_IFMT) == S_IFIFO) /* fifo */
2367 STRCAT(IObuff, _("[fifo]"));
2368 c = TRUE;
2370 # endif
2371 # ifdef S_IFSOCK
2372 if ((perm & S_IFMT) == S_IFSOCK) /* or socket */
2374 STRCAT(IObuff, _("[socket]"));
2375 c = TRUE;
2377 # endif
2378 # endif
2379 # ifdef OPEN_CHR_FILES
2380 if (S_ISCHR(perm)) /* or character special */
2382 STRCAT(IObuff, _("[character special]"));
2383 c = TRUE;
2385 # endif
2386 #endif
2387 if (curbuf->b_p_ro)
2389 STRCAT(IObuff, shortmess(SHM_RO) ? _("[RO]") : _("[readonly]"));
2390 c = TRUE;
2392 if (read_no_eol_lnum)
2394 msg_add_eol();
2395 c = TRUE;
2397 if (ff_error == EOL_DOS)
2399 STRCAT(IObuff, _("[CR missing]"));
2400 c = TRUE;
2402 if (split)
2404 STRCAT(IObuff, _("[long lines split]"));
2405 c = TRUE;
2407 #ifdef FEAT_MBYTE
2408 if (notconverted)
2410 STRCAT(IObuff, _("[NOT converted]"));
2411 c = TRUE;
2413 else if (converted)
2415 STRCAT(IObuff, _("[converted]"));
2416 c = TRUE;
2418 #endif
2419 #ifdef FEAT_CRYPT
2420 if (cryptkey != NULL)
2422 STRCAT(IObuff, _("[crypted]"));
2423 c = TRUE;
2425 #endif
2426 #ifdef FEAT_MBYTE
2427 if (conv_error != 0)
2429 sprintf((char *)IObuff + STRLEN(IObuff),
2430 _("[CONVERSION ERROR in line %ld]"), (long)conv_error);
2431 c = TRUE;
2433 else if (illegal_byte > 0)
2435 sprintf((char *)IObuff + STRLEN(IObuff),
2436 _("[ILLEGAL BYTE in line %ld]"), (long)illegal_byte);
2437 c = TRUE;
2439 else
2440 #endif
2441 if (error)
2443 STRCAT(IObuff, _("[READ ERRORS]"));
2444 c = TRUE;
2446 if (msg_add_fileformat(fileformat))
2447 c = TRUE;
2448 #ifdef FEAT_CRYPT
2449 if (cryptkey != NULL)
2450 msg_add_lines(c, (long)linecnt, filesize - CRYPT_MAGIC_LEN);
2451 else
2452 #endif
2453 msg_add_lines(c, (long)linecnt, filesize);
2455 vim_free(keep_msg);
2456 keep_msg = NULL;
2457 msg_scrolled_ign = TRUE;
2458 #ifdef ALWAYS_USE_GUI
2459 /* Don't show the message when reading stdin, it would end up in a
2460 * message box (which might be shown when exiting!) */
2461 if (read_stdin || read_buffer)
2462 p = msg_may_trunc(FALSE, IObuff);
2463 else
2464 #endif
2465 p = msg_trunc_attr(IObuff, FALSE, 0);
2466 if (read_stdin || read_buffer || restart_edit != 0
2467 || (msg_scrolled != 0 && !need_wait_return))
2468 /* Need to repeat the message after redrawing when:
2469 * - When reading from stdin (the screen will be cleared next).
2470 * - When restart_edit is set (otherwise there will be a delay
2471 * before redrawing).
2472 * - When the screen was scrolled but there is no wait-return
2473 * prompt. */
2474 set_keep_msg(p, 0);
2475 msg_scrolled_ign = FALSE;
2478 /* with errors writing the file requires ":w!" */
2479 if (newfile && (error
2480 #ifdef FEAT_MBYTE
2481 || conv_error != 0
2482 || (illegal_byte > 0 && bad_char_behavior != BAD_KEEP)
2483 #endif
2485 curbuf->b_p_ro = TRUE;
2487 u_clearline(); /* cannot use "U" command after adding lines */
2490 * In Ex mode: cursor at last new line.
2491 * Otherwise: cursor at first new line.
2493 if (exmode_active)
2494 curwin->w_cursor.lnum = from + linecnt;
2495 else
2496 curwin->w_cursor.lnum = from + 1;
2497 check_cursor_lnum();
2498 beginline(BL_WHITE | BL_FIX); /* on first non-blank */
2501 * Set '[ and '] marks to the newly read lines.
2503 curbuf->b_op_start.lnum = from + 1;
2504 curbuf->b_op_start.col = 0;
2505 curbuf->b_op_end.lnum = from + linecnt;
2506 curbuf->b_op_end.col = 0;
2508 #ifdef WIN32
2510 * Work around a weird problem: When a file has two links (only
2511 * possible on NTFS) and we write through one link, then stat() it
2512 * through the other link, the timestamp information may be wrong.
2513 * It's correct again after reading the file, thus reset the timestamp
2514 * here.
2516 if (newfile && !read_stdin && !read_buffer
2517 && mch_stat((char *)fname, &st) >= 0)
2519 buf_store_time(curbuf, &st, fname);
2520 curbuf->b_mtime_read = curbuf->b_mtime;
2522 #endif
2524 msg_scroll = msg_save;
2526 #ifdef FEAT_VIMINFO
2528 * Get the marks before executing autocommands, so they can be used there.
2530 check_marks_read();
2531 #endif
2534 * Trick: We remember if the last line of the read didn't have
2535 * an eol for when writing it again. This is required for
2536 * ":autocmd FileReadPost *.gz set bin|'[,']!gunzip" to work.
2538 write_no_eol_lnum = read_no_eol_lnum;
2540 #ifdef FEAT_AUTOCMD
2541 if (!read_stdin && !read_buffer)
2543 int m = msg_scroll;
2544 int n = msg_scrolled;
2546 /* Save the fileformat now, otherwise the buffer will be considered
2547 * modified if the format/encoding was automatically detected. */
2548 if (set_options)
2549 save_file_ff(curbuf);
2552 * The output from the autocommands should not overwrite anything and
2553 * should not be overwritten: Set msg_scroll, restore its value if no
2554 * output was done.
2556 msg_scroll = TRUE;
2557 if (filtering)
2558 apply_autocmds_exarg(EVENT_FILTERREADPOST, NULL, sfname,
2559 FALSE, curbuf, eap);
2560 else if (newfile)
2561 apply_autocmds_exarg(EVENT_BUFREADPOST, NULL, sfname,
2562 FALSE, curbuf, eap);
2563 else
2564 apply_autocmds_exarg(EVENT_FILEREADPOST, sfname, sfname,
2565 FALSE, NULL, eap);
2566 if (msg_scrolled == n)
2567 msg_scroll = m;
2568 #ifdef FEAT_EVAL
2569 if (aborting()) /* autocmds may abort script processing */
2570 return FAIL;
2571 #endif
2573 #endif
2575 if (recoverymode && error)
2576 return FAIL;
2577 return OK;
2580 #ifdef OPEN_CHR_FILES
2582 * Returns TRUE if the file name argument is of the form "/dev/fd/\d\+",
2583 * which is the name of files used for process substitution output by
2584 * some shells on some operating systems, e.g., bash on SunOS.
2585 * Do not accept "/dev/fd/[012]", opening these may hang Vim.
2587 static int
2588 is_dev_fd_file(fname)
2589 char_u *fname;
2591 return (STRNCMP(fname, "/dev/fd/", 8) == 0
2592 && VIM_ISDIGIT(fname[8])
2593 && *skipdigits(fname + 9) == NUL
2594 && (fname[9] != NUL
2595 || (fname[8] != '0' && fname[8] != '1' && fname[8] != '2')));
2597 #endif
2599 #ifdef FEAT_MBYTE
2602 * From the current line count and characters read after that, estimate the
2603 * line number where we are now.
2604 * Used for error messages that include a line number.
2606 static linenr_T
2607 readfile_linenr(linecnt, p, endp)
2608 linenr_T linecnt; /* line count before reading more bytes */
2609 char_u *p; /* start of more bytes read */
2610 char_u *endp; /* end of more bytes read */
2612 char_u *s;
2613 linenr_T lnum;
2615 lnum = curbuf->b_ml.ml_line_count - linecnt + 1;
2616 for (s = p; s < endp; ++s)
2617 if (*s == '\n')
2618 ++lnum;
2619 return lnum;
2621 #endif
2624 * Fill "*eap" to force the 'fileencoding', 'fileformat' and 'binary to be
2625 * equal to the buffer "buf". Used for calling readfile().
2626 * Returns OK or FAIL.
2629 prep_exarg(eap, buf)
2630 exarg_T *eap;
2631 buf_T *buf;
2633 eap->cmd = alloc((unsigned)(STRLEN(buf->b_p_ff)
2634 #ifdef FEAT_MBYTE
2635 + STRLEN(buf->b_p_fenc)
2636 #endif
2637 + 15));
2638 if (eap->cmd == NULL)
2639 return FAIL;
2641 #ifdef FEAT_MBYTE
2642 sprintf((char *)eap->cmd, "e ++ff=%s ++enc=%s", buf->b_p_ff, buf->b_p_fenc);
2643 eap->force_enc = 14 + (int)STRLEN(buf->b_p_ff);
2644 eap->bad_char = buf->b_bad_char;
2645 #else
2646 sprintf((char *)eap->cmd, "e ++ff=%s", buf->b_p_ff);
2647 #endif
2648 eap->force_ff = 7;
2650 eap->force_bin = buf->b_p_bin ? FORCE_BIN : FORCE_NOBIN;
2651 eap->read_edit = FALSE;
2652 eap->forceit = FALSE;
2653 return OK;
2656 #ifdef FEAT_MBYTE
2658 * Find next fileencoding to use from 'fileencodings'.
2659 * "pp" points to fenc_next. It's advanced to the next item.
2660 * When there are no more items, an empty string is returned and *pp is set to
2661 * NULL.
2662 * When *pp is not set to NULL, the result is in allocated memory.
2664 static char_u *
2665 next_fenc(pp)
2666 char_u **pp;
2668 char_u *p;
2669 char_u *r;
2671 if (**pp == NUL)
2673 *pp = NULL;
2674 return (char_u *)"";
2676 p = vim_strchr(*pp, ',');
2677 if (p == NULL)
2679 r = enc_canonize(*pp);
2680 *pp += STRLEN(*pp);
2682 else
2684 r = vim_strnsave(*pp, (int)(p - *pp));
2685 *pp = p + 1;
2686 if (r != NULL)
2688 p = enc_canonize(r);
2689 vim_free(r);
2690 r = p;
2693 if (r == NULL) /* out of memory */
2695 r = (char_u *)"";
2696 *pp = NULL;
2698 return r;
2701 # ifdef FEAT_EVAL
2703 * Convert a file with the 'charconvert' expression.
2704 * This closes the file which is to be read, converts it and opens the
2705 * resulting file for reading.
2706 * Returns name of the resulting converted file (the caller should delete it
2707 * after reading it).
2708 * Returns NULL if the conversion failed ("*fdp" is not set) .
2710 static char_u *
2711 readfile_charconvert(fname, fenc, fdp)
2712 char_u *fname; /* name of input file */
2713 char_u *fenc; /* converted from */
2714 int *fdp; /* in/out: file descriptor of file */
2716 char_u *tmpname;
2717 char_u *errmsg = NULL;
2719 tmpname = vim_tempname('r');
2720 if (tmpname == NULL)
2721 errmsg = (char_u *)_("Can't find temp file for conversion");
2722 else
2724 close(*fdp); /* close the input file, ignore errors */
2725 *fdp = -1;
2726 if (eval_charconvert(fenc, enc_utf8 ? (char_u *)"utf-8" : p_enc,
2727 fname, tmpname) == FAIL)
2728 errmsg = (char_u *)_("Conversion with 'charconvert' failed");
2729 if (errmsg == NULL && (*fdp = mch_open((char *)tmpname,
2730 O_RDONLY | O_EXTRA, 0)) < 0)
2731 errmsg = (char_u *)_("can't read output of 'charconvert'");
2734 if (errmsg != NULL)
2736 /* Don't use emsg(), it breaks mappings, the retry with
2737 * another type of conversion might still work. */
2738 MSG(errmsg);
2739 if (tmpname != NULL)
2741 mch_remove(tmpname); /* delete converted file */
2742 vim_free(tmpname);
2743 tmpname = NULL;
2747 /* If the input file is closed, open it (caller should check for error). */
2748 if (*fdp < 0)
2749 *fdp = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
2751 return tmpname;
2753 # endif
2755 #endif
2757 #ifdef FEAT_VIMINFO
2759 * Read marks for the current buffer from the viminfo file, when we support
2760 * buffer marks and the buffer has a name.
2762 static void
2763 check_marks_read()
2765 if (!curbuf->b_marks_read && get_viminfo_parameter('\'') > 0
2766 && curbuf->b_ffname != NULL)
2767 read_viminfo(NULL, VIF_WANT_MARKS);
2769 /* Always set b_marks_read; needed when 'viminfo' is changed to include
2770 * the ' parameter after opening a buffer. */
2771 curbuf->b_marks_read = TRUE;
2773 #endif
2775 #ifdef FEAT_CRYPT
2777 * Check for magic number used for encryption.
2778 * If found, the magic number is removed from ptr[*sizep] and *sizep and
2779 * *filesizep are updated.
2780 * Return the (new) encryption key, NULL for no encryption.
2782 static char_u *
2783 check_for_cryptkey(cryptkey, ptr, sizep, filesizep, newfile)
2784 char_u *cryptkey; /* previous encryption key or NULL */
2785 char_u *ptr; /* pointer to read bytes */
2786 long *sizep; /* length of read bytes */
2787 long *filesizep; /* nr of bytes used from file */
2788 int newfile; /* editing a new buffer */
2790 if (*sizep >= CRYPT_MAGIC_LEN
2791 && STRNCMP(ptr, CRYPT_MAGIC, CRYPT_MAGIC_LEN) == 0)
2793 if (cryptkey == NULL)
2795 if (*curbuf->b_p_key)
2796 cryptkey = curbuf->b_p_key;
2797 else
2799 /* When newfile is TRUE, store the typed key
2800 * in the 'key' option and don't free it. */
2801 cryptkey = get_crypt_key(newfile, FALSE);
2802 /* check if empty key entered */
2803 if (cryptkey != NULL && *cryptkey == NUL)
2805 if (cryptkey != curbuf->b_p_key)
2806 vim_free(cryptkey);
2807 cryptkey = NULL;
2812 if (cryptkey != NULL)
2814 crypt_init_keys(cryptkey);
2816 /* Remove magic number from the text */
2817 *filesizep += CRYPT_MAGIC_LEN;
2818 *sizep -= CRYPT_MAGIC_LEN;
2819 mch_memmove(ptr, ptr + CRYPT_MAGIC_LEN, (size_t)*sizep);
2822 /* When starting to edit a new file which does not have
2823 * encryption, clear the 'key' option, except when
2824 * starting up (called with -x argument) */
2825 else if (newfile && *curbuf->b_p_key && !starting)
2826 set_option_value((char_u *)"key", 0L, (char_u *)"", OPT_LOCAL);
2828 return cryptkey;
2830 #endif
2832 #ifdef UNIX
2833 static void
2834 set_file_time(fname, atime, mtime)
2835 char_u *fname;
2836 time_t atime; /* access time */
2837 time_t mtime; /* modification time */
2839 # if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
2840 struct utimbuf buf;
2842 buf.actime = atime;
2843 buf.modtime = mtime;
2844 (void)utime((char *)fname, &buf);
2845 # else
2846 # if defined(HAVE_UTIMES)
2847 struct timeval tvp[2];
2849 tvp[0].tv_sec = atime;
2850 tvp[0].tv_usec = 0;
2851 tvp[1].tv_sec = mtime;
2852 tvp[1].tv_usec = 0;
2853 # ifdef NeXT
2854 (void)utimes((char *)fname, tvp);
2855 # else
2856 (void)utimes((char *)fname, (const struct timeval *)&tvp);
2857 # endif
2858 # endif
2859 # endif
2861 #endif /* UNIX */
2863 #if defined(VMS) && !defined(MIN)
2864 /* Older DECC compiler for VAX doesn't define MIN() */
2865 # define MIN(a, b) ((a) < (b) ? (a) : (b))
2866 #endif
2869 * Return TRUE if a file appears to be read-only from the file permissions.
2872 check_file_readonly(fname, perm)
2873 char_u *fname; /* full path to file */
2874 int perm; /* known permissions on file */
2876 #ifndef USE_MCH_ACCESS
2877 int fd = 0;
2878 #endif
2880 return (
2881 #ifdef USE_MCH_ACCESS
2882 # ifdef UNIX
2883 (perm & 0222) == 0 ||
2884 # endif
2885 mch_access((char *)fname, W_OK)
2886 #else
2887 (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0
2888 ? TRUE : (close(fd), FALSE)
2889 #endif
2895 * buf_write() - write to file "fname" lines "start" through "end"
2897 * We do our own buffering here because fwrite() is so slow.
2899 * If "forceit" is true, we don't care for errors when attempting backups.
2900 * In case of an error everything possible is done to restore the original
2901 * file. But when "forceit" is TRUE, we risk losing it.
2903 * When "reset_changed" is TRUE and "append" == FALSE and "start" == 1 and
2904 * "end" == curbuf->b_ml.ml_line_count, reset curbuf->b_changed.
2906 * This function must NOT use NameBuff (because it's called by autowrite()).
2908 * return FAIL for failure, OK otherwise
2911 buf_write(buf, fname, sfname, start, end, eap, append, forceit,
2912 reset_changed, filtering)
2913 buf_T *buf;
2914 char_u *fname;
2915 char_u *sfname;
2916 linenr_T start, end;
2917 exarg_T *eap; /* for forced 'ff' and 'fenc', can be
2918 NULL! */
2919 int append; /* append to the file */
2920 int forceit;
2921 int reset_changed;
2922 int filtering;
2924 int fd;
2925 char_u *backup = NULL;
2926 int backup_copy = FALSE; /* copy the original file? */
2927 int dobackup;
2928 char_u *ffname;
2929 char_u *wfname = NULL; /* name of file to write to */
2930 char_u *s;
2931 char_u *ptr;
2932 char_u c;
2933 int len;
2934 linenr_T lnum;
2935 long nchars;
2936 char_u *errmsg = NULL;
2937 int errmsg_allocated = FALSE;
2938 char_u *errnum = NULL;
2939 char_u *buffer;
2940 char_u smallbuf[SMBUFSIZE];
2941 char_u *backup_ext;
2942 int bufsize;
2943 long perm; /* file permissions */
2944 int retval = OK;
2945 int newfile = FALSE; /* TRUE if file doesn't exist yet */
2946 int msg_save = msg_scroll;
2947 int overwriting; /* TRUE if writing over original */
2948 int no_eol = FALSE; /* no end-of-line written */
2949 int device = FALSE; /* writing to a device */
2950 struct stat st_old;
2951 int prev_got_int = got_int;
2952 int file_readonly = FALSE; /* overwritten file is read-only */
2953 static char *err_readonly = "is read-only (cannot override: \"W\" in 'cpoptions')";
2954 #if defined(UNIX) || defined(__EMX__XX) /*XXX fix me sometime? */
2955 int made_writable = FALSE; /* 'w' bit has been set */
2956 #endif
2957 /* writing everything */
2958 int whole = (start == 1 && end == buf->b_ml.ml_line_count);
2959 #ifdef FEAT_AUTOCMD
2960 linenr_T old_line_count = buf->b_ml.ml_line_count;
2961 #endif
2962 int attr;
2963 int fileformat;
2964 int write_bin;
2965 struct bw_info write_info; /* info for buf_write_bytes() */
2966 #ifdef FEAT_MBYTE
2967 int converted = FALSE;
2968 int notconverted = FALSE;
2969 char_u *fenc; /* effective 'fileencoding' */
2970 char_u *fenc_tofree = NULL; /* allocated "fenc" */
2971 #endif
2972 #ifdef HAS_BW_FLAGS
2973 int wb_flags = 0;
2974 #endif
2975 #ifdef HAVE_ACL
2976 vim_acl_T acl = NULL; /* ACL copied from original file to
2977 backup or new file */
2978 #endif
2980 if (fname == NULL || *fname == NUL) /* safety check */
2981 return FAIL;
2984 * Disallow writing from .exrc and .vimrc in current directory for
2985 * security reasons.
2987 if (check_secure())
2988 return FAIL;
2990 /* Avoid a crash for a long name. */
2991 if (STRLEN(fname) >= MAXPATHL)
2993 EMSG(_(e_longname));
2994 return FAIL;
2997 #ifdef FEAT_MBYTE
2998 /* must init bw_conv_buf and bw_iconv_fd before jumping to "fail" */
2999 write_info.bw_conv_buf = NULL;
3000 write_info.bw_conv_error = FALSE;
3001 write_info.bw_conv_error_lnum = 0;
3002 write_info.bw_restlen = 0;
3003 # ifdef USE_ICONV
3004 write_info.bw_iconv_fd = (iconv_t)-1;
3005 # endif
3006 #endif
3008 /* After writing a file changedtick changes but we don't want to display
3009 * the line. */
3010 ex_no_reprint = TRUE;
3013 * If there is no file name yet, use the one for the written file.
3014 * BF_NOTEDITED is set to reflect this (in case the write fails).
3015 * Don't do this when the write is for a filter command.
3016 * Don't do this when appending.
3017 * Only do this when 'cpoptions' contains the 'F' flag.
3019 if (buf->b_ffname == NULL
3020 && reset_changed
3021 && whole
3022 && buf == curbuf
3023 #ifdef FEAT_QUICKFIX
3024 && !bt_nofile(buf)
3025 #endif
3026 && !filtering
3027 && (!append || vim_strchr(p_cpo, CPO_FNAMEAPP) != NULL)
3028 && vim_strchr(p_cpo, CPO_FNAMEW) != NULL)
3030 if (set_rw_fname(fname, sfname) == FAIL)
3031 return FAIL;
3032 buf = curbuf; /* just in case autocmds made "buf" invalid */
3035 if (sfname == NULL)
3036 sfname = fname;
3038 * For Unix: Use the short file name whenever possible.
3039 * Avoids problems with networks and when directory names are changed.
3040 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
3041 * another directory, which we don't detect
3043 ffname = fname; /* remember full fname */
3044 #ifdef UNIX
3045 fname = sfname;
3046 #endif
3048 if (buf->b_ffname != NULL && fnamecmp(ffname, buf->b_ffname) == 0)
3049 overwriting = TRUE;
3050 else
3051 overwriting = FALSE;
3053 if (exiting)
3054 settmode(TMODE_COOK); /* when exiting allow typahead now */
3056 ++no_wait_return; /* don't wait for return yet */
3059 * Set '[ and '] marks to the lines to be written.
3061 buf->b_op_start.lnum = start;
3062 buf->b_op_start.col = 0;
3063 buf->b_op_end.lnum = end;
3064 buf->b_op_end.col = 0;
3066 #ifdef FEAT_AUTOCMD
3068 aco_save_T aco;
3069 int buf_ffname = FALSE;
3070 int buf_sfname = FALSE;
3071 int buf_fname_f = FALSE;
3072 int buf_fname_s = FALSE;
3073 int did_cmd = FALSE;
3074 int nofile_err = FALSE;
3075 int empty_memline = (buf->b_ml.ml_mfp == NULL);
3078 * Apply PRE aucocommands.
3079 * Set curbuf to the buffer to be written.
3080 * Careful: The autocommands may call buf_write() recursively!
3082 if (ffname == buf->b_ffname)
3083 buf_ffname = TRUE;
3084 if (sfname == buf->b_sfname)
3085 buf_sfname = TRUE;
3086 if (fname == buf->b_ffname)
3087 buf_fname_f = TRUE;
3088 if (fname == buf->b_sfname)
3089 buf_fname_s = TRUE;
3091 /* set curwin/curbuf to buf and save a few things */
3092 aucmd_prepbuf(&aco, buf);
3094 if (append)
3096 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD,
3097 sfname, sfname, FALSE, curbuf, eap)))
3099 #ifdef FEAT_QUICKFIX
3100 if (overwriting && bt_nofile(curbuf))
3101 nofile_err = TRUE;
3102 else
3103 #endif
3104 apply_autocmds_exarg(EVENT_FILEAPPENDPRE,
3105 sfname, sfname, FALSE, curbuf, eap);
3108 else if (filtering)
3110 apply_autocmds_exarg(EVENT_FILTERWRITEPRE,
3111 NULL, sfname, FALSE, curbuf, eap);
3113 else if (reset_changed && whole)
3115 if (!(did_cmd = apply_autocmds_exarg(EVENT_BUFWRITECMD,
3116 sfname, sfname, FALSE, curbuf, eap)))
3118 #ifdef FEAT_QUICKFIX
3119 if (overwriting && bt_nofile(curbuf))
3120 nofile_err = TRUE;
3121 else
3122 #endif
3123 apply_autocmds_exarg(EVENT_BUFWRITEPRE,
3124 sfname, sfname, FALSE, curbuf, eap);
3127 else
3129 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD,
3130 sfname, sfname, FALSE, curbuf, eap)))
3132 #ifdef FEAT_QUICKFIX
3133 if (overwriting && bt_nofile(curbuf))
3134 nofile_err = TRUE;
3135 else
3136 #endif
3137 apply_autocmds_exarg(EVENT_FILEWRITEPRE,
3138 sfname, sfname, FALSE, curbuf, eap);
3142 /* restore curwin/curbuf and a few other things */
3143 aucmd_restbuf(&aco);
3146 * In three situations we return here and don't write the file:
3147 * 1. the autocommands deleted or unloaded the buffer.
3148 * 2. The autocommands abort script processing.
3149 * 3. If one of the "Cmd" autocommands was executed.
3151 if (!buf_valid(buf))
3152 buf = NULL;
3153 if (buf == NULL || (buf->b_ml.ml_mfp == NULL && !empty_memline)
3154 || did_cmd || nofile_err
3155 #ifdef FEAT_EVAL
3156 || aborting()
3157 #endif
3160 --no_wait_return;
3161 msg_scroll = msg_save;
3162 if (nofile_err)
3163 EMSG(_("E676: No matching autocommands for acwrite buffer"));
3165 if (nofile_err
3166 #ifdef FEAT_EVAL
3167 || aborting()
3168 #endif
3170 /* An aborting error, interrupt or exception in the
3171 * autocommands. */
3172 return FAIL;
3173 if (did_cmd)
3175 if (buf == NULL)
3176 /* The buffer was deleted. We assume it was written
3177 * (can't retry anyway). */
3178 return OK;
3179 if (overwriting)
3181 /* Assume the buffer was written, update the timestamp. */
3182 ml_timestamp(buf);
3183 if (append)
3184 buf->b_flags &= ~BF_NEW;
3185 else
3186 buf->b_flags &= ~BF_WRITE_MASK;
3188 if (reset_changed && buf->b_changed && !append
3189 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL))
3190 /* Buffer still changed, the autocommands didn't work
3191 * properly. */
3192 return FAIL;
3193 return OK;
3195 #ifdef FEAT_EVAL
3196 if (!aborting())
3197 #endif
3198 EMSG(_("E203: Autocommands deleted or unloaded buffer to be written"));
3199 return FAIL;
3203 * The autocommands may have changed the number of lines in the file.
3204 * When writing the whole file, adjust the end.
3205 * When writing part of the file, assume that the autocommands only
3206 * changed the number of lines that are to be written (tricky!).
3208 if (buf->b_ml.ml_line_count != old_line_count)
3210 if (whole) /* write all */
3211 end = buf->b_ml.ml_line_count;
3212 else if (buf->b_ml.ml_line_count > old_line_count) /* more lines */
3213 end += buf->b_ml.ml_line_count - old_line_count;
3214 else /* less lines */
3216 end -= old_line_count - buf->b_ml.ml_line_count;
3217 if (end < start)
3219 --no_wait_return;
3220 msg_scroll = msg_save;
3221 EMSG(_("E204: Autocommand changed number of lines in unexpected way"));
3222 return FAIL;
3228 * The autocommands may have changed the name of the buffer, which may
3229 * be kept in fname, ffname and sfname.
3231 if (buf_ffname)
3232 ffname = buf->b_ffname;
3233 if (buf_sfname)
3234 sfname = buf->b_sfname;
3235 if (buf_fname_f)
3236 fname = buf->b_ffname;
3237 if (buf_fname_s)
3238 fname = buf->b_sfname;
3240 #endif
3242 #ifdef FEAT_NETBEANS_INTG
3243 if (usingNetbeans && isNetbeansBuffer(buf))
3245 if (whole)
3248 * b_changed can be 0 after an undo, but we still need to write
3249 * the buffer to NetBeans.
3251 if (buf->b_changed || isNetbeansModified(buf))
3253 --no_wait_return; /* may wait for return now */
3254 msg_scroll = msg_save;
3255 netbeans_save_buffer(buf); /* no error checking... */
3256 return retval;
3258 else
3260 errnum = (char_u *)"E656: ";
3261 errmsg = (char_u *)_("NetBeans disallows writes of unmodified buffers");
3262 buffer = NULL;
3263 goto fail;
3266 else
3268 errnum = (char_u *)"E657: ";
3269 errmsg = (char_u *)_("Partial writes disallowed for NetBeans buffers");
3270 buffer = NULL;
3271 goto fail;
3274 #endif
3276 if (shortmess(SHM_OVER) && !exiting)
3277 msg_scroll = FALSE; /* overwrite previous file message */
3278 else
3279 msg_scroll = TRUE; /* don't overwrite previous file message */
3280 if (!filtering)
3281 filemess(buf,
3282 #ifndef UNIX
3283 sfname,
3284 #else
3285 fname,
3286 #endif
3287 (char_u *)"", 0); /* show that we are busy */
3288 msg_scroll = FALSE; /* always overwrite the file message now */
3290 buffer = alloc(BUFSIZE);
3291 if (buffer == NULL) /* can't allocate big buffer, use small
3292 * one (to be able to write when out of
3293 * memory) */
3295 buffer = smallbuf;
3296 bufsize = SMBUFSIZE;
3298 else
3299 bufsize = BUFSIZE;
3302 * Get information about original file (if there is one).
3304 #if defined(UNIX) && !defined(ARCHIE)
3305 st_old.st_dev = 0;
3306 st_old.st_ino = 0;
3307 perm = -1;
3308 if (mch_stat((char *)fname, &st_old) < 0)
3309 newfile = TRUE;
3310 else
3312 perm = st_old.st_mode;
3313 if (!S_ISREG(st_old.st_mode)) /* not a file */
3315 if (S_ISDIR(st_old.st_mode))
3317 errnum = (char_u *)"E502: ";
3318 errmsg = (char_u *)_("is a directory");
3319 goto fail;
3321 if (mch_nodetype(fname) != NODE_WRITABLE)
3323 errnum = (char_u *)"E503: ";
3324 errmsg = (char_u *)_("is not a file or writable device");
3325 goto fail;
3327 /* It's a device of some kind (or a fifo) which we can write to
3328 * but for which we can't make a backup. */
3329 device = TRUE;
3330 newfile = TRUE;
3331 perm = -1;
3334 #else /* !UNIX */
3336 * Check for a writable device name.
3338 c = mch_nodetype(fname);
3339 if (c == NODE_OTHER)
3341 errnum = (char_u *)"E503: ";
3342 errmsg = (char_u *)_("is not a file or writable device");
3343 goto fail;
3345 if (c == NODE_WRITABLE)
3347 # if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3348 /* MS-Windows allows opening a device, but we will probably get stuck
3349 * trying to write to it. */
3350 if (!p_odev)
3352 errnum = (char_u *)"E796: ";
3353 errmsg = (char_u *)_("writing to device disabled with 'opendevice' option");
3354 goto fail;
3356 # endif
3357 device = TRUE;
3358 newfile = TRUE;
3359 perm = -1;
3361 else
3363 perm = mch_getperm(fname);
3364 if (perm < 0)
3365 newfile = TRUE;
3366 else if (mch_isdir(fname))
3368 errnum = (char_u *)"E502: ";
3369 errmsg = (char_u *)_("is a directory");
3370 goto fail;
3372 if (overwriting)
3373 (void)mch_stat((char *)fname, &st_old);
3375 #endif /* !UNIX */
3377 if (!device && !newfile)
3380 * Check if the file is really writable (when renaming the file to
3381 * make a backup we won't discover it later).
3383 file_readonly = check_file_readonly(fname, (int)perm);
3385 if (!forceit && file_readonly)
3387 if (vim_strchr(p_cpo, CPO_FWRITE) != NULL)
3389 errnum = (char_u *)"E504: ";
3390 errmsg = (char_u *)_(err_readonly);
3392 else
3394 errnum = (char_u *)"E505: ";
3395 errmsg = (char_u *)_("is read-only (add ! to override)");
3397 goto fail;
3401 * Check if the timestamp hasn't changed since reading the file.
3403 if (overwriting)
3405 retval = check_mtime(buf, &st_old);
3406 if (retval == FAIL)
3407 goto fail;
3411 #ifdef HAVE_ACL
3413 * For systems that support ACL: get the ACL from the original file.
3415 if (!newfile)
3416 acl = mch_get_acl(fname);
3417 #endif
3420 * If 'backupskip' is not empty, don't make a backup for some files.
3422 dobackup = (p_wb || p_bk || *p_pm != NUL);
3423 #ifdef FEAT_WILDIGN
3424 if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname))
3425 dobackup = FALSE;
3426 #endif
3429 * Save the value of got_int and reset it. We don't want a previous
3430 * interruption cancel writing, only hitting CTRL-C while writing should
3431 * abort it.
3433 prev_got_int = got_int;
3434 got_int = FALSE;
3436 /* Mark the buffer as 'being saved' to prevent changed buffer warnings */
3437 buf->b_saving = TRUE;
3440 * If we are not appending or filtering, the file exists, and the
3441 * 'writebackup', 'backup' or 'patchmode' option is set, need a backup.
3442 * When 'patchmode' is set also make a backup when appending.
3444 * Do not make any backup, if 'writebackup' and 'backup' are both switched
3445 * off. This helps when editing large files on almost-full disks.
3447 if (!(append && *p_pm == NUL) && !filtering && perm >= 0 && dobackup)
3449 #if defined(UNIX) || defined(WIN32)
3450 struct stat st;
3451 #endif
3453 if ((bkc_flags & BKC_YES) || append) /* "yes" */
3454 backup_copy = TRUE;
3455 #if defined(UNIX) || defined(WIN32)
3456 else if ((bkc_flags & BKC_AUTO)) /* "auto" */
3458 int i;
3460 # ifdef UNIX
3462 * Don't rename the file when:
3463 * - it's a hard link
3464 * - it's a symbolic link
3465 * - we don't have write permission in the directory
3466 * - we can't set the owner/group of the new file
3468 if (st_old.st_nlink > 1
3469 || mch_lstat((char *)fname, &st) < 0
3470 || st.st_dev != st_old.st_dev
3471 || st.st_ino != st_old.st_ino
3472 # ifndef HAVE_FCHOWN
3473 || st.st_uid != st_old.st_uid
3474 || st.st_gid != st_old.st_gid
3475 # endif
3477 backup_copy = TRUE;
3478 else
3479 # else
3480 # ifdef WIN32
3481 /* On NTFS file systems hard links are possible. */
3482 if (mch_is_linked(fname))
3483 backup_copy = TRUE;
3484 else
3485 # endif
3486 # endif
3489 * Check if we can create a file and set the owner/group to
3490 * the ones from the original file.
3491 * First find a file name that doesn't exist yet (use some
3492 * arbitrary numbers).
3494 STRCPY(IObuff, fname);
3495 for (i = 4913; ; i += 123)
3497 sprintf((char *)gettail(IObuff), "%d", i);
3498 if (mch_lstat((char *)IObuff, &st) < 0)
3499 break;
3501 fd = mch_open((char *)IObuff,
3502 O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, perm);
3503 if (fd < 0) /* can't write in directory */
3504 backup_copy = TRUE;
3505 else
3507 # ifdef UNIX
3508 # ifdef HAVE_FCHOWN
3509 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
3510 # endif
3511 if (mch_stat((char *)IObuff, &st) < 0
3512 || st.st_uid != st_old.st_uid
3513 || st.st_gid != st_old.st_gid
3514 || (long)st.st_mode != perm)
3515 backup_copy = TRUE;
3516 # endif
3517 /* Close the file before removing it, on MS-Windows we
3518 * can't delete an open file. */
3519 close(fd);
3520 mch_remove(IObuff);
3525 # ifdef UNIX
3527 * Break symlinks and/or hardlinks if we've been asked to.
3529 if ((bkc_flags & BKC_BREAKSYMLINK) || (bkc_flags & BKC_BREAKHARDLINK))
3531 int lstat_res;
3533 lstat_res = mch_lstat((char *)fname, &st);
3535 /* Symlinks. */
3536 if ((bkc_flags & BKC_BREAKSYMLINK)
3537 && lstat_res == 0
3538 && st.st_ino != st_old.st_ino)
3539 backup_copy = FALSE;
3541 /* Hardlinks. */
3542 if ((bkc_flags & BKC_BREAKHARDLINK)
3543 && st_old.st_nlink > 1
3544 && (lstat_res != 0 || st.st_ino == st_old.st_ino))
3545 backup_copy = FALSE;
3547 #endif
3549 #endif
3551 /* make sure we have a valid backup extension to use */
3552 if (*p_bex == NUL)
3554 #ifdef RISCOS
3555 backup_ext = (char_u *)"/bak";
3556 #else
3557 backup_ext = (char_u *)".bak";
3558 #endif
3560 else
3561 backup_ext = p_bex;
3563 if (backup_copy
3564 && (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) >= 0)
3566 int bfd;
3567 char_u *copybuf, *wp;
3568 int some_error = FALSE;
3569 struct stat st_new;
3570 char_u *dirp;
3571 char_u *rootname;
3572 #if defined(UNIX) && !defined(SHORT_FNAME)
3573 int did_set_shortname;
3574 #endif
3576 copybuf = alloc(BUFSIZE + 1);
3577 if (copybuf == NULL)
3579 some_error = TRUE; /* out of memory */
3580 goto nobackup;
3584 * Try to make the backup in each directory in the 'bdir' option.
3586 * Unix semantics has it, that we may have a writable file,
3587 * that cannot be recreated with a simple open(..., O_CREAT, ) e.g:
3588 * - the directory is not writable,
3589 * - the file may be a symbolic link,
3590 * - the file may belong to another user/group, etc.
3592 * For these reasons, the existing writable file must be truncated
3593 * and reused. Creation of a backup COPY will be attempted.
3595 dirp = p_bdir;
3596 while (*dirp)
3598 #ifdef UNIX
3599 st_new.st_ino = 0;
3600 st_new.st_dev = 0;
3601 st_new.st_gid = 0;
3602 #endif
3605 * Isolate one directory name, using an entry in 'bdir'.
3607 (void)copy_option_part(&dirp, copybuf, BUFSIZE, ",");
3608 rootname = get_file_in_dir(fname, copybuf);
3609 if (rootname == NULL)
3611 some_error = TRUE; /* out of memory */
3612 goto nobackup;
3615 #if defined(UNIX) && !defined(SHORT_FNAME)
3616 did_set_shortname = FALSE;
3617 #endif
3620 * May try twice if 'shortname' not set.
3622 for (;;)
3625 * Make backup file name.
3627 backup = buf_modname(
3628 #ifdef SHORT_FNAME
3629 TRUE,
3630 #else
3631 (buf->b_p_sn || buf->b_shortname),
3632 #endif
3633 rootname, backup_ext, FALSE);
3634 if (backup == NULL)
3636 vim_free(rootname);
3637 some_error = TRUE; /* out of memory */
3638 goto nobackup;
3642 * Check if backup file already exists.
3644 if (mch_stat((char *)backup, &st_new) >= 0)
3646 #ifdef UNIX
3648 * Check if backup file is same as original file.
3649 * May happen when modname() gave the same file back.
3650 * E.g. silly link, or file name-length reached.
3651 * If we don't check here, we either ruin the file
3652 * when copying or erase it after writing. jw.
3654 if (st_new.st_dev == st_old.st_dev
3655 && st_new.st_ino == st_old.st_ino)
3657 vim_free(backup);
3658 backup = NULL; /* no backup file to delete */
3659 # ifndef SHORT_FNAME
3661 * may try again with 'shortname' set
3663 if (!(buf->b_shortname || buf->b_p_sn))
3665 buf->b_shortname = TRUE;
3666 did_set_shortname = TRUE;
3667 continue;
3669 /* setting shortname didn't help */
3670 if (did_set_shortname)
3671 buf->b_shortname = FALSE;
3672 # endif
3673 break;
3675 #endif
3678 * If we are not going to keep the backup file, don't
3679 * delete an existing one, try to use another name.
3680 * Change one character, just before the extension.
3682 if (!p_bk)
3684 wp = backup + STRLEN(backup) - 1
3685 - STRLEN(backup_ext);
3686 if (wp < backup) /* empty file name ??? */
3687 wp = backup;
3688 *wp = 'z';
3689 while (*wp > 'a'
3690 && mch_stat((char *)backup, &st_new) >= 0)
3691 --*wp;
3692 /* They all exist??? Must be something wrong. */
3693 if (*wp == 'a')
3695 vim_free(backup);
3696 backup = NULL;
3700 break;
3702 vim_free(rootname);
3705 * Try to create the backup file
3707 if (backup != NULL)
3709 /* remove old backup, if present */
3710 mch_remove(backup);
3711 /* Open with O_EXCL to avoid the file being created while
3712 * we were sleeping (symlink hacker attack?) */
3713 bfd = mch_open((char *)backup,
3714 O_WRONLY|O_CREAT|O_EXTRA|O_EXCL|O_NOFOLLOW,
3715 perm & 0777);
3716 if (bfd < 0)
3718 vim_free(backup);
3719 backup = NULL;
3721 else
3723 /* set file protection same as original file, but
3724 * strip s-bit */
3725 (void)mch_setperm(backup, perm & 0777);
3727 #ifdef UNIX
3729 * Try to set the group of the backup same as the
3730 * original file. If this fails, set the protection
3731 * bits for the group same as the protection bits for
3732 * others.
3734 if (st_new.st_gid != st_old.st_gid
3735 # ifdef HAVE_FCHOWN /* sequent-ptx lacks fchown() */
3736 && fchown(bfd, (uid_t)-1, st_old.st_gid) != 0
3737 # endif
3739 mch_setperm(backup,
3740 (perm & 0707) | ((perm & 07) << 3));
3741 # ifdef HAVE_SELINUX
3742 mch_copy_sec(fname, backup);
3743 # endif
3744 #endif
3747 * copy the file.
3749 write_info.bw_fd = bfd;
3750 write_info.bw_buf = copybuf;
3751 #ifdef HAS_BW_FLAGS
3752 write_info.bw_flags = FIO_NOCONVERT;
3753 #endif
3754 while ((write_info.bw_len = vim_read(fd, copybuf,
3755 BUFSIZE)) > 0)
3757 if (buf_write_bytes(&write_info) == FAIL)
3759 errmsg = (char_u *)_("E506: Can't write to backup file (add ! to override)");
3760 break;
3762 ui_breakcheck();
3763 if (got_int)
3765 errmsg = (char_u *)_(e_interr);
3766 break;
3770 if (close(bfd) < 0 && errmsg == NULL)
3771 errmsg = (char_u *)_("E507: Close error for backup file (add ! to override)");
3772 if (write_info.bw_len < 0)
3773 errmsg = (char_u *)_("E508: Can't read file for backup (add ! to override)");
3774 #ifdef UNIX
3775 set_file_time(backup, st_old.st_atime, st_old.st_mtime);
3776 #endif
3777 #ifdef HAVE_ACL
3778 mch_set_acl(backup, acl);
3779 #endif
3780 #ifdef HAVE_SELINUX
3781 mch_copy_sec(fname, backup);
3782 #endif
3783 break;
3787 nobackup:
3788 close(fd); /* ignore errors for closing read file */
3789 vim_free(copybuf);
3791 if (backup == NULL && errmsg == NULL)
3792 errmsg = (char_u *)_("E509: Cannot create backup file (add ! to override)");
3793 /* ignore errors when forceit is TRUE */
3794 if ((some_error || errmsg != NULL) && !forceit)
3796 retval = FAIL;
3797 goto fail;
3799 errmsg = NULL;
3801 else
3803 char_u *dirp;
3804 char_u *p;
3805 char_u *rootname;
3808 * Make a backup by renaming the original file.
3811 * If 'cpoptions' includes the "W" flag, we don't want to
3812 * overwrite a read-only file. But rename may be possible
3813 * anyway, thus we need an extra check here.
3815 if (file_readonly && vim_strchr(p_cpo, CPO_FWRITE) != NULL)
3817 errnum = (char_u *)"E504: ";
3818 errmsg = (char_u *)_(err_readonly);
3819 goto fail;
3824 * Form the backup file name - change path/fo.o.h to
3825 * path/fo.o.h.bak Try all directories in 'backupdir', first one
3826 * that works is used.
3828 dirp = p_bdir;
3829 while (*dirp)
3832 * Isolate one directory name and make the backup file name.
3834 (void)copy_option_part(&dirp, IObuff, IOSIZE, ",");
3835 rootname = get_file_in_dir(fname, IObuff);
3836 if (rootname == NULL)
3837 backup = NULL;
3838 else
3840 backup = buf_modname(
3841 #ifdef SHORT_FNAME
3842 TRUE,
3843 #else
3844 (buf->b_p_sn || buf->b_shortname),
3845 #endif
3846 rootname, backup_ext, FALSE);
3847 vim_free(rootname);
3850 if (backup != NULL)
3853 * If we are not going to keep the backup file, don't
3854 * delete an existing one, try to use another name.
3855 * Change one character, just before the extension.
3857 if (!p_bk && mch_getperm(backup) >= 0)
3859 p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext);
3860 if (p < backup) /* empty file name ??? */
3861 p = backup;
3862 *p = 'z';
3863 while (*p > 'a' && mch_getperm(backup) >= 0)
3864 --*p;
3865 /* They all exist??? Must be something wrong! */
3866 if (*p == 'a')
3868 vim_free(backup);
3869 backup = NULL;
3873 if (backup != NULL)
3876 * Delete any existing backup and move the current version
3877 * to the backup. For safety, we don't remove the backup
3878 * until the write has finished successfully. And if the
3879 * 'backup' option is set, leave it around.
3882 * If the renaming of the original file to the backup file
3883 * works, quit here.
3885 if (vim_rename(fname, backup) == 0)
3886 break;
3888 vim_free(backup); /* don't do the rename below */
3889 backup = NULL;
3892 if (backup == NULL && !forceit)
3894 errmsg = (char_u *)_("E510: Can't make backup file (add ! to override)");
3895 goto fail;
3900 #if defined(UNIX) && !defined(ARCHIE)
3901 /* When using ":w!" and the file was read-only: make it writable */
3902 if (forceit && perm >= 0 && !(perm & 0200) && st_old.st_uid == getuid()
3903 && vim_strchr(p_cpo, CPO_FWRITE) == NULL)
3905 perm |= 0200;
3906 (void)mch_setperm(fname, perm);
3907 made_writable = TRUE;
3909 #endif
3911 /* When using ":w!" and writing to the current file, 'readonly' makes no
3912 * sense, reset it, unless 'Z' appears in 'cpoptions'. */
3913 if (forceit && overwriting && vim_strchr(p_cpo, CPO_KEEPRO) == NULL)
3915 buf->b_p_ro = FALSE;
3916 #ifdef FEAT_TITLE
3917 need_maketitle = TRUE; /* set window title later */
3918 #endif
3919 #ifdef FEAT_WINDOWS
3920 status_redraw_all(); /* redraw status lines later */
3921 #endif
3924 if (end > buf->b_ml.ml_line_count)
3925 end = buf->b_ml.ml_line_count;
3926 if (buf->b_ml.ml_flags & ML_EMPTY)
3927 start = end + 1;
3930 * If the original file is being overwritten, there is a small chance that
3931 * we crash in the middle of writing. Therefore the file is preserved now.
3932 * This makes all block numbers positive so that recovery does not need
3933 * the original file.
3934 * Don't do this if there is a backup file and we are exiting.
3936 if (reset_changed && !newfile && overwriting
3937 && !(exiting && backup != NULL))
3939 ml_preserve(buf, FALSE);
3940 if (got_int)
3942 errmsg = (char_u *)_(e_interr);
3943 goto restore_backup;
3947 #ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
3949 * Before risking to lose the original file verify if there's
3950 * a resource fork to preserve, and if cannot be done warn
3951 * the users. This happens when overwriting without backups.
3953 if (backup == NULL && overwriting && !append)
3954 if (mch_has_resource_fork(fname))
3956 errmsg = (char_u *)_("E460: The resource fork would be lost (add ! to override)");
3957 goto restore_backup;
3959 #endif
3961 #ifdef VMS
3962 vms_remove_version(fname); /* remove version */
3963 #endif
3964 /* Default: write the file directly. May write to a temp file for
3965 * multi-byte conversion. */
3966 wfname = fname;
3968 #ifdef FEAT_MBYTE
3969 /* Check for forced 'fileencoding' from "++opt=val" argument. */
3970 if (eap != NULL && eap->force_enc != 0)
3972 fenc = eap->cmd + eap->force_enc;
3973 fenc = enc_canonize(fenc);
3974 fenc_tofree = fenc;
3976 else
3977 fenc = buf->b_p_fenc;
3980 * Check if the file needs to be converted.
3982 converted = need_conversion(fenc);
3985 * Check if UTF-8 to UCS-2/4 or Latin1 conversion needs to be done. Or
3986 * Latin1 to Unicode conversion. This is handled in buf_write_bytes().
3987 * Prepare the flags for it and allocate bw_conv_buf when needed.
3989 if (converted && (enc_utf8 || STRCMP(p_enc, "latin1") == 0))
3991 wb_flags = get_fio_flags(fenc);
3992 if (wb_flags & (FIO_UCS2 | FIO_UCS4 | FIO_UTF16 | FIO_UTF8))
3994 /* Need to allocate a buffer to translate into. */
3995 if (wb_flags & (FIO_UCS2 | FIO_UTF16 | FIO_UTF8))
3996 write_info.bw_conv_buflen = bufsize * 2;
3997 else /* FIO_UCS4 */
3998 write_info.bw_conv_buflen = bufsize * 4;
3999 write_info.bw_conv_buf
4000 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4001 if (write_info.bw_conv_buf == NULL)
4002 end = 0;
4006 # ifdef WIN3264
4007 if (converted && wb_flags == 0 && (wb_flags = get_win_fio_flags(fenc)) != 0)
4009 /* Convert UTF-8 -> UCS-2 and UCS-2 -> DBCS. Worst-case * 4: */
4010 write_info.bw_conv_buflen = bufsize * 4;
4011 write_info.bw_conv_buf
4012 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4013 if (write_info.bw_conv_buf == NULL)
4014 end = 0;
4016 # endif
4018 # ifdef MACOS_X
4019 if (converted && wb_flags == 0 && (wb_flags = get_mac_fio_flags(fenc)) != 0)
4021 write_info.bw_conv_buflen = bufsize * 3;
4022 write_info.bw_conv_buf
4023 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4024 if (write_info.bw_conv_buf == NULL)
4025 end = 0;
4027 # endif
4029 # if defined(FEAT_EVAL) || defined(USE_ICONV)
4030 if (converted && wb_flags == 0)
4032 # ifdef USE_ICONV
4034 * Use iconv() conversion when conversion is needed and it's not done
4035 * internally.
4037 write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc,
4038 enc_utf8 ? (char_u *)"utf-8" : p_enc);
4039 if (write_info.bw_iconv_fd != (iconv_t)-1)
4041 /* We're going to use iconv(), allocate a buffer to convert in. */
4042 write_info.bw_conv_buflen = bufsize * ICONV_MULT;
4043 write_info.bw_conv_buf
4044 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4045 if (write_info.bw_conv_buf == NULL)
4046 end = 0;
4047 write_info.bw_first = TRUE;
4049 # ifdef FEAT_EVAL
4050 else
4051 # endif
4052 # endif
4054 # ifdef FEAT_EVAL
4056 * When the file needs to be converted with 'charconvert' after
4057 * writing, write to a temp file instead and let the conversion
4058 * overwrite the original file.
4060 if (*p_ccv != NUL)
4062 wfname = vim_tempname('w');
4063 if (wfname == NULL) /* Can't write without a tempfile! */
4065 errmsg = (char_u *)_("E214: Can't find temp file for writing");
4066 goto restore_backup;
4069 # endif
4071 # endif
4072 if (converted && wb_flags == 0
4073 # ifdef USE_ICONV
4074 && write_info.bw_iconv_fd == (iconv_t)-1
4075 # endif
4076 # ifdef FEAT_EVAL
4077 && wfname == fname
4078 # endif
4081 if (!forceit)
4083 errmsg = (char_u *)_("E213: Cannot convert (add ! to write without conversion)");
4084 goto restore_backup;
4086 notconverted = TRUE;
4088 #endif
4091 * Open the file "wfname" for writing.
4092 * We may try to open the file twice: If we can't write to the
4093 * file and forceit is TRUE we delete the existing file and try to create
4094 * a new one. If this still fails we may have lost the original file!
4095 * (this may happen when the user reached his quotum for number of files).
4096 * Appending will fail if the file does not exist and forceit is FALSE.
4098 while ((fd = mch_open((char *)wfname, O_WRONLY | O_EXTRA | (append
4099 ? (forceit ? (O_APPEND | O_CREAT) : O_APPEND)
4100 : (O_CREAT | O_TRUNC))
4101 , perm < 0 ? 0666 : (perm & 0777))) < 0)
4104 * A forced write will try to create a new file if the old one is
4105 * still readonly. This may also happen when the directory is
4106 * read-only. In that case the mch_remove() will fail.
4108 if (errmsg == NULL)
4110 #ifdef UNIX
4111 struct stat st;
4113 /* Don't delete the file when it's a hard or symbolic link. */
4114 if ((!newfile && st_old.st_nlink > 1)
4115 || (mch_lstat((char *)fname, &st) == 0
4116 && (st.st_dev != st_old.st_dev
4117 || st.st_ino != st_old.st_ino)))
4118 errmsg = (char_u *)_("E166: Can't open linked file for writing");
4119 else
4120 #endif
4122 errmsg = (char_u *)_("E212: Can't open file for writing");
4123 if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL
4124 && perm >= 0)
4126 #ifdef UNIX
4127 /* we write to the file, thus it should be marked
4128 writable after all */
4129 if (!(perm & 0200))
4130 made_writable = TRUE;
4131 perm |= 0200;
4132 if (st_old.st_uid != getuid() || st_old.st_gid != getgid())
4133 perm &= 0777;
4134 #endif
4135 if (!append) /* don't remove when appending */
4136 mch_remove(wfname);
4137 continue;
4142 restore_backup:
4144 struct stat st;
4147 * If we failed to open the file, we don't need a backup. Throw it
4148 * away. If we moved or removed the original file try to put the
4149 * backup in its place.
4151 if (backup != NULL && wfname == fname)
4153 if (backup_copy)
4156 * There is a small chance that we removed the original,
4157 * try to move the copy in its place.
4158 * This may not work if the vim_rename() fails.
4159 * In that case we leave the copy around.
4161 /* If file does not exist, put the copy in its place */
4162 if (mch_stat((char *)fname, &st) < 0)
4163 vim_rename(backup, fname);
4164 /* if original file does exist throw away the copy */
4165 if (mch_stat((char *)fname, &st) >= 0)
4166 mch_remove(backup);
4168 else
4170 /* try to put the original file back */
4171 vim_rename(backup, fname);
4175 /* if original file no longer exists give an extra warning */
4176 if (!newfile && mch_stat((char *)fname, &st) < 0)
4177 end = 0;
4180 #ifdef FEAT_MBYTE
4181 if (wfname != fname)
4182 vim_free(wfname);
4183 #endif
4184 goto fail;
4186 errmsg = NULL;
4188 #if defined(MACOS_CLASSIC) || defined(WIN3264)
4189 /* TODO: Is it need for MACOS_X? (Dany) */
4191 * On macintosh copy the original files attributes (i.e. the backup)
4192 * This is done in order to preserve the resource fork and the
4193 * Finder attribute (label, comments, custom icons, file creator)
4195 if (backup != NULL && overwriting && !append)
4197 if (backup_copy)
4198 (void)mch_copy_file_attribute(wfname, backup);
4199 else
4200 (void)mch_copy_file_attribute(backup, wfname);
4203 if (!overwriting && !append)
4205 if (buf->b_ffname != NULL)
4206 (void)mch_copy_file_attribute(buf->b_ffname, wfname);
4207 /* Should copy resource fork */
4209 #endif
4211 write_info.bw_fd = fd;
4213 #ifdef FEAT_CRYPT
4214 if (*buf->b_p_key && !filtering)
4216 crypt_init_keys(buf->b_p_key);
4217 /* Write magic number, so that Vim knows that this file is encrypted
4218 * when reading it again. This also undergoes utf-8 to ucs-2/4
4219 * conversion when needed. */
4220 write_info.bw_buf = (char_u *)CRYPT_MAGIC;
4221 write_info.bw_len = CRYPT_MAGIC_LEN;
4222 write_info.bw_flags = FIO_NOCONVERT;
4223 if (buf_write_bytes(&write_info) == FAIL)
4224 end = 0;
4225 wb_flags |= FIO_ENCRYPTED;
4227 #endif
4229 write_info.bw_buf = buffer;
4230 nchars = 0;
4232 /* use "++bin", "++nobin" or 'binary' */
4233 if (eap != NULL && eap->force_bin != 0)
4234 write_bin = (eap->force_bin == FORCE_BIN);
4235 else
4236 write_bin = buf->b_p_bin;
4238 #ifdef FEAT_MBYTE
4240 * The BOM is written just after the encryption magic number.
4241 * Skip it when appending and the file already existed, the BOM only makes
4242 * sense at the start of the file.
4244 if (buf->b_p_bomb && !write_bin && (!append || perm < 0))
4246 write_info.bw_len = make_bom(buffer, fenc);
4247 if (write_info.bw_len > 0)
4249 /* don't convert, do encryption */
4250 write_info.bw_flags = FIO_NOCONVERT | wb_flags;
4251 if (buf_write_bytes(&write_info) == FAIL)
4252 end = 0;
4253 else
4254 nchars += write_info.bw_len;
4257 write_info.bw_start_lnum = start;
4258 #endif
4260 write_info.bw_len = bufsize;
4261 #ifdef HAS_BW_FLAGS
4262 write_info.bw_flags = wb_flags;
4263 #endif
4264 fileformat = get_fileformat_force(buf, eap);
4265 s = buffer;
4266 len = 0;
4267 for (lnum = start; lnum <= end; ++lnum)
4270 * The next while loop is done once for each character written.
4271 * Keep it fast!
4273 ptr = ml_get_buf(buf, lnum, FALSE) - 1;
4274 while ((c = *++ptr) != NUL)
4276 if (c == NL)
4277 *s = NUL; /* replace newlines with NULs */
4278 else if (c == CAR && fileformat == EOL_MAC)
4279 *s = NL; /* Mac: replace CRs with NLs */
4280 else
4281 *s = c;
4282 ++s;
4283 if (++len != bufsize)
4284 continue;
4285 if (buf_write_bytes(&write_info) == FAIL)
4287 end = 0; /* write error: break loop */
4288 break;
4290 nchars += bufsize;
4291 s = buffer;
4292 len = 0;
4293 #ifdef FEAT_MBYTE
4294 write_info.bw_start_lnum = lnum;
4295 #endif
4297 /* write failed or last line has no EOL: stop here */
4298 if (end == 0
4299 || (lnum == end
4300 && write_bin
4301 && (lnum == write_no_eol_lnum
4302 || (lnum == buf->b_ml.ml_line_count && !buf->b_p_eol))))
4304 ++lnum; /* written the line, count it */
4305 no_eol = TRUE;
4306 break;
4308 if (fileformat == EOL_UNIX)
4309 *s++ = NL;
4310 else
4312 *s++ = CAR; /* EOL_MAC or EOL_DOS: write CR */
4313 if (fileformat == EOL_DOS) /* write CR-NL */
4315 if (++len == bufsize)
4317 if (buf_write_bytes(&write_info) == FAIL)
4319 end = 0; /* write error: break loop */
4320 break;
4322 nchars += bufsize;
4323 s = buffer;
4324 len = 0;
4326 *s++ = NL;
4329 if (++len == bufsize && end)
4331 if (buf_write_bytes(&write_info) == FAIL)
4333 end = 0; /* write error: break loop */
4334 break;
4336 nchars += bufsize;
4337 s = buffer;
4338 len = 0;
4340 ui_breakcheck();
4341 if (got_int)
4343 end = 0; /* Interrupted, break loop */
4344 break;
4347 #ifdef VMS
4349 * On VMS there is a problem: newlines get added when writing blocks
4350 * at a time. Fix it by writing a line at a time.
4351 * This is much slower!
4352 * Explanation: VAX/DECC RTL insists that records in some RMS
4353 * structures end with a newline (carriage return) character, and if
4354 * they don't it adds one.
4355 * With other RMS structures it works perfect without this fix.
4357 if (buf->b_fab_rfm == FAB$C_VFC
4358 || ((buf->b_fab_rat & (FAB$M_FTN | FAB$M_CR)) != 0))
4360 int b2write;
4362 buf->b_fab_mrs = (buf->b_fab_mrs == 0
4363 ? MIN(4096, bufsize)
4364 : MIN(buf->b_fab_mrs, bufsize));
4366 b2write = len;
4367 while (b2write > 0)
4369 write_info.bw_len = MIN(b2write, buf->b_fab_mrs);
4370 if (buf_write_bytes(&write_info) == FAIL)
4372 end = 0;
4373 break;
4375 b2write -= MIN(b2write, buf->b_fab_mrs);
4377 write_info.bw_len = bufsize;
4378 nchars += len;
4379 s = buffer;
4380 len = 0;
4382 #endif
4384 if (len > 0 && end > 0)
4386 write_info.bw_len = len;
4387 if (buf_write_bytes(&write_info) == FAIL)
4388 end = 0; /* write error */
4389 nchars += len;
4392 #if defined(UNIX) && defined(HAVE_FSYNC)
4393 /* On many journalling file systems there is a bug that causes both the
4394 * original and the backup file to be lost when halting the system right
4395 * after writing the file. That's because only the meta-data is
4396 * journalled. Syncing the file slows down the system, but assures it has
4397 * been written to disk and we don't lose it.
4398 * For a device do try the fsync() but don't complain if it does not work
4399 * (could be a pipe).
4400 * If the 'fsync' option is FALSE, don't fsync(). Useful for laptops. */
4401 if (p_fs && fsync(fd) != 0 && !device)
4403 errmsg = (char_u *)_("E667: Fsync failed");
4404 end = 0;
4406 #endif
4408 #ifdef HAVE_SELINUX
4409 /* Probably need to set the security context. */
4410 if (!backup_copy)
4411 mch_copy_sec(backup, wfname);
4412 #endif
4414 #ifdef UNIX
4415 /* When creating a new file, set its owner/group to that of the original
4416 * file. Get the new device and inode number. */
4417 if (backup != NULL && !backup_copy)
4419 # ifdef HAVE_FCHOWN
4420 struct stat st;
4422 /* don't change the owner when it's already OK, some systems remove
4423 * permission or ACL stuff */
4424 if (mch_stat((char *)wfname, &st) < 0
4425 || st.st_uid != st_old.st_uid
4426 || st.st_gid != st_old.st_gid)
4428 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
4429 if (perm >= 0) /* set permission again, may have changed */
4430 (void)mch_setperm(wfname, perm);
4432 # endif
4433 buf_setino(buf);
4435 else if (!buf->b_dev_valid)
4436 /* Set the inode when creating a new file. */
4437 buf_setino(buf);
4438 #endif
4440 if (close(fd) != 0)
4442 errmsg = (char_u *)_("E512: Close failed");
4443 end = 0;
4446 #ifdef UNIX
4447 if (made_writable)
4448 perm &= ~0200; /* reset 'w' bit for security reasons */
4449 #endif
4450 if (perm >= 0) /* set perm. of new file same as old file */
4451 (void)mch_setperm(wfname, perm);
4452 #ifdef RISCOS
4453 if (!append && !filtering)
4454 /* Set the filetype after writing the file. */
4455 mch_set_filetype(wfname, buf->b_p_oft);
4456 #endif
4457 #ifdef HAVE_ACL
4458 /* Probably need to set the ACL before changing the user (can't set the
4459 * ACL on a file the user doesn't own). */
4460 if (!backup_copy)
4461 mch_set_acl(wfname, acl);
4462 #endif
4465 #if defined(FEAT_MBYTE) && defined(FEAT_EVAL)
4466 if (wfname != fname)
4469 * The file was written to a temp file, now it needs to be converted
4470 * with 'charconvert' to (overwrite) the output file.
4472 if (end != 0)
4474 if (eval_charconvert(enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc,
4475 wfname, fname) == FAIL)
4477 write_info.bw_conv_error = TRUE;
4478 end = 0;
4481 mch_remove(wfname);
4482 vim_free(wfname);
4484 #endif
4486 if (end == 0)
4488 if (errmsg == NULL)
4490 #ifdef FEAT_MBYTE
4491 if (write_info.bw_conv_error)
4493 if (write_info.bw_conv_error_lnum == 0)
4494 errmsg = (char_u *)_("E513: write error, conversion failed (make 'fenc' empty to override)");
4495 else
4497 errmsg_allocated = TRUE;
4498 errmsg = alloc(300);
4499 vim_snprintf((char *)errmsg, 300, _("E513: write error, conversion failed in line %ld (make 'fenc' empty to override)"),
4500 (long)write_info.bw_conv_error_lnum);
4503 else
4504 #endif
4505 if (got_int)
4506 errmsg = (char_u *)_(e_interr);
4507 else
4508 errmsg = (char_u *)_("E514: write error (file system full?)");
4512 * If we have a backup file, try to put it in place of the new file,
4513 * because the new file is probably corrupt. This avoids losing the
4514 * original file when trying to make a backup when writing the file a
4515 * second time.
4516 * When "backup_copy" is set we need to copy the backup over the new
4517 * file. Otherwise rename the backup file.
4518 * If this is OK, don't give the extra warning message.
4520 if (backup != NULL)
4522 if (backup_copy)
4524 /* This may take a while, if we were interrupted let the user
4525 * know we got the message. */
4526 if (got_int)
4528 MSG(_(e_interr));
4529 out_flush();
4531 if ((fd = mch_open((char *)backup, O_RDONLY | O_EXTRA, 0)) >= 0)
4533 if ((write_info.bw_fd = mch_open((char *)fname,
4534 O_WRONLY | O_CREAT | O_TRUNC | O_EXTRA,
4535 perm & 0777)) >= 0)
4537 /* copy the file. */
4538 write_info.bw_buf = smallbuf;
4539 #ifdef HAS_BW_FLAGS
4540 write_info.bw_flags = FIO_NOCONVERT;
4541 #endif
4542 while ((write_info.bw_len = vim_read(fd, smallbuf,
4543 SMBUFSIZE)) > 0)
4544 if (buf_write_bytes(&write_info) == FAIL)
4545 break;
4547 if (close(write_info.bw_fd) >= 0
4548 && write_info.bw_len == 0)
4549 end = 1; /* success */
4551 close(fd); /* ignore errors for closing read file */
4554 else
4556 if (vim_rename(backup, fname) == 0)
4557 end = 1;
4560 goto fail;
4563 lnum -= start; /* compute number of written lines */
4564 --no_wait_return; /* may wait for return now */
4566 #if !(defined(UNIX) || defined(VMS))
4567 fname = sfname; /* use shortname now, for the messages */
4568 #endif
4569 if (!filtering)
4571 msg_add_fname(buf, fname); /* put fname in IObuff with quotes */
4572 c = FALSE;
4573 #ifdef FEAT_MBYTE
4574 if (write_info.bw_conv_error)
4576 STRCAT(IObuff, _(" CONVERSION ERROR"));
4577 c = TRUE;
4578 if (write_info.bw_conv_error_lnum != 0)
4580 size_t l = STRLEN(IObuff);
4581 vim_snprintf((char *)IObuff + l, IOSIZE - l, _(" in line %ld;"),
4582 (long)write_info.bw_conv_error_lnum);
4585 else if (notconverted)
4587 STRCAT(IObuff, _("[NOT converted]"));
4588 c = TRUE;
4590 else if (converted)
4592 STRCAT(IObuff, _("[converted]"));
4593 c = TRUE;
4595 #endif
4596 if (device)
4598 STRCAT(IObuff, _("[Device]"));
4599 c = TRUE;
4601 else if (newfile)
4603 STRCAT(IObuff, shortmess(SHM_NEW) ? _("[New]") : _("[New File]"));
4604 c = TRUE;
4606 if (no_eol)
4608 msg_add_eol();
4609 c = TRUE;
4611 /* may add [unix/dos/mac] */
4612 if (msg_add_fileformat(fileformat))
4613 c = TRUE;
4614 #ifdef FEAT_CRYPT
4615 if (wb_flags & FIO_ENCRYPTED)
4617 STRCAT(IObuff, _("[crypted]"));
4618 c = TRUE;
4620 #endif
4621 msg_add_lines(c, (long)lnum, nchars); /* add line/char count */
4622 if (!shortmess(SHM_WRITE))
4624 if (append)
4625 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended"));
4626 else
4627 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written"));
4630 set_keep_msg(msg_trunc_attr(IObuff, FALSE, 0), 0);
4633 /* When written everything correctly: reset 'modified'. Unless not
4634 * writing to the original file and '+' is not in 'cpoptions'. */
4635 if (reset_changed && whole && !append
4636 #ifdef FEAT_MBYTE
4637 && !write_info.bw_conv_error
4638 #endif
4639 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL)
4642 unchanged(buf, TRUE);
4643 u_unchanged(buf);
4647 * If written to the current file, update the timestamp of the swap file
4648 * and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
4650 if (overwriting)
4652 ml_timestamp(buf);
4653 if (append)
4654 buf->b_flags &= ~BF_NEW;
4655 else
4656 buf->b_flags &= ~BF_WRITE_MASK;
4660 * If we kept a backup until now, and we are in patch mode, then we make
4661 * the backup file our 'original' file.
4663 if (*p_pm && dobackup)
4665 char *org = (char *)buf_modname(
4666 #ifdef SHORT_FNAME
4667 TRUE,
4668 #else
4669 (buf->b_p_sn || buf->b_shortname),
4670 #endif
4671 fname, p_pm, FALSE);
4673 if (backup != NULL)
4675 struct stat st;
4678 * If the original file does not exist yet
4679 * the current backup file becomes the original file
4681 if (org == NULL)
4682 EMSG(_("E205: Patchmode: can't save original file"));
4683 else if (mch_stat(org, &st) < 0)
4685 vim_rename(backup, (char_u *)org);
4686 vim_free(backup); /* don't delete the file */
4687 backup = NULL;
4688 #ifdef UNIX
4689 set_file_time((char_u *)org, st_old.st_atime, st_old.st_mtime);
4690 #endif
4694 * If there is no backup file, remember that a (new) file was
4695 * created.
4697 else
4699 int empty_fd;
4701 if (org == NULL
4702 || (empty_fd = mch_open(org,
4703 O_CREAT | O_EXTRA | O_EXCL | O_NOFOLLOW,
4704 perm < 0 ? 0666 : (perm & 0777))) < 0)
4705 EMSG(_("E206: patchmode: can't touch empty original file"));
4706 else
4707 close(empty_fd);
4709 if (org != NULL)
4711 mch_setperm((char_u *)org, mch_getperm(fname) & 0777);
4712 vim_free(org);
4717 * Remove the backup unless 'backup' option is set
4719 if (!p_bk && backup != NULL && mch_remove(backup) != 0)
4720 EMSG(_("E207: Can't delete backup file"));
4722 #ifdef FEAT_SUN_WORKSHOP
4723 if (usingSunWorkShop)
4724 workshop_file_saved((char *) ffname);
4725 #endif
4727 goto nofail;
4730 * Finish up. We get here either after failure or success.
4732 fail:
4733 --no_wait_return; /* may wait for return now */
4734 nofail:
4736 /* Done saving, we accept changed buffer warnings again */
4737 buf->b_saving = FALSE;
4739 vim_free(backup);
4740 if (buffer != smallbuf)
4741 vim_free(buffer);
4742 #ifdef FEAT_MBYTE
4743 vim_free(fenc_tofree);
4744 vim_free(write_info.bw_conv_buf);
4745 # ifdef USE_ICONV
4746 if (write_info.bw_iconv_fd != (iconv_t)-1)
4748 iconv_close(write_info.bw_iconv_fd);
4749 write_info.bw_iconv_fd = (iconv_t)-1;
4751 # endif
4752 #endif
4753 #ifdef HAVE_ACL
4754 mch_free_acl(acl);
4755 #endif
4757 if (errmsg != NULL)
4759 int numlen = errnum != NULL ? (int)STRLEN(errnum) : 0;
4761 attr = hl_attr(HLF_E); /* set highlight for error messages */
4762 msg_add_fname(buf,
4763 #ifndef UNIX
4764 sfname
4765 #else
4766 fname
4767 #endif
4768 ); /* put file name in IObuff with quotes */
4769 if (STRLEN(IObuff) + STRLEN(errmsg) + numlen >= IOSIZE)
4770 IObuff[IOSIZE - STRLEN(errmsg) - numlen - 1] = NUL;
4771 /* If the error message has the form "is ...", put the error number in
4772 * front of the file name. */
4773 if (errnum != NULL)
4775 STRMOVE(IObuff + numlen, IObuff);
4776 mch_memmove(IObuff, errnum, (size_t)numlen);
4778 STRCAT(IObuff, errmsg);
4779 emsg(IObuff);
4780 if (errmsg_allocated)
4781 vim_free(errmsg);
4783 retval = FAIL;
4784 if (end == 0)
4786 MSG_PUTS_ATTR(_("\nWARNING: Original file may be lost or damaged\n"),
4787 attr | MSG_HIST);
4788 MSG_PUTS_ATTR(_("don't quit the editor until the file is successfully written!"),
4789 attr | MSG_HIST);
4791 /* Update the timestamp to avoid an "overwrite changed file"
4792 * prompt when writing again. */
4793 if (mch_stat((char *)fname, &st_old) >= 0)
4795 buf_store_time(buf, &st_old, fname);
4796 buf->b_mtime_read = buf->b_mtime;
4800 msg_scroll = msg_save;
4802 #ifdef FEAT_AUTOCMD
4803 #ifdef FEAT_EVAL
4804 if (!should_abort(retval))
4805 #else
4806 if (!got_int)
4807 #endif
4809 aco_save_T aco;
4811 write_no_eol_lnum = 0; /* in case it was set by the previous read */
4814 * Apply POST autocommands.
4815 * Careful: The autocommands may call buf_write() recursively!
4817 aucmd_prepbuf(&aco, buf);
4819 if (append)
4820 apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname,
4821 FALSE, curbuf, eap);
4822 else if (filtering)
4823 apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname,
4824 FALSE, curbuf, eap);
4825 else if (reset_changed && whole)
4826 apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname,
4827 FALSE, curbuf, eap);
4828 else
4829 apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname,
4830 FALSE, curbuf, eap);
4832 /* restore curwin/curbuf and a few other things */
4833 aucmd_restbuf(&aco);
4835 #ifdef FEAT_EVAL
4836 if (aborting()) /* autocmds may abort script processing */
4837 retval = FALSE;
4838 #endif
4840 #endif
4842 got_int |= prev_got_int;
4844 #ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
4845 /* Update machine specific information. */
4846 mch_post_buffer_write(buf);
4847 #endif
4848 return retval;
4852 * Set the name of the current buffer. Use when the buffer doesn't have a
4853 * name and a ":r" or ":w" command with a file name is used.
4855 static int
4856 set_rw_fname(fname, sfname)
4857 char_u *fname;
4858 char_u *sfname;
4860 #ifdef FEAT_AUTOCMD
4861 buf_T *buf = curbuf;
4863 /* It's like the unnamed buffer is deleted.... */
4864 if (curbuf->b_p_bl)
4865 apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
4866 apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf);
4867 # ifdef FEAT_EVAL
4868 if (aborting()) /* autocmds may abort script processing */
4869 return FAIL;
4870 # endif
4871 if (curbuf != buf)
4873 /* We are in another buffer now, don't do the renaming. */
4874 EMSG(_(e_auchangedbuf));
4875 return FAIL;
4877 #endif
4879 if (setfname(curbuf, fname, sfname, FALSE) == OK)
4880 curbuf->b_flags |= BF_NOTEDITED;
4882 #ifdef FEAT_AUTOCMD
4883 /* ....and a new named one is created */
4884 apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, curbuf);
4885 if (curbuf->b_p_bl)
4886 apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf);
4887 # ifdef FEAT_EVAL
4888 if (aborting()) /* autocmds may abort script processing */
4889 return FAIL;
4890 # endif
4892 /* Do filetype detection now if 'filetype' is empty. */
4893 if (*curbuf->b_p_ft == NUL)
4895 if (au_has_group((char_u *)"filetypedetect"))
4896 (void)do_doautocmd((char_u *)"filetypedetect BufRead", FALSE);
4897 do_modelines(0);
4899 #endif
4901 return OK;
4905 * Put file name into IObuff with quotes.
4907 void
4908 msg_add_fname(buf, fname)
4909 buf_T *buf;
4910 char_u *fname;
4912 if (fname == NULL)
4913 fname = (char_u *)"-stdin-";
4914 home_replace(buf, fname, IObuff + 1, IOSIZE - 4, TRUE);
4915 IObuff[0] = '"';
4916 STRCAT(IObuff, "\" ");
4920 * Append message for text mode to IObuff.
4921 * Return TRUE if something appended.
4923 static int
4924 msg_add_fileformat(eol_type)
4925 int eol_type;
4927 #ifndef USE_CRNL
4928 if (eol_type == EOL_DOS)
4930 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[dos]") : _("[dos format]"));
4931 return TRUE;
4933 #endif
4934 #ifndef USE_CR
4935 if (eol_type == EOL_MAC)
4937 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[mac]") : _("[mac format]"));
4938 return TRUE;
4940 #endif
4941 #if defined(USE_CRNL) || defined(USE_CR)
4942 if (eol_type == EOL_UNIX)
4944 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[unix]") : _("[unix format]"));
4945 return TRUE;
4947 #endif
4948 return FALSE;
4952 * Append line and character count to IObuff.
4954 void
4955 msg_add_lines(insert_space, lnum, nchars)
4956 int insert_space;
4957 long lnum;
4958 long nchars;
4960 char_u *p;
4962 p = IObuff + STRLEN(IObuff);
4964 if (insert_space)
4965 *p++ = ' ';
4966 if (shortmess(SHM_LINES))
4967 sprintf((char *)p, "%ldL, %ldC", lnum, nchars);
4968 else
4970 if (lnum == 1)
4971 STRCPY(p, _("1 line, "));
4972 else
4973 sprintf((char *)p, _("%ld lines, "), lnum);
4974 p += STRLEN(p);
4975 if (nchars == 1)
4976 STRCPY(p, _("1 character"));
4977 else
4978 sprintf((char *)p, _("%ld characters"), nchars);
4983 * Append message for missing line separator to IObuff.
4985 static void
4986 msg_add_eol()
4988 STRCAT(IObuff, shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]"));
4992 * Check modification time of file, before writing to it.
4993 * The size isn't checked, because using a tool like "gzip" takes care of
4994 * using the same timestamp but can't set the size.
4996 static int
4997 check_mtime(buf, st)
4998 buf_T *buf;
4999 struct stat *st;
5001 if (buf->b_mtime_read != 0
5002 && time_differs((long)st->st_mtime, buf->b_mtime_read))
5004 msg_scroll = TRUE; /* don't overwrite messages here */
5005 msg_silent = 0; /* must give this prompt */
5006 /* don't use emsg() here, don't want to flush the buffers */
5007 MSG_ATTR(_("WARNING: The file has been changed since reading it!!!"),
5008 hl_attr(HLF_E));
5009 if (ask_yesno((char_u *)_("Do you really want to write to it"),
5010 TRUE) == 'n')
5011 return FAIL;
5012 msg_scroll = FALSE; /* always overwrite the file message now */
5014 return OK;
5017 static int
5018 time_differs(t1, t2)
5019 long t1, t2;
5021 #if defined(__linux__) || defined(MSDOS) || defined(MSWIN)
5022 /* On a FAT filesystem, esp. under Linux, there are only 5 bits to store
5023 * the seconds. Since the roundoff is done when flushing the inode, the
5024 * time may change unexpectedly by one second!!! */
5025 return (t1 - t2 > 1 || t2 - t1 > 1);
5026 #else
5027 return (t1 != t2);
5028 #endif
5032 * Call write() to write a number of bytes to the file.
5033 * Also handles encryption and 'encoding' conversion.
5035 * Return FAIL for failure, OK otherwise.
5037 static int
5038 buf_write_bytes(ip)
5039 struct bw_info *ip;
5041 int wlen;
5042 char_u *buf = ip->bw_buf; /* data to write */
5043 int len = ip->bw_len; /* length of data */
5044 #ifdef HAS_BW_FLAGS
5045 int flags = ip->bw_flags; /* extra flags */
5046 #endif
5048 #ifdef FEAT_MBYTE
5050 * Skip conversion when writing the crypt magic number or the BOM.
5052 if (!(flags & FIO_NOCONVERT))
5054 char_u *p;
5055 unsigned c;
5056 int n;
5058 if (flags & FIO_UTF8)
5061 * Convert latin1 in the buffer to UTF-8 in the file.
5063 p = ip->bw_conv_buf; /* translate to buffer */
5064 for (wlen = 0; wlen < len; ++wlen)
5065 p += utf_char2bytes(buf[wlen], p);
5066 buf = ip->bw_conv_buf;
5067 len = (int)(p - ip->bw_conv_buf);
5069 else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1))
5072 * Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
5073 * Latin1 chars in the file.
5075 if (flags & FIO_LATIN1)
5076 p = buf; /* translate in-place (can only get shorter) */
5077 else
5078 p = ip->bw_conv_buf; /* translate to buffer */
5079 for (wlen = 0; wlen < len; wlen += n)
5081 if (wlen == 0 && ip->bw_restlen != 0)
5083 int l;
5085 /* Use remainder of previous call. Append the start of
5086 * buf[] to get a full sequence. Might still be too
5087 * short! */
5088 l = CONV_RESTLEN - ip->bw_restlen;
5089 if (l > len)
5090 l = len;
5091 mch_memmove(ip->bw_rest + ip->bw_restlen, buf, (size_t)l);
5092 n = utf_ptr2len_len(ip->bw_rest, ip->bw_restlen + l);
5093 if (n > ip->bw_restlen + len)
5095 /* We have an incomplete byte sequence at the end to
5096 * be written. We can't convert it without the
5097 * remaining bytes. Keep them for the next call. */
5098 if (ip->bw_restlen + len > CONV_RESTLEN)
5099 return FAIL;
5100 ip->bw_restlen += len;
5101 break;
5103 if (n > 1)
5104 c = utf_ptr2char(ip->bw_rest);
5105 else
5106 c = ip->bw_rest[0];
5107 if (n >= ip->bw_restlen)
5109 n -= ip->bw_restlen;
5110 ip->bw_restlen = 0;
5112 else
5114 ip->bw_restlen -= n;
5115 mch_memmove(ip->bw_rest, ip->bw_rest + n,
5116 (size_t)ip->bw_restlen);
5117 n = 0;
5120 else
5122 n = utf_ptr2len_len(buf + wlen, len - wlen);
5123 if (n > len - wlen)
5125 /* We have an incomplete byte sequence at the end to
5126 * be written. We can't convert it without the
5127 * remaining bytes. Keep them for the next call. */
5128 if (len - wlen > CONV_RESTLEN)
5129 return FAIL;
5130 ip->bw_restlen = len - wlen;
5131 mch_memmove(ip->bw_rest, buf + wlen,
5132 (size_t)ip->bw_restlen);
5133 break;
5135 if (n > 1)
5136 c = utf_ptr2char(buf + wlen);
5137 else
5138 c = buf[wlen];
5141 if (ucs2bytes(c, &p, flags) && !ip->bw_conv_error)
5143 ip->bw_conv_error = TRUE;
5144 ip->bw_conv_error_lnum = ip->bw_start_lnum;
5146 if (c == NL)
5147 ++ip->bw_start_lnum;
5149 if (flags & FIO_LATIN1)
5150 len = (int)(p - buf);
5151 else
5153 buf = ip->bw_conv_buf;
5154 len = (int)(p - ip->bw_conv_buf);
5158 # ifdef WIN3264
5159 else if (flags & FIO_CODEPAGE)
5162 * Convert UTF-8 or codepage to UCS-2 and then to MS-Windows
5163 * codepage.
5165 char_u *from;
5166 size_t fromlen;
5167 char_u *to;
5168 int u8c;
5169 BOOL bad = FALSE;
5170 int needed;
5172 if (ip->bw_restlen > 0)
5174 /* Need to concatenate the remainder of the previous call and
5175 * the bytes of the current call. Use the end of the
5176 * conversion buffer for this. */
5177 fromlen = len + ip->bw_restlen;
5178 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5179 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5180 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5182 else
5184 from = buf;
5185 fromlen = len;
5188 to = ip->bw_conv_buf;
5189 if (enc_utf8)
5191 /* Convert from UTF-8 to UCS-2, to the start of the buffer.
5192 * The buffer has been allocated to be big enough. */
5193 while (fromlen > 0)
5195 n = (int)utf_ptr2len_len(from, (int)fromlen);
5196 if (n > (int)fromlen) /* incomplete byte sequence */
5197 break;
5198 u8c = utf_ptr2char(from);
5199 *to++ = (u8c & 0xff);
5200 *to++ = (u8c >> 8);
5201 fromlen -= n;
5202 from += n;
5205 /* Copy remainder to ip->bw_rest[] to be used for the next
5206 * call. */
5207 if (fromlen > CONV_RESTLEN)
5209 /* weird overlong sequence */
5210 ip->bw_conv_error = TRUE;
5211 return FAIL;
5213 mch_memmove(ip->bw_rest, from, fromlen);
5214 ip->bw_restlen = (int)fromlen;
5216 else
5218 /* Convert from enc_codepage to UCS-2, to the start of the
5219 * buffer. The buffer has been allocated to be big enough. */
5220 ip->bw_restlen = 0;
5221 needed = MultiByteToWideChar(enc_codepage,
5222 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen,
5223 NULL, 0);
5224 if (needed == 0)
5226 /* When conversion fails there may be a trailing byte. */
5227 needed = MultiByteToWideChar(enc_codepage,
5228 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen - 1,
5229 NULL, 0);
5230 if (needed == 0)
5232 /* Conversion doesn't work. */
5233 ip->bw_conv_error = TRUE;
5234 return FAIL;
5236 /* Save the trailing byte for the next call. */
5237 ip->bw_rest[0] = from[fromlen - 1];
5238 ip->bw_restlen = 1;
5240 needed = MultiByteToWideChar(enc_codepage, MB_ERR_INVALID_CHARS,
5241 (LPCSTR)from, (int)(fromlen - ip->bw_restlen),
5242 (LPWSTR)to, needed);
5243 if (needed == 0)
5245 /* Safety check: Conversion doesn't work. */
5246 ip->bw_conv_error = TRUE;
5247 return FAIL;
5249 to += needed * 2;
5252 fromlen = to - ip->bw_conv_buf;
5253 buf = to;
5254 # ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5255 if (FIO_GET_CP(flags) == CP_UTF8)
5257 /* Convert from UCS-2 to UTF-8, using the remainder of the
5258 * conversion buffer. Fails when out of space. */
5259 for (from = ip->bw_conv_buf; fromlen > 1; fromlen -= 2)
5261 u8c = *from++;
5262 u8c += (*from++ << 8);
5263 to += utf_char2bytes(u8c, to);
5264 if (to + 6 >= ip->bw_conv_buf + ip->bw_conv_buflen)
5266 ip->bw_conv_error = TRUE;
5267 return FAIL;
5270 len = (int)(to - buf);
5272 else
5273 #endif
5275 /* Convert from UCS-2 to the codepage, using the remainder of
5276 * the conversion buffer. If the conversion uses the default
5277 * character "0", the data doesn't fit in this encoding, so
5278 * fail. */
5279 len = WideCharToMultiByte(FIO_GET_CP(flags), 0,
5280 (LPCWSTR)ip->bw_conv_buf, (int)fromlen / sizeof(WCHAR),
5281 (LPSTR)to, (int)(ip->bw_conv_buflen - fromlen), 0,
5282 &bad);
5283 if (bad)
5285 ip->bw_conv_error = TRUE;
5286 return FAIL;
5290 # endif
5292 # ifdef MACOS_CONVERT
5293 else if (flags & FIO_MACROMAN)
5296 * Convert UTF-8 or latin1 to Apple MacRoman.
5298 char_u *from;
5299 size_t fromlen;
5301 if (ip->bw_restlen > 0)
5303 /* Need to concatenate the remainder of the previous call and
5304 * the bytes of the current call. Use the end of the
5305 * conversion buffer for this. */
5306 fromlen = len + ip->bw_restlen;
5307 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5308 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5309 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5311 else
5313 from = buf;
5314 fromlen = len;
5317 if (enc2macroman(from, fromlen,
5318 ip->bw_conv_buf, &len, ip->bw_conv_buflen,
5319 ip->bw_rest, &ip->bw_restlen) == FAIL)
5321 ip->bw_conv_error = TRUE;
5322 return FAIL;
5324 buf = ip->bw_conv_buf;
5326 # endif
5328 # ifdef USE_ICONV
5329 if (ip->bw_iconv_fd != (iconv_t)-1)
5331 const char *from;
5332 size_t fromlen;
5333 char *to;
5334 size_t tolen;
5336 /* Convert with iconv(). */
5337 if (ip->bw_restlen > 0)
5339 char *fp;
5341 /* Need to concatenate the remainder of the previous call and
5342 * the bytes of the current call. Use the end of the
5343 * conversion buffer for this. */
5344 fromlen = len + ip->bw_restlen;
5345 fp = (char *)ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5346 mch_memmove(fp, ip->bw_rest, (size_t)ip->bw_restlen);
5347 mch_memmove(fp + ip->bw_restlen, buf, (size_t)len);
5348 from = fp;
5349 tolen = ip->bw_conv_buflen - fromlen;
5351 else
5353 from = (const char *)buf;
5354 fromlen = len;
5355 tolen = ip->bw_conv_buflen;
5357 to = (char *)ip->bw_conv_buf;
5359 if (ip->bw_first)
5361 size_t save_len = tolen;
5363 /* output the initial shift state sequence */
5364 (void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen);
5366 /* There is a bug in iconv() on Linux (which appears to be
5367 * wide-spread) which sets "to" to NULL and messes up "tolen".
5369 if (to == NULL)
5371 to = (char *)ip->bw_conv_buf;
5372 tolen = save_len;
5374 ip->bw_first = FALSE;
5378 * If iconv() has an error or there is not enough room, fail.
5380 if ((iconv(ip->bw_iconv_fd, (void *)&from, &fromlen, &to, &tolen)
5381 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
5382 || fromlen > CONV_RESTLEN)
5384 ip->bw_conv_error = TRUE;
5385 return FAIL;
5388 /* copy remainder to ip->bw_rest[] to be used for the next call. */
5389 if (fromlen > 0)
5390 mch_memmove(ip->bw_rest, (void *)from, fromlen);
5391 ip->bw_restlen = (int)fromlen;
5393 buf = ip->bw_conv_buf;
5394 len = (int)((char_u *)to - ip->bw_conv_buf);
5396 # endif
5398 #endif /* FEAT_MBYTE */
5400 #ifdef FEAT_CRYPT
5401 if (flags & FIO_ENCRYPTED) /* encrypt the data */
5403 int ztemp, t, i;
5405 for (i = 0; i < len; i++)
5407 ztemp = buf[i];
5408 buf[i] = ZENCODE(ztemp, t);
5411 #endif
5413 /* Repeat the write(), it may be interrupted by a signal. */
5414 while (len > 0)
5416 wlen = vim_write(ip->bw_fd, buf, len);
5417 if (wlen <= 0) /* error! */
5418 return FAIL;
5419 len -= wlen;
5420 buf += wlen;
5422 return OK;
5425 #ifdef FEAT_MBYTE
5427 * Convert a Unicode character to bytes.
5428 * Return TRUE for an error, FALSE when it's OK.
5430 static int
5431 ucs2bytes(c, pp, flags)
5432 unsigned c; /* in: character */
5433 char_u **pp; /* in/out: pointer to result */
5434 int flags; /* FIO_ flags */
5436 char_u *p = *pp;
5437 int error = FALSE;
5438 int cc;
5441 if (flags & FIO_UCS4)
5443 if (flags & FIO_ENDIAN_L)
5445 *p++ = c;
5446 *p++ = (c >> 8);
5447 *p++ = (c >> 16);
5448 *p++ = (c >> 24);
5450 else
5452 *p++ = (c >> 24);
5453 *p++ = (c >> 16);
5454 *p++ = (c >> 8);
5455 *p++ = c;
5458 else if (flags & (FIO_UCS2 | FIO_UTF16))
5460 if (c >= 0x10000)
5462 if (flags & FIO_UTF16)
5464 /* Make two words, ten bits of the character in each. First
5465 * word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff */
5466 c -= 0x10000;
5467 if (c >= 0x100000)
5468 error = TRUE;
5469 cc = ((c >> 10) & 0x3ff) + 0xd800;
5470 if (flags & FIO_ENDIAN_L)
5472 *p++ = cc;
5473 *p++ = ((unsigned)cc >> 8);
5475 else
5477 *p++ = ((unsigned)cc >> 8);
5478 *p++ = cc;
5480 c = (c & 0x3ff) + 0xdc00;
5482 else
5483 error = TRUE;
5485 if (flags & FIO_ENDIAN_L)
5487 *p++ = c;
5488 *p++ = (c >> 8);
5490 else
5492 *p++ = (c >> 8);
5493 *p++ = c;
5496 else /* Latin1 */
5498 if (c >= 0x100)
5500 error = TRUE;
5501 *p++ = 0xBF;
5503 else
5504 *p++ = c;
5507 *pp = p;
5508 return error;
5512 * Return TRUE if file encoding "fenc" requires conversion from or to
5513 * 'encoding'.
5515 static int
5516 need_conversion(fenc)
5517 char_u *fenc;
5519 int same_encoding;
5520 int enc_flags;
5521 int fenc_flags;
5523 if (*fenc == NUL || STRCMP(p_enc, fenc) == 0)
5524 same_encoding = TRUE;
5525 else
5527 /* Ignore difference between "ansi" and "latin1", "ucs-4" and
5528 * "ucs-4be", etc. */
5529 enc_flags = get_fio_flags(p_enc);
5530 fenc_flags = get_fio_flags(fenc);
5531 same_encoding = (enc_flags != 0 && fenc_flags == enc_flags);
5533 if (same_encoding)
5535 /* Specified encoding matches with 'encoding'. This requires
5536 * conversion when 'encoding' is Unicode but not UTF-8. */
5537 return enc_unicode != 0;
5540 /* Encodings differ. However, conversion is not needed when 'enc' is any
5541 * Unicode encoding and the file is UTF-8. */
5542 return !(enc_utf8 && fenc_flags == FIO_UTF8);
5546 * Check "ptr" for a unicode encoding and return the FIO_ flags needed for the
5547 * internal conversion.
5548 * if "ptr" is an empty string, use 'encoding'.
5550 static int
5551 get_fio_flags(ptr)
5552 char_u *ptr;
5554 int prop;
5556 if (*ptr == NUL)
5557 ptr = p_enc;
5559 prop = enc_canon_props(ptr);
5560 if (prop & ENC_UNICODE)
5562 if (prop & ENC_2BYTE)
5564 if (prop & ENC_ENDIAN_L)
5565 return FIO_UCS2 | FIO_ENDIAN_L;
5566 return FIO_UCS2;
5568 if (prop & ENC_4BYTE)
5570 if (prop & ENC_ENDIAN_L)
5571 return FIO_UCS4 | FIO_ENDIAN_L;
5572 return FIO_UCS4;
5574 if (prop & ENC_2WORD)
5576 if (prop & ENC_ENDIAN_L)
5577 return FIO_UTF16 | FIO_ENDIAN_L;
5578 return FIO_UTF16;
5580 return FIO_UTF8;
5582 if (prop & ENC_LATIN1)
5583 return FIO_LATIN1;
5584 /* must be ENC_DBCS, requires iconv() */
5585 return 0;
5588 #ifdef WIN3264
5590 * Check "ptr" for a MS-Windows codepage name and return the FIO_ flags needed
5591 * for the conversion MS-Windows can do for us. Also accept "utf-8".
5592 * Used for conversion between 'encoding' and 'fileencoding'.
5594 static int
5595 get_win_fio_flags(ptr)
5596 char_u *ptr;
5598 int cp;
5600 /* Cannot do this when 'encoding' is not utf-8 and not a codepage. */
5601 if (!enc_utf8 && enc_codepage <= 0)
5602 return 0;
5604 cp = encname2codepage(ptr);
5605 if (cp == 0)
5607 # ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5608 if (STRCMP(ptr, "utf-8") == 0)
5609 cp = CP_UTF8;
5610 else
5611 # endif
5612 return 0;
5614 return FIO_PUT_CP(cp) | FIO_CODEPAGE;
5616 #endif
5618 #ifdef MACOS_X
5620 * Check "ptr" for a Carbon supported encoding and return the FIO_ flags
5621 * needed for the internal conversion to/from utf-8 or latin1.
5623 static int
5624 get_mac_fio_flags(ptr)
5625 char_u *ptr;
5627 if ((enc_utf8 || STRCMP(p_enc, "latin1") == 0)
5628 && (enc_canon_props(ptr) & ENC_MACROMAN))
5629 return FIO_MACROMAN;
5630 return 0;
5632 #endif
5635 * Check for a Unicode BOM (Byte Order Mark) at the start of p[size].
5636 * "size" must be at least 2.
5637 * Return the name of the encoding and set "*lenp" to the length.
5638 * Returns NULL when no BOM found.
5640 static char_u *
5641 check_for_bom(p, size, lenp, flags)
5642 char_u *p;
5643 long size;
5644 int *lenp;
5645 int flags;
5647 char *name = NULL;
5648 int len = 2;
5650 if (p[0] == 0xef && p[1] == 0xbb && size >= 3 && p[2] == 0xbf
5651 && (flags == FIO_ALL || flags == FIO_UTF8 || flags == 0))
5653 name = "utf-8"; /* EF BB BF */
5654 len = 3;
5656 else if (p[0] == 0xff && p[1] == 0xfe)
5658 if (size >= 4 && p[2] == 0 && p[3] == 0
5659 && (flags == FIO_ALL || flags == (FIO_UCS4 | FIO_ENDIAN_L)))
5661 name = "ucs-4le"; /* FF FE 00 00 */
5662 len = 4;
5664 else if (flags == (FIO_UCS2 | FIO_ENDIAN_L))
5665 name = "ucs-2le"; /* FF FE */
5666 else if (flags == FIO_ALL || flags == (FIO_UTF16 | FIO_ENDIAN_L))
5667 /* utf-16le is preferred, it also works for ucs-2le text */
5668 name = "utf-16le"; /* FF FE */
5670 else if (p[0] == 0xfe && p[1] == 0xff
5671 && (flags == FIO_ALL || flags == FIO_UCS2 || flags == FIO_UTF16))
5673 /* Default to utf-16, it works also for ucs-2 text. */
5674 if (flags == FIO_UCS2)
5675 name = "ucs-2"; /* FE FF */
5676 else
5677 name = "utf-16"; /* FE FF */
5679 else if (size >= 4 && p[0] == 0 && p[1] == 0 && p[2] == 0xfe
5680 && p[3] == 0xff && (flags == FIO_ALL || flags == FIO_UCS4))
5682 name = "ucs-4"; /* 00 00 FE FF */
5683 len = 4;
5686 *lenp = len;
5687 return (char_u *)name;
5691 * Generate a BOM in "buf[4]" for encoding "name".
5692 * Return the length of the BOM (zero when no BOM).
5694 static int
5695 make_bom(buf, name)
5696 char_u *buf;
5697 char_u *name;
5699 int flags;
5700 char_u *p;
5702 flags = get_fio_flags(name);
5704 /* Can't put a BOM in a non-Unicode file. */
5705 if (flags == FIO_LATIN1 || flags == 0)
5706 return 0;
5708 if (flags == FIO_UTF8) /* UTF-8 */
5710 buf[0] = 0xef;
5711 buf[1] = 0xbb;
5712 buf[2] = 0xbf;
5713 return 3;
5715 p = buf;
5716 (void)ucs2bytes(0xfeff, &p, flags);
5717 return (int)(p - buf);
5719 #endif
5721 #if defined(FEAT_VIMINFO) || defined(FEAT_BROWSE) || \
5722 defined(FEAT_QUICKFIX) || defined(FEAT_AUTOCMD) || defined(PROTO)
5724 * Try to find a shortname by comparing the fullname with the current
5725 * directory.
5726 * Returns "full_path" or pointer into "full_path" if shortened.
5728 char_u *
5729 shorten_fname1(full_path)
5730 char_u *full_path;
5732 char_u dirname[MAXPATHL];
5733 char_u *p = full_path;
5735 if (mch_dirname(dirname, MAXPATHL) == OK)
5737 p = shorten_fname(full_path, dirname);
5738 if (p == NULL || *p == NUL)
5739 p = full_path;
5741 return p;
5743 #endif
5746 * Try to find a shortname by comparing the fullname with the current
5747 * directory.
5748 * Returns NULL if not shorter name possible, pointer into "full_path"
5749 * otherwise.
5751 char_u *
5752 shorten_fname(full_path, dir_name)
5753 char_u *full_path;
5754 char_u *dir_name;
5756 int len;
5757 char_u *p;
5759 if (full_path == NULL)
5760 return NULL;
5761 len = (int)STRLEN(dir_name);
5762 if (fnamencmp(dir_name, full_path, len) == 0)
5764 p = full_path + len;
5765 #if defined(MSDOS) || defined(MSWIN) || defined(OS2)
5767 * MSDOS: when a file is in the root directory, dir_name will end in a
5768 * slash, since C: by itself does not define a specific dir. In this
5769 * case p may already be correct. <negri>
5771 if (!((len > 2) && (*(p - 2) == ':')))
5772 #endif
5774 if (vim_ispathsep(*p))
5775 ++p;
5776 #ifndef VMS /* the path separator is always part of the path */
5777 else
5778 p = NULL;
5779 #endif
5782 #if defined(MSDOS) || defined(MSWIN) || defined(OS2)
5784 * When using a file in the current drive, remove the drive name:
5785 * "A:\dir\file" -> "\dir\file". This helps when moving a session file on
5786 * a floppy from "A:\dir" to "B:\dir".
5788 else if (len > 3
5789 && TOUPPER_LOC(full_path[0]) == TOUPPER_LOC(dir_name[0])
5790 && full_path[1] == ':'
5791 && vim_ispathsep(full_path[2]))
5792 p = full_path + 2;
5793 #endif
5794 else
5795 p = NULL;
5796 return p;
5800 * Shorten filenames for all buffers.
5801 * When "force" is TRUE: Use full path from now on for files currently being
5802 * edited, both for file name and swap file name. Try to shorten the file
5803 * names a bit, if safe to do so.
5804 * When "force" is FALSE: Only try to shorten absolute file names.
5805 * For buffers that have buftype "nofile" or "scratch": never change the file
5806 * name.
5808 void
5809 shorten_fnames(force)
5810 int force;
5812 char_u dirname[MAXPATHL];
5813 buf_T *buf;
5814 char_u *p;
5816 mch_dirname(dirname, MAXPATHL);
5817 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
5819 if (buf->b_fname != NULL
5820 #ifdef FEAT_QUICKFIX
5821 && !bt_nofile(buf)
5822 #endif
5823 && !path_with_url(buf->b_fname)
5824 && (force
5825 || buf->b_sfname == NULL
5826 || mch_isFullName(buf->b_sfname)))
5828 vim_free(buf->b_sfname);
5829 buf->b_sfname = NULL;
5830 p = shorten_fname(buf->b_ffname, dirname);
5831 if (p != NULL)
5833 buf->b_sfname = vim_strsave(p);
5834 buf->b_fname = buf->b_sfname;
5836 if (p == NULL || buf->b_fname == NULL)
5837 buf->b_fname = buf->b_ffname;
5840 /* Always make the swap file name a full path, a "nofile" buffer may
5841 * also have a swap file. */
5842 mf_fullname(buf->b_ml.ml_mfp);
5844 #ifdef FEAT_WINDOWS
5845 status_redraw_all();
5846 redraw_tabline = TRUE;
5847 #endif
5850 #if (defined(FEAT_DND) && defined(FEAT_GUI_GTK)) \
5851 || defined(FEAT_GUI_MSWIN) \
5852 || defined(FEAT_GUI_MAC) \
5853 || defined(PROTO)
5855 * Shorten all filenames in "fnames[count]" by current directory.
5857 void
5858 shorten_filenames(fnames, count)
5859 char_u **fnames;
5860 int count;
5862 int i;
5863 char_u dirname[MAXPATHL];
5864 char_u *p;
5866 if (fnames == NULL || count < 1)
5867 return;
5868 mch_dirname(dirname, sizeof(dirname));
5869 for (i = 0; i < count; ++i)
5871 if ((p = shorten_fname(fnames[i], dirname)) != NULL)
5873 /* shorten_fname() returns pointer in given "fnames[i]". If free
5874 * "fnames[i]" first, "p" becomes invalid. So we need to copy
5875 * "p" first then free fnames[i]. */
5876 p = vim_strsave(p);
5877 vim_free(fnames[i]);
5878 fnames[i] = p;
5882 #endif
5885 * add extension to file name - change path/fo.o.h to path/fo.o.h.ext or
5886 * fo_o_h.ext for MSDOS or when shortname option set.
5888 * Assumed that fname is a valid name found in the filesystem we assure that
5889 * the return value is a different name and ends in 'ext'.
5890 * "ext" MUST be at most 4 characters long if it starts with a dot, 3
5891 * characters otherwise.
5892 * Space for the returned name is allocated, must be freed later.
5893 * Returns NULL when out of memory.
5895 char_u *
5896 modname(fname, ext, prepend_dot)
5897 char_u *fname, *ext;
5898 int prepend_dot; /* may prepend a '.' to file name */
5900 return buf_modname(
5901 #ifdef SHORT_FNAME
5902 TRUE,
5903 #else
5904 (curbuf->b_p_sn || curbuf->b_shortname),
5905 #endif
5906 fname, ext, prepend_dot);
5909 char_u *
5910 buf_modname(shortname, fname, ext, prepend_dot)
5911 int shortname; /* use 8.3 file name */
5912 char_u *fname, *ext;
5913 int prepend_dot; /* may prepend a '.' to file name */
5915 char_u *retval;
5916 char_u *s;
5917 char_u *e;
5918 char_u *ptr;
5919 int fnamelen, extlen;
5921 extlen = (int)STRLEN(ext);
5924 * If there is no file name we must get the name of the current directory
5925 * (we need the full path in case :cd is used).
5927 if (fname == NULL || *fname == NUL)
5929 retval = alloc((unsigned)(MAXPATHL + extlen + 3));
5930 if (retval == NULL)
5931 return NULL;
5932 if (mch_dirname(retval, MAXPATHL) == FAIL ||
5933 (fnamelen = (int)STRLEN(retval)) == 0)
5935 vim_free(retval);
5936 return NULL;
5938 if (!after_pathsep(retval, retval + fnamelen))
5940 retval[fnamelen++] = PATHSEP;
5941 retval[fnamelen] = NUL;
5943 #ifndef SHORT_FNAME
5944 prepend_dot = FALSE; /* nothing to prepend a dot to */
5945 #endif
5947 else
5949 fnamelen = (int)STRLEN(fname);
5950 retval = alloc((unsigned)(fnamelen + extlen + 3));
5951 if (retval == NULL)
5952 return NULL;
5953 STRCPY(retval, fname);
5954 #ifdef VMS
5955 vms_remove_version(retval); /* we do not need versions here */
5956 #endif
5960 * search backwards until we hit a '/', '\' or ':' replacing all '.'
5961 * by '_' for MSDOS or when shortname option set and ext starts with a dot.
5962 * Then truncate what is after the '/', '\' or ':' to 8 characters for
5963 * MSDOS and 26 characters for AMIGA, a lot more for UNIX.
5965 for (ptr = retval + fnamelen; ptr > retval; mb_ptr_back(retval, ptr))
5967 #ifndef RISCOS
5968 if (*ext == '.'
5969 # ifdef USE_LONG_FNAME
5970 && (!USE_LONG_FNAME || shortname)
5971 # else
5972 # ifndef SHORT_FNAME
5973 && shortname
5974 # endif
5975 # endif
5977 if (*ptr == '.') /* replace '.' by '_' */
5978 *ptr = '_';
5979 #endif
5980 if (vim_ispathsep(*ptr))
5982 ++ptr;
5983 break;
5987 /* the file name has at most BASENAMELEN characters. */
5988 #ifndef SHORT_FNAME
5989 if (STRLEN(ptr) > (unsigned)BASENAMELEN)
5990 ptr[BASENAMELEN] = '\0';
5991 #endif
5993 s = ptr + STRLEN(ptr);
5996 * For 8.3 file names we may have to reduce the length.
5998 #ifdef USE_LONG_FNAME
5999 if (!USE_LONG_FNAME || shortname)
6000 #else
6001 # ifndef SHORT_FNAME
6002 if (shortname)
6003 # endif
6004 #endif
6007 * If there is no file name, or the file name ends in '/', and the
6008 * extension starts with '.', put a '_' before the dot, because just
6009 * ".ext" is invalid.
6011 if (fname == NULL || *fname == NUL
6012 || vim_ispathsep(fname[STRLEN(fname) - 1]))
6014 #ifdef RISCOS
6015 if (*ext == '/')
6016 #else
6017 if (*ext == '.')
6018 #endif
6019 *s++ = '_';
6022 * If the extension starts with '.', truncate the base name at 8
6023 * characters
6025 #ifdef RISCOS
6026 /* We normally use '/', but swap files are '_' */
6027 else if (*ext == '/' || *ext == '_')
6028 #else
6029 else if (*ext == '.')
6030 #endif
6032 if ((size_t)(s - ptr) > (size_t)8)
6034 s = ptr + 8;
6035 *s = '\0';
6039 * If the extension doesn't start with '.', and the file name
6040 * doesn't have an extension yet, append a '.'
6042 #ifdef RISCOS
6043 else if ((e = vim_strchr(ptr, '/')) == NULL)
6044 *s++ = '/';
6045 #else
6046 else if ((e = vim_strchr(ptr, '.')) == NULL)
6047 *s++ = '.';
6048 #endif
6050 * If the extension doesn't start with '.', and there already is an
6051 * extension, it may need to be truncated
6053 else if ((int)STRLEN(e) + extlen > 4)
6054 s = e + 4 - extlen;
6056 #if defined(OS2) || defined(USE_LONG_FNAME) || defined(WIN3264)
6058 * If there is no file name, and the extension starts with '.', put a
6059 * '_' before the dot, because just ".ext" may be invalid if it's on a
6060 * FAT partition, and on HPFS it doesn't matter.
6062 else if ((fname == NULL || *fname == NUL) && *ext == '.')
6063 *s++ = '_';
6064 #endif
6067 * Append the extension.
6068 * ext can start with '.' and cannot exceed 3 more characters.
6070 STRCPY(s, ext);
6072 #ifndef SHORT_FNAME
6074 * Prepend the dot.
6076 if (prepend_dot && !shortname && *(e = gettail(retval)) !=
6077 #ifdef RISCOS
6079 #else
6081 #endif
6082 #ifdef USE_LONG_FNAME
6083 && USE_LONG_FNAME
6084 #endif
6087 STRMOVE(e + 1, e);
6088 #ifdef RISCOS
6089 *e = '/';
6090 #else
6091 *e = '.';
6092 #endif
6094 #endif
6097 * Check that, after appending the extension, the file name is really
6098 * different.
6100 if (fname != NULL && STRCMP(fname, retval) == 0)
6102 /* we search for a character that can be replaced by '_' */
6103 while (--s >= ptr)
6105 if (*s != '_')
6107 *s = '_';
6108 break;
6111 if (s < ptr) /* fname was "________.<ext>", how tricky! */
6112 *ptr = 'v';
6114 return retval;
6118 * Like fgets(), but if the file line is too long, it is truncated and the
6119 * rest of the line is thrown away. Returns TRUE for end-of-file.
6122 vim_fgets(buf, size, fp)
6123 char_u *buf;
6124 int size;
6125 FILE *fp;
6127 char *eof;
6128 #define FGETS_SIZE 200
6129 char tbuf[FGETS_SIZE];
6131 buf[size - 2] = NUL;
6132 #ifdef USE_CR
6133 eof = fgets_cr((char *)buf, size, fp);
6134 #else
6135 eof = fgets((char *)buf, size, fp);
6136 #endif
6137 if (buf[size - 2] != NUL && buf[size - 2] != '\n')
6139 buf[size - 1] = NUL; /* Truncate the line */
6141 /* Now throw away the rest of the line: */
6144 tbuf[FGETS_SIZE - 2] = NUL;
6145 #ifdef USE_CR
6146 ignoredp = fgets_cr((char *)tbuf, FGETS_SIZE, fp);
6147 #else
6148 ignoredp = fgets((char *)tbuf, FGETS_SIZE, fp);
6149 #endif
6150 } while (tbuf[FGETS_SIZE - 2] != NUL && tbuf[FGETS_SIZE - 2] != '\n');
6152 return (eof == NULL);
6155 #if defined(USE_CR) || defined(PROTO)
6157 * Like vim_fgets(), but accept any line terminator: CR, CR-LF or LF.
6158 * Returns TRUE for end-of-file.
6159 * Only used for the Mac, because it's much slower than vim_fgets().
6162 tag_fgets(buf, size, fp)
6163 char_u *buf;
6164 int size;
6165 FILE *fp;
6167 int i = 0;
6168 int c;
6169 int eof = FALSE;
6171 for (;;)
6173 c = fgetc(fp);
6174 if (c == EOF)
6176 eof = TRUE;
6177 break;
6179 if (c == '\r')
6181 /* Always store a NL for end-of-line. */
6182 if (i < size - 1)
6183 buf[i++] = '\n';
6184 c = fgetc(fp);
6185 if (c != '\n') /* Macintosh format: single CR. */
6186 ungetc(c, fp);
6187 break;
6189 if (i < size - 1)
6190 buf[i++] = c;
6191 if (c == '\n')
6192 break;
6194 buf[i] = NUL;
6195 return eof;
6197 #endif
6200 * rename() only works if both files are on the same file system, this
6201 * function will (attempts to?) copy the file across if rename fails -- webb
6202 * Return -1 for failure, 0 for success.
6205 vim_rename(from, to)
6206 char_u *from;
6207 char_u *to;
6209 int fd_in;
6210 int fd_out;
6211 int n;
6212 char *errmsg = NULL;
6213 char *buffer;
6214 #ifdef AMIGA
6215 BPTR flock;
6216 #endif
6217 struct stat st;
6218 long perm;
6219 #ifdef HAVE_ACL
6220 vim_acl_T acl; /* ACL from original file */
6221 #endif
6222 #if defined(UNIX) || defined(CASE_INSENSITIVE_FILENAME)
6223 int use_tmp_file = FALSE;
6224 #endif
6227 * When the names are identical, there is nothing to do. When they refer
6228 * to the same file (ignoring case and slash/backslash differences) but
6229 * the file name differs we need to go through a temp file.
6231 if (fnamecmp(from, to) == 0)
6233 #ifdef CASE_INSENSITIVE_FILENAME
6234 if (STRCMP(gettail(from), gettail(to)) != 0)
6235 use_tmp_file = TRUE;
6236 else
6237 #endif
6238 return 0;
6242 * Fail if the "from" file doesn't exist. Avoids that "to" is deleted.
6244 if (mch_stat((char *)from, &st) < 0)
6245 return -1;
6247 #ifdef UNIX
6249 struct stat st_to;
6251 /* It's possible for the source and destination to be the same file.
6252 * This happens when "from" and "to" differ in case and are on a FAT32
6253 * filesystem. In that case go through a temp file name. */
6254 if (mch_stat((char *)to, &st_to) >= 0
6255 && st.st_dev == st_to.st_dev
6256 && st.st_ino == st_to.st_ino)
6257 use_tmp_file = TRUE;
6259 #endif
6261 #if defined(UNIX) || defined(CASE_INSENSITIVE_FILENAME)
6262 if (use_tmp_file)
6264 char tempname[MAXPATHL + 1];
6267 * Find a name that doesn't exist and is in the same directory.
6268 * Rename "from" to "tempname" and then rename "tempname" to "to".
6270 if (STRLEN(from) >= MAXPATHL - 5)
6271 return -1;
6272 STRCPY(tempname, from);
6273 for (n = 123; n < 99999; ++n)
6275 sprintf((char *)gettail((char_u *)tempname), "%d", n);
6276 if (mch_stat(tempname, &st) < 0)
6278 if (mch_rename((char *)from, tempname) == 0)
6280 if (mch_rename(tempname, (char *)to) == 0)
6281 return 0;
6282 /* Strange, the second step failed. Try moving the
6283 * file back and return failure. */
6284 mch_rename(tempname, (char *)from);
6285 return -1;
6287 /* If it fails for one temp name it will most likely fail
6288 * for any temp name, give up. */
6289 return -1;
6292 return -1;
6294 #endif
6297 * Delete the "to" file, this is required on some systems to make the
6298 * mch_rename() work, on other systems it makes sure that we don't have
6299 * two files when the mch_rename() fails.
6302 #ifdef AMIGA
6304 * With MSDOS-compatible filesystems (crossdos, messydos) it is possible
6305 * that the name of the "to" file is the same as the "from" file, even
6306 * though the names are different. To avoid the chance of accidentally
6307 * deleting the "from" file (horror!) we lock it during the remove.
6309 * When used for making a backup before writing the file: This should not
6310 * happen with ":w", because startscript() should detect this problem and
6311 * set buf->b_shortname, causing modname() to return a correct ".bak" file
6312 * name. This problem does exist with ":w filename", but then the
6313 * original file will be somewhere else so the backup isn't really
6314 * important. If autoscripting is off the rename may fail.
6316 flock = Lock((UBYTE *)from, (long)ACCESS_READ);
6317 #endif
6318 mch_remove(to);
6319 #ifdef AMIGA
6320 if (flock)
6321 UnLock(flock);
6322 #endif
6325 * First try a normal rename, return if it works.
6327 if (mch_rename((char *)from, (char *)to) == 0)
6328 return 0;
6331 * Rename() failed, try copying the file.
6333 perm = mch_getperm(from);
6334 #ifdef HAVE_ACL
6335 /* For systems that support ACL: get the ACL from the original file. */
6336 acl = mch_get_acl(from);
6337 #endif
6338 fd_in = mch_open((char *)from, O_RDONLY|O_EXTRA, 0);
6339 if (fd_in == -1)
6341 #ifdef HAVE_ACL
6342 mch_free_acl(acl);
6343 #endif
6344 return -1;
6347 /* Create the new file with same permissions as the original. */
6348 fd_out = mch_open((char *)to,
6349 O_CREAT|O_EXCL|O_WRONLY|O_EXTRA|O_NOFOLLOW, (int)perm);
6350 if (fd_out == -1)
6352 close(fd_in);
6353 #ifdef HAVE_ACL
6354 mch_free_acl(acl);
6355 #endif
6356 return -1;
6359 buffer = (char *)alloc(BUFSIZE);
6360 if (buffer == NULL)
6362 close(fd_out);
6363 close(fd_in);
6364 #ifdef HAVE_ACL
6365 mch_free_acl(acl);
6366 #endif
6367 return -1;
6370 while ((n = vim_read(fd_in, buffer, BUFSIZE)) > 0)
6371 if (vim_write(fd_out, buffer, n) != n)
6373 errmsg = _("E208: Error writing to \"%s\"");
6374 break;
6377 vim_free(buffer);
6378 close(fd_in);
6379 if (close(fd_out) < 0)
6380 errmsg = _("E209: Error closing \"%s\"");
6381 if (n < 0)
6383 errmsg = _("E210: Error reading \"%s\"");
6384 to = from;
6386 #ifndef UNIX /* for Unix mch_open() already set the permission */
6387 mch_setperm(to, perm);
6388 #endif
6389 #ifdef HAVE_ACL
6390 mch_set_acl(to, acl);
6391 mch_free_acl(acl);
6392 #endif
6393 if (errmsg != NULL)
6395 EMSG2(errmsg, to);
6396 return -1;
6398 mch_remove(from);
6399 return 0;
6402 static int already_warned = FALSE;
6405 * Check if any not hidden buffer has been changed.
6406 * Postpone the check if there are characters in the stuff buffer, a global
6407 * command is being executed, a mapping is being executed or an autocommand is
6408 * busy.
6409 * Returns TRUE if some message was written (screen should be redrawn and
6410 * cursor positioned).
6413 check_timestamps(focus)
6414 int focus; /* called for GUI focus event */
6416 buf_T *buf;
6417 int didit = 0;
6418 int n;
6420 /* Don't check timestamps while system() or another low-level function may
6421 * cause us to lose and gain focus. */
6422 if (no_check_timestamps > 0)
6423 return FALSE;
6425 /* Avoid doing a check twice. The OK/Reload dialog can cause a focus
6426 * event and we would keep on checking if the file is steadily growing.
6427 * Do check again after typing something. */
6428 if (focus && did_check_timestamps)
6430 need_check_timestamps = TRUE;
6431 return FALSE;
6434 if (!stuff_empty() || global_busy || !typebuf_typed()
6435 #ifdef FEAT_AUTOCMD
6436 || autocmd_busy || curbuf_lock > 0 || allbuf_lock > 0
6437 #endif
6439 need_check_timestamps = TRUE; /* check later */
6440 else
6442 ++no_wait_return;
6443 did_check_timestamps = TRUE;
6444 already_warned = FALSE;
6445 for (buf = firstbuf; buf != NULL; )
6447 /* Only check buffers in a window. */
6448 if (buf->b_nwindows > 0)
6450 n = buf_check_timestamp(buf, focus);
6451 if (didit < n)
6452 didit = n;
6453 if (n > 0 && !buf_valid(buf))
6455 /* Autocommands have removed the buffer, start at the
6456 * first one again. */
6457 buf = firstbuf;
6458 continue;
6461 buf = buf->b_next;
6463 --no_wait_return;
6464 need_check_timestamps = FALSE;
6465 if (need_wait_return && didit == 2)
6467 /* make sure msg isn't overwritten */
6468 msg_puts((char_u *)"\n");
6469 out_flush();
6472 return didit;
6476 * Move all the lines from buffer "frombuf" to buffer "tobuf".
6477 * Return OK or FAIL. When FAIL "tobuf" is incomplete and/or "frombuf" is not
6478 * empty.
6480 static int
6481 move_lines(frombuf, tobuf)
6482 buf_T *frombuf;
6483 buf_T *tobuf;
6485 buf_T *tbuf = curbuf;
6486 int retval = OK;
6487 linenr_T lnum;
6488 char_u *p;
6490 /* Copy the lines in "frombuf" to "tobuf". */
6491 curbuf = tobuf;
6492 for (lnum = 1; lnum <= frombuf->b_ml.ml_line_count; ++lnum)
6494 p = vim_strsave(ml_get_buf(frombuf, lnum, FALSE));
6495 if (p == NULL || ml_append(lnum - 1, p, 0, FALSE) == FAIL)
6497 vim_free(p);
6498 retval = FAIL;
6499 break;
6501 vim_free(p);
6504 /* Delete all the lines in "frombuf". */
6505 if (retval != FAIL)
6507 curbuf = frombuf;
6508 for (lnum = curbuf->b_ml.ml_line_count; lnum > 0; --lnum)
6509 if (ml_delete(lnum, FALSE) == FAIL)
6511 /* Oops! We could try putting back the saved lines, but that
6512 * might fail again... */
6513 retval = FAIL;
6514 break;
6518 curbuf = tbuf;
6519 return retval;
6523 * Check if buffer "buf" has been changed.
6524 * Also check if the file for a new buffer unexpectedly appeared.
6525 * return 1 if a changed buffer was found.
6526 * return 2 if a message has been displayed.
6527 * return 0 otherwise.
6530 buf_check_timestamp(buf, focus)
6531 buf_T *buf;
6532 int focus UNUSED; /* called for GUI focus event */
6534 struct stat st;
6535 int stat_res;
6536 int retval = 0;
6537 char_u *path;
6538 char_u *tbuf;
6539 char *mesg = NULL;
6540 char *mesg2 = "";
6541 int helpmesg = FALSE;
6542 int reload = FALSE;
6543 #if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6544 int can_reload = FALSE;
6545 #endif
6546 size_t orig_size = buf->b_orig_size;
6547 int orig_mode = buf->b_orig_mode;
6548 #ifdef FEAT_GUI
6549 int save_mouse_correct = need_mouse_correct;
6550 #endif
6551 #ifdef FEAT_AUTOCMD
6552 static int busy = FALSE;
6553 int n;
6554 char_u *s;
6555 #endif
6556 char *reason;
6558 /* If there is no file name, the buffer is not loaded, 'buftype' is
6559 * set, we are in the middle of a save or being called recursively: ignore
6560 * this buffer. */
6561 if (buf->b_ffname == NULL
6562 || buf->b_ml.ml_mfp == NULL
6563 #if defined(FEAT_QUICKFIX)
6564 || *buf->b_p_bt != NUL
6565 #endif
6566 || buf->b_saving
6567 #ifdef FEAT_AUTOCMD
6568 || busy
6569 #endif
6570 #ifdef FEAT_NETBEANS_INTG
6571 || isNetbeansBuffer(buf)
6572 #endif
6574 return 0;
6576 if ( !(buf->b_flags & BF_NOTEDITED)
6577 && buf->b_mtime != 0
6578 && ((stat_res = mch_stat((char *)buf->b_ffname, &st)) < 0
6579 || time_differs((long)st.st_mtime, buf->b_mtime)
6580 #ifdef HAVE_ST_MODE
6581 || (int)st.st_mode != buf->b_orig_mode
6582 #else
6583 || mch_getperm(buf->b_ffname) != buf->b_orig_mode
6584 #endif
6587 retval = 1;
6589 /* set b_mtime to stop further warnings (e.g., when executing
6590 * FileChangedShell autocmd) */
6591 if (stat_res < 0)
6593 buf->b_mtime = 0;
6594 buf->b_orig_size = 0;
6595 buf->b_orig_mode = 0;
6597 else
6598 buf_store_time(buf, &st, buf->b_ffname);
6600 /* Don't do anything for a directory. Might contain the file
6601 * explorer. */
6602 if (mch_isdir(buf->b_fname))
6606 * If 'autoread' is set, the buffer has no changes and the file still
6607 * exists, reload the buffer. Use the buffer-local option value if it
6608 * was set, the global option value otherwise.
6610 else if ((buf->b_p_ar >= 0 ? buf->b_p_ar : p_ar)
6611 && !bufIsChanged(buf) && stat_res >= 0)
6612 reload = TRUE;
6613 else
6615 if (stat_res < 0)
6616 reason = "deleted";
6617 else if (bufIsChanged(buf))
6618 reason = "conflict";
6619 else if (orig_size != buf->b_orig_size || buf_contents_changed(buf))
6620 reason = "changed";
6621 else if (orig_mode != buf->b_orig_mode)
6622 reason = "mode";
6623 else
6624 reason = "time";
6626 #ifdef FEAT_AUTOCMD
6628 * Only give the warning if there are no FileChangedShell
6629 * autocommands.
6630 * Avoid being called recursively by setting "busy".
6632 busy = TRUE;
6633 # ifdef FEAT_EVAL
6634 set_vim_var_string(VV_FCS_REASON, (char_u *)reason, -1);
6635 set_vim_var_string(VV_FCS_CHOICE, (char_u *)"", -1);
6636 # endif
6637 ++allbuf_lock;
6638 n = apply_autocmds(EVENT_FILECHANGEDSHELL,
6639 buf->b_fname, buf->b_fname, FALSE, buf);
6640 --allbuf_lock;
6641 busy = FALSE;
6642 if (n)
6644 if (!buf_valid(buf))
6645 EMSG(_("E246: FileChangedShell autocommand deleted buffer"));
6646 # ifdef FEAT_EVAL
6647 s = get_vim_var_str(VV_FCS_CHOICE);
6648 if (STRCMP(s, "reload") == 0 && *reason != 'd')
6649 reload = TRUE;
6650 else if (STRCMP(s, "ask") == 0)
6651 n = FALSE;
6652 else
6653 # endif
6654 return 2;
6656 if (!n)
6657 #endif
6659 if (*reason == 'd')
6660 mesg = _("E211: File \"%s\" no longer available");
6661 else
6663 helpmesg = TRUE;
6664 #if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6665 can_reload = TRUE;
6666 #endif
6668 * Check if the file contents really changed to avoid
6669 * giving a warning when only the timestamp was set (e.g.,
6670 * checked out of CVS). Always warn when the buffer was
6671 * changed.
6673 if (reason[2] == 'n')
6675 mesg = _("W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well");
6676 mesg2 = _("See \":help W12\" for more info.");
6678 else if (reason[1] == 'h')
6680 mesg = _("W11: Warning: File \"%s\" has changed since editing started");
6681 mesg2 = _("See \":help W11\" for more info.");
6683 else if (*reason == 'm')
6685 mesg = _("W16: Warning: Mode of file \"%s\" has changed since editing started");
6686 mesg2 = _("See \":help W16\" for more info.");
6688 else
6689 /* Only timestamp changed, store it to avoid a warning
6690 * in check_mtime() later. */
6691 buf->b_mtime_read = buf->b_mtime;
6697 else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W)
6698 && vim_fexists(buf->b_ffname))
6700 retval = 1;
6701 mesg = _("W13: Warning: File \"%s\" has been created after editing started");
6702 buf->b_flags |= BF_NEW_W;
6703 #if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6704 can_reload = TRUE;
6705 #endif
6708 if (mesg != NULL)
6710 path = home_replace_save(buf, buf->b_fname);
6711 if (path != NULL)
6713 if (!helpmesg)
6714 mesg2 = "";
6715 tbuf = alloc((unsigned)(STRLEN(path) + STRLEN(mesg)
6716 + STRLEN(mesg2) + 2));
6717 sprintf((char *)tbuf, mesg, path);
6718 #ifdef FEAT_EVAL
6719 /* Set warningmsg here, before the unimportant and output-specific
6720 * mesg2 has been appended. */
6721 set_vim_var_string(VV_WARNINGMSG, tbuf, -1);
6722 #endif
6723 #if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6724 if (can_reload)
6726 if (*mesg2 != NUL)
6728 STRCAT(tbuf, "\n");
6729 STRCAT(tbuf, mesg2);
6731 if (do_dialog(VIM_WARNING, (char_u *)_("Warning"), tbuf,
6732 (char_u *)_("&OK\n&Load File"), 1, NULL) == 2)
6733 reload = TRUE;
6735 else
6736 #endif
6737 if (State > NORMAL_BUSY || (State & CMDLINE) || already_warned)
6739 if (*mesg2 != NUL)
6741 STRCAT(tbuf, "; ");
6742 STRCAT(tbuf, mesg2);
6744 EMSG(tbuf);
6745 retval = 2;
6747 else
6749 # ifdef FEAT_AUTOCMD
6750 if (!autocmd_busy)
6751 # endif
6753 msg_start();
6754 msg_puts_attr(tbuf, hl_attr(HLF_E) + MSG_HIST);
6755 if (*mesg2 != NUL)
6756 msg_puts_attr((char_u *)mesg2,
6757 hl_attr(HLF_W) + MSG_HIST);
6758 msg_clr_eos();
6759 (void)msg_end();
6760 if (emsg_silent == 0)
6762 out_flush();
6763 # ifdef FEAT_GUI
6764 if (!focus)
6765 # endif
6766 /* give the user some time to think about it */
6767 ui_delay(1000L, TRUE);
6769 /* don't redraw and erase the message */
6770 redraw_cmdline = FALSE;
6773 already_warned = TRUE;
6776 vim_free(path);
6777 vim_free(tbuf);
6781 if (reload)
6782 /* Reload the buffer. */
6783 buf_reload(buf, orig_mode);
6785 #ifdef FEAT_AUTOCMD
6786 /* Trigger FileChangedShell when the file was changed in any way. */
6787 if (buf_valid(buf) && retval != 0)
6788 (void)apply_autocmds(EVENT_FILECHANGEDSHELLPOST,
6789 buf->b_fname, buf->b_fname, FALSE, buf);
6790 #endif
6791 #ifdef FEAT_GUI
6792 /* restore this in case an autocommand has set it; it would break
6793 * 'mousefocus' */
6794 need_mouse_correct = save_mouse_correct;
6795 #endif
6797 return retval;
6801 * Reload a buffer that is already loaded.
6802 * Used when the file was changed outside of Vim.
6803 * "orig_mode" is buf->b_orig_mode before the need for reloading was detected.
6804 * buf->b_orig_mode may have been reset already.
6806 void
6807 buf_reload(buf, orig_mode)
6808 buf_T *buf;
6809 int orig_mode;
6811 exarg_T ea;
6812 pos_T old_cursor;
6813 linenr_T old_topline;
6814 int old_ro = buf->b_p_ro;
6815 buf_T *savebuf;
6816 int saved = OK;
6817 aco_save_T aco;
6819 /* set curwin/curbuf for "buf" and save some things */
6820 aucmd_prepbuf(&aco, buf);
6822 /* We only want to read the text from the file, not reset the syntax
6823 * highlighting, clear marks, diff status, etc. Force the fileformat
6824 * and encoding to be the same. */
6825 if (prep_exarg(&ea, buf) == OK)
6827 old_cursor = curwin->w_cursor;
6828 old_topline = curwin->w_topline;
6831 * To behave like when a new file is edited (matters for
6832 * BufReadPost autocommands) we first need to delete the current
6833 * buffer contents. But if reading the file fails we should keep
6834 * the old contents. Can't use memory only, the file might be
6835 * too big. Use a hidden buffer to move the buffer contents to.
6837 if (bufempty())
6838 savebuf = NULL;
6839 else
6841 /* Allocate a buffer without putting it in the buffer list. */
6842 savebuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
6843 if (savebuf != NULL && buf == curbuf)
6845 /* Open the memline. */
6846 curbuf = savebuf;
6847 curwin->w_buffer = savebuf;
6848 saved = ml_open(curbuf);
6849 curbuf = buf;
6850 curwin->w_buffer = buf;
6852 if (savebuf == NULL || saved == FAIL || buf != curbuf
6853 || move_lines(buf, savebuf) == FAIL)
6855 EMSG2(_("E462: Could not prepare for reloading \"%s\""),
6856 buf->b_fname);
6857 saved = FAIL;
6861 if (saved == OK)
6863 curbuf->b_flags |= BF_CHECK_RO; /* check for RO again */
6864 #ifdef FEAT_AUTOCMD
6865 keep_filetype = TRUE; /* don't detect 'filetype' */
6866 #endif
6867 if (readfile(buf->b_ffname, buf->b_fname, (linenr_T)0,
6868 (linenr_T)0,
6869 (linenr_T)MAXLNUM, &ea, READ_NEW) == FAIL)
6871 #if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
6872 if (!aborting())
6873 #endif
6874 EMSG2(_("E321: Could not reload \"%s\""), buf->b_fname);
6875 if (savebuf != NULL && buf_valid(savebuf) && buf == curbuf)
6877 /* Put the text back from the save buffer. First
6878 * delete any lines that readfile() added. */
6879 while (!bufempty())
6880 if (ml_delete(buf->b_ml.ml_line_count, FALSE) == FAIL)
6881 break;
6882 (void)move_lines(savebuf, buf);
6885 else if (buf == curbuf)
6887 /* Mark the buffer as unmodified and free undo info. */
6888 unchanged(buf, TRUE);
6889 u_blockfree(buf);
6890 u_clearall(buf);
6893 vim_free(ea.cmd);
6895 if (savebuf != NULL && buf_valid(savebuf))
6896 wipe_buffer(savebuf, FALSE);
6898 #ifdef FEAT_DIFF
6899 /* Invalidate diff info if necessary. */
6900 diff_invalidate(curbuf);
6901 #endif
6903 /* Restore the topline and cursor position and check it (lines may
6904 * have been removed). */
6905 if (old_topline > curbuf->b_ml.ml_line_count)
6906 curwin->w_topline = curbuf->b_ml.ml_line_count;
6907 else
6908 curwin->w_topline = old_topline;
6909 curwin->w_cursor = old_cursor;
6910 check_cursor();
6911 update_topline();
6912 #ifdef FEAT_AUTOCMD
6913 keep_filetype = FALSE;
6914 #endif
6915 #ifdef FEAT_FOLDING
6917 win_T *wp;
6918 tabpage_T *tp;
6920 /* Update folds unless they are defined manually. */
6921 FOR_ALL_TAB_WINDOWS(tp, wp)
6922 if (wp->w_buffer == curwin->w_buffer
6923 && !foldmethodIsManual(wp))
6924 foldUpdateAll(wp);
6926 #endif
6927 /* If the mode didn't change and 'readonly' was set, keep the old
6928 * value; the user probably used the ":view" command. But don't
6929 * reset it, might have had a read error. */
6930 if (orig_mode == curbuf->b_orig_mode)
6931 curbuf->b_p_ro |= old_ro;
6934 /* restore curwin/curbuf and a few other things */
6935 aucmd_restbuf(&aco);
6936 /* Careful: autocommands may have made "buf" invalid! */
6939 void
6940 buf_store_time(buf, st, fname)
6941 buf_T *buf;
6942 struct stat *st;
6943 char_u *fname UNUSED;
6945 buf->b_mtime = (long)st->st_mtime;
6946 buf->b_orig_size = (size_t)st->st_size;
6947 #ifdef HAVE_ST_MODE
6948 buf->b_orig_mode = (int)st->st_mode;
6949 #else
6950 buf->b_orig_mode = mch_getperm(fname);
6951 #endif
6955 * Adjust the line with missing eol, used for the next write.
6956 * Used for do_filter(), when the input lines for the filter are deleted.
6958 void
6959 write_lnum_adjust(offset)
6960 linenr_T offset;
6962 if (write_no_eol_lnum != 0) /* only if there is a missing eol */
6963 write_no_eol_lnum += offset;
6966 #if defined(TEMPDIRNAMES) || defined(PROTO)
6967 static long temp_count = 0; /* Temp filename counter. */
6970 * Delete the temp directory and all files it contains.
6972 void
6973 vim_deltempdir()
6975 char_u **files;
6976 int file_count;
6977 int i;
6979 if (vim_tempdir != NULL)
6981 sprintf((char *)NameBuff, "%s*", vim_tempdir);
6982 if (gen_expand_wildcards(1, &NameBuff, &file_count, &files,
6983 EW_DIR|EW_FILE|EW_SILENT) == OK)
6985 for (i = 0; i < file_count; ++i)
6986 mch_remove(files[i]);
6987 FreeWild(file_count, files);
6989 gettail(NameBuff)[-1] = NUL;
6990 (void)mch_rmdir(NameBuff);
6992 vim_free(vim_tempdir);
6993 vim_tempdir = NULL;
6996 #endif
6999 * Directory "tempdir" was created. Expand this name to a full path and put
7000 * it in "vim_tempdir". This avoids that using ":cd" would confuse us.
7001 * "tempdir" must be no longer than MAXPATHL.
7003 static void
7004 vim_settempdir(tempdir)
7005 char_u *tempdir;
7007 char_u *buf;
7009 buf = alloc((unsigned)MAXPATHL + 2);
7010 if (buf != NULL)
7012 if (vim_FullName(tempdir, buf, MAXPATHL, FALSE) == FAIL)
7013 STRCPY(buf, tempdir);
7014 # ifdef __EMX__
7015 if (vim_strchr(buf, '/') != NULL)
7016 STRCAT(buf, "/");
7017 else
7018 # endif
7019 add_pathsep(buf);
7020 vim_tempdir = vim_strsave(buf);
7021 vim_free(buf);
7026 * vim_tempname(): Return a unique name that can be used for a temp file.
7028 * The temp file is NOT created.
7030 * The returned pointer is to allocated memory.
7031 * The returned pointer is NULL if no valid name was found.
7033 char_u *
7034 vim_tempname(extra_char)
7035 int extra_char UNUSED; /* char to use in the name instead of '?' */
7037 #ifdef USE_TMPNAM
7038 char_u itmp[L_tmpnam]; /* use tmpnam() */
7039 #else
7040 char_u itmp[TEMPNAMELEN];
7041 #endif
7043 #ifdef TEMPDIRNAMES
7044 static char *(tempdirs[]) = {TEMPDIRNAMES};
7045 int i;
7046 # ifndef EEXIST
7047 struct stat st;
7048 # endif
7051 * This will create a directory for private use by this instance of Vim.
7052 * This is done once, and the same directory is used for all temp files.
7053 * This method avoids security problems because of symlink attacks et al.
7054 * It's also a bit faster, because we only need to check for an existing
7055 * file when creating the directory and not for each temp file.
7057 if (vim_tempdir == NULL)
7060 * Try the entries in TEMPDIRNAMES to create the temp directory.
7062 for (i = 0; i < (int)(sizeof(tempdirs) / sizeof(char *)); ++i)
7064 size_t itmplen;
7065 # ifndef HAVE_MKDTEMP
7066 long nr;
7067 long off;
7068 # endif
7070 /* expand $TMP, leave room for "/v1100000/999999999" */
7071 expand_env((char_u *)tempdirs[i], itmp, TEMPNAMELEN - 20);
7072 if (mch_isdir(itmp)) /* directory exists */
7074 # ifdef __EMX__
7075 /* If $TMP contains a forward slash (perhaps using bash or
7076 * tcsh), don't add a backslash, use a forward slash!
7077 * Adding 2 backslashes didn't work. */
7078 if (vim_strchr(itmp, '/') != NULL)
7079 STRCAT(itmp, "/");
7080 else
7081 # endif
7082 add_pathsep(itmp);
7083 itmplen = STRLEN(itmp);
7085 # ifdef HAVE_MKDTEMP
7086 /* Leave room for filename */
7087 STRCAT(itmp, "vXXXXXX");
7088 if (mkdtemp((char *)itmp) != NULL)
7089 vim_settempdir(itmp);
7090 # else
7091 /* Get an arbitrary number of up to 6 digits. When it's
7092 * unlikely that it already exists it will be faster,
7093 * otherwise it doesn't matter. The use of mkdir() avoids any
7094 * security problems because of the predictable number. */
7095 nr = (mch_get_pid() + (long)time(NULL)) % 1000000L;
7097 /* Try up to 10000 different values until we find a name that
7098 * doesn't exist. */
7099 for (off = 0; off < 10000L; ++off)
7101 int r;
7102 # if defined(UNIX) || defined(VMS)
7103 mode_t umask_save;
7104 # endif
7106 sprintf((char *)itmp + itmplen, "v%ld", nr + off);
7107 # ifndef EEXIST
7108 /* If mkdir() does not set errno to EEXIST, check for
7109 * existing file here. There is a race condition then,
7110 * although it's fail-safe. */
7111 if (mch_stat((char *)itmp, &st) >= 0)
7112 continue;
7113 # endif
7114 # if defined(UNIX) || defined(VMS)
7115 /* Make sure the umask doesn't remove the executable bit.
7116 * "repl" has been reported to use "177". */
7117 umask_save = umask(077);
7118 # endif
7119 r = vim_mkdir(itmp, 0700);
7120 # if defined(UNIX) || defined(VMS)
7121 (void)umask(umask_save);
7122 # endif
7123 if (r == 0)
7125 vim_settempdir(itmp);
7126 break;
7128 # ifdef EEXIST
7129 /* If the mkdir() didn't fail because the file/dir exists,
7130 * we probably can't create any dir here, try another
7131 * place. */
7132 if (errno != EEXIST)
7133 # endif
7134 break;
7136 # endif /* HAVE_MKDTEMP */
7137 if (vim_tempdir != NULL)
7138 break;
7143 if (vim_tempdir != NULL)
7145 /* There is no need to check if the file exists, because we own the
7146 * directory and nobody else creates a file in it. */
7147 sprintf((char *)itmp, "%s%ld", vim_tempdir, temp_count++);
7148 return vim_strsave(itmp);
7151 return NULL;
7153 #else /* TEMPDIRNAMES */
7155 # ifdef WIN3264
7156 char szTempFile[_MAX_PATH + 1];
7157 char buf4[4];
7158 char_u *retval;
7159 char_u *p;
7161 STRCPY(itmp, "");
7162 if (GetTempPath(_MAX_PATH, szTempFile) == 0)
7163 szTempFile[0] = NUL; /* GetTempPath() failed, use current dir */
7164 strcpy(buf4, "VIM");
7165 buf4[2] = extra_char; /* make it "VIa", "VIb", etc. */
7166 if (GetTempFileName(szTempFile, buf4, 0, itmp) == 0)
7167 return NULL;
7168 /* GetTempFileName() will create the file, we don't want that */
7169 (void)DeleteFile(itmp);
7171 /* Backslashes in a temp file name cause problems when filtering with
7172 * "sh". NOTE: This also checks 'shellcmdflag' to help those people who
7173 * didn't set 'shellslash'. */
7174 retval = vim_strsave(itmp);
7175 if (*p_shcf == '-' || p_ssl)
7176 for (p = retval; *p; ++p)
7177 if (*p == '\\')
7178 *p = '/';
7179 return retval;
7181 # else /* WIN3264 */
7183 # ifdef USE_TMPNAM
7184 /* tmpnam() will make its own name */
7185 if (*tmpnam((char *)itmp) == NUL)
7186 return NULL;
7187 # else
7188 char_u *p;
7190 # ifdef VMS_TEMPNAM
7191 /* mktemp() is not working on VMS. It seems to be
7192 * a do-nothing function. Therefore we use tempnam().
7194 sprintf((char *)itmp, "VIM%c", extra_char);
7195 p = (char_u *)tempnam("tmp:", (char *)itmp);
7196 if (p != NULL)
7198 /* VMS will use '.LOG' if we don't explicitly specify an extension,
7199 * and VIM will then be unable to find the file later */
7200 STRCPY(itmp, p);
7201 STRCAT(itmp, ".txt");
7202 free(p);
7204 else
7205 return NULL;
7206 # else
7207 STRCPY(itmp, TEMPNAME);
7208 if ((p = vim_strchr(itmp, '?')) != NULL)
7209 *p = extra_char;
7210 if (mktemp((char *)itmp) == NULL)
7211 return NULL;
7212 # endif
7213 # endif
7215 return vim_strsave(itmp);
7216 # endif /* WIN3264 */
7217 #endif /* TEMPDIRNAMES */
7220 #if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
7222 * Convert all backslashes in fname to forward slashes in-place.
7224 void
7225 forward_slash(fname)
7226 char_u *fname;
7228 char_u *p;
7230 for (p = fname; *p != NUL; ++p)
7231 # ifdef FEAT_MBYTE
7232 /* The Big5 encoding can have '\' in the trail byte. */
7233 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
7234 ++p;
7235 else
7236 # endif
7237 if (*p == '\\')
7238 *p = '/';
7240 #endif
7244 * Code for automatic commands.
7246 * Only included when "FEAT_AUTOCMD" has been defined.
7249 #if defined(FEAT_AUTOCMD) || defined(PROTO)
7252 * The autocommands are stored in a list for each event.
7253 * Autocommands for the same pattern, that are consecutive, are joined
7254 * together, to avoid having to match the pattern too often.
7255 * The result is an array of Autopat lists, which point to AutoCmd lists:
7257 * first_autopat[0] --> Autopat.next --> Autopat.next --> NULL
7258 * Autopat.cmds Autopat.cmds
7259 * | |
7260 * V V
7261 * AutoCmd.next AutoCmd.next
7262 * | |
7263 * V V
7264 * AutoCmd.next NULL
7267 * NULL
7269 * first_autopat[1] --> Autopat.next --> NULL
7270 * Autopat.cmds
7273 * AutoCmd.next
7276 * NULL
7277 * etc.
7279 * The order of AutoCmds is important, this is the order in which they were
7280 * defined and will have to be executed.
7282 typedef struct AutoCmd
7284 char_u *cmd; /* The command to be executed (NULL
7285 when command has been removed) */
7286 char nested; /* If autocommands nest here */
7287 char last; /* last command in list */
7288 #ifdef FEAT_EVAL
7289 scid_T scriptID; /* script ID where defined */
7290 #endif
7291 struct AutoCmd *next; /* Next AutoCmd in list */
7292 } AutoCmd;
7294 typedef struct AutoPat
7296 int group; /* group ID */
7297 char_u *pat; /* pattern as typed (NULL when pattern
7298 has been removed) */
7299 int patlen; /* strlen() of pat */
7300 regprog_T *reg_prog; /* compiled regprog for pattern */
7301 char allow_dirs; /* Pattern may match whole path */
7302 char last; /* last pattern for apply_autocmds() */
7303 AutoCmd *cmds; /* list of commands to do */
7304 struct AutoPat *next; /* next AutoPat in AutoPat list */
7305 int buflocal_nr; /* !=0 for buffer-local AutoPat */
7306 } AutoPat;
7308 static struct event_name
7310 char *name; /* event name */
7311 event_T event; /* event number */
7312 } event_names[] =
7314 {"BufAdd", EVENT_BUFADD},
7315 {"BufCreate", EVENT_BUFADD},
7316 {"BufDelete", EVENT_BUFDELETE},
7317 {"BufEnter", EVENT_BUFENTER},
7318 {"BufFilePost", EVENT_BUFFILEPOST},
7319 {"BufFilePre", EVENT_BUFFILEPRE},
7320 {"BufHidden", EVENT_BUFHIDDEN},
7321 {"BufLeave", EVENT_BUFLEAVE},
7322 {"BufNew", EVENT_BUFNEW},
7323 {"BufNewFile", EVENT_BUFNEWFILE},
7324 {"BufRead", EVENT_BUFREADPOST},
7325 {"BufReadCmd", EVENT_BUFREADCMD},
7326 {"BufReadPost", EVENT_BUFREADPOST},
7327 {"BufReadPre", EVENT_BUFREADPRE},
7328 {"BufUnload", EVENT_BUFUNLOAD},
7329 {"BufWinEnter", EVENT_BUFWINENTER},
7330 {"BufWinLeave", EVENT_BUFWINLEAVE},
7331 {"BufWipeout", EVENT_BUFWIPEOUT},
7332 {"BufWrite", EVENT_BUFWRITEPRE},
7333 {"BufWritePost", EVENT_BUFWRITEPOST},
7334 {"BufWritePre", EVENT_BUFWRITEPRE},
7335 {"BufWriteCmd", EVENT_BUFWRITECMD},
7336 {"CmdwinEnter", EVENT_CMDWINENTER},
7337 {"CmdwinLeave", EVENT_CMDWINLEAVE},
7338 {"ColorScheme", EVENT_COLORSCHEME},
7339 {"CursorHold", EVENT_CURSORHOLD},
7340 {"CursorHoldI", EVENT_CURSORHOLDI},
7341 {"CursorMoved", EVENT_CURSORMOVED},
7342 {"CursorMovedI", EVENT_CURSORMOVEDI},
7343 {"EncodingChanged", EVENT_ENCODINGCHANGED},
7344 {"FileEncoding", EVENT_ENCODINGCHANGED},
7345 {"FileAppendPost", EVENT_FILEAPPENDPOST},
7346 {"FileAppendPre", EVENT_FILEAPPENDPRE},
7347 {"FileAppendCmd", EVENT_FILEAPPENDCMD},
7348 {"FileChangedShell",EVENT_FILECHANGEDSHELL},
7349 {"FileChangedShellPost",EVENT_FILECHANGEDSHELLPOST},
7350 {"FileChangedRO", EVENT_FILECHANGEDRO},
7351 {"FileReadPost", EVENT_FILEREADPOST},
7352 {"FileReadPre", EVENT_FILEREADPRE},
7353 {"FileReadCmd", EVENT_FILEREADCMD},
7354 {"FileType", EVENT_FILETYPE},
7355 {"FileWritePost", EVENT_FILEWRITEPOST},
7356 {"FileWritePre", EVENT_FILEWRITEPRE},
7357 {"FileWriteCmd", EVENT_FILEWRITECMD},
7358 {"FilterReadPost", EVENT_FILTERREADPOST},
7359 {"FilterReadPre", EVENT_FILTERREADPRE},
7360 {"FilterWritePost", EVENT_FILTERWRITEPOST},
7361 {"FilterWritePre", EVENT_FILTERWRITEPRE},
7362 {"FocusGained", EVENT_FOCUSGAINED},
7363 {"FocusLost", EVENT_FOCUSLOST},
7364 {"FuncUndefined", EVENT_FUNCUNDEFINED},
7365 {"GUIEnter", EVENT_GUIENTER},
7366 {"GUIFailed", EVENT_GUIFAILED},
7367 {"InsertChange", EVENT_INSERTCHANGE},
7368 {"InsertEnter", EVENT_INSERTENTER},
7369 {"InsertLeave", EVENT_INSERTLEAVE},
7370 {"MenuPopup", EVENT_MENUPOPUP},
7371 {"QuickFixCmdPost", EVENT_QUICKFIXCMDPOST},
7372 {"QuickFixCmdPre", EVENT_QUICKFIXCMDPRE},
7373 {"RemoteReply", EVENT_REMOTEREPLY},
7374 {"SessionLoadPost", EVENT_SESSIONLOADPOST},
7375 {"ShellCmdPost", EVENT_SHELLCMDPOST},
7376 {"ShellFilterPost", EVENT_SHELLFILTERPOST},
7377 {"SourcePre", EVENT_SOURCEPRE},
7378 {"SourceCmd", EVENT_SOURCECMD},
7379 {"SpellFileMissing",EVENT_SPELLFILEMISSING},
7380 {"StdinReadPost", EVENT_STDINREADPOST},
7381 {"StdinReadPre", EVENT_STDINREADPRE},
7382 {"SwapExists", EVENT_SWAPEXISTS},
7383 {"Syntax", EVENT_SYNTAX},
7384 {"TabEnter", EVENT_TABENTER},
7385 {"TabLeave", EVENT_TABLEAVE},
7386 {"TermChanged", EVENT_TERMCHANGED},
7387 {"TermResponse", EVENT_TERMRESPONSE},
7388 {"User", EVENT_USER},
7389 {"VimEnter", EVENT_VIMENTER},
7390 {"VimLeave", EVENT_VIMLEAVE},
7391 {"VimLeavePre", EVENT_VIMLEAVEPRE},
7392 {"WinEnter", EVENT_WINENTER},
7393 {"WinLeave", EVENT_WINLEAVE},
7394 {"VimResized", EVENT_VIMRESIZED},
7395 {NULL, (event_T)0}
7398 static AutoPat *first_autopat[NUM_EVENTS] =
7400 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7401 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7402 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7403 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7404 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7405 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
7409 * struct used to keep status while executing autocommands for an event.
7411 typedef struct AutoPatCmd
7413 AutoPat *curpat; /* next AutoPat to examine */
7414 AutoCmd *nextcmd; /* next AutoCmd to execute */
7415 int group; /* group being used */
7416 char_u *fname; /* fname to match with */
7417 char_u *sfname; /* sfname to match with */
7418 char_u *tail; /* tail of fname */
7419 event_T event; /* current event */
7420 int arg_bufnr; /* initially equal to <abuf>, set to zero when
7421 buf is deleted */
7422 struct AutoPatCmd *next; /* chain of active apc-s for auto-invalidation*/
7423 } AutoPatCmd;
7425 static AutoPatCmd *active_apc_list = NULL; /* stack of active autocommands */
7428 * augroups stores a list of autocmd group names.
7430 static garray_T augroups = {0, 0, sizeof(char_u *), 10, NULL};
7431 #define AUGROUP_NAME(i) (((char_u **)augroups.ga_data)[i])
7434 * The ID of the current group. Group 0 is the default one.
7436 static int current_augroup = AUGROUP_DEFAULT;
7438 static int au_need_clean = FALSE; /* need to delete marked patterns */
7440 static void show_autocmd __ARGS((AutoPat *ap, event_T event));
7441 static void au_remove_pat __ARGS((AutoPat *ap));
7442 static void au_remove_cmds __ARGS((AutoPat *ap));
7443 static void au_cleanup __ARGS((void));
7444 static int au_new_group __ARGS((char_u *name));
7445 static void au_del_group __ARGS((char_u *name));
7446 static event_T event_name2nr __ARGS((char_u *start, char_u **end));
7447 static char_u *event_nr2name __ARGS((event_T event));
7448 static char_u *find_end_event __ARGS((char_u *arg, int have_group));
7449 static int event_ignored __ARGS((event_T event));
7450 static int au_get_grouparg __ARGS((char_u **argp));
7451 static int do_autocmd_event __ARGS((event_T event, char_u *pat, int nested, char_u *cmd, int forceit, int group));
7452 static char_u *getnextac __ARGS((int c, void *cookie, int indent));
7453 static 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));
7454 static void auto_next_pat __ARGS((AutoPatCmd *apc, int stop_at_last));
7457 static event_T last_event;
7458 static int last_group;
7459 static int autocmd_blocked = 0; /* block all autocmds */
7462 * Show the autocommands for one AutoPat.
7464 static void
7465 show_autocmd(ap, event)
7466 AutoPat *ap;
7467 event_T event;
7469 AutoCmd *ac;
7471 /* Check for "got_int" (here and at various places below), which is set
7472 * when "q" has been hit for the "--more--" prompt */
7473 if (got_int)
7474 return;
7475 if (ap->pat == NULL) /* pattern has been removed */
7476 return;
7478 msg_putchar('\n');
7479 if (got_int)
7480 return;
7481 if (event != last_event || ap->group != last_group)
7483 if (ap->group != AUGROUP_DEFAULT)
7485 if (AUGROUP_NAME(ap->group) == NULL)
7486 msg_puts_attr((char_u *)_("--Deleted--"), hl_attr(HLF_E));
7487 else
7488 msg_puts_attr(AUGROUP_NAME(ap->group), hl_attr(HLF_T));
7489 msg_puts((char_u *)" ");
7491 msg_puts_attr(event_nr2name(event), hl_attr(HLF_T));
7492 last_event = event;
7493 last_group = ap->group;
7494 msg_putchar('\n');
7495 if (got_int)
7496 return;
7498 msg_col = 4;
7499 msg_outtrans(ap->pat);
7501 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7503 if (ac->cmd != NULL) /* skip removed commands */
7505 if (msg_col >= 14)
7506 msg_putchar('\n');
7507 msg_col = 14;
7508 if (got_int)
7509 return;
7510 msg_outtrans(ac->cmd);
7511 #ifdef FEAT_EVAL
7512 if (p_verbose > 0)
7513 last_set_msg(ac->scriptID);
7514 #endif
7515 if (got_int)
7516 return;
7517 if (ac->next != NULL)
7519 msg_putchar('\n');
7520 if (got_int)
7521 return;
7528 * Mark an autocommand pattern for deletion.
7530 static void
7531 au_remove_pat(ap)
7532 AutoPat *ap;
7534 vim_free(ap->pat);
7535 ap->pat = NULL;
7536 ap->buflocal_nr = -1;
7537 au_need_clean = TRUE;
7541 * Mark all commands for a pattern for deletion.
7543 static void
7544 au_remove_cmds(ap)
7545 AutoPat *ap;
7547 AutoCmd *ac;
7549 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7551 vim_free(ac->cmd);
7552 ac->cmd = NULL;
7554 au_need_clean = TRUE;
7558 * Cleanup autocommands and patterns that have been deleted.
7559 * This is only done when not executing autocommands.
7561 static void
7562 au_cleanup()
7564 AutoPat *ap, **prev_ap;
7565 AutoCmd *ac, **prev_ac;
7566 event_T event;
7568 if (autocmd_busy || !au_need_clean)
7569 return;
7571 /* loop over all events */
7572 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7573 event = (event_T)((int)event + 1))
7575 /* loop over all autocommand patterns */
7576 prev_ap = &(first_autopat[(int)event]);
7577 for (ap = *prev_ap; ap != NULL; ap = *prev_ap)
7579 /* loop over all commands for this pattern */
7580 prev_ac = &(ap->cmds);
7581 for (ac = *prev_ac; ac != NULL; ac = *prev_ac)
7583 /* remove the command if the pattern is to be deleted or when
7584 * the command has been marked for deletion */
7585 if (ap->pat == NULL || ac->cmd == NULL)
7587 *prev_ac = ac->next;
7588 vim_free(ac->cmd);
7589 vim_free(ac);
7591 else
7592 prev_ac = &(ac->next);
7595 /* remove the pattern if it has been marked for deletion */
7596 if (ap->pat == NULL)
7598 *prev_ap = ap->next;
7599 vim_free(ap->reg_prog);
7600 vim_free(ap);
7602 else
7603 prev_ap = &(ap->next);
7607 au_need_clean = FALSE;
7611 * Called when buffer is freed, to remove/invalidate related buffer-local
7612 * autocmds.
7614 void
7615 aubuflocal_remove(buf)
7616 buf_T *buf;
7618 AutoPat *ap;
7619 event_T event;
7620 AutoPatCmd *apc;
7622 /* invalidate currently executing autocommands */
7623 for (apc = active_apc_list; apc; apc = apc->next)
7624 if (buf->b_fnum == apc->arg_bufnr)
7625 apc->arg_bufnr = 0;
7627 /* invalidate buflocals looping through events */
7628 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7629 event = (event_T)((int)event + 1))
7630 /* loop over all autocommand patterns */
7631 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
7632 if (ap->buflocal_nr == buf->b_fnum)
7634 au_remove_pat(ap);
7635 if (p_verbose >= 6)
7637 verbose_enter();
7638 smsg((char_u *)
7639 _("auto-removing autocommand: %s <buffer=%d>"),
7640 event_nr2name(event), buf->b_fnum);
7641 verbose_leave();
7644 au_cleanup();
7648 * Add an autocmd group name.
7649 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
7651 static int
7652 au_new_group(name)
7653 char_u *name;
7655 int i;
7657 i = au_find_group(name);
7658 if (i == AUGROUP_ERROR) /* the group doesn't exist yet, add it */
7660 /* First try using a free entry. */
7661 for (i = 0; i < augroups.ga_len; ++i)
7662 if (AUGROUP_NAME(i) == NULL)
7663 break;
7664 if (i == augroups.ga_len && ga_grow(&augroups, 1) == FAIL)
7665 return AUGROUP_ERROR;
7667 AUGROUP_NAME(i) = vim_strsave(name);
7668 if (AUGROUP_NAME(i) == NULL)
7669 return AUGROUP_ERROR;
7670 if (i == augroups.ga_len)
7671 ++augroups.ga_len;
7674 return i;
7677 static void
7678 au_del_group(name)
7679 char_u *name;
7681 int i;
7683 i = au_find_group(name);
7684 if (i == AUGROUP_ERROR) /* the group doesn't exist */
7685 EMSG2(_("E367: No such group: \"%s\""), name);
7686 else
7688 vim_free(AUGROUP_NAME(i));
7689 AUGROUP_NAME(i) = NULL;
7694 * Find the ID of an autocmd group name.
7695 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
7697 static int
7698 au_find_group(name)
7699 char_u *name;
7701 int i;
7703 for (i = 0; i < augroups.ga_len; ++i)
7704 if (AUGROUP_NAME(i) != NULL && STRCMP(AUGROUP_NAME(i), name) == 0)
7705 return i;
7706 return AUGROUP_ERROR;
7710 * Return TRUE if augroup "name" exists.
7713 au_has_group(name)
7714 char_u *name;
7716 return au_find_group(name) != AUGROUP_ERROR;
7720 * ":augroup {name}".
7722 void
7723 do_augroup(arg, del_group)
7724 char_u *arg;
7725 int del_group;
7727 int i;
7729 if (del_group)
7731 if (*arg == NUL)
7732 EMSG(_(e_argreq));
7733 else
7734 au_del_group(arg);
7736 else if (STRICMP(arg, "end") == 0) /* ":aug end": back to group 0 */
7737 current_augroup = AUGROUP_DEFAULT;
7738 else if (*arg) /* ":aug xxx": switch to group xxx */
7740 i = au_new_group(arg);
7741 if (i != AUGROUP_ERROR)
7742 current_augroup = i;
7744 else /* ":aug": list the group names */
7746 msg_start();
7747 for (i = 0; i < augroups.ga_len; ++i)
7749 if (AUGROUP_NAME(i) != NULL)
7751 msg_puts(AUGROUP_NAME(i));
7752 msg_puts((char_u *)" ");
7755 msg_clr_eos();
7756 msg_end();
7760 #if defined(EXITFREE) || defined(PROTO)
7761 void
7762 free_all_autocmds()
7764 for (current_augroup = -1; current_augroup < augroups.ga_len;
7765 ++current_augroup)
7766 do_autocmd((char_u *)"", TRUE);
7767 ga_clear_strings(&augroups);
7769 #endif
7772 * Return the event number for event name "start".
7773 * Return NUM_EVENTS if the event name was not found.
7774 * Return a pointer to the next event name in "end".
7776 static event_T
7777 event_name2nr(start, end)
7778 char_u *start;
7779 char_u **end;
7781 char_u *p;
7782 int i;
7783 int len;
7785 /* the event name ends with end of line, a blank or a comma */
7786 for (p = start; *p && !vim_iswhite(*p) && *p != ','; ++p)
7788 for (i = 0; event_names[i].name != NULL; ++i)
7790 len = (int)STRLEN(event_names[i].name);
7791 if (len == p - start && STRNICMP(event_names[i].name, start, len) == 0)
7792 break;
7794 if (*p == ',')
7795 ++p;
7796 *end = p;
7797 if (event_names[i].name == NULL)
7798 return NUM_EVENTS;
7799 return event_names[i].event;
7803 * Return the name for event "event".
7805 static char_u *
7806 event_nr2name(event)
7807 event_T event;
7809 int i;
7811 for (i = 0; event_names[i].name != NULL; ++i)
7812 if (event_names[i].event == event)
7813 return (char_u *)event_names[i].name;
7814 return (char_u *)"Unknown";
7818 * Scan over the events. "*" stands for all events.
7820 static char_u *
7821 find_end_event(arg, have_group)
7822 char_u *arg;
7823 int have_group; /* TRUE when group name was found */
7825 char_u *pat;
7826 char_u *p;
7828 if (*arg == '*')
7830 if (arg[1] && !vim_iswhite(arg[1]))
7832 EMSG2(_("E215: Illegal character after *: %s"), arg);
7833 return NULL;
7835 pat = arg + 1;
7837 else
7839 for (pat = arg; *pat && !vim_iswhite(*pat); pat = p)
7841 if ((int)event_name2nr(pat, &p) >= (int)NUM_EVENTS)
7843 if (have_group)
7844 EMSG2(_("E216: No such event: %s"), pat);
7845 else
7846 EMSG2(_("E216: No such group or event: %s"), pat);
7847 return NULL;
7851 return pat;
7855 * Return TRUE if "event" is included in 'eventignore'.
7857 static int
7858 event_ignored(event)
7859 event_T event;
7861 char_u *p = p_ei;
7863 while (*p != NUL)
7865 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
7866 return TRUE;
7867 if (event_name2nr(p, &p) == event)
7868 return TRUE;
7871 return FALSE;
7875 * Return OK when the contents of p_ei is valid, FAIL otherwise.
7878 check_ei()
7880 char_u *p = p_ei;
7882 while (*p)
7884 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
7886 p += 3;
7887 if (*p == ',')
7888 ++p;
7890 else if (event_name2nr(p, &p) == NUM_EVENTS)
7891 return FAIL;
7894 return OK;
7897 # if defined(FEAT_SYN_HL) || defined(PROTO)
7900 * Add "what" to 'eventignore' to skip loading syntax highlighting for every
7901 * buffer loaded into the window. "what" must start with a comma.
7902 * Returns the old value of 'eventignore' in allocated memory.
7904 char_u *
7905 au_event_disable(what)
7906 char *what;
7908 char_u *new_ei;
7909 char_u *save_ei;
7911 save_ei = vim_strsave(p_ei);
7912 if (save_ei != NULL)
7914 new_ei = vim_strnsave(p_ei, (int)(STRLEN(p_ei) + STRLEN(what)));
7915 if (new_ei != NULL)
7917 STRCAT(new_ei, what);
7918 set_string_option_direct((char_u *)"ei", -1, new_ei,
7919 OPT_FREE, SID_NONE);
7920 vim_free(new_ei);
7923 return save_ei;
7926 void
7927 au_event_restore(old_ei)
7928 char_u *old_ei;
7930 if (old_ei != NULL)
7932 set_string_option_direct((char_u *)"ei", -1, old_ei,
7933 OPT_FREE, SID_NONE);
7934 vim_free(old_ei);
7937 # endif /* FEAT_SYN_HL */
7940 * do_autocmd() -- implements the :autocmd command. Can be used in the
7941 * following ways:
7943 * :autocmd <event> <pat> <cmd> Add <cmd> to the list of commands that
7944 * will be automatically executed for <event>
7945 * when editing a file matching <pat>, in
7946 * the current group.
7947 * :autocmd <event> <pat> Show the auto-commands associated with
7948 * <event> and <pat>.
7949 * :autocmd <event> Show the auto-commands associated with
7950 * <event>.
7951 * :autocmd Show all auto-commands.
7952 * :autocmd! <event> <pat> <cmd> Remove all auto-commands associated with
7953 * <event> and <pat>, and add the command
7954 * <cmd>, for the current group.
7955 * :autocmd! <event> <pat> Remove all auto-commands associated with
7956 * <event> and <pat> for the current group.
7957 * :autocmd! <event> Remove all auto-commands associated with
7958 * <event> for the current group.
7959 * :autocmd! Remove ALL auto-commands for the current
7960 * group.
7962 * Multiple events and patterns may be given separated by commas. Here are
7963 * some examples:
7964 * :autocmd bufread,bufenter *.c,*.h set tw=0 smartindent noic
7965 * :autocmd bufleave * set tw=79 nosmartindent ic infercase
7967 * :autocmd * *.c show all autocommands for *.c files.
7969 * Mostly a {group} argument can optionally appear before <event>.
7971 void
7972 do_autocmd(arg, forceit)
7973 char_u *arg;
7974 int forceit;
7976 char_u *pat;
7977 char_u *envpat = NULL;
7978 char_u *cmd;
7979 event_T event;
7980 int need_free = FALSE;
7981 int nested = FALSE;
7982 int group;
7985 * Check for a legal group name. If not, use AUGROUP_ALL.
7987 group = au_get_grouparg(&arg);
7988 if (arg == NULL) /* out of memory */
7989 return;
7992 * Scan over the events.
7993 * If we find an illegal name, return here, don't do anything.
7995 pat = find_end_event(arg, group != AUGROUP_ALL);
7996 if (pat == NULL)
7997 return;
8000 * Scan over the pattern. Put a NUL at the end.
8002 pat = skipwhite(pat);
8003 cmd = pat;
8004 while (*cmd && (!vim_iswhite(*cmd) || cmd[-1] == '\\'))
8005 cmd++;
8006 if (*cmd)
8007 *cmd++ = NUL;
8009 /* Expand environment variables in the pattern. Set 'shellslash', we want
8010 * forward slashes here. */
8011 if (vim_strchr(pat, '$') != NULL || vim_strchr(pat, '~') != NULL)
8013 #ifdef BACKSLASH_IN_FILENAME
8014 int p_ssl_save = p_ssl;
8016 p_ssl = TRUE;
8017 #endif
8018 envpat = expand_env_save(pat);
8019 #ifdef BACKSLASH_IN_FILENAME
8020 p_ssl = p_ssl_save;
8021 #endif
8022 if (envpat != NULL)
8023 pat = envpat;
8027 * Check for "nested" flag.
8029 cmd = skipwhite(cmd);
8030 if (*cmd != NUL && STRNCMP(cmd, "nested", 6) == 0 && vim_iswhite(cmd[6]))
8032 nested = TRUE;
8033 cmd = skipwhite(cmd + 6);
8037 * Find the start of the commands.
8038 * Expand <sfile> in it.
8040 if (*cmd != NUL)
8042 cmd = expand_sfile(cmd);
8043 if (cmd == NULL) /* some error */
8044 return;
8045 need_free = TRUE;
8049 * Print header when showing autocommands.
8051 if (!forceit && *cmd == NUL)
8053 /* Highlight title */
8054 MSG_PUTS_TITLE(_("\n--- Auto-Commands ---"));
8058 * Loop over the events.
8060 last_event = (event_T)-1; /* for listing the event name */
8061 last_group = AUGROUP_ERROR; /* for listing the group name */
8062 if (*arg == '*' || *arg == NUL)
8064 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8065 event = (event_T)((int)event + 1))
8066 if (do_autocmd_event(event, pat,
8067 nested, cmd, forceit, group) == FAIL)
8068 break;
8070 else
8072 while (*arg && !vim_iswhite(*arg))
8073 if (do_autocmd_event(event_name2nr(arg, &arg), pat,
8074 nested, cmd, forceit, group) == FAIL)
8075 break;
8078 if (need_free)
8079 vim_free(cmd);
8080 vim_free(envpat);
8084 * Find the group ID in a ":autocmd" or ":doautocmd" argument.
8085 * The "argp" argument is advanced to the following argument.
8087 * Returns the group ID, AUGROUP_ERROR for error (out of memory).
8089 static int
8090 au_get_grouparg(argp)
8091 char_u **argp;
8093 char_u *group_name;
8094 char_u *p;
8095 char_u *arg = *argp;
8096 int group = AUGROUP_ALL;
8098 p = skiptowhite(arg);
8099 if (p > arg)
8101 group_name = vim_strnsave(arg, (int)(p - arg));
8102 if (group_name == NULL) /* out of memory */
8103 return AUGROUP_ERROR;
8104 group = au_find_group(group_name);
8105 if (group == AUGROUP_ERROR)
8106 group = AUGROUP_ALL; /* no match, use all groups */
8107 else
8108 *argp = skipwhite(p); /* match, skip over group name */
8109 vim_free(group_name);
8111 return group;
8115 * do_autocmd() for one event.
8116 * If *pat == NUL do for all patterns.
8117 * If *cmd == NUL show entries.
8118 * If forceit == TRUE delete entries.
8119 * If group is not AUGROUP_ALL, only use this group.
8121 static int
8122 do_autocmd_event(event, pat, nested, cmd, forceit, group)
8123 event_T event;
8124 char_u *pat;
8125 int nested;
8126 char_u *cmd;
8127 int forceit;
8128 int group;
8130 AutoPat *ap;
8131 AutoPat **prev_ap;
8132 AutoCmd *ac;
8133 AutoCmd **prev_ac;
8134 int brace_level;
8135 char_u *endpat;
8136 int findgroup;
8137 int allgroups;
8138 int patlen;
8139 int is_buflocal;
8140 int buflocal_nr;
8141 char_u buflocal_pat[25]; /* for "<buffer=X>" */
8143 if (group == AUGROUP_ALL)
8144 findgroup = current_augroup;
8145 else
8146 findgroup = group;
8147 allgroups = (group == AUGROUP_ALL && !forceit && *cmd == NUL);
8150 * Show or delete all patterns for an event.
8152 if (*pat == NUL)
8154 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8156 if (forceit) /* delete the AutoPat, if it's in the current group */
8158 if (ap->group == findgroup)
8159 au_remove_pat(ap);
8161 else if (group == AUGROUP_ALL || ap->group == group)
8162 show_autocmd(ap, event);
8167 * Loop through all the specified patterns.
8169 for ( ; *pat; pat = (*endpat == ',' ? endpat + 1 : endpat))
8172 * Find end of the pattern.
8173 * Watch out for a comma in braces, like "*.\{obj,o\}".
8175 brace_level = 0;
8176 for (endpat = pat; *endpat && (*endpat != ',' || brace_level
8177 || endpat[-1] == '\\'); ++endpat)
8179 if (*endpat == '{')
8180 brace_level++;
8181 else if (*endpat == '}')
8182 brace_level--;
8184 if (pat == endpat) /* ignore single comma */
8185 continue;
8186 patlen = (int)(endpat - pat);
8189 * detect special <buflocal[=X]> buffer-local patterns
8191 is_buflocal = FALSE;
8192 buflocal_nr = 0;
8194 if (patlen >= 7 && STRNCMP(pat, "<buffer", 7) == 0
8195 && pat[patlen - 1] == '>')
8197 /* Error will be printed only for addition. printing and removing
8198 * will proceed silently. */
8199 is_buflocal = TRUE;
8200 if (patlen == 8)
8201 buflocal_nr = curbuf->b_fnum;
8202 else if (patlen > 9 && pat[7] == '=')
8204 /* <buffer=abuf> */
8205 if (patlen == 13 && STRNICMP(pat, "<buffer=abuf>", 13))
8206 buflocal_nr = autocmd_bufnr;
8207 /* <buffer=123> */
8208 else if (skipdigits(pat + 8) == pat + patlen - 1)
8209 buflocal_nr = atoi((char *)pat + 8);
8213 if (is_buflocal)
8215 /* normalize pat into standard "<buffer>#N" form */
8216 sprintf((char *)buflocal_pat, "<buffer=%d>", buflocal_nr);
8217 pat = buflocal_pat; /* can modify pat and patlen */
8218 patlen = (int)STRLEN(buflocal_pat); /* but not endpat */
8222 * Find AutoPat entries with this pattern.
8224 prev_ap = &first_autopat[(int)event];
8225 while ((ap = *prev_ap) != NULL)
8227 if (ap->pat != NULL)
8229 /* Accept a pattern when:
8230 * - a group was specified and it's that group, or a group was
8231 * not specified and it's the current group, or a group was
8232 * not specified and we are listing
8233 * - the length of the pattern matches
8234 * - the pattern matches.
8235 * For <buffer[=X]>, this condition works because we normalize
8236 * all buffer-local patterns.
8238 if ((allgroups || ap->group == findgroup)
8239 && ap->patlen == patlen
8240 && STRNCMP(pat, ap->pat, patlen) == 0)
8243 * Remove existing autocommands.
8244 * If adding any new autocmd's for this AutoPat, don't
8245 * delete the pattern from the autopat list, append to
8246 * this list.
8248 if (forceit)
8250 if (*cmd != NUL && ap->next == NULL)
8252 au_remove_cmds(ap);
8253 break;
8255 au_remove_pat(ap);
8259 * Show autocmd's for this autopat, or buflocals <buffer=X>
8261 else if (*cmd == NUL)
8262 show_autocmd(ap, event);
8265 * Add autocmd to this autopat, if it's the last one.
8267 else if (ap->next == NULL)
8268 break;
8271 prev_ap = &ap->next;
8275 * Add a new command.
8277 if (*cmd != NUL)
8280 * If the pattern we want to add a command to does appear at the
8281 * end of the list (or not is not in the list at all), add the
8282 * pattern at the end of the list.
8284 if (ap == NULL)
8286 /* refuse to add buffer-local ap if buffer number is invalid */
8287 if (is_buflocal && (buflocal_nr == 0
8288 || buflist_findnr(buflocal_nr) == NULL))
8290 EMSGN(_("E680: <buffer=%d>: invalid buffer number "),
8291 buflocal_nr);
8292 return FAIL;
8295 ap = (AutoPat *)alloc((unsigned)sizeof(AutoPat));
8296 if (ap == NULL)
8297 return FAIL;
8298 ap->pat = vim_strnsave(pat, patlen);
8299 ap->patlen = patlen;
8300 if (ap->pat == NULL)
8302 vim_free(ap);
8303 return FAIL;
8306 if (is_buflocal)
8308 ap->buflocal_nr = buflocal_nr;
8309 ap->reg_prog = NULL;
8311 else
8313 char_u *reg_pat;
8315 ap->buflocal_nr = 0;
8316 reg_pat = file_pat_to_reg_pat(pat, endpat,
8317 &ap->allow_dirs, TRUE);
8318 if (reg_pat != NULL)
8319 ap->reg_prog = vim_regcomp(reg_pat, RE_MAGIC);
8320 vim_free(reg_pat);
8321 if (reg_pat == NULL || ap->reg_prog == NULL)
8323 vim_free(ap->pat);
8324 vim_free(ap);
8325 return FAIL;
8328 ap->cmds = NULL;
8329 *prev_ap = ap;
8330 ap->next = NULL;
8331 if (group == AUGROUP_ALL)
8332 ap->group = current_augroup;
8333 else
8334 ap->group = group;
8338 * Add the autocmd at the end of the AutoCmd list.
8340 prev_ac = &(ap->cmds);
8341 while ((ac = *prev_ac) != NULL)
8342 prev_ac = &ac->next;
8343 ac = (AutoCmd *)alloc((unsigned)sizeof(AutoCmd));
8344 if (ac == NULL)
8345 return FAIL;
8346 ac->cmd = vim_strsave(cmd);
8347 #ifdef FEAT_EVAL
8348 ac->scriptID = current_SID;
8349 #endif
8350 if (ac->cmd == NULL)
8352 vim_free(ac);
8353 return FAIL;
8355 ac->next = NULL;
8356 *prev_ac = ac;
8357 ac->nested = nested;
8361 au_cleanup(); /* may really delete removed patterns/commands now */
8362 return OK;
8366 * Implementation of ":doautocmd [group] event [fname]".
8367 * Return OK for success, FAIL for failure;
8370 do_doautocmd(arg, do_msg)
8371 char_u *arg;
8372 int do_msg; /* give message for no matching autocmds? */
8374 char_u *fname;
8375 int nothing_done = TRUE;
8376 int group;
8379 * Check for a legal group name. If not, use AUGROUP_ALL.
8381 group = au_get_grouparg(&arg);
8382 if (arg == NULL) /* out of memory */
8383 return FAIL;
8385 if (*arg == '*')
8387 EMSG(_("E217: Can't execute autocommands for ALL events"));
8388 return FAIL;
8392 * Scan over the events.
8393 * If we find an illegal name, return here, don't do anything.
8395 fname = find_end_event(arg, group != AUGROUP_ALL);
8396 if (fname == NULL)
8397 return FAIL;
8399 fname = skipwhite(fname);
8402 * Loop over the events.
8404 while (*arg && !vim_iswhite(*arg))
8405 if (apply_autocmds_group(event_name2nr(arg, &arg),
8406 fname, NULL, TRUE, group, curbuf, NULL))
8407 nothing_done = FALSE;
8409 if (nothing_done && do_msg)
8410 MSG(_("No matching autocommands"));
8412 #ifdef FEAT_EVAL
8413 return aborting() ? FAIL : OK;
8414 #else
8415 return OK;
8416 #endif
8420 * ":doautoall": execute autocommands for each loaded buffer.
8422 void
8423 ex_doautoall(eap)
8424 exarg_T *eap;
8426 int retval;
8427 aco_save_T aco;
8428 buf_T *buf;
8431 * This is a bit tricky: For some commands curwin->w_buffer needs to be
8432 * equal to curbuf, but for some buffers there may not be a window.
8433 * So we change the buffer for the current window for a moment. This
8434 * gives problems when the autocommands make changes to the list of
8435 * buffers or windows...
8437 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8439 if (buf->b_ml.ml_mfp != NULL)
8441 /* find a window for this buffer and save some values */
8442 aucmd_prepbuf(&aco, buf);
8444 /* execute the autocommands for this buffer */
8445 retval = do_doautocmd(eap->arg, FALSE);
8447 /* Execute the modeline settings, but don't set window-local
8448 * options if we are using the current window for another buffer. */
8449 do_modelines(curwin == aucmd_win ? OPT_NOWIN : 0);
8451 /* restore the current window */
8452 aucmd_restbuf(&aco);
8454 /* stop if there is some error or buffer was deleted */
8455 if (retval == FAIL || !buf_valid(buf))
8456 break;
8460 check_cursor(); /* just in case lines got deleted */
8464 * Prepare for executing autocommands for (hidden) buffer "buf".
8465 * Search for a visible window containing the current buffer. If there isn't
8466 * one then use "aucmd_win".
8467 * Set "curbuf" and "curwin" to match "buf".
8468 * When FEAT_AUTOCMD is not defined another version is used, see below.
8470 void
8471 aucmd_prepbuf(aco, buf)
8472 aco_save_T *aco; /* structure to save values in */
8473 buf_T *buf; /* new curbuf */
8475 win_T *win;
8476 #ifdef FEAT_WINDOWS
8477 int save_ea;
8478 #endif
8480 /* Find a window that is for the new buffer */
8481 if (buf == curbuf) /* be quick when buf is curbuf */
8482 win = curwin;
8483 else
8484 #ifdef FEAT_WINDOWS
8485 for (win = firstwin; win != NULL; win = win->w_next)
8486 if (win->w_buffer == buf)
8487 break;
8488 #else
8489 win = NULL;
8490 #endif
8492 /* Allocate "aucmd_win" when needed. If this fails (out of memory) fall
8493 * back to using the current window. */
8494 if (win == NULL && aucmd_win == NULL)
8496 win_alloc_aucmd_win();
8497 if (aucmd_win == NULL)
8498 win = curwin;
8500 if (win == NULL && aucmd_win_used)
8501 /* Strange recursive autocommand, fall back to using the current
8502 * window. Expect a few side effects... */
8503 win = curwin;
8505 aco->save_curwin = curwin;
8506 aco->save_curbuf = curbuf;
8507 if (win != NULL)
8509 /* There is a window for "buf" in the current tab page, make it the
8510 * curwin. This is preferred, it has the least side effects (esp. if
8511 * "buf" is curbuf). */
8512 aco->use_aucmd_win = FALSE;
8513 curwin = win;
8515 else
8517 /* There is no window for "buf", use "aucmd_win". To minimize the side
8518 * effects, insert it in a the current tab page.
8519 * Anything related to a window (e.g., setting folds) may have
8520 * unexpected results. */
8521 aco->use_aucmd_win = TRUE;
8522 aucmd_win_used = TRUE;
8523 aucmd_win->w_buffer = buf;
8524 ++buf->b_nwindows;
8525 win_init_empty(aucmd_win); /* set cursor and topline to safe values */
8526 vim_free(aucmd_win->w_localdir);
8527 aucmd_win->w_localdir = NULL;
8529 /* Make sure w_localdir and globaldir are NULL to avoid a chdir() in
8530 * win_enter_ext(). */
8531 aucmd_win->w_localdir = NULL;
8532 aco->globaldir = globaldir;
8533 globaldir = NULL;
8536 #ifdef FEAT_WINDOWS
8537 /* Split the current window, put the aucmd_win in the upper half.
8538 * We don't want the BufEnter or WinEnter autocommands. */
8539 block_autocmds();
8540 make_snapshot(SNAP_AUCMD_IDX);
8541 save_ea = p_ea;
8542 p_ea = FALSE;
8543 (void)win_split_ins(0, WSP_TOP, aucmd_win, 0);
8544 (void)win_comp_pos(); /* recompute window positions */
8545 p_ea = save_ea;
8546 unblock_autocmds();
8547 #endif
8548 curwin = aucmd_win;
8550 curbuf = buf;
8551 aco->new_curwin = curwin;
8552 aco->new_curbuf = curbuf;
8556 * Cleanup after executing autocommands for a (hidden) buffer.
8557 * Restore the window as it was (if possible).
8558 * When FEAT_AUTOCMD is not defined another version is used, see below.
8560 void
8561 aucmd_restbuf(aco)
8562 aco_save_T *aco; /* structure holding saved values */
8564 #ifdef FEAT_WINDOWS
8565 int dummy;
8566 #endif
8568 if (aco->use_aucmd_win)
8570 --curbuf->b_nwindows;
8571 #ifdef FEAT_WINDOWS
8572 /* Find "aucmd_win", it can't be closed, but it may be in another tab
8573 * page. Do not trigger autocommands here. */
8574 block_autocmds();
8575 if (curwin != aucmd_win)
8577 tabpage_T *tp;
8578 win_T *wp;
8580 FOR_ALL_TAB_WINDOWS(tp, wp)
8582 if (wp == aucmd_win)
8584 if (tp != curtab)
8585 goto_tabpage_tp(tp);
8586 win_goto(aucmd_win);
8587 break;
8592 /* Remove the window and frame from the tree of frames. */
8593 (void)winframe_remove(curwin, &dummy, NULL);
8594 win_remove(curwin, NULL);
8595 aucmd_win_used = FALSE;
8596 last_status(FALSE); /* may need to remove last status line */
8597 restore_snapshot(SNAP_AUCMD_IDX, FALSE);
8598 (void)win_comp_pos(); /* recompute window positions */
8599 unblock_autocmds();
8601 if (win_valid(aco->save_curwin))
8602 curwin = aco->save_curwin;
8603 else
8604 /* Hmm, original window disappeared. Just use the first one. */
8605 curwin = firstwin;
8606 # ifdef FEAT_EVAL
8607 vars_clear(&aucmd_win->w_vars.dv_hashtab); /* free all w: variables */
8608 hash_init(&aucmd_win->w_vars.dv_hashtab); /* re-use the hashtab */
8609 # endif
8610 #else
8611 curwin = aco->save_curwin;
8612 #endif
8613 curbuf = curwin->w_buffer;
8615 vim_free(globaldir);
8616 globaldir = aco->globaldir;
8618 /* the buffer contents may have changed */
8619 check_cursor();
8620 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
8622 curwin->w_topline = curbuf->b_ml.ml_line_count;
8623 #ifdef FEAT_DIFF
8624 curwin->w_topfill = 0;
8625 #endif
8627 #if defined(FEAT_GUI)
8628 /* Hide the scrollbars from the aucmd_win and update. */
8629 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_LEFT], FALSE);
8630 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_RIGHT], FALSE);
8631 gui_may_update_scrollbars();
8632 #endif
8634 else
8636 /* restore curwin */
8637 #ifdef FEAT_WINDOWS
8638 if (win_valid(aco->save_curwin))
8639 #endif
8641 /* Restore the buffer which was previously edited by curwin, if
8642 * it was changed, we are still the same window and the buffer is
8643 * valid. */
8644 if (curwin == aco->new_curwin
8645 && curbuf != aco->new_curbuf
8646 && buf_valid(aco->new_curbuf)
8647 && aco->new_curbuf->b_ml.ml_mfp != NULL)
8649 --curbuf->b_nwindows;
8650 curbuf = aco->new_curbuf;
8651 curwin->w_buffer = curbuf;
8652 ++curbuf->b_nwindows;
8655 curwin = aco->save_curwin;
8656 curbuf = curwin->w_buffer;
8661 static int autocmd_nested = FALSE;
8664 * Execute autocommands for "event" and file name "fname".
8665 * Return TRUE if some commands were executed.
8668 apply_autocmds(event, fname, fname_io, force, buf)
8669 event_T event;
8670 char_u *fname; /* NULL or empty means use actual file name */
8671 char_u *fname_io; /* fname to use for <afile> on cmdline */
8672 int force; /* when TRUE, ignore autocmd_busy */
8673 buf_T *buf; /* buffer for <abuf> */
8675 return apply_autocmds_group(event, fname, fname_io, force,
8676 AUGROUP_ALL, buf, NULL);
8680 * Like apply_autocmds(), but with extra "eap" argument. This takes care of
8681 * setting v:filearg.
8683 static int
8684 apply_autocmds_exarg(event, fname, fname_io, force, buf, eap)
8685 event_T event;
8686 char_u *fname;
8687 char_u *fname_io;
8688 int force;
8689 buf_T *buf;
8690 exarg_T *eap;
8692 return apply_autocmds_group(event, fname, fname_io, force,
8693 AUGROUP_ALL, buf, eap);
8697 * Like apply_autocmds(), but handles the caller's retval. If the script
8698 * processing is being aborted or if retval is FAIL when inside a try
8699 * conditional, no autocommands are executed. If otherwise the autocommands
8700 * cause the script to be aborted, retval is set to FAIL.
8703 apply_autocmds_retval(event, fname, fname_io, force, buf, retval)
8704 event_T event;
8705 char_u *fname; /* NULL or empty means use actual file name */
8706 char_u *fname_io; /* fname to use for <afile> on cmdline */
8707 int force; /* when TRUE, ignore autocmd_busy */
8708 buf_T *buf; /* buffer for <abuf> */
8709 int *retval; /* pointer to caller's retval */
8711 int did_cmd;
8713 #ifdef FEAT_EVAL
8714 if (should_abort(*retval))
8715 return FALSE;
8716 #endif
8718 did_cmd = apply_autocmds_group(event, fname, fname_io, force,
8719 AUGROUP_ALL, buf, NULL);
8720 if (did_cmd
8721 #ifdef FEAT_EVAL
8722 && aborting()
8723 #endif
8725 *retval = FAIL;
8726 return did_cmd;
8730 * Return TRUE when there is a CursorHold autocommand defined.
8733 has_cursorhold()
8735 return (first_autopat[(int)(get_real_state() == NORMAL_BUSY
8736 ? EVENT_CURSORHOLD : EVENT_CURSORHOLDI)] != NULL);
8740 * Return TRUE if the CursorHold event can be triggered.
8743 trigger_cursorhold()
8745 int state;
8747 /* trigger a compile request if the current buffer is in
8748 * the watchlist and the current mode is NOT CMDLINE. */
8749 if ((State & CMDLINE) == 0)
8750 if (cc_is_buf_watched(curbuf))
8751 cc_request_compile(curbuf);
8753 if (!did_cursorhold && has_cursorhold() && !Recording
8754 #ifdef FEAT_INS_EXPAND
8755 && !ins_compl_active()
8756 #endif
8759 state = get_real_state();
8760 if (state == NORMAL_BUSY || (state & INSERT) != 0)
8761 return TRUE;
8763 return FALSE;
8767 * Return TRUE when there is a CursorMoved autocommand defined.
8770 has_cursormoved()
8772 return (first_autopat[(int)EVENT_CURSORMOVED] != NULL);
8776 * Return TRUE when there is a CursorMovedI autocommand defined.
8779 has_cursormovedI()
8781 return (first_autopat[(int)EVENT_CURSORMOVEDI] != NULL);
8784 static int
8785 apply_autocmds_group(event, fname, fname_io, force, group, buf, eap)
8786 event_T event;
8787 char_u *fname; /* NULL or empty means use actual file name */
8788 char_u *fname_io; /* fname to use for <afile> on cmdline, NULL means
8789 use fname */
8790 int force; /* when TRUE, ignore autocmd_busy */
8791 int group; /* group ID, or AUGROUP_ALL */
8792 buf_T *buf; /* buffer for <abuf> */
8793 exarg_T *eap; /* command arguments */
8795 char_u *sfname = NULL; /* short file name */
8796 char_u *tail;
8797 int save_changed;
8798 buf_T *old_curbuf;
8799 int retval = FALSE;
8800 char_u *save_sourcing_name;
8801 linenr_T save_sourcing_lnum;
8802 char_u *save_autocmd_fname;
8803 int save_autocmd_fname_full;
8804 int save_autocmd_bufnr;
8805 char_u *save_autocmd_match;
8806 int save_autocmd_busy;
8807 int save_autocmd_nested;
8808 static int nesting = 0;
8809 AutoPatCmd patcmd;
8810 AutoPat *ap;
8811 #ifdef FEAT_EVAL
8812 scid_T save_current_SID;
8813 void *save_funccalp;
8814 char_u *save_cmdarg;
8815 long save_cmdbang;
8816 #endif
8817 static int filechangeshell_busy = FALSE;
8818 #ifdef FEAT_PROFILE
8819 proftime_T wait_time;
8820 #endif
8823 * Quickly return if there are no autocommands for this event or
8824 * autocommands are blocked.
8826 if (first_autopat[(int)event] == NULL || autocmd_blocked > 0)
8827 goto BYPASS_AU;
8830 * When autocommands are busy, new autocommands are only executed when
8831 * explicitly enabled with the "nested" flag.
8833 if (autocmd_busy && !(force || autocmd_nested))
8834 goto BYPASS_AU;
8836 #ifdef FEAT_EVAL
8838 * Quickly return when immediately aborting on error, or when an interrupt
8839 * occurred or an exception was thrown but not caught.
8841 if (aborting())
8842 goto BYPASS_AU;
8843 #endif
8846 * FileChangedShell never nests, because it can create an endless loop.
8848 if (filechangeshell_busy && (event == EVENT_FILECHANGEDSHELL
8849 || event == EVENT_FILECHANGEDSHELLPOST))
8850 goto BYPASS_AU;
8853 * Ignore events in 'eventignore'.
8855 if (event_ignored(event))
8856 goto BYPASS_AU;
8859 * Allow nesting of autocommands, but restrict the depth, because it's
8860 * possible to create an endless loop.
8862 if (nesting == 10)
8864 EMSG(_("E218: autocommand nesting too deep"));
8865 goto BYPASS_AU;
8869 * Check if these autocommands are disabled. Used when doing ":all" or
8870 * ":ball".
8872 if ( (autocmd_no_enter
8873 && (event == EVENT_WINENTER || event == EVENT_BUFENTER))
8874 || (autocmd_no_leave
8875 && (event == EVENT_WINLEAVE || event == EVENT_BUFLEAVE)))
8876 goto BYPASS_AU;
8879 * Save the autocmd_* variables and info about the current buffer.
8881 save_autocmd_fname = autocmd_fname;
8882 save_autocmd_fname_full = autocmd_fname_full;
8883 save_autocmd_bufnr = autocmd_bufnr;
8884 save_autocmd_match = autocmd_match;
8885 save_autocmd_busy = autocmd_busy;
8886 save_autocmd_nested = autocmd_nested;
8887 save_changed = curbuf->b_changed;
8888 old_curbuf = curbuf;
8891 * Set the file name to be used for <afile>.
8892 * Make a copy to avoid that changing a buffer name or directory makes it
8893 * invalid.
8895 if (fname_io == NULL)
8897 if (fname != NULL && *fname != NUL)
8898 autocmd_fname = fname;
8899 else if (buf != NULL)
8900 autocmd_fname = buf->b_ffname;
8901 else
8902 autocmd_fname = NULL;
8904 else
8905 autocmd_fname = fname_io;
8906 if (autocmd_fname != NULL)
8907 autocmd_fname = vim_strsave(autocmd_fname);
8908 autocmd_fname_full = FALSE; /* call FullName_save() later */
8911 * Set the buffer number to be used for <abuf>.
8913 if (buf == NULL)
8914 autocmd_bufnr = 0;
8915 else
8916 autocmd_bufnr = buf->b_fnum;
8919 * When the file name is NULL or empty, use the file name of buffer "buf".
8920 * Always use the full path of the file name to match with, in case
8921 * "allow_dirs" is set.
8923 if (fname == NULL || *fname == NUL)
8925 if (buf == NULL)
8926 fname = NULL;
8927 else
8929 #ifdef FEAT_SYN_HL
8930 if (event == EVENT_SYNTAX)
8931 fname = buf->b_p_syn;
8932 else
8933 #endif
8934 if (event == EVENT_FILETYPE)
8935 fname = buf->b_p_ft;
8936 else
8938 if (buf->b_sfname != NULL)
8939 sfname = vim_strsave(buf->b_sfname);
8940 fname = buf->b_ffname;
8943 if (fname == NULL)
8944 fname = (char_u *)"";
8945 fname = vim_strsave(fname); /* make a copy, so we can change it */
8947 else
8949 sfname = vim_strsave(fname);
8950 /* Don't try expanding FileType, Syntax, FuncUndefined, WindowID or
8951 * QuickFixCmd* */
8952 if (event == EVENT_FILETYPE
8953 || event == EVENT_SYNTAX
8954 || event == EVENT_FUNCUNDEFINED
8955 || event == EVENT_REMOTEREPLY
8956 || event == EVENT_SPELLFILEMISSING
8957 || event == EVENT_QUICKFIXCMDPRE
8958 || event == EVENT_QUICKFIXCMDPOST)
8959 fname = vim_strsave(fname);
8960 else
8961 fname = FullName_save(fname, FALSE);
8963 if (fname == NULL) /* out of memory */
8965 vim_free(sfname);
8966 retval = FALSE;
8967 goto BYPASS_AU;
8970 #ifdef BACKSLASH_IN_FILENAME
8972 * Replace all backslashes with forward slashes. This makes the
8973 * autocommand patterns portable between Unix and MS-DOS.
8975 if (sfname != NULL)
8976 forward_slash(sfname);
8977 forward_slash(fname);
8978 #endif
8980 #ifdef VMS
8981 /* remove version for correct match */
8982 if (sfname != NULL)
8983 vms_remove_version(sfname);
8984 vms_remove_version(fname);
8985 #endif
8988 * Set the name to be used for <amatch>.
8990 autocmd_match = fname;
8993 /* Don't redraw while doing auto commands. */
8994 ++RedrawingDisabled;
8995 save_sourcing_name = sourcing_name;
8996 sourcing_name = NULL; /* don't free this one */
8997 save_sourcing_lnum = sourcing_lnum;
8998 sourcing_lnum = 0; /* no line number here */
9000 #ifdef FEAT_EVAL
9001 save_current_SID = current_SID;
9003 # ifdef FEAT_PROFILE
9004 if (do_profiling == PROF_YES)
9005 prof_child_enter(&wait_time); /* doesn't count for the caller itself */
9006 # endif
9008 /* Don't use local function variables, if called from a function */
9009 save_funccalp = save_funccal();
9010 #endif
9013 * When starting to execute autocommands, save the search patterns.
9015 if (!autocmd_busy)
9017 save_search_patterns();
9018 saveRedobuff();
9019 did_filetype = keep_filetype;
9023 * Note that we are applying autocmds. Some commands need to know.
9025 autocmd_busy = TRUE;
9026 filechangeshell_busy = (event == EVENT_FILECHANGEDSHELL);
9027 ++nesting; /* see matching decrement below */
9029 /* Remember that FileType was triggered. Used for did_filetype(). */
9030 if (event == EVENT_FILETYPE)
9031 did_filetype = TRUE;
9033 tail = gettail(fname);
9035 /* Find first autocommand that matches */
9036 patcmd.curpat = first_autopat[(int)event];
9037 patcmd.nextcmd = NULL;
9038 patcmd.group = group;
9039 patcmd.fname = fname;
9040 patcmd.sfname = sfname;
9041 patcmd.tail = tail;
9042 patcmd.event = event;
9043 patcmd.arg_bufnr = autocmd_bufnr;
9044 patcmd.next = NULL;
9045 auto_next_pat(&patcmd, FALSE);
9047 /* found one, start executing the autocommands */
9048 if (patcmd.curpat != NULL)
9050 /* add to active_apc_list */
9051 patcmd.next = active_apc_list;
9052 active_apc_list = &patcmd;
9054 #ifdef FEAT_EVAL
9055 /* set v:cmdarg (only when there is a matching pattern) */
9056 save_cmdbang = get_vim_var_nr(VV_CMDBANG);
9057 if (eap != NULL)
9059 save_cmdarg = set_cmdarg(eap, NULL);
9060 set_vim_var_nr(VV_CMDBANG, (long)eap->forceit);
9062 else
9063 save_cmdarg = NULL; /* avoid gcc warning */
9064 #endif
9065 retval = TRUE;
9066 /* mark the last pattern, to avoid an endless loop when more patterns
9067 * are added when executing autocommands */
9068 for (ap = patcmd.curpat; ap->next != NULL; ap = ap->next)
9069 ap->last = FALSE;
9070 ap->last = TRUE;
9071 check_lnums(TRUE); /* make sure cursor and topline are valid */
9072 do_cmdline(NULL, getnextac, (void *)&patcmd,
9073 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
9074 #ifdef FEAT_EVAL
9075 if (eap != NULL)
9077 (void)set_cmdarg(NULL, save_cmdarg);
9078 set_vim_var_nr(VV_CMDBANG, save_cmdbang);
9080 #endif
9081 /* delete from active_apc_list */
9082 if (active_apc_list == &patcmd) /* just in case */
9083 active_apc_list = patcmd.next;
9086 --RedrawingDisabled;
9087 autocmd_busy = save_autocmd_busy;
9088 filechangeshell_busy = FALSE;
9089 autocmd_nested = save_autocmd_nested;
9090 vim_free(sourcing_name);
9091 sourcing_name = save_sourcing_name;
9092 sourcing_lnum = save_sourcing_lnum;
9093 vim_free(autocmd_fname);
9094 autocmd_fname = save_autocmd_fname;
9095 autocmd_fname_full = save_autocmd_fname_full;
9096 autocmd_bufnr = save_autocmd_bufnr;
9097 autocmd_match = save_autocmd_match;
9098 #ifdef FEAT_EVAL
9099 current_SID = save_current_SID;
9100 restore_funccal(save_funccalp);
9101 # ifdef FEAT_PROFILE
9102 if (do_profiling == PROF_YES)
9103 prof_child_exit(&wait_time);
9104 # endif
9105 #endif
9106 vim_free(fname);
9107 vim_free(sfname);
9108 --nesting; /* see matching increment above */
9111 * When stopping to execute autocommands, restore the search patterns and
9112 * the redo buffer.
9114 if (!autocmd_busy)
9116 restore_search_patterns();
9117 restoreRedobuff();
9118 did_filetype = FALSE;
9122 * Some events don't set or reset the Changed flag.
9123 * Check if still in the same buffer!
9125 if (curbuf == old_curbuf
9126 && (event == EVENT_BUFREADPOST
9127 || event == EVENT_BUFWRITEPOST
9128 || event == EVENT_FILEAPPENDPOST
9129 || event == EVENT_VIMLEAVE
9130 || event == EVENT_VIMLEAVEPRE))
9132 #ifdef FEAT_TITLE
9133 if (curbuf->b_changed != save_changed)
9134 need_maketitle = TRUE;
9135 #endif
9136 curbuf->b_changed = save_changed;
9139 au_cleanup(); /* may really delete removed patterns/commands now */
9141 BYPASS_AU:
9142 /* When wiping out a buffer make sure all its buffer-local autocommands
9143 * are deleted. */
9144 if (event == EVENT_BUFWIPEOUT && buf != NULL)
9145 aubuflocal_remove(buf);
9147 return retval;
9150 # ifdef FEAT_EVAL
9151 static char_u *old_termresponse = NULL;
9152 # endif
9155 * Block triggering autocommands until unblock_autocmd() is called.
9156 * Can be used recursively, so long as it's symmetric.
9158 void
9159 block_autocmds()
9161 # ifdef FEAT_EVAL
9162 /* Remember the value of v:termresponse. */
9163 if (autocmd_blocked == 0)
9164 old_termresponse = get_vim_var_str(VV_TERMRESPONSE);
9165 # endif
9166 ++autocmd_blocked;
9169 void
9170 unblock_autocmds()
9172 --autocmd_blocked;
9174 # ifdef FEAT_EVAL
9175 /* When v:termresponse was set while autocommands were blocked, trigger
9176 * the autocommands now. Esp. useful when executing a shell command
9177 * during startup (vimdiff). */
9178 if (autocmd_blocked == 0
9179 && get_vim_var_str(VV_TERMRESPONSE) != old_termresponse)
9180 apply_autocmds(EVENT_TERMRESPONSE, NULL, NULL, FALSE, curbuf);
9181 # endif
9185 * Find next autocommand pattern that matches.
9187 static void
9188 auto_next_pat(apc, stop_at_last)
9189 AutoPatCmd *apc;
9190 int stop_at_last; /* stop when 'last' flag is set */
9192 AutoPat *ap;
9193 AutoCmd *cp;
9194 char_u *name;
9195 char *s;
9197 vim_free(sourcing_name);
9198 sourcing_name = NULL;
9200 for (ap = apc->curpat; ap != NULL && !got_int; ap = ap->next)
9202 apc->curpat = NULL;
9204 /* Only use a pattern when it has not been removed, has commands and
9205 * the group matches. For buffer-local autocommands only check the
9206 * buffer number. */
9207 if (ap->pat != NULL && ap->cmds != NULL
9208 && (apc->group == AUGROUP_ALL || apc->group == ap->group))
9210 /* execution-condition */
9211 if (ap->buflocal_nr == 0
9212 ? (match_file_pat(NULL, ap->reg_prog, apc->fname,
9213 apc->sfname, apc->tail, ap->allow_dirs))
9214 : ap->buflocal_nr == apc->arg_bufnr)
9216 name = event_nr2name(apc->event);
9217 s = _("%s Auto commands for \"%s\"");
9218 sourcing_name = alloc((unsigned)(STRLEN(s)
9219 + STRLEN(name) + ap->patlen + 1));
9220 if (sourcing_name != NULL)
9222 sprintf((char *)sourcing_name, s,
9223 (char *)name, (char *)ap->pat);
9224 if (p_verbose >= 8)
9226 verbose_enter();
9227 smsg((char_u *)_("Executing %s"), sourcing_name);
9228 verbose_leave();
9232 apc->curpat = ap;
9233 apc->nextcmd = ap->cmds;
9234 /* mark last command */
9235 for (cp = ap->cmds; cp->next != NULL; cp = cp->next)
9236 cp->last = FALSE;
9237 cp->last = TRUE;
9239 line_breakcheck();
9240 if (apc->curpat != NULL) /* found a match */
9241 break;
9243 if (stop_at_last && ap->last)
9244 break;
9249 * Get next autocommand command.
9250 * Called by do_cmdline() to get the next line for ":if".
9251 * Returns allocated string, or NULL for end of autocommands.
9253 static char_u *
9254 getnextac(c, cookie, indent)
9255 int c UNUSED;
9256 void *cookie;
9257 int indent UNUSED;
9259 AutoPatCmd *acp = (AutoPatCmd *)cookie;
9260 char_u *retval;
9261 AutoCmd *ac;
9263 /* Can be called again after returning the last line. */
9264 if (acp->curpat == NULL)
9265 return NULL;
9267 /* repeat until we find an autocommand to execute */
9268 for (;;)
9270 /* skip removed commands */
9271 while (acp->nextcmd != NULL && acp->nextcmd->cmd == NULL)
9272 if (acp->nextcmd->last)
9273 acp->nextcmd = NULL;
9274 else
9275 acp->nextcmd = acp->nextcmd->next;
9277 if (acp->nextcmd != NULL)
9278 break;
9280 /* at end of commands, find next pattern that matches */
9281 if (acp->curpat->last)
9282 acp->curpat = NULL;
9283 else
9284 acp->curpat = acp->curpat->next;
9285 if (acp->curpat != NULL)
9286 auto_next_pat(acp, TRUE);
9287 if (acp->curpat == NULL)
9288 return NULL;
9291 ac = acp->nextcmd;
9293 if (p_verbose >= 9)
9295 verbose_enter_scroll();
9296 smsg((char_u *)_("autocommand %s"), ac->cmd);
9297 msg_puts((char_u *)"\n"); /* don't overwrite this either */
9298 verbose_leave_scroll();
9300 retval = vim_strsave(ac->cmd);
9301 autocmd_nested = ac->nested;
9302 #ifdef FEAT_EVAL
9303 current_SID = ac->scriptID;
9304 #endif
9305 if (ac->last)
9306 acp->nextcmd = NULL;
9307 else
9308 acp->nextcmd = ac->next;
9309 return retval;
9313 * Return TRUE if there is a matching autocommand for "fname".
9314 * To account for buffer-local autocommands, function needs to know
9315 * in which buffer the file will be opened.
9318 has_autocmd(event, sfname, buf)
9319 event_T event;
9320 char_u *sfname;
9321 buf_T *buf;
9323 AutoPat *ap;
9324 char_u *fname;
9325 char_u *tail = gettail(sfname);
9326 int retval = FALSE;
9328 fname = FullName_save(sfname, FALSE);
9329 if (fname == NULL)
9330 return FALSE;
9332 #ifdef BACKSLASH_IN_FILENAME
9334 * Replace all backslashes with forward slashes. This makes the
9335 * autocommand patterns portable between Unix and MS-DOS.
9337 sfname = vim_strsave(sfname);
9338 if (sfname != NULL)
9339 forward_slash(sfname);
9340 forward_slash(fname);
9341 #endif
9343 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
9344 if (ap->pat != NULL && ap->cmds != NULL
9345 && (ap->buflocal_nr == 0
9346 ? match_file_pat(NULL, ap->reg_prog,
9347 fname, sfname, tail, ap->allow_dirs)
9348 : buf != NULL && ap->buflocal_nr == buf->b_fnum
9351 retval = TRUE;
9352 break;
9355 vim_free(fname);
9356 #ifdef BACKSLASH_IN_FILENAME
9357 vim_free(sfname);
9358 #endif
9360 return retval;
9363 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
9365 * Function given to ExpandGeneric() to obtain the list of autocommand group
9366 * names.
9368 char_u *
9369 get_augroup_name(xp, idx)
9370 expand_T *xp UNUSED;
9371 int idx;
9373 if (idx == augroups.ga_len) /* add "END" add the end */
9374 return (char_u *)"END";
9375 if (idx >= augroups.ga_len) /* end of list */
9376 return NULL;
9377 if (AUGROUP_NAME(idx) == NULL) /* skip deleted entries */
9378 return (char_u *)"";
9379 return AUGROUP_NAME(idx); /* return a name */
9382 static int include_groups = FALSE;
9384 char_u *
9385 set_context_in_autocmd(xp, arg, doautocmd)
9386 expand_T *xp;
9387 char_u *arg;
9388 int doautocmd; /* TRUE for :doauto*, FALSE for :autocmd */
9390 char_u *p;
9391 int group;
9393 /* check for a group name, skip it if present */
9394 include_groups = FALSE;
9395 p = arg;
9396 group = au_get_grouparg(&arg);
9397 if (group == AUGROUP_ERROR)
9398 return NULL;
9399 /* If there only is a group name that's what we expand. */
9400 if (*arg == NUL && group != AUGROUP_ALL && !vim_iswhite(arg[-1]))
9402 arg = p;
9403 group = AUGROUP_ALL;
9406 /* skip over event name */
9407 for (p = arg; *p != NUL && !vim_iswhite(*p); ++p)
9408 if (*p == ',')
9409 arg = p + 1;
9410 if (*p == NUL)
9412 if (group == AUGROUP_ALL)
9413 include_groups = TRUE;
9414 xp->xp_context = EXPAND_EVENTS; /* expand event name */
9415 xp->xp_pattern = arg;
9416 return NULL;
9419 /* skip over pattern */
9420 arg = skipwhite(p);
9421 while (*arg && (!vim_iswhite(*arg) || arg[-1] == '\\'))
9422 arg++;
9423 if (*arg)
9424 return arg; /* expand (next) command */
9426 if (doautocmd)
9427 xp->xp_context = EXPAND_FILES; /* expand file names */
9428 else
9429 xp->xp_context = EXPAND_NOTHING; /* pattern is not expanded */
9430 return NULL;
9434 * Function given to ExpandGeneric() to obtain the list of event names.
9436 char_u *
9437 get_event_name(xp, idx)
9438 expand_T *xp UNUSED;
9439 int idx;
9441 if (idx < augroups.ga_len) /* First list group names, if wanted */
9443 if (!include_groups || AUGROUP_NAME(idx) == NULL)
9444 return (char_u *)""; /* skip deleted entries */
9445 return AUGROUP_NAME(idx); /* return a name */
9447 return (char_u *)event_names[idx - augroups.ga_len].name;
9450 #endif /* FEAT_CMDL_COMPL */
9453 * Return TRUE if autocmd is supported.
9456 autocmd_supported(name)
9457 char_u *name;
9459 char_u *p;
9461 return (event_name2nr(name, &p) != NUM_EVENTS);
9465 * Return TRUE if an autocommand is defined for a group, event and
9466 * pattern: The group can be omitted to accept any group. "event" and "pattern"
9467 * can be NULL to accept any event and pattern. "pattern" can be NULL to accept
9468 * any pattern. Buffer-local patterns <buffer> or <buffer=N> are accepted.
9469 * Used for:
9470 * exists("#Group") or
9471 * exists("#Group#Event") or
9472 * exists("#Group#Event#pat") or
9473 * exists("#Event") or
9474 * exists("#Event#pat")
9477 au_exists(arg)
9478 char_u *arg;
9480 char_u *arg_save;
9481 char_u *pattern = NULL;
9482 char_u *event_name;
9483 char_u *p;
9484 event_T event;
9485 AutoPat *ap;
9486 buf_T *buflocal_buf = NULL;
9487 int group;
9488 int retval = FALSE;
9490 /* Make a copy so that we can change the '#' chars to a NUL. */
9491 arg_save = vim_strsave(arg);
9492 if (arg_save == NULL)
9493 return FALSE;
9494 p = vim_strchr(arg_save, '#');
9495 if (p != NULL)
9496 *p++ = NUL;
9498 /* First, look for an autocmd group name */
9499 group = au_find_group(arg_save);
9500 if (group == AUGROUP_ERROR)
9502 /* Didn't match a group name, assume the first argument is an event. */
9503 group = AUGROUP_ALL;
9504 event_name = arg_save;
9506 else
9508 if (p == NULL)
9510 /* "Group": group name is present and it's recognized */
9511 retval = TRUE;
9512 goto theend;
9515 /* Must be "Group#Event" or "Group#Event#pat". */
9516 event_name = p;
9517 p = vim_strchr(event_name, '#');
9518 if (p != NULL)
9519 *p++ = NUL; /* "Group#Event#pat" */
9522 pattern = p; /* "pattern" is NULL when there is no pattern */
9524 /* find the index (enum) for the event name */
9525 event = event_name2nr(event_name, &p);
9527 /* return FALSE if the event name is not recognized */
9528 if (event == NUM_EVENTS)
9529 goto theend;
9531 /* Find the first autocommand for this event.
9532 * If there isn't any, return FALSE;
9533 * If there is one and no pattern given, return TRUE; */
9534 ap = first_autopat[(int)event];
9535 if (ap == NULL)
9536 goto theend;
9538 /* if pattern is "<buffer>", special handling is needed which uses curbuf */
9539 /* for pattern "<buffer=N>, fnamecmp() will work fine */
9540 if (pattern != NULL && STRICMP(pattern, "<buffer>") == 0)
9541 buflocal_buf = curbuf;
9543 /* Check if there is an autocommand with the given pattern. */
9544 for ( ; ap != NULL; ap = ap->next)
9545 /* only use a pattern when it has not been removed and has commands. */
9546 /* For buffer-local autocommands, fnamecmp() works fine. */
9547 if (ap->pat != NULL && ap->cmds != NULL
9548 && (group == AUGROUP_ALL || ap->group == group)
9549 && (pattern == NULL
9550 || (buflocal_buf == NULL
9551 ? fnamecmp(ap->pat, pattern) == 0
9552 : ap->buflocal_nr == buflocal_buf->b_fnum)))
9554 retval = TRUE;
9555 break;
9558 theend:
9559 vim_free(arg_save);
9560 return retval;
9563 #else /* FEAT_AUTOCMD */
9566 * Prepare for executing commands for (hidden) buffer "buf".
9567 * This is the non-autocommand version, it simply saves "curbuf" and sets
9568 * "curbuf" and "curwin" to match "buf".
9570 void
9571 aucmd_prepbuf(aco, buf)
9572 aco_save_T *aco; /* structure to save values in */
9573 buf_T *buf; /* new curbuf */
9575 aco->save_curbuf = curbuf;
9576 --curbuf->b_nwindows;
9577 curbuf = buf;
9578 curwin->w_buffer = buf;
9579 ++curbuf->b_nwindows;
9583 * Restore after executing commands for a (hidden) buffer.
9584 * This is the non-autocommand version.
9586 void
9587 aucmd_restbuf(aco)
9588 aco_save_T *aco; /* structure holding saved values */
9590 --curbuf->b_nwindows;
9591 curbuf = aco->save_curbuf;
9592 curwin->w_buffer = curbuf;
9593 ++curbuf->b_nwindows;
9596 #endif /* FEAT_AUTOCMD */
9599 #if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN) || defined(PROTO)
9601 * Try matching a filename with a "pattern" ("prog" is NULL), or use the
9602 * precompiled regprog "prog" ("pattern" is NULL). That avoids calling
9603 * vim_regcomp() often.
9604 * Used for autocommands and 'wildignore'.
9605 * Returns TRUE if there is a match, FALSE otherwise.
9608 match_file_pat(pattern, prog, fname, sfname, tail, allow_dirs)
9609 char_u *pattern; /* pattern to match with */
9610 regprog_T *prog; /* pre-compiled regprog or NULL */
9611 char_u *fname; /* full path of file name */
9612 char_u *sfname; /* short file name or NULL */
9613 char_u *tail; /* tail of path */
9614 int allow_dirs; /* allow matching with dir */
9616 regmatch_T regmatch;
9617 int result = FALSE;
9618 #ifdef FEAT_OSFILETYPE
9619 int no_pattern = FALSE; /* TRUE if check is filetype only */
9620 char_u *type_start;
9621 char_u c;
9622 int match = FALSE;
9623 #endif
9625 #ifdef CASE_INSENSITIVE_FILENAME
9626 regmatch.rm_ic = TRUE; /* Always ignore case */
9627 #else
9628 regmatch.rm_ic = FALSE; /* Don't ever ignore case */
9629 #endif
9630 #ifdef FEAT_OSFILETYPE
9631 if (*pattern == '<')
9633 /* There is a filetype condition specified with this pattern.
9634 * Check the filetype matches first. If not, don't bother with the
9635 * pattern (set regprog to NULL).
9636 * Always use magic for the regexp.
9639 for (type_start = pattern + 1; (c = *pattern); pattern++)
9641 if ((c == ';' || c == '>') && match == FALSE)
9643 *pattern = NUL; /* Terminate the string */
9644 match = mch_check_filetype(fname, type_start);
9645 *pattern = c; /* Restore the terminator */
9646 type_start = pattern + 1;
9648 if (c == '>')
9649 break;
9652 /* (c should never be NUL, but check anyway) */
9653 if (match == FALSE || c == NUL)
9654 regmatch.regprog = NULL; /* Doesn't match - don't check pat. */
9655 else if (*pattern == NUL)
9657 regmatch.regprog = NULL; /* Vim will try to free regprog later */
9658 no_pattern = TRUE; /* Always matches - don't check pat. */
9660 else
9661 regmatch.regprog = vim_regcomp(pattern + 1, RE_MAGIC);
9663 else
9664 #endif
9666 if (prog != NULL)
9667 regmatch.regprog = prog;
9668 else
9669 regmatch.regprog = vim_regcomp(pattern, RE_MAGIC);
9673 * Try for a match with the pattern with:
9674 * 1. the full file name, when the pattern has a '/'.
9675 * 2. the short file name, when the pattern has a '/'.
9676 * 3. the tail of the file name, when the pattern has no '/'.
9678 if (
9679 #ifdef FEAT_OSFILETYPE
9680 /* If the check is for a filetype only and we don't care
9681 * about the path then skip all the regexp stuff.
9683 no_pattern ||
9684 #endif
9685 (regmatch.regprog != NULL
9686 && ((allow_dirs
9687 && (vim_regexec(&regmatch, fname, (colnr_T)0)
9688 || (sfname != NULL
9689 && vim_regexec(&regmatch, sfname, (colnr_T)0))))
9690 || (!allow_dirs && vim_regexec(&regmatch, tail, (colnr_T)0)))))
9691 result = TRUE;
9693 if (prog == NULL)
9694 vim_free(regmatch.regprog);
9695 return result;
9697 #endif
9699 #if defined(FEAT_WILDIGN) || defined(PROTO)
9701 * Return TRUE if a file matches with a pattern in "list".
9702 * "list" is a comma-separated list of patterns, like 'wildignore'.
9703 * "sfname" is the short file name or NULL, "ffname" the long file name.
9706 match_file_list(list, sfname, ffname)
9707 char_u *list;
9708 char_u *sfname;
9709 char_u *ffname;
9711 char_u buf[100];
9712 char_u *tail;
9713 char_u *regpat;
9714 char allow_dirs;
9715 int match;
9716 char_u *p;
9718 tail = gettail(sfname);
9720 /* try all patterns in 'wildignore' */
9721 p = list;
9722 while (*p)
9724 copy_option_part(&p, buf, 100, ",");
9725 regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, FALSE);
9726 if (regpat == NULL)
9727 break;
9728 match = match_file_pat(regpat, NULL, ffname, sfname,
9729 tail, (int)allow_dirs);
9730 vim_free(regpat);
9731 if (match)
9732 return TRUE;
9734 return FALSE;
9736 #endif
9739 * Convert the given pattern "pat" which has shell style wildcards in it, into
9740 * a regular expression, and return the result in allocated memory. If there
9741 * is a directory path separator to be matched, then TRUE is put in
9742 * allow_dirs, otherwise FALSE is put there -- webb.
9743 * Handle backslashes before special characters, like "\*" and "\ ".
9745 * If FEAT_OSFILETYPE defined then pass initial <type> through unchanged. Eg:
9746 * '<html>myfile' becomes '<html>^myfile$' -- leonard.
9748 * Returns NULL when out of memory.
9750 char_u *
9751 file_pat_to_reg_pat(pat, pat_end, allow_dirs, no_bslash)
9752 char_u *pat;
9753 char_u *pat_end; /* first char after pattern or NULL */
9754 char *allow_dirs; /* Result passed back out in here */
9755 int no_bslash UNUSED; /* Don't use a backward slash as pathsep */
9757 int size;
9758 char_u *endp;
9759 char_u *reg_pat;
9760 char_u *p;
9761 int i;
9762 int nested = 0;
9763 int add_dollar = TRUE;
9764 #ifdef FEAT_OSFILETYPE
9765 int check_length = 0;
9766 #endif
9768 if (allow_dirs != NULL)
9769 *allow_dirs = FALSE;
9770 if (pat_end == NULL)
9771 pat_end = pat + STRLEN(pat);
9773 #ifdef FEAT_OSFILETYPE
9774 /* Find out how much of the string is the filetype check */
9775 if (*pat == '<')
9777 /* Count chars until the next '>' */
9778 for (p = pat + 1; p < pat_end && *p != '>'; p++)
9780 if (p < pat_end)
9782 /* Pattern is of the form <.*>.* */
9783 check_length = p - pat + 1;
9784 if (p + 1 >= pat_end)
9786 /* The 'pattern' is a filetype check ONLY */
9787 reg_pat = (char_u *)alloc(check_length + 1);
9788 if (reg_pat != NULL)
9790 mch_memmove(reg_pat, pat, (size_t)check_length);
9791 reg_pat[check_length] = NUL;
9793 return reg_pat;
9796 /* else: there was no closing '>' - assume it was a normal pattern */
9799 pat += check_length;
9800 size = 2 + check_length;
9801 #else
9802 size = 2; /* '^' at start, '$' at end */
9803 #endif
9805 for (p = pat; p < pat_end; p++)
9807 switch (*p)
9809 case '*':
9810 case '.':
9811 case ',':
9812 case '{':
9813 case '}':
9814 case '~':
9815 size += 2; /* extra backslash */
9816 break;
9817 #ifdef BACKSLASH_IN_FILENAME
9818 case '\\':
9819 case '/':
9820 size += 4; /* could become "[\/]" */
9821 break;
9822 #endif
9823 default:
9824 size++;
9825 # ifdef FEAT_MBYTE
9826 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
9828 ++p;
9829 ++size;
9831 # endif
9832 break;
9835 reg_pat = alloc(size + 1);
9836 if (reg_pat == NULL)
9837 return NULL;
9839 #ifdef FEAT_OSFILETYPE
9840 /* Copy the type check in to the start. */
9841 if (check_length)
9842 mch_memmove(reg_pat, pat - check_length, (size_t)check_length);
9843 i = check_length;
9844 #else
9845 i = 0;
9846 #endif
9848 if (pat[0] == '*')
9849 while (pat[0] == '*' && pat < pat_end - 1)
9850 pat++;
9851 else
9852 reg_pat[i++] = '^';
9853 endp = pat_end - 1;
9854 if (*endp == '*')
9856 while (endp - pat > 0 && *endp == '*')
9857 endp--;
9858 add_dollar = FALSE;
9860 for (p = pat; *p && nested >= 0 && p <= endp; p++)
9862 switch (*p)
9864 case '*':
9865 reg_pat[i++] = '.';
9866 reg_pat[i++] = '*';
9867 while (p[1] == '*') /* "**" matches like "*" */
9868 ++p;
9869 break;
9870 case '.':
9871 #ifdef RISCOS
9872 if (allow_dirs != NULL)
9873 *allow_dirs = TRUE;
9874 /* FALLTHROUGH */
9875 #endif
9876 case '~':
9877 reg_pat[i++] = '\\';
9878 reg_pat[i++] = *p;
9879 break;
9880 case '?':
9881 #ifdef RISCOS
9882 case '#':
9883 #endif
9884 reg_pat[i++] = '.';
9885 break;
9886 case '\\':
9887 if (p[1] == NUL)
9888 break;
9889 #ifdef BACKSLASH_IN_FILENAME
9890 if (!no_bslash)
9892 /* translate:
9893 * "\x" to "\\x" e.g., "dir\file"
9894 * "\*" to "\\.*" e.g., "dir\*.c"
9895 * "\?" to "\\." e.g., "dir\??.c"
9896 * "\+" to "\+" e.g., "fileX\+.c"
9898 if ((vim_isfilec(p[1]) || p[1] == '*' || p[1] == '?')
9899 && p[1] != '+')
9901 reg_pat[i++] = '[';
9902 reg_pat[i++] = '\\';
9903 reg_pat[i++] = '/';
9904 reg_pat[i++] = ']';
9905 if (allow_dirs != NULL)
9906 *allow_dirs = TRUE;
9907 break;
9910 #endif
9911 if (*++p == '?'
9912 #ifdef BACKSLASH_IN_FILENAME
9913 && no_bslash
9914 #endif
9916 reg_pat[i++] = '?';
9917 else
9918 if (*p == ',')
9919 reg_pat[i++] = ',';
9920 else
9922 if (allow_dirs != NULL && vim_ispathsep(*p)
9923 #ifdef BACKSLASH_IN_FILENAME
9924 && (!no_bslash || *p != '\\')
9925 #endif
9927 *allow_dirs = TRUE;
9928 reg_pat[i++] = '\\';
9929 reg_pat[i++] = *p;
9931 break;
9932 #ifdef BACKSLASH_IN_FILENAME
9933 case '/':
9934 reg_pat[i++] = '[';
9935 reg_pat[i++] = '\\';
9936 reg_pat[i++] = '/';
9937 reg_pat[i++] = ']';
9938 if (allow_dirs != NULL)
9939 *allow_dirs = TRUE;
9940 break;
9941 #endif
9942 case '{':
9943 reg_pat[i++] = '\\';
9944 reg_pat[i++] = '(';
9945 nested++;
9946 break;
9947 case '}':
9948 reg_pat[i++] = '\\';
9949 reg_pat[i++] = ')';
9950 --nested;
9951 break;
9952 case ',':
9953 if (nested)
9955 reg_pat[i++] = '\\';
9956 reg_pat[i++] = '|';
9958 else
9959 reg_pat[i++] = ',';
9960 break;
9961 default:
9962 # ifdef FEAT_MBYTE
9963 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
9964 reg_pat[i++] = *p++;
9965 else
9966 # endif
9967 if (allow_dirs != NULL && vim_ispathsep(*p))
9968 *allow_dirs = TRUE;
9969 reg_pat[i++] = *p;
9970 break;
9973 if (add_dollar)
9974 reg_pat[i++] = '$';
9975 reg_pat[i] = NUL;
9976 if (nested != 0)
9978 if (nested < 0)
9979 EMSG(_("E219: Missing {."));
9980 else
9981 EMSG(_("E220: Missing }."));
9982 vim_free(reg_pat);
9983 reg_pat = NULL;
9985 return reg_pat;