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